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 //===----------------------------------------------------------------------===//
122 /// Back-end specific code
125 /// OptionType - One of six different option types. See the
126 /// documentation for detailed description of differences.
127 /// Extern* options are those that are defined in some other plugin.
128 namespace OptionType {
129 enum OptionType { Alias, Switch, Parameter, ParameterList,
132 bool IsList (OptionType t) {
133 return (t == ParameterList || t == PrefixList);
136 bool IsSwitch (OptionType t) {
137 return (t == Switch);
140 bool IsParameter (OptionType t) {
141 return (t == Parameter || t == Prefix);
146 OptionType::OptionType stringToOptionType(const std::string& T) {
147 if (T == "alias_option")
148 return OptionType::Alias;
149 else if (T == "switch_option")
150 return OptionType::Switch;
151 else if (T == "parameter_option")
152 return OptionType::Parameter;
153 else if (T == "parameter_list_option")
154 return OptionType::ParameterList;
155 else if (T == "prefix_option")
156 return OptionType::Prefix;
157 else if (T == "prefix_list_option")
158 return OptionType::PrefixList;
160 throw "Unknown option type: " + T + '!';
163 namespace OptionDescriptionFlags {
164 enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
165 ReallyHidden = 0x4, Extern = 0x8 };
168 /// OptionDescription - Represents data contained in a single
169 /// OptionList entry.
170 struct OptionDescription {
171 OptionType::OptionType Type;
176 OptionDescription(OptionType::OptionType t = OptionType::Switch,
177 const std::string& n = "",
178 const std::string& h = DefaultHelpString)
179 : Type(t), Name(n), Flags(0x0), Help(h)
182 /// GenTypeDeclaration - Returns the C++ variable type of this
184 const char* GenTypeDeclaration() const;
186 /// GenVariableName - Returns the variable name used in the
187 /// generated C++ code.
188 std::string GenVariableName() const;
190 /// Merge - Merge two option descriptions.
191 void Merge (const OptionDescription& other);
193 // Misc convenient getters/setters.
195 bool isAlias() const;
197 bool isExtern() const;
200 bool isRequired() const;
203 bool isHidden() const;
206 bool isReallyHidden() const;
207 void setReallyHidden();
210 void OptionDescription::Merge (const OptionDescription& other)
212 if (other.Type != Type)
213 throw "Conflicting definitions for the option " + Name + "!";
215 if (Help == other.Help || Help == DefaultHelpString)
217 else if (other.Help != DefaultHelpString) {
218 llvm::cerr << "Warning: several different help strings"
219 " defined for option " + Name + "\n";
222 Flags |= other.Flags;
225 bool OptionDescription::isAlias() const {
226 return Type == OptionType::Alias;
229 bool OptionDescription::isExtern() const {
230 return Flags & OptionDescriptionFlags::Extern;
232 void OptionDescription::setExtern() {
233 Flags |= OptionDescriptionFlags::Extern;
236 bool OptionDescription::isRequired() const {
237 return Flags & OptionDescriptionFlags::Required;
239 void OptionDescription::setRequired() {
240 Flags |= OptionDescriptionFlags::Required;
243 bool OptionDescription::isHidden() const {
244 return Flags & OptionDescriptionFlags::Hidden;
246 void OptionDescription::setHidden() {
247 Flags |= OptionDescriptionFlags::Hidden;
250 bool OptionDescription::isReallyHidden() const {
251 return Flags & OptionDescriptionFlags::ReallyHidden;
253 void OptionDescription::setReallyHidden() {
254 Flags |= OptionDescriptionFlags::ReallyHidden;
257 const char* OptionDescription::GenTypeDeclaration() const {
259 case OptionType::Alias:
261 case OptionType::PrefixList:
262 case OptionType::ParameterList:
263 return "cl::list<std::string>";
264 case OptionType::Switch:
265 return "cl::opt<bool>";
266 case OptionType::Parameter:
267 case OptionType::Prefix:
269 return "cl::opt<std::string>";
273 std::string OptionDescription::GenVariableName() const {
274 const std::string& EscapedName = EscapeVariableName(Name);
276 case OptionType::Alias:
277 return "AutoGeneratedAlias_" + EscapedName;
278 case OptionType::PrefixList:
279 case OptionType::ParameterList:
280 return "AutoGeneratedList_" + EscapedName;
281 case OptionType::Switch:
282 return "AutoGeneratedSwitch_" + EscapedName;
283 case OptionType::Prefix:
284 case OptionType::Parameter:
286 return "AutoGeneratedParameter_" + EscapedName;
290 /// OptionDescriptions - An OptionDescription array plus some helper
292 class OptionDescriptions {
293 typedef StringMap<OptionDescription> container_type;
295 /// Descriptions - A list of OptionDescriptions.
296 container_type Descriptions;
299 /// FindOption - exception-throwing wrapper for find().
300 const OptionDescription& FindOption(const std::string& OptName) const;
302 /// insertDescription - Insert new OptionDescription into
303 /// OptionDescriptions list
304 void InsertDescription (const OptionDescription& o);
306 // Support for STL-style iteration
307 typedef container_type::const_iterator const_iterator;
308 const_iterator begin() const { return Descriptions.begin(); }
309 const_iterator end() const { return Descriptions.end(); }
312 const OptionDescription&
313 OptionDescriptions::FindOption(const std::string& OptName) const
315 const_iterator I = Descriptions.find(OptName);
316 if (I != Descriptions.end())
319 throw OptName + ": no such option!";
322 void OptionDescriptions::InsertDescription (const OptionDescription& o)
324 container_type::iterator I = Descriptions.find(o.Name);
325 if (I != Descriptions.end()) {
326 OptionDescription& D = I->second;
330 Descriptions[o.Name] = o;
334 /// HandlerTable - A base class for function objects implemented as
335 /// 'tables of handlers'.
339 // Implementation details.
342 typedef void (T::* Handler) (const DagInit*);
343 /// HandlerMap - A map from property names to property handlers
344 typedef StringMap<Handler> HandlerMap;
346 static HandlerMap Handlers_;
347 static bool staticMembersInitialized_;
352 HandlerTable(T* cp) : childPtr(cp)
355 /// operator() - Just forwards to the corresponding property
357 void operator() (Init* i) {
358 const DagInit& property = InitPtrToDag(i);
359 const std::string& property_name = property.getOperator()->getAsString();
360 typename HandlerMap::iterator method = Handlers_.find(property_name);
362 if (method != Handlers_.end()) {
363 Handler h = method->second;
364 (childPtr->*h)(&property);
367 throw "No handler found for property " + property_name + "!";
371 void AddHandler(const char* Property, Handler Handl) {
372 Handlers_[Property] = Handl;
376 template <class T> typename HandlerTable<T>::HandlerMap
377 HandlerTable<T>::Handlers_;
378 template <class T> bool HandlerTable<T>::staticMembersInitialized_ = false;
381 /// CollectOptionProperties - Function object for iterating over an
382 /// option property list.
383 class CollectOptionProperties : public HandlerTable<CollectOptionProperties> {
386 /// optDescs_ - OptionDescriptions table. This is where the
387 /// information is stored.
388 OptionDescription& optDesc_;
392 explicit CollectOptionProperties(OptionDescription& OD)
393 : HandlerTable<CollectOptionProperties>(this), optDesc_(OD)
395 if (!staticMembersInitialized_) {
396 AddHandler("extern", &CollectOptionProperties::onExtern);
397 AddHandler("help", &CollectOptionProperties::onHelp);
398 AddHandler("hidden", &CollectOptionProperties::onHidden);
399 AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
400 AddHandler("required", &CollectOptionProperties::onRequired);
402 staticMembersInitialized_ = true;
408 /// Option property handlers --
409 /// Methods that handle option properties such as (help) or (hidden).
411 void onExtern (const DagInit* d) {
412 checkNumberOfArguments(d, 0);
413 optDesc_.setExtern();
416 void onHelp (const DagInit* d) {
417 checkNumberOfArguments(d, 1);
418 optDesc_.Help = InitPtrToString(d->getArg(0));
421 void onHidden (const DagInit* d) {
422 checkNumberOfArguments(d, 0);
423 optDesc_.setHidden();
426 void onReallyHidden (const DagInit* d) {
427 checkNumberOfArguments(d, 0);
428 optDesc_.setReallyHidden();
431 void onRequired (const DagInit* d) {
432 checkNumberOfArguments(d, 0);
433 optDesc_.setRequired();
438 /// AddOption - A function object that is applied to every option
439 /// description. Used by CollectOptionDescriptions.
442 OptionDescriptions& OptDescs_;
445 explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
448 void operator()(const Init* i) {
449 const DagInit& d = InitPtrToDag(i);
450 checkNumberOfArguments(&d, 1);
452 const OptionType::OptionType Type =
453 stringToOptionType(d.getOperator()->getAsString());
454 const std::string& Name = InitPtrToString(d.getArg(0));
456 OptionDescription OD(Type, Name);
459 checkNumberOfArguments(&d, 2);
462 // Aliases store the aliased option name in the 'Help' field.
463 OD.Help = InitPtrToString(d.getArg(1));
465 else if (!OD.isExtern()) {
466 processOptionProperties(&d, OD);
468 OptDescs_.InsertDescription(OD);
472 /// processOptionProperties - Go through the list of option
473 /// properties and call a corresponding handler for each.
474 static void processOptionProperties (const DagInit* d, OptionDescription& o) {
475 checkNumberOfArguments(d, 2);
476 DagInit::const_arg_iterator B = d->arg_begin();
477 // Skip the first argument: it's always the option name.
479 std::for_each(B, d->arg_end(), CollectOptionProperties(o));
484 /// CollectOptionDescriptions - Collects option properties from all
486 void CollectOptionDescriptions (RecordVector::const_iterator B,
487 RecordVector::const_iterator E,
488 OptionDescriptions& OptDescs)
490 // For every OptionList:
492 RecordVector::value_type T = *B;
493 // Throws an exception if the value does not exist.
494 ListInit* PropList = T->getValueAsListInit("options");
496 // For every option description in this list:
497 // collect the information and
498 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
502 // Tool information record
504 namespace ToolFlags {
505 enum ToolFlags { Join = 0x1, Sink = 0x2 };
508 struct ToolDescription : public RefCountedBase<ToolDescription> {
512 StrVector InLanguage;
513 std::string OutLanguage;
514 std::string OutputSuffix;
517 // Various boolean properties
518 void setSink() { Flags |= ToolFlags::Sink; }
519 bool isSink() const { return Flags & ToolFlags::Sink; }
520 void setJoin() { Flags |= ToolFlags::Join; }
521 bool isJoin() const { return Flags & ToolFlags::Join; }
523 // Default ctor here is needed because StringMap can only store
524 // DefaultConstructible objects
525 ToolDescription() : CmdLine(0), Actions(0), Flags(0) {}
526 ToolDescription (const std::string& n)
527 : Name(n), CmdLine(0), Actions(0), Flags(0)
531 /// ToolDescriptions - A list of Tool information records.
532 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
535 /// CollectToolProperties - Function object for iterating over a list of
536 /// tool property records.
537 class CollectToolProperties : public HandlerTable<CollectToolProperties> {
540 /// toolDesc_ - Properties of the current Tool. This is where the
541 /// information is stored.
542 ToolDescription& toolDesc_;
546 explicit CollectToolProperties (ToolDescription& d)
547 : HandlerTable<CollectToolProperties>(this) , toolDesc_(d)
549 if (!staticMembersInitialized_) {
551 AddHandler("actions", &CollectToolProperties::onActions);
552 AddHandler("cmd_line", &CollectToolProperties::onCmdLine);
553 AddHandler("in_language", &CollectToolProperties::onInLanguage);
554 AddHandler("join", &CollectToolProperties::onJoin);
555 AddHandler("out_language", &CollectToolProperties::onOutLanguage);
556 AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
557 AddHandler("sink", &CollectToolProperties::onSink);
559 staticMembersInitialized_ = true;
565 /// Property handlers --
566 /// Functions that extract information about tool properties from
567 /// DAG representation.
569 void onActions (const DagInit* d) {
570 checkNumberOfArguments(d, 1);
571 Init* Case = d->getArg(0);
572 if (typeid(*Case) != typeid(DagInit) ||
573 static_cast<DagInit*>(Case)->getOperator()->getAsString() != "case")
575 std::string("The argument to (actions) should be a 'case' construct!");
576 toolDesc_.Actions = Case;
579 void onCmdLine (const DagInit* d) {
580 checkNumberOfArguments(d, 1);
581 toolDesc_.CmdLine = d->getArg(0);
584 void onInLanguage (const DagInit* d) {
585 checkNumberOfArguments(d, 1);
586 Init* arg = d->getArg(0);
588 // Find out the argument's type.
589 if (typeid(*arg) == typeid(StringInit)) {
591 toolDesc_.InLanguage.push_back(InitPtrToString(arg));
595 const ListInit& lst = InitPtrToList(arg);
596 StrVector& out = toolDesc_.InLanguage;
598 // Copy strings to the output vector.
599 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
601 out.push_back(InitPtrToString(*B));
604 // Remove duplicates.
605 std::sort(out.begin(), out.end());
606 StrVector::iterator newE = std::unique(out.begin(), out.end());
607 out.erase(newE, out.end());
611 void onJoin (const DagInit* d) {
612 checkNumberOfArguments(d, 0);
616 void onOutLanguage (const DagInit* d) {
617 checkNumberOfArguments(d, 1);
618 toolDesc_.OutLanguage = InitPtrToString(d->getArg(0));
621 void onOutputSuffix (const DagInit* d) {
622 checkNumberOfArguments(d, 1);
623 toolDesc_.OutputSuffix = InitPtrToString(d->getArg(0));
626 void onSink (const DagInit* d) {
627 checkNumberOfArguments(d, 0);
634 /// CollectToolDescriptions - Gather information about tool properties
635 /// from the parsed TableGen data (basically a wrapper for the
636 /// CollectToolProperties function object).
637 void CollectToolDescriptions (RecordVector::const_iterator B,
638 RecordVector::const_iterator E,
639 ToolDescriptions& ToolDescs)
641 // Iterate over a properties list of every Tool definition
643 const Record* T = *B;
644 // Throws an exception if the value does not exist.
645 ListInit* PropList = T->getValueAsListInit("properties");
647 IntrusiveRefCntPtr<ToolDescription>
648 ToolDesc(new ToolDescription(T->getName()));
650 std::for_each(PropList->begin(), PropList->end(),
651 CollectToolProperties(*ToolDesc));
652 ToolDescs.push_back(ToolDesc);
656 /// FillInEdgeVector - Merge all compilation graph definitions into
657 /// one single edge list.
658 void FillInEdgeVector(RecordVector::const_iterator B,
659 RecordVector::const_iterator E, RecordVector& Out) {
660 for (; B != E; ++B) {
661 const ListInit* edges = (*B)->getValueAsListInit("edges");
663 for (unsigned i = 0; i < edges->size(); ++i)
664 Out.push_back(edges->getElementAsRecord(i));
668 /// CalculatePriority - Calculate the priority of this plugin.
669 int CalculatePriority(RecordVector::const_iterator B,
670 RecordVector::const_iterator E) {
673 total += static_cast<int>((*B)->getValueAsInt("priority"));
678 /// NotInGraph - Helper function object for FilterNotInGraph.
681 const llvm::StringSet<>& ToolsInGraph_;
684 NotInGraph(const llvm::StringSet<>& ToolsInGraph)
685 : ToolsInGraph_(ToolsInGraph)
688 bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
689 return (ToolsInGraph_.count(x->Name) == 0);
693 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
694 /// mentioned in the compilation graph definition.
695 void FilterNotInGraph (const RecordVector& EdgeVector,
696 ToolDescriptions& ToolDescs) {
698 // List all tools mentioned in the graph.
699 llvm::StringSet<> ToolsInGraph;
701 for (RecordVector::const_iterator B = EdgeVector.begin(),
702 E = EdgeVector.end(); B != E; ++B) {
704 const Record* Edge = *B;
705 const std::string& NodeA = Edge->getValueAsString("a");
706 const std::string& NodeB = Edge->getValueAsString("b");
709 ToolsInGraph.insert(NodeA);
710 ToolsInGraph.insert(NodeB);
713 // Filter ToolPropertiesList.
714 ToolDescriptions::iterator new_end =
715 std::remove_if(ToolDescs.begin(), ToolDescs.end(),
716 NotInGraph(ToolsInGraph));
717 ToolDescs.erase(new_end, ToolDescs.end());
720 /// FillInToolToLang - Fills in two tables that map tool names to
721 /// (input, output) languages. Helper function used by TypecheckGraph().
722 void FillInToolToLang (const ToolDescriptions& ToolDescs,
723 StringMap<StringSet<> >& ToolToInLang,
724 StringMap<std::string>& ToolToOutLang) {
725 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
726 E = ToolDescs.end(); B != E; ++B) {
727 const ToolDescription& D = *(*B);
728 for (StrVector::const_iterator B = D.InLanguage.begin(),
729 E = D.InLanguage.end(); B != E; ++B)
730 ToolToInLang[D.Name].insert(*B);
731 ToolToOutLang[D.Name] = D.OutLanguage;
735 /// TypecheckGraph - Check that names for output and input languages
736 /// on all edges do match. This doesn't do much when the information
737 /// about the whole graph is not available (i.e. when compiling most
739 void TypecheckGraph (const RecordVector& EdgeVector,
740 const ToolDescriptions& ToolDescs) {
741 StringMap<StringSet<> > ToolToInLang;
742 StringMap<std::string> ToolToOutLang;
744 FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
745 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
746 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
748 for (RecordVector::const_iterator B = EdgeVector.begin(),
749 E = EdgeVector.end(); B != E; ++B) {
750 const Record* Edge = *B;
751 const std::string& NodeA = Edge->getValueAsString("a");
752 const std::string& NodeB = Edge->getValueAsString("b");
753 StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
754 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
756 if (NodeA != "root") {
757 if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
758 throw "Edge " + NodeA + "->" + NodeB
759 + ": output->input language mismatch";
763 throw std::string("Edges back to the root are not allowed!");
767 /// WalkCase - Walks the 'case' expression DAG and invokes
768 /// TestCallback on every test, and StatementCallback on every
769 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
771 // TODO: Re-implement EmitCaseConstructHandler on top of this function?
772 template <typename F1, typename F2>
773 void WalkCase(Init* Case, F1 TestCallback, F2 StatementCallback) {
774 const DagInit& d = InitPtrToDag(Case);
776 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
779 if (even && dynamic_cast<DagInit*>(arg)
780 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
781 WalkCase(arg, TestCallback, StatementCallback);
785 StatementCallback(arg);
790 /// ExtractOptionNames - A helper function object used by
791 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
792 class ExtractOptionNames {
793 llvm::StringSet<>& OptionNames_;
795 void processDag(const Init* Statement) {
796 const DagInit& Stmt = InitPtrToDag(Statement);
797 const std::string& ActionName = Stmt.getOperator()->getAsString();
798 if (ActionName == "forward" || ActionName == "forward_as" ||
799 ActionName == "unpack_values" || ActionName == "switch_on" ||
800 ActionName == "parameter_equals" || ActionName == "element_in_list" ||
801 ActionName == "not_empty" || ActionName == "empty") {
802 checkNumberOfArguments(&Stmt, 1);
803 const std::string& Name = InitPtrToString(Stmt.getArg(0));
804 OptionNames_.insert(Name);
806 else if (ActionName == "and" || ActionName == "or") {
807 for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
808 this->processDag(Stmt.getArg(i));
814 ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
817 void operator()(const Init* Statement) {
818 if (typeid(*Statement) == typeid(ListInit)) {
819 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
820 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
822 this->processDag(*B);
825 this->processDag(Statement);
830 /// CheckForSuperfluousOptions - Check that there are no side
831 /// effect-free options (specified only in the OptionList). Otherwise,
832 /// output a warning.
833 void CheckForSuperfluousOptions (const RecordVector& Edges,
834 const ToolDescriptions& ToolDescs,
835 const OptionDescriptions& OptDescs) {
836 llvm::StringSet<> nonSuperfluousOptions;
838 // Add all options mentioned in the ToolDesc.Actions to the set of
839 // non-superfluous options.
840 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
841 E = ToolDescs.end(); B != E; ++B) {
842 const ToolDescription& TD = *(*B);
843 ExtractOptionNames Callback(nonSuperfluousOptions);
845 WalkCase(TD.Actions, Callback, Callback);
848 // Add all options mentioned in the 'case' clauses of the
849 // OptionalEdges of the compilation graph to the set of
850 // non-superfluous options.
851 for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
853 const Record* Edge = *B;
854 DagInit* Weight = Edge->getValueAsDag("weight");
856 if (!isDagEmpty(Weight))
857 WalkCase(Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
860 // Check that all options in OptDescs belong to the set of
861 // non-superfluous options.
862 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
863 E = OptDescs.end(); B != E; ++B) {
864 const OptionDescription& Val = B->second;
865 if (!nonSuperfluousOptions.count(Val.Name)
866 && Val.Type != OptionType::Alias)
867 llvm::cerr << "Warning: option '-" << Val.Name << "' has no effect! "
868 "Probable cause: this option is specified only in the OptionList.\n";
872 /// EmitCaseTest1Arg - Helper function used by
873 /// EmitCaseConstructHandler.
874 bool EmitCaseTest1Arg(const std::string& TestName,
876 const OptionDescriptions& OptDescs,
878 checkNumberOfArguments(&d, 1);
879 const std::string& OptName = InitPtrToString(d.getArg(0));
881 if (TestName == "switch_on") {
882 const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
883 if (!OptionType::IsSwitch(OptDesc.Type))
884 throw OptName + ": incorrect option type - should be a switch!";
885 O << OptDesc.GenVariableName();
887 } else if (TestName == "input_languages_contain") {
888 O << "InLangs.count(\"" << OptName << "\") != 0";
890 } else if (TestName == "in_language") {
891 // This works only for single-argument Tool::GenerateAction. Join
892 // tools can process several files in different languages simultaneously.
894 // TODO: make this work with Edge::Weight (if possible).
895 O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
897 } else if (TestName == "not_empty" || TestName == "empty") {
898 const char* Test = (TestName == "empty") ? "" : "!";
900 if (OptName == "o") {
901 O << Test << "OutputFilename.empty()";
905 const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
906 if (OptionType::IsSwitch(OptDesc.Type))
908 + ": incorrect option type - should be a list or parameter!";
909 O << Test << OptDesc.GenVariableName() << ".empty()";
917 /// EmitCaseTest2Args - Helper function used by
918 /// EmitCaseConstructHandler.
919 bool EmitCaseTest2Args(const std::string& TestName,
921 const char* IndentLevel,
922 const OptionDescriptions& OptDescs,
924 checkNumberOfArguments(&d, 2);
925 const std::string& OptName = InitPtrToString(d.getArg(0));
926 const std::string& OptArg = InitPtrToString(d.getArg(1));
927 const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
929 if (TestName == "parameter_equals") {
930 if (!OptionType::IsParameter(OptDesc.Type))
931 throw OptName + ": incorrect option type - should be a parameter!";
932 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
935 else if (TestName == "element_in_list") {
936 if (!OptionType::IsList(OptDesc.Type))
937 throw OptName + ": incorrect option type - should be a list!";
938 const std::string& VarName = OptDesc.GenVariableName();
939 O << "std::find(" << VarName << ".begin(),\n"
940 << IndentLevel << Indent1 << VarName << ".end(), \""
941 << OptArg << "\") != " << VarName << ".end()";
948 // Forward declaration.
949 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
950 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
951 const OptionDescriptions& OptDescs,
954 /// EmitLogicalOperationTest - Helper function used by
955 /// EmitCaseConstructHandler.
956 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
957 const char* IndentLevel,
958 const OptionDescriptions& OptDescs,
961 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
962 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
963 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
964 if (j != NumArgs - 1)
965 O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
971 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
972 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
973 const OptionDescriptions& OptDescs,
975 const std::string& TestName = d.getOperator()->getAsString();
977 if (TestName == "and")
978 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
979 else if (TestName == "or")
980 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
981 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
983 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
986 throw TestName + ": unknown edge property!";
989 // Emit code that handles the 'case' construct.
990 // Takes a function object that should emit code for every case clause.
991 // Callback's type is
992 // void F(Init* Statement, const char* IndentLevel, std::ostream& O).
993 template <typename F>
994 void EmitCaseConstructHandler(const Init* Dag, const char* IndentLevel,
995 F Callback, bool EmitElseIf,
996 const OptionDescriptions& OptDescs,
998 const DagInit* d = &InitPtrToDag(Dag);
999 if (d->getOperator()->getAsString() != "case")
1000 throw std::string("EmitCaseConstructHandler should be invoked"
1001 " only on 'case' expressions!");
1003 unsigned numArgs = d->getNumArgs();
1004 if (d->getNumArgs() < 2)
1005 throw "There should be at least one clause in the 'case' expression:\n"
1008 for (unsigned i = 0; i != numArgs; ++i) {
1009 const DagInit& Test = InitPtrToDag(d->getArg(i));
1012 if (Test.getOperator()->getAsString() == "default") {
1014 throw std::string("The 'default' clause should be the last in the"
1015 "'case' construct!");
1016 O << IndentLevel << "else {\n";
1019 O << IndentLevel << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
1020 EmitCaseTest(Test, IndentLevel, OptDescs, O);
1024 // Emit the corresponding statement.
1027 throw "Case construct handler: no corresponding action "
1028 "found for the test " + Test.getAsString() + '!';
1030 Init* arg = d->getArg(i);
1031 const DagInit* nd = dynamic_cast<DagInit*>(arg);
1032 if (nd && (nd->getOperator()->getAsString() == "case")) {
1033 // Handle the nested 'case'.
1034 EmitCaseConstructHandler(nd, (std::string(IndentLevel) + Indent1).c_str(),
1035 Callback, EmitElseIf, OptDescs, O);
1038 Callback(arg, (std::string(IndentLevel) + Indent1).c_str(), O);
1040 O << IndentLevel << "}\n";
1044 /// SubstituteSpecialCommands - Perform string substitution for $CALL
1045 /// and $ENV. Helper function used by EmitCmdLineVecFill().
1046 std::string SubstituteSpecialCommands(const std::string& cmd) {
1047 size_t cparen = cmd.find(")");
1050 if (cmd.find("$CALL(") == 0) {
1051 if (cmd.size() == 6)
1052 throw std::string("$CALL invocation: empty argument list!");
1055 ret += std::string(cmd.begin() + 6, cmd.begin() + cparen);
1058 else if (cmd.find("$ENV(") == 0) {
1059 if (cmd.size() == 5)
1060 throw std::string("$ENV invocation: empty argument list!");
1062 ret += "checkCString(std::getenv(\"";
1063 ret += std::string(cmd.begin() + 5, cmd.begin() + cparen);
1067 throw "Unknown special command: " + cmd;
1070 if (cmd.begin() + cparen + 1 != cmd.end()) {
1071 ret += " + std::string(\"";
1072 ret += (cmd.c_str() + cparen + 1);
1079 /// EmitCmdLineVecFill - Emit code that fills in the command line
1080 /// vector. Helper function used by EmitGenerateActionMethod().
1081 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1082 bool IsJoin, const char* IndentLevel,
1085 SplitString(InitPtrToString(CmdLine), StrVec);
1087 throw "Tool " + ToolName + " has empty command line!";
1089 StrVector::const_iterator I = StrVec.begin();
1091 for (StrVector::const_iterator E = StrVec.end(); I != E; ++I) {
1092 const std::string& cmd = *I;
1094 if (cmd.at(0) == '$') {
1095 if (cmd == "$INFILE") {
1097 O << "for (PathVector::const_iterator B = inFiles.begin()"
1098 << ", E = inFiles.end();\n"
1099 << IndentLevel << "B != E; ++B)\n"
1100 << IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
1102 O << "vec.push_back(inFile.toString());\n";
1104 else if (cmd == "$OUTFILE") {
1105 O << "vec.push_back(out_file);\n";
1108 O << "vec.push_back(" << SubstituteSpecialCommands(cmd);
1113 O << "vec.push_back(\"" << cmd << "\");\n";
1116 O << IndentLevel << "cmd = "
1117 << ((StrVec[0][0] == '$') ? SubstituteSpecialCommands(StrVec[0])
1118 : "\"" + StrVec[0] + "\"")
1122 /// EmitCmdLineVecFillCallback - A function object wrapper around
1123 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1124 /// argument to EmitCaseConstructHandler().
1125 class EmitCmdLineVecFillCallback {
1127 const std::string& ToolName;
1129 EmitCmdLineVecFillCallback(bool J, const std::string& TN)
1130 : IsJoin(J), ToolName(TN) {}
1132 void operator()(const Init* Statement, const char* IndentLevel,
1133 std::ostream& O) const
1135 EmitCmdLineVecFill(Statement, ToolName, IsJoin,
1140 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1141 /// implement EmitActionHandler. Emits code for
1142 /// handling the (forward) and (forward_as) option properties.
1143 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1145 const std::string& NewName,
1147 const std::string& Name = NewName.empty()
1152 case OptionType::Switch:
1153 O << Indent << "vec.push_back(\"" << Name << "\");\n";
1155 case OptionType::Parameter:
1156 O << Indent << "vec.push_back(\"" << Name << "\");\n";
1157 O << Indent << "vec.push_back(" << D.GenVariableName() << ");\n";
1159 case OptionType::Prefix:
1160 O << Indent << "vec.push_back(\"" << Name << "\" + "
1161 << D.GenVariableName() << ");\n";
1163 case OptionType::PrefixList:
1164 O << Indent << "for (" << D.GenTypeDeclaration()
1165 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1166 << Indent << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
1167 << Indent << Indent1 << "vec.push_back(\"" << Name << "\" + "
1170 case OptionType::ParameterList:
1171 O << Indent << "for (" << D.GenTypeDeclaration()
1172 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1173 << Indent << "E = " << D.GenVariableName()
1174 << ".end() ; B != E; ++B) {\n"
1175 << Indent << Indent1 << "vec.push_back(\"" << Name << "\");\n"
1176 << Indent << Indent1 << "vec.push_back(*B);\n"
1179 case OptionType::Alias:
1181 throw std::string("Aliases are not allowed in tool option descriptions!");
1185 /// EmitActionHandler - Emit code that handles actions. Used by
1186 /// EmitGenerateActionMethod() as an argument to
1187 /// EmitCaseConstructHandler().
1188 class EmitActionHandler {
1189 const OptionDescriptions& OptDescs;
1191 void processActionDag(const Init* Statement, const char* IndentLevel,
1192 std::ostream& O) const
1194 const DagInit& Dag = InitPtrToDag(Statement);
1195 const std::string& ActionName = Dag.getOperator()->getAsString();
1197 if (ActionName == "append_cmd") {
1198 checkNumberOfArguments(&Dag, 1);
1199 const std::string& Cmd = InitPtrToString(Dag.getArg(0));
1200 O << IndentLevel << "vec.push_back(\"" << Cmd << "\");\n";
1202 else if (ActionName == "error") {
1203 O << IndentLevel << "throw std::runtime_error(\"" <<
1204 (Dag.getNumArgs() >= 1 ? InitPtrToString(Dag.getArg(0))
1208 else if (ActionName == "forward") {
1209 checkNumberOfArguments(&Dag, 1);
1210 const std::string& Name = InitPtrToString(Dag.getArg(0));
1211 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1212 IndentLevel, "", O);
1214 else if (ActionName == "forward_as") {
1215 checkNumberOfArguments(&Dag, 2);
1216 const std::string& Name = InitPtrToString(Dag.getArg(0));
1217 const std::string& NewName = InitPtrToString(Dag.getArg(0));
1218 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1219 IndentLevel, NewName, O);
1221 else if (ActionName == "output_suffix") {
1222 checkNumberOfArguments(&Dag, 1);
1223 const std::string& OutSuf = InitPtrToString(Dag.getArg(0));
1224 O << IndentLevel << "output_suffix = \"" << OutSuf << "\";\n";
1226 else if (ActionName == "stop_compilation") {
1227 O << IndentLevel << "stop_compilation = true;\n";
1229 else if (ActionName == "unpack_values") {
1230 checkNumberOfArguments(&Dag, 1);
1231 const std::string& Name = InitPtrToString(Dag.getArg(0));
1232 const OptionDescription& D = OptDescs.FindOption(Name);
1234 if (OptionType::IsList(D.Type)) {
1235 O << IndentLevel << "for (" << D.GenTypeDeclaration()
1236 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1237 << IndentLevel << "E = " << D.GenVariableName()
1238 << ".end(); B != E; ++B)\n"
1239 << IndentLevel << Indent1 << "llvm::SplitString(*B, vec, \",\");\n";
1241 else if (OptionType::IsParameter(D.Type)){
1242 O << Indent3 << "llvm::SplitString("
1243 << D.GenVariableName() << ", vec, \",\");\n";
1246 throw "Option '" + D.Name +
1247 "': switches can't have the 'unpack_values' property!";
1251 throw "Unknown action name: " + ActionName + "!";
1255 EmitActionHandler(const OptionDescriptions& OD)
1258 void operator()(const Init* Statement, const char* IndentLevel,
1259 std::ostream& O) const
1261 if (typeid(*Statement) == typeid(ListInit)) {
1262 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1263 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1265 this->processActionDag(*B, IndentLevel, O);
1268 this->processActionDag(Statement, IndentLevel, O);
1273 // EmitGenerateActionMethod - Emit one of two versions of the
1274 // Tool::GenerateAction() method.
1275 void EmitGenerateActionMethod (const ToolDescription& D,
1276 const OptionDescriptions& OptDescs,
1277 bool IsJoin, std::ostream& O) {
1279 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
1281 O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
1283 O << Indent2 << "bool HasChildren,\n"
1284 << Indent2 << "const llvm::sys::Path& TempDir,\n"
1285 << Indent2 << "const InputLanguagesSet& InLangs,\n"
1286 << Indent2 << "const LanguageMap& LangMap) const\n"
1288 << Indent2 << "std::string cmd;\n"
1289 << Indent2 << "std::vector<std::string> vec;\n"
1290 << Indent2 << "bool stop_compilation = !HasChildren;\n"
1291 << Indent2 << "const char* output_suffix = \"" << D.OutputSuffix << "\";\n"
1292 << Indent2 << "std::string out_file;\n\n";
1294 // For every understood option, emit handling code.
1296 EmitCaseConstructHandler(D.Actions, Indent2, EmitActionHandler(OptDescs),
1297 false, OptDescs, O);
1299 O << '\n' << Indent2
1300 << "out_file = OutFilename(" << (IsJoin ? "sys::Path(),\n" : "inFile,\n")
1301 << Indent3 << "TempDir, stop_compilation, output_suffix).toString();\n\n";
1303 // cmd_line is either a string or a 'case' construct.
1305 throw "Tool " + D.Name + " has no cmd_line property!";
1306 else if (typeid(*D.CmdLine) == typeid(StringInit))
1307 EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
1309 EmitCaseConstructHandler(D.CmdLine, Indent2,
1310 EmitCmdLineVecFillCallback(IsJoin, D.Name),
1313 // Handle the Sink property.
1315 O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
1316 << Indent3 << "vec.insert(vec.end(), "
1317 << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
1318 << Indent2 << "}\n";
1321 O << Indent2 << "return Action(cmd, vec, stop_compilation, out_file);\n"
1322 << Indent1 << "}\n\n";
1325 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1326 /// a given Tool class.
1327 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
1328 const OptionDescriptions& OptDescs,
1330 if (!ToolDesc.isJoin())
1331 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
1332 << Indent2 << "bool HasChildren,\n"
1333 << Indent2 << "const llvm::sys::Path& TempDir,\n"
1334 << Indent2 << "const InputLanguagesSet& InLangs,\n"
1335 << Indent2 << "const LanguageMap& LangMap) const\n"
1337 << Indent2 << "throw std::runtime_error(\"" << ToolDesc.Name
1338 << " is not a Join tool!\");\n"
1339 << Indent1 << "}\n\n";
1341 EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
1343 EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
1346 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1347 /// methods for a given Tool class.
1348 void EmitInOutLanguageMethods (const ToolDescription& D, std::ostream& O) {
1349 O << Indent1 << "const char** InputLanguages() const {\n"
1350 << Indent2 << "return InputLanguages_;\n"
1351 << Indent1 << "}\n\n";
1353 if (D.OutLanguage.empty())
1354 throw "Tool " + D.Name + " has no 'out_language' property!";
1356 O << Indent1 << "const char* OutputLanguage() const {\n"
1357 << Indent2 << "return \"" << D.OutLanguage << "\";\n"
1358 << Indent1 << "}\n\n";
1361 /// EmitNameMethod - Emit the Name() method for a given Tool class.
1362 void EmitNameMethod (const ToolDescription& D, std::ostream& O) {
1363 O << Indent1 << "const char* Name() const {\n"
1364 << Indent2 << "return \"" << D.Name << "\";\n"
1365 << Indent1 << "}\n\n";
1368 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1370 void EmitIsJoinMethod (const ToolDescription& D, std::ostream& O) {
1371 O << Indent1 << "bool IsJoin() const {\n";
1373 O << Indent2 << "return true;\n";
1375 O << Indent2 << "return false;\n";
1376 O << Indent1 << "}\n\n";
1379 /// EmitStaticMemberDefinitions - Emit static member definitions for a
1380 /// given Tool class.
1381 void EmitStaticMemberDefinitions(const ToolDescription& D, std::ostream& O) {
1382 if (D.InLanguage.empty())
1383 throw "Tool " + D.Name + " has no 'in_language' property!";
1385 O << "const char* " << D.Name << "::InputLanguages_[] = {";
1386 for (StrVector::const_iterator B = D.InLanguage.begin(),
1387 E = D.InLanguage.end(); B != E; ++B)
1388 O << '\"' << *B << "\", ";
1392 /// EmitToolClassDefinition - Emit a Tool class definition.
1393 void EmitToolClassDefinition (const ToolDescription& D,
1394 const OptionDescriptions& OptDescs,
1396 if (D.Name == "root")
1400 O << "class " << D.Name << " : public ";
1406 O << "{\nprivate:\n"
1407 << Indent1 << "static const char* InputLanguages_[];\n\n";
1410 EmitNameMethod(D, O);
1411 EmitInOutLanguageMethods(D, O);
1412 EmitIsJoinMethod(D, O);
1413 EmitGenerateActionMethods(D, OptDescs, O);
1415 // Close class definition
1418 EmitStaticMemberDefinitions(D, O);
1422 /// EmitOptionDefintions - Iterate over a list of option descriptions
1423 /// and emit registration code.
1424 void EmitOptionDefintions (const OptionDescriptions& descs,
1425 bool HasSink, bool HasExterns,
1428 std::vector<OptionDescription> Aliases;
1430 // Emit static cl::Option variables.
1431 for (OptionDescriptions::const_iterator B = descs.begin(),
1432 E = descs.end(); B!=E; ++B) {
1433 const OptionDescription& val = B->second;
1435 if (val.Type == OptionType::Alias) {
1436 Aliases.push_back(val);
1443 O << val.GenTypeDeclaration() << ' '
1444 << val.GenVariableName();
1446 if (val.isExtern()) {
1451 O << "(\"" << val.Name << '\"';
1453 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1454 O << ", cl::Prefix";
1456 if (val.isRequired()) {
1458 case OptionType::PrefixList:
1459 case OptionType::ParameterList:
1460 O << ", cl::OneOrMore";
1463 O << ", cl::Required";
1467 if (val.isReallyHidden() || val.isHidden()) {
1468 if (val.isRequired())
1472 if (val.isReallyHidden())
1473 O << " cl::ReallyHidden";
1478 if (!val.Help.empty())
1479 O << ", cl::desc(\"" << val.Help << "\")";
1484 // Emit the aliases (they should go after all the 'proper' options).
1485 for (std::vector<OptionDescription>::const_iterator
1486 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
1487 const OptionDescription& val = *B;
1489 O << val.GenTypeDeclaration() << ' '
1490 << val.GenVariableName()
1491 << "(\"" << val.Name << '\"';
1493 const OptionDescription& D = descs.FindOption(val.Help);
1494 O << ", cl::aliasopt(" << D.GenVariableName() << ")";
1496 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
1499 // Emit the sink option.
1501 O << (HasExterns ? "extern cl" : "cl")
1502 << "::list<std::string> " << SinkOptionName
1503 << (HasExterns ? ";\n" : "(cl::Sink);\n");
1508 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
1509 void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
1512 O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
1514 // Get the relevant field out of RecordKeeper
1515 const Record* LangMapRecord = Records.getDef("LanguageMap");
1517 // It is allowed for a plugin to have no language map.
1518 if (LangMapRecord) {
1520 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
1521 if (!LangsToSuffixesList)
1522 throw std::string("Error in the language map definition!");
1524 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
1525 const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
1527 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
1528 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
1530 for (unsigned i = 0; i < Suffixes->size(); ++i)
1531 O << Indent1 << "langMap[\""
1532 << InitPtrToString(Suffixes->getElement(i))
1533 << "\"] = \"" << Lang << "\";\n";
1540 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
1541 /// by EmitEdgeClass().
1542 void IncDecWeight (const Init* i, const char* IndentLevel,
1544 const DagInit& d = InitPtrToDag(i);
1545 const std::string& OpName = d.getOperator()->getAsString();
1547 if (OpName == "inc_weight") {
1548 O << IndentLevel << "ret += ";
1550 else if (OpName == "dec_weight") {
1551 O << IndentLevel << "ret -= ";
1553 else if (OpName == "error") {
1554 O << IndentLevel << "throw std::runtime_error(\"" <<
1555 (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0))
1562 throw "Unknown operator in edge properties list: " + OpName + '!' +
1563 "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
1565 if (d.getNumArgs() > 0)
1566 O << InitPtrToInt(d.getArg(0)) << ";\n";
1572 /// EmitEdgeClass - Emit a single Edge# class.
1573 void EmitEdgeClass (unsigned N, const std::string& Target,
1574 DagInit* Case, const OptionDescriptions& OptDescs,
1577 // Class constructor.
1578 O << "class Edge" << N << ": public Edge {\n"
1580 << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1583 // Function Weight().
1584 << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
1585 << Indent2 << "unsigned ret = 0;\n";
1587 // Handle the 'case' construct.
1588 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
1590 O << Indent2 << "return ret;\n"
1591 << Indent1 << "};\n\n};\n\n";
1594 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
1595 void EmitEdgeClasses (const RecordVector& EdgeVector,
1596 const OptionDescriptions& OptDescs,
1599 for (RecordVector::const_iterator B = EdgeVector.begin(),
1600 E = EdgeVector.end(); B != E; ++B) {
1601 const Record* Edge = *B;
1602 const std::string& NodeB = Edge->getValueAsString("b");
1603 DagInit* Weight = Edge->getValueAsDag("weight");
1605 if (!isDagEmpty(Weight))
1606 EmitEdgeClass(i, NodeB, Weight, OptDescs, O);
1611 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1613 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
1614 const ToolDescriptions& ToolDescs,
1617 O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
1619 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1620 E = ToolDescs.end(); B != E; ++B)
1621 O << Indent1 << "G.insertNode(new " << (*B)->Name << "());\n";
1628 for (RecordVector::const_iterator B = EdgeVector.begin(),
1629 E = EdgeVector.end(); B != E; ++B) {
1630 const Record* Edge = *B;
1631 const std::string& NodeA = Edge->getValueAsString("a");
1632 const std::string& NodeB = Edge->getValueAsString("b");
1633 DagInit* Weight = Edge->getValueAsDag("weight");
1635 O << Indent1 << "G.insertEdge(\"" << NodeA << "\", ";
1637 if (isDagEmpty(Weight))
1638 O << "new SimpleEdge(\"" << NodeB << "\")";
1640 O << "new Edge" << i << "()";
1649 /// ExtractHookNames - Extract the hook names from all instances of
1650 /// $CALL(HookName) in the provided command line string. Helper
1651 /// function used by FillInHookNames().
1652 class ExtractHookNames {
1653 llvm::StringSet<>& HookNames_;
1655 ExtractHookNames(llvm::StringSet<>& HookNames)
1656 : HookNames_(HookNames_) {}
1658 void operator()(const Init* CmdLine) {
1660 llvm::SplitString(InitPtrToString(CmdLine), cmds);
1661 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
1663 const std::string& cmd = *B;
1664 if (cmd.find("$CALL(") == 0) {
1665 if (cmd.size() == 6)
1666 throw std::string("$CALL invocation: empty argument list!");
1667 HookNames_.insert(std::string(cmd.begin() + 6,
1668 cmd.begin() + cmd.find(")")));
1674 /// FillInHookNames - Actually extract the hook names from all command
1675 /// line strings. Helper function used by EmitHookDeclarations().
1676 void FillInHookNames(const ToolDescriptions& ToolDescs,
1677 llvm::StringSet<>& HookNames)
1679 // For all command lines:
1680 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1681 E = ToolDescs.end(); B != E; ++B) {
1682 const ToolDescription& D = *(*B);
1685 if (dynamic_cast<StringInit*>(D.CmdLine))
1686 // This is a string.
1687 ExtractHookNames(HookNames).operator()(D.CmdLine);
1689 // This is a 'case' construct.
1690 WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames));
1694 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
1695 /// property records and emit hook function declaration for each
1696 /// instance of $CALL(HookName).
1697 void EmitHookDeclarations(const ToolDescriptions& ToolDescs, std::ostream& O) {
1698 llvm::StringSet<> HookNames;
1699 FillInHookNames(ToolDescs, HookNames);
1700 if (HookNames.empty())
1703 O << "namespace hooks {\n";
1704 for (StringSet<>::const_iterator B = HookNames.begin(), E = HookNames.end();
1706 O << Indent1 << "std::string " << B->first() << "();\n";
1711 /// EmitRegisterPlugin - Emit code to register this plugin.
1712 void EmitRegisterPlugin(int Priority, std::ostream& O) {
1713 O << "struct Plugin : public llvmc::BasePlugin {\n\n"
1714 << Indent1 << "int Priority() const { return " << Priority << "; }\n\n"
1715 << Indent1 << "void PopulateLanguageMap(LanguageMap& langMap) const\n"
1716 << Indent1 << "{ PopulateLanguageMapLocal(langMap); }\n\n"
1718 << "void PopulateCompilationGraph(CompilationGraph& graph) const\n"
1719 << Indent1 << "{ PopulateCompilationGraphLocal(graph); }\n"
1722 << "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
1725 /// EmitIncludes - Emit necessary #include directives and some
1726 /// additional declarations.
1727 void EmitIncludes(std::ostream& O) {
1728 O << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
1729 << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
1730 << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
1732 << "#include \"llvm/ADT/StringExtras.h\"\n"
1733 << "#include \"llvm/Support/CommandLine.h\"\n\n"
1735 << "#include <cstdlib>\n"
1736 << "#include <stdexcept>\n\n"
1738 << "using namespace llvm;\n"
1739 << "using namespace llvmc;\n\n"
1741 << "extern cl::opt<std::string> OutputFilename;\n\n"
1743 << "inline const char* checkCString(const char* s)\n"
1744 << "{ return s == NULL ? \"\" : s; }\n\n";
1748 /// PluginData - Holds all information about a plugin.
1750 OptionDescriptions OptDescs;
1753 ToolDescriptions ToolDescs;
1758 /// HasSink - Go through the list of tool descriptions and check if
1759 /// there are any with the 'sink' property set.
1760 bool HasSink(const ToolDescriptions& ToolDescs) {
1761 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1762 E = ToolDescs.end(); B != E; ++B)
1769 /// HasExterns - Go through the list of option descriptions and check
1770 /// if there are any external options.
1771 bool HasExterns(const OptionDescriptions& OptDescs) {
1772 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
1773 E = OptDescs.end(); B != E; ++B)
1774 if (B->second.isExtern())
1780 /// CollectPluginData - Collect tool and option properties,
1781 /// compilation graph edges and plugin priority from the parse tree.
1782 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
1783 // Collect option properties.
1784 const RecordVector& OptionLists =
1785 Records.getAllDerivedDefinitions("OptionList");
1786 CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
1789 // Collect tool properties.
1790 const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
1791 CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
1792 Data.HasSink = HasSink(Data.ToolDescs);
1793 Data.HasExterns = HasExterns(Data.OptDescs);
1795 // Collect compilation graph edges.
1796 const RecordVector& CompilationGraphs =
1797 Records.getAllDerivedDefinitions("CompilationGraph");
1798 FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
1801 // Calculate the priority of this plugin.
1802 const RecordVector& Priorities =
1803 Records.getAllDerivedDefinitions("PluginPriority");
1804 Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
1807 /// CheckPluginData - Perform some sanity checks on the collected data.
1808 void CheckPluginData(PluginData& Data) {
1809 // Filter out all tools not mentioned in the compilation graph.
1810 FilterNotInGraph(Data.Edges, Data.ToolDescs);
1812 // Typecheck the compilation graph.
1813 TypecheckGraph(Data.Edges, Data.ToolDescs);
1815 // Check that there are no options without side effects (specified
1816 // only in the OptionList).
1817 CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
1821 void EmitPluginCode(const PluginData& Data, std::ostream& O) {
1822 // Emit file header.
1825 // Emit global option registration code.
1826 EmitOptionDefintions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
1828 // Emit hook declarations.
1829 EmitHookDeclarations(Data.ToolDescs, O);
1831 O << "namespace {\n\n";
1833 // Emit PopulateLanguageMap() function
1834 // (a language map maps from file extensions to language names).
1835 EmitPopulateLanguageMap(Records, O);
1837 // Emit Tool classes.
1838 for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
1839 E = Data.ToolDescs.end(); B!=E; ++B)
1840 EmitToolClassDefinition(*(*B), Data.OptDescs, O);
1842 // Emit Edge# classes.
1843 EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
1845 // Emit PopulateCompilationGraph() function.
1846 EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
1848 // Emit code for plugin registration.
1849 EmitRegisterPlugin(Data.Priority, O);
1851 O << "} // End anonymous namespace.\n";
1856 // End of anonymous namespace
1859 /// run - The back-end entry point.
1860 void LLVMCConfigurationEmitter::run (std::ostream &O) {
1864 CollectPluginData(Records, Data);
1865 CheckPluginData(Data);
1867 EmitSourceFileHeader("LLVMC Configuration Library", O);
1868 EmitPluginCode(Data, O);
1870 } catch (std::exception& Error) {
1871 throw Error.what() + std::string(" - usually this means a syntax error.");