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 = " ";
49 // Default help string.
50 const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
52 // Name for the "sink" option.
53 const char * SinkOptionName = "AutoGeneratedSinkOption";
55 //===----------------------------------------------------------------------===//
58 /// Id - An 'identity' function object.
61 void operator()(const T&) const {
65 int InitPtrToInt(const Init* ptr) {
66 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
67 return val.getValue();
70 const std::string& InitPtrToString(const Init* ptr) {
71 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
72 return val.getValue();
75 const ListInit& InitPtrToList(const Init* ptr) {
76 const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
80 const DagInit& InitPtrToDag(const Init* ptr) {
81 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
85 // checkNumberOfArguments - Ensure that the number of args in d is
86 // less than or equal to min_arguments, otherwise throw an exception.
87 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
88 if (!d || d->getNumArgs() < min_arguments)
89 throw "Property " + d->getOperator()->getAsString()
90 + " has too few arguments!";
93 // isDagEmpty - is this DAG marked with an empty marker?
94 bool isDagEmpty (const DagInit* d) {
95 return d->getOperator()->getAsString() == "empty";
98 // EscapeVariableName - Escape commas and other symbols not allowed
99 // in the C++ variable names. Makes it possible to use options named
100 // like "Wa," (useful for prefix options).
101 std::string EscapeVariableName(const std::string& Var) {
103 for (unsigned i = 0; i != Var.size(); ++i) {
104 char cur_char = Var[i];
105 if (cur_char == ',') {
108 else if (cur_char == '+') {
111 else if (cur_char == '-') {
115 ret.push_back(cur_char);
121 /// oneOf - Does the input string contain this character?
122 bool oneOf(const char* lst, char c) {
130 //===----------------------------------------------------------------------===//
131 /// Back-end specific code
134 /// OptionType - One of six different option types. See the
135 /// documentation for detailed description of differences.
136 /// Extern* options are those that are defined in some other plugin.
137 namespace OptionType {
138 enum OptionType { Alias, Switch, Parameter, ParameterList,
141 bool IsList (OptionType t) {
142 return (t == ParameterList || t == PrefixList);
145 bool IsSwitch (OptionType t) {
146 return (t == Switch);
149 bool IsParameter (OptionType t) {
150 return (t == Parameter || t == Prefix);
155 OptionType::OptionType stringToOptionType(const std::string& T) {
156 if (T == "alias_option")
157 return OptionType::Alias;
158 else if (T == "switch_option")
159 return OptionType::Switch;
160 else if (T == "parameter_option")
161 return OptionType::Parameter;
162 else if (T == "parameter_list_option")
163 return OptionType::ParameterList;
164 else if (T == "prefix_option")
165 return OptionType::Prefix;
166 else if (T == "prefix_list_option")
167 return OptionType::PrefixList;
169 throw "Unknown option type: " + T + '!';
172 namespace OptionDescriptionFlags {
173 enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
174 ReallyHidden = 0x4, Extern = 0x8 };
177 /// OptionDescription - Represents data contained in a single
178 /// OptionList entry.
179 struct OptionDescription {
180 OptionType::OptionType Type;
185 OptionDescription(OptionType::OptionType t = OptionType::Switch,
186 const std::string& n = "",
187 const std::string& h = DefaultHelpString)
188 : Type(t), Name(n), Flags(0x0), Help(h)
191 /// GenTypeDeclaration - Returns the C++ variable type of this
193 const char* GenTypeDeclaration() const;
195 /// GenVariableName - Returns the variable name used in the
196 /// generated C++ code.
197 std::string GenVariableName() const;
199 /// Merge - Merge two option descriptions.
200 void Merge (const OptionDescription& other);
202 // Misc convenient getters/setters.
204 bool isAlias() const;
206 bool isExtern() const;
209 bool isRequired() const;
212 bool isHidden() const;
215 bool isReallyHidden() const;
216 void setReallyHidden();
219 void OptionDescription::Merge (const OptionDescription& other)
221 if (other.Type != Type)
222 throw "Conflicting definitions for the option " + Name + "!";
224 if (Help == other.Help || Help == DefaultHelpString)
226 else if (other.Help != DefaultHelpString) {
227 llvm::cerr << "Warning: several different help strings"
228 " defined for option " + Name + "\n";
231 Flags |= other.Flags;
234 bool OptionDescription::isAlias() const {
235 return Type == OptionType::Alias;
238 bool OptionDescription::isExtern() const {
239 return Flags & OptionDescriptionFlags::Extern;
241 void OptionDescription::setExtern() {
242 Flags |= OptionDescriptionFlags::Extern;
245 bool OptionDescription::isRequired() const {
246 return Flags & OptionDescriptionFlags::Required;
248 void OptionDescription::setRequired() {
249 Flags |= OptionDescriptionFlags::Required;
252 bool OptionDescription::isHidden() const {
253 return Flags & OptionDescriptionFlags::Hidden;
255 void OptionDescription::setHidden() {
256 Flags |= OptionDescriptionFlags::Hidden;
259 bool OptionDescription::isReallyHidden() const {
260 return Flags & OptionDescriptionFlags::ReallyHidden;
262 void OptionDescription::setReallyHidden() {
263 Flags |= OptionDescriptionFlags::ReallyHidden;
266 const char* OptionDescription::GenTypeDeclaration() const {
268 case OptionType::Alias:
270 case OptionType::PrefixList:
271 case OptionType::ParameterList:
272 return "cl::list<std::string>";
273 case OptionType::Switch:
274 return "cl::opt<bool>";
275 case OptionType::Parameter:
276 case OptionType::Prefix:
278 return "cl::opt<std::string>";
282 std::string OptionDescription::GenVariableName() const {
283 const std::string& EscapedName = EscapeVariableName(Name);
285 case OptionType::Alias:
286 return "AutoGeneratedAlias_" + EscapedName;
287 case OptionType::PrefixList:
288 case OptionType::ParameterList:
289 return "AutoGeneratedList_" + EscapedName;
290 case OptionType::Switch:
291 return "AutoGeneratedSwitch_" + EscapedName;
292 case OptionType::Prefix:
293 case OptionType::Parameter:
295 return "AutoGeneratedParameter_" + EscapedName;
299 /// OptionDescriptions - An OptionDescription array plus some helper
301 class OptionDescriptions {
302 typedef StringMap<OptionDescription> container_type;
304 /// Descriptions - A list of OptionDescriptions.
305 container_type Descriptions;
308 /// FindOption - exception-throwing wrapper for find().
309 const OptionDescription& FindOption(const std::string& OptName) const;
311 /// insertDescription - Insert new OptionDescription into
312 /// OptionDescriptions list
313 void InsertDescription (const OptionDescription& o);
315 // Support for STL-style iteration
316 typedef container_type::const_iterator const_iterator;
317 const_iterator begin() const { return Descriptions.begin(); }
318 const_iterator end() const { return Descriptions.end(); }
321 const OptionDescription&
322 OptionDescriptions::FindOption(const std::string& OptName) const
324 const_iterator I = Descriptions.find(OptName);
325 if (I != Descriptions.end())
328 throw OptName + ": no such option!";
331 void OptionDescriptions::InsertDescription (const OptionDescription& o)
333 container_type::iterator I = Descriptions.find(o.Name);
334 if (I != Descriptions.end()) {
335 OptionDescription& D = I->second;
339 Descriptions[o.Name] = o;
343 /// HandlerTable - A base class for function objects implemented as
344 /// 'tables of handlers'.
348 // Implementation details.
351 typedef void (T::* Handler) (const DagInit*);
352 /// HandlerMap - A map from property names to property handlers
353 typedef StringMap<Handler> HandlerMap;
355 static HandlerMap Handlers_;
356 static bool staticMembersInitialized_;
361 HandlerTable(T* cp) : childPtr(cp)
364 /// operator() - Just forwards to the corresponding property
366 void operator() (Init* i) {
367 const DagInit& property = InitPtrToDag(i);
368 const std::string& property_name = property.getOperator()->getAsString();
369 typename HandlerMap::iterator method = Handlers_.find(property_name);
371 if (method != Handlers_.end()) {
372 Handler h = method->second;
373 (childPtr->*h)(&property);
376 throw "No handler found for property " + property_name + "!";
380 void AddHandler(const char* Property, Handler Handl) {
381 Handlers_[Property] = Handl;
385 template <class T> typename HandlerTable<T>::HandlerMap
386 HandlerTable<T>::Handlers_;
387 template <class T> bool HandlerTable<T>::staticMembersInitialized_ = false;
390 /// CollectOptionProperties - Function object for iterating over an
391 /// option property list.
392 class CollectOptionProperties : public HandlerTable<CollectOptionProperties> {
395 /// optDescs_ - OptionDescriptions table. This is where the
396 /// information is stored.
397 OptionDescription& optDesc_;
401 explicit CollectOptionProperties(OptionDescription& OD)
402 : HandlerTable<CollectOptionProperties>(this), optDesc_(OD)
404 if (!staticMembersInitialized_) {
405 AddHandler("extern", &CollectOptionProperties::onExtern);
406 AddHandler("help", &CollectOptionProperties::onHelp);
407 AddHandler("hidden", &CollectOptionProperties::onHidden);
408 AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
409 AddHandler("required", &CollectOptionProperties::onRequired);
411 staticMembersInitialized_ = true;
417 /// Option property handlers --
418 /// Methods that handle option properties such as (help) or (hidden).
420 void onExtern (const DagInit* d) {
421 checkNumberOfArguments(d, 0);
422 optDesc_.setExtern();
425 void onHelp (const DagInit* d) {
426 checkNumberOfArguments(d, 1);
427 optDesc_.Help = InitPtrToString(d->getArg(0));
430 void onHidden (const DagInit* d) {
431 checkNumberOfArguments(d, 0);
432 optDesc_.setHidden();
435 void onReallyHidden (const DagInit* d) {
436 checkNumberOfArguments(d, 0);
437 optDesc_.setReallyHidden();
440 void onRequired (const DagInit* d) {
441 checkNumberOfArguments(d, 0);
442 optDesc_.setRequired();
447 /// AddOption - A function object that is applied to every option
448 /// description. Used by CollectOptionDescriptions.
451 OptionDescriptions& OptDescs_;
454 explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
457 void operator()(const Init* i) {
458 const DagInit& d = InitPtrToDag(i);
459 checkNumberOfArguments(&d, 1);
461 const OptionType::OptionType Type =
462 stringToOptionType(d.getOperator()->getAsString());
463 const std::string& Name = InitPtrToString(d.getArg(0));
465 OptionDescription OD(Type, Name);
468 checkNumberOfArguments(&d, 2);
471 // Aliases store the aliased option name in the 'Help' field.
472 OD.Help = InitPtrToString(d.getArg(1));
474 else if (!OD.isExtern()) {
475 processOptionProperties(&d, OD);
477 OptDescs_.InsertDescription(OD);
481 /// processOptionProperties - Go through the list of option
482 /// properties and call a corresponding handler for each.
483 static void processOptionProperties (const DagInit* d, OptionDescription& o) {
484 checkNumberOfArguments(d, 2);
485 DagInit::const_arg_iterator B = d->arg_begin();
486 // Skip the first argument: it's always the option name.
488 std::for_each(B, d->arg_end(), CollectOptionProperties(o));
493 /// CollectOptionDescriptions - Collects option properties from all
495 void CollectOptionDescriptions (RecordVector::const_iterator B,
496 RecordVector::const_iterator E,
497 OptionDescriptions& OptDescs)
499 // For every OptionList:
501 RecordVector::value_type T = *B;
502 // Throws an exception if the value does not exist.
503 ListInit* PropList = T->getValueAsListInit("options");
505 // For every option description in this list:
506 // collect the information and
507 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
511 // Tool information record
513 namespace ToolFlags {
514 enum ToolFlags { Join = 0x1, Sink = 0x2 };
517 struct ToolDescription : public RefCountedBase<ToolDescription> {
521 StrVector InLanguage;
522 std::string OutLanguage;
523 std::string OutputSuffix;
526 // Various boolean properties
527 void setSink() { Flags |= ToolFlags::Sink; }
528 bool isSink() const { return Flags & ToolFlags::Sink; }
529 void setJoin() { Flags |= ToolFlags::Join; }
530 bool isJoin() const { return Flags & ToolFlags::Join; }
532 // Default ctor here is needed because StringMap can only store
533 // DefaultConstructible objects
534 ToolDescription() : CmdLine(0), Actions(0), Flags(0) {}
535 ToolDescription (const std::string& n)
536 : Name(n), CmdLine(0), Actions(0), Flags(0)
540 /// ToolDescriptions - A list of Tool information records.
541 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
544 /// CollectToolProperties - Function object for iterating over a list of
545 /// tool property records.
546 class CollectToolProperties : public HandlerTable<CollectToolProperties> {
549 /// toolDesc_ - Properties of the current Tool. This is where the
550 /// information is stored.
551 ToolDescription& toolDesc_;
555 explicit CollectToolProperties (ToolDescription& d)
556 : HandlerTable<CollectToolProperties>(this) , toolDesc_(d)
558 if (!staticMembersInitialized_) {
560 AddHandler("actions", &CollectToolProperties::onActions);
561 AddHandler("cmd_line", &CollectToolProperties::onCmdLine);
562 AddHandler("in_language", &CollectToolProperties::onInLanguage);
563 AddHandler("join", &CollectToolProperties::onJoin);
564 AddHandler("out_language", &CollectToolProperties::onOutLanguage);
565 AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
566 AddHandler("sink", &CollectToolProperties::onSink);
568 staticMembersInitialized_ = true;
574 /// Property handlers --
575 /// Functions that extract information about tool properties from
576 /// DAG representation.
578 void onActions (const DagInit* d) {
579 checkNumberOfArguments(d, 1);
580 Init* Case = d->getArg(0);
581 if (typeid(*Case) != typeid(DagInit) ||
582 static_cast<DagInit*>(Case)->getOperator()->getAsString() != "case")
584 std::string("The argument to (actions) should be a 'case' construct!");
585 toolDesc_.Actions = Case;
588 void onCmdLine (const DagInit* d) {
589 checkNumberOfArguments(d, 1);
590 toolDesc_.CmdLine = d->getArg(0);
593 void onInLanguage (const DagInit* d) {
594 checkNumberOfArguments(d, 1);
595 Init* arg = d->getArg(0);
597 // Find out the argument's type.
598 if (typeid(*arg) == typeid(StringInit)) {
600 toolDesc_.InLanguage.push_back(InitPtrToString(arg));
604 const ListInit& lst = InitPtrToList(arg);
605 StrVector& out = toolDesc_.InLanguage;
607 // Copy strings to the output vector.
608 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
610 out.push_back(InitPtrToString(*B));
613 // Remove duplicates.
614 std::sort(out.begin(), out.end());
615 StrVector::iterator newE = std::unique(out.begin(), out.end());
616 out.erase(newE, out.end());
620 void onJoin (const DagInit* d) {
621 checkNumberOfArguments(d, 0);
625 void onOutLanguage (const DagInit* d) {
626 checkNumberOfArguments(d, 1);
627 toolDesc_.OutLanguage = InitPtrToString(d->getArg(0));
630 void onOutputSuffix (const DagInit* d) {
631 checkNumberOfArguments(d, 1);
632 toolDesc_.OutputSuffix = InitPtrToString(d->getArg(0));
635 void onSink (const DagInit* d) {
636 checkNumberOfArguments(d, 0);
643 /// CollectToolDescriptions - Gather information about tool properties
644 /// from the parsed TableGen data (basically a wrapper for the
645 /// CollectToolProperties function object).
646 void CollectToolDescriptions (RecordVector::const_iterator B,
647 RecordVector::const_iterator E,
648 ToolDescriptions& ToolDescs)
650 // Iterate over a properties list of every Tool definition
652 const Record* T = *B;
653 // Throws an exception if the value does not exist.
654 ListInit* PropList = T->getValueAsListInit("properties");
656 IntrusiveRefCntPtr<ToolDescription>
657 ToolDesc(new ToolDescription(T->getName()));
659 std::for_each(PropList->begin(), PropList->end(),
660 CollectToolProperties(*ToolDesc));
661 ToolDescs.push_back(ToolDesc);
665 /// FillInEdgeVector - Merge all compilation graph definitions into
666 /// one single edge list.
667 void FillInEdgeVector(RecordVector::const_iterator B,
668 RecordVector::const_iterator E, RecordVector& Out) {
669 for (; B != E; ++B) {
670 const ListInit* edges = (*B)->getValueAsListInit("edges");
672 for (unsigned i = 0; i < edges->size(); ++i)
673 Out.push_back(edges->getElementAsRecord(i));
677 /// CalculatePriority - Calculate the priority of this plugin.
678 int CalculatePriority(RecordVector::const_iterator B,
679 RecordVector::const_iterator E) {
682 total += static_cast<int>((*B)->getValueAsInt("priority"));
687 /// NotInGraph - Helper function object for FilterNotInGraph.
690 const llvm::StringSet<>& ToolsInGraph_;
693 NotInGraph(const llvm::StringSet<>& ToolsInGraph)
694 : ToolsInGraph_(ToolsInGraph)
697 bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
698 return (ToolsInGraph_.count(x->Name) == 0);
702 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
703 /// mentioned in the compilation graph definition.
704 void FilterNotInGraph (const RecordVector& EdgeVector,
705 ToolDescriptions& ToolDescs) {
707 // List all tools mentioned in the graph.
708 llvm::StringSet<> ToolsInGraph;
710 for (RecordVector::const_iterator B = EdgeVector.begin(),
711 E = EdgeVector.end(); B != E; ++B) {
713 const Record* Edge = *B;
714 const std::string& NodeA = Edge->getValueAsString("a");
715 const std::string& NodeB = Edge->getValueAsString("b");
718 ToolsInGraph.insert(NodeA);
719 ToolsInGraph.insert(NodeB);
722 // Filter ToolPropertiesList.
723 ToolDescriptions::iterator new_end =
724 std::remove_if(ToolDescs.begin(), ToolDescs.end(),
725 NotInGraph(ToolsInGraph));
726 ToolDescs.erase(new_end, ToolDescs.end());
729 /// FillInToolToLang - Fills in two tables that map tool names to
730 /// (input, output) languages. Helper function used by TypecheckGraph().
731 void FillInToolToLang (const ToolDescriptions& ToolDescs,
732 StringMap<StringSet<> >& ToolToInLang,
733 StringMap<std::string>& ToolToOutLang) {
734 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
735 E = ToolDescs.end(); B != E; ++B) {
736 const ToolDescription& D = *(*B);
737 for (StrVector::const_iterator B = D.InLanguage.begin(),
738 E = D.InLanguage.end(); B != E; ++B)
739 ToolToInLang[D.Name].insert(*B);
740 ToolToOutLang[D.Name] = D.OutLanguage;
744 /// TypecheckGraph - Check that names for output and input languages
745 /// on all edges do match. This doesn't do much when the information
746 /// about the whole graph is not available (i.e. when compiling most
748 void TypecheckGraph (const RecordVector& EdgeVector,
749 const ToolDescriptions& ToolDescs) {
750 StringMap<StringSet<> > ToolToInLang;
751 StringMap<std::string> ToolToOutLang;
753 FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
754 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
755 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
757 for (RecordVector::const_iterator B = EdgeVector.begin(),
758 E = EdgeVector.end(); B != E; ++B) {
759 const Record* Edge = *B;
760 const std::string& NodeA = Edge->getValueAsString("a");
761 const std::string& NodeB = Edge->getValueAsString("b");
762 StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
763 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
765 if (NodeA != "root") {
766 if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
767 throw "Edge " + NodeA + "->" + NodeB
768 + ": output->input language mismatch";
772 throw std::string("Edges back to the root are not allowed!");
776 /// WalkCase - Walks the 'case' expression DAG and invokes
777 /// TestCallback on every test, and StatementCallback on every
778 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
780 // TODO: Re-implement EmitCaseConstructHandler on top of this function?
781 template <typename F1, typename F2>
782 void WalkCase(Init* Case, F1 TestCallback, F2 StatementCallback) {
783 const DagInit& d = InitPtrToDag(Case);
785 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
788 if (even && dynamic_cast<DagInit*>(arg)
789 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
790 WalkCase(arg, TestCallback, StatementCallback);
794 StatementCallback(arg);
799 /// ExtractOptionNames - A helper function object used by
800 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
801 class ExtractOptionNames {
802 llvm::StringSet<>& OptionNames_;
804 void processDag(const Init* Statement) {
805 const DagInit& Stmt = InitPtrToDag(Statement);
806 const std::string& ActionName = Stmt.getOperator()->getAsString();
807 if (ActionName == "forward" || ActionName == "forward_as" ||
808 ActionName == "unpack_values" || ActionName == "switch_on" ||
809 ActionName == "parameter_equals" || ActionName == "element_in_list" ||
810 ActionName == "not_empty" || ActionName == "empty") {
811 checkNumberOfArguments(&Stmt, 1);
812 const std::string& Name = InitPtrToString(Stmt.getArg(0));
813 OptionNames_.insert(Name);
815 else if (ActionName == "and" || ActionName == "or") {
816 for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
817 this->processDag(Stmt.getArg(i));
823 ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
826 void operator()(const Init* Statement) {
827 if (typeid(*Statement) == typeid(ListInit)) {
828 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
829 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
831 this->processDag(*B);
834 this->processDag(Statement);
839 /// CheckForSuperfluousOptions - Check that there are no side
840 /// effect-free options (specified only in the OptionList). Otherwise,
841 /// output a warning.
842 void CheckForSuperfluousOptions (const RecordVector& Edges,
843 const ToolDescriptions& ToolDescs,
844 const OptionDescriptions& OptDescs) {
845 llvm::StringSet<> nonSuperfluousOptions;
847 // Add all options mentioned in the ToolDesc.Actions to the set of
848 // non-superfluous options.
849 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
850 E = ToolDescs.end(); B != E; ++B) {
851 const ToolDescription& TD = *(*B);
852 ExtractOptionNames Callback(nonSuperfluousOptions);
854 WalkCase(TD.Actions, Callback, Callback);
857 // Add all options mentioned in the 'case' clauses of the
858 // OptionalEdges of the compilation graph to the set of
859 // non-superfluous options.
860 for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
862 const Record* Edge = *B;
863 DagInit* Weight = Edge->getValueAsDag("weight");
865 if (!isDagEmpty(Weight))
866 WalkCase(Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
869 // Check that all options in OptDescs belong to the set of
870 // non-superfluous options.
871 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
872 E = OptDescs.end(); B != E; ++B) {
873 const OptionDescription& Val = B->second;
874 if (!nonSuperfluousOptions.count(Val.Name)
875 && Val.Type != OptionType::Alias)
876 llvm::cerr << "Warning: option '-" << Val.Name << "' has no effect! "
877 "Probable cause: this option is specified only in the OptionList.\n";
881 /// EmitCaseTest1Arg - Helper function used by
882 /// EmitCaseConstructHandler.
883 bool EmitCaseTest1Arg(const std::string& TestName,
885 const OptionDescriptions& OptDescs,
887 checkNumberOfArguments(&d, 1);
888 const std::string& OptName = InitPtrToString(d.getArg(0));
890 if (TestName == "switch_on") {
891 const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
892 if (!OptionType::IsSwitch(OptDesc.Type))
893 throw OptName + ": incorrect option type - should be a switch!";
894 O << OptDesc.GenVariableName();
896 } else if (TestName == "input_languages_contain") {
897 O << "InLangs.count(\"" << OptName << "\") != 0";
899 } else if (TestName == "in_language") {
900 // This works only for single-argument Tool::GenerateAction. Join
901 // tools can process several files in different languages simultaneously.
903 // TODO: make this work with Edge::Weight (if possible).
904 O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
906 } else if (TestName == "not_empty" || TestName == "empty") {
907 const char* Test = (TestName == "empty") ? "" : "!";
909 if (OptName == "o") {
910 O << Test << "OutputFilename.empty()";
914 const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
915 if (OptionType::IsSwitch(OptDesc.Type))
917 + ": incorrect option type - should be a list or parameter!";
918 O << Test << OptDesc.GenVariableName() << ".empty()";
926 /// EmitCaseTest2Args - Helper function used by
927 /// EmitCaseConstructHandler.
928 bool EmitCaseTest2Args(const std::string& TestName,
930 const char* IndentLevel,
931 const OptionDescriptions& OptDescs,
933 checkNumberOfArguments(&d, 2);
934 const std::string& OptName = InitPtrToString(d.getArg(0));
935 const std::string& OptArg = InitPtrToString(d.getArg(1));
936 const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
938 if (TestName == "parameter_equals") {
939 if (!OptionType::IsParameter(OptDesc.Type))
940 throw OptName + ": incorrect option type - should be a parameter!";
941 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
944 else if (TestName == "element_in_list") {
945 if (!OptionType::IsList(OptDesc.Type))
946 throw OptName + ": incorrect option type - should be a list!";
947 const std::string& VarName = OptDesc.GenVariableName();
948 O << "std::find(" << VarName << ".begin(),\n"
949 << IndentLevel << Indent1 << VarName << ".end(), \""
950 << OptArg << "\") != " << VarName << ".end()";
957 // Forward declaration.
958 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
959 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
960 const OptionDescriptions& OptDescs,
963 /// EmitLogicalOperationTest - Helper function used by
964 /// EmitCaseConstructHandler.
965 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
966 const char* IndentLevel,
967 const OptionDescriptions& OptDescs,
970 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
971 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
972 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
973 if (j != NumArgs - 1)
974 O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
980 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
981 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
982 const OptionDescriptions& OptDescs,
984 const std::string& TestName = d.getOperator()->getAsString();
986 if (TestName == "and")
987 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
988 else if (TestName == "or")
989 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
990 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
992 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
995 throw TestName + ": unknown edge property!";
998 // Emit code that handles the 'case' construct.
999 // Takes a function object that should emit code for every case clause.
1000 // Callback's type is
1001 // void F(Init* Statement, const char* IndentLevel, std::ostream& O).
1002 template <typename F>
1003 void EmitCaseConstructHandler(const Init* Dag, const char* IndentLevel,
1004 F Callback, bool EmitElseIf,
1005 const OptionDescriptions& OptDescs,
1007 const DagInit* d = &InitPtrToDag(Dag);
1008 if (d->getOperator()->getAsString() != "case")
1009 throw std::string("EmitCaseConstructHandler should be invoked"
1010 " only on 'case' expressions!");
1012 unsigned numArgs = d->getNumArgs();
1013 if (d->getNumArgs() < 2)
1014 throw "There should be at least one clause in the 'case' expression:\n"
1017 for (unsigned i = 0; i != numArgs; ++i) {
1018 const DagInit& Test = InitPtrToDag(d->getArg(i));
1021 if (Test.getOperator()->getAsString() == "default") {
1023 throw std::string("The 'default' clause should be the last in the"
1024 "'case' construct!");
1025 O << IndentLevel << "else {\n";
1028 O << IndentLevel << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
1029 EmitCaseTest(Test, IndentLevel, OptDescs, O);
1033 // Emit the corresponding statement.
1036 throw "Case construct handler: no corresponding action "
1037 "found for the test " + Test.getAsString() + '!';
1039 Init* arg = d->getArg(i);
1040 const DagInit* nd = dynamic_cast<DagInit*>(arg);
1041 if (nd && (nd->getOperator()->getAsString() == "case")) {
1042 // Handle the nested 'case'.
1043 EmitCaseConstructHandler(nd, (std::string(IndentLevel) + Indent1).c_str(),
1044 Callback, EmitElseIf, OptDescs, O);
1047 Callback(arg, (std::string(IndentLevel) + Indent1).c_str(), O);
1049 O << IndentLevel << "}\n";
1053 /// TokenizeCmdline - converts from "$CALL(HookName, 'Arg1', 'Arg2')/path" to
1054 /// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path"] .
1055 /// Helper function used by EmitCmdLineVecFill and.
1056 void TokenizeCmdline(const std::string& CmdLine, StrVector& Out) {
1057 const char* Delimiters = " \t\n\v\f\r";
1059 { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1063 std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1065 if (B == std::string::npos)
1066 throw "Empty command-line string!";
1067 for (; B != E; ++B) {
1068 char cur_ch = CmdLine[B];
1072 if (cur_ch == '$') {
1073 cur_st = SpecialCommand;
1076 if (oneOf(Delimiters, cur_ch)) {
1078 B = CmdLine.find_first_not_of(Delimiters, B);
1079 if (B == std::string::npos) {
1090 case SpecialCommand:
1091 if (oneOf(Delimiters, cur_ch)) {
1096 if (cur_ch == '(') {
1098 cur_st = InsideSpecialCommand;
1103 case InsideSpecialCommand:
1104 if (oneOf(Delimiters, cur_ch)) {
1107 if (cur_ch == '\'') {
1108 cur_st = InsideQuotationMarks;
1112 if (cur_ch == ')') {
1116 if (cur_ch == ',') {
1122 case InsideQuotationMarks:
1123 if (cur_ch == '\'') {
1124 cur_st = InsideSpecialCommand;
1130 Out.back().push_back(cur_ch);
1134 template <class I, class S>
1135 void checkedIncrement(I& P, I E, S ErrorString) {
1141 /// SubstituteSpecialCommands - Perform string substitution for $CALL
1142 /// and $ENV. Helper function used by EmitCmdLineVecFill().
1143 StrVector::const_iterator SubstituteSpecialCommands
1144 (StrVector::const_iterator Pos, StrVector::const_iterator End, std::ostream& O)
1147 const std::string& cmd = *Pos;
1149 if (cmd == "$CALL") {
1150 checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1151 const std::string& CmdName = *Pos;
1154 throw std::string("$CALL invocation: empty argument list!");
1157 O << CmdName << "(";
1160 bool firstIteration = true;
1162 checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1163 const std::string& Arg = *Pos;
1164 assert(Arg.size() != 0);
1170 firstIteration = false;
1174 O << '"' << Arg << '"';
1180 else if (cmd == "$ENV") {
1181 checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1182 const std::string& EnvName = *Pos;
1185 throw "$ENV invocation: empty argument list!";
1187 O << "checkCString(std::getenv(\"";
1191 checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1194 throw "Unknown special command: " + cmd;
1197 const std::string& Leftover = *Pos;
1198 assert(Leftover.at(0) == ')');
1199 if (Leftover.size() != 1)
1200 O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1206 /// EmitCmdLineVecFill - Emit code that fills in the command line
1207 /// vector. Helper function used by EmitGenerateActionMethod().
1208 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1209 bool IsJoin, const char* IndentLevel,
1212 TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1215 throw "Tool " + ToolName + " has empty command line!";
1217 StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1219 // If there is a hook invocation on the place of the first command, skip it.
1220 if (StrVec[0][0] == '$') {
1221 while (I != E && (*I)[0] != ')' )
1224 // Skip the ')' symbol.
1231 for (; I != E; ++I) {
1232 const std::string& cmd = *I;
1233 // std::cerr << cmd;
1235 if (cmd.at(0) == '$') {
1236 if (cmd == "$INFILE") {
1238 O << "for (PathVector::const_iterator B = inFiles.begin()"
1239 << ", E = inFiles.end();\n"
1240 << IndentLevel << "B != E; ++B)\n"
1241 << IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
1243 O << "vec.push_back(inFile.toString());\n";
1245 else if (cmd == "$OUTFILE") {
1246 O << "vec.push_back(out_file);\n";
1249 O << "vec.push_back(";
1250 I = SubstituteSpecialCommands(I, E, O);
1255 O << "vec.push_back(\"" << cmd << "\");\n";
1258 O << IndentLevel << "cmd = ";
1260 if (StrVec[0][0] == '$')
1261 SubstituteSpecialCommands(StrVec.begin(), StrVec.end(), O);
1263 O << '"' << StrVec[0] << '"';
1267 /// EmitCmdLineVecFillCallback - A function object wrapper around
1268 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1269 /// argument to EmitCaseConstructHandler().
1270 class EmitCmdLineVecFillCallback {
1272 const std::string& ToolName;
1274 EmitCmdLineVecFillCallback(bool J, const std::string& TN)
1275 : IsJoin(J), ToolName(TN) {}
1277 void operator()(const Init* Statement, const char* IndentLevel,
1278 std::ostream& O) const
1280 EmitCmdLineVecFill(Statement, ToolName, IsJoin,
1285 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1286 /// implement EmitActionHandler. Emits code for
1287 /// handling the (forward) and (forward_as) option properties.
1288 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1290 const std::string& NewName,
1292 const std::string& Name = NewName.empty()
1297 case OptionType::Switch:
1298 O << Indent << "vec.push_back(\"" << Name << "\");\n";
1300 case OptionType::Parameter:
1301 O << Indent << "vec.push_back(\"" << Name << "\");\n";
1302 O << Indent << "vec.push_back(" << D.GenVariableName() << ");\n";
1304 case OptionType::Prefix:
1305 O << Indent << "vec.push_back(\"" << Name << "\" + "
1306 << D.GenVariableName() << ");\n";
1308 case OptionType::PrefixList:
1309 O << Indent << "for (" << D.GenTypeDeclaration()
1310 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1311 << Indent << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
1312 << Indent << Indent1 << "vec.push_back(\"" << Name << "\" + "
1315 case OptionType::ParameterList:
1316 O << Indent << "for (" << D.GenTypeDeclaration()
1317 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1318 << Indent << "E = " << D.GenVariableName()
1319 << ".end() ; B != E; ++B) {\n"
1320 << Indent << Indent1 << "vec.push_back(\"" << Name << "\");\n"
1321 << Indent << Indent1 << "vec.push_back(*B);\n"
1324 case OptionType::Alias:
1326 throw std::string("Aliases are not allowed in tool option descriptions!");
1330 /// EmitActionHandler - Emit code that handles actions. Used by
1331 /// EmitGenerateActionMethod() as an argument to
1332 /// EmitCaseConstructHandler().
1333 class EmitActionHandler {
1334 const OptionDescriptions& OptDescs;
1336 void processActionDag(const Init* Statement, const char* IndentLevel,
1337 std::ostream& O) const
1339 const DagInit& Dag = InitPtrToDag(Statement);
1340 const std::string& ActionName = Dag.getOperator()->getAsString();
1342 if (ActionName == "append_cmd") {
1343 checkNumberOfArguments(&Dag, 1);
1344 const std::string& Cmd = InitPtrToString(Dag.getArg(0));
1345 O << IndentLevel << "vec.push_back(\"" << Cmd << "\");\n";
1347 else if (ActionName == "error") {
1348 O << IndentLevel << "throw std::runtime_error(\"" <<
1349 (Dag.getNumArgs() >= 1 ? InitPtrToString(Dag.getArg(0))
1353 else if (ActionName == "forward") {
1354 checkNumberOfArguments(&Dag, 1);
1355 const std::string& Name = InitPtrToString(Dag.getArg(0));
1356 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1357 IndentLevel, "", O);
1359 else if (ActionName == "forward_as") {
1360 checkNumberOfArguments(&Dag, 2);
1361 const std::string& Name = InitPtrToString(Dag.getArg(0));
1362 const std::string& NewName = InitPtrToString(Dag.getArg(0));
1363 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1364 IndentLevel, NewName, O);
1366 else if (ActionName == "output_suffix") {
1367 checkNumberOfArguments(&Dag, 1);
1368 const std::string& OutSuf = InitPtrToString(Dag.getArg(0));
1369 O << IndentLevel << "output_suffix = \"" << OutSuf << "\";\n";
1371 else if (ActionName == "stop_compilation") {
1372 O << IndentLevel << "stop_compilation = true;\n";
1374 else if (ActionName == "unpack_values") {
1375 checkNumberOfArguments(&Dag, 1);
1376 const std::string& Name = InitPtrToString(Dag.getArg(0));
1377 const OptionDescription& D = OptDescs.FindOption(Name);
1379 if (OptionType::IsList(D.Type)) {
1380 O << IndentLevel << "for (" << D.GenTypeDeclaration()
1381 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1382 << IndentLevel << "E = " << D.GenVariableName()
1383 << ".end(); B != E; ++B)\n"
1384 << IndentLevel << Indent1 << "llvm::SplitString(*B, vec, \",\");\n";
1386 else if (OptionType::IsParameter(D.Type)){
1387 O << Indent3 << "llvm::SplitString("
1388 << D.GenVariableName() << ", vec, \",\");\n";
1391 throw "Option '" + D.Name +
1392 "': switches can't have the 'unpack_values' property!";
1396 throw "Unknown action name: " + ActionName + "!";
1400 EmitActionHandler(const OptionDescriptions& OD)
1403 void operator()(const Init* Statement, const char* IndentLevel,
1404 std::ostream& O) const
1406 if (typeid(*Statement) == typeid(ListInit)) {
1407 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1408 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1410 this->processActionDag(*B, IndentLevel, O);
1413 this->processActionDag(Statement, IndentLevel, O);
1418 // EmitGenerateActionMethod - Emit one of two versions of the
1419 // Tool::GenerateAction() method.
1420 void EmitGenerateActionMethod (const ToolDescription& D,
1421 const OptionDescriptions& OptDescs,
1422 bool IsJoin, std::ostream& O) {
1424 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
1426 O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
1428 O << Indent2 << "bool HasChildren,\n"
1429 << Indent2 << "const llvm::sys::Path& TempDir,\n"
1430 << Indent2 << "const InputLanguagesSet& InLangs,\n"
1431 << Indent2 << "const LanguageMap& LangMap) const\n"
1433 << Indent2 << "std::string cmd;\n"
1434 << Indent2 << "std::vector<std::string> vec;\n"
1435 << Indent2 << "bool stop_compilation = !HasChildren;\n"
1436 << Indent2 << "const char* output_suffix = \"" << D.OutputSuffix << "\";\n"
1437 << Indent2 << "std::string out_file;\n\n";
1439 // For every understood option, emit handling code.
1441 EmitCaseConstructHandler(D.Actions, Indent2, EmitActionHandler(OptDescs),
1442 false, OptDescs, O);
1444 O << '\n' << Indent2
1445 << "out_file = OutFilename(" << (IsJoin ? "sys::Path(),\n" : "inFile,\n")
1446 << Indent3 << "TempDir, stop_compilation, output_suffix).toString();\n\n";
1448 // cmd_line is either a string or a 'case' construct.
1450 throw "Tool " + D.Name + " has no cmd_line property!";
1451 else if (typeid(*D.CmdLine) == typeid(StringInit))
1452 EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
1454 EmitCaseConstructHandler(D.CmdLine, Indent2,
1455 EmitCmdLineVecFillCallback(IsJoin, D.Name),
1458 // Handle the Sink property.
1460 O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
1461 << Indent3 << "vec.insert(vec.end(), "
1462 << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
1463 << Indent2 << "}\n";
1466 O << Indent2 << "return Action(cmd, vec, stop_compilation, out_file);\n"
1467 << Indent1 << "}\n\n";
1470 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1471 /// a given Tool class.
1472 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
1473 const OptionDescriptions& OptDescs,
1475 if (!ToolDesc.isJoin())
1476 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
1477 << Indent2 << "bool HasChildren,\n"
1478 << Indent2 << "const llvm::sys::Path& TempDir,\n"
1479 << Indent2 << "const InputLanguagesSet& InLangs,\n"
1480 << Indent2 << "const LanguageMap& LangMap) const\n"
1482 << Indent2 << "throw std::runtime_error(\"" << ToolDesc.Name
1483 << " is not a Join tool!\");\n"
1484 << Indent1 << "}\n\n";
1486 EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
1488 EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
1491 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1492 /// methods for a given Tool class.
1493 void EmitInOutLanguageMethods (const ToolDescription& D, std::ostream& O) {
1494 O << Indent1 << "const char** InputLanguages() const {\n"
1495 << Indent2 << "return InputLanguages_;\n"
1496 << Indent1 << "}\n\n";
1498 if (D.OutLanguage.empty())
1499 throw "Tool " + D.Name + " has no 'out_language' property!";
1501 O << Indent1 << "const char* OutputLanguage() const {\n"
1502 << Indent2 << "return \"" << D.OutLanguage << "\";\n"
1503 << Indent1 << "}\n\n";
1506 /// EmitNameMethod - Emit the Name() method for a given Tool class.
1507 void EmitNameMethod (const ToolDescription& D, std::ostream& O) {
1508 O << Indent1 << "const char* Name() const {\n"
1509 << Indent2 << "return \"" << D.Name << "\";\n"
1510 << Indent1 << "}\n\n";
1513 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1515 void EmitIsJoinMethod (const ToolDescription& D, std::ostream& O) {
1516 O << Indent1 << "bool IsJoin() const {\n";
1518 O << Indent2 << "return true;\n";
1520 O << Indent2 << "return false;\n";
1521 O << Indent1 << "}\n\n";
1524 /// EmitStaticMemberDefinitions - Emit static member definitions for a
1525 /// given Tool class.
1526 void EmitStaticMemberDefinitions(const ToolDescription& D, std::ostream& O) {
1527 if (D.InLanguage.empty())
1528 throw "Tool " + D.Name + " has no 'in_language' property!";
1530 O << "const char* " << D.Name << "::InputLanguages_[] = {";
1531 for (StrVector::const_iterator B = D.InLanguage.begin(),
1532 E = D.InLanguage.end(); B != E; ++B)
1533 O << '\"' << *B << "\", ";
1537 /// EmitToolClassDefinition - Emit a Tool class definition.
1538 void EmitToolClassDefinition (const ToolDescription& D,
1539 const OptionDescriptions& OptDescs,
1541 if (D.Name == "root")
1545 O << "class " << D.Name << " : public ";
1551 O << "{\nprivate:\n"
1552 << Indent1 << "static const char* InputLanguages_[];\n\n";
1555 EmitNameMethod(D, O);
1556 EmitInOutLanguageMethods(D, O);
1557 EmitIsJoinMethod(D, O);
1558 EmitGenerateActionMethods(D, OptDescs, O);
1560 // Close class definition
1563 EmitStaticMemberDefinitions(D, O);
1567 /// EmitOptionDefintions - Iterate over a list of option descriptions
1568 /// and emit registration code.
1569 void EmitOptionDefintions (const OptionDescriptions& descs,
1570 bool HasSink, bool HasExterns,
1573 std::vector<OptionDescription> Aliases;
1575 // Emit static cl::Option variables.
1576 for (OptionDescriptions::const_iterator B = descs.begin(),
1577 E = descs.end(); B!=E; ++B) {
1578 const OptionDescription& val = B->second;
1580 if (val.Type == OptionType::Alias) {
1581 Aliases.push_back(val);
1588 O << val.GenTypeDeclaration() << ' '
1589 << val.GenVariableName();
1591 if (val.isExtern()) {
1596 O << "(\"" << val.Name << '\"';
1598 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1599 O << ", cl::Prefix";
1601 if (val.isRequired()) {
1603 case OptionType::PrefixList:
1604 case OptionType::ParameterList:
1605 O << ", cl::OneOrMore";
1608 O << ", cl::Required";
1612 if (val.isReallyHidden() || val.isHidden()) {
1613 if (val.isRequired())
1617 if (val.isReallyHidden())
1618 O << " cl::ReallyHidden";
1623 if (!val.Help.empty())
1624 O << ", cl::desc(\"" << val.Help << "\")";
1629 // Emit the aliases (they should go after all the 'proper' options).
1630 for (std::vector<OptionDescription>::const_iterator
1631 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
1632 const OptionDescription& val = *B;
1634 O << val.GenTypeDeclaration() << ' '
1635 << val.GenVariableName()
1636 << "(\"" << val.Name << '\"';
1638 const OptionDescription& D = descs.FindOption(val.Help);
1639 O << ", cl::aliasopt(" << D.GenVariableName() << ")";
1641 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
1644 // Emit the sink option.
1646 O << (HasExterns ? "extern cl" : "cl")
1647 << "::list<std::string> " << SinkOptionName
1648 << (HasExterns ? ";\n" : "(cl::Sink);\n");
1653 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
1654 void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
1657 O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
1659 // Get the relevant field out of RecordKeeper
1660 const Record* LangMapRecord = Records.getDef("LanguageMap");
1662 // It is allowed for a plugin to have no language map.
1663 if (LangMapRecord) {
1665 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
1666 if (!LangsToSuffixesList)
1667 throw std::string("Error in the language map definition!");
1669 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
1670 const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
1672 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
1673 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
1675 for (unsigned i = 0; i < Suffixes->size(); ++i)
1676 O << Indent1 << "langMap[\""
1677 << InitPtrToString(Suffixes->getElement(i))
1678 << "\"] = \"" << Lang << "\";\n";
1685 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
1686 /// by EmitEdgeClass().
1687 void IncDecWeight (const Init* i, const char* IndentLevel,
1689 const DagInit& d = InitPtrToDag(i);
1690 const std::string& OpName = d.getOperator()->getAsString();
1692 if (OpName == "inc_weight") {
1693 O << IndentLevel << "ret += ";
1695 else if (OpName == "dec_weight") {
1696 O << IndentLevel << "ret -= ";
1698 else if (OpName == "error") {
1699 O << IndentLevel << "throw std::runtime_error(\"" <<
1700 (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0))
1707 throw "Unknown operator in edge properties list: " + OpName + '!' +
1708 "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
1710 if (d.getNumArgs() > 0)
1711 O << InitPtrToInt(d.getArg(0)) << ";\n";
1717 /// EmitEdgeClass - Emit a single Edge# class.
1718 void EmitEdgeClass (unsigned N, const std::string& Target,
1719 DagInit* Case, const OptionDescriptions& OptDescs,
1722 // Class constructor.
1723 O << "class Edge" << N << ": public Edge {\n"
1725 << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1728 // Function Weight().
1729 << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
1730 << Indent2 << "unsigned ret = 0;\n";
1732 // Handle the 'case' construct.
1733 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
1735 O << Indent2 << "return ret;\n"
1736 << Indent1 << "};\n\n};\n\n";
1739 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
1740 void EmitEdgeClasses (const RecordVector& EdgeVector,
1741 const OptionDescriptions& OptDescs,
1744 for (RecordVector::const_iterator B = EdgeVector.begin(),
1745 E = EdgeVector.end(); B != E; ++B) {
1746 const Record* Edge = *B;
1747 const std::string& NodeB = Edge->getValueAsString("b");
1748 DagInit* Weight = Edge->getValueAsDag("weight");
1750 if (!isDagEmpty(Weight))
1751 EmitEdgeClass(i, NodeB, Weight, OptDescs, O);
1756 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1758 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
1759 const ToolDescriptions& ToolDescs,
1762 O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
1764 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1765 E = ToolDescs.end(); B != E; ++B)
1766 O << Indent1 << "G.insertNode(new " << (*B)->Name << "());\n";
1773 for (RecordVector::const_iterator B = EdgeVector.begin(),
1774 E = EdgeVector.end(); B != E; ++B) {
1775 const Record* Edge = *B;
1776 const std::string& NodeA = Edge->getValueAsString("a");
1777 const std::string& NodeB = Edge->getValueAsString("b");
1778 DagInit* Weight = Edge->getValueAsDag("weight");
1780 O << Indent1 << "G.insertEdge(\"" << NodeA << "\", ";
1782 if (isDagEmpty(Weight))
1783 O << "new SimpleEdge(\"" << NodeB << "\")";
1785 O << "new Edge" << i << "()";
1794 /// ExtractHookNames - Extract the hook names from all instances of
1795 /// $CALL(HookName) in the provided command line string. Helper
1796 /// function used by FillInHookNames().
1797 class ExtractHookNames {
1798 llvm::StringMap<unsigned>& HookNames_;
1800 ExtractHookNames(llvm::StringMap<unsigned>& HookNames)
1801 : HookNames_(HookNames) {}
1803 void operator()(const Init* CmdLine) {
1805 TokenizeCmdline(InitPtrToString(CmdLine), cmds);
1806 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
1808 const std::string& cmd = *B;
1810 if (cmd == "$CALL") {
1811 unsigned NumArgs = 0;
1812 checkedIncrement(B, E, "Syntax error in $CALL invocation!");
1813 const std::string& HookName = *B;
1816 if (HookName.at(0) == ')')
1817 throw "$CALL invoked with no arguments!";
1819 while (++B != E && B->at(0) != ')') {
1823 StringMap<unsigned>::const_iterator H = HookNames_.find(HookName);
1825 if (H != HookNames_.end() && H->second != NumArgs)
1826 throw "Overloading of hooks is not allowed. Overloaded hook: "
1829 HookNames_[HookName] = NumArgs;
1836 /// FillInHookNames - Actually extract the hook names from all command
1837 /// line strings. Helper function used by EmitHookDeclarations().
1838 void FillInHookNames(const ToolDescriptions& ToolDescs,
1839 llvm::StringMap<unsigned>& HookNames)
1841 // For all command lines:
1842 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1843 E = ToolDescs.end(); B != E; ++B) {
1844 const ToolDescription& D = *(*B);
1847 if (dynamic_cast<StringInit*>(D.CmdLine))
1848 // This is a string.
1849 ExtractHookNames(HookNames).operator()(D.CmdLine);
1851 // This is a 'case' construct.
1852 WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames));
1856 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
1857 /// property records and emit hook function declaration for each
1858 /// instance of $CALL(HookName).
1859 void EmitHookDeclarations(const ToolDescriptions& ToolDescs, std::ostream& O) {
1860 llvm::StringMap<unsigned> HookNames;
1862 FillInHookNames(ToolDescs, HookNames);
1863 if (HookNames.empty())
1866 O << "namespace hooks {\n";
1867 for (StringMap<unsigned>::const_iterator B = HookNames.begin(),
1868 E = HookNames.end(); B != E; ++B) {
1869 O << Indent1 << "std::string " << B->first() << "(";
1871 for (unsigned i = 0, j = B->second; i < j; ++i) {
1872 O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
1880 /// EmitRegisterPlugin - Emit code to register this plugin.
1881 void EmitRegisterPlugin(int Priority, std::ostream& O) {
1882 O << "struct Plugin : public llvmc::BasePlugin {\n\n"
1883 << Indent1 << "int Priority() const { return " << Priority << "; }\n\n"
1884 << Indent1 << "void PopulateLanguageMap(LanguageMap& langMap) const\n"
1885 << Indent1 << "{ PopulateLanguageMapLocal(langMap); }\n\n"
1887 << "void PopulateCompilationGraph(CompilationGraph& graph) const\n"
1888 << Indent1 << "{ PopulateCompilationGraphLocal(graph); }\n"
1891 << "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
1894 /// EmitIncludes - Emit necessary #include directives and some
1895 /// additional declarations.
1896 void EmitIncludes(std::ostream& O) {
1897 O << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
1898 << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
1899 << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
1901 << "#include \"llvm/ADT/StringExtras.h\"\n"
1902 << "#include \"llvm/Support/CommandLine.h\"\n\n"
1904 << "#include <cstdlib>\n"
1905 << "#include <stdexcept>\n\n"
1907 << "using namespace llvm;\n"
1908 << "using namespace llvmc;\n\n"
1910 << "extern cl::opt<std::string> OutputFilename;\n\n"
1912 << "inline const char* checkCString(const char* s)\n"
1913 << "{ return s == NULL ? \"\" : s; }\n\n";
1917 /// PluginData - Holds all information about a plugin.
1919 OptionDescriptions OptDescs;
1922 ToolDescriptions ToolDescs;
1927 /// HasSink - Go through the list of tool descriptions and check if
1928 /// there are any with the 'sink' property set.
1929 bool HasSink(const ToolDescriptions& ToolDescs) {
1930 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1931 E = ToolDescs.end(); B != E; ++B)
1938 /// HasExterns - Go through the list of option descriptions and check
1939 /// if there are any external options.
1940 bool HasExterns(const OptionDescriptions& OptDescs) {
1941 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
1942 E = OptDescs.end(); B != E; ++B)
1943 if (B->second.isExtern())
1949 /// CollectPluginData - Collect tool and option properties,
1950 /// compilation graph edges and plugin priority from the parse tree.
1951 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
1952 // Collect option properties.
1953 const RecordVector& OptionLists =
1954 Records.getAllDerivedDefinitions("OptionList");
1955 CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
1958 // Collect tool properties.
1959 const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
1960 CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
1961 Data.HasSink = HasSink(Data.ToolDescs);
1962 Data.HasExterns = HasExterns(Data.OptDescs);
1964 // Collect compilation graph edges.
1965 const RecordVector& CompilationGraphs =
1966 Records.getAllDerivedDefinitions("CompilationGraph");
1967 FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
1970 // Calculate the priority of this plugin.
1971 const RecordVector& Priorities =
1972 Records.getAllDerivedDefinitions("PluginPriority");
1973 Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
1976 /// CheckPluginData - Perform some sanity checks on the collected data.
1977 void CheckPluginData(PluginData& Data) {
1978 // Filter out all tools not mentioned in the compilation graph.
1979 FilterNotInGraph(Data.Edges, Data.ToolDescs);
1981 // Typecheck the compilation graph.
1982 TypecheckGraph(Data.Edges, Data.ToolDescs);
1984 // Check that there are no options without side effects (specified
1985 // only in the OptionList).
1986 CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
1990 void EmitPluginCode(const PluginData& Data, std::ostream& O) {
1991 // Emit file header.
1994 // Emit global option registration code.
1995 EmitOptionDefintions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
1997 // Emit hook declarations.
1998 EmitHookDeclarations(Data.ToolDescs, O);
2000 O << "namespace {\n\n";
2002 // Emit PopulateLanguageMap() function
2003 // (a language map maps from file extensions to language names).
2004 EmitPopulateLanguageMap(Records, O);
2006 // Emit Tool classes.
2007 for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
2008 E = Data.ToolDescs.end(); B!=E; ++B)
2009 EmitToolClassDefinition(*(*B), Data.OptDescs, O);
2011 // Emit Edge# classes.
2012 EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
2014 // Emit PopulateCompilationGraph() function.
2015 EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
2017 // Emit code for plugin registration.
2018 EmitRegisterPlugin(Data.Priority, O);
2020 O << "} // End anonymous namespace.\n";
2025 // End of anonymous namespace
2028 /// run - The back-end entry point.
2029 void LLVMCConfigurationEmitter::run (std::ostream &O) {
2033 CollectPluginData(Records, Data);
2034 CheckPluginData(Data);
2036 EmitSourceFileHeader("LLVMC Configuration Library", O);
2037 EmitPluginCode(Data, O);
2039 } catch (std::exception& Error) {
2040 throw Error.what() + std::string(" - usually this means a syntax error.");