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"
33 //===----------------------------------------------------------------------===//
36 typedef std::vector<Record*> RecordVector;
37 typedef std::vector<std::string> StrVector;
39 //===----------------------------------------------------------------------===//
43 unsigned TabWidth = 4;
44 unsigned Indent1 = TabWidth*1;
45 unsigned Indent2 = TabWidth*2;
46 unsigned Indent3 = TabWidth*3;
48 // Default help string.
49 const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
51 // Name for the "sink" option.
52 const char * SinkOptionName = "AutoGeneratedSinkOption";
54 //===----------------------------------------------------------------------===//
57 /// Id - An 'identity' function object.
60 void operator()(const T&) const {
64 int InitPtrToInt(const Init* ptr) {
65 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
66 return val.getValue();
69 const std::string& InitPtrToString(const Init* ptr) {
70 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
71 return val.getValue();
74 const ListInit& InitPtrToList(const Init* ptr) {
75 const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
79 const DagInit& InitPtrToDag(const Init* ptr) {
80 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
84 // checkNumberOfArguments - Ensure that the number of args in d is
85 // greater than or equal to min_arguments, otherwise throw an exception.
86 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
87 if (!d || d->getNumArgs() < min_arguments)
88 throw d->getOperator()->getAsString() + ": too few arguments!";
91 // isDagEmpty - is this DAG marked with an empty marker?
92 bool isDagEmpty (const DagInit* d) {
93 return d->getOperator()->getAsString() == "empty_dag_marker";
96 // EscapeVariableName - Escape commas and other symbols not allowed
97 // in the C++ variable names. Makes it possible to use options named
98 // like "Wa," (useful for prefix options).
99 std::string EscapeVariableName(const std::string& Var) {
101 for (unsigned i = 0; i != Var.size(); ++i) {
102 char cur_char = Var[i];
103 if (cur_char == ',') {
106 else if (cur_char == '+') {
109 else if (cur_char == '-') {
113 ret.push_back(cur_char);
119 /// oneOf - Does the input string contain this character?
120 bool oneOf(const char* lst, char c) {
128 template <class I, class S>
129 void checkedIncrement(I& P, I E, S ErrorString) {
135 //===----------------------------------------------------------------------===//
136 /// Back-end specific code
139 /// OptionType - One of six different option types. See the
140 /// documentation for detailed description of differences.
141 namespace OptionType {
143 enum OptionType { Alias, Switch, Parameter, ParameterList,
146 bool IsList (OptionType t) {
147 return (t == ParameterList || t == PrefixList);
150 bool IsSwitch (OptionType t) {
151 return (t == Switch);
154 bool IsParameter (OptionType t) {
155 return (t == Parameter || t == Prefix);
160 OptionType::OptionType stringToOptionType(const std::string& T) {
161 if (T == "alias_option")
162 return OptionType::Alias;
163 else if (T == "switch_option")
164 return OptionType::Switch;
165 else if (T == "parameter_option")
166 return OptionType::Parameter;
167 else if (T == "parameter_list_option")
168 return OptionType::ParameterList;
169 else if (T == "prefix_option")
170 return OptionType::Prefix;
171 else if (T == "prefix_list_option")
172 return OptionType::PrefixList;
174 throw "Unknown option type: " + T + '!';
177 namespace OptionDescriptionFlags {
178 enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
179 ReallyHidden = 0x4, Extern = 0x8,
180 OneOrMore = 0x10, ZeroOrOne = 0x20 };
183 /// OptionDescription - Represents data contained in a single
184 /// OptionList entry.
185 struct OptionDescription {
186 OptionType::OptionType Type;
193 OptionDescription(OptionType::OptionType t = OptionType::Switch,
194 const std::string& n = "",
195 const std::string& h = DefaultHelpString)
196 : Type(t), Name(n), Flags(0x0), Help(h), MultiVal(1), InitVal(0)
199 /// GenTypeDeclaration - Returns the C++ variable type of this
201 const char* GenTypeDeclaration() const;
203 /// GenVariableName - Returns the variable name used in the
204 /// generated C++ code.
205 std::string GenVariableName() const;
207 /// Merge - Merge two option descriptions.
208 void Merge (const OptionDescription& other);
210 // Misc convenient getters/setters.
212 bool isAlias() const;
214 bool isMultiVal() const;
216 bool isExtern() const;
219 bool isRequired() const;
222 bool isOneOrMore() const;
225 bool isZeroOrOne() const;
228 bool isHidden() const;
231 bool isReallyHidden() const;
232 void setReallyHidden();
234 bool isParameter() const
235 { return OptionType::IsParameter(this->Type); }
237 bool isSwitch() const
238 { return OptionType::IsSwitch(this->Type); }
241 { return OptionType::IsList(this->Type); }
245 void OptionDescription::Merge (const OptionDescription& other)
247 if (other.Type != Type)
248 throw "Conflicting definitions for the option " + Name + "!";
250 if (Help == other.Help || Help == DefaultHelpString)
252 else if (other.Help != DefaultHelpString) {
253 llvm::errs() << "Warning: several different help strings"
254 " defined for option " + Name + "\n";
257 Flags |= other.Flags;
260 bool OptionDescription::isAlias() const {
261 return Type == OptionType::Alias;
264 bool OptionDescription::isMultiVal() const {
268 bool OptionDescription::isExtern() const {
269 return Flags & OptionDescriptionFlags::Extern;
271 void OptionDescription::setExtern() {
272 Flags |= OptionDescriptionFlags::Extern;
275 bool OptionDescription::isRequired() const {
276 return Flags & OptionDescriptionFlags::Required;
278 void OptionDescription::setRequired() {
279 Flags |= OptionDescriptionFlags::Required;
282 bool OptionDescription::isOneOrMore() const {
283 return Flags & OptionDescriptionFlags::OneOrMore;
285 void OptionDescription::setOneOrMore() {
286 Flags |= OptionDescriptionFlags::OneOrMore;
289 bool OptionDescription::isZeroOrOne() const {
290 return Flags & OptionDescriptionFlags::ZeroOrOne;
292 void OptionDescription::setZeroOrOne() {
293 Flags |= OptionDescriptionFlags::ZeroOrOne;
296 bool OptionDescription::isHidden() const {
297 return Flags & OptionDescriptionFlags::Hidden;
299 void OptionDescription::setHidden() {
300 Flags |= OptionDescriptionFlags::Hidden;
303 bool OptionDescription::isReallyHidden() const {
304 return Flags & OptionDescriptionFlags::ReallyHidden;
306 void OptionDescription::setReallyHidden() {
307 Flags |= OptionDescriptionFlags::ReallyHidden;
310 const char* OptionDescription::GenTypeDeclaration() const {
312 case OptionType::Alias:
314 case OptionType::PrefixList:
315 case OptionType::ParameterList:
316 return "cl::list<std::string>";
317 case OptionType::Switch:
318 return "cl::opt<bool>";
319 case OptionType::Parameter:
320 case OptionType::Prefix:
322 return "cl::opt<std::string>";
326 std::string OptionDescription::GenVariableName() const {
327 const std::string& EscapedName = EscapeVariableName(Name);
329 case OptionType::Alias:
330 return "AutoGeneratedAlias_" + EscapedName;
331 case OptionType::PrefixList:
332 case OptionType::ParameterList:
333 return "AutoGeneratedList_" + EscapedName;
334 case OptionType::Switch:
335 return "AutoGeneratedSwitch_" + EscapedName;
336 case OptionType::Prefix:
337 case OptionType::Parameter:
339 return "AutoGeneratedParameter_" + EscapedName;
343 /// OptionDescriptions - An OptionDescription array plus some helper
345 class OptionDescriptions {
346 typedef StringMap<OptionDescription> container_type;
348 /// Descriptions - A list of OptionDescriptions.
349 container_type Descriptions;
352 /// FindOption - exception-throwing wrapper for find().
353 const OptionDescription& FindOption(const std::string& OptName) const;
355 /// insertDescription - Insert new OptionDescription into
356 /// OptionDescriptions list
357 void InsertDescription (const OptionDescription& o);
359 // Support for STL-style iteration
360 typedef container_type::const_iterator const_iterator;
361 const_iterator begin() const { return Descriptions.begin(); }
362 const_iterator end() const { return Descriptions.end(); }
365 const OptionDescription&
366 OptionDescriptions::FindOption(const std::string& OptName) const
368 const_iterator I = Descriptions.find(OptName);
369 if (I != Descriptions.end())
372 throw OptName + ": no such option!";
375 void OptionDescriptions::InsertDescription (const OptionDescription& o)
377 container_type::iterator I = Descriptions.find(o.Name);
378 if (I != Descriptions.end()) {
379 OptionDescription& D = I->second;
383 Descriptions[o.Name] = o;
387 /// HandlerTable - A base class for function objects implemented as
388 /// 'tables of handlers'.
392 // Implementation details.
395 typedef void (T::* Handler) (const DagInit*);
396 /// HandlerMap - A map from property names to property handlers
397 typedef StringMap<Handler> HandlerMap;
399 static HandlerMap Handlers_;
400 static bool staticMembersInitialized_;
405 HandlerTable(T* cp) : childPtr(cp)
408 /// operator() - Just forwards to the corresponding property
410 void operator() (Init* i) {
411 const DagInit& property = InitPtrToDag(i);
412 const std::string& property_name = property.getOperator()->getAsString();
413 typename HandlerMap::iterator method = Handlers_.find(property_name);
415 if (method != Handlers_.end()) {
416 Handler h = method->second;
417 (childPtr->*h)(&property);
420 throw "No handler found for property " + property_name + "!";
424 void AddHandler(const char* Property, Handler Handl) {
425 Handlers_[Property] = Handl;
429 template <class T> typename HandlerTable<T>::HandlerMap
430 HandlerTable<T>::Handlers_;
431 template <class T> bool HandlerTable<T>::staticMembersInitialized_ = false;
434 /// CollectOptionProperties - Function object for iterating over an
435 /// option property list.
436 class CollectOptionProperties : public HandlerTable<CollectOptionProperties> {
439 /// optDescs_ - OptionDescriptions table. This is where the
440 /// information is stored.
441 OptionDescription& optDesc_;
445 explicit CollectOptionProperties(OptionDescription& OD)
446 : HandlerTable<CollectOptionProperties>(this), optDesc_(OD)
448 if (!staticMembersInitialized_) {
449 AddHandler("extern", &CollectOptionProperties::onExtern);
450 AddHandler("help", &CollectOptionProperties::onHelp);
451 AddHandler("hidden", &CollectOptionProperties::onHidden);
452 AddHandler("init", &CollectOptionProperties::onInit);
453 AddHandler("multi_val", &CollectOptionProperties::onMultiVal);
454 AddHandler("one_or_more", &CollectOptionProperties::onOneOrMore);
455 AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
456 AddHandler("required", &CollectOptionProperties::onRequired);
457 AddHandler("zero_or_one", &CollectOptionProperties::onZeroOrOne);
459 staticMembersInitialized_ = true;
465 /// Option property handlers --
466 /// Methods that handle option properties such as (help) or (hidden).
468 void onExtern (const DagInit* d) {
469 checkNumberOfArguments(d, 0);
470 optDesc_.setExtern();
473 void onHelp (const DagInit* d) {
474 checkNumberOfArguments(d, 1);
475 optDesc_.Help = InitPtrToString(d->getArg(0));
478 void onHidden (const DagInit* d) {
479 checkNumberOfArguments(d, 0);
480 optDesc_.setHidden();
483 void onReallyHidden (const DagInit* d) {
484 checkNumberOfArguments(d, 0);
485 optDesc_.setReallyHidden();
488 void onRequired (const DagInit* d) {
489 checkNumberOfArguments(d, 0);
490 if (optDesc_.isOneOrMore())
491 throw std::string("An option can't have both (required) "
492 "and (one_or_more) properties!");
493 optDesc_.setRequired();
496 void onInit (const DagInit* d) {
497 checkNumberOfArguments(d, 1);
498 Init* i = d->getArg(0);
499 const std::string& str = i->getAsString();
501 bool correct = optDesc_.isParameter() && dynamic_cast<StringInit*>(i);
502 correct |= (optDesc_.isSwitch() && (str == "true" || str == "false"));
505 throw std::string("Incorrect usage of the 'init' option property!");
507 optDesc_.InitVal = i;
510 void onOneOrMore (const DagInit* d) {
511 checkNumberOfArguments(d, 0);
512 if (optDesc_.isRequired() || optDesc_.isZeroOrOne())
513 throw std::string("Only one of (required), (zero_or_one) or "
514 "(one_or_more) properties is allowed!");
515 if (!OptionType::IsList(optDesc_.Type))
516 llvm::errs() << "Warning: specifying the 'one_or_more' property "
517 "on a non-list option will have no effect.\n";
518 optDesc_.setOneOrMore();
521 void onZeroOrOne (const DagInit* d) {
522 checkNumberOfArguments(d, 0);
523 if (optDesc_.isRequired() || optDesc_.isOneOrMore())
524 throw std::string("Only one of (required), (zero_or_one) or "
525 "(one_or_more) properties is allowed!");
526 if (!OptionType::IsList(optDesc_.Type))
527 llvm::errs() << "Warning: specifying the 'zero_or_one' property"
528 "on a non-list option will have no effect.\n";
529 optDesc_.setZeroOrOne();
532 void onMultiVal (const DagInit* d) {
533 checkNumberOfArguments(d, 1);
534 int val = InitPtrToInt(d->getArg(0));
536 throw std::string("Error in the 'multi_val' property: "
537 "the value must be greater than 1!");
538 if (!OptionType::IsList(optDesc_.Type))
539 throw std::string("The multi_val property is valid only "
541 optDesc_.MultiVal = val;
546 /// AddOption - A function object that is applied to every option
547 /// description. Used by CollectOptionDescriptions.
550 OptionDescriptions& OptDescs_;
553 explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
556 void operator()(const Init* i) {
557 const DagInit& d = InitPtrToDag(i);
558 checkNumberOfArguments(&d, 1);
560 const OptionType::OptionType Type =
561 stringToOptionType(d.getOperator()->getAsString());
562 const std::string& Name = InitPtrToString(d.getArg(0));
564 OptionDescription OD(Type, Name);
567 checkNumberOfArguments(&d, 2);
570 // Aliases store the aliased option name in the 'Help' field.
571 OD.Help = InitPtrToString(d.getArg(1));
573 else if (!OD.isExtern()) {
574 processOptionProperties(&d, OD);
576 OptDescs_.InsertDescription(OD);
580 /// processOptionProperties - Go through the list of option
581 /// properties and call a corresponding handler for each.
582 static void processOptionProperties (const DagInit* d, OptionDescription& o) {
583 checkNumberOfArguments(d, 2);
584 DagInit::const_arg_iterator B = d->arg_begin();
585 // Skip the first argument: it's always the option name.
587 std::for_each(B, d->arg_end(), CollectOptionProperties(o));
592 /// CollectOptionDescriptions - Collects option properties from all
594 void CollectOptionDescriptions (RecordVector::const_iterator B,
595 RecordVector::const_iterator E,
596 OptionDescriptions& OptDescs)
598 // For every OptionList:
600 RecordVector::value_type T = *B;
601 // Throws an exception if the value does not exist.
602 ListInit* PropList = T->getValueAsListInit("options");
604 // For every option description in this list:
605 // collect the information and
606 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
610 // Tool information record
612 namespace ToolFlags {
613 enum ToolFlags { Join = 0x1, Sink = 0x2 };
616 struct ToolDescription : public RefCountedBase<ToolDescription> {
620 StrVector InLanguage;
621 std::string OutLanguage;
622 std::string OutputSuffix;
625 // Various boolean properties
626 void setSink() { Flags |= ToolFlags::Sink; }
627 bool isSink() const { return Flags & ToolFlags::Sink; }
628 void setJoin() { Flags |= ToolFlags::Join; }
629 bool isJoin() const { return Flags & ToolFlags::Join; }
631 // Default ctor here is needed because StringMap can only store
632 // DefaultConstructible objects
633 ToolDescription() : CmdLine(0), Actions(0), Flags(0) {}
634 ToolDescription (const std::string& n)
635 : Name(n), CmdLine(0), Actions(0), Flags(0)
639 /// ToolDescriptions - A list of Tool information records.
640 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
643 /// CollectToolProperties - Function object for iterating over a list of
644 /// tool property records.
645 class CollectToolProperties : public HandlerTable<CollectToolProperties> {
648 /// toolDesc_ - Properties of the current Tool. This is where the
649 /// information is stored.
650 ToolDescription& toolDesc_;
654 explicit CollectToolProperties (ToolDescription& d)
655 : HandlerTable<CollectToolProperties>(this) , toolDesc_(d)
657 if (!staticMembersInitialized_) {
659 AddHandler("actions", &CollectToolProperties::onActions);
660 AddHandler("cmd_line", &CollectToolProperties::onCmdLine);
661 AddHandler("in_language", &CollectToolProperties::onInLanguage);
662 AddHandler("join", &CollectToolProperties::onJoin);
663 AddHandler("out_language", &CollectToolProperties::onOutLanguage);
664 AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
665 AddHandler("sink", &CollectToolProperties::onSink);
667 staticMembersInitialized_ = true;
673 /// Property handlers --
674 /// Functions that extract information about tool properties from
675 /// DAG representation.
677 void onActions (const DagInit* d) {
678 checkNumberOfArguments(d, 1);
679 Init* Case = d->getArg(0);
680 if (typeid(*Case) != typeid(DagInit) ||
681 static_cast<DagInit*>(Case)->getOperator()->getAsString() != "case")
683 std::string("The argument to (actions) should be a 'case' construct!");
684 toolDesc_.Actions = Case;
687 void onCmdLine (const DagInit* d) {
688 checkNumberOfArguments(d, 1);
689 toolDesc_.CmdLine = d->getArg(0);
692 void onInLanguage (const DagInit* d) {
693 checkNumberOfArguments(d, 1);
694 Init* arg = d->getArg(0);
696 // Find out the argument's type.
697 if (typeid(*arg) == typeid(StringInit)) {
699 toolDesc_.InLanguage.push_back(InitPtrToString(arg));
703 const ListInit& lst = InitPtrToList(arg);
704 StrVector& out = toolDesc_.InLanguage;
706 // Copy strings to the output vector.
707 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
709 out.push_back(InitPtrToString(*B));
712 // Remove duplicates.
713 std::sort(out.begin(), out.end());
714 StrVector::iterator newE = std::unique(out.begin(), out.end());
715 out.erase(newE, out.end());
719 void onJoin (const DagInit* d) {
720 checkNumberOfArguments(d, 0);
724 void onOutLanguage (const DagInit* d) {
725 checkNumberOfArguments(d, 1);
726 toolDesc_.OutLanguage = InitPtrToString(d->getArg(0));
729 void onOutputSuffix (const DagInit* d) {
730 checkNumberOfArguments(d, 1);
731 toolDesc_.OutputSuffix = InitPtrToString(d->getArg(0));
734 void onSink (const DagInit* d) {
735 checkNumberOfArguments(d, 0);
741 /// CollectToolDescriptions - Gather information about tool properties
742 /// from the parsed TableGen data (basically a wrapper for the
743 /// CollectToolProperties function object).
744 void CollectToolDescriptions (RecordVector::const_iterator B,
745 RecordVector::const_iterator E,
746 ToolDescriptions& ToolDescs)
748 // Iterate over a properties list of every Tool definition
750 const Record* T = *B;
751 // Throws an exception if the value does not exist.
752 ListInit* PropList = T->getValueAsListInit("properties");
754 IntrusiveRefCntPtr<ToolDescription>
755 ToolDesc(new ToolDescription(T->getName()));
757 std::for_each(PropList->begin(), PropList->end(),
758 CollectToolProperties(*ToolDesc));
759 ToolDescs.push_back(ToolDesc);
763 /// FillInEdgeVector - Merge all compilation graph definitions into
764 /// one single edge list.
765 void FillInEdgeVector(RecordVector::const_iterator B,
766 RecordVector::const_iterator E, RecordVector& Out) {
767 for (; B != E; ++B) {
768 const ListInit* edges = (*B)->getValueAsListInit("edges");
770 for (unsigned i = 0; i < edges->size(); ++i)
771 Out.push_back(edges->getElementAsRecord(i));
775 /// CalculatePriority - Calculate the priority of this plugin.
776 int CalculatePriority(RecordVector::const_iterator B,
777 RecordVector::const_iterator E) {
780 total += static_cast<int>((*B)->getValueAsInt("priority"));
785 /// NotInGraph - Helper function object for FilterNotInGraph.
788 const llvm::StringSet<>& ToolsInGraph_;
791 NotInGraph(const llvm::StringSet<>& ToolsInGraph)
792 : ToolsInGraph_(ToolsInGraph)
795 bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
796 return (ToolsInGraph_.count(x->Name) == 0);
800 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
801 /// mentioned in the compilation graph definition.
802 void FilterNotInGraph (const RecordVector& EdgeVector,
803 ToolDescriptions& ToolDescs) {
805 // List all tools mentioned in the graph.
806 llvm::StringSet<> ToolsInGraph;
808 for (RecordVector::const_iterator B = EdgeVector.begin(),
809 E = EdgeVector.end(); B != E; ++B) {
811 const Record* Edge = *B;
812 const std::string& NodeA = Edge->getValueAsString("a");
813 const std::string& NodeB = Edge->getValueAsString("b");
816 ToolsInGraph.insert(NodeA);
817 ToolsInGraph.insert(NodeB);
820 // Filter ToolPropertiesList.
821 ToolDescriptions::iterator new_end =
822 std::remove_if(ToolDescs.begin(), ToolDescs.end(),
823 NotInGraph(ToolsInGraph));
824 ToolDescs.erase(new_end, ToolDescs.end());
827 /// FillInToolToLang - Fills in two tables that map tool names to
828 /// (input, output) languages. Helper function used by TypecheckGraph().
829 void FillInToolToLang (const ToolDescriptions& ToolDescs,
830 StringMap<StringSet<> >& ToolToInLang,
831 StringMap<std::string>& ToolToOutLang) {
832 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
833 E = ToolDescs.end(); B != E; ++B) {
834 const ToolDescription& D = *(*B);
835 for (StrVector::const_iterator B = D.InLanguage.begin(),
836 E = D.InLanguage.end(); B != E; ++B)
837 ToolToInLang[D.Name].insert(*B);
838 ToolToOutLang[D.Name] = D.OutLanguage;
842 /// TypecheckGraph - Check that names for output and input languages
843 /// on all edges do match. This doesn't do much when the information
844 /// about the whole graph is not available (i.e. when compiling most
846 void TypecheckGraph (const RecordVector& EdgeVector,
847 const ToolDescriptions& ToolDescs) {
848 StringMap<StringSet<> > ToolToInLang;
849 StringMap<std::string> ToolToOutLang;
851 FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
852 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
853 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
855 for (RecordVector::const_iterator B = EdgeVector.begin(),
856 E = EdgeVector.end(); B != E; ++B) {
857 const Record* Edge = *B;
858 const std::string& NodeA = Edge->getValueAsString("a");
859 const std::string& NodeB = Edge->getValueAsString("b");
860 StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
861 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
863 if (NodeA != "root") {
864 if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
865 throw "Edge " + NodeA + "->" + NodeB
866 + ": output->input language mismatch";
870 throw std::string("Edges back to the root are not allowed!");
874 /// WalkCase - Walks the 'case' expression DAG and invokes
875 /// TestCallback on every test, and StatementCallback on every
876 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
878 // TODO: Re-implement EmitCaseConstructHandler on top of this function?
879 template <typename F1, typename F2>
880 void WalkCase(Init* Case, F1 TestCallback, F2 StatementCallback) {
881 const DagInit& d = InitPtrToDag(Case);
883 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
886 if (even && dynamic_cast<DagInit*>(arg)
887 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
888 WalkCase(arg, TestCallback, StatementCallback);
892 StatementCallback(arg);
897 /// ExtractOptionNames - A helper function object used by
898 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
899 class ExtractOptionNames {
900 llvm::StringSet<>& OptionNames_;
902 void processDag(const Init* Statement) {
903 const DagInit& Stmt = InitPtrToDag(Statement);
904 const std::string& ActionName = Stmt.getOperator()->getAsString();
905 if (ActionName == "forward" || ActionName == "forward_as" ||
906 ActionName == "unpack_values" || ActionName == "switch_on" ||
907 ActionName == "parameter_equals" || ActionName == "element_in_list" ||
908 ActionName == "not_empty" || ActionName == "empty") {
909 checkNumberOfArguments(&Stmt, 1);
910 const std::string& Name = InitPtrToString(Stmt.getArg(0));
911 OptionNames_.insert(Name);
913 else if (ActionName == "and" || ActionName == "or") {
914 for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
915 this->processDag(Stmt.getArg(i));
921 ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
924 void operator()(const Init* Statement) {
925 if (typeid(*Statement) == typeid(ListInit)) {
926 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
927 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
929 this->processDag(*B);
932 this->processDag(Statement);
937 /// CheckForSuperfluousOptions - Check that there are no side
938 /// effect-free options (specified only in the OptionList). Otherwise,
939 /// output a warning.
940 void CheckForSuperfluousOptions (const RecordVector& Edges,
941 const ToolDescriptions& ToolDescs,
942 const OptionDescriptions& OptDescs) {
943 llvm::StringSet<> nonSuperfluousOptions;
945 // Add all options mentioned in the ToolDesc.Actions to the set of
946 // non-superfluous options.
947 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
948 E = ToolDescs.end(); B != E; ++B) {
949 const ToolDescription& TD = *(*B);
950 ExtractOptionNames Callback(nonSuperfluousOptions);
952 WalkCase(TD.Actions, Callback, Callback);
955 // Add all options mentioned in the 'case' clauses of the
956 // OptionalEdges of the compilation graph to the set of
957 // non-superfluous options.
958 for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
960 const Record* Edge = *B;
961 DagInit* Weight = Edge->getValueAsDag("weight");
963 if (!isDagEmpty(Weight))
964 WalkCase(Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
967 // Check that all options in OptDescs belong to the set of
968 // non-superfluous options.
969 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
970 E = OptDescs.end(); B != E; ++B) {
971 const OptionDescription& Val = B->second;
972 if (!nonSuperfluousOptions.count(Val.Name)
973 && Val.Type != OptionType::Alias)
974 llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! "
975 "Probable cause: this option is specified only in the OptionList.\n";
979 /// EmitCaseTest0Args - Helper function used by EmitCaseConstructHandler().
980 bool EmitCaseTest0Args(const std::string& TestName, raw_ostream& O) {
981 if (TestName == "single_input_file") {
982 O << "InputFilenames.size() == 1";
985 else if (TestName == "multiple_input_files") {
986 O << "InputFilenames.size() > 1";
994 /// EmitCaseTest1Arg - Helper function used by EmitCaseConstructHandler().
995 bool EmitCaseTest1Arg(const std::string& TestName,
997 const OptionDescriptions& OptDescs,
999 checkNumberOfArguments(&d, 1);
1000 const std::string& OptName = InitPtrToString(d.getArg(0));
1002 if (TestName == "switch_on") {
1003 const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
1004 if (!OptDesc.isSwitch())
1005 throw OptName + ": incorrect option type - should be a switch!";
1006 O << OptDesc.GenVariableName();
1008 } else if (TestName == "input_languages_contain") {
1009 O << "InLangs.count(\"" << OptName << "\") != 0";
1011 } else if (TestName == "in_language") {
1012 // This works only for single-argument Tool::GenerateAction. Join
1013 // tools can process several files in different languages simultaneously.
1015 // TODO: make this work with Edge::Weight (if possible).
1016 O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
1018 } else if (TestName == "not_empty" || TestName == "empty") {
1019 const char* Test = (TestName == "empty") ? "" : "!";
1021 if (OptName == "o") {
1022 O << Test << "OutputFilename.empty()";
1026 const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
1027 if (OptDesc.isSwitch())
1029 + ": incorrect option type - should be a list or parameter!";
1030 O << Test << OptDesc.GenVariableName() << ".empty()";
1038 /// EmitCaseTest2Args - Helper function used by EmitCaseConstructHandler().
1039 bool EmitCaseTest2Args(const std::string& TestName,
1041 unsigned IndentLevel,
1042 const OptionDescriptions& OptDescs,
1044 checkNumberOfArguments(&d, 2);
1045 const std::string& OptName = InitPtrToString(d.getArg(0));
1046 const std::string& OptArg = InitPtrToString(d.getArg(1));
1047 const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
1049 if (TestName == "parameter_equals") {
1050 if (!OptDesc.isParameter())
1051 throw OptName + ": incorrect option type - should be a parameter!";
1052 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
1055 else if (TestName == "element_in_list") {
1056 if (!OptDesc.isList())
1057 throw OptName + ": incorrect option type - should be a list!";
1058 const std::string& VarName = OptDesc.GenVariableName();
1059 O << "std::find(" << VarName << ".begin(),\n";
1060 O.indent(IndentLevel + Indent1)
1061 << VarName << ".end(), \""
1062 << OptArg << "\") != " << VarName << ".end()";
1069 // Forward declaration.
1070 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
1071 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1072 const OptionDescriptions& OptDescs,
1075 /// EmitLogicalOperationTest - Helper function used by
1076 /// EmitCaseConstructHandler.
1077 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
1078 unsigned IndentLevel,
1079 const OptionDescriptions& OptDescs,
1082 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
1083 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
1084 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1085 if (j != NumArgs - 1) {
1087 O.indent(IndentLevel + Indent1) << ' ' << LogicOp << " (";
1095 void EmitLogicalNot(const DagInit& d, unsigned IndentLevel,
1096 const OptionDescriptions& OptDescs, raw_ostream& O)
1098 checkNumberOfArguments(&d, 1);
1099 const DagInit& InnerTest = InitPtrToDag(d.getArg(0));
1101 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1105 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
1106 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1107 const OptionDescriptions& OptDescs,
1109 const std::string& TestName = d.getOperator()->getAsString();
1111 if (TestName == "and")
1112 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
1113 else if (TestName == "or")
1114 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
1115 else if (TestName == "not")
1116 EmitLogicalNot(d, IndentLevel, OptDescs, O);
1117 else if (EmitCaseTest0Args(TestName, O))
1119 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
1121 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
1124 throw TestName + ": unknown edge property!";
1127 // Emit code that handles the 'case' construct.
1128 // Takes a function object that should emit code for every case clause.
1129 // Callback's type is
1130 // void F(Init* Statement, unsigned IndentLevel, raw_ostream& O).
1131 template <typename F>
1132 void EmitCaseConstructHandler(const Init* Dag, unsigned IndentLevel,
1133 F Callback, bool EmitElseIf,
1134 const OptionDescriptions& OptDescs,
1136 const DagInit* d = &InitPtrToDag(Dag);
1137 if (d->getOperator()->getAsString() != "case")
1138 throw std::string("EmitCaseConstructHandler should be invoked"
1139 " only on 'case' expressions!");
1141 unsigned numArgs = d->getNumArgs();
1142 if (d->getNumArgs() < 2)
1143 throw "There should be at least one clause in the 'case' expression:\n"
1146 for (unsigned i = 0; i != numArgs; ++i) {
1147 const DagInit& Test = InitPtrToDag(d->getArg(i));
1150 if (Test.getOperator()->getAsString() == "default") {
1152 throw std::string("The 'default' clause should be the last in the"
1153 "'case' construct!");
1154 O.indent(IndentLevel) << "else {\n";
1157 O.indent(IndentLevel) << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
1158 EmitCaseTest(Test, IndentLevel, OptDescs, O);
1162 // Emit the corresponding statement.
1165 throw "Case construct handler: no corresponding action "
1166 "found for the test " + Test.getAsString() + '!';
1168 Init* arg = d->getArg(i);
1169 const DagInit* nd = dynamic_cast<DagInit*>(arg);
1170 if (nd && (nd->getOperator()->getAsString() == "case")) {
1171 // Handle the nested 'case'.
1172 EmitCaseConstructHandler(nd, (IndentLevel + Indent1),
1173 Callback, EmitElseIf, OptDescs, O);
1176 Callback(arg, (IndentLevel + Indent1), O);
1178 O.indent(IndentLevel) << "}\n";
1182 /// TokenizeCmdline - converts from "$CALL(HookName, 'Arg1', 'Arg2')/path" to
1183 /// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path"] .
1184 /// Helper function used by EmitCmdLineVecFill and.
1185 void TokenizeCmdline(const std::string& CmdLine, StrVector& Out) {
1186 const char* Delimiters = " \t\n\v\f\r";
1188 { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1191 if (CmdLine.empty())
1195 std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1198 for (; B != E; ++B) {
1199 char cur_ch = CmdLine[B];
1203 if (cur_ch == '$') {
1204 cur_st = SpecialCommand;
1207 if (oneOf(Delimiters, cur_ch)) {
1209 B = CmdLine.find_first_not_of(Delimiters, B);
1210 if (B == std::string::npos) {
1221 case SpecialCommand:
1222 if (oneOf(Delimiters, cur_ch)) {
1227 if (cur_ch == '(') {
1229 cur_st = InsideSpecialCommand;
1234 case InsideSpecialCommand:
1235 if (oneOf(Delimiters, cur_ch)) {
1238 if (cur_ch == '\'') {
1239 cur_st = InsideQuotationMarks;
1243 if (cur_ch == ')') {
1247 if (cur_ch == ',') {
1253 case InsideQuotationMarks:
1254 if (cur_ch == '\'') {
1255 cur_st = InsideSpecialCommand;
1261 Out.back().push_back(cur_ch);
1265 /// SubstituteSpecialCommands - Perform string substitution for $CALL
1266 /// and $ENV. Helper function used by EmitCmdLineVecFill().
1267 StrVector::const_iterator SubstituteSpecialCommands
1268 (StrVector::const_iterator Pos, StrVector::const_iterator End, raw_ostream& O)
1271 const std::string& cmd = *Pos;
1273 if (cmd == "$CALL") {
1274 checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1275 const std::string& CmdName = *Pos;
1278 throw std::string("$CALL invocation: empty argument list!");
1281 O << CmdName << "(";
1284 bool firstIteration = true;
1286 checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1287 const std::string& Arg = *Pos;
1288 assert(Arg.size() != 0);
1294 firstIteration = false;
1298 O << '"' << Arg << '"';
1304 else if (cmd == "$ENV") {
1305 checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1306 const std::string& EnvName = *Pos;
1309 throw "$ENV invocation: empty argument list!";
1311 O << "checkCString(std::getenv(\"";
1315 checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1318 throw "Unknown special command: " + cmd;
1321 const std::string& Leftover = *Pos;
1322 assert(Leftover.at(0) == ')');
1323 if (Leftover.size() != 1)
1324 O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1329 /// EmitCmdLineVecFill - Emit code that fills in the command line
1330 /// vector. Helper function used by EmitGenerateActionMethod().
1331 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1332 bool IsJoin, unsigned IndentLevel,
1335 TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1338 throw "Tool '" + ToolName + "' has empty command line!";
1340 StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1342 // If there is a hook invocation on the place of the first command, skip it.
1343 assert(!StrVec[0].empty());
1344 if (StrVec[0][0] == '$') {
1345 while (I != E && (*I)[0] != ')' )
1348 // Skip the ')' symbol.
1355 bool hasINFILE = false;
1357 for (; I != E; ++I) {
1358 const std::string& cmd = *I;
1359 assert(!cmd.empty());
1360 O.indent(IndentLevel);
1361 if (cmd.at(0) == '$') {
1362 if (cmd == "$INFILE") {
1365 O << "for (PathVector::const_iterator B = inFiles.begin()"
1366 << ", E = inFiles.end();\n";
1367 O.indent(IndentLevel) << "B != E; ++B)\n";
1368 O.indent(IndentLevel + Indent1) << "vec.push_back(B->str());\n";
1371 O << "vec.push_back(inFile.str());\n";
1374 else if (cmd == "$OUTFILE") {
1375 O << "vec.push_back(\"\");\n";
1376 O.indent(IndentLevel) << "out_file_index = vec.size()-1;\n";
1379 O << "vec.push_back(";
1380 I = SubstituteSpecialCommands(I, E, O);
1385 O << "vec.push_back(\"" << cmd << "\");\n";
1389 throw "Tool '" + ToolName + "' doesn't take any input!";
1391 O.indent(IndentLevel) << "cmd = ";
1392 if (StrVec[0][0] == '$')
1393 SubstituteSpecialCommands(StrVec.begin(), StrVec.end(), O);
1395 O << '"' << StrVec[0] << '"';
1399 /// EmitCmdLineVecFillCallback - A function object wrapper around
1400 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1401 /// argument to EmitCaseConstructHandler().
1402 class EmitCmdLineVecFillCallback {
1404 const std::string& ToolName;
1406 EmitCmdLineVecFillCallback(bool J, const std::string& TN)
1407 : IsJoin(J), ToolName(TN) {}
1409 void operator()(const Init* Statement, unsigned IndentLevel,
1410 raw_ostream& O) const
1412 EmitCmdLineVecFill(Statement, ToolName, IsJoin, IndentLevel, O);
1416 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1417 /// implement EmitActionHandler. Emits code for
1418 /// handling the (forward) and (forward_as) option properties.
1419 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1420 unsigned IndentLevel,
1421 const std::string& NewName,
1423 const std::string& Name = NewName.empty()
1426 unsigned IndentLevel1 = IndentLevel + Indent1;
1429 case OptionType::Switch:
1430 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1432 case OptionType::Parameter:
1433 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1434 O.indent(IndentLevel) << "vec.push_back(" << D.GenVariableName() << ");\n";
1436 case OptionType::Prefix:
1437 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\" + "
1438 << D.GenVariableName() << ");\n";
1440 case OptionType::PrefixList:
1441 O.indent(IndentLevel)
1442 << "for (" << D.GenTypeDeclaration()
1443 << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1444 O.indent(IndentLevel)
1445 << "E = " << D.GenVariableName() << ".end(); B != E;) {\n";
1446 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\" + " << "*B);\n";
1447 O.indent(IndentLevel1) << "++B;\n";
1449 for (int i = 1, j = D.MultiVal; i < j; ++i) {
1450 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1451 O.indent(IndentLevel1) << "++B;\n";
1454 O.indent(IndentLevel) << "}\n";
1456 case OptionType::ParameterList:
1457 O.indent(IndentLevel)
1458 << "for (" << D.GenTypeDeclaration() << "::iterator B = "
1459 << D.GenVariableName() << ".begin(),\n";
1460 O.indent(IndentLevel) << "E = " << D.GenVariableName()
1461 << ".end() ; B != E;) {\n";
1462 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\");\n";
1464 for (int i = 0, j = D.MultiVal; i < j; ++i) {
1465 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1466 O.indent(IndentLevel1) << "++B;\n";
1469 O.indent(IndentLevel) << "}\n";
1471 case OptionType::Alias:
1473 throw std::string("Aliases are not allowed in tool option descriptions!");
1477 /// EmitActionHandler - Emit code that handles actions. Used by
1478 /// EmitGenerateActionMethod() as an argument to
1479 /// EmitCaseConstructHandler().
1480 class EmitActionHandler {
1481 const OptionDescriptions& OptDescs;
1483 void processActionDag(const Init* Statement, unsigned IndentLevel,
1484 raw_ostream& O) const
1486 const DagInit& Dag = InitPtrToDag(Statement);
1487 const std::string& ActionName = Dag.getOperator()->getAsString();
1489 if (ActionName == "append_cmd") {
1490 checkNumberOfArguments(&Dag, 1);
1491 const std::string& Cmd = InitPtrToString(Dag.getArg(0));
1493 llvm::SplitString(Cmd, Out);
1495 for (StrVector::const_iterator B = Out.begin(), E = Out.end();
1497 O.indent(IndentLevel) << "vec.push_back(\"" << *B << "\");\n";
1499 else if (ActionName == "error") {
1500 O.indent(IndentLevel) << "throw std::runtime_error(\"" <<
1501 (Dag.getNumArgs() >= 1 ? InitPtrToString(Dag.getArg(0))
1505 else if (ActionName == "forward") {
1506 checkNumberOfArguments(&Dag, 1);
1507 const std::string& Name = InitPtrToString(Dag.getArg(0));
1508 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1509 IndentLevel, "", O);
1511 else if (ActionName == "forward_as") {
1512 checkNumberOfArguments(&Dag, 2);
1513 const std::string& Name = InitPtrToString(Dag.getArg(0));
1514 const std::string& NewName = InitPtrToString(Dag.getArg(1));
1515 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1516 IndentLevel, NewName, O);
1518 else if (ActionName == "output_suffix") {
1519 checkNumberOfArguments(&Dag, 1);
1520 const std::string& OutSuf = InitPtrToString(Dag.getArg(0));
1521 O.indent(IndentLevel) << "output_suffix = \"" << OutSuf << "\";\n";
1523 else if (ActionName == "stop_compilation") {
1524 O.indent(IndentLevel) << "stop_compilation = true;\n";
1526 else if (ActionName == "unpack_values") {
1527 checkNumberOfArguments(&Dag, 1);
1528 const std::string& Name = InitPtrToString(Dag.getArg(0));
1529 const OptionDescription& D = OptDescs.FindOption(Name);
1532 throw std::string("Can't use unpack_values with multi-valued options!");
1535 O.indent(IndentLevel)
1536 << "for (" << D.GenTypeDeclaration()
1537 << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1538 O.indent(IndentLevel)
1539 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n";
1540 O.indent(IndentLevel + Indent1)
1541 << "llvm::SplitString(*B, vec, \",\");\n";
1543 else if (D.isParameter()){
1544 O.indent(IndentLevel) << "llvm::SplitString("
1545 << D.GenVariableName() << ", vec, \",\");\n";
1548 throw "Option '" + D.Name +
1549 "': switches can't have the 'unpack_values' property!";
1553 throw "Unknown action name: " + ActionName + "!";
1557 EmitActionHandler(const OptionDescriptions& OD)
1560 void operator()(const Init* Statement, unsigned IndentLevel,
1561 raw_ostream& O) const
1563 if (typeid(*Statement) == typeid(ListInit)) {
1564 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1565 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1567 this->processActionDag(*B, IndentLevel, O);
1570 this->processActionDag(Statement, IndentLevel, O);
1575 bool IsOutFileIndexCheckRequiredStr (const Init* CmdLine) {
1577 TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1579 for (StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1581 if (*I == "$OUTFILE")
1588 class IsOutFileIndexCheckRequiredStrCallback {
1592 IsOutFileIndexCheckRequiredStrCallback(bool* ret) : ret_(ret)
1595 void operator()(const Init* CmdLine) {
1596 if (IsOutFileIndexCheckRequiredStr(CmdLine))
1601 bool IsOutFileIndexCheckRequiredCase (Init* CmdLine) {
1603 WalkCase(CmdLine, Id(), IsOutFileIndexCheckRequiredStrCallback(&ret));
1607 /// IsOutFileIndexCheckRequired - Should we emit an "out_file_index != -1" check
1608 /// in EmitGenerateActionMethod() ?
1609 bool IsOutFileIndexCheckRequired (Init* CmdLine) {
1610 if (typeid(*CmdLine) == typeid(StringInit))
1611 return IsOutFileIndexCheckRequiredStr(CmdLine);
1613 return IsOutFileIndexCheckRequiredCase(CmdLine);
1616 // EmitGenerateActionMethod - Emit either a normal or a "join" version of the
1617 // Tool::GenerateAction() method.
1618 void EmitGenerateActionMethod (const ToolDescription& D,
1619 const OptionDescriptions& OptDescs,
1620 bool IsJoin, raw_ostream& O) {
1622 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
1624 O.indent(Indent1) << "Action GenerateAction(const sys::Path& inFile,\n";
1626 O.indent(Indent2) << "bool HasChildren,\n";
1627 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
1628 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
1629 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
1630 O.indent(Indent1) << "{\n";
1631 O.indent(Indent2) << "std::string cmd;\n";
1632 O.indent(Indent2) << "std::vector<std::string> vec;\n";
1633 O.indent(Indent2) << "bool stop_compilation = !HasChildren;\n";
1634 O.indent(Indent2) << "const char* output_suffix = \""
1635 << D.OutputSuffix << "\";\n";
1638 throw "Tool " + D.Name + " has no cmd_line property!";
1640 bool IndexCheckRequired = IsOutFileIndexCheckRequired(D.CmdLine);
1641 O.indent(Indent2) << "int out_file_index"
1642 << (IndexCheckRequired ? " = -1" : "")
1645 // Process the cmd_line property.
1646 if (typeid(*D.CmdLine) == typeid(StringInit))
1647 EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
1649 EmitCaseConstructHandler(D.CmdLine, Indent2,
1650 EmitCmdLineVecFillCallback(IsJoin, D.Name),
1653 // For every understood option, emit handling code.
1655 EmitCaseConstructHandler(D.Actions, Indent2, EmitActionHandler(OptDescs),
1656 false, OptDescs, O);
1660 << "std::string out_file = OutFilename("
1661 << (IsJoin ? "sys::Path(),\n" : "inFile,\n");
1662 O.indent(Indent3) << "TempDir, stop_compilation, output_suffix).str();\n\n";
1664 if (IndexCheckRequired)
1665 O.indent(Indent2) << "if (out_file_index != -1)\n";
1666 O.indent(IndexCheckRequired ? Indent3 : Indent2)
1667 << "vec[out_file_index] = out_file;\n";
1669 // Handle the Sink property.
1671 O.indent(Indent2) << "if (!" << SinkOptionName << ".empty()) {\n";
1672 O.indent(Indent3) << "vec.insert(vec.end(), "
1673 << SinkOptionName << ".begin(), " << SinkOptionName
1675 O.indent(Indent2) << "}\n";
1678 O.indent(Indent2) << "return Action(cmd, vec, stop_compilation, out_file);\n";
1679 O.indent(Indent1) << "}\n\n";
1682 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1683 /// a given Tool class.
1684 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
1685 const OptionDescriptions& OptDescs,
1687 if (!ToolDesc.isJoin()) {
1688 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
1689 O.indent(Indent2) << "bool HasChildren,\n";
1690 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
1691 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
1692 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
1693 O.indent(Indent1) << "{\n";
1694 O.indent(Indent2) << "throw std::runtime_error(\"" << ToolDesc.Name
1695 << " is not a Join tool!\");\n";
1696 O.indent(Indent1) << "}\n\n";
1699 EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
1702 EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
1705 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1706 /// methods for a given Tool class.
1707 void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
1708 O.indent(Indent1) << "const char** InputLanguages() const {\n";
1709 O.indent(Indent2) << "return InputLanguages_;\n";
1710 O.indent(Indent1) << "}\n\n";
1712 if (D.OutLanguage.empty())
1713 throw "Tool " + D.Name + " has no 'out_language' property!";
1715 O.indent(Indent1) << "const char* OutputLanguage() const {\n";
1716 O.indent(Indent2) << "return \"" << D.OutLanguage << "\";\n";
1717 O.indent(Indent1) << "}\n\n";
1720 /// EmitNameMethod - Emit the Name() method for a given Tool class.
1721 void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
1722 O.indent(Indent1) << "const char* Name() const {\n";
1723 O.indent(Indent2) << "return \"" << D.Name << "\";\n";
1724 O.indent(Indent1) << "}\n\n";
1727 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1729 void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
1730 O.indent(Indent1) << "bool IsJoin() const {\n";
1732 O.indent(Indent2) << "return true;\n";
1734 O.indent(Indent2) << "return false;\n";
1735 O.indent(Indent1) << "}\n\n";
1738 /// EmitStaticMemberDefinitions - Emit static member definitions for a
1739 /// given Tool class.
1740 void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
1741 if (D.InLanguage.empty())
1742 throw "Tool " + D.Name + " has no 'in_language' property!";
1744 O << "const char* " << D.Name << "::InputLanguages_[] = {";
1745 for (StrVector::const_iterator B = D.InLanguage.begin(),
1746 E = D.InLanguage.end(); B != E; ++B)
1747 O << '\"' << *B << "\", ";
1751 /// EmitToolClassDefinition - Emit a Tool class definition.
1752 void EmitToolClassDefinition (const ToolDescription& D,
1753 const OptionDescriptions& OptDescs,
1755 if (D.Name == "root")
1759 O << "class " << D.Name << " : public ";
1765 O << "{\nprivate:\n";
1766 O.indent(Indent1) << "static const char* InputLanguages_[];\n\n";
1769 EmitNameMethod(D, O);
1770 EmitInOutLanguageMethods(D, O);
1771 EmitIsJoinMethod(D, O);
1772 EmitGenerateActionMethods(D, OptDescs, O);
1774 // Close class definition
1777 EmitStaticMemberDefinitions(D, O);
1781 /// EmitOptionDefinitions - Iterate over a list of option descriptions
1782 /// and emit registration code.
1783 void EmitOptionDefinitions (const OptionDescriptions& descs,
1784 bool HasSink, bool HasExterns,
1787 std::vector<OptionDescription> Aliases;
1789 // Emit static cl::Option variables.
1790 for (OptionDescriptions::const_iterator B = descs.begin(),
1791 E = descs.end(); B!=E; ++B) {
1792 const OptionDescription& val = B->second;
1794 if (val.Type == OptionType::Alias) {
1795 Aliases.push_back(val);
1802 O << val.GenTypeDeclaration() << ' '
1803 << val.GenVariableName();
1805 if (val.isExtern()) {
1810 O << "(\"" << val.Name << "\"\n";
1812 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1813 O << ", cl::Prefix";
1815 if (val.isRequired()) {
1816 if (val.isList() && !val.isMultiVal())
1817 O << ", cl::OneOrMore";
1819 O << ", cl::Required";
1821 else if (val.isOneOrMore() && val.isList()) {
1822 O << ", cl::OneOrMore";
1824 else if (val.isZeroOrOne() && val.isList()) {
1825 O << ", cl::ZeroOrOne";
1828 if (val.isReallyHidden()) {
1829 O << ", cl::ReallyHidden";
1831 else if (val.isHidden()) {
1832 O << ", cl::Hidden";
1835 if (val.MultiVal > 1)
1836 O << ", cl::multi_val(" << val.MultiVal << ')';
1839 const std::string& str = val.InitVal->getAsString();
1840 O << ", cl::init(" << str << ')';
1843 if (!val.Help.empty())
1844 O << ", cl::desc(\"" << val.Help << "\")";
1849 // Emit the aliases (they should go after all the 'proper' options).
1850 for (std::vector<OptionDescription>::const_iterator
1851 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
1852 const OptionDescription& val = *B;
1854 O << val.GenTypeDeclaration() << ' '
1855 << val.GenVariableName()
1856 << "(\"" << val.Name << '\"';
1858 const OptionDescription& D = descs.FindOption(val.Help);
1859 O << ", cl::aliasopt(" << D.GenVariableName() << ")";
1861 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
1864 // Emit the sink option.
1866 O << (HasExterns ? "extern cl" : "cl")
1867 << "::list<std::string> " << SinkOptionName
1868 << (HasExterns ? ";\n" : "(cl::Sink);\n");
1873 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
1874 void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
1877 O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
1879 // Get the relevant field out of RecordKeeper
1880 const Record* LangMapRecord = Records.getDef("LanguageMap");
1882 // It is allowed for a plugin to have no language map.
1883 if (LangMapRecord) {
1885 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
1886 if (!LangsToSuffixesList)
1887 throw std::string("Error in the language map definition!");
1889 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
1890 const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
1892 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
1893 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
1895 for (unsigned i = 0; i < Suffixes->size(); ++i)
1896 O.indent(Indent1) << "langMap[\""
1897 << InitPtrToString(Suffixes->getElement(i))
1898 << "\"] = \"" << Lang << "\";\n";
1905 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
1906 /// by EmitEdgeClass().
1907 void IncDecWeight (const Init* i, unsigned IndentLevel,
1909 const DagInit& d = InitPtrToDag(i);
1910 const std::string& OpName = d.getOperator()->getAsString();
1912 if (OpName == "inc_weight") {
1913 O.indent(IndentLevel) << "ret += ";
1915 else if (OpName == "dec_weight") {
1916 O.indent(IndentLevel) << "ret -= ";
1918 else if (OpName == "error") {
1919 O.indent(IndentLevel)
1920 << "throw std::runtime_error(\"" <<
1921 (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0))
1928 throw "Unknown operator in edge properties list: " + OpName + '!' +
1929 "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
1931 if (d.getNumArgs() > 0)
1932 O << InitPtrToInt(d.getArg(0)) << ";\n";
1938 /// EmitEdgeClass - Emit a single Edge# class.
1939 void EmitEdgeClass (unsigned N, const std::string& Target,
1940 DagInit* Case, const OptionDescriptions& OptDescs,
1943 // Class constructor.
1944 O << "class Edge" << N << ": public Edge {\n"
1946 O.indent(Indent1) << "Edge" << N << "() : Edge(\"" << Target
1949 // Function Weight().
1951 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n";
1952 O.indent(Indent2) << "unsigned ret = 0;\n";
1954 // Handle the 'case' construct.
1955 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
1957 O.indent(Indent2) << "return ret;\n";
1958 O.indent(Indent1) << "};\n\n};\n\n";
1961 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
1962 void EmitEdgeClasses (const RecordVector& EdgeVector,
1963 const OptionDescriptions& OptDescs,
1966 for (RecordVector::const_iterator B = EdgeVector.begin(),
1967 E = EdgeVector.end(); B != E; ++B) {
1968 const Record* Edge = *B;
1969 const std::string& NodeB = Edge->getValueAsString("b");
1970 DagInit* Weight = Edge->getValueAsDag("weight");
1972 if (!isDagEmpty(Weight))
1973 EmitEdgeClass(i, NodeB, Weight, OptDescs, O);
1978 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1980 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
1981 const ToolDescriptions& ToolDescs,
1984 O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
1986 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1987 E = ToolDescs.end(); B != E; ++B)
1988 O.indent(Indent1) << "G.insertNode(new " << (*B)->Name << "());\n";
1995 for (RecordVector::const_iterator B = EdgeVector.begin(),
1996 E = EdgeVector.end(); B != E; ++B) {
1997 const Record* Edge = *B;
1998 const std::string& NodeA = Edge->getValueAsString("a");
1999 const std::string& NodeB = Edge->getValueAsString("b");
2000 DagInit* Weight = Edge->getValueAsDag("weight");
2002 O.indent(Indent1) << "G.insertEdge(\"" << NodeA << "\", ";
2004 if (isDagEmpty(Weight))
2005 O << "new SimpleEdge(\"" << NodeB << "\")";
2007 O << "new Edge" << i << "()";
2016 /// ExtractHookNames - Extract the hook names from all instances of
2017 /// $CALL(HookName) in the provided command line string. Helper
2018 /// function used by FillInHookNames().
2019 class ExtractHookNames {
2020 llvm::StringMap<unsigned>& HookNames_;
2022 ExtractHookNames(llvm::StringMap<unsigned>& HookNames)
2023 : HookNames_(HookNames) {}
2025 void operator()(const Init* CmdLine) {
2027 TokenizeCmdline(InitPtrToString(CmdLine), cmds);
2028 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
2030 const std::string& cmd = *B;
2032 if (cmd == "$CALL") {
2033 unsigned NumArgs = 0;
2034 checkedIncrement(B, E, "Syntax error in $CALL invocation!");
2035 const std::string& HookName = *B;
2038 if (HookName.at(0) == ')')
2039 throw "$CALL invoked with no arguments!";
2041 while (++B != E && B->at(0) != ')') {
2045 StringMap<unsigned>::const_iterator H = HookNames_.find(HookName);
2047 if (H != HookNames_.end() && H->second != NumArgs)
2048 throw "Overloading of hooks is not allowed. Overloaded hook: "
2051 HookNames_[HookName] = NumArgs;
2058 /// FillInHookNames - Actually extract the hook names from all command
2059 /// line strings. Helper function used by EmitHookDeclarations().
2060 void FillInHookNames(const ToolDescriptions& ToolDescs,
2061 llvm::StringMap<unsigned>& HookNames)
2063 // For all command lines:
2064 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2065 E = ToolDescs.end(); B != E; ++B) {
2066 const ToolDescription& D = *(*B);
2069 if (dynamic_cast<StringInit*>(D.CmdLine))
2070 // This is a string.
2071 ExtractHookNames(HookNames).operator()(D.CmdLine);
2073 // This is a 'case' construct.
2074 WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames));
2078 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
2079 /// property records and emit hook function declaration for each
2080 /// instance of $CALL(HookName).
2081 void EmitHookDeclarations(const ToolDescriptions& ToolDescs, raw_ostream& O) {
2082 llvm::StringMap<unsigned> HookNames;
2084 FillInHookNames(ToolDescs, HookNames);
2085 if (HookNames.empty())
2088 O << "namespace hooks {\n";
2089 for (StringMap<unsigned>::const_iterator B = HookNames.begin(),
2090 E = HookNames.end(); B != E; ++B) {
2091 O.indent(Indent1) << "std::string " << B->first() << "(";
2093 for (unsigned i = 0, j = B->second; i < j; ++i) {
2094 O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
2102 /// EmitRegisterPlugin - Emit code to register this plugin.
2103 void EmitRegisterPlugin(int Priority, raw_ostream& O) {
2104 O << "struct Plugin : public llvmc::BasePlugin {\n\n";
2105 O.indent(Indent1) << "int Priority() const { return "
2106 << Priority << "; }\n\n";
2107 O.indent(Indent1) << "void PopulateLanguageMap(LanguageMap& langMap) const\n";
2108 O.indent(Indent1) << "{ PopulateLanguageMapLocal(langMap); }\n\n";
2110 << "void PopulateCompilationGraph(CompilationGraph& graph) const\n";
2111 O.indent(Indent1) << "{ PopulateCompilationGraphLocal(graph); }\n"
2113 << "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
2116 /// EmitIncludes - Emit necessary #include directives and some
2117 /// additional declarations.
2118 void EmitIncludes(raw_ostream& O) {
2119 O << "#include \"llvm/CompilerDriver/BuiltinOptions.h\"\n"
2120 << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
2121 << "#include \"llvm/CompilerDriver/ForceLinkageMacros.h\"\n"
2122 << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
2123 << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
2125 << "#include \"llvm/ADT/StringExtras.h\"\n"
2126 << "#include \"llvm/Support/CommandLine.h\"\n\n"
2128 << "#include <cstdlib>\n"
2129 << "#include <stdexcept>\n\n"
2131 << "using namespace llvm;\n"
2132 << "using namespace llvmc;\n\n"
2134 << "extern cl::opt<std::string> OutputFilename;\n\n"
2136 << "inline const char* checkCString(const char* s)\n"
2137 << "{ return s == NULL ? \"\" : s; }\n\n";
2141 /// PluginData - Holds all information about a plugin.
2143 OptionDescriptions OptDescs;
2146 ToolDescriptions ToolDescs;
2151 /// HasSink - Go through the list of tool descriptions and check if
2152 /// there are any with the 'sink' property set.
2153 bool HasSink(const ToolDescriptions& ToolDescs) {
2154 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2155 E = ToolDescs.end(); B != E; ++B)
2162 /// HasExterns - Go through the list of option descriptions and check
2163 /// if there are any external options.
2164 bool HasExterns(const OptionDescriptions& OptDescs) {
2165 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
2166 E = OptDescs.end(); B != E; ++B)
2167 if (B->second.isExtern())
2173 /// CollectPluginData - Collect tool and option properties,
2174 /// compilation graph edges and plugin priority from the parse tree.
2175 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
2176 // Collect option properties.
2177 const RecordVector& OptionLists =
2178 Records.getAllDerivedDefinitions("OptionList");
2179 CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
2182 // Collect tool properties.
2183 const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
2184 CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
2185 Data.HasSink = HasSink(Data.ToolDescs);
2186 Data.HasExterns = HasExterns(Data.OptDescs);
2188 // Collect compilation graph edges.
2189 const RecordVector& CompilationGraphs =
2190 Records.getAllDerivedDefinitions("CompilationGraph");
2191 FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
2194 // Calculate the priority of this plugin.
2195 const RecordVector& Priorities =
2196 Records.getAllDerivedDefinitions("PluginPriority");
2197 Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
2200 /// CheckPluginData - Perform some sanity checks on the collected data.
2201 void CheckPluginData(PluginData& Data) {
2202 // Filter out all tools not mentioned in the compilation graph.
2203 FilterNotInGraph(Data.Edges, Data.ToolDescs);
2205 // Typecheck the compilation graph.
2206 TypecheckGraph(Data.Edges, Data.ToolDescs);
2208 // Check that there are no options without side effects (specified
2209 // only in the OptionList).
2210 CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
2214 void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
2215 // Emit file header.
2218 // Emit global option registration code.
2219 EmitOptionDefinitions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
2221 // Emit hook declarations.
2222 EmitHookDeclarations(Data.ToolDescs, O);
2224 O << "namespace {\n\n";
2226 // Emit PopulateLanguageMap() function
2227 // (a language map maps from file extensions to language names).
2228 EmitPopulateLanguageMap(Records, O);
2230 // Emit Tool classes.
2231 for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
2232 E = Data.ToolDescs.end(); B!=E; ++B)
2233 EmitToolClassDefinition(*(*B), Data.OptDescs, O);
2235 // Emit Edge# classes.
2236 EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
2238 // Emit PopulateCompilationGraph() function.
2239 EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
2241 // Emit code for plugin registration.
2242 EmitRegisterPlugin(Data.Priority, O);
2244 O << "} // End anonymous namespace.\n\n";
2246 // Force linkage magic.
2247 O << "namespace llvmc {\n";
2248 O << "LLVMC_FORCE_LINKAGE_DECL(LLVMC_PLUGIN_NAME) {}\n";
2255 // End of anonymous namespace
2258 /// run - The back-end entry point.
2259 void LLVMCConfigurationEmitter::run (raw_ostream &O) {
2263 CollectPluginData(Records, Data);
2264 CheckPluginData(Data);
2266 EmitSourceFileHeader("LLVMC Configuration Library", O);
2267 EmitPluginCode(Data, O);
2269 } catch (std::exception& Error) {
2270 throw Error.what() + std::string(" - usually this means a syntax error.");