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"
32 //===----------------------------------------------------------------------===//
35 typedef std::vector<Record*> RecordVector;
36 typedef std::vector<std::string> StrVector;
38 //===----------------------------------------------------------------------===//
42 const unsigned TabWidth = 4;
43 const unsigned Indent1 = TabWidth*1;
44 const unsigned Indent2 = TabWidth*2;
45 const unsigned Indent3 = TabWidth*3;
47 // Default help string.
48 const char * const DefaultHelpString = "NO HELP MESSAGE PROVIDED";
50 // Name for the "sink" option.
51 const char * const SinkOptionName = "AutoGeneratedSinkOption";
53 //===----------------------------------------------------------------------===//
56 /// Id - An 'identity' function object.
59 void operator()(const T0&) const {
61 template<typename T0, typename T1>
62 void operator()(const T0&, const T1&) const {
64 template<typename T0, typename T1, typename T2>
65 void operator()(const T0&, const T1&, const T2&) const {
69 int InitPtrToInt(const Init* ptr) {
70 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
71 return val.getValue();
74 const std::string& InitPtrToString(const Init* ptr) {
75 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
76 return val.getValue();
79 const ListInit& InitPtrToList(const Init* ptr) {
80 const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
84 const DagInit& InitPtrToDag(const Init* ptr) {
85 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
89 const std::string GetOperatorName(const DagInit& D) {
90 return D.getOperator()->getAsString();
93 /// CheckBooleanConstant - Check that the provided value is a boolean constant.
94 void CheckBooleanConstant(const Init* I) {
95 const DefInit& val = dynamic_cast<const DefInit&>(*I);
96 const std::string& str = val.getAsString();
98 if (str != "true" && str != "false") {
99 throw "Incorrect boolean value: '" + str +
100 "': must be either 'true' or 'false'";
104 // CheckNumberOfArguments - Ensure that the number of args in d is
105 // greater than or equal to min_arguments, otherwise throw an exception.
106 void CheckNumberOfArguments (const DagInit& d, unsigned minArgs) {
107 if (d.getNumArgs() < minArgs)
108 throw GetOperatorName(d) + ": too few arguments!";
111 // IsDagEmpty - is this DAG marked with an empty marker?
112 bool IsDagEmpty (const DagInit& d) {
113 return GetOperatorName(d) == "empty_dag_marker";
116 // EscapeVariableName - Escape commas and other symbols not allowed
117 // in the C++ variable names. Makes it possible to use options named
118 // like "Wa," (useful for prefix options).
119 std::string EscapeVariableName (const std::string& Var) {
121 for (unsigned i = 0; i != Var.size(); ++i) {
122 char cur_char = Var[i];
123 if (cur_char == ',') {
126 else if (cur_char == '+') {
129 else if (cur_char == '-') {
133 ret.push_back(cur_char);
139 /// EscapeQuotes - Replace '"' with '\"'.
140 std::string EscapeQuotes (const std::string& Var) {
142 for (unsigned i = 0; i != Var.size(); ++i) {
143 char cur_char = Var[i];
144 if (cur_char == '"') {
148 ret.push_back(cur_char);
154 /// OneOf - Does the input string contain this character?
155 bool OneOf(const char* lst, char c) {
163 template <class I, class S>
164 void CheckedIncrement(I& P, I E, S ErrorString) {
170 // apply is needed because C++'s syntax doesn't let us construct a function
171 // object and call it in the same statement.
172 template<typename F, typename T0>
173 void apply(F Fun, T0& Arg0) {
177 template<typename F, typename T0, typename T1>
178 void apply(F Fun, T0& Arg0, T1& Arg1) {
179 return Fun(Arg0, Arg1);
182 //===----------------------------------------------------------------------===//
183 /// Back-end specific code
186 /// OptionType - One of six different option types. See the
187 /// documentation for detailed description of differences.
188 namespace OptionType {
190 enum OptionType { Alias, Switch, Parameter, ParameterList,
193 bool IsAlias(OptionType t) {
197 bool IsList (OptionType t) {
198 return (t == ParameterList || t == PrefixList);
201 bool IsSwitch (OptionType t) {
202 return (t == Switch);
205 bool IsParameter (OptionType t) {
206 return (t == Parameter || t == Prefix);
211 OptionType::OptionType stringToOptionType(const std::string& T) {
212 if (T == "alias_option")
213 return OptionType::Alias;
214 else if (T == "switch_option")
215 return OptionType::Switch;
216 else if (T == "parameter_option")
217 return OptionType::Parameter;
218 else if (T == "parameter_list_option")
219 return OptionType::ParameterList;
220 else if (T == "prefix_option")
221 return OptionType::Prefix;
222 else if (T == "prefix_list_option")
223 return OptionType::PrefixList;
225 throw "Unknown option type: " + T + '!';
228 namespace OptionDescriptionFlags {
229 enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
230 ReallyHidden = 0x4, Extern = 0x8,
231 OneOrMore = 0x10, Optional = 0x20,
232 CommaSeparated = 0x40 };
235 /// OptionDescription - Represents data contained in a single
236 /// OptionList entry.
237 struct OptionDescription {
238 OptionType::OptionType Type;
245 OptionDescription(OptionType::OptionType t = OptionType::Switch,
246 const std::string& n = "",
247 const std::string& h = DefaultHelpString)
248 : Type(t), Name(n), Flags(0x0), Help(h), MultiVal(1), InitVal(0)
251 /// GenTypeDeclaration - Returns the C++ variable type of this
253 const char* GenTypeDeclaration() const;
255 /// GenVariableName - Returns the variable name used in the
256 /// generated C++ code.
257 std::string GenVariableName() const;
259 /// Merge - Merge two option descriptions.
260 void Merge (const OptionDescription& other);
262 // Misc convenient getters/setters.
264 bool isAlias() const;
266 bool isMultiVal() const;
268 bool isCommaSeparated() const;
269 void setCommaSeparated();
271 bool isExtern() const;
274 bool isRequired() const;
277 bool isOneOrMore() const;
280 bool isOptional() const;
283 bool isHidden() const;
286 bool isReallyHidden() const;
287 void setReallyHidden();
289 bool isSwitch() const
290 { return OptionType::IsSwitch(this->Type); }
292 bool isParameter() const
293 { return OptionType::IsParameter(this->Type); }
296 { return OptionType::IsList(this->Type); }
300 void OptionDescription::Merge (const OptionDescription& other)
302 if (other.Type != Type)
303 throw "Conflicting definitions for the option " + Name + "!";
305 if (Help == other.Help || Help == DefaultHelpString)
307 else if (other.Help != DefaultHelpString) {
308 llvm::errs() << "Warning: several different help strings"
309 " defined for option " + Name + "\n";
312 Flags |= other.Flags;
315 bool OptionDescription::isAlias() const {
316 return OptionType::IsAlias(this->Type);
319 bool OptionDescription::isMultiVal() const {
323 bool OptionDescription::isCommaSeparated() const {
324 return Flags & OptionDescriptionFlags::CommaSeparated;
326 void OptionDescription::setCommaSeparated() {
327 Flags |= OptionDescriptionFlags::CommaSeparated;
330 bool OptionDescription::isExtern() const {
331 return Flags & OptionDescriptionFlags::Extern;
333 void OptionDescription::setExtern() {
334 Flags |= OptionDescriptionFlags::Extern;
337 bool OptionDescription::isRequired() const {
338 return Flags & OptionDescriptionFlags::Required;
340 void OptionDescription::setRequired() {
341 Flags |= OptionDescriptionFlags::Required;
344 bool OptionDescription::isOneOrMore() const {
345 return Flags & OptionDescriptionFlags::OneOrMore;
347 void OptionDescription::setOneOrMore() {
348 Flags |= OptionDescriptionFlags::OneOrMore;
351 bool OptionDescription::isOptional() const {
352 return Flags & OptionDescriptionFlags::Optional;
354 void OptionDescription::setOptional() {
355 Flags |= OptionDescriptionFlags::Optional;
358 bool OptionDescription::isHidden() const {
359 return Flags & OptionDescriptionFlags::Hidden;
361 void OptionDescription::setHidden() {
362 Flags |= OptionDescriptionFlags::Hidden;
365 bool OptionDescription::isReallyHidden() const {
366 return Flags & OptionDescriptionFlags::ReallyHidden;
368 void OptionDescription::setReallyHidden() {
369 Flags |= OptionDescriptionFlags::ReallyHidden;
372 const char* OptionDescription::GenTypeDeclaration() const {
374 case OptionType::Alias:
376 case OptionType::PrefixList:
377 case OptionType::ParameterList:
378 return "cl::list<std::string>";
379 case OptionType::Switch:
380 return "cl::opt<bool>";
381 case OptionType::Parameter:
382 case OptionType::Prefix:
384 return "cl::opt<std::string>";
388 std::string OptionDescription::GenVariableName() const {
389 const std::string& EscapedName = EscapeVariableName(Name);
391 case OptionType::Alias:
392 return "AutoGeneratedAlias_" + EscapedName;
393 case OptionType::PrefixList:
394 case OptionType::ParameterList:
395 return "AutoGeneratedList_" + EscapedName;
396 case OptionType::Switch:
397 return "AutoGeneratedSwitch_" + EscapedName;
398 case OptionType::Prefix:
399 case OptionType::Parameter:
401 return "AutoGeneratedParameter_" + EscapedName;
405 /// OptionDescriptions - An OptionDescription array plus some helper
407 class OptionDescriptions {
408 typedef StringMap<OptionDescription> container_type;
410 /// Descriptions - A list of OptionDescriptions.
411 container_type Descriptions;
414 /// FindOption - exception-throwing wrapper for find().
415 const OptionDescription& FindOption(const std::string& OptName) const;
417 // Wrappers for FindOption that throw an exception in case the option has a
419 const OptionDescription& FindSwitch(const std::string& OptName) const;
420 const OptionDescription& FindParameter(const std::string& OptName) const;
421 const OptionDescription& FindList(const std::string& OptName) const;
422 const OptionDescription&
423 FindListOrParameter(const std::string& OptName) const;
425 /// insertDescription - Insert new OptionDescription into
426 /// OptionDescriptions list
427 void InsertDescription (const OptionDescription& o);
429 // Support for STL-style iteration
430 typedef container_type::const_iterator const_iterator;
431 const_iterator begin() const { return Descriptions.begin(); }
432 const_iterator end() const { return Descriptions.end(); }
435 const OptionDescription&
436 OptionDescriptions::FindOption(const std::string& OptName) const {
437 const_iterator I = Descriptions.find(OptName);
438 if (I != Descriptions.end())
441 throw OptName + ": no such option!";
444 const OptionDescription&
445 OptionDescriptions::FindSwitch(const std::string& OptName) const {
446 const OptionDescription& OptDesc = this->FindOption(OptName);
447 if (!OptDesc.isSwitch())
448 throw OptName + ": incorrect option type - should be a switch!";
452 const OptionDescription&
453 OptionDescriptions::FindList(const std::string& OptName) const {
454 const OptionDescription& OptDesc = this->FindOption(OptName);
455 if (!OptDesc.isList())
456 throw OptName + ": incorrect option type - should be a list!";
460 const OptionDescription&
461 OptionDescriptions::FindParameter(const std::string& OptName) const {
462 const OptionDescription& OptDesc = this->FindOption(OptName);
463 if (!OptDesc.isParameter())
464 throw OptName + ": incorrect option type - should be a parameter!";
468 const OptionDescription&
469 OptionDescriptions::FindListOrParameter(const std::string& OptName) const {
470 const OptionDescription& OptDesc = this->FindOption(OptName);
471 if (!OptDesc.isList() && !OptDesc.isParameter())
473 + ": incorrect option type - should be a list or parameter!";
477 void OptionDescriptions::InsertDescription (const OptionDescription& o) {
478 container_type::iterator I = Descriptions.find(o.Name);
479 if (I != Descriptions.end()) {
480 OptionDescription& D = I->second;
484 Descriptions[o.Name] = o;
488 /// HandlerTable - A base class for function objects implemented as
489 /// 'tables of handlers'.
490 template <typename Handler>
493 // Implementation details.
495 /// HandlerMap - A map from property names to property handlers
496 typedef StringMap<Handler> HandlerMap;
498 static HandlerMap Handlers_;
499 static bool staticMembersInitialized_;
503 Handler GetHandler (const std::string& HandlerName) const {
504 typename HandlerMap::iterator method = Handlers_.find(HandlerName);
506 if (method != Handlers_.end()) {
507 Handler h = method->second;
511 throw "No handler found for property " + HandlerName + "!";
515 void AddHandler(const char* Property, Handler H) {
516 Handlers_[Property] = H;
521 template <class Handler, class FunctionObject>
522 Handler GetHandler(FunctionObject* Obj, const DagInit& Dag) {
523 const std::string& HandlerName = GetOperatorName(Dag);
524 return Obj->GetHandler(HandlerName);
527 template <class FunctionObject>
528 void InvokeDagInitHandler(FunctionObject* Obj, Init* I) {
529 typedef void (FunctionObject::*Handler) (const DagInit&);
531 const DagInit& Dag = InitPtrToDag(I);
532 Handler h = GetHandler<Handler>(Obj, Dag);
537 template <class FunctionObject>
538 void InvokeDagInitHandler(const FunctionObject* const Obj,
539 const Init* I, unsigned IndentLevel, raw_ostream& O)
541 typedef void (FunctionObject::*Handler)
542 (const DagInit&, unsigned IndentLevel, raw_ostream& O) const;
544 const DagInit& Dag = InitPtrToDag(I);
545 Handler h = GetHandler<Handler>(Obj, Dag);
547 ((Obj)->*(h))(Dag, IndentLevel, O);
551 template <typename H>
552 typename HandlerTable<H>::HandlerMap HandlerTable<H>::Handlers_;
554 template <typename H>
555 bool HandlerTable<H>::staticMembersInitialized_ = false;
558 /// CollectOptionProperties - Function object for iterating over an
559 /// option property list.
560 class CollectOptionProperties;
561 typedef void (CollectOptionProperties::* CollectOptionPropertiesHandler)
564 class CollectOptionProperties
565 : public HandlerTable<CollectOptionPropertiesHandler>
569 /// optDescs_ - OptionDescriptions table. This is where the
570 /// information is stored.
571 OptionDescription& optDesc_;
575 explicit CollectOptionProperties(OptionDescription& OD)
578 if (!staticMembersInitialized_) {
579 AddHandler("extern", &CollectOptionProperties::onExtern);
580 AddHandler("help", &CollectOptionProperties::onHelp);
581 AddHandler("hidden", &CollectOptionProperties::onHidden);
582 AddHandler("init", &CollectOptionProperties::onInit);
583 AddHandler("multi_val", &CollectOptionProperties::onMultiVal);
584 AddHandler("one_or_more", &CollectOptionProperties::onOneOrMore);
585 AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
586 AddHandler("required", &CollectOptionProperties::onRequired);
587 AddHandler("optional", &CollectOptionProperties::onOptional);
588 AddHandler("comma_separated", &CollectOptionProperties::onCommaSeparated);
590 staticMembersInitialized_ = true;
594 /// operator() - Just forwards to the corresponding property
596 void operator() (Init* I) {
597 InvokeDagInitHandler(this, I);
602 /// Option property handlers --
603 /// Methods that handle option properties such as (help) or (hidden).
605 void onExtern (const DagInit& d) {
606 CheckNumberOfArguments(d, 0);
607 optDesc_.setExtern();
610 void onHelp (const DagInit& d) {
611 CheckNumberOfArguments(d, 1);
612 optDesc_.Help = EscapeQuotes(InitPtrToString(d.getArg(0)));
615 void onHidden (const DagInit& d) {
616 CheckNumberOfArguments(d, 0);
617 optDesc_.setHidden();
620 void onReallyHidden (const DagInit& d) {
621 CheckNumberOfArguments(d, 0);
622 optDesc_.setReallyHidden();
625 void onCommaSeparated (const DagInit& d) {
626 CheckNumberOfArguments(d, 0);
627 if (!optDesc_.isList())
628 throw "'comma_separated' is valid only on list options!";
629 optDesc_.setCommaSeparated();
632 void onRequired (const DagInit& d) {
633 CheckNumberOfArguments(d, 0);
634 if (optDesc_.isOneOrMore() || optDesc_.isOptional())
635 throw "Only one of (required), (optional) or "
636 "(one_or_more) properties is allowed!";
637 optDesc_.setRequired();
640 void onInit (const DagInit& d) {
641 CheckNumberOfArguments(d, 1);
642 Init* i = d.getArg(0);
643 const std::string& str = i->getAsString();
645 bool correct = optDesc_.isParameter() && dynamic_cast<StringInit*>(i);
646 correct |= (optDesc_.isSwitch() && (str == "true" || str == "false"));
649 throw "Incorrect usage of the 'init' option property!";
651 optDesc_.InitVal = i;
654 void onOneOrMore (const DagInit& d) {
655 CheckNumberOfArguments(d, 0);
656 if (optDesc_.isRequired() || optDesc_.isOptional())
657 throw "Only one of (required), (optional) or "
658 "(one_or_more) properties is allowed!";
659 if (!OptionType::IsList(optDesc_.Type))
660 llvm::errs() << "Warning: specifying the 'one_or_more' property "
661 "on a non-list option will have no effect.\n";
662 optDesc_.setOneOrMore();
665 void onOptional (const DagInit& d) {
666 CheckNumberOfArguments(d, 0);
667 if (optDesc_.isRequired() || optDesc_.isOneOrMore())
668 throw "Only one of (required), (optional) or "
669 "(one_or_more) properties is allowed!";
670 if (!OptionType::IsList(optDesc_.Type))
671 llvm::errs() << "Warning: specifying the 'optional' property"
672 "on a non-list option will have no effect.\n";
673 optDesc_.setOptional();
676 void onMultiVal (const DagInit& d) {
677 CheckNumberOfArguments(d, 1);
678 int val = InitPtrToInt(d.getArg(0));
680 throw "Error in the 'multi_val' property: "
681 "the value must be greater than 1!";
682 if (!OptionType::IsList(optDesc_.Type))
683 throw "The multi_val property is valid only on list options!";
684 optDesc_.MultiVal = val;
689 /// AddOption - A function object that is applied to every option
690 /// description. Used by CollectOptionDescriptions.
693 OptionDescriptions& OptDescs_;
696 explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
699 void operator()(const Init* i) {
700 const DagInit& d = InitPtrToDag(i);
701 CheckNumberOfArguments(d, 1);
703 const OptionType::OptionType Type =
704 stringToOptionType(GetOperatorName(d));
705 const std::string& Name = InitPtrToString(d.getArg(0));
707 OptionDescription OD(Type, Name);
710 CheckNumberOfArguments(d, 2);
713 // Aliases store the aliased option name in the 'Help' field.
714 OD.Help = InitPtrToString(d.getArg(1));
716 else if (!OD.isExtern()) {
717 processOptionProperties(d, OD);
719 OptDescs_.InsertDescription(OD);
723 /// processOptionProperties - Go through the list of option
724 /// properties and call a corresponding handler for each.
725 static void processOptionProperties (const DagInit& d, OptionDescription& o) {
726 CheckNumberOfArguments(d, 2);
727 DagInit::const_arg_iterator B = d.arg_begin();
728 // Skip the first argument: it's always the option name.
730 std::for_each(B, d.arg_end(), CollectOptionProperties(o));
735 /// CollectOptionDescriptions - Collects option properties from all
737 void CollectOptionDescriptions (RecordVector::const_iterator B,
738 RecordVector::const_iterator E,
739 OptionDescriptions& OptDescs)
741 // For every OptionList:
743 RecordVector::value_type T = *B;
744 // Throws an exception if the value does not exist.
745 ListInit* PropList = T->getValueAsListInit("options");
747 // For every option description in this list:
748 // collect the information and
749 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
753 // Tool information record
755 namespace ToolFlags {
756 enum ToolFlags { Join = 0x1, Sink = 0x2 };
759 struct ToolDescription : public RefCountedBase<ToolDescription> {
763 StrVector InLanguage;
764 std::string OutLanguage;
765 std::string OutputSuffix;
768 // Various boolean properties
769 void setSink() { Flags |= ToolFlags::Sink; }
770 bool isSink() const { return Flags & ToolFlags::Sink; }
771 void setJoin() { Flags |= ToolFlags::Join; }
772 bool isJoin() const { return Flags & ToolFlags::Join; }
774 // Default ctor here is needed because StringMap can only store
775 // DefaultConstructible objects
776 ToolDescription() : CmdLine(0), Actions(0), Flags(0) {}
777 ToolDescription (const std::string& n)
778 : Name(n), CmdLine(0), Actions(0), Flags(0)
782 /// ToolDescriptions - A list of Tool information records.
783 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
786 /// CollectToolProperties - Function object for iterating over a list of
787 /// tool property records.
789 class CollectToolProperties;
790 typedef void (CollectToolProperties::* CollectToolPropertiesHandler)
793 class CollectToolProperties : public HandlerTable<CollectToolPropertiesHandler>
797 /// toolDesc_ - Properties of the current Tool. This is where the
798 /// information is stored.
799 ToolDescription& toolDesc_;
803 explicit CollectToolProperties (ToolDescription& d)
806 if (!staticMembersInitialized_) {
808 AddHandler("actions", &CollectToolProperties::onActions);
809 AddHandler("cmd_line", &CollectToolProperties::onCmdLine);
810 AddHandler("in_language", &CollectToolProperties::onInLanguage);
811 AddHandler("join", &CollectToolProperties::onJoin);
812 AddHandler("out_language", &CollectToolProperties::onOutLanguage);
813 AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
814 AddHandler("sink", &CollectToolProperties::onSink);
816 staticMembersInitialized_ = true;
820 void operator() (Init* I) {
821 InvokeDagInitHandler(this, I);
826 /// Property handlers --
827 /// Functions that extract information about tool properties from
828 /// DAG representation.
830 void onActions (const DagInit& d) {
831 CheckNumberOfArguments(d, 1);
832 Init* Case = d.getArg(0);
833 if (typeid(*Case) != typeid(DagInit) ||
834 GetOperatorName(static_cast<DagInit&>(*Case)) != "case")
835 throw "The argument to (actions) should be a 'case' construct!";
836 toolDesc_.Actions = Case;
839 void onCmdLine (const DagInit& d) {
840 CheckNumberOfArguments(d, 1);
841 toolDesc_.CmdLine = d.getArg(0);
844 void onInLanguage (const DagInit& d) {
845 CheckNumberOfArguments(d, 1);
846 Init* arg = d.getArg(0);
848 // Find out the argument's type.
849 if (typeid(*arg) == typeid(StringInit)) {
851 toolDesc_.InLanguage.push_back(InitPtrToString(arg));
855 const ListInit& lst = InitPtrToList(arg);
856 StrVector& out = toolDesc_.InLanguage;
858 // Copy strings to the output vector.
859 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
861 out.push_back(InitPtrToString(*B));
864 // Remove duplicates.
865 std::sort(out.begin(), out.end());
866 StrVector::iterator newE = std::unique(out.begin(), out.end());
867 out.erase(newE, out.end());
871 void onJoin (const DagInit& d) {
872 CheckNumberOfArguments(d, 0);
876 void onOutLanguage (const DagInit& d) {
877 CheckNumberOfArguments(d, 1);
878 toolDesc_.OutLanguage = InitPtrToString(d.getArg(0));
881 void onOutputSuffix (const DagInit& d) {
882 CheckNumberOfArguments(d, 1);
883 toolDesc_.OutputSuffix = InitPtrToString(d.getArg(0));
886 void onSink (const DagInit& d) {
887 CheckNumberOfArguments(d, 0);
893 /// CollectToolDescriptions - Gather information about tool properties
894 /// from the parsed TableGen data (basically a wrapper for the
895 /// CollectToolProperties function object).
896 void CollectToolDescriptions (RecordVector::const_iterator B,
897 RecordVector::const_iterator E,
898 ToolDescriptions& ToolDescs)
900 // Iterate over a properties list of every Tool definition
902 const Record* T = *B;
903 // Throws an exception if the value does not exist.
904 ListInit* PropList = T->getValueAsListInit("properties");
906 IntrusiveRefCntPtr<ToolDescription>
907 ToolDesc(new ToolDescription(T->getName()));
909 std::for_each(PropList->begin(), PropList->end(),
910 CollectToolProperties(*ToolDesc));
911 ToolDescs.push_back(ToolDesc);
915 /// FillInEdgeVector - Merge all compilation graph definitions into
916 /// one single edge list.
917 void FillInEdgeVector(RecordVector::const_iterator B,
918 RecordVector::const_iterator E, RecordVector& Out) {
919 for (; B != E; ++B) {
920 const ListInit* edges = (*B)->getValueAsListInit("edges");
922 for (unsigned i = 0; i < edges->size(); ++i)
923 Out.push_back(edges->getElementAsRecord(i));
927 /// CalculatePriority - Calculate the priority of this plugin.
928 int CalculatePriority(RecordVector::const_iterator B,
929 RecordVector::const_iterator E) {
933 priority = static_cast<int>((*B)->getValueAsInt("priority"));
936 throw "More than one 'PluginPriority' instance found: "
937 "most probably an error!";
943 /// NotInGraph - Helper function object for FilterNotInGraph.
946 const llvm::StringSet<>& ToolsInGraph_;
949 NotInGraph(const llvm::StringSet<>& ToolsInGraph)
950 : ToolsInGraph_(ToolsInGraph)
953 bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
954 return (ToolsInGraph_.count(x->Name) == 0);
958 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
959 /// mentioned in the compilation graph definition.
960 void FilterNotInGraph (const RecordVector& EdgeVector,
961 ToolDescriptions& ToolDescs) {
963 // List all tools mentioned in the graph.
964 llvm::StringSet<> ToolsInGraph;
966 for (RecordVector::const_iterator B = EdgeVector.begin(),
967 E = EdgeVector.end(); B != E; ++B) {
969 const Record* Edge = *B;
970 const std::string& NodeA = Edge->getValueAsString("a");
971 const std::string& NodeB = Edge->getValueAsString("b");
974 ToolsInGraph.insert(NodeA);
975 ToolsInGraph.insert(NodeB);
978 // Filter ToolPropertiesList.
979 ToolDescriptions::iterator new_end =
980 std::remove_if(ToolDescs.begin(), ToolDescs.end(),
981 NotInGraph(ToolsInGraph));
982 ToolDescs.erase(new_end, ToolDescs.end());
985 /// FillInToolToLang - Fills in two tables that map tool names to
986 /// (input, output) languages. Helper function used by TypecheckGraph().
987 void FillInToolToLang (const ToolDescriptions& ToolDescs,
988 StringMap<StringSet<> >& ToolToInLang,
989 StringMap<std::string>& ToolToOutLang) {
990 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
991 E = ToolDescs.end(); B != E; ++B) {
992 const ToolDescription& D = *(*B);
993 for (StrVector::const_iterator B = D.InLanguage.begin(),
994 E = D.InLanguage.end(); B != E; ++B)
995 ToolToInLang[D.Name].insert(*B);
996 ToolToOutLang[D.Name] = D.OutLanguage;
1000 /// TypecheckGraph - Check that names for output and input languages
1001 /// on all edges do match. This doesn't do much when the information
1002 /// about the whole graph is not available (i.e. when compiling most
1004 void TypecheckGraph (const RecordVector& EdgeVector,
1005 const ToolDescriptions& ToolDescs) {
1006 StringMap<StringSet<> > ToolToInLang;
1007 StringMap<std::string> ToolToOutLang;
1009 FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
1010 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
1011 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
1013 for (RecordVector::const_iterator B = EdgeVector.begin(),
1014 E = EdgeVector.end(); B != E; ++B) {
1015 const Record* Edge = *B;
1016 const std::string& NodeA = Edge->getValueAsString("a");
1017 const std::string& NodeB = Edge->getValueAsString("b");
1018 StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
1019 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
1021 if (NodeA != "root") {
1022 if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
1023 throw "Edge " + NodeA + "->" + NodeB
1024 + ": output->input language mismatch";
1027 if (NodeB == "root")
1028 throw "Edges back to the root are not allowed!";
1032 /// WalkCase - Walks the 'case' expression DAG and invokes
1033 /// TestCallback on every test, and StatementCallback on every
1034 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
1035 /// combinators (that is, they are passed directly to TestCallback).
1036 /// TestCallback must have type 'void TestCallback(const DagInit*, unsigned
1037 /// IndentLevel, bool FirstTest)'.
1038 /// StatementCallback must have type 'void StatementCallback(const Init*,
1039 /// unsigned IndentLevel)'.
1040 template <typename F1, typename F2>
1041 void WalkCase(const Init* Case, F1 TestCallback, F2 StatementCallback,
1042 unsigned IndentLevel = 0)
1044 const DagInit& d = InitPtrToDag(Case);
1047 if (GetOperatorName(d) != "case")
1048 throw "WalkCase should be invoked only on 'case' expressions!";
1050 if (d.getNumArgs() < 2)
1051 throw "There should be at least one clause in the 'case' expression:\n"
1056 const unsigned numArgs = d.getNumArgs();
1058 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1065 const DagInit& Test = InitPtrToDag(arg);
1067 if (GetOperatorName(Test) == "default" && (i+1 != numArgs))
1068 throw "The 'default' clause should be the last in the "
1069 "'case' construct!";
1071 throw "Case construct handler: no corresponding action "
1072 "found for the test " + Test.getAsString() + '!';
1074 TestCallback(Test, IndentLevel, (i == 1));
1078 if (dynamic_cast<DagInit*>(arg)
1079 && GetOperatorName(static_cast<DagInit&>(*arg)) == "case") {
1081 WalkCase(arg, TestCallback, StatementCallback, IndentLevel + Indent1);
1084 // Handle statement.
1085 StatementCallback(arg, IndentLevel);
1093 /// ExtractOptionNames - A helper function object used by
1094 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
1095 class ExtractOptionNames {
1096 llvm::StringSet<>& OptionNames_;
1098 void processDag(const Init* Statement) {
1099 const DagInit& Stmt = InitPtrToDag(Statement);
1100 const std::string& ActionName = GetOperatorName(Stmt);
1101 if (ActionName == "forward" || ActionName == "forward_as" ||
1102 ActionName == "forward_value" ||
1103 ActionName == "forward_transformed_value" ||
1104 ActionName == "switch_on" || ActionName == "any_switch_on" ||
1105 ActionName == "parameter_equals" ||
1106 ActionName == "element_in_list" || ActionName == "not_empty" ||
1107 ActionName == "empty") {
1108 CheckNumberOfArguments(Stmt, 1);
1110 Init* Arg = Stmt.getArg(0);
1111 if (typeid(*Arg) == typeid(StringInit)) {
1112 const std::string& Name = InitPtrToString(Arg);
1113 OptionNames_.insert(Name);
1117 const ListInit& List = InitPtrToList(Arg);
1118 for (ListInit::const_iterator B = List.begin(), E = List.end();
1120 const std::string& Name = InitPtrToString(*B);
1121 OptionNames_.insert(Name);
1125 else if (ActionName == "and" || ActionName == "or" || ActionName == "not") {
1126 for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
1127 this->processDag(Stmt.getArg(i));
1133 ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
1136 void operator()(const Init* Statement) {
1137 if (typeid(*Statement) == typeid(ListInit)) {
1138 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1139 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1141 this->processDag(*B);
1144 this->processDag(Statement);
1148 void operator()(const DagInit& Test, unsigned, bool) {
1149 this->operator()(&Test);
1151 void operator()(const Init* Statement, unsigned) {
1152 this->operator()(Statement);
1156 /// CheckForSuperfluousOptions - Check that there are no side
1157 /// effect-free options (specified only in the OptionList). Otherwise,
1158 /// output a warning.
1159 void CheckForSuperfluousOptions (const RecordVector& Edges,
1160 const ToolDescriptions& ToolDescs,
1161 const OptionDescriptions& OptDescs) {
1162 llvm::StringSet<> nonSuperfluousOptions;
1164 // Add all options mentioned in the ToolDesc.Actions to the set of
1165 // non-superfluous options.
1166 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1167 E = ToolDescs.end(); B != E; ++B) {
1168 const ToolDescription& TD = *(*B);
1169 ExtractOptionNames Callback(nonSuperfluousOptions);
1171 WalkCase(TD.Actions, Callback, Callback);
1174 // Add all options mentioned in the 'case' clauses of the
1175 // OptionalEdges of the compilation graph to the set of
1176 // non-superfluous options.
1177 for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
1179 const Record* Edge = *B;
1180 DagInit& Weight = *Edge->getValueAsDag("weight");
1182 if (!IsDagEmpty(Weight))
1183 WalkCase(&Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
1186 // Check that all options in OptDescs belong to the set of
1187 // non-superfluous options.
1188 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
1189 E = OptDescs.end(); B != E; ++B) {
1190 const OptionDescription& Val = B->second;
1191 if (!nonSuperfluousOptions.count(Val.Name)
1192 && Val.Type != OptionType::Alias)
1193 llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! "
1194 "Probable cause: this option is specified only in the OptionList.\n";
1198 /// EmitCaseTest0Args - Helper function used by EmitCaseConstructHandler().
1199 bool EmitCaseTest0Args(const std::string& TestName, raw_ostream& O) {
1200 if (TestName == "single_input_file") {
1201 O << "InputFilenames.size() == 1";
1204 else if (TestName == "multiple_input_files") {
1205 O << "InputFilenames.size() > 1";
1212 /// EmitListTest - Helper function used by EmitCaseTest1ArgList().
1213 template <typename F>
1214 void EmitListTest(const ListInit& L, const char* LogicOp,
1215 F Callback, raw_ostream& O)
1217 // This is a lot like EmitLogicalOperationTest, but works on ListInits instead
1219 bool isFirst = true;
1220 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B) {
1224 O << ' ' << LogicOp << ' ';
1225 Callback(InitPtrToString(*B), O);
1229 // Callbacks for use with EmitListTest.
1231 class EmitSwitchOn {
1232 const OptionDescriptions& OptDescs_;
1234 EmitSwitchOn(const OptionDescriptions& OptDescs) : OptDescs_(OptDescs)
1237 void operator()(const std::string& OptName, raw_ostream& O) const {
1238 const OptionDescription& OptDesc = OptDescs_.FindSwitch(OptName);
1239 O << OptDesc.GenVariableName();
1243 class EmitEmptyTest {
1245 const OptionDescriptions& OptDescs_;
1247 EmitEmptyTest(bool EmitNegate, const OptionDescriptions& OptDescs)
1248 : EmitNegate_(EmitNegate), OptDescs_(OptDescs)
1251 void operator()(const std::string& OptName, raw_ostream& O) const {
1252 const char* Neg = (EmitNegate_ ? "!" : "");
1253 if (OptName == "o") {
1254 O << Neg << "OutputFilename.empty()";
1256 else if (OptName == "save-temps") {
1257 O << Neg << "(SaveTemps == SaveTempsEnum::Unset)";
1260 const OptionDescription& OptDesc = OptDescs_.FindListOrParameter(OptName);
1261 O << Neg << OptDesc.GenVariableName() << ".empty()";
1267 /// EmitCaseTest1ArgList - Helper function used by EmitCaseTest1Arg();
1268 bool EmitCaseTest1ArgList(const std::string& TestName,
1270 const OptionDescriptions& OptDescs,
1272 const ListInit& L = InitPtrToList(d.getArg(0));
1274 if (TestName == "any_switch_on") {
1275 EmitListTest(L, "||", EmitSwitchOn(OptDescs), O);
1278 else if (TestName == "switch_on") {
1279 EmitListTest(L, "&&", EmitSwitchOn(OptDescs), O);
1282 else if (TestName == "any_not_empty") {
1283 EmitListTest(L, "||", EmitEmptyTest(true, OptDescs), O);
1286 else if (TestName == "any_empty") {
1287 EmitListTest(L, "||", EmitEmptyTest(false, OptDescs), O);
1290 else if (TestName == "not_empty") {
1291 EmitListTest(L, "&&", EmitEmptyTest(true, OptDescs), O);
1294 else if (TestName == "empty") {
1295 EmitListTest(L, "&&", EmitEmptyTest(false, OptDescs), O);
1302 /// EmitCaseTest1ArgStr - Helper function used by EmitCaseTest1Arg();
1303 bool EmitCaseTest1ArgStr(const std::string& TestName,
1305 const OptionDescriptions& OptDescs,
1307 const std::string& OptName = InitPtrToString(d.getArg(0));
1309 if (TestName == "switch_on") {
1310 apply(EmitSwitchOn(OptDescs), OptName, O);
1313 else if (TestName == "input_languages_contain") {
1314 O << "InLangs.count(\"" << OptName << "\") != 0";
1317 else if (TestName == "in_language") {
1318 // This works only for single-argument Tool::GenerateAction. Join
1319 // tools can process several files in different languages simultaneously.
1321 // TODO: make this work with Edge::Weight (if possible).
1322 O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
1325 else if (TestName == "not_empty" || TestName == "empty") {
1326 bool EmitNegate = (TestName == "not_empty");
1327 apply(EmitEmptyTest(EmitNegate, OptDescs), OptName, O);
1334 /// EmitCaseTest1Arg - Helper function used by EmitCaseConstructHandler();
1335 bool EmitCaseTest1Arg(const std::string& TestName,
1337 const OptionDescriptions& OptDescs,
1339 CheckNumberOfArguments(d, 1);
1340 if (typeid(*d.getArg(0)) == typeid(ListInit))
1341 return EmitCaseTest1ArgList(TestName, d, OptDescs, O);
1343 return EmitCaseTest1ArgStr(TestName, d, OptDescs, O);
1346 /// EmitCaseTest2Args - Helper function used by EmitCaseConstructHandler().
1347 bool EmitCaseTest2Args(const std::string& TestName,
1349 unsigned IndentLevel,
1350 const OptionDescriptions& OptDescs,
1352 CheckNumberOfArguments(d, 2);
1353 const std::string& OptName = InitPtrToString(d.getArg(0));
1354 const std::string& OptArg = InitPtrToString(d.getArg(1));
1356 if (TestName == "parameter_equals") {
1357 const OptionDescription& OptDesc = OptDescs.FindParameter(OptName);
1358 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
1361 else if (TestName == "element_in_list") {
1362 const OptionDescription& OptDesc = OptDescs.FindList(OptName);
1363 const std::string& VarName = OptDesc.GenVariableName();
1364 O << "std::find(" << VarName << ".begin(),\n";
1365 O.indent(IndentLevel + Indent1)
1366 << VarName << ".end(), \""
1367 << OptArg << "\") != " << VarName << ".end()";
1374 // Forward declaration.
1375 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
1376 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1377 const OptionDescriptions& OptDescs,
1380 /// EmitLogicalOperationTest - Helper function used by
1381 /// EmitCaseConstructHandler.
1382 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
1383 unsigned IndentLevel,
1384 const OptionDescriptions& OptDescs,
1387 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
1388 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
1389 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1390 if (j != NumArgs - 1) {
1392 O.indent(IndentLevel + Indent1) << ' ' << LogicOp << " (";
1400 void EmitLogicalNot(const DagInit& d, unsigned IndentLevel,
1401 const OptionDescriptions& OptDescs, raw_ostream& O)
1403 CheckNumberOfArguments(d, 1);
1404 const DagInit& InnerTest = InitPtrToDag(d.getArg(0));
1406 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1410 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
1411 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1412 const OptionDescriptions& OptDescs,
1414 const std::string& TestName = GetOperatorName(d);
1416 if (TestName == "and")
1417 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
1418 else if (TestName == "or")
1419 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
1420 else if (TestName == "not")
1421 EmitLogicalNot(d, IndentLevel, OptDescs, O);
1422 else if (EmitCaseTest0Args(TestName, O))
1424 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
1426 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
1429 throw "Unknown test '" + TestName + "' used in the 'case' construct!";
1433 /// EmitCaseTestCallback - Callback used by EmitCaseConstructHandler.
1434 class EmitCaseTestCallback {
1436 const OptionDescriptions& OptDescs_;
1440 EmitCaseTestCallback(bool EmitElseIf,
1441 const OptionDescriptions& OptDescs, raw_ostream& O)
1442 : EmitElseIf_(EmitElseIf), OptDescs_(OptDescs), O_(O)
1445 void operator()(const DagInit& Test, unsigned IndentLevel, bool FirstTest)
1447 if (GetOperatorName(Test) == "default") {
1448 O_.indent(IndentLevel) << "else {\n";
1451 O_.indent(IndentLevel)
1452 << ((!FirstTest && EmitElseIf_) ? "else if (" : "if (");
1453 EmitCaseTest(Test, IndentLevel, OptDescs_, O_);
1459 /// EmitCaseStatementCallback - Callback used by EmitCaseConstructHandler.
1460 template <typename F>
1461 class EmitCaseStatementCallback {
1466 EmitCaseStatementCallback(F Callback, raw_ostream& O)
1467 : Callback_(Callback), O_(O)
1470 void operator() (const Init* Statement, unsigned IndentLevel) {
1472 // Ignore nested 'case' DAG.
1473 if (!(dynamic_cast<const DagInit*>(Statement) &&
1474 GetOperatorName(static_cast<const DagInit&>(*Statement)) == "case")) {
1475 if (typeid(*Statement) == typeid(ListInit)) {
1476 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1477 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1479 Callback_(*B, (IndentLevel + Indent1), O_);
1482 Callback_(Statement, (IndentLevel + Indent1), O_);
1485 O_.indent(IndentLevel) << "}\n";
1490 /// EmitCaseConstructHandler - Emit code that handles the 'case'
1491 /// construct. Takes a function object that should emit code for every case
1492 /// clause. Implemented on top of WalkCase.
1493 /// Callback's type is void F(Init* Statement, unsigned IndentLevel,
1494 /// raw_ostream& O).
1495 /// EmitElseIf parameter controls the type of condition that is emitted ('if
1496 /// (..) {..} else if (..) {} .. else {..}' vs. 'if (..) {..} if(..) {..}
1498 template <typename F>
1499 void EmitCaseConstructHandler(const Init* Case, unsigned IndentLevel,
1500 F Callback, bool EmitElseIf,
1501 const OptionDescriptions& OptDescs,
1503 WalkCase(Case, EmitCaseTestCallback(EmitElseIf, OptDescs, O),
1504 EmitCaseStatementCallback<F>(Callback, O), IndentLevel);
1507 /// TokenizeCmdLine - converts from
1508 /// "$CALL(HookName, 'Arg1', 'Arg2')/path -arg1 -arg2" to
1509 /// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path", "-arg1", "-arg2"].
1510 void TokenizeCmdLine(const std::string& CmdLine, StrVector& Out) {
1511 const char* Delimiters = " \t\n\v\f\r";
1513 { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1516 if (CmdLine.empty())
1520 std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1523 for (; B != E; ++B) {
1524 char cur_ch = CmdLine[B];
1528 if (cur_ch == '$') {
1529 cur_st = SpecialCommand;
1532 if (OneOf(Delimiters, cur_ch)) {
1534 B = CmdLine.find_first_not_of(Delimiters, B);
1535 if (B == std::string::npos) {
1546 case SpecialCommand:
1547 if (OneOf(Delimiters, cur_ch)) {
1552 if (cur_ch == '(') {
1554 cur_st = InsideSpecialCommand;
1559 case InsideSpecialCommand:
1560 if (OneOf(Delimiters, cur_ch)) {
1563 if (cur_ch == '\'') {
1564 cur_st = InsideQuotationMarks;
1568 if (cur_ch == ')') {
1572 if (cur_ch == ',') {
1578 case InsideQuotationMarks:
1579 if (cur_ch == '\'') {
1580 cur_st = InsideSpecialCommand;
1586 Out.back().push_back(cur_ch);
1590 /// SubstituteCall - Given "$CALL(HookName, [Arg1 [, Arg2 [...]]])", output
1591 /// "hooks::HookName([Arg1 [, Arg2 [, ...]]])". Helper function used by
1592 /// SubstituteSpecialCommands().
1593 StrVector::const_iterator
1594 SubstituteCall (StrVector::const_iterator Pos,
1595 StrVector::const_iterator End,
1596 bool IsJoin, raw_ostream& O)
1598 const char* errorMessage = "Syntax error in $CALL invocation!";
1599 CheckedIncrement(Pos, End, errorMessage);
1600 const std::string& CmdName = *Pos;
1603 throw "$CALL invocation: empty argument list!";
1606 O << CmdName << "(";
1609 bool firstIteration = true;
1611 CheckedIncrement(Pos, End, errorMessage);
1612 const std::string& Arg = *Pos;
1613 assert(Arg.size() != 0);
1619 firstIteration = false;
1623 if (Arg == "$INFILE") {
1625 throw "$CALL(Hook, $INFILE) can't be used with a Join tool!";
1627 O << "inFile.c_str()";
1630 O << '"' << Arg << '"';
1639 /// SubstituteEnv - Given '$ENV(VAR_NAME)', output 'getenv("VAR_NAME")'. Helper
1640 /// function used by SubstituteSpecialCommands().
1641 StrVector::const_iterator
1642 SubstituteEnv (StrVector::const_iterator Pos,
1643 StrVector::const_iterator End, raw_ostream& O)
1645 const char* errorMessage = "Syntax error in $ENV invocation!";
1646 CheckedIncrement(Pos, End, errorMessage);
1647 const std::string& EnvName = *Pos;
1650 throw "$ENV invocation: empty argument list!";
1652 O << "checkCString(std::getenv(\"";
1656 CheckedIncrement(Pos, End, errorMessage);
1661 /// SubstituteSpecialCommands - Given an invocation of $CALL or $ENV, output
1662 /// handler code. Helper function used by EmitCmdLineVecFill().
1663 StrVector::const_iterator
1664 SubstituteSpecialCommands (StrVector::const_iterator Pos,
1665 StrVector::const_iterator End,
1666 bool IsJoin, raw_ostream& O)
1669 const std::string& cmd = *Pos;
1671 // Perform substitution.
1672 if (cmd == "$CALL") {
1673 Pos = SubstituteCall(Pos, End, IsJoin, O);
1675 else if (cmd == "$ENV") {
1676 Pos = SubstituteEnv(Pos, End, O);
1679 throw "Unknown special command: " + cmd;
1682 // Handle '$CMD(ARG)/additional/text'.
1683 const std::string& Leftover = *Pos;
1684 assert(Leftover.at(0) == ')');
1685 if (Leftover.size() != 1)
1686 O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1691 /// EmitCmdLineVecFill - Emit code that fills in the command line
1692 /// vector. Helper function used by EmitGenerateActionMethod().
1693 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1694 bool IsJoin, unsigned IndentLevel,
1697 TokenizeCmdLine(InitPtrToString(CmdLine), StrVec);
1700 throw "Tool '" + ToolName + "' has empty command line!";
1702 StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1704 // If there is a hook invocation on the place of the first command, skip it.
1705 assert(!StrVec[0].empty());
1706 if (StrVec[0][0] == '$') {
1707 while (I != E && (*I)[0] != ')' )
1710 // Skip the ')' symbol.
1717 bool hasINFILE = false;
1719 for (; I != E; ++I) {
1720 const std::string& cmd = *I;
1721 assert(!cmd.empty());
1722 O.indent(IndentLevel);
1723 if (cmd.at(0) == '$') {
1724 if (cmd == "$INFILE") {
1727 O << "for (PathVector::const_iterator B = inFiles.begin()"
1728 << ", E = inFiles.end();\n";
1729 O.indent(IndentLevel) << "B != E; ++B)\n";
1730 O.indent(IndentLevel + Indent1) << "vec.push_back(B->str());\n";
1733 O << "vec.push_back(inFile.str());\n";
1736 else if (cmd == "$OUTFILE") {
1737 O << "vec.push_back(\"\");\n";
1738 O.indent(IndentLevel) << "out_file_index = vec.size()-1;\n";
1741 O << "vec.push_back(";
1742 I = SubstituteSpecialCommands(I, E, IsJoin, O);
1747 O << "vec.push_back(\"" << cmd << "\");\n";
1751 throw "Tool '" + ToolName + "' doesn't take any input!";
1753 O.indent(IndentLevel) << "cmd = ";
1754 if (StrVec[0][0] == '$')
1755 SubstituteSpecialCommands(StrVec.begin(), StrVec.end(), IsJoin, O);
1757 O << '"' << StrVec[0] << '"';
1761 /// EmitCmdLineVecFillCallback - A function object wrapper around
1762 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1763 /// argument to EmitCaseConstructHandler().
1764 class EmitCmdLineVecFillCallback {
1766 const std::string& ToolName;
1768 EmitCmdLineVecFillCallback(bool J, const std::string& TN)
1769 : IsJoin(J), ToolName(TN) {}
1771 void operator()(const Init* Statement, unsigned IndentLevel,
1772 raw_ostream& O) const
1774 EmitCmdLineVecFill(Statement, ToolName, IsJoin, IndentLevel, O);
1778 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1779 /// implement EmitActionHandler. Emits code for
1780 /// handling the (forward) and (forward_as) option properties.
1781 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1782 unsigned IndentLevel,
1783 const std::string& NewName,
1785 const std::string& Name = NewName.empty()
1788 unsigned IndentLevel1 = IndentLevel + Indent1;
1791 case OptionType::Switch:
1792 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1794 case OptionType::Parameter:
1795 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "=\" + "
1796 << D.GenVariableName() << ");\n";
1798 case OptionType::Prefix:
1799 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\" + "
1800 << D.GenVariableName() << ");\n";
1802 case OptionType::PrefixList:
1803 O.indent(IndentLevel)
1804 << "for (" << D.GenTypeDeclaration()
1805 << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1806 O.indent(IndentLevel)
1807 << "E = " << D.GenVariableName() << ".end(); B != E;) {\n";
1808 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\" + " << "*B);\n";
1809 O.indent(IndentLevel1) << "++B;\n";
1811 for (int i = 1, j = D.MultiVal; i < j; ++i) {
1812 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1813 O.indent(IndentLevel1) << "++B;\n";
1816 O.indent(IndentLevel) << "}\n";
1818 case OptionType::ParameterList:
1819 O.indent(IndentLevel)
1820 << "for (" << D.GenTypeDeclaration() << "::iterator B = "
1821 << D.GenVariableName() << ".begin(),\n";
1822 O.indent(IndentLevel) << "E = " << D.GenVariableName()
1823 << ".end() ; B != E;) {\n";
1824 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\");\n";
1826 for (int i = 0, j = D.MultiVal; i < j; ++i) {
1827 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1828 O.indent(IndentLevel1) << "++B;\n";
1831 O.indent(IndentLevel) << "}\n";
1833 case OptionType::Alias:
1835 throw "Aliases are not allowed in tool option descriptions!";
1839 /// ActionHandlingCallbackBase - Base class of EmitActionHandlersCallback and
1840 /// EmitPreprocessOptionsCallback.
1841 struct ActionHandlingCallbackBase
1844 void onErrorDag(const DagInit& d,
1845 unsigned IndentLevel, raw_ostream& O) const
1847 O.indent(IndentLevel)
1848 << "throw std::runtime_error(\"" <<
1849 (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0))
1854 void onWarningDag(const DagInit& d,
1855 unsigned IndentLevel, raw_ostream& O) const
1857 CheckNumberOfArguments(d, 1);
1858 O.indent(IndentLevel) << "llvm::errs() << \""
1859 << InitPtrToString(d.getArg(0)) << "\";\n";
1864 /// EmitActionHandlersCallback - Emit code that handles actions. Used by
1865 /// EmitGenerateActionMethod() as an argument to EmitCaseConstructHandler().
1867 class EmitActionHandlersCallback;
1869 typedef void (EmitActionHandlersCallback::* EmitActionHandlersCallbackHandler)
1870 (const DagInit&, unsigned, raw_ostream&) const;
1872 class EmitActionHandlersCallback :
1873 public ActionHandlingCallbackBase,
1874 public HandlerTable<EmitActionHandlersCallbackHandler>
1876 typedef EmitActionHandlersCallbackHandler Handler;
1878 const OptionDescriptions& OptDescs;
1880 /// EmitHookInvocation - Common code for hook invocation from actions. Used by
1881 /// onAppendCmd and onOutputSuffix.
1882 void EmitHookInvocation(const std::string& Str,
1883 const char* BlockOpen, const char* BlockClose,
1884 unsigned IndentLevel, raw_ostream& O) const
1887 TokenizeCmdLine(Str, Out);
1889 for (StrVector::const_iterator B = Out.begin(), E = Out.end();
1891 const std::string& cmd = *B;
1893 O.indent(IndentLevel) << BlockOpen;
1895 if (cmd.at(0) == '$')
1896 B = SubstituteSpecialCommands(B, E, /* IsJoin = */ true, O);
1898 O << '"' << cmd << '"';
1904 void onAppendCmd (const DagInit& Dag,
1905 unsigned IndentLevel, raw_ostream& O) const
1907 CheckNumberOfArguments(Dag, 1);
1908 this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
1909 "vec.push_back(", ");\n", IndentLevel, O);
1912 void onForward (const DagInit& Dag,
1913 unsigned IndentLevel, raw_ostream& O) const
1915 CheckNumberOfArguments(Dag, 1);
1916 const std::string& Name = InitPtrToString(Dag.getArg(0));
1917 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1918 IndentLevel, "", O);
1921 void onForwardAs (const DagInit& Dag,
1922 unsigned IndentLevel, raw_ostream& O) const
1924 CheckNumberOfArguments(Dag, 2);
1925 const std::string& Name = InitPtrToString(Dag.getArg(0));
1926 const std::string& NewName = InitPtrToString(Dag.getArg(1));
1927 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1928 IndentLevel, NewName, O);
1931 void onForwardValue (const DagInit& Dag,
1932 unsigned IndentLevel, raw_ostream& O) const
1934 CheckNumberOfArguments(Dag, 1);
1935 const std::string& Name = InitPtrToString(Dag.getArg(0));
1936 const OptionDescription& D = OptDescs.FindListOrParameter(Name);
1938 if (D.isParameter()) {
1939 O.indent(IndentLevel) << "vec.push_back("
1940 << D.GenVariableName() << ");\n";
1943 O.indent(IndentLevel) << "std::copy(" << D.GenVariableName()
1944 << ".begin(), " << D.GenVariableName()
1945 << ".end(), std::back_inserter(vec));\n";
1949 void onForwardTransformedValue (const DagInit& Dag,
1950 unsigned IndentLevel, raw_ostream& O) const
1952 CheckNumberOfArguments(Dag, 2);
1953 const std::string& Name = InitPtrToString(Dag.getArg(0));
1954 const std::string& Hook = InitPtrToString(Dag.getArg(1));
1955 const OptionDescription& D = OptDescs.FindListOrParameter(Name);
1957 O.indent(IndentLevel) << "vec.push_back(" << "hooks::"
1958 << Hook << "(" << D.GenVariableName()
1959 << (D.isParameter() ? ".c_str()" : "") << "));\n";
1962 void onOutputSuffix (const DagInit& Dag,
1963 unsigned IndentLevel, raw_ostream& O) const
1965 CheckNumberOfArguments(Dag, 1);
1966 this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
1967 "output_suffix = ", ";\n", IndentLevel, O);
1970 void onStopCompilation (const DagInit& Dag,
1971 unsigned IndentLevel, raw_ostream& O) const
1973 O.indent(IndentLevel) << "stop_compilation = true;\n";
1977 void onUnpackValues (const DagInit& Dag,
1978 unsigned IndentLevel, raw_ostream& O) const
1980 throw "'unpack_values' is deprecated. "
1981 "Use 'comma_separated' + 'forward_value' instead!";
1986 explicit EmitActionHandlersCallback(const OptionDescriptions& OD)
1989 if (!staticMembersInitialized_) {
1990 AddHandler("error", &EmitActionHandlersCallback::onErrorDag);
1991 AddHandler("warning", &EmitActionHandlersCallback::onWarningDag);
1992 AddHandler("append_cmd", &EmitActionHandlersCallback::onAppendCmd);
1993 AddHandler("forward", &EmitActionHandlersCallback::onForward);
1994 AddHandler("forward_as", &EmitActionHandlersCallback::onForwardAs);
1995 AddHandler("forward_value", &EmitActionHandlersCallback::onForwardValue);
1996 AddHandler("forward_transformed_value",
1997 &EmitActionHandlersCallback::onForwardTransformedValue);
1998 AddHandler("output_suffix", &EmitActionHandlersCallback::onOutputSuffix);
1999 AddHandler("stop_compilation",
2000 &EmitActionHandlersCallback::onStopCompilation);
2001 AddHandler("unpack_values",
2002 &EmitActionHandlersCallback::onUnpackValues);
2004 staticMembersInitialized_ = true;
2008 void operator()(const Init* I,
2009 unsigned IndentLevel, raw_ostream& O) const
2011 InvokeDagInitHandler(this, I, IndentLevel, O);
2015 bool IsOutFileIndexCheckRequiredStr (const Init* CmdLine) {
2017 TokenizeCmdLine(InitPtrToString(CmdLine), StrVec);
2019 for (StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
2021 if (*I == "$OUTFILE")
2028 class IsOutFileIndexCheckRequiredStrCallback {
2032 IsOutFileIndexCheckRequiredStrCallback(bool* ret) : ret_(ret)
2035 void operator()(const Init* CmdLine) {
2036 // Ignore nested 'case' DAG.
2037 if (typeid(*CmdLine) == typeid(DagInit))
2040 if (IsOutFileIndexCheckRequiredStr(CmdLine))
2044 void operator()(const DagInit* Test, unsigned, bool) {
2045 this->operator()(Test);
2047 void operator()(const Init* Statement, unsigned) {
2048 this->operator()(Statement);
2052 bool IsOutFileIndexCheckRequiredCase (Init* CmdLine) {
2054 WalkCase(CmdLine, Id(), IsOutFileIndexCheckRequiredStrCallback(&ret));
2058 /// IsOutFileIndexCheckRequired - Should we emit an "out_file_index != -1" check
2059 /// in EmitGenerateActionMethod() ?
2060 bool IsOutFileIndexCheckRequired (Init* CmdLine) {
2061 if (typeid(*CmdLine) == typeid(StringInit))
2062 return IsOutFileIndexCheckRequiredStr(CmdLine);
2064 return IsOutFileIndexCheckRequiredCase(CmdLine);
2067 void EmitGenerateActionMethodHeader(const ToolDescription& D,
2068 bool IsJoin, raw_ostream& O)
2071 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
2073 O.indent(Indent1) << "Action GenerateAction(const sys::Path& inFile,\n";
2075 O.indent(Indent2) << "bool HasChildren,\n";
2076 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
2077 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
2078 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
2079 O.indent(Indent1) << "{\n";
2080 O.indent(Indent2) << "std::string cmd;\n";
2081 O.indent(Indent2) << "std::vector<std::string> vec;\n";
2082 O.indent(Indent2) << "bool stop_compilation = !HasChildren;\n";
2083 O.indent(Indent2) << "const char* output_suffix = \""
2084 << D.OutputSuffix << "\";\n";
2087 // EmitGenerateActionMethod - Emit either a normal or a "join" version of the
2088 // Tool::GenerateAction() method.
2089 void EmitGenerateActionMethod (const ToolDescription& D,
2090 const OptionDescriptions& OptDescs,
2091 bool IsJoin, raw_ostream& O) {
2093 EmitGenerateActionMethodHeader(D, IsJoin, O);
2096 throw "Tool " + D.Name + " has no cmd_line property!";
2098 bool IndexCheckRequired = IsOutFileIndexCheckRequired(D.CmdLine);
2099 O.indent(Indent2) << "int out_file_index"
2100 << (IndexCheckRequired ? " = -1" : "")
2103 // Process the cmd_line property.
2104 if (typeid(*D.CmdLine) == typeid(StringInit))
2105 EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
2107 EmitCaseConstructHandler(D.CmdLine, Indent2,
2108 EmitCmdLineVecFillCallback(IsJoin, D.Name),
2111 // For every understood option, emit handling code.
2113 EmitCaseConstructHandler(D.Actions, Indent2,
2114 EmitActionHandlersCallback(OptDescs),
2115 false, OptDescs, O);
2119 << "std::string out_file = OutFilename("
2120 << (IsJoin ? "sys::Path(),\n" : "inFile,\n");
2121 O.indent(Indent3) << "TempDir, stop_compilation, output_suffix).str();\n\n";
2123 if (IndexCheckRequired)
2124 O.indent(Indent2) << "if (out_file_index != -1)\n";
2125 O.indent(IndexCheckRequired ? Indent3 : Indent2)
2126 << "vec[out_file_index] = out_file;\n";
2128 // Handle the Sink property.
2130 O.indent(Indent2) << "if (!" << SinkOptionName << ".empty()) {\n";
2131 O.indent(Indent3) << "vec.insert(vec.end(), "
2132 << SinkOptionName << ".begin(), " << SinkOptionName
2134 O.indent(Indent2) << "}\n";
2137 O.indent(Indent2) << "return Action(cmd, vec, stop_compilation, out_file);\n";
2138 O.indent(Indent1) << "}\n\n";
2141 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
2142 /// a given Tool class.
2143 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
2144 const OptionDescriptions& OptDescs,
2146 if (!ToolDesc.isJoin()) {
2147 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
2148 O.indent(Indent2) << "bool HasChildren,\n";
2149 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
2150 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
2151 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
2152 O.indent(Indent1) << "{\n";
2153 O.indent(Indent2) << "throw std::runtime_error(\"" << ToolDesc.Name
2154 << " is not a Join tool!\");\n";
2155 O.indent(Indent1) << "}\n\n";
2158 EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
2161 EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
2164 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
2165 /// methods for a given Tool class.
2166 void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
2167 O.indent(Indent1) << "const char** InputLanguages() const {\n";
2168 O.indent(Indent2) << "return InputLanguages_;\n";
2169 O.indent(Indent1) << "}\n\n";
2171 if (D.OutLanguage.empty())
2172 throw "Tool " + D.Name + " has no 'out_language' property!";
2174 O.indent(Indent1) << "const char* OutputLanguage() const {\n";
2175 O.indent(Indent2) << "return \"" << D.OutLanguage << "\";\n";
2176 O.indent(Indent1) << "}\n\n";
2179 /// EmitNameMethod - Emit the Name() method for a given Tool class.
2180 void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
2181 O.indent(Indent1) << "const char* Name() const {\n";
2182 O.indent(Indent2) << "return \"" << D.Name << "\";\n";
2183 O.indent(Indent1) << "}\n\n";
2186 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
2188 void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
2189 O.indent(Indent1) << "bool IsJoin() const {\n";
2191 O.indent(Indent2) << "return true;\n";
2193 O.indent(Indent2) << "return false;\n";
2194 O.indent(Indent1) << "}\n\n";
2197 /// EmitStaticMemberDefinitions - Emit static member definitions for a
2198 /// given Tool class.
2199 void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
2200 if (D.InLanguage.empty())
2201 throw "Tool " + D.Name + " has no 'in_language' property!";
2203 O << "const char* " << D.Name << "::InputLanguages_[] = {";
2204 for (StrVector::const_iterator B = D.InLanguage.begin(),
2205 E = D.InLanguage.end(); B != E; ++B)
2206 O << '\"' << *B << "\", ";
2210 /// EmitToolClassDefinition - Emit a Tool class definition.
2211 void EmitToolClassDefinition (const ToolDescription& D,
2212 const OptionDescriptions& OptDescs,
2214 if (D.Name == "root")
2218 O << "class " << D.Name << " : public ";
2224 O << " {\nprivate:\n";
2225 O.indent(Indent1) << "static const char* InputLanguages_[];\n\n";
2228 EmitNameMethod(D, O);
2229 EmitInOutLanguageMethods(D, O);
2230 EmitIsJoinMethod(D, O);
2231 EmitGenerateActionMethods(D, OptDescs, O);
2233 // Close class definition
2236 EmitStaticMemberDefinitions(D, O);
2240 /// EmitOptionDefinitions - Iterate over a list of option descriptions
2241 /// and emit registration code.
2242 void EmitOptionDefinitions (const OptionDescriptions& descs,
2243 bool HasSink, bool HasExterns,
2246 std::vector<OptionDescription> Aliases;
2248 // Emit static cl::Option variables.
2249 for (OptionDescriptions::const_iterator B = descs.begin(),
2250 E = descs.end(); B!=E; ++B) {
2251 const OptionDescription& val = B->second;
2253 if (val.Type == OptionType::Alias) {
2254 Aliases.push_back(val);
2261 O << val.GenTypeDeclaration() << ' '
2262 << val.GenVariableName();
2264 if (val.isExtern()) {
2269 O << "(\"" << val.Name << "\"\n";
2271 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
2272 O << ", cl::Prefix";
2274 if (val.isRequired()) {
2275 if (val.isList() && !val.isMultiVal())
2276 O << ", cl::OneOrMore";
2278 O << ", cl::Required";
2280 else if (val.isOneOrMore() && val.isList()) {
2281 O << ", cl::OneOrMore";
2283 else if (val.isOptional() && val.isList()) {
2284 O << ", cl::Optional";
2287 if (val.isReallyHidden())
2288 O << ", cl::ReallyHidden";
2289 else if (val.isHidden())
2290 O << ", cl::Hidden";
2292 if (val.isCommaSeparated())
2293 O << ", cl::CommaSeparated";
2295 if (val.MultiVal > 1)
2296 O << ", cl::multi_val(" << val.MultiVal << ')';
2299 const std::string& str = val.InitVal->getAsString();
2300 O << ", cl::init(" << str << ')';
2303 if (!val.Help.empty())
2304 O << ", cl::desc(\"" << val.Help << "\")";
2309 // Emit the aliases (they should go after all the 'proper' options).
2310 for (std::vector<OptionDescription>::const_iterator
2311 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
2312 const OptionDescription& val = *B;
2314 O << val.GenTypeDeclaration() << ' '
2315 << val.GenVariableName()
2316 << "(\"" << val.Name << '\"';
2318 const OptionDescription& D = descs.FindOption(val.Help);
2319 O << ", cl::aliasopt(" << D.GenVariableName() << ")";
2321 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
2324 // Emit the sink option.
2326 O << (HasExterns ? "extern cl" : "cl")
2327 << "::list<std::string> " << SinkOptionName
2328 << (HasExterns ? ";\n" : "(cl::Sink);\n");
2333 /// EmitPreprocessOptionsCallback - Helper function passed to
2334 /// EmitCaseConstructHandler() by EmitPreprocessOptions().
2336 class EmitPreprocessOptionsCallback;
2339 (EmitPreprocessOptionsCallback::* EmitPreprocessOptionsCallbackHandler)
2340 (const DagInit&, unsigned, raw_ostream&) const;
2342 class EmitPreprocessOptionsCallback :
2343 public ActionHandlingCallbackBase,
2344 public HandlerTable<EmitPreprocessOptionsCallbackHandler>
2346 typedef EmitPreprocessOptionsCallbackHandler Handler;
2348 (EmitPreprocessOptionsCallback::* HandlerImpl)
2349 (const Init*, unsigned, raw_ostream&) const;
2351 const OptionDescriptions& OptDescs_;
2353 void onListOrDag(const DagInit& d, HandlerImpl h,
2354 unsigned IndentLevel, raw_ostream& O) const
2356 CheckNumberOfArguments(d, 1);
2357 const Init* I = d.getArg(0);
2359 // If I is a list, apply h to each element.
2360 if (typeid(*I) == typeid(ListInit)) {
2361 const ListInit& L = *static_cast<const ListInit*>(I);
2362 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B)
2363 ((this)->*(h))(*B, IndentLevel, O);
2365 // Otherwise, apply h to I.
2367 ((this)->*(h))(I, IndentLevel, O);
2371 void onUnsetOptionImpl(const Init* I,
2372 unsigned IndentLevel, raw_ostream& O) const
2374 const std::string& OptName = InitPtrToString(I);
2375 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2377 if (OptDesc.isSwitch()) {
2378 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = false;\n";
2380 else if (OptDesc.isParameter()) {
2381 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = \"\";\n";
2383 else if (OptDesc.isList()) {
2384 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2387 throw "Can't apply 'unset_option' to alias option '" + OptName + "'!";
2391 void onUnsetOption(const DagInit& d,
2392 unsigned IndentLevel, raw_ostream& O) const
2394 this->onListOrDag(d, &EmitPreprocessOptionsCallback::onUnsetOptionImpl,
2398 void onSetOptionImpl(const DagInit& d,
2399 unsigned IndentLevel, raw_ostream& O) const {
2400 CheckNumberOfArguments(d, 2);
2401 const std::string& OptName = InitPtrToString(d.getArg(0));
2402 const Init* Value = d.getArg(1);
2403 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2405 if (OptDesc.isList()) {
2406 const ListInit& List = InitPtrToList(Value);
2408 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2409 for (ListInit::const_iterator B = List.begin(), E = List.end();
2411 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".push_back(\""
2412 << InitPtrToString(*B) << "\");\n";
2415 else if (OptDesc.isSwitch()) {
2416 CheckBooleanConstant(Value);
2417 O.indent(IndentLevel) << OptDesc.GenVariableName()
2418 << " = " << Value->getAsString() << ";\n";
2420 else if (OptDesc.isParameter()) {
2421 const std::string& Str = InitPtrToString(Value);
2422 O.indent(IndentLevel) << OptDesc.GenVariableName()
2423 << " = \"" << Str << "\";\n";
2426 throw "Can't apply 'set_option' to alias option -" + OptName + " !";
2430 void onSetSwitch(const Init* I,
2431 unsigned IndentLevel, raw_ostream& O) const {
2432 const std::string& OptName = InitPtrToString(I);
2433 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2435 if (OptDesc.isSwitch())
2436 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = true;\n";
2438 throw "set_option: -" + OptName + " is not a switch option!";
2441 void onSetOption(const DagInit& d,
2442 unsigned IndentLevel, raw_ostream& O) const
2444 CheckNumberOfArguments(d, 1);
2446 // Two arguments: (set_option "parameter", VALUE), where VALUE can be a
2447 // boolean, a string or a string list.
2448 if (d.getNumArgs() > 1)
2449 this->onSetOptionImpl(d, IndentLevel, O);
2450 // One argument: (set_option "switch")
2451 // or (set_option ["switch1", "switch2", ...])
2453 this->onListOrDag(d, &EmitPreprocessOptionsCallback::onSetSwitch,
2459 EmitPreprocessOptionsCallback(const OptionDescriptions& OptDescs)
2460 : OptDescs_(OptDescs)
2462 if (!staticMembersInitialized_) {
2463 AddHandler("error", &EmitPreprocessOptionsCallback::onErrorDag);
2464 AddHandler("warning", &EmitPreprocessOptionsCallback::onWarningDag);
2465 AddHandler("unset_option", &EmitPreprocessOptionsCallback::onUnsetOption);
2466 AddHandler("set_option", &EmitPreprocessOptionsCallback::onSetOption);
2468 staticMembersInitialized_ = true;
2472 void operator()(const Init* I,
2473 unsigned IndentLevel, raw_ostream& O) const
2475 InvokeDagInitHandler(this, I, IndentLevel, O);
2480 /// EmitPreprocessOptions - Emit the PreprocessOptionsLocal() function.
2481 void EmitPreprocessOptions (const RecordKeeper& Records,
2482 const OptionDescriptions& OptDecs, raw_ostream& O)
2484 O << "void PreprocessOptionsLocal() {\n";
2486 const RecordVector& OptionPreprocessors =
2487 Records.getAllDerivedDefinitions("OptionPreprocessor");
2489 for (RecordVector::const_iterator B = OptionPreprocessors.begin(),
2490 E = OptionPreprocessors.end(); B!=E; ++B) {
2491 DagInit* Case = (*B)->getValueAsDag("preprocessor");
2492 EmitCaseConstructHandler(Case, Indent1,
2493 EmitPreprocessOptionsCallback(OptDecs),
2500 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMapLocal() function.
2501 void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
2503 O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
2505 // Get the relevant field out of RecordKeeper
2506 const Record* LangMapRecord = Records.getDef("LanguageMap");
2508 // It is allowed for a plugin to have no language map.
2509 if (LangMapRecord) {
2511 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
2512 if (!LangsToSuffixesList)
2513 throw "Error in the language map definition!";
2515 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
2516 const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
2518 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
2519 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
2521 for (unsigned i = 0; i < Suffixes->size(); ++i)
2522 O.indent(Indent1) << "langMap[\""
2523 << InitPtrToString(Suffixes->getElement(i))
2524 << "\"] = \"" << Lang << "\";\n";
2531 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
2532 /// by EmitEdgeClass().
2533 void IncDecWeight (const Init* i, unsigned IndentLevel,
2535 const DagInit& d = InitPtrToDag(i);
2536 const std::string& OpName = GetOperatorName(d);
2538 if (OpName == "inc_weight") {
2539 O.indent(IndentLevel) << "ret += ";
2541 else if (OpName == "dec_weight") {
2542 O.indent(IndentLevel) << "ret -= ";
2544 else if (OpName == "error") {
2545 CheckNumberOfArguments(d, 1);
2546 O.indent(IndentLevel) << "throw std::runtime_error(\""
2547 << InitPtrToString(d.getArg(0))
2552 throw "Unknown operator in edge properties list: '" + OpName + "'!"
2553 "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
2556 if (d.getNumArgs() > 0)
2557 O << InitPtrToInt(d.getArg(0)) << ";\n";
2563 /// EmitEdgeClass - Emit a single Edge# class.
2564 void EmitEdgeClass (unsigned N, const std::string& Target,
2565 DagInit* Case, const OptionDescriptions& OptDescs,
2568 // Class constructor.
2569 O << "class Edge" << N << ": public Edge {\n"
2571 O.indent(Indent1) << "Edge" << N << "() : Edge(\"" << Target
2574 // Function Weight().
2576 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n";
2577 O.indent(Indent2) << "unsigned ret = 0;\n";
2579 // Handle the 'case' construct.
2580 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
2582 O.indent(Indent2) << "return ret;\n";
2583 O.indent(Indent1) << "}\n\n};\n\n";
2586 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
2587 void EmitEdgeClasses (const RecordVector& EdgeVector,
2588 const OptionDescriptions& OptDescs,
2591 for (RecordVector::const_iterator B = EdgeVector.begin(),
2592 E = EdgeVector.end(); B != E; ++B) {
2593 const Record* Edge = *B;
2594 const std::string& NodeB = Edge->getValueAsString("b");
2595 DagInit& Weight = *Edge->getValueAsDag("weight");
2597 if (!IsDagEmpty(Weight))
2598 EmitEdgeClass(i, NodeB, &Weight, OptDescs, O);
2603 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraphLocal()
2605 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
2606 const ToolDescriptions& ToolDescs,
2609 O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
2611 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2612 E = ToolDescs.end(); B != E; ++B)
2613 O.indent(Indent1) << "G.insertNode(new " << (*B)->Name << "());\n";
2620 for (RecordVector::const_iterator B = EdgeVector.begin(),
2621 E = EdgeVector.end(); B != E; ++B) {
2622 const Record* Edge = *B;
2623 const std::string& NodeA = Edge->getValueAsString("a");
2624 const std::string& NodeB = Edge->getValueAsString("b");
2625 DagInit& Weight = *Edge->getValueAsDag("weight");
2627 O.indent(Indent1) << "G.insertEdge(\"" << NodeA << "\", ";
2629 if (IsDagEmpty(Weight))
2630 O << "new SimpleEdge(\"" << NodeB << "\")";
2632 O << "new Edge" << i << "()";
2641 /// HookInfo - Information about the hook type and number of arguments.
2644 // A hook can either have a single parameter of type std::vector<std::string>,
2645 // or NumArgs parameters of type const char*.
2646 enum HookType { ListHook, ArgHook };
2651 HookInfo() : Type(ArgHook), NumArgs(1)
2654 HookInfo(HookType T) : Type(T), NumArgs(1)
2657 HookInfo(unsigned N) : Type(ArgHook), NumArgs(N)
2661 typedef llvm::StringMap<HookInfo> HookInfoMap;
2663 /// ExtractHookNames - Extract the hook names from all instances of
2664 /// $CALL(HookName) in the provided command line string/action. Helper
2665 /// function used by FillInHookNames().
2666 class ExtractHookNames {
2667 HookInfoMap& HookNames_;
2668 const OptionDescriptions& OptDescs_;
2670 ExtractHookNames(HookInfoMap& HookNames, const OptionDescriptions& OptDescs)
2671 : HookNames_(HookNames), OptDescs_(OptDescs)
2674 void onAction (const DagInit& Dag) {
2675 const std::string& Name = GetOperatorName(Dag);
2677 if (Name == "forward_transformed_value") {
2678 CheckNumberOfArguments(Dag, 2);
2679 const std::string& OptName = InitPtrToString(Dag.getArg(0));
2680 const std::string& HookName = InitPtrToString(Dag.getArg(1));
2681 const OptionDescription& D = OptDescs_.FindOption(OptName);
2683 HookNames_[HookName] = HookInfo(D.isList() ? HookInfo::ListHook
2684 : HookInfo::ArgHook);
2686 else if (Name == "append_cmd" || Name == "output_suffix") {
2687 CheckNumberOfArguments(Dag, 1);
2688 this->onCmdLine(InitPtrToString(Dag.getArg(0)));
2692 void onCmdLine(const std::string& Cmd) {
2694 TokenizeCmdLine(Cmd, cmds);
2696 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
2698 const std::string& cmd = *B;
2700 if (cmd == "$CALL") {
2701 unsigned NumArgs = 0;
2702 CheckedIncrement(B, E, "Syntax error in $CALL invocation!");
2703 const std::string& HookName = *B;
2705 if (HookName.at(0) == ')')
2706 throw "$CALL invoked with no arguments!";
2708 while (++B != E && B->at(0) != ')') {
2712 HookInfoMap::const_iterator H = HookNames_.find(HookName);
2714 if (H != HookNames_.end() && H->second.NumArgs != NumArgs &&
2715 H->second.Type != HookInfo::ArgHook)
2716 throw "Overloading of hooks is not allowed. Overloaded hook: "
2719 HookNames_[HookName] = HookInfo(NumArgs);
2724 void operator()(const Init* Arg) {
2726 // We're invoked on an action (either a dag or a dag list).
2727 if (typeid(*Arg) == typeid(DagInit)) {
2728 const DagInit& Dag = InitPtrToDag(Arg);
2729 this->onAction(Dag);
2732 else if (typeid(*Arg) == typeid(ListInit)) {
2733 const ListInit& List = InitPtrToList(Arg);
2734 for (ListInit::const_iterator B = List.begin(), E = List.end(); B != E;
2736 const DagInit& Dag = InitPtrToDag(*B);
2737 this->onAction(Dag);
2742 // We're invoked on a command line.
2743 this->onCmdLine(InitPtrToString(Arg));
2746 void operator()(const DagInit* Test, unsigned, bool) {
2747 this->operator()(Test);
2749 void operator()(const Init* Statement, unsigned) {
2750 this->operator()(Statement);
2754 /// FillInHookNames - Actually extract the hook names from all command
2755 /// line strings. Helper function used by EmitHookDeclarations().
2756 void FillInHookNames(const ToolDescriptions& ToolDescs,
2757 const OptionDescriptions& OptDescs,
2758 HookInfoMap& HookNames)
2760 // For all tool descriptions:
2761 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2762 E = ToolDescs.end(); B != E; ++B) {
2763 const ToolDescription& D = *(*B);
2765 // Look for 'forward_transformed_value' in 'actions'.
2767 WalkCase(D.Actions, Id(), ExtractHookNames(HookNames, OptDescs));
2769 // Look for hook invocations in 'cmd_line'.
2772 if (dynamic_cast<StringInit*>(D.CmdLine))
2773 // This is a string.
2774 ExtractHookNames(HookNames, OptDescs).operator()(D.CmdLine);
2776 // This is a 'case' construct.
2777 WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames, OptDescs));
2781 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
2782 /// property records and emit hook function declaration for each
2783 /// instance of $CALL(HookName).
2784 void EmitHookDeclarations(const ToolDescriptions& ToolDescs,
2785 const OptionDescriptions& OptDescs, raw_ostream& O) {
2786 HookInfoMap HookNames;
2788 FillInHookNames(ToolDescs, OptDescs, HookNames);
2789 if (HookNames.empty())
2792 O << "namespace hooks {\n";
2793 for (HookInfoMap::const_iterator B = HookNames.begin(),
2794 E = HookNames.end(); B != E; ++B) {
2795 const char* HookName = B->first();
2796 const HookInfo& Info = B->second;
2798 O.indent(Indent1) << "std::string " << HookName << "(";
2800 if (Info.Type == HookInfo::ArgHook) {
2801 for (unsigned i = 0, j = Info.NumArgs; i < j; ++i) {
2802 O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
2806 O << "const std::vector<std::string>& Arg";
2814 /// EmitRegisterPlugin - Emit code to register this plugin.
2815 void EmitRegisterPlugin(int Priority, raw_ostream& O) {
2816 O << "struct Plugin : public llvmc::BasePlugin {\n\n";
2817 O.indent(Indent1) << "int Priority() const { return "
2818 << Priority << "; }\n\n";
2819 O.indent(Indent1) << "void PreprocessOptions() const\n";
2820 O.indent(Indent1) << "{ PreprocessOptionsLocal(); }\n\n";
2821 O.indent(Indent1) << "void PopulateLanguageMap(LanguageMap& langMap) const\n";
2822 O.indent(Indent1) << "{ PopulateLanguageMapLocal(langMap); }\n\n";
2824 << "void PopulateCompilationGraph(CompilationGraph& graph) const\n";
2825 O.indent(Indent1) << "{ PopulateCompilationGraphLocal(graph); }\n"
2827 << "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
2830 /// EmitIncludes - Emit necessary #include directives and some
2831 /// additional declarations.
2832 void EmitIncludes(raw_ostream& O) {
2833 O << "#include \"llvm/CompilerDriver/BuiltinOptions.h\"\n"
2834 << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
2835 << "#include \"llvm/CompilerDriver/ForceLinkageMacros.h\"\n"
2836 << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
2837 << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
2839 << "#include \"llvm/Support/CommandLine.h\"\n"
2840 << "#include \"llvm/Support/raw_ostream.h\"\n\n"
2842 << "#include <algorithm>\n"
2843 << "#include <cstdlib>\n"
2844 << "#include <iterator>\n"
2845 << "#include <stdexcept>\n\n"
2847 << "using namespace llvm;\n"
2848 << "using namespace llvmc;\n\n"
2850 << "extern cl::opt<std::string> OutputFilename;\n\n"
2852 << "inline const char* checkCString(const char* s)\n"
2853 << "{ return s == NULL ? \"\" : s; }\n\n";
2857 /// PluginData - Holds all information about a plugin.
2859 OptionDescriptions OptDescs;
2862 ToolDescriptions ToolDescs;
2867 /// HasSink - Go through the list of tool descriptions and check if
2868 /// there are any with the 'sink' property set.
2869 bool HasSink(const ToolDescriptions& ToolDescs) {
2870 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2871 E = ToolDescs.end(); B != E; ++B)
2878 /// HasExterns - Go through the list of option descriptions and check
2879 /// if there are any external options.
2880 bool HasExterns(const OptionDescriptions& OptDescs) {
2881 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
2882 E = OptDescs.end(); B != E; ++B)
2883 if (B->second.isExtern())
2889 /// CollectPluginData - Collect tool and option properties,
2890 /// compilation graph edges and plugin priority from the parse tree.
2891 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
2892 // Collect option properties.
2893 const RecordVector& OptionLists =
2894 Records.getAllDerivedDefinitions("OptionList");
2895 CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
2898 // Collect tool properties.
2899 const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
2900 CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
2901 Data.HasSink = HasSink(Data.ToolDescs);
2902 Data.HasExterns = HasExterns(Data.OptDescs);
2904 // Collect compilation graph edges.
2905 const RecordVector& CompilationGraphs =
2906 Records.getAllDerivedDefinitions("CompilationGraph");
2907 FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
2910 // Calculate the priority of this plugin.
2911 const RecordVector& Priorities =
2912 Records.getAllDerivedDefinitions("PluginPriority");
2913 Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
2916 /// CheckPluginData - Perform some sanity checks on the collected data.
2917 void CheckPluginData(PluginData& Data) {
2918 // Filter out all tools not mentioned in the compilation graph.
2919 FilterNotInGraph(Data.Edges, Data.ToolDescs);
2921 // Typecheck the compilation graph.
2922 TypecheckGraph(Data.Edges, Data.ToolDescs);
2924 // Check that there are no options without side effects (specified
2925 // only in the OptionList).
2926 CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
2929 void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
2930 // Emit file header.
2933 // Emit global option registration code.
2934 EmitOptionDefinitions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
2936 // Emit hook declarations.
2937 EmitHookDeclarations(Data.ToolDescs, Data.OptDescs, O);
2939 O << "namespace {\n\n";
2941 // Emit PreprocessOptionsLocal() function.
2942 EmitPreprocessOptions(Records, Data.OptDescs, O);
2944 // Emit PopulateLanguageMapLocal() function
2945 // (language map maps from file extensions to language names).
2946 EmitPopulateLanguageMap(Records, O);
2948 // Emit Tool classes.
2949 for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
2950 E = Data.ToolDescs.end(); B!=E; ++B)
2951 EmitToolClassDefinition(*(*B), Data.OptDescs, O);
2953 // Emit Edge# classes.
2954 EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
2956 // Emit PopulateCompilationGraphLocal() function.
2957 EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
2959 // Emit code for plugin registration.
2960 EmitRegisterPlugin(Data.Priority, O);
2962 O << "} // End anonymous namespace.\n\n";
2964 // Force linkage magic.
2965 O << "namespace llvmc {\n";
2966 O << "LLVMC_FORCE_LINKAGE_DECL(LLVMC_PLUGIN_NAME) {}\n";
2973 // End of anonymous namespace
2976 /// run - The back-end entry point.
2977 void LLVMCConfigurationEmitter::run (raw_ostream &O) {
2981 CollectPluginData(Records, Data);
2982 CheckPluginData(Data);
2984 EmitSourceFileHeader("LLVMC Configuration Library", O);
2985 EmitPluginCode(Data, O);
2987 } catch (std::exception& Error) {
2988 throw Error.what() + std::string(" - usually this means a syntax error.");