1 //===- LLVMCConfigurationEmitter.cpp - Generate LLVMC config ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open
6 // Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend is responsible for emitting LLVMC configuration code.
12 //===----------------------------------------------------------------------===//
14 #include "LLVMCConfigurationEmitter.h"
17 #include "llvm/ADT/IntrusiveRefCntPtr.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringSet.h"
22 #include "llvm/Support/Streams.h"
35 //===----------------------------------------------------------------------===//
38 typedef std::vector<Record*> RecordVector;
39 typedef std::vector<std::string> StrVector;
41 //===----------------------------------------------------------------------===//
44 // Indentation strings.
45 const char * Indent1 = " ";
46 const char * Indent2 = " ";
47 const char * Indent3 = " ";
48 const char * Indent4 = " ";
50 // Default help string.
51 const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
53 // Name for the "sink" option.
54 const char * SinkOptionName = "AutoGeneratedSinkOption";
56 //===----------------------------------------------------------------------===//
59 int InitPtrToInt(const Init* ptr) {
60 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
61 return val.getValue();
64 const std::string& InitPtrToString(const Init* ptr) {
65 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
66 return val.getValue();
69 const ListInit& InitPtrToList(const Init* ptr) {
70 const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
74 const DagInit& InitPtrToDag(const Init* ptr) {
75 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
79 // checkNumberOfArguments - Ensure that the number of args in d is
80 // less than or equal to min_arguments, otherwise throw an exception.
81 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
82 if (d->getNumArgs() < min_arguments)
83 throw "Property " + d->getOperator()->getAsString()
84 + " has too few arguments!";
87 // isDagEmpty - is this DAG marked with an empty marker?
88 bool isDagEmpty (const DagInit* d) {
89 return d->getOperator()->getAsString() == "empty";
92 //===----------------------------------------------------------------------===//
93 /// Back-end specific code
95 // A command-line option can have one of the following types:
97 // Alias - an alias for another option.
99 // Switch - a simple switch without arguments, e.g. -O2
101 // Parameter - an option that takes one(and only one) argument, e.g. -o file,
104 // ParameterList - same as Parameter, but more than one occurence
105 // of the option is allowed, e.g. -lm -lpthread
107 // Prefix - argument is everything after the prefix,
108 // e.g. -Wa,-foo,-bar, -DNAME=VALUE
110 // PrefixList - same as Prefix, but more than one option occurence is
113 namespace OptionType {
114 enum OptionType { Alias, Switch,
115 Parameter, ParameterList, Prefix, PrefixList};
118 bool IsListOptionType (OptionType::OptionType t) {
119 return (t == OptionType::ParameterList || t == OptionType::PrefixList);
122 // Code duplication here is necessary because one option can affect
123 // several tools and those tools may have different actions associated
124 // with this option. GlobalOptionDescriptions are used to generate
125 // the option registration code, while ToolOptionDescriptions are used
126 // to generate tool-specific code.
128 /// OptionDescription - Base class for option descriptions.
129 struct OptionDescription {
130 OptionType::OptionType Type;
133 OptionDescription(OptionType::OptionType t = OptionType::Switch,
134 const std::string& n = "")
138 const char* GenTypeDeclaration() const {
140 case OptionType::Alias:
142 case OptionType::PrefixList:
143 case OptionType::ParameterList:
144 return "cl::list<std::string>";
145 case OptionType::Switch:
146 return "cl::opt<bool>";
147 case OptionType::Parameter:
148 case OptionType::Prefix:
150 return "cl::opt<std::string>";
154 // Escape commas and other symbols not allowed in the C++ variable
155 // names. Makes it possible to use options with names like "Wa,"
156 // (useful for prefix options).
157 std::string EscapeVariableName(const std::string& Var) const {
159 for (unsigned i = 0; i != Var.size(); ++i) {
160 char cur_char = Var[i];
161 if (cur_char == ',') {
164 else if (cur_char == '+') {
167 else if (cur_char == '-') {
171 ret.push_back(cur_char);
177 std::string GenVariableName() const {
178 const std::string& EscapedName = EscapeVariableName(Name);
180 case OptionType::Alias:
181 return "AutoGeneratedAlias" + EscapedName;
182 case OptionType::Switch:
183 return "AutoGeneratedSwitch" + EscapedName;
184 case OptionType::Prefix:
185 return "AutoGeneratedPrefix" + EscapedName;
186 case OptionType::PrefixList:
187 return "AutoGeneratedPrefixList" + EscapedName;
188 case OptionType::Parameter:
189 return "AutoGeneratedParameter" + EscapedName;
190 case OptionType::ParameterList:
192 return "AutoGeneratedParameterList" + EscapedName;
198 // Global option description.
200 namespace GlobalOptionDescriptionFlags {
201 enum GlobalOptionDescriptionFlags { Required = 0x1 };
204 struct GlobalOptionDescription : public OptionDescription {
208 // We need to provide a default constructor because
209 // StringMap can only store DefaultConstructible objects.
210 GlobalOptionDescription() : OptionDescription(), Flags(0)
213 GlobalOptionDescription (OptionType::OptionType t, const std::string& n,
214 const std::string& h = DefaultHelpString)
215 : OptionDescription(t, n), Help(h), Flags(0)
218 bool isRequired() const {
219 return Flags & GlobalOptionDescriptionFlags::Required;
222 Flags |= GlobalOptionDescriptionFlags::Required;
225 /// Merge - Merge two option descriptions.
226 void Merge (const GlobalOptionDescription& other)
228 if (other.Type != Type)
229 throw "Conflicting definitions for the option " + Name + "!";
231 if (Help == DefaultHelpString)
233 else if (other.Help != DefaultHelpString) {
234 llvm::cerr << "Warning: more than one help string defined for option "
238 Flags |= other.Flags;
242 /// GlobalOptionDescriptions - A GlobalOptionDescription array
243 /// together with some flags affecting generation of option
245 struct GlobalOptionDescriptions {
246 typedef StringMap<GlobalOptionDescription> container_type;
247 typedef container_type::const_iterator const_iterator;
249 /// Descriptions - A list of GlobalOptionDescriptions.
250 container_type Descriptions;
251 /// HasSink - Should the emitter generate a "cl::sink" option?
254 /// FindOption - exception-throwing wrapper for find().
255 const GlobalOptionDescription& FindOption(const std::string& OptName) const {
256 const_iterator I = Descriptions.find(OptName);
257 if (I != Descriptions.end())
260 throw OptName + ": no such option!";
263 /// insertDescription - Insert new GlobalOptionDescription into
264 /// GlobalOptionDescriptions list
265 void insertDescription (const GlobalOptionDescription& o)
267 container_type::iterator I = Descriptions.find(o.Name);
268 if (I != Descriptions.end()) {
269 GlobalOptionDescription& D = I->second;
273 Descriptions[o.Name] = o;
277 // Support for STL-style iteration
278 const_iterator begin() const { return Descriptions.begin(); }
279 const_iterator end() const { return Descriptions.end(); }
283 // Tool-local option description.
285 // Properties without arguments are implemented as flags.
286 namespace ToolOptionDescriptionFlags {
287 enum ToolOptionDescriptionFlags { StopCompilation = 0x1,
288 Forward = 0x2, UnpackValues = 0x4};
290 namespace OptionPropertyType {
291 enum OptionPropertyType { AppendCmd, ForwardAs, OutputSuffix };
294 typedef std::pair<OptionPropertyType::OptionPropertyType, std::string>
296 typedef SmallVector<OptionProperty, 4> OptionPropertyList;
298 struct ToolOptionDescription : public OptionDescription {
300 OptionPropertyList Props;
302 // StringMap can only store DefaultConstructible objects
303 ToolOptionDescription() : OptionDescription(), Flags(0) {}
305 ToolOptionDescription (OptionType::OptionType t, const std::string& n)
306 : OptionDescription(t, n)
309 // Various boolean properties
310 bool isStopCompilation() const {
311 return Flags & ToolOptionDescriptionFlags::StopCompilation;
313 void setStopCompilation() {
314 Flags |= ToolOptionDescriptionFlags::StopCompilation;
317 bool isForward() const {
318 return Flags & ToolOptionDescriptionFlags::Forward;
321 Flags |= ToolOptionDescriptionFlags::Forward;
324 bool isUnpackValues() const {
325 return Flags & ToolOptionDescriptionFlags::UnpackValues;
327 void setUnpackValues() {
328 Flags |= ToolOptionDescriptionFlags::UnpackValues;
331 void AddProperty (OptionPropertyType::OptionPropertyType t,
332 const std::string& val)
334 Props.push_back(std::make_pair(t, val));
338 typedef StringMap<ToolOptionDescription> ToolOptionDescriptions;
340 // Tool information record
342 namespace ToolFlags {
343 enum ToolFlags { Join = 0x1, Sink = 0x2 };
346 struct ToolProperties : public RefCountedBase<ToolProperties> {
349 StrVector InLanguage;
350 std::string OutLanguage;
351 std::string OutputSuffix;
353 ToolOptionDescriptions OptDescs;
355 // Various boolean properties
356 void setSink() { Flags |= ToolFlags::Sink; }
357 bool isSink() const { return Flags & ToolFlags::Sink; }
358 void setJoin() { Flags |= ToolFlags::Join; }
359 bool isJoin() const { return Flags & ToolFlags::Join; }
361 // Default ctor here is needed because StringMap can only store
362 // DefaultConstructible objects
363 ToolProperties() : CmdLine(0), Flags(0) {}
364 ToolProperties (const std::string& n) : Name(n), CmdLine(0), Flags(0) {}
368 /// ToolPropertiesList - A list of Tool information records
369 /// IntrusiveRefCntPtrs are used here because StringMap has no copy
370 /// constructor (and we want to avoid copying ToolProperties anyway).
371 typedef std::vector<IntrusiveRefCntPtr<ToolProperties> > ToolPropertiesList;
374 /// CollectOptionProperties - Function object for iterating over a
375 /// list (usually, a DAG) of option property records.
376 class CollectOptionProperties {
378 // Implementation details.
380 /// OptionPropertyHandler - a function that extracts information
381 /// about a given option property from its DAG representation.
382 typedef void (CollectOptionProperties::* OptionPropertyHandler)
385 /// OptionPropertyHandlerMap - A map from option property names to
386 /// option property handlers
387 typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
389 static OptionPropertyHandlerMap optionPropertyHandlers_;
390 static bool staticMembersInitialized_;
392 /// This is where the information is stored
394 /// toolProps_ - Properties of the current Tool.
395 ToolProperties* toolProps_;
396 /// optDescs_ - OptionDescriptions table (used to register options
398 GlobalOptionDescription& optDesc_;
402 explicit CollectOptionProperties(ToolProperties* TP,
403 GlobalOptionDescription& OD)
404 : toolProps_(TP), optDesc_(OD)
406 if (!staticMembersInitialized_) {
407 optionPropertyHandlers_["append_cmd"] =
408 &CollectOptionProperties::onAppendCmd;
409 optionPropertyHandlers_["forward"] =
410 &CollectOptionProperties::onForward;
411 optionPropertyHandlers_["forward_as"] =
412 &CollectOptionProperties::onForwardAs;
413 optionPropertyHandlers_["help"] =
414 &CollectOptionProperties::onHelp;
415 optionPropertyHandlers_["output_suffix"] =
416 &CollectOptionProperties::onOutputSuffix;
417 optionPropertyHandlers_["required"] =
418 &CollectOptionProperties::onRequired;
419 optionPropertyHandlers_["stop_compilation"] =
420 &CollectOptionProperties::onStopCompilation;
421 optionPropertyHandlers_["unpack_values"] =
422 &CollectOptionProperties::onUnpackValues;
424 staticMembersInitialized_ = true;
428 /// operator() - Gets called for every option property; Just forwards
429 /// to the corresponding property handler.
430 void operator() (Init* i) {
431 const DagInit& option_property = InitPtrToDag(i);
432 const std::string& option_property_name
433 = option_property.getOperator()->getAsString();
434 OptionPropertyHandlerMap::iterator method
435 = optionPropertyHandlers_.find(option_property_name);
437 if (method != optionPropertyHandlers_.end()) {
438 OptionPropertyHandler h = method->second;
439 (this->*h)(&option_property);
442 throw "Unknown option property: " + option_property_name + "!";
448 /// Option property handlers --
449 /// Methods that handle properties that are common for all types of
450 /// options (like append_cmd, stop_compilation)
452 void onAppendCmd (const DagInit* d) {
453 checkNumberOfArguments(d, 1);
455 const std::string& cmd = InitPtrToString(d->getArg(0));
457 toolProps_->OptDescs[optDesc_.Name].
458 AddProperty(OptionPropertyType::AppendCmd, cmd);
461 void onOutputSuffix (const DagInit* d) {
462 checkNumberOfArguments(d, 1);
464 const std::string& suf = InitPtrToString(d->getArg(0));
466 if (toolProps_->OptDescs[optDesc_.Name].Type != OptionType::Switch)
467 throw "Option " + optDesc_.Name
468 + " can't have 'output_suffix' property since it isn't a switch!";
470 toolProps_->OptDescs[optDesc_.Name].AddProperty
471 (OptionPropertyType::OutputSuffix, suf);
474 void onForward (const DagInit* d) {
475 checkNumberOfArguments(d, 0);
477 toolProps_->OptDescs[optDesc_.Name].setForward();
480 void onForwardAs (const DagInit* d) {
481 checkNumberOfArguments(d, 1);
483 const std::string& cmd = InitPtrToString(d->getArg(0));
485 toolProps_->OptDescs[optDesc_.Name].
486 AddProperty(OptionPropertyType::ForwardAs, cmd);
489 void onHelp (const DagInit* d) {
490 checkNumberOfArguments(d, 1);
491 const std::string& help_message = InitPtrToString(d->getArg(0));
493 optDesc_.Help = help_message;
496 void onRequired (const DagInit* d) {
497 checkNumberOfArguments(d, 0);
499 optDesc_.setRequired();
502 void onStopCompilation (const DagInit* d) {
503 checkNumberOfArguments(d, 0);
505 if (optDesc_.Type != OptionType::Switch)
506 throw std::string("Only options of type Switch can stop compilation!");
507 toolProps_->OptDescs[optDesc_.Name].setStopCompilation();
510 void onUnpackValues (const DagInit* d) {
511 checkNumberOfArguments(d, 0);
513 toolProps_->OptDescs[optDesc_.Name].setUnpackValues();
518 /// checkToolProps - Throw an error if toolProps_ == 0.
519 void checkToolProps(const DagInit* d) {
521 throw "Option property " + d->getOperator()->getAsString()
522 + " can't be used in this context";
527 CollectOptionProperties::OptionPropertyHandlerMap
528 CollectOptionProperties::optionPropertyHandlers_;
530 bool CollectOptionProperties::staticMembersInitialized_ = false;
533 /// processOptionProperties - Go through the list of option
534 /// properties and call a corresponding handler for each.
535 void processOptionProperties (const DagInit* d, ToolProperties* t,
536 GlobalOptionDescription& o) {
537 checkNumberOfArguments(d, 2);
538 DagInit::const_arg_iterator B = d->arg_begin();
539 // Skip the first argument: it's always the option name.
541 std::for_each(B, d->arg_end(), CollectOptionProperties(t, o));
544 /// AddOption - A function object wrapper for
545 /// processOptionProperties. Used by CollectProperties and
546 /// CollectPropertiesFromOptionList.
549 GlobalOptionDescriptions& OptDescs_;
550 ToolProperties* ToolProps_;
553 explicit AddOption(GlobalOptionDescriptions& OD, ToolProperties* TP = 0)
554 : OptDescs_(OD), ToolProps_(TP)
557 void operator()(const Init* i) {
558 const DagInit& d = InitPtrToDag(i);
559 checkNumberOfArguments(&d, 2);
561 const OptionType::OptionType Type =
562 getOptionType(d.getOperator()->getAsString());
563 const std::string& Name = InitPtrToString(d.getArg(0));
565 GlobalOptionDescription OD(Type, Name);
566 if (Type != OptionType::Alias) {
567 processOptionProperties(&d, ToolProps_, OD);
569 ToolProps_->OptDescs[Name].Type = Type;
570 ToolProps_->OptDescs[Name].Name = Name;
574 OD.Help = InitPtrToString(d.getArg(1));
576 OptDescs_.insertDescription(OD);
580 OptionType::OptionType getOptionType(const std::string& T) const {
581 if (T == "alias_option")
582 return OptionType::Alias;
583 else if (T == "switch_option")
584 return OptionType::Switch;
585 else if (T == "parameter_option")
586 return OptionType::Parameter;
587 else if (T == "parameter_list_option")
588 return OptionType::ParameterList;
589 else if (T == "prefix_option")
590 return OptionType::Prefix;
591 else if (T == "prefix_list_option")
592 return OptionType::PrefixList;
594 throw "Unknown option type: " + T + '!';
599 /// CollectProperties - Function object for iterating over a list of
600 /// tool property records.
601 class CollectProperties {
604 // Implementation details
606 /// PropertyHandler - a function that extracts information
607 /// about a given tool property from its DAG representation
608 typedef void (CollectProperties::*PropertyHandler)(const DagInit*);
610 /// PropertyHandlerMap - A map from property names to property
612 typedef StringMap<PropertyHandler> PropertyHandlerMap;
614 // Static maps from strings to CollectProperties methods("handlers")
615 static PropertyHandlerMap propertyHandlers_;
616 static bool staticMembersInitialized_;
619 /// This is where the information is stored
621 /// toolProps_ - Properties of the current Tool.
622 ToolProperties& toolProps_;
623 /// optDescs_ - OptionDescriptions table (used to register options
625 GlobalOptionDescriptions& optDescs_;
629 explicit CollectProperties (ToolProperties& p, GlobalOptionDescriptions& d)
630 : toolProps_(p), optDescs_(d)
632 if (!staticMembersInitialized_) {
633 propertyHandlers_["cmd_line"] = &CollectProperties::onCmdLine;
634 propertyHandlers_["in_language"] = &CollectProperties::onInLanguage;
635 propertyHandlers_["join"] = &CollectProperties::onJoin;
636 propertyHandlers_["out_language"] = &CollectProperties::onOutLanguage;
637 propertyHandlers_["output_suffix"] = &CollectProperties::onOutputSuffix;
638 propertyHandlers_["parameter_option"]
639 = &CollectProperties::addOption;
640 propertyHandlers_["parameter_list_option"] =
641 &CollectProperties::addOption;
642 propertyHandlers_["prefix_option"] = &CollectProperties::addOption;
643 propertyHandlers_["prefix_list_option"] =
644 &CollectProperties::addOption;
645 propertyHandlers_["sink"] = &CollectProperties::onSink;
646 propertyHandlers_["switch_option"] = &CollectProperties::addOption;
647 propertyHandlers_["alias_option"] = &CollectProperties::addOption;
649 staticMembersInitialized_ = true;
653 /// operator() - Gets called for every tool property; Just forwards
654 /// to the corresponding property handler.
655 void operator() (Init* i) {
656 const DagInit& d = InitPtrToDag(i);
657 const std::string& property_name = d.getOperator()->getAsString();
658 PropertyHandlerMap::iterator method
659 = propertyHandlers_.find(property_name);
661 if (method != propertyHandlers_.end()) {
662 PropertyHandler h = method->second;
666 throw "Unknown tool property: " + property_name + "!";
672 /// Property handlers --
673 /// Functions that extract information about tool properties from
674 /// DAG representation.
676 void onCmdLine (const DagInit* d) {
677 checkNumberOfArguments(d, 1);
678 toolProps_.CmdLine = d->getArg(0);
681 void onInLanguage (const DagInit* d) {
682 checkNumberOfArguments(d, 1);
683 Init* arg = d->getArg(0);
685 // Find out the argument's type.
686 if (typeid(*arg) == typeid(StringInit)) {
688 toolProps_.InLanguage.push_back(InitPtrToString(arg));
692 const ListInit& lst = InitPtrToList(arg);
693 StrVector& out = toolProps_.InLanguage;
695 // Copy strings to the output vector.
696 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
698 out.push_back(InitPtrToString(*B));
701 // Remove duplicates.
702 std::sort(out.begin(), out.end());
703 StrVector::iterator newE = std::unique(out.begin(), out.end());
704 out.erase(newE, out.end());
708 void onJoin (const DagInit* d) {
709 checkNumberOfArguments(d, 0);
710 toolProps_.setJoin();
713 void onOutLanguage (const DagInit* d) {
714 checkNumberOfArguments(d, 1);
715 toolProps_.OutLanguage = InitPtrToString(d->getArg(0));
718 void onOutputSuffix (const DagInit* d) {
719 checkNumberOfArguments(d, 1);
720 toolProps_.OutputSuffix = InitPtrToString(d->getArg(0));
723 void onSink (const DagInit* d) {
724 checkNumberOfArguments(d, 0);
725 optDescs_.HasSink = true;
726 toolProps_.setSink();
729 // Just forwards to the AddOption function object. Somewhat
730 // non-optimal, but avoids code duplication.
731 void addOption (const DagInit* d) {
732 checkNumberOfArguments(d, 2);
733 AddOption(optDescs_, &toolProps_)(d);
738 // Defintions of static members of CollectProperties.
739 CollectProperties::PropertyHandlerMap CollectProperties::propertyHandlers_;
740 bool CollectProperties::staticMembersInitialized_ = false;
743 /// CollectToolProperties - Gather information about tool properties
744 /// from the parsed TableGen data (basically a wrapper for the
745 /// CollectProperties function object).
746 void CollectToolProperties (RecordVector::const_iterator B,
747 RecordVector::const_iterator E,
748 ToolPropertiesList& TPList,
749 GlobalOptionDescriptions& OptDescs)
751 // Iterate over a properties list of every Tool definition
754 // Throws an exception if the value does not exist.
755 ListInit* PropList = T->getValueAsListInit("properties");
757 IntrusiveRefCntPtr<ToolProperties>
758 ToolProps(new ToolProperties(T->getName()));
760 std::for_each(PropList->begin(), PropList->end(),
761 CollectProperties(*ToolProps, OptDescs));
762 TPList.push_back(ToolProps);
767 /// CollectPropertiesFromOptionList - Gather information about
768 /// *global* option properties from the OptionList.
769 void CollectPropertiesFromOptionList (RecordVector::const_iterator B,
770 RecordVector::const_iterator E,
771 GlobalOptionDescriptions& OptDescs)
773 // Iterate over a properties list of every Tool definition
775 RecordVector::value_type T = *B;
776 // Throws an exception if the value does not exist.
777 ListInit* PropList = T->getValueAsListInit("options");
779 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
783 /// CheckForSuperfluousOptions - Check that there are no side
784 /// effect-free options (specified only in the OptionList). Otherwise,
785 /// output a warning.
786 void CheckForSuperfluousOptions (const ToolPropertiesList& TPList,
787 const GlobalOptionDescriptions& OptDescs) {
788 llvm::StringSet<> nonSuperfluousOptions;
790 // Add all options mentioned in the TPList to the set of
791 // non-superfluous options.
792 for (ToolPropertiesList::const_iterator B = TPList.begin(),
793 E = TPList.end(); B != E; ++B) {
794 const ToolProperties& TP = *(*B);
795 for (ToolOptionDescriptions::const_iterator B = TP.OptDescs.begin(),
796 E = TP.OptDescs.end(); B != E; ++B) {
797 nonSuperfluousOptions.insert(B->first());
801 // Check that all options in OptDescs belong to the set of
802 // non-superfluous options.
803 for (GlobalOptionDescriptions::const_iterator B = OptDescs.begin(),
804 E = OptDescs.end(); B != E; ++B) {
805 const GlobalOptionDescription& Val = B->second;
806 if (!nonSuperfluousOptions.count(Val.Name)
807 && Val.Type != OptionType::Alias)
808 cerr << "Warning: option '-" << Val.Name << "' has no effect! "
809 "Probable cause: this option is specified only in the OptionList.\n";
813 /// EmitCaseTest1Arg - Helper function used by
814 /// EmitCaseConstructHandler.
815 bool EmitCaseTest1Arg(const std::string& TestName,
817 const GlobalOptionDescriptions& OptDescs,
819 checkNumberOfArguments(&d, 1);
820 const std::string& OptName = InitPtrToString(d.getArg(0));
821 if (TestName == "switch_on") {
822 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
823 if (OptDesc.Type != OptionType::Switch)
824 throw OptName + ": incorrect option type!";
825 O << OptDesc.GenVariableName();
827 } else if (TestName == "input_languages_contain") {
828 O << "InLangs.count(\"" << OptName << "\") != 0";
830 } else if (TestName == "in_language") {
831 // This works only for single-argument Tool::GenerateAction. Join
832 // tools can process several files in different languages simultaneously.
834 // TODO: make this work with Edge::Weight (if possible).
835 O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
837 } else if (TestName == "not_empty") {
838 if (OptName == "o") {
839 O << "!OutputFilename.empty()";
843 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
844 if (OptDesc.Type == OptionType::Switch)
845 throw OptName + ": incorrect option type!";
846 O << '!' << OptDesc.GenVariableName() << ".empty()";
854 /// EmitCaseTest2Args - Helper function used by
855 /// EmitCaseConstructHandler.
856 bool EmitCaseTest2Args(const std::string& TestName,
858 const char* IndentLevel,
859 const GlobalOptionDescriptions& OptDescs,
861 checkNumberOfArguments(&d, 2);
862 const std::string& OptName = InitPtrToString(d.getArg(0));
863 const std::string& OptArg = InitPtrToString(d.getArg(1));
864 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
866 if (TestName == "parameter_equals") {
867 if (OptDesc.Type != OptionType::Parameter
868 && OptDesc.Type != OptionType::Prefix)
869 throw OptName + ": incorrect option type!";
870 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
873 else if (TestName == "element_in_list") {
874 if (OptDesc.Type != OptionType::ParameterList
875 && OptDesc.Type != OptionType::PrefixList)
876 throw OptName + ": incorrect option type!";
877 const std::string& VarName = OptDesc.GenVariableName();
878 O << "std::find(" << VarName << ".begin(),\n"
879 << IndentLevel << Indent1 << VarName << ".end(), \""
880 << OptArg << "\") != " << VarName << ".end()";
887 // Forward declaration.
888 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
889 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
890 const GlobalOptionDescriptions& OptDescs,
893 /// EmitLogicalOperationTest - Helper function used by
894 /// EmitCaseConstructHandler.
895 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
896 const char* IndentLevel,
897 const GlobalOptionDescriptions& OptDescs,
900 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
901 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
902 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
903 if (j != NumArgs - 1)
904 O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
910 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
911 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
912 const GlobalOptionDescriptions& OptDescs,
914 const std::string& TestName = d.getOperator()->getAsString();
916 if (TestName == "and")
917 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
918 else if (TestName == "or")
919 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
920 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
922 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
925 throw TestName + ": unknown edge property!";
928 // Emit code that handles the 'case' construct.
929 // Takes a function object that should emit code for every case clause.
930 // Callback's type is
931 // void F(Init* Statement, const char* IndentLevel, std::ostream& O).
932 template <typename F>
933 void EmitCaseConstructHandler(const DagInit* d, const char* IndentLevel,
934 F Callback, bool EmitElseIf,
935 const GlobalOptionDescriptions& OptDescs,
937 assert(d->getOperator()->getAsString() == "case");
939 unsigned numArgs = d->getNumArgs();
940 if (d->getNumArgs() < 2)
941 throw "There should be at least one clause in the 'case' expression:\n"
944 for (unsigned i = 0; i != numArgs; ++i) {
945 const DagInit& Test = InitPtrToDag(d->getArg(i));
948 if (Test.getOperator()->getAsString() == "default") {
950 throw std::string("The 'default' clause should be the last in the"
951 "'case' construct!");
952 O << IndentLevel << "else {\n";
955 O << IndentLevel << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
956 EmitCaseTest(Test, IndentLevel, OptDescs, O);
960 // Emit the corresponding statement.
963 throw "Case construct handler: no corresponding action "
964 "found for the test " + Test.getAsString() + '!';
966 Init* arg = d->getArg(i);
967 if (dynamic_cast<DagInit*>(arg)
968 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case") {
969 EmitCaseConstructHandler(static_cast<DagInit*>(arg),
970 (std::string(IndentLevel) + Indent1).c_str(),
971 Callback, EmitElseIf, OptDescs, O);
974 Callback(arg, IndentLevel, O);
976 O << IndentLevel << "}\n";
980 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
981 /// implement EmitOptionPropertyHandlingCode(). Emits code for
982 /// handling the (forward) and (forward_as) option properties.
983 void EmitForwardOptionPropertyHandlingCode (const ToolOptionDescription& D,
984 const std::string& NewName,
986 const std::string& Name = NewName.empty()
991 case OptionType::Switch:
992 O << Indent3 << "vec.push_back(\"" << Name << "\");\n";
994 case OptionType::Parameter:
995 O << Indent3 << "vec.push_back(\"" << Name << "\");\n";
996 O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
998 case OptionType::Prefix:
999 O << Indent3 << "vec.push_back(\"" << Name << "\" + "
1000 << D.GenVariableName() << ");\n";
1002 case OptionType::PrefixList:
1003 O << Indent3 << "for (" << D.GenTypeDeclaration()
1004 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1005 << Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
1006 << Indent4 << "vec.push_back(\"" << Name << "\" + "
1009 case OptionType::ParameterList:
1010 O << Indent3 << "for (" << D.GenTypeDeclaration()
1011 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1012 << Indent3 << "E = " << D.GenVariableName()
1013 << ".end() ; B != E; ++B) {\n"
1014 << Indent4 << "vec.push_back(\"" << Name << "\");\n"
1015 << Indent4 << "vec.push_back(*B);\n"
1016 << Indent3 << "}\n";
1018 case OptionType::Alias:
1020 throw std::string("Aliases are not allowed in tool option descriptions!");
1024 // ToolOptionHasInterestingProperties - A helper function used by
1025 // EmitOptionPropertyHandlingCode() that tells us whether we should
1026 // emit any property handling code at all.
1027 bool ToolOptionHasInterestingProperties(const ToolOptionDescription& D) {
1029 for (OptionPropertyList::const_iterator B = D.Props.begin(),
1030 E = D.Props.end(); B != E; ++B) {
1031 const OptionProperty& OptProp = *B;
1032 if (OptProp.first == OptionPropertyType::AppendCmd
1033 || OptProp.first == OptionPropertyType::ForwardAs)
1036 if (D.isForward() || D.isUnpackValues())
1041 /// EmitOptionPropertyHandlingCode - Helper function used by
1042 /// EmitGenerateActionMethod(). Emits code that handles option
1044 void EmitOptionPropertyHandlingCode (const ToolOptionDescription& D,
1047 if (!ToolOptionHasInterestingProperties(D))
1049 // Start of the if-clause.
1050 O << Indent2 << "if (";
1051 if (D.Type == OptionType::Switch)
1052 O << D.GenVariableName();
1054 O << '!' << D.GenVariableName() << ".empty()";
1058 // Handle option properties that take an argument.
1059 for (OptionPropertyList::const_iterator B = D.Props.begin(),
1060 E = D.Props.end(); B!=E; ++B) {
1061 const OptionProperty& val = *B;
1063 switch (val.first) {
1064 // (append_cmd cmd) property
1065 case OptionPropertyType::AppendCmd:
1066 O << Indent3 << "vec.push_back(\"" << val.second << "\");\n";
1068 // (forward_as) property
1069 case OptionPropertyType::ForwardAs:
1070 EmitForwardOptionPropertyHandlingCode(D, val.second, O);
1072 // Other properties with argument
1080 // (forward) property
1082 EmitForwardOptionPropertyHandlingCode(D, "", O);
1084 // (unpack_values) property
1085 if (D.isUnpackValues()) {
1086 if (IsListOptionType(D.Type)) {
1087 O << Indent3 << "for (" << D.GenTypeDeclaration()
1088 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1089 << Indent3 << "E = " << D.GenVariableName()
1090 << ".end(); B != E; ++B)\n"
1091 << Indent4 << "llvm::SplitString(*B, vec, \",\");\n";
1093 else if (D.Type == OptionType::Prefix || D.Type == OptionType::Parameter){
1094 O << Indent3 << "llvm::SplitString("
1095 << D.GenVariableName() << ", vec, \",\");\n";
1098 throw std::string("Switches can't have unpack_values property!");
1102 // End of the if-clause.
1103 O << Indent2 << "}\n";
1106 /// SubstituteSpecialCommands - Perform string substitution for $CALL
1107 /// and $ENV. Helper function used by EmitCmdLineVecFill().
1108 std::string SubstituteSpecialCommands(const std::string& cmd) {
1109 size_t cparen = cmd.find(")");
1112 if (cmd.find("$CALL(") == 0) {
1113 if (cmd.size() == 6)
1114 throw std::string("$CALL invocation: empty argument list!");
1117 ret += std::string(cmd.begin() + 6, cmd.begin() + cparen);
1120 else if (cmd.find("$ENV(") == 0) {
1121 if (cmd.size() == 5)
1122 throw std::string("$ENV invocation: empty argument list!");
1124 ret += "std::getenv(\"";
1125 ret += std::string(cmd.begin() + 5, cmd.begin() + cparen);
1129 throw "Unknown special command: " + cmd;
1132 if (cmd.begin() + cparen + 1 != cmd.end()) {
1133 ret += " + std::string(\"";
1134 ret += (cmd.c_str() + cparen + 1);
1141 /// EmitCmdLineVecFill - Emit code that fills in the command line
1142 /// vector. Helper function used by EmitGenerateActionMethod().
1143 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1144 bool Version, const char* IndentLevel,
1147 SplitString(InitPtrToString(CmdLine), StrVec);
1149 throw "Tool " + ToolName + " has empty command line!";
1151 StrVector::const_iterator I = StrVec.begin();
1153 for (StrVector::const_iterator E = StrVec.end(); I != E; ++I) {
1154 const std::string& cmd = *I;
1156 if (cmd.at(0) == '$') {
1157 if (cmd == "$INFILE") {
1159 O << "for (PathVector::const_iterator B = inFiles.begin()"
1160 << ", E = inFiles.end();\n"
1161 << IndentLevel << "B != E; ++B)\n"
1162 << IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
1164 O << "vec.push_back(inFile.toString());\n";
1166 else if (cmd == "$OUTFILE") {
1167 O << "vec.push_back(outFile.toString());\n";
1170 O << "vec.push_back(" << SubstituteSpecialCommands(cmd);
1175 O << "vec.push_back(\"" << cmd << "\");\n";
1178 O << IndentLevel << "cmd = "
1179 << ((StrVec[0][0] == '$') ? SubstituteSpecialCommands(StrVec[0])
1180 : "\"" + StrVec[0] + "\"")
1184 /// EmitCmdLineVecFillCallback - A function object wrapper around
1185 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1186 /// argument to EmitCaseConstructHandler().
1187 class EmitCmdLineVecFillCallback {
1189 const std::string& ToolName;
1191 EmitCmdLineVecFillCallback(bool Ver, const std::string& TN)
1192 : Version(Ver), ToolName(TN) {}
1194 void operator()(const Init* Statement, const char* IndentLevel,
1195 std::ostream& O) const
1197 EmitCmdLineVecFill(Statement, ToolName, Version,
1198 (std::string(IndentLevel) + Indent1).c_str(), O);
1202 // EmitGenerateActionMethod - Emit one of two versions of the
1203 // Tool::GenerateAction() method.
1204 void EmitGenerateActionMethod (const ToolProperties& P,
1205 const GlobalOptionDescriptions& OptDescs,
1206 bool Version, std::ostream& O) {
1208 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
1210 O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
1212 O << Indent2 << "const sys::Path& outFile,\n"
1213 << Indent2 << "const InputLanguagesSet& InLangs,\n"
1214 << Indent2 << "const LanguageMap& LangMap) const\n"
1216 << Indent2 << "std::string cmd;\n"
1217 << Indent2 << "std::vector<std::string> vec;\n";
1219 // cmd_line is either a string or a 'case' construct.
1220 if (typeid(*P.CmdLine) == typeid(StringInit))
1221 EmitCmdLineVecFill(P.CmdLine, P.Name, Version, Indent2, O);
1223 EmitCaseConstructHandler(&InitPtrToDag(P.CmdLine), Indent2,
1224 EmitCmdLineVecFillCallback(Version, P.Name),
1227 // For every understood option, emit handling code.
1228 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1229 E = P.OptDescs.end(); B != E; ++B) {
1230 const ToolOptionDescription& val = B->second;
1231 EmitOptionPropertyHandlingCode(val, O);
1234 // Handle the Sink property.
1236 O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
1237 << Indent3 << "vec.insert(vec.end(), "
1238 << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
1239 << Indent2 << "}\n";
1242 O << Indent2 << "return Action(cmd, vec);\n"
1243 << Indent1 << "}\n\n";
1246 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1247 /// a given Tool class.
1248 void EmitGenerateActionMethods (const ToolProperties& P,
1249 const GlobalOptionDescriptions& OptDescs,
1252 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
1253 << Indent2 << "const llvm::sys::Path& outFile,\n"
1254 << Indent2 << "const InputLanguagesSet& InLangs,\n"
1255 << Indent2 << "const LanguageMap& LangMap) const\n"
1257 << Indent2 << "throw std::runtime_error(\"" << P.Name
1258 << " is not a Join tool!\");\n"
1259 << Indent1 << "}\n\n";
1261 EmitGenerateActionMethod(P, OptDescs, true, O);
1263 EmitGenerateActionMethod(P, OptDescs, false, O);
1266 /// EmitIsLastMethod - Emit the IsLast() method for a given Tool
1268 void EmitIsLastMethod (const ToolProperties& P, std::ostream& O) {
1269 O << Indent1 << "bool IsLast() const {\n"
1270 << Indent2 << "bool last = false;\n";
1272 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1273 E = P.OptDescs.end(); B != E; ++B) {
1274 const ToolOptionDescription& val = B->second;
1276 if (val.isStopCompilation())
1278 << "if (" << val.GenVariableName()
1279 << ")\n" << Indent3 << "last = true;\n";
1282 O << Indent2 << "return last;\n"
1283 << Indent1 << "}\n\n";
1286 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1287 /// methods for a given Tool class.
1288 void EmitInOutLanguageMethods (const ToolProperties& P, std::ostream& O) {
1289 O << Indent1 << "const char** InputLanguages() const {\n"
1290 << Indent2 << "return InputLanguages_;\n"
1291 << Indent1 << "}\n\n";
1293 O << Indent1 << "const char* OutputLanguage() const {\n"
1294 << Indent2 << "return \"" << P.OutLanguage << "\";\n"
1295 << Indent1 << "}\n\n";
1298 /// EmitOutputSuffixMethod - Emit the OutputSuffix() method for a
1299 /// given Tool class.
1300 void EmitOutputSuffixMethod (const ToolProperties& P, std::ostream& O) {
1301 O << Indent1 << "const char* OutputSuffix() const {\n"
1302 << Indent2 << "const char* ret = \"" << P.OutputSuffix << "\";\n";
1304 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1305 E = P.OptDescs.end(); B != E; ++B) {
1306 const ToolOptionDescription& OptDesc = B->second;
1307 for (OptionPropertyList::const_iterator B = OptDesc.Props.begin(),
1308 E = OptDesc.Props.end(); B != E; ++B) {
1309 const OptionProperty& OptProp = *B;
1310 if (OptProp.first == OptionPropertyType::OutputSuffix) {
1311 O << Indent2 << "if (" << OptDesc.GenVariableName() << ")\n"
1312 << Indent3 << "ret = \"" << OptProp.second << "\";\n";
1317 O << Indent2 << "return ret;\n"
1318 << Indent1 << "}\n\n";
1321 /// EmitNameMethod - Emit the Name() method for a given Tool class.
1322 void EmitNameMethod (const ToolProperties& P, std::ostream& O) {
1323 O << Indent1 << "const char* Name() const {\n"
1324 << Indent2 << "return \"" << P.Name << "\";\n"
1325 << Indent1 << "}\n\n";
1328 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1330 void EmitIsJoinMethod (const ToolProperties& P, std::ostream& O) {
1331 O << Indent1 << "bool IsJoin() const {\n";
1333 O << Indent2 << "return true;\n";
1335 O << Indent2 << "return false;\n";
1336 O << Indent1 << "}\n\n";
1339 /// EmitStaticMemberDefinitions - Emit static member definitions for a
1340 /// given Tool class.
1341 void EmitStaticMemberDefinitions(const ToolProperties& P, std::ostream& O) {
1342 O << "const char* " << P.Name << "::InputLanguages_[] = {";
1343 for (StrVector::const_iterator B = P.InLanguage.begin(),
1344 E = P.InLanguage.end(); B != E; ++B)
1345 O << '\"' << *B << "\", ";
1349 /// EmitToolClassDefinition - Emit a Tool class definition.
1350 void EmitToolClassDefinition (const ToolProperties& P,
1351 const GlobalOptionDescriptions& OptDescs,
1353 if (P.Name == "root")
1357 O << "class " << P.Name << " : public ";
1363 O << "{\nprivate:\n"
1364 << Indent1 << "static const char* InputLanguages_[];\n\n";
1367 EmitNameMethod(P, O);
1368 EmitInOutLanguageMethods(P, O);
1369 EmitOutputSuffixMethod(P, O);
1370 EmitIsJoinMethod(P, O);
1371 EmitGenerateActionMethods(P, OptDescs, O);
1372 EmitIsLastMethod(P, O);
1374 // Close class definition
1377 EmitStaticMemberDefinitions(P, O);
1381 /// EmitOptionDescriptions - Iterate over a list of option
1382 /// descriptions and emit registration code.
1383 void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
1386 std::vector<GlobalOptionDescription> Aliases;
1388 // Emit static cl::Option variables.
1389 for (GlobalOptionDescriptions::const_iterator B = descs.begin(),
1390 E = descs.end(); B!=E; ++B) {
1391 const GlobalOptionDescription& val = B->second;
1393 if (val.Type == OptionType::Alias) {
1394 Aliases.push_back(val);
1398 O << val.GenTypeDeclaration() << ' '
1399 << val.GenVariableName()
1400 << "(\"" << val.Name << '\"';
1402 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1403 O << ", cl::Prefix";
1405 if (val.isRequired()) {
1407 case OptionType::PrefixList:
1408 case OptionType::ParameterList:
1409 O << ", cl::OneOrMore";
1412 O << ", cl::Required";
1416 if (!val.Help.empty())
1417 O << ", cl::desc(\"" << val.Help << "\")";
1422 // Emit the aliases (they should go after all the 'proper' options).
1423 for (std::vector<GlobalOptionDescription>::const_iterator
1424 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
1425 const GlobalOptionDescription& val = *B;
1427 O << val.GenTypeDeclaration() << ' '
1428 << val.GenVariableName()
1429 << "(\"" << val.Name << '\"';
1431 GlobalOptionDescriptions::container_type
1432 ::const_iterator F = descs.Descriptions.find(val.Help);
1433 if (F != descs.Descriptions.end())
1434 O << ", cl::aliasopt(" << F->second.GenVariableName() << ")";
1436 throw val.Name + ": alias to an unknown option!";
1438 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
1441 // Emit the sink option.
1443 O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
1448 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
1449 void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
1451 // Get the relevant field out of RecordKeeper
1452 Record* LangMapRecord = Records.getDef("LanguageMap");
1454 throw std::string("Language map definition not found!");
1456 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
1457 if (!LangsToSuffixesList)
1458 throw std::string("Error in the language map definition!");
1461 O << "namespace {\n\n";
1462 O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
1464 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
1465 Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
1467 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
1468 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
1470 for (unsigned i = 0; i < Suffixes->size(); ++i)
1471 O << Indent1 << "langMap[\""
1472 << InitPtrToString(Suffixes->getElement(i))
1473 << "\"] = \"" << Lang << "\";\n";
1479 /// FillInToolToLang - Fills in two tables that map tool names to
1480 /// (input, output) languages. Used by the typechecker.
1481 void FillInToolToLang (const ToolPropertiesList& TPList,
1482 StringMap<StringSet<> >& ToolToInLang,
1483 StringMap<std::string>& ToolToOutLang) {
1484 for (ToolPropertiesList::const_iterator B = TPList.begin(), E = TPList.end();
1486 const ToolProperties& P = *(*B);
1487 for (StrVector::const_iterator B = P.InLanguage.begin(),
1488 E = P.InLanguage.end(); B != E; ++B)
1489 ToolToInLang[P.Name].insert(*B);
1490 ToolToOutLang[P.Name] = P.OutLanguage;
1494 /// TypecheckGraph - Check that names for output and input languages
1495 /// on all edges do match.
1496 // TOFIX: It would be nice if this function also checked for cycles
1497 // and multiple default edges in the graph (better error
1498 // reporting). Unfortunately, it is awkward to do right now because
1499 // our intermediate representation is not sufficiently
1500 // sophisticated. Algorithms like these require a real graph instead of
1502 void TypecheckGraph (Record* CompilationGraph,
1503 const ToolPropertiesList& TPList) {
1504 StringMap<StringSet<> > ToolToInLang;
1505 StringMap<std::string> ToolToOutLang;
1507 FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
1508 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1509 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
1510 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
1512 for (unsigned i = 0; i < edges->size(); ++i) {
1513 Record* Edge = edges->getElementAsRecord(i);
1514 Record* A = Edge->getValueAsDef("a");
1515 Record* B = Edge->getValueAsDef("b");
1516 StringMap<std::string>::iterator IA = ToolToOutLang.find(A->getName());
1517 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(B->getName());
1519 throw A->getName() + ": no such tool!";
1521 throw B->getName() + ": no such tool!";
1522 if (A->getName() != "root" && IB->second.count(IA->second) == 0)
1523 throw "Edge " + A->getName() + "->" + B->getName()
1524 + ": output->input language mismatch";
1525 if (B->getName() == "root")
1526 throw std::string("Edges back to the root are not allowed!");
1530 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
1531 /// by EmitEdgeClass().
1532 void IncDecWeight (const Init* i, const char* IndentLevel,
1534 const DagInit& d = InitPtrToDag(i);
1535 const std::string& OpName = d.getOperator()->getAsString();
1537 if (OpName == "inc_weight")
1538 O << IndentLevel << Indent1 << "ret += ";
1539 else if (OpName == "dec_weight")
1540 O << IndentLevel << Indent1 << "ret -= ";
1542 throw "Unknown operator in edge properties list: " + OpName + '!';
1544 if (d.getNumArgs() > 0)
1545 O << InitPtrToInt(d.getArg(0)) << ";\n";
1551 /// EmitEdgeClass - Emit a single Edge# class.
1552 void EmitEdgeClass (unsigned N, const std::string& Target,
1553 DagInit* Case, const GlobalOptionDescriptions& OptDescs,
1556 // Class constructor.
1557 O << "class Edge" << N << ": public Edge {\n"
1559 << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1562 // Function Weight().
1563 << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
1564 << Indent2 << "unsigned ret = 0;\n";
1566 // Handle the 'case' construct.
1567 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
1569 O << Indent2 << "return ret;\n"
1570 << Indent1 << "};\n\n};\n\n";
1573 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
1574 void EmitEdgeClasses (Record* CompilationGraph,
1575 const GlobalOptionDescriptions& OptDescs,
1577 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1579 for (unsigned i = 0; i < edges->size(); ++i) {
1580 Record* Edge = edges->getElementAsRecord(i);
1581 Record* B = Edge->getValueAsDef("b");
1582 DagInit* Weight = Edge->getValueAsDag("weight");
1584 if (isDagEmpty(Weight))
1587 EmitEdgeClass(i, B->getName(), Weight, OptDescs, O);
1591 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1593 void EmitPopulateCompilationGraph (Record* CompilationGraph,
1596 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1599 O << "namespace {\n\n";
1600 O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
1604 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1606 throw std::string("No tool definitions found!");
1608 for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
1609 const std::string& Name = (*B)->getName();
1611 O << Indent1 << "G.insertNode(new "
1612 << Name << "());\n";
1618 for (unsigned i = 0; i < edges->size(); ++i) {
1619 Record* Edge = edges->getElementAsRecord(i);
1620 Record* A = Edge->getValueAsDef("a");
1621 Record* B = Edge->getValueAsDef("b");
1622 DagInit* Weight = Edge->getValueAsDag("weight");
1624 O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
1626 if (isDagEmpty(Weight))
1627 O << "new SimpleEdge(\"" << B->getName() << "\")";
1629 O << "new Edge" << i << "()";
1637 /// ExtractHookNames - Extract the hook names from all instances of
1638 /// $CALL(HookName) in the provided command line string. Helper
1639 /// function used by FillInHookNames().
1640 void ExtractHookNames(const Init* CmdLine, StrVector& HookNames) {
1642 llvm::SplitString(InitPtrToString(CmdLine), cmds);
1643 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
1645 const std::string& cmd = *B;
1646 if (cmd.find("$CALL(") == 0) {
1647 if (cmd.size() == 6)
1648 throw std::string("$CALL invocation: empty argument list!");
1649 HookNames.push_back(std::string(cmd.begin() + 6,
1650 cmd.begin() + cmd.find(")")));
1655 /// ExtractHookNamesFromCaseConstruct - Extract hook names from the
1656 /// 'case' expression, handle nesting. Helper function used by
1657 /// FillInHookNames().
1658 void ExtractHookNamesFromCaseConstruct(Init* Case, StrVector& HookNames) {
1659 const DagInit& d = InitPtrToDag(Case);
1661 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1664 if (even && dynamic_cast<DagInit*>(arg)
1665 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
1666 ExtractHookNamesFromCaseConstruct(arg, HookNames);
1668 ExtractHookNames(arg, HookNames);
1673 /// FillInHookNames - Actually extract the hook names from all command
1674 /// line strings. Helper function used by EmitHookDeclarations().
1675 void FillInHookNames(const ToolPropertiesList& TPList,
1676 StrVector& HookNames) {
1677 // For all command lines:
1678 for (ToolPropertiesList::const_iterator B = TPList.begin(),
1679 E = TPList.end(); B != E; ++B) {
1680 const ToolProperties& P = *(*B);
1683 if (dynamic_cast<StringInit*>(P.CmdLine))
1684 // This is a string.
1685 ExtractHookNames(P.CmdLine, HookNames);
1687 // This is a 'case' construct.
1688 ExtractHookNamesFromCaseConstruct(P.CmdLine, HookNames);
1692 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
1693 /// property records and emit hook function declaration for each
1694 /// instance of $CALL(HookName).
1695 void EmitHookDeclarations(const ToolPropertiesList& ToolProps,
1697 StrVector HookNames;
1698 FillInHookNames(ToolProps, HookNames);
1699 if (HookNames.empty())
1701 std::sort(HookNames.begin(), HookNames.end());
1702 StrVector::const_iterator E = std::unique(HookNames.begin(), HookNames.end());
1704 O << "namespace hooks {\n";
1705 for (StrVector::const_iterator B = HookNames.begin(); B != E; ++B)
1706 O << Indent1 << "std::string " << *B << "();\n";
1711 /// EmitRegisterPlugin - Emit code to register this plugin.
1712 void EmitRegisterPlugin(std::ostream& O) {
1713 O << "namespace {\n\n"
1714 << "struct Plugin : public llvmc::BasePlugin {\n"
1715 << Indent1 << "void PopulateLanguageMap(LanguageMap& langMap) const\n"
1716 << Indent1 << "{ PopulateLanguageMapLocal(langMap); }\n\n"
1718 << "void PopulateCompilationGraph(CompilationGraph& graph) const\n"
1719 << Indent1 << "{ PopulateCompilationGraphLocal(graph); }\n"
1722 << "static llvmc::RegisterPlugin<Plugin> RP;\n\n}\n\n";
1725 /// EmitInclude - Emit necessary #include directives.
1726 void EmitIncludes(std::ostream& O) {
1727 O << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
1728 << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
1729 << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
1731 << "#include \"llvm/ADT/StringExtras.h\"\n"
1732 << "#include \"llvm/Support/CommandLine.h\"\n\n"
1734 << "#include <cstdlib>\n"
1735 << "#include <stdexcept>\n\n"
1737 << "using namespace llvm;\n"
1738 << "using namespace llvmc;\n\n"
1740 << "extern cl::opt<std::string> OutputFilename;\n\n";
1743 // End of anonymous namespace
1746 /// run - The back-end entry point.
1747 void LLVMCConfigurationEmitter::run (std::ostream &O) {
1750 // Emit file header.
1751 EmitSourceFileHeader("LLVMC Configuration Library", O);
1754 // Get a list of all defined Tools.
1755 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1757 throw std::string("No tool definitions found!");
1759 // Gather information from the Tool description dags.
1760 ToolPropertiesList tool_props;
1761 GlobalOptionDescriptions opt_descs;
1762 CollectToolProperties(Tools.begin(), Tools.end(), tool_props, opt_descs);
1764 RecordVector OptionLists = Records.getAllDerivedDefinitions("OptionList");
1765 CollectPropertiesFromOptionList(OptionLists.begin(), OptionLists.end(),
1768 // Check that there are no options without side effects (specified
1769 // only in the OptionList).
1770 CheckForSuperfluousOptions(tool_props, opt_descs);
1772 // Emit global option registration code.
1773 EmitOptionDescriptions(opt_descs, O);
1775 // Emit hook declarations.
1776 EmitHookDeclarations(tool_props, O);
1778 // Emit PopulateLanguageMap() function
1779 // (a language map maps from file extensions to language names).
1780 EmitPopulateLanguageMap(Records, O);
1782 // Emit Tool classes.
1783 for (ToolPropertiesList::const_iterator B = tool_props.begin(),
1784 E = tool_props.end(); B!=E; ++B)
1785 EmitToolClassDefinition(*(*B), opt_descs, O);
1787 Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
1788 if (!CompilationGraphRecord)
1789 throw std::string("Compilation graph description not found!");
1791 // Typecheck the compilation graph.
1792 TypecheckGraph(CompilationGraphRecord, tool_props);
1794 // Emit Edge# classes.
1795 EmitEdgeClasses(CompilationGraphRecord, opt_descs, O);
1797 // Emit PopulateCompilationGraph() function.
1798 EmitPopulateCompilationGraph(CompilationGraphRecord, O);
1800 // Emit code for plugin registration.
1801 EmitRegisterPlugin(O);
1804 } catch (std::exception& Error) {
1805 throw Error.what() + std::string(" - usually this means a syntax error.");