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/StringMap.h"
19 #include "llvm/ADT/StringSet.h"
31 //===----------------------------------------------------------------------===//
34 typedef std::vector<Record*> RecordVector;
35 typedef std::vector<std::string> StrVector;
37 //===----------------------------------------------------------------------===//
41 const unsigned TabWidth = 4;
42 const unsigned Indent1 = TabWidth*1;
43 const unsigned Indent2 = TabWidth*2;
44 const unsigned Indent3 = TabWidth*3;
46 // Default help string.
47 const char * const DefaultHelpString = "NO HELP MESSAGE PROVIDED";
49 // Name for the "sink" option.
50 const char * const SinkOptionName = "AutoGeneratedSinkOption";
52 //===----------------------------------------------------------------------===//
55 /// Id - An 'identity' function object.
58 void operator()(const T0&) const {
60 template<typename T0, typename T1>
61 void operator()(const T0&, const T1&) const {
63 template<typename T0, typename T1, typename T2>
64 void operator()(const T0&, const T1&, const T2&) const {
68 int InitPtrToInt(const Init* ptr) {
69 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
70 return val.getValue();
73 const std::string& InitPtrToString(const Init* ptr) {
74 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
75 return val.getValue();
78 const ListInit& InitPtrToList(const Init* ptr) {
79 const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
83 const DagInit& InitPtrToDag(const Init* ptr) {
84 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
88 const std::string GetOperatorName(const DagInit& D) {
89 return D.getOperator()->getAsString();
92 // checkNumberOfArguments - Ensure that the number of args in d is
93 // greater than or equal to min_arguments, otherwise throw an exception.
94 void checkNumberOfArguments (const DagInit& d, unsigned minArgs) {
95 if (d.getNumArgs() < minArgs)
96 throw GetOperatorName(d) + ": too few arguments!";
99 // isDagEmpty - is this DAG marked with an empty marker?
100 bool isDagEmpty (const DagInit& d) {
101 return GetOperatorName(d) == "empty_dag_marker";
104 // EscapeVariableName - Escape commas and other symbols not allowed
105 // in the C++ variable names. Makes it possible to use options named
106 // like "Wa," (useful for prefix options).
107 std::string EscapeVariableName(const std::string& Var) {
109 for (unsigned i = 0; i != Var.size(); ++i) {
110 char cur_char = Var[i];
111 if (cur_char == ',') {
114 else if (cur_char == '+') {
117 else if (cur_char == '-') {
121 ret.push_back(cur_char);
127 /// oneOf - Does the input string contain this character?
128 bool oneOf(const char* lst, char c) {
136 template <class I, class S>
137 void checkedIncrement(I& P, I E, S ErrorString) {
143 // apply is needed because C++'s syntax doesn't let us construct a function
144 // object and call it in the same statement.
145 template<typename F, typename T0>
146 void apply(F Fun, T0& Arg0) {
150 template<typename F, typename T0, typename T1>
151 void apply(F Fun, T0& Arg0, T1& Arg1) {
152 return Fun(Arg0, Arg1);
155 //===----------------------------------------------------------------------===//
156 /// Back-end specific code
159 /// OptionType - One of six different option types. See the
160 /// documentation for detailed description of differences.
161 namespace OptionType {
163 enum OptionType { Alias, Switch, Parameter, ParameterList,
166 bool IsAlias(OptionType t) {
170 bool IsList (OptionType t) {
171 return (t == ParameterList || t == PrefixList);
174 bool IsSwitch (OptionType t) {
175 return (t == Switch);
178 bool IsParameter (OptionType t) {
179 return (t == Parameter || t == Prefix);
184 OptionType::OptionType stringToOptionType(const std::string& T) {
185 if (T == "alias_option")
186 return OptionType::Alias;
187 else if (T == "switch_option")
188 return OptionType::Switch;
189 else if (T == "parameter_option")
190 return OptionType::Parameter;
191 else if (T == "parameter_list_option")
192 return OptionType::ParameterList;
193 else if (T == "prefix_option")
194 return OptionType::Prefix;
195 else if (T == "prefix_list_option")
196 return OptionType::PrefixList;
198 throw "Unknown option type: " + T + '!';
201 namespace OptionDescriptionFlags {
202 enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
203 ReallyHidden = 0x4, Extern = 0x8,
204 OneOrMore = 0x10, Optional = 0x20,
205 CommaSeparated = 0x40 };
208 /// OptionDescription - Represents data contained in a single
209 /// OptionList entry.
210 struct OptionDescription {
211 OptionType::OptionType Type;
218 OptionDescription(OptionType::OptionType t = OptionType::Switch,
219 const std::string& n = "",
220 const std::string& h = DefaultHelpString)
221 : Type(t), Name(n), Flags(0x0), Help(h), MultiVal(1), InitVal(0)
224 /// GenTypeDeclaration - Returns the C++ variable type of this
226 const char* GenTypeDeclaration() const;
228 /// GenVariableName - Returns the variable name used in the
229 /// generated C++ code.
230 std::string GenVariableName() const;
232 /// Merge - Merge two option descriptions.
233 void Merge (const OptionDescription& other);
235 // Misc convenient getters/setters.
237 bool isAlias() const;
239 bool isMultiVal() const;
241 bool isCommaSeparated() const;
242 void setCommaSeparated();
244 bool isExtern() const;
247 bool isRequired() const;
250 bool isOneOrMore() const;
253 bool isOptional() const;
256 bool isHidden() const;
259 bool isReallyHidden() const;
260 void setReallyHidden();
262 bool isSwitch() const
263 { return OptionType::IsSwitch(this->Type); }
265 bool isParameter() const
266 { return OptionType::IsParameter(this->Type); }
269 { return OptionType::IsList(this->Type); }
273 void OptionDescription::Merge (const OptionDescription& other)
275 if (other.Type != Type)
276 throw "Conflicting definitions for the option " + Name + "!";
278 if (Help == other.Help || Help == DefaultHelpString)
280 else if (other.Help != DefaultHelpString) {
281 llvm::errs() << "Warning: several different help strings"
282 " defined for option " + Name + "\n";
285 Flags |= other.Flags;
288 bool OptionDescription::isAlias() const {
289 return OptionType::IsAlias(this->Type);
292 bool OptionDescription::isMultiVal() const {
296 bool OptionDescription::isCommaSeparated() const {
297 return Flags & OptionDescriptionFlags::CommaSeparated;
299 void OptionDescription::setCommaSeparated() {
300 Flags |= OptionDescriptionFlags::CommaSeparated;
303 bool OptionDescription::isExtern() const {
304 return Flags & OptionDescriptionFlags::Extern;
306 void OptionDescription::setExtern() {
307 Flags |= OptionDescriptionFlags::Extern;
310 bool OptionDescription::isRequired() const {
311 return Flags & OptionDescriptionFlags::Required;
313 void OptionDescription::setRequired() {
314 Flags |= OptionDescriptionFlags::Required;
317 bool OptionDescription::isOneOrMore() const {
318 return Flags & OptionDescriptionFlags::OneOrMore;
320 void OptionDescription::setOneOrMore() {
321 Flags |= OptionDescriptionFlags::OneOrMore;
324 bool OptionDescription::isOptional() const {
325 return Flags & OptionDescriptionFlags::Optional;
327 void OptionDescription::setOptional() {
328 Flags |= OptionDescriptionFlags::Optional;
331 bool OptionDescription::isHidden() const {
332 return Flags & OptionDescriptionFlags::Hidden;
334 void OptionDescription::setHidden() {
335 Flags |= OptionDescriptionFlags::Hidden;
338 bool OptionDescription::isReallyHidden() const {
339 return Flags & OptionDescriptionFlags::ReallyHidden;
341 void OptionDescription::setReallyHidden() {
342 Flags |= OptionDescriptionFlags::ReallyHidden;
345 const char* OptionDescription::GenTypeDeclaration() const {
347 case OptionType::Alias:
349 case OptionType::PrefixList:
350 case OptionType::ParameterList:
351 return "cl::list<std::string>";
352 case OptionType::Switch:
353 return "cl::opt<bool>";
354 case OptionType::Parameter:
355 case OptionType::Prefix:
357 return "cl::opt<std::string>";
361 std::string OptionDescription::GenVariableName() const {
362 const std::string& EscapedName = EscapeVariableName(Name);
364 case OptionType::Alias:
365 return "AutoGeneratedAlias_" + EscapedName;
366 case OptionType::PrefixList:
367 case OptionType::ParameterList:
368 return "AutoGeneratedList_" + EscapedName;
369 case OptionType::Switch:
370 return "AutoGeneratedSwitch_" + EscapedName;
371 case OptionType::Prefix:
372 case OptionType::Parameter:
374 return "AutoGeneratedParameter_" + EscapedName;
378 /// OptionDescriptions - An OptionDescription array plus some helper
380 class OptionDescriptions {
381 typedef StringMap<OptionDescription> container_type;
383 /// Descriptions - A list of OptionDescriptions.
384 container_type Descriptions;
387 /// FindOption - exception-throwing wrapper for find().
388 const OptionDescription& FindOption(const std::string& OptName) const;
390 // Wrappers for FindOption that throw an exception in case the option has a
392 const OptionDescription& FindSwitch(const std::string& OptName) const;
393 const OptionDescription& FindParameter(const std::string& OptName) const;
394 const OptionDescription& FindList(const std::string& OptName) const;
395 const OptionDescription&
396 FindListOrParameter(const std::string& OptName) const;
398 /// insertDescription - Insert new OptionDescription into
399 /// OptionDescriptions list
400 void InsertDescription (const OptionDescription& o);
402 // Support for STL-style iteration
403 typedef container_type::const_iterator const_iterator;
404 const_iterator begin() const { return Descriptions.begin(); }
405 const_iterator end() const { return Descriptions.end(); }
408 const OptionDescription&
409 OptionDescriptions::FindOption(const std::string& OptName) const {
410 const_iterator I = Descriptions.find(OptName);
411 if (I != Descriptions.end())
414 throw OptName + ": no such option!";
417 const OptionDescription&
418 OptionDescriptions::FindSwitch(const std::string& OptName) const {
419 const OptionDescription& OptDesc = this->FindOption(OptName);
420 if (!OptDesc.isSwitch())
421 throw OptName + ": incorrect option type - should be a switch!";
425 const OptionDescription&
426 OptionDescriptions::FindList(const std::string& OptName) const {
427 const OptionDescription& OptDesc = this->FindOption(OptName);
428 if (!OptDesc.isList())
429 throw OptName + ": incorrect option type - should be a list!";
433 const OptionDescription&
434 OptionDescriptions::FindParameter(const std::string& OptName) const {
435 const OptionDescription& OptDesc = this->FindOption(OptName);
436 if (!OptDesc.isParameter())
437 throw OptName + ": incorrect option type - should be a parameter!";
441 const OptionDescription&
442 OptionDescriptions::FindListOrParameter(const std::string& OptName) const {
443 const OptionDescription& OptDesc = this->FindOption(OptName);
444 if (!OptDesc.isList() && !OptDesc.isParameter())
446 + ": incorrect option type - should be a list or parameter!";
450 void OptionDescriptions::InsertDescription (const OptionDescription& o) {
451 container_type::iterator I = Descriptions.find(o.Name);
452 if (I != Descriptions.end()) {
453 OptionDescription& D = I->second;
457 Descriptions[o.Name] = o;
461 /// HandlerTable - A base class for function objects implemented as
462 /// 'tables of handlers'.
463 template <typename Handler>
466 // Implementation details.
468 /// HandlerMap - A map from property names to property handlers
469 typedef StringMap<Handler> HandlerMap;
471 static HandlerMap Handlers_;
472 static bool staticMembersInitialized_;
476 Handler GetHandler (const std::string& HandlerName) const {
477 typename HandlerMap::iterator method = Handlers_.find(HandlerName);
479 if (method != Handlers_.end()) {
480 Handler h = method->second;
484 throw "No handler found for property " + HandlerName + "!";
488 void AddHandler(const char* Property, Handler H) {
489 Handlers_[Property] = H;
494 template <class Handler, class FunctionObject>
495 Handler GetHandler(FunctionObject* Obj, const DagInit& Dag) {
496 const std::string& HandlerName = GetOperatorName(Dag);
497 return Obj->GetHandler(HandlerName);
500 template <class FunctionObject>
501 void InvokeDagInitHandler(FunctionObject* Obj, Init* I) {
502 typedef void (FunctionObject::*Handler) (const DagInit&);
504 const DagInit& Dag = InitPtrToDag(I);
505 Handler h = GetHandler<Handler>(Obj, Dag);
510 template <class FunctionObject>
511 void InvokeDagInitHandler(const FunctionObject* const Obj,
512 const Init* I, unsigned IndentLevel, raw_ostream& O)
514 typedef void (FunctionObject::*Handler)
515 (const DagInit&, unsigned IndentLevel, raw_ostream& O) const;
517 const DagInit& Dag = InitPtrToDag(I);
518 Handler h = GetHandler<Handler>(Obj, Dag);
520 ((Obj)->*(h))(Dag, IndentLevel, O);
524 template <typename H>
525 typename HandlerTable<H>::HandlerMap HandlerTable<H>::Handlers_;
527 template <typename H>
528 bool HandlerTable<H>::staticMembersInitialized_ = false;
531 /// CollectOptionProperties - Function object for iterating over an
532 /// option property list.
533 class CollectOptionProperties;
534 typedef void (CollectOptionProperties::* CollectOptionPropertiesHandler)
537 class CollectOptionProperties
538 : public HandlerTable<CollectOptionPropertiesHandler>
542 /// optDescs_ - OptionDescriptions table. This is where the
543 /// information is stored.
544 OptionDescription& optDesc_;
548 explicit CollectOptionProperties(OptionDescription& OD)
551 if (!staticMembersInitialized_) {
552 AddHandler("extern", &CollectOptionProperties::onExtern);
553 AddHandler("help", &CollectOptionProperties::onHelp);
554 AddHandler("hidden", &CollectOptionProperties::onHidden);
555 AddHandler("init", &CollectOptionProperties::onInit);
556 AddHandler("multi_val", &CollectOptionProperties::onMultiVal);
557 AddHandler("one_or_more", &CollectOptionProperties::onOneOrMore);
558 AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
559 AddHandler("required", &CollectOptionProperties::onRequired);
560 AddHandler("optional", &CollectOptionProperties::onOptional);
561 AddHandler("comma_separated", &CollectOptionProperties::onCommaSeparated);
563 staticMembersInitialized_ = true;
567 /// operator() - Just forwards to the corresponding property
569 void operator() (Init* I) {
570 InvokeDagInitHandler(this, I);
575 /// Option property handlers --
576 /// Methods that handle option properties such as (help) or (hidden).
578 void onExtern (const DagInit& d) {
579 checkNumberOfArguments(d, 0);
580 optDesc_.setExtern();
583 void onHelp (const DagInit& d) {
584 checkNumberOfArguments(d, 1);
585 optDesc_.Help = InitPtrToString(d.getArg(0));
588 void onHidden (const DagInit& d) {
589 checkNumberOfArguments(d, 0);
590 optDesc_.setHidden();
593 void onReallyHidden (const DagInit& d) {
594 checkNumberOfArguments(d, 0);
595 optDesc_.setReallyHidden();
598 void onCommaSeparated (const DagInit& d) {
599 checkNumberOfArguments(d, 0);
600 if (!optDesc_.isList())
601 throw "'comma_separated' is valid only on list options!";
602 optDesc_.setCommaSeparated();
605 void onRequired (const DagInit& d) {
606 checkNumberOfArguments(d, 0);
607 if (optDesc_.isOneOrMore() || optDesc_.isOptional())
608 throw "Only one of (required), (optional) or "
609 "(one_or_more) properties is allowed!";
610 optDesc_.setRequired();
613 void onInit (const DagInit& d) {
614 checkNumberOfArguments(d, 1);
615 Init* i = d.getArg(0);
616 const std::string& str = i->getAsString();
618 bool correct = optDesc_.isParameter() && dynamic_cast<StringInit*>(i);
619 correct |= (optDesc_.isSwitch() && (str == "true" || str == "false"));
622 throw "Incorrect usage of the 'init' option property!";
624 optDesc_.InitVal = i;
627 void onOneOrMore (const DagInit& d) {
628 checkNumberOfArguments(d, 0);
629 if (optDesc_.isRequired() || optDesc_.isOptional())
630 throw "Only one of (required), (optional) or "
631 "(one_or_more) properties is allowed!";
632 if (!OptionType::IsList(optDesc_.Type))
633 llvm::errs() << "Warning: specifying the 'one_or_more' property "
634 "on a non-list option will have no effect.\n";
635 optDesc_.setOneOrMore();
638 void onOptional (const DagInit& d) {
639 checkNumberOfArguments(d, 0);
640 if (optDesc_.isRequired() || optDesc_.isOneOrMore())
641 throw "Only one of (required), (optional) or "
642 "(one_or_more) properties is allowed!";
643 if (!OptionType::IsList(optDesc_.Type))
644 llvm::errs() << "Warning: specifying the 'optional' property"
645 "on a non-list option will have no effect.\n";
646 optDesc_.setOptional();
649 void onMultiVal (const DagInit& d) {
650 checkNumberOfArguments(d, 1);
651 int val = InitPtrToInt(d.getArg(0));
653 throw "Error in the 'multi_val' property: "
654 "the value must be greater than 1!";
655 if (!OptionType::IsList(optDesc_.Type))
656 throw "The multi_val property is valid only on list options!";
657 optDesc_.MultiVal = val;
662 /// AddOption - A function object that is applied to every option
663 /// description. Used by CollectOptionDescriptions.
666 OptionDescriptions& OptDescs_;
669 explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
672 void operator()(const Init* i) {
673 const DagInit& d = InitPtrToDag(i);
674 checkNumberOfArguments(d, 1);
676 const OptionType::OptionType Type =
677 stringToOptionType(GetOperatorName(d));
678 const std::string& Name = InitPtrToString(d.getArg(0));
680 OptionDescription OD(Type, Name);
683 checkNumberOfArguments(d, 2);
686 // Aliases store the aliased option name in the 'Help' field.
687 OD.Help = InitPtrToString(d.getArg(1));
689 else if (!OD.isExtern()) {
690 processOptionProperties(d, OD);
692 OptDescs_.InsertDescription(OD);
696 /// processOptionProperties - Go through the list of option
697 /// properties and call a corresponding handler for each.
698 static void processOptionProperties (const DagInit& d, OptionDescription& o) {
699 checkNumberOfArguments(d, 2);
700 DagInit::const_arg_iterator B = d.arg_begin();
701 // Skip the first argument: it's always the option name.
703 std::for_each(B, d.arg_end(), CollectOptionProperties(o));
708 /// CollectOptionDescriptions - Collects option properties from all
710 void CollectOptionDescriptions (RecordVector::const_iterator B,
711 RecordVector::const_iterator E,
712 OptionDescriptions& OptDescs)
714 // For every OptionList:
716 RecordVector::value_type T = *B;
717 // Throws an exception if the value does not exist.
718 ListInit* PropList = T->getValueAsListInit("options");
720 // For every option description in this list:
721 // collect the information and
722 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
726 // Tool information record
728 namespace ToolFlags {
729 enum ToolFlags { Join = 0x1, Sink = 0x2 };
732 struct ToolDescription : public RefCountedBase<ToolDescription> {
736 StrVector InLanguage;
737 std::string OutLanguage;
738 std::string OutputSuffix;
741 // Various boolean properties
742 void setSink() { Flags |= ToolFlags::Sink; }
743 bool isSink() const { return Flags & ToolFlags::Sink; }
744 void setJoin() { Flags |= ToolFlags::Join; }
745 bool isJoin() const { return Flags & ToolFlags::Join; }
747 // Default ctor here is needed because StringMap can only store
748 // DefaultConstructible objects
749 ToolDescription() : CmdLine(0), Actions(0), Flags(0) {}
750 ToolDescription (const std::string& n)
751 : Name(n), CmdLine(0), Actions(0), Flags(0)
755 /// ToolDescriptions - A list of Tool information records.
756 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
759 /// CollectToolProperties - Function object for iterating over a list of
760 /// tool property records.
762 class CollectToolProperties;
763 typedef void (CollectToolProperties::* CollectToolPropertiesHandler)
766 class CollectToolProperties : public HandlerTable<CollectToolPropertiesHandler>
770 /// toolDesc_ - Properties of the current Tool. This is where the
771 /// information is stored.
772 ToolDescription& toolDesc_;
776 explicit CollectToolProperties (ToolDescription& d)
779 if (!staticMembersInitialized_) {
781 AddHandler("actions", &CollectToolProperties::onActions);
782 AddHandler("cmd_line", &CollectToolProperties::onCmdLine);
783 AddHandler("in_language", &CollectToolProperties::onInLanguage);
784 AddHandler("join", &CollectToolProperties::onJoin);
785 AddHandler("out_language", &CollectToolProperties::onOutLanguage);
786 AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
787 AddHandler("sink", &CollectToolProperties::onSink);
789 staticMembersInitialized_ = true;
793 void operator() (Init* I) {
794 InvokeDagInitHandler(this, I);
799 /// Property handlers --
800 /// Functions that extract information about tool properties from
801 /// DAG representation.
803 void onActions (const DagInit& d) {
804 checkNumberOfArguments(d, 1);
805 Init* Case = d.getArg(0);
806 if (typeid(*Case) != typeid(DagInit) ||
807 GetOperatorName(static_cast<DagInit&>(*Case)) != "case")
808 throw "The argument to (actions) should be a 'case' construct!";
809 toolDesc_.Actions = Case;
812 void onCmdLine (const DagInit& d) {
813 checkNumberOfArguments(d, 1);
814 toolDesc_.CmdLine = d.getArg(0);
817 void onInLanguage (const DagInit& d) {
818 checkNumberOfArguments(d, 1);
819 Init* arg = d.getArg(0);
821 // Find out the argument's type.
822 if (typeid(*arg) == typeid(StringInit)) {
824 toolDesc_.InLanguage.push_back(InitPtrToString(arg));
828 const ListInit& lst = InitPtrToList(arg);
829 StrVector& out = toolDesc_.InLanguage;
831 // Copy strings to the output vector.
832 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
834 out.push_back(InitPtrToString(*B));
837 // Remove duplicates.
838 std::sort(out.begin(), out.end());
839 StrVector::iterator newE = std::unique(out.begin(), out.end());
840 out.erase(newE, out.end());
844 void onJoin (const DagInit& d) {
845 checkNumberOfArguments(d, 0);
849 void onOutLanguage (const DagInit& d) {
850 checkNumberOfArguments(d, 1);
851 toolDesc_.OutLanguage = InitPtrToString(d.getArg(0));
854 void onOutputSuffix (const DagInit& d) {
855 checkNumberOfArguments(d, 1);
856 toolDesc_.OutputSuffix = InitPtrToString(d.getArg(0));
859 void onSink (const DagInit& d) {
860 checkNumberOfArguments(d, 0);
866 /// CollectToolDescriptions - Gather information about tool properties
867 /// from the parsed TableGen data (basically a wrapper for the
868 /// CollectToolProperties function object).
869 void CollectToolDescriptions (RecordVector::const_iterator B,
870 RecordVector::const_iterator E,
871 ToolDescriptions& ToolDescs)
873 // Iterate over a properties list of every Tool definition
875 const Record* T = *B;
876 // Throws an exception if the value does not exist.
877 ListInit* PropList = T->getValueAsListInit("properties");
879 IntrusiveRefCntPtr<ToolDescription>
880 ToolDesc(new ToolDescription(T->getName()));
882 std::for_each(PropList->begin(), PropList->end(),
883 CollectToolProperties(*ToolDesc));
884 ToolDescs.push_back(ToolDesc);
888 /// FillInEdgeVector - Merge all compilation graph definitions into
889 /// one single edge list.
890 void FillInEdgeVector(RecordVector::const_iterator B,
891 RecordVector::const_iterator E, RecordVector& Out) {
892 for (; B != E; ++B) {
893 const ListInit* edges = (*B)->getValueAsListInit("edges");
895 for (unsigned i = 0; i < edges->size(); ++i)
896 Out.push_back(edges->getElementAsRecord(i));
900 /// CalculatePriority - Calculate the priority of this plugin.
901 int CalculatePriority(RecordVector::const_iterator B,
902 RecordVector::const_iterator E) {
906 priority = static_cast<int>((*B)->getValueAsInt("priority"));
909 throw "More than one 'PluginPriority' instance found: "
910 "most probably an error!";
916 /// NotInGraph - Helper function object for FilterNotInGraph.
919 const llvm::StringSet<>& ToolsInGraph_;
922 NotInGraph(const llvm::StringSet<>& ToolsInGraph)
923 : ToolsInGraph_(ToolsInGraph)
926 bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
927 return (ToolsInGraph_.count(x->Name) == 0);
931 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
932 /// mentioned in the compilation graph definition.
933 void FilterNotInGraph (const RecordVector& EdgeVector,
934 ToolDescriptions& ToolDescs) {
936 // List all tools mentioned in the graph.
937 llvm::StringSet<> ToolsInGraph;
939 for (RecordVector::const_iterator B = EdgeVector.begin(),
940 E = EdgeVector.end(); B != E; ++B) {
942 const Record* Edge = *B;
943 const std::string& NodeA = Edge->getValueAsString("a");
944 const std::string& NodeB = Edge->getValueAsString("b");
947 ToolsInGraph.insert(NodeA);
948 ToolsInGraph.insert(NodeB);
951 // Filter ToolPropertiesList.
952 ToolDescriptions::iterator new_end =
953 std::remove_if(ToolDescs.begin(), ToolDescs.end(),
954 NotInGraph(ToolsInGraph));
955 ToolDescs.erase(new_end, ToolDescs.end());
958 /// FillInToolToLang - Fills in two tables that map tool names to
959 /// (input, output) languages. Helper function used by TypecheckGraph().
960 void FillInToolToLang (const ToolDescriptions& ToolDescs,
961 StringMap<StringSet<> >& ToolToInLang,
962 StringMap<std::string>& ToolToOutLang) {
963 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
964 E = ToolDescs.end(); B != E; ++B) {
965 const ToolDescription& D = *(*B);
966 for (StrVector::const_iterator B = D.InLanguage.begin(),
967 E = D.InLanguage.end(); B != E; ++B)
968 ToolToInLang[D.Name].insert(*B);
969 ToolToOutLang[D.Name] = D.OutLanguage;
973 /// TypecheckGraph - Check that names for output and input languages
974 /// on all edges do match. This doesn't do much when the information
975 /// about the whole graph is not available (i.e. when compiling most
977 void TypecheckGraph (const RecordVector& EdgeVector,
978 const ToolDescriptions& ToolDescs) {
979 StringMap<StringSet<> > ToolToInLang;
980 StringMap<std::string> ToolToOutLang;
982 FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
983 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
984 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
986 for (RecordVector::const_iterator B = EdgeVector.begin(),
987 E = EdgeVector.end(); B != E; ++B) {
988 const Record* Edge = *B;
989 const std::string& NodeA = Edge->getValueAsString("a");
990 const std::string& NodeB = Edge->getValueAsString("b");
991 StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
992 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
994 if (NodeA != "root") {
995 if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
996 throw "Edge " + NodeA + "->" + NodeB
997 + ": output->input language mismatch";
1000 if (NodeB == "root")
1001 throw "Edges back to the root are not allowed!";
1005 /// WalkCase - Walks the 'case' expression DAG and invokes
1006 /// TestCallback on every test, and StatementCallback on every
1007 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
1008 /// combinators (that is, they are passed directly to TestCallback).
1009 /// TestCallback must have type 'void TestCallback(const DagInit*, unsigned
1010 /// IndentLevel, bool FirstTest)'.
1011 /// StatementCallback must have type 'void StatementCallback(const Init*,
1012 /// unsigned IndentLevel)'.
1013 template <typename F1, typename F2>
1014 void WalkCase(const Init* Case, F1 TestCallback, F2 StatementCallback,
1015 unsigned IndentLevel = 0)
1017 const DagInit& d = InitPtrToDag(Case);
1020 if (GetOperatorName(d) != "case")
1021 throw "WalkCase should be invoked only on 'case' expressions!";
1023 if (d.getNumArgs() < 2)
1024 throw "There should be at least one clause in the 'case' expression:\n"
1029 const unsigned numArgs = d.getNumArgs();
1031 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1038 const DagInit& Test = InitPtrToDag(arg);
1040 if (GetOperatorName(Test) == "default" && (i+1 != numArgs))
1041 throw "The 'default' clause should be the last in the "
1042 "'case' construct!";
1044 throw "Case construct handler: no corresponding action "
1045 "found for the test " + Test.getAsString() + '!';
1047 TestCallback(Test, IndentLevel, (i == 1));
1051 if (dynamic_cast<DagInit*>(arg)
1052 && GetOperatorName(static_cast<DagInit&>(*arg)) == "case") {
1054 WalkCase(arg, TestCallback, StatementCallback, IndentLevel + Indent1);
1057 // Handle statement.
1058 StatementCallback(arg, IndentLevel);
1066 /// ExtractOptionNames - A helper function object used by
1067 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
1068 class ExtractOptionNames {
1069 llvm::StringSet<>& OptionNames_;
1071 void processDag(const Init* Statement) {
1072 const DagInit& Stmt = InitPtrToDag(Statement);
1073 const std::string& ActionName = GetOperatorName(Stmt);
1074 if (ActionName == "forward" || ActionName == "forward_as" ||
1075 ActionName == "forward_value" ||
1076 ActionName == "forward_transformed_value" ||
1077 ActionName == "switch_on" || ActionName == "parameter_equals" ||
1078 ActionName == "element_in_list" || ActionName == "not_empty" ||
1079 ActionName == "empty") {
1080 checkNumberOfArguments(Stmt, 1);
1081 const std::string& Name = InitPtrToString(Stmt.getArg(0));
1082 OptionNames_.insert(Name);
1084 else if (ActionName == "and" || ActionName == "or") {
1085 for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
1086 this->processDag(Stmt.getArg(i));
1092 ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
1095 void operator()(const Init* Statement) {
1096 if (typeid(*Statement) == typeid(ListInit)) {
1097 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1098 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1100 this->processDag(*B);
1103 this->processDag(Statement);
1107 void operator()(const DagInit& Test, unsigned, bool) {
1108 this->operator()(&Test);
1110 void operator()(const Init* Statement, unsigned) {
1111 this->operator()(Statement);
1115 /// CheckForSuperfluousOptions - Check that there are no side
1116 /// effect-free options (specified only in the OptionList). Otherwise,
1117 /// output a warning.
1118 void CheckForSuperfluousOptions (const RecordVector& Edges,
1119 const ToolDescriptions& ToolDescs,
1120 const OptionDescriptions& OptDescs) {
1121 llvm::StringSet<> nonSuperfluousOptions;
1123 // Add all options mentioned in the ToolDesc.Actions to the set of
1124 // non-superfluous options.
1125 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1126 E = ToolDescs.end(); B != E; ++B) {
1127 const ToolDescription& TD = *(*B);
1128 ExtractOptionNames Callback(nonSuperfluousOptions);
1130 WalkCase(TD.Actions, Callback, Callback);
1133 // Add all options mentioned in the 'case' clauses of the
1134 // OptionalEdges of the compilation graph to the set of
1135 // non-superfluous options.
1136 for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
1138 const Record* Edge = *B;
1139 DagInit& Weight = *Edge->getValueAsDag("weight");
1141 if (!isDagEmpty(Weight))
1142 WalkCase(&Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
1145 // Check that all options in OptDescs belong to the set of
1146 // non-superfluous options.
1147 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
1148 E = OptDescs.end(); B != E; ++B) {
1149 const OptionDescription& Val = B->second;
1150 if (!nonSuperfluousOptions.count(Val.Name)
1151 && Val.Type != OptionType::Alias)
1152 llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! "
1153 "Probable cause: this option is specified only in the OptionList.\n";
1157 /// EmitCaseTest0Args - Helper function used by EmitCaseConstructHandler().
1158 bool EmitCaseTest0Args(const std::string& TestName, raw_ostream& O) {
1159 if (TestName == "single_input_file") {
1160 O << "InputFilenames.size() == 1";
1163 else if (TestName == "multiple_input_files") {
1164 O << "InputFilenames.size() > 1";
1171 /// EmitListTest - Helper function used by EmitCaseTest1ArgList().
1172 template <typename F>
1173 void EmitListTest(const ListInit& L, const char* LogicOp,
1174 F Callback, raw_ostream& O)
1176 // This is a lot like EmitLogicalOperationTest, but works on ListInits instead
1178 bool isFirst = true;
1179 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B) {
1184 Callback(InitPtrToString(*B), O);
1188 // Callbacks for use with EmitListTest.
1190 class EmitSwitchOn {
1191 const OptionDescriptions& OptDescs_;
1193 EmitSwitchOn(const OptionDescriptions& OptDescs) : OptDescs_(OptDescs)
1196 void operator()(const std::string& OptName, raw_ostream& O) const {
1197 const OptionDescription& OptDesc = OptDescs_.FindSwitch(OptName);
1198 O << OptDesc.GenVariableName();
1202 class EmitEmptyTest {
1204 const OptionDescriptions& OptDescs_;
1206 EmitEmptyTest(bool EmitNegate, const OptionDescriptions& OptDescs)
1207 : EmitNegate_(EmitNegate), OptDescs_(OptDescs)
1210 void operator()(const std::string& OptName, raw_ostream& O) const {
1211 const char* Neg = (EmitNegate_ ? "!" : "");
1212 if (OptName == "o") {
1213 O << Neg << "OutputFilename.empty()";
1215 else if (OptName == "save-temps") {
1216 O << Neg << "(SaveTemps == SaveTempsEnum::Unset)";
1219 const OptionDescription& OptDesc = OptDescs_.FindListOrParameter(OptName);
1220 O << Neg << OptDesc.GenVariableName() << ".empty()";
1226 /// EmitCaseTest1ArgList - Helper function used by EmitCaseTest1Arg();
1227 bool EmitCaseTest1ArgList(const std::string& TestName,
1229 const OptionDescriptions& OptDescs,
1231 const ListInit& L = *static_cast<ListInit*>(d.getArg(0));
1233 if (TestName == "any_switch_on") {
1234 EmitListTest(L, "||", EmitSwitchOn(OptDescs), O);
1237 else if (TestName == "switch_on") {
1238 EmitListTest(L, "&&", EmitSwitchOn(OptDescs), O);
1241 else if (TestName == "any_not_empty") {
1242 EmitListTest(L, "||", EmitEmptyTest(true, OptDescs), O);
1245 else if (TestName == "any_empty") {
1246 EmitListTest(L, "||", EmitEmptyTest(false, OptDescs), O);
1249 else if (TestName == "not_empty") {
1250 EmitListTest(L, "&&", EmitEmptyTest(true, OptDescs), O);
1253 else if (TestName == "empty") {
1254 EmitListTest(L, "&&", EmitEmptyTest(false, OptDescs), O);
1261 /// EmitCaseTest1ArgStr - Helper function used by EmitCaseTest1Arg();
1262 bool EmitCaseTest1ArgStr(const std::string& TestName,
1264 const OptionDescriptions& OptDescs,
1266 const std::string& OptName = InitPtrToString(d.getArg(0));
1268 if (TestName == "switch_on") {
1269 apply(EmitSwitchOn(OptDescs), OptName, O);
1272 else if (TestName == "input_languages_contain") {
1273 O << "InLangs.count(\"" << OptName << "\") != 0";
1276 else if (TestName == "in_language") {
1277 // This works only for single-argument Tool::GenerateAction. Join
1278 // tools can process several files in different languages simultaneously.
1280 // TODO: make this work with Edge::Weight (if possible).
1281 O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
1284 else if (TestName == "not_empty" || TestName == "empty") {
1285 bool EmitNegate = (TestName == "not_empty");
1286 apply(EmitEmptyTest(EmitNegate, OptDescs), OptName, O);
1293 /// EmitCaseTest1Arg - Helper function used by EmitCaseConstructHandler();
1294 bool EmitCaseTest1Arg(const std::string& TestName,
1296 const OptionDescriptions& OptDescs,
1298 checkNumberOfArguments(d, 1);
1299 if (typeid(*d.getArg(0)) == typeid(ListInit))
1300 return EmitCaseTest1ArgList(TestName, d, OptDescs, O);
1302 return EmitCaseTest1ArgStr(TestName, d, OptDescs, O);
1305 /// EmitCaseTest2Args - Helper function used by EmitCaseConstructHandler().
1306 bool EmitCaseTest2Args(const std::string& TestName,
1308 unsigned IndentLevel,
1309 const OptionDescriptions& OptDescs,
1311 checkNumberOfArguments(d, 2);
1312 const std::string& OptName = InitPtrToString(d.getArg(0));
1313 const std::string& OptArg = InitPtrToString(d.getArg(1));
1315 if (TestName == "parameter_equals") {
1316 const OptionDescription& OptDesc = OptDescs.FindParameter(OptName);
1317 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
1320 else if (TestName == "element_in_list") {
1321 const OptionDescription& OptDesc = OptDescs.FindList(OptName);
1322 const std::string& VarName = OptDesc.GenVariableName();
1323 O << "std::find(" << VarName << ".begin(),\n";
1324 O.indent(IndentLevel + Indent1)
1325 << VarName << ".end(), \""
1326 << OptArg << "\") != " << VarName << ".end()";
1333 // Forward declaration.
1334 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
1335 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1336 const OptionDescriptions& OptDescs,
1339 /// EmitLogicalOperationTest - Helper function used by
1340 /// EmitCaseConstructHandler.
1341 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
1342 unsigned IndentLevel,
1343 const OptionDescriptions& OptDescs,
1346 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
1347 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
1348 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1349 if (j != NumArgs - 1) {
1351 O.indent(IndentLevel + Indent1) << ' ' << LogicOp << " (";
1359 void EmitLogicalNot(const DagInit& d, unsigned IndentLevel,
1360 const OptionDescriptions& OptDescs, raw_ostream& O)
1362 checkNumberOfArguments(d, 1);
1363 const DagInit& InnerTest = InitPtrToDag(d.getArg(0));
1365 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1369 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
1370 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1371 const OptionDescriptions& OptDescs,
1373 const std::string& TestName = GetOperatorName(d);
1375 if (TestName == "and")
1376 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
1377 else if (TestName == "or")
1378 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
1379 else if (TestName == "not")
1380 EmitLogicalNot(d, IndentLevel, OptDescs, O);
1381 else if (EmitCaseTest0Args(TestName, O))
1383 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
1385 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
1388 throw TestName + ": unknown edge property!";
1392 /// EmitCaseTestCallback - Callback used by EmitCaseConstructHandler.
1393 class EmitCaseTestCallback {
1395 const OptionDescriptions& OptDescs_;
1399 EmitCaseTestCallback(bool EmitElseIf,
1400 const OptionDescriptions& OptDescs, raw_ostream& O)
1401 : EmitElseIf_(EmitElseIf), OptDescs_(OptDescs), O_(O)
1404 void operator()(const DagInit& Test, unsigned IndentLevel, bool FirstTest)
1406 if (GetOperatorName(Test) == "default") {
1407 O_.indent(IndentLevel) << "else {\n";
1410 O_.indent(IndentLevel)
1411 << ((!FirstTest && EmitElseIf_) ? "else if (" : "if (");
1412 EmitCaseTest(Test, IndentLevel, OptDescs_, O_);
1418 /// EmitCaseStatementCallback - Callback used by EmitCaseConstructHandler.
1419 template <typename F>
1420 class EmitCaseStatementCallback {
1425 EmitCaseStatementCallback(F Callback, raw_ostream& O)
1426 : Callback_(Callback), O_(O)
1429 void operator() (const Init* Statement, unsigned IndentLevel) {
1431 // Ignore nested 'case' DAG.
1432 if (!(dynamic_cast<const DagInit*>(Statement) &&
1433 GetOperatorName(static_cast<const DagInit&>(*Statement)) == "case")) {
1434 if (typeid(*Statement) == typeid(ListInit)) {
1435 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1436 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1438 Callback_(*B, (IndentLevel + Indent1), O_);
1441 Callback_(Statement, (IndentLevel + Indent1), O_);
1444 O_.indent(IndentLevel) << "}\n";
1449 /// EmitCaseConstructHandler - Emit code that handles the 'case'
1450 /// construct. Takes a function object that should emit code for every case
1451 /// clause. Implemented on top of WalkCase.
1452 /// Callback's type is void F(Init* Statement, unsigned IndentLevel,
1453 /// raw_ostream& O).
1454 /// EmitElseIf parameter controls the type of condition that is emitted ('if
1455 /// (..) {..} else if (..) {} .. else {..}' vs. 'if (..) {..} if(..) {..}
1457 template <typename F>
1458 void EmitCaseConstructHandler(const Init* Case, unsigned IndentLevel,
1459 F Callback, bool EmitElseIf,
1460 const OptionDescriptions& OptDescs,
1462 WalkCase(Case, EmitCaseTestCallback(EmitElseIf, OptDescs, O),
1463 EmitCaseStatementCallback<F>(Callback, O), IndentLevel);
1466 /// TokenizeCmdLine - converts from
1467 /// "$CALL(HookName, 'Arg1', 'Arg2')/path -arg1 -arg2" to
1468 /// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path", "-arg1", "-arg2"].
1469 void TokenizeCmdLine(const std::string& CmdLine, StrVector& Out) {
1470 const char* Delimiters = " \t\n\v\f\r";
1472 { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1475 if (CmdLine.empty())
1479 std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1482 for (; B != E; ++B) {
1483 char cur_ch = CmdLine[B];
1487 if (cur_ch == '$') {
1488 cur_st = SpecialCommand;
1491 if (oneOf(Delimiters, cur_ch)) {
1493 B = CmdLine.find_first_not_of(Delimiters, B);
1494 if (B == std::string::npos) {
1505 case SpecialCommand:
1506 if (oneOf(Delimiters, cur_ch)) {
1511 if (cur_ch == '(') {
1513 cur_st = InsideSpecialCommand;
1518 case InsideSpecialCommand:
1519 if (oneOf(Delimiters, cur_ch)) {
1522 if (cur_ch == '\'') {
1523 cur_st = InsideQuotationMarks;
1527 if (cur_ch == ')') {
1531 if (cur_ch == ',') {
1537 case InsideQuotationMarks:
1538 if (cur_ch == '\'') {
1539 cur_st = InsideSpecialCommand;
1545 Out.back().push_back(cur_ch);
1549 /// SubstituteCall - Given "$CALL(HookName, [Arg1 [, Arg2 [...]]])", output
1550 /// "hooks::HookName([Arg1 [, Arg2 [, ...]]])". Helper function used by
1551 /// SubstituteSpecialCommands().
1552 StrVector::const_iterator
1553 SubstituteCall (StrVector::const_iterator Pos,
1554 StrVector::const_iterator End,
1555 bool IsJoin, raw_ostream& O)
1557 const char* errorMessage = "Syntax error in $CALL invocation!";
1558 checkedIncrement(Pos, End, errorMessage);
1559 const std::string& CmdName = *Pos;
1562 throw "$CALL invocation: empty argument list!";
1565 O << CmdName << "(";
1568 bool firstIteration = true;
1570 checkedIncrement(Pos, End, errorMessage);
1571 const std::string& Arg = *Pos;
1572 assert(Arg.size() != 0);
1578 firstIteration = false;
1582 if (Arg == "$INFILE") {
1584 throw "$CALL(Hook, $INFILE) can't be used with a Join tool!";
1586 O << "inFile.c_str()";
1589 O << '"' << Arg << '"';
1598 /// SubstituteEnv - Given '$ENV(VAR_NAME)', output 'getenv("VAR_NAME")'. Helper
1599 /// function used by SubstituteSpecialCommands().
1600 StrVector::const_iterator
1601 SubstituteEnv (StrVector::const_iterator Pos,
1602 StrVector::const_iterator End, raw_ostream& O)
1604 const char* errorMessage = "Syntax error in $ENV invocation!";
1605 checkedIncrement(Pos, End, errorMessage);
1606 const std::string& EnvName = *Pos;
1609 throw "$ENV invocation: empty argument list!";
1611 O << "checkCString(std::getenv(\"";
1615 checkedIncrement(Pos, End, errorMessage);
1620 /// SubstituteSpecialCommands - Given an invocation of $CALL or $ENV, output
1621 /// handler code. Helper function used by EmitCmdLineVecFill().
1622 StrVector::const_iterator
1623 SubstituteSpecialCommands (StrVector::const_iterator Pos,
1624 StrVector::const_iterator End,
1625 bool IsJoin, raw_ostream& O)
1628 const std::string& cmd = *Pos;
1630 // Perform substitution.
1631 if (cmd == "$CALL") {
1632 Pos = SubstituteCall(Pos, End, IsJoin, O);
1634 else if (cmd == "$ENV") {
1635 Pos = SubstituteEnv(Pos, End, O);
1638 throw "Unknown special command: " + cmd;
1641 // Handle '$CMD(ARG)/additional/text'.
1642 const std::string& Leftover = *Pos;
1643 assert(Leftover.at(0) == ')');
1644 if (Leftover.size() != 1)
1645 O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1650 /// EmitCmdLineVecFill - Emit code that fills in the command line
1651 /// vector. Helper function used by EmitGenerateActionMethod().
1652 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1653 bool IsJoin, unsigned IndentLevel,
1656 TokenizeCmdLine(InitPtrToString(CmdLine), StrVec);
1659 throw "Tool '" + ToolName + "' has empty command line!";
1661 StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1663 // If there is a hook invocation on the place of the first command, skip it.
1664 assert(!StrVec[0].empty());
1665 if (StrVec[0][0] == '$') {
1666 while (I != E && (*I)[0] != ')' )
1669 // Skip the ')' symbol.
1676 bool hasINFILE = false;
1678 for (; I != E; ++I) {
1679 const std::string& cmd = *I;
1680 assert(!cmd.empty());
1681 O.indent(IndentLevel);
1682 if (cmd.at(0) == '$') {
1683 if (cmd == "$INFILE") {
1686 O << "for (PathVector::const_iterator B = inFiles.begin()"
1687 << ", E = inFiles.end();\n";
1688 O.indent(IndentLevel) << "B != E; ++B)\n";
1689 O.indent(IndentLevel + Indent1) << "vec.push_back(B->str());\n";
1692 O << "vec.push_back(inFile.str());\n";
1695 else if (cmd == "$OUTFILE") {
1696 O << "vec.push_back(\"\");\n";
1697 O.indent(IndentLevel) << "out_file_index = vec.size()-1;\n";
1700 O << "vec.push_back(";
1701 I = SubstituteSpecialCommands(I, E, IsJoin, O);
1706 O << "vec.push_back(\"" << cmd << "\");\n";
1710 throw "Tool '" + ToolName + "' doesn't take any input!";
1712 O.indent(IndentLevel) << "cmd = ";
1713 if (StrVec[0][0] == '$')
1714 SubstituteSpecialCommands(StrVec.begin(), StrVec.end(), IsJoin, O);
1716 O << '"' << StrVec[0] << '"';
1720 /// EmitCmdLineVecFillCallback - A function object wrapper around
1721 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1722 /// argument to EmitCaseConstructHandler().
1723 class EmitCmdLineVecFillCallback {
1725 const std::string& ToolName;
1727 EmitCmdLineVecFillCallback(bool J, const std::string& TN)
1728 : IsJoin(J), ToolName(TN) {}
1730 void operator()(const Init* Statement, unsigned IndentLevel,
1731 raw_ostream& O) const
1733 EmitCmdLineVecFill(Statement, ToolName, IsJoin, IndentLevel, O);
1737 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1738 /// implement EmitActionHandler. Emits code for
1739 /// handling the (forward) and (forward_as) option properties.
1740 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1741 unsigned IndentLevel,
1742 const std::string& NewName,
1744 const std::string& Name = NewName.empty()
1747 unsigned IndentLevel1 = IndentLevel + Indent1;
1750 case OptionType::Switch:
1751 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1753 case OptionType::Parameter:
1754 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1755 O.indent(IndentLevel) << "vec.push_back(" << D.GenVariableName() << ");\n";
1757 case OptionType::Prefix:
1758 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\" + "
1759 << D.GenVariableName() << ");\n";
1761 case OptionType::PrefixList:
1762 O.indent(IndentLevel)
1763 << "for (" << D.GenTypeDeclaration()
1764 << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1765 O.indent(IndentLevel)
1766 << "E = " << D.GenVariableName() << ".end(); B != E;) {\n";
1767 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\" + " << "*B);\n";
1768 O.indent(IndentLevel1) << "++B;\n";
1770 for (int i = 1, j = D.MultiVal; i < j; ++i) {
1771 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1772 O.indent(IndentLevel1) << "++B;\n";
1775 O.indent(IndentLevel) << "}\n";
1777 case OptionType::ParameterList:
1778 O.indent(IndentLevel)
1779 << "for (" << D.GenTypeDeclaration() << "::iterator B = "
1780 << D.GenVariableName() << ".begin(),\n";
1781 O.indent(IndentLevel) << "E = " << D.GenVariableName()
1782 << ".end() ; B != E;) {\n";
1783 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\");\n";
1785 for (int i = 0, j = D.MultiVal; i < j; ++i) {
1786 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1787 O.indent(IndentLevel1) << "++B;\n";
1790 O.indent(IndentLevel) << "}\n";
1792 case OptionType::Alias:
1794 throw "Aliases are not allowed in tool option descriptions!";
1798 /// ActionHandlingCallbackBase - Base class of EmitActionHandlersCallback and
1799 /// EmitPreprocessOptionsCallback.
1800 struct ActionHandlingCallbackBase
1803 void onErrorDag(const DagInit& d,
1804 unsigned IndentLevel, raw_ostream& O) const
1806 O.indent(IndentLevel)
1807 << "throw std::runtime_error(\"" <<
1808 (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0))
1813 void onWarningDag(const DagInit& d,
1814 unsigned IndentLevel, raw_ostream& O) const
1816 checkNumberOfArguments(d, 1);
1817 O.indent(IndentLevel) << "llvm::errs() << \""
1818 << InitPtrToString(d.getArg(0)) << "\";\n";
1823 /// EmitActionHandlersCallback - Emit code that handles actions. Used by
1824 /// EmitGenerateActionMethod() as an argument to EmitCaseConstructHandler().
1826 class EmitActionHandlersCallback;
1828 typedef void (EmitActionHandlersCallback::* EmitActionHandlersCallbackHandler)
1829 (const DagInit&, unsigned, raw_ostream&) const;
1831 class EmitActionHandlersCallback :
1832 public ActionHandlingCallbackBase,
1833 public HandlerTable<EmitActionHandlersCallbackHandler>
1835 typedef EmitActionHandlersCallbackHandler Handler;
1837 const OptionDescriptions& OptDescs;
1839 /// EmitHookInvocation - Common code for hook invocation from actions. Used by
1840 /// onAppendCmd and onOutputSuffix.
1841 void EmitHookInvocation(const std::string& Str,
1842 const char* BlockOpen, const char* BlockClose,
1843 unsigned IndentLevel, raw_ostream& O) const
1846 TokenizeCmdLine(Str, Out);
1848 for (StrVector::const_iterator B = Out.begin(), E = Out.end();
1850 const std::string& cmd = *B;
1852 O.indent(IndentLevel) << BlockOpen;
1854 if (cmd.at(0) == '$')
1855 B = SubstituteSpecialCommands(B, E, /* IsJoin = */ true, O);
1857 O << '"' << cmd << '"';
1863 void onAppendCmd (const DagInit& Dag,
1864 unsigned IndentLevel, raw_ostream& O) const
1866 checkNumberOfArguments(Dag, 1);
1867 this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
1868 "vec.push_back(", ");\n", IndentLevel, O);
1871 void onForward (const DagInit& Dag,
1872 unsigned IndentLevel, raw_ostream& O) const
1874 checkNumberOfArguments(Dag, 1);
1875 const std::string& Name = InitPtrToString(Dag.getArg(0));
1876 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1877 IndentLevel, "", O);
1880 void onForwardAs (const DagInit& Dag,
1881 unsigned IndentLevel, raw_ostream& O) const
1883 checkNumberOfArguments(Dag, 2);
1884 const std::string& Name = InitPtrToString(Dag.getArg(0));
1885 const std::string& NewName = InitPtrToString(Dag.getArg(1));
1886 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1887 IndentLevel, NewName, O);
1890 void onForwardValue (const DagInit& Dag,
1891 unsigned IndentLevel, raw_ostream& O) const
1893 checkNumberOfArguments(Dag, 1);
1894 const std::string& Name = InitPtrToString(Dag.getArg(0));
1895 const OptionDescription& D = OptDescs.FindListOrParameter(Name);
1897 if (D.isParameter()) {
1898 O.indent(IndentLevel) << "vec.push_back("
1899 << D.GenVariableName() << ");\n";
1902 O.indent(IndentLevel) << "std::copy(" << D.GenVariableName()
1903 << ".begin(), " << D.GenVariableName()
1904 << ".end(), std::back_inserter(vec));\n";
1908 void onForwardTransformedValue (const DagInit& Dag,
1909 unsigned IndentLevel, raw_ostream& O) const
1911 checkNumberOfArguments(Dag, 2);
1912 const std::string& Name = InitPtrToString(Dag.getArg(0));
1913 const std::string& Hook = InitPtrToString(Dag.getArg(1));
1914 const OptionDescription& D = OptDescs.FindListOrParameter(Name);
1916 O.indent(IndentLevel) << "vec.push_back(" << "hooks::"
1917 << Hook << "(" << D.GenVariableName()
1918 << (D.isParameter() ? ".c_str()" : "") << "));\n";
1921 void onOutputSuffix (const DagInit& Dag,
1922 unsigned IndentLevel, raw_ostream& O) const
1924 checkNumberOfArguments(Dag, 1);
1925 this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
1926 "output_suffix = ", ";\n", IndentLevel, O);
1929 void onStopCompilation (const DagInit& Dag,
1930 unsigned IndentLevel, raw_ostream& O) const
1932 O.indent(IndentLevel) << "stop_compilation = true;\n";
1936 void onUnpackValues (const DagInit& Dag,
1937 unsigned IndentLevel, raw_ostream& O) const
1939 throw "'unpack_values' is deprecated. "
1940 "Use 'comma_separated' + 'forward_value' instead!";
1945 explicit EmitActionHandlersCallback(const OptionDescriptions& OD)
1948 if (!staticMembersInitialized_) {
1949 AddHandler("error", &EmitActionHandlersCallback::onErrorDag);
1950 AddHandler("warning", &EmitActionHandlersCallback::onWarningDag);
1951 AddHandler("append_cmd", &EmitActionHandlersCallback::onAppendCmd);
1952 AddHandler("forward", &EmitActionHandlersCallback::onForward);
1953 AddHandler("forward_as", &EmitActionHandlersCallback::onForwardAs);
1954 AddHandler("forward_value", &EmitActionHandlersCallback::onForwardValue);
1955 AddHandler("forward_transformed_value",
1956 &EmitActionHandlersCallback::onForwardTransformedValue);
1957 AddHandler("output_suffix", &EmitActionHandlersCallback::onOutputSuffix);
1958 AddHandler("stop_compilation",
1959 &EmitActionHandlersCallback::onStopCompilation);
1960 AddHandler("unpack_values",
1961 &EmitActionHandlersCallback::onUnpackValues);
1963 staticMembersInitialized_ = true;
1967 void operator()(const Init* I,
1968 unsigned IndentLevel, raw_ostream& O) const
1970 InvokeDagInitHandler(this, I, IndentLevel, O);
1974 bool IsOutFileIndexCheckRequiredStr (const Init* CmdLine) {
1976 TokenizeCmdLine(InitPtrToString(CmdLine), StrVec);
1978 for (StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1980 if (*I == "$OUTFILE")
1987 class IsOutFileIndexCheckRequiredStrCallback {
1991 IsOutFileIndexCheckRequiredStrCallback(bool* ret) : ret_(ret)
1994 void operator()(const Init* CmdLine) {
1995 // Ignore nested 'case' DAG.
1996 if (typeid(*CmdLine) == typeid(DagInit))
1999 if (IsOutFileIndexCheckRequiredStr(CmdLine))
2003 void operator()(const DagInit* Test, unsigned, bool) {
2004 this->operator()(Test);
2006 void operator()(const Init* Statement, unsigned) {
2007 this->operator()(Statement);
2011 bool IsOutFileIndexCheckRequiredCase (Init* CmdLine) {
2013 WalkCase(CmdLine, Id(), IsOutFileIndexCheckRequiredStrCallback(&ret));
2017 /// IsOutFileIndexCheckRequired - Should we emit an "out_file_index != -1" check
2018 /// in EmitGenerateActionMethod() ?
2019 bool IsOutFileIndexCheckRequired (Init* CmdLine) {
2020 if (typeid(*CmdLine) == typeid(StringInit))
2021 return IsOutFileIndexCheckRequiredStr(CmdLine);
2023 return IsOutFileIndexCheckRequiredCase(CmdLine);
2026 void EmitGenerateActionMethodHeader(const ToolDescription& D,
2027 bool IsJoin, raw_ostream& O)
2030 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
2032 O.indent(Indent1) << "Action GenerateAction(const sys::Path& inFile,\n";
2034 O.indent(Indent2) << "bool HasChildren,\n";
2035 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
2036 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
2037 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
2038 O.indent(Indent1) << "{\n";
2039 O.indent(Indent2) << "std::string cmd;\n";
2040 O.indent(Indent2) << "std::vector<std::string> vec;\n";
2041 O.indent(Indent2) << "bool stop_compilation = !HasChildren;\n";
2042 O.indent(Indent2) << "const char* output_suffix = \""
2043 << D.OutputSuffix << "\";\n";
2046 // EmitGenerateActionMethod - Emit either a normal or a "join" version of the
2047 // Tool::GenerateAction() method.
2048 void EmitGenerateActionMethod (const ToolDescription& D,
2049 const OptionDescriptions& OptDescs,
2050 bool IsJoin, raw_ostream& O) {
2052 EmitGenerateActionMethodHeader(D, IsJoin, O);
2055 throw "Tool " + D.Name + " has no cmd_line property!";
2057 bool IndexCheckRequired = IsOutFileIndexCheckRequired(D.CmdLine);
2058 O.indent(Indent2) << "int out_file_index"
2059 << (IndexCheckRequired ? " = -1" : "")
2062 // Process the cmd_line property.
2063 if (typeid(*D.CmdLine) == typeid(StringInit))
2064 EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
2066 EmitCaseConstructHandler(D.CmdLine, Indent2,
2067 EmitCmdLineVecFillCallback(IsJoin, D.Name),
2070 // For every understood option, emit handling code.
2072 EmitCaseConstructHandler(D.Actions, Indent2,
2073 EmitActionHandlersCallback(OptDescs),
2074 false, OptDescs, O);
2078 << "std::string out_file = OutFilename("
2079 << (IsJoin ? "sys::Path(),\n" : "inFile,\n");
2080 O.indent(Indent3) << "TempDir, stop_compilation, output_suffix).str();\n\n";
2082 if (IndexCheckRequired)
2083 O.indent(Indent2) << "if (out_file_index != -1)\n";
2084 O.indent(IndexCheckRequired ? Indent3 : Indent2)
2085 << "vec[out_file_index] = out_file;\n";
2087 // Handle the Sink property.
2089 O.indent(Indent2) << "if (!" << SinkOptionName << ".empty()) {\n";
2090 O.indent(Indent3) << "vec.insert(vec.end(), "
2091 << SinkOptionName << ".begin(), " << SinkOptionName
2093 O.indent(Indent2) << "}\n";
2096 O.indent(Indent2) << "return Action(cmd, vec, stop_compilation, out_file);\n";
2097 O.indent(Indent1) << "}\n\n";
2100 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
2101 /// a given Tool class.
2102 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
2103 const OptionDescriptions& OptDescs,
2105 if (!ToolDesc.isJoin()) {
2106 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
2107 O.indent(Indent2) << "bool HasChildren,\n";
2108 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
2109 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
2110 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
2111 O.indent(Indent1) << "{\n";
2112 O.indent(Indent2) << "throw std::runtime_error(\"" << ToolDesc.Name
2113 << " is not a Join tool!\");\n";
2114 O.indent(Indent1) << "}\n\n";
2117 EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
2120 EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
2123 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
2124 /// methods for a given Tool class.
2125 void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
2126 O.indent(Indent1) << "const char** InputLanguages() const {\n";
2127 O.indent(Indent2) << "return InputLanguages_;\n";
2128 O.indent(Indent1) << "}\n\n";
2130 if (D.OutLanguage.empty())
2131 throw "Tool " + D.Name + " has no 'out_language' property!";
2133 O.indent(Indent1) << "const char* OutputLanguage() const {\n";
2134 O.indent(Indent2) << "return \"" << D.OutLanguage << "\";\n";
2135 O.indent(Indent1) << "}\n\n";
2138 /// EmitNameMethod - Emit the Name() method for a given Tool class.
2139 void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
2140 O.indent(Indent1) << "const char* Name() const {\n";
2141 O.indent(Indent2) << "return \"" << D.Name << "\";\n";
2142 O.indent(Indent1) << "}\n\n";
2145 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
2147 void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
2148 O.indent(Indent1) << "bool IsJoin() const {\n";
2150 O.indent(Indent2) << "return true;\n";
2152 O.indent(Indent2) << "return false;\n";
2153 O.indent(Indent1) << "}\n\n";
2156 /// EmitStaticMemberDefinitions - Emit static member definitions for a
2157 /// given Tool class.
2158 void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
2159 if (D.InLanguage.empty())
2160 throw "Tool " + D.Name + " has no 'in_language' property!";
2162 O << "const char* " << D.Name << "::InputLanguages_[] = {";
2163 for (StrVector::const_iterator B = D.InLanguage.begin(),
2164 E = D.InLanguage.end(); B != E; ++B)
2165 O << '\"' << *B << "\", ";
2169 /// EmitToolClassDefinition - Emit a Tool class definition.
2170 void EmitToolClassDefinition (const ToolDescription& D,
2171 const OptionDescriptions& OptDescs,
2173 if (D.Name == "root")
2177 O << "class " << D.Name << " : public ";
2183 O << " {\nprivate:\n";
2184 O.indent(Indent1) << "static const char* InputLanguages_[];\n\n";
2187 EmitNameMethod(D, O);
2188 EmitInOutLanguageMethods(D, O);
2189 EmitIsJoinMethod(D, O);
2190 EmitGenerateActionMethods(D, OptDescs, O);
2192 // Close class definition
2195 EmitStaticMemberDefinitions(D, O);
2199 /// EmitOptionDefinitions - Iterate over a list of option descriptions
2200 /// and emit registration code.
2201 void EmitOptionDefinitions (const OptionDescriptions& descs,
2202 bool HasSink, bool HasExterns,
2205 std::vector<OptionDescription> Aliases;
2207 // Emit static cl::Option variables.
2208 for (OptionDescriptions::const_iterator B = descs.begin(),
2209 E = descs.end(); B!=E; ++B) {
2210 const OptionDescription& val = B->second;
2212 if (val.Type == OptionType::Alias) {
2213 Aliases.push_back(val);
2220 O << val.GenTypeDeclaration() << ' '
2221 << val.GenVariableName();
2223 if (val.isExtern()) {
2228 O << "(\"" << val.Name << "\"\n";
2230 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
2231 O << ", cl::Prefix";
2233 if (val.isRequired()) {
2234 if (val.isList() && !val.isMultiVal())
2235 O << ", cl::OneOrMore";
2237 O << ", cl::Required";
2239 else if (val.isOneOrMore() && val.isList()) {
2240 O << ", cl::OneOrMore";
2242 else if (val.isOptional() && val.isList()) {
2243 O << ", cl::Optional";
2246 if (val.isReallyHidden())
2247 O << ", cl::ReallyHidden";
2248 else if (val.isHidden())
2249 O << ", cl::Hidden";
2251 if (val.isCommaSeparated())
2252 O << ", cl::CommaSeparated";
2254 if (val.MultiVal > 1)
2255 O << ", cl::multi_val(" << val.MultiVal << ')';
2258 const std::string& str = val.InitVal->getAsString();
2259 O << ", cl::init(" << str << ')';
2262 if (!val.Help.empty())
2263 O << ", cl::desc(\"" << val.Help << "\")";
2268 // Emit the aliases (they should go after all the 'proper' options).
2269 for (std::vector<OptionDescription>::const_iterator
2270 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
2271 const OptionDescription& val = *B;
2273 O << val.GenTypeDeclaration() << ' '
2274 << val.GenVariableName()
2275 << "(\"" << val.Name << '\"';
2277 const OptionDescription& D = descs.FindOption(val.Help);
2278 O << ", cl::aliasopt(" << D.GenVariableName() << ")";
2280 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
2283 // Emit the sink option.
2285 O << (HasExterns ? "extern cl" : "cl")
2286 << "::list<std::string> " << SinkOptionName
2287 << (HasExterns ? ";\n" : "(cl::Sink);\n");
2292 /// EmitPreprocessOptionsCallback - Helper function passed to
2293 /// EmitCaseConstructHandler() by EmitPreprocessOptions().
2295 class EmitPreprocessOptionsCallback;
2298 (EmitPreprocessOptionsCallback::* EmitPreprocessOptionsCallbackHandler)
2299 (const DagInit&, unsigned, raw_ostream&) const;
2301 class EmitPreprocessOptionsCallback :
2302 public ActionHandlingCallbackBase,
2303 public HandlerTable<EmitPreprocessOptionsCallbackHandler>
2305 typedef EmitPreprocessOptionsCallbackHandler Handler;
2307 (EmitPreprocessOptionsCallback::* HandlerImpl)
2308 (const Init*, unsigned, raw_ostream&) const;
2310 const OptionDescriptions& OptDescs_;
2312 void onListOrDag(HandlerImpl h,
2313 const DagInit& d, unsigned IndentLevel, raw_ostream& O) const
2315 checkNumberOfArguments(d, 1);
2316 const Init* I = d.getArg(0);
2318 // If I is a list, apply h to each element.
2319 if (typeid(*I) == typeid(ListInit)) {
2320 const ListInit& L = *static_cast<const ListInit*>(I);
2321 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B)
2322 ((this)->*(h))(*B, IndentLevel, O);
2324 // Otherwise, apply h to I.
2326 ((this)->*(h))(I, IndentLevel, O);
2330 void onUnsetOptionImpl(const Init* I,
2331 unsigned IndentLevel, raw_ostream& O) const
2333 const std::string& OptName = InitPtrToString(I);
2334 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2336 if (OptDesc.isSwitch()) {
2337 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = false;\n";
2339 else if (OptDesc.isParameter()) {
2340 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = \"\";\n";
2342 else if (OptDesc.isList()) {
2343 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2346 throw "Can't apply 'unset_option' to alias option '" + OptName + "'!";
2350 void onUnsetOption(const DagInit& d,
2351 unsigned IndentLevel, raw_ostream& O) const
2353 this->onListOrDag(&EmitPreprocessOptionsCallback::onUnsetOptionImpl,
2357 void onSetListOrParameter(const DagInit& d,
2358 unsigned IndentLevel, raw_ostream& O) const {
2359 checkNumberOfArguments(d, 2);
2360 const std::string& OptName = InitPtrToString(d.getArg(0));
2361 const Init* Value = d.getArg(1);
2362 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2364 if (OptDesc.isList()) {
2365 const ListInit& List = InitPtrToList(Value);
2367 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2368 for (ListInit::const_iterator B = List.begin(), E = List.end();
2370 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".push_back(\""
2371 << InitPtrToString(*B) << "\");\n";
2374 else if (OptDesc.isParameter()) {
2375 const std::string& Str = InitPtrToString(Value);
2376 O.indent(IndentLevel) << OptDesc.GenVariableName()
2377 << " = \"" << Str << "\";\n";
2380 throw "set_option: -" + OptName + ": is not a list or parameter option!";
2384 void onSetSwitch(const Init* I,
2385 unsigned IndentLevel, raw_ostream& O) const {
2386 const std::string& OptName = InitPtrToString(I);
2387 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2389 if (OptDesc.isSwitch())
2390 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = true;\n";
2392 throw "set_option: -" + OptName + " is not a switch option!";
2395 void onSetOption(const DagInit& d,
2396 unsigned IndentLevel, raw_ostream& O) const
2398 checkNumberOfArguments(d, 1);
2400 // Two arguments: (set_option "parameter", VALUE), where VALUE is either a
2401 // string or a string list.
2402 if (d.getNumArgs() > 1)
2403 this->onSetListOrParameter(d, IndentLevel, O);
2404 // One argument: (set_option "switch")
2405 // or (set_option ["switch1", "switch2", ...])
2407 this->onListOrDag(&EmitPreprocessOptionsCallback::onSetSwitch,
2413 EmitPreprocessOptionsCallback(const OptionDescriptions& OptDescs)
2414 : OptDescs_(OptDescs)
2416 if (!staticMembersInitialized_) {
2417 AddHandler("error", &EmitPreprocessOptionsCallback::onErrorDag);
2418 AddHandler("warning", &EmitPreprocessOptionsCallback::onWarningDag);
2419 AddHandler("unset_option", &EmitPreprocessOptionsCallback::onUnsetOption);
2420 AddHandler("set_option", &EmitPreprocessOptionsCallback::onSetOption);
2422 staticMembersInitialized_ = true;
2426 void operator()(const Init* I,
2427 unsigned IndentLevel, raw_ostream& O) const
2429 InvokeDagInitHandler(this, I, IndentLevel, O);
2434 /// EmitPreprocessOptions - Emit the PreprocessOptionsLocal() function.
2435 void EmitPreprocessOptions (const RecordKeeper& Records,
2436 const OptionDescriptions& OptDecs, raw_ostream& O)
2438 O << "void PreprocessOptionsLocal() {\n";
2440 const RecordVector& OptionPreprocessors =
2441 Records.getAllDerivedDefinitions("OptionPreprocessor");
2443 for (RecordVector::const_iterator B = OptionPreprocessors.begin(),
2444 E = OptionPreprocessors.end(); B!=E; ++B) {
2445 DagInit* Case = (*B)->getValueAsDag("preprocessor");
2446 EmitCaseConstructHandler(Case, Indent1,
2447 EmitPreprocessOptionsCallback(OptDecs),
2454 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMapLocal() function.
2455 void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
2457 O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
2459 // Get the relevant field out of RecordKeeper
2460 const Record* LangMapRecord = Records.getDef("LanguageMap");
2462 // It is allowed for a plugin to have no language map.
2463 if (LangMapRecord) {
2465 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
2466 if (!LangsToSuffixesList)
2467 throw "Error in the language map definition!";
2469 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
2470 const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
2472 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
2473 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
2475 for (unsigned i = 0; i < Suffixes->size(); ++i)
2476 O.indent(Indent1) << "langMap[\""
2477 << InitPtrToString(Suffixes->getElement(i))
2478 << "\"] = \"" << Lang << "\";\n";
2485 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
2486 /// by EmitEdgeClass().
2487 void IncDecWeight (const Init* i, unsigned IndentLevel,
2489 const DagInit& d = InitPtrToDag(i);
2490 const std::string& OpName = GetOperatorName(d);
2492 if (OpName == "inc_weight") {
2493 O.indent(IndentLevel) << "ret += ";
2495 else if (OpName == "dec_weight") {
2496 O.indent(IndentLevel) << "ret -= ";
2498 else if (OpName == "error") {
2499 checkNumberOfArguments(d, 1);
2500 O.indent(IndentLevel) << "throw std::runtime_error(\""
2501 << InitPtrToString(d.getArg(0))
2506 throw "Unknown operator in edge properties list: '" + OpName + "'!"
2507 "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
2510 if (d.getNumArgs() > 0)
2511 O << InitPtrToInt(d.getArg(0)) << ";\n";
2517 /// EmitEdgeClass - Emit a single Edge# class.
2518 void EmitEdgeClass (unsigned N, const std::string& Target,
2519 DagInit* Case, const OptionDescriptions& OptDescs,
2522 // Class constructor.
2523 O << "class Edge" << N << ": public Edge {\n"
2525 O.indent(Indent1) << "Edge" << N << "() : Edge(\"" << Target
2528 // Function Weight().
2530 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n";
2531 O.indent(Indent2) << "unsigned ret = 0;\n";
2533 // Handle the 'case' construct.
2534 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
2536 O.indent(Indent2) << "return ret;\n";
2537 O.indent(Indent1) << "};\n\n};\n\n";
2540 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
2541 void EmitEdgeClasses (const RecordVector& EdgeVector,
2542 const OptionDescriptions& OptDescs,
2545 for (RecordVector::const_iterator B = EdgeVector.begin(),
2546 E = EdgeVector.end(); B != E; ++B) {
2547 const Record* Edge = *B;
2548 const std::string& NodeB = Edge->getValueAsString("b");
2549 DagInit& Weight = *Edge->getValueAsDag("weight");
2551 if (!isDagEmpty(Weight))
2552 EmitEdgeClass(i, NodeB, &Weight, OptDescs, O);
2557 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraphLocal()
2559 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
2560 const ToolDescriptions& ToolDescs,
2563 O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
2565 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2566 E = ToolDescs.end(); B != E; ++B)
2567 O.indent(Indent1) << "G.insertNode(new " << (*B)->Name << "());\n";
2574 for (RecordVector::const_iterator B = EdgeVector.begin(),
2575 E = EdgeVector.end(); B != E; ++B) {
2576 const Record* Edge = *B;
2577 const std::string& NodeA = Edge->getValueAsString("a");
2578 const std::string& NodeB = Edge->getValueAsString("b");
2579 DagInit& Weight = *Edge->getValueAsDag("weight");
2581 O.indent(Indent1) << "G.insertEdge(\"" << NodeA << "\", ";
2583 if (isDagEmpty(Weight))
2584 O << "new SimpleEdge(\"" << NodeB << "\")";
2586 O << "new Edge" << i << "()";
2595 /// HookInfo - Information about the hook type and number of arguments.
2598 // A hook can either have a single parameter of type std::vector<std::string>,
2599 // or NumArgs parameters of type const char*.
2600 enum HookType { ListHook, ArgHook };
2605 HookInfo() : Type(ArgHook), NumArgs(1)
2608 HookInfo(HookType T) : Type(T), NumArgs(1)
2611 HookInfo(unsigned N) : Type(ArgHook), NumArgs(N)
2615 typedef llvm::StringMap<HookInfo> HookInfoMap;
2617 /// ExtractHookNames - Extract the hook names from all instances of
2618 /// $CALL(HookName) in the provided command line string/action. Helper
2619 /// function used by FillInHookNames().
2620 class ExtractHookNames {
2621 HookInfoMap& HookNames_;
2622 const OptionDescriptions& OptDescs_;
2624 ExtractHookNames(HookInfoMap& HookNames, const OptionDescriptions& OptDescs)
2625 : HookNames_(HookNames), OptDescs_(OptDescs)
2628 void onAction (const DagInit& Dag) {
2629 const std::string& Name = GetOperatorName(Dag);
2631 if (Name == "forward_transformed_value") {
2632 checkNumberOfArguments(Dag, 2);
2633 const std::string& OptName = InitPtrToString(Dag.getArg(0));
2634 const std::string& HookName = InitPtrToString(Dag.getArg(1));
2635 const OptionDescription& D = OptDescs_.FindOption(OptName);
2637 HookNames_[HookName] = HookInfo(D.isList() ? HookInfo::ListHook
2638 : HookInfo::ArgHook);
2640 else if (Name == "append_cmd" || Name == "output_suffix") {
2641 checkNumberOfArguments(Dag, 1);
2642 this->onCmdLine(InitPtrToString(Dag.getArg(0)));
2646 void onCmdLine(const std::string& Cmd) {
2648 TokenizeCmdLine(Cmd, cmds);
2650 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
2652 const std::string& cmd = *B;
2654 if (cmd == "$CALL") {
2655 unsigned NumArgs = 0;
2656 checkedIncrement(B, E, "Syntax error in $CALL invocation!");
2657 const std::string& HookName = *B;
2659 if (HookName.at(0) == ')')
2660 throw "$CALL invoked with no arguments!";
2662 while (++B != E && B->at(0) != ')') {
2666 HookInfoMap::const_iterator H = HookNames_.find(HookName);
2668 if (H != HookNames_.end() && H->second.NumArgs != NumArgs &&
2669 H->second.Type != HookInfo::ArgHook)
2670 throw "Overloading of hooks is not allowed. Overloaded hook: "
2673 HookNames_[HookName] = HookInfo(NumArgs);
2678 void operator()(const Init* Arg) {
2680 // We're invoked on an action (either a dag or a dag list).
2681 if (typeid(*Arg) == typeid(DagInit)) {
2682 const DagInit& Dag = InitPtrToDag(Arg);
2683 this->onAction(Dag);
2686 else if (typeid(*Arg) == typeid(ListInit)) {
2687 const ListInit& List = InitPtrToList(Arg);
2688 for (ListInit::const_iterator B = List.begin(), E = List.end(); B != E;
2690 const DagInit& Dag = InitPtrToDag(*B);
2691 this->onAction(Dag);
2696 // We're invoked on a command line.
2697 this->onCmdLine(InitPtrToString(Arg));
2700 void operator()(const DagInit* Test, unsigned, bool) {
2701 this->operator()(Test);
2703 void operator()(const Init* Statement, unsigned) {
2704 this->operator()(Statement);
2708 /// FillInHookNames - Actually extract the hook names from all command
2709 /// line strings. Helper function used by EmitHookDeclarations().
2710 void FillInHookNames(const ToolDescriptions& ToolDescs,
2711 const OptionDescriptions& OptDescs,
2712 HookInfoMap& HookNames)
2714 // For all tool descriptions:
2715 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2716 E = ToolDescs.end(); B != E; ++B) {
2717 const ToolDescription& D = *(*B);
2719 // Look for 'forward_transformed_value' in 'actions'.
2721 WalkCase(D.Actions, Id(), ExtractHookNames(HookNames, OptDescs));
2723 // Look for hook invocations in 'cmd_line'.
2726 if (dynamic_cast<StringInit*>(D.CmdLine))
2727 // This is a string.
2728 ExtractHookNames(HookNames, OptDescs).operator()(D.CmdLine);
2730 // This is a 'case' construct.
2731 WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames, OptDescs));
2735 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
2736 /// property records and emit hook function declaration for each
2737 /// instance of $CALL(HookName).
2738 void EmitHookDeclarations(const ToolDescriptions& ToolDescs,
2739 const OptionDescriptions& OptDescs, raw_ostream& O) {
2740 HookInfoMap HookNames;
2742 FillInHookNames(ToolDescs, OptDescs, HookNames);
2743 if (HookNames.empty())
2746 O << "namespace hooks {\n";
2747 for (HookInfoMap::const_iterator B = HookNames.begin(),
2748 E = HookNames.end(); B != E; ++B) {
2749 const char* HookName = B->first();
2750 const HookInfo& Info = B->second;
2752 O.indent(Indent1) << "std::string " << HookName << "(";
2754 if (Info.Type == HookInfo::ArgHook) {
2755 for (unsigned i = 0, j = Info.NumArgs; i < j; ++i) {
2756 O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
2760 O << "const std::vector<std::string>& Arg";
2768 /// EmitRegisterPlugin - Emit code to register this plugin.
2769 void EmitRegisterPlugin(int Priority, raw_ostream& O) {
2770 O << "struct Plugin : public llvmc::BasePlugin {\n\n";
2771 O.indent(Indent1) << "int Priority() const { return "
2772 << Priority << "; }\n\n";
2773 O.indent(Indent1) << "void PreprocessOptions() const\n";
2774 O.indent(Indent1) << "{ PreprocessOptionsLocal(); }\n\n";
2775 O.indent(Indent1) << "void PopulateLanguageMap(LanguageMap& langMap) const\n";
2776 O.indent(Indent1) << "{ PopulateLanguageMapLocal(langMap); }\n\n";
2778 << "void PopulateCompilationGraph(CompilationGraph& graph) const\n";
2779 O.indent(Indent1) << "{ PopulateCompilationGraphLocal(graph); }\n"
2781 << "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
2784 /// EmitIncludes - Emit necessary #include directives and some
2785 /// additional declarations.
2786 void EmitIncludes(raw_ostream& O) {
2787 O << "#include \"llvm/CompilerDriver/BuiltinOptions.h\"\n"
2788 << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
2789 << "#include \"llvm/CompilerDriver/ForceLinkageMacros.h\"\n"
2790 << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
2791 << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
2793 << "#include \"llvm/Support/CommandLine.h\"\n"
2794 << "#include \"llvm/Support/raw_ostream.h\"\n\n"
2796 << "#include <algorithm>\n"
2797 << "#include <cstdlib>\n"
2798 << "#include <iterator>\n"
2799 << "#include <stdexcept>\n\n"
2801 << "using namespace llvm;\n"
2802 << "using namespace llvmc;\n\n"
2804 << "extern cl::opt<std::string> OutputFilename;\n\n"
2806 << "inline const char* checkCString(const char* s)\n"
2807 << "{ return s == NULL ? \"\" : s; }\n\n";
2811 /// PluginData - Holds all information about a plugin.
2813 OptionDescriptions OptDescs;
2816 ToolDescriptions ToolDescs;
2821 /// HasSink - Go through the list of tool descriptions and check if
2822 /// there are any with the 'sink' property set.
2823 bool HasSink(const ToolDescriptions& ToolDescs) {
2824 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2825 E = ToolDescs.end(); B != E; ++B)
2832 /// HasExterns - Go through the list of option descriptions and check
2833 /// if there are any external options.
2834 bool HasExterns(const OptionDescriptions& OptDescs) {
2835 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
2836 E = OptDescs.end(); B != E; ++B)
2837 if (B->second.isExtern())
2843 /// CollectPluginData - Collect tool and option properties,
2844 /// compilation graph edges and plugin priority from the parse tree.
2845 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
2846 // Collect option properties.
2847 const RecordVector& OptionLists =
2848 Records.getAllDerivedDefinitions("OptionList");
2849 CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
2852 // Collect tool properties.
2853 const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
2854 CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
2855 Data.HasSink = HasSink(Data.ToolDescs);
2856 Data.HasExterns = HasExterns(Data.OptDescs);
2858 // Collect compilation graph edges.
2859 const RecordVector& CompilationGraphs =
2860 Records.getAllDerivedDefinitions("CompilationGraph");
2861 FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
2864 // Calculate the priority of this plugin.
2865 const RecordVector& Priorities =
2866 Records.getAllDerivedDefinitions("PluginPriority");
2867 Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
2870 /// CheckPluginData - Perform some sanity checks on the collected data.
2871 void CheckPluginData(PluginData& Data) {
2872 // Filter out all tools not mentioned in the compilation graph.
2873 FilterNotInGraph(Data.Edges, Data.ToolDescs);
2875 // Typecheck the compilation graph.
2876 TypecheckGraph(Data.Edges, Data.ToolDescs);
2878 // Check that there are no options without side effects (specified
2879 // only in the OptionList).
2880 CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
2884 void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
2885 // Emit file header.
2888 // Emit global option registration code.
2889 EmitOptionDefinitions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
2891 // Emit hook declarations.
2892 EmitHookDeclarations(Data.ToolDescs, Data.OptDescs, O);
2894 O << "namespace {\n\n";
2896 // Emit PreprocessOptionsLocal() function.
2897 EmitPreprocessOptions(Records, Data.OptDescs, O);
2899 // Emit PopulateLanguageMapLocal() function
2900 // (language map maps from file extensions to language names).
2901 EmitPopulateLanguageMap(Records, O);
2903 // Emit Tool classes.
2904 for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
2905 E = Data.ToolDescs.end(); B!=E; ++B)
2906 EmitToolClassDefinition(*(*B), Data.OptDescs, O);
2908 // Emit Edge# classes.
2909 EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
2911 // Emit PopulateCompilationGraphLocal() function.
2912 EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
2914 // Emit code for plugin registration.
2915 EmitRegisterPlugin(Data.Priority, O);
2917 O << "} // End anonymous namespace.\n\n";
2919 // Force linkage magic.
2920 O << "namespace llvmc {\n";
2921 O << "LLVMC_FORCE_LINKAGE_DECL(LLVMC_PLUGIN_NAME) {}\n";
2928 // End of anonymous namespace
2931 /// run - The back-end entry point.
2932 void LLVMCConfigurationEmitter::run (raw_ostream &O) {
2936 CollectPluginData(Records, Data);
2937 CheckPluginData(Data);
2939 EmitSourceFileHeader("LLVMC Configuration Library", O);
2940 EmitPluginCode(Data, O);
2942 } catch (std::exception& Error) {
2943 throw Error.what() + std::string(" - usually this means a syntax error.");