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"
30 //===----------------------------------------------------------------------===//
33 typedef std::vector<Record*> RecordVector;
34 typedef std::vector<std::string> StrVector;
36 //===----------------------------------------------------------------------===//
40 static const unsigned TabWidth = 4;
41 static const unsigned Indent1 = TabWidth*1;
42 static const unsigned Indent2 = TabWidth*2;
43 static const unsigned Indent3 = TabWidth*3;
45 // Default help string.
46 static const char * const DefaultHelpString = "NO HELP MESSAGE PROVIDED";
48 // Name for the "sink" option.
49 static 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 const std::string GetOperatorName(const DagInit& D) {
94 return GetOperatorName(&D);
97 // checkNumberOfArguments - Ensure that the number of args in d is
98 // greater than or equal to min_arguments, otherwise throw an exception.
99 void checkNumberOfArguments (const DagInit* d, unsigned minArgs) {
100 if (!d || d->getNumArgs() < minArgs)
101 throw GetOperatorName(d) + ": too few arguments!";
103 void checkNumberOfArguments (const DagInit& d, unsigned minArgs) {
104 checkNumberOfArguments(&d, minArgs);
107 // isDagEmpty - is this DAG marked with an empty marker?
108 bool isDagEmpty (const DagInit* d) {
109 return GetOperatorName(d) == "empty_dag_marker";
112 // EscapeVariableName - Escape commas and other symbols not allowed
113 // in the C++ variable names. Makes it possible to use options named
114 // like "Wa," (useful for prefix options).
115 std::string EscapeVariableName(const std::string& Var) {
117 for (unsigned i = 0; i != Var.size(); ++i) {
118 char cur_char = Var[i];
119 if (cur_char == ',') {
122 else if (cur_char == '+') {
125 else if (cur_char == '-') {
129 ret.push_back(cur_char);
135 /// oneOf - Does the input string contain this character?
136 bool oneOf(const char* lst, char c) {
144 template <class I, class S>
145 void checkedIncrement(I& P, I E, S ErrorString) {
151 // apply is needed because C++'s syntax doesn't let us construct a function
152 // object and call it in the same statement.
153 template<typename F, typename T0>
154 void apply(F Fun, T0& Arg0) {
158 template<typename F, typename T0, typename T1>
159 void apply(F Fun, T0& Arg0, T1& Arg1) {
160 return Fun(Arg0, Arg1);
163 //===----------------------------------------------------------------------===//
164 /// Back-end specific code
167 /// OptionType - One of six different option types. See the
168 /// documentation for detailed description of differences.
169 namespace OptionType {
171 enum OptionType { Alias, Switch, Parameter, ParameterList,
174 bool IsAlias(OptionType t) {
178 bool IsList (OptionType t) {
179 return (t == ParameterList || t == PrefixList);
182 bool IsSwitch (OptionType t) {
183 return (t == Switch);
186 bool IsParameter (OptionType t) {
187 return (t == Parameter || t == Prefix);
192 OptionType::OptionType stringToOptionType(const std::string& T) {
193 if (T == "alias_option")
194 return OptionType::Alias;
195 else if (T == "switch_option")
196 return OptionType::Switch;
197 else if (T == "parameter_option")
198 return OptionType::Parameter;
199 else if (T == "parameter_list_option")
200 return OptionType::ParameterList;
201 else if (T == "prefix_option")
202 return OptionType::Prefix;
203 else if (T == "prefix_list_option")
204 return OptionType::PrefixList;
206 throw "Unknown option type: " + T + '!';
209 namespace OptionDescriptionFlags {
210 enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
211 ReallyHidden = 0x4, Extern = 0x8,
212 OneOrMore = 0x10, Optional = 0x20,
213 CommaSeparated = 0x40 };
216 /// OptionDescription - Represents data contained in a single
217 /// OptionList entry.
218 struct OptionDescription {
219 OptionType::OptionType Type;
226 OptionDescription(OptionType::OptionType t = OptionType::Switch,
227 const std::string& n = "",
228 const std::string& h = DefaultHelpString)
229 : Type(t), Name(n), Flags(0x0), Help(h), MultiVal(1), InitVal(0)
232 /// GenTypeDeclaration - Returns the C++ variable type of this
234 const char* GenTypeDeclaration() const;
236 /// GenVariableName - Returns the variable name used in the
237 /// generated C++ code.
238 std::string GenVariableName() const;
240 /// Merge - Merge two option descriptions.
241 void Merge (const OptionDescription& other);
243 // Misc convenient getters/setters.
245 bool isAlias() const;
247 bool isMultiVal() const;
249 bool isCommaSeparated() const;
250 void setCommaSeparated();
252 bool isExtern() const;
255 bool isRequired() const;
258 bool isOneOrMore() const;
261 bool isOptional() const;
264 bool isHidden() const;
267 bool isReallyHidden() const;
268 void setReallyHidden();
270 bool isSwitch() const
271 { return OptionType::IsSwitch(this->Type); }
273 bool isParameter() const
274 { return OptionType::IsParameter(this->Type); }
277 { return OptionType::IsList(this->Type); }
281 void OptionDescription::Merge (const OptionDescription& other)
283 if (other.Type != Type)
284 throw "Conflicting definitions for the option " + Name + "!";
286 if (Help == other.Help || Help == DefaultHelpString)
288 else if (other.Help != DefaultHelpString) {
289 llvm::errs() << "Warning: several different help strings"
290 " defined for option " + Name + "\n";
293 Flags |= other.Flags;
296 bool OptionDescription::isAlias() const {
297 return OptionType::IsAlias(this->Type);
300 bool OptionDescription::isMultiVal() const {
304 bool OptionDescription::isCommaSeparated() const {
305 return Flags & OptionDescriptionFlags::CommaSeparated;
307 void OptionDescription::setCommaSeparated() {
308 Flags |= OptionDescriptionFlags::CommaSeparated;
311 bool OptionDescription::isExtern() const {
312 return Flags & OptionDescriptionFlags::Extern;
314 void OptionDescription::setExtern() {
315 Flags |= OptionDescriptionFlags::Extern;
318 bool OptionDescription::isRequired() const {
319 return Flags & OptionDescriptionFlags::Required;
321 void OptionDescription::setRequired() {
322 Flags |= OptionDescriptionFlags::Required;
325 bool OptionDescription::isOneOrMore() const {
326 return Flags & OptionDescriptionFlags::OneOrMore;
328 void OptionDescription::setOneOrMore() {
329 Flags |= OptionDescriptionFlags::OneOrMore;
332 bool OptionDescription::isOptional() const {
333 return Flags & OptionDescriptionFlags::Optional;
335 void OptionDescription::setOptional() {
336 Flags |= OptionDescriptionFlags::Optional;
339 bool OptionDescription::isHidden() const {
340 return Flags & OptionDescriptionFlags::Hidden;
342 void OptionDescription::setHidden() {
343 Flags |= OptionDescriptionFlags::Hidden;
346 bool OptionDescription::isReallyHidden() const {
347 return Flags & OptionDescriptionFlags::ReallyHidden;
349 void OptionDescription::setReallyHidden() {
350 Flags |= OptionDescriptionFlags::ReallyHidden;
353 const char* OptionDescription::GenTypeDeclaration() const {
355 case OptionType::Alias:
357 case OptionType::PrefixList:
358 case OptionType::ParameterList:
359 return "cl::list<std::string>";
360 case OptionType::Switch:
361 return "cl::opt<bool>";
362 case OptionType::Parameter:
363 case OptionType::Prefix:
365 return "cl::opt<std::string>";
369 std::string OptionDescription::GenVariableName() const {
370 const std::string& EscapedName = EscapeVariableName(Name);
372 case OptionType::Alias:
373 return "AutoGeneratedAlias_" + EscapedName;
374 case OptionType::PrefixList:
375 case OptionType::ParameterList:
376 return "AutoGeneratedList_" + EscapedName;
377 case OptionType::Switch:
378 return "AutoGeneratedSwitch_" + EscapedName;
379 case OptionType::Prefix:
380 case OptionType::Parameter:
382 return "AutoGeneratedParameter_" + EscapedName;
386 /// OptionDescriptions - An OptionDescription array plus some helper
388 class OptionDescriptions {
389 typedef StringMap<OptionDescription> container_type;
391 /// Descriptions - A list of OptionDescriptions.
392 container_type Descriptions;
395 /// FindOption - exception-throwing wrapper for find().
396 const OptionDescription& FindOption(const std::string& OptName) const;
398 // Wrappers for FindOption that throw an exception in case the option has a
400 const OptionDescription& FindSwitch(const std::string& OptName) const;
401 const OptionDescription& FindParameter(const std::string& OptName) const;
402 const OptionDescription& FindList(const std::string& OptName) const;
403 const OptionDescription&
404 FindListOrParameter(const std::string& OptName) const;
406 /// insertDescription - Insert new OptionDescription into
407 /// OptionDescriptions list
408 void InsertDescription (const OptionDescription& o);
410 // Support for STL-style iteration
411 typedef container_type::const_iterator const_iterator;
412 const_iterator begin() const { return Descriptions.begin(); }
413 const_iterator end() const { return Descriptions.end(); }
416 const OptionDescription&
417 OptionDescriptions::FindOption(const std::string& OptName) const {
418 const_iterator I = Descriptions.find(OptName);
419 if (I != Descriptions.end())
422 throw OptName + ": no such option!";
425 const OptionDescription&
426 OptionDescriptions::FindSwitch(const std::string& OptName) const {
427 const OptionDescription& OptDesc = this->FindOption(OptName);
428 if (!OptDesc.isSwitch())
429 throw OptName + ": incorrect option type - should be a switch!";
433 const OptionDescription&
434 OptionDescriptions::FindList(const std::string& OptName) const {
435 const OptionDescription& OptDesc = this->FindOption(OptName);
436 if (!OptDesc.isList())
437 throw OptName + ": incorrect option type - should be a list!";
441 const OptionDescription&
442 OptionDescriptions::FindParameter(const std::string& OptName) const {
443 const OptionDescription& OptDesc = this->FindOption(OptName);
444 if (!OptDesc.isParameter())
445 throw OptName + ": incorrect option type - should be a parameter!";
449 const OptionDescription&
450 OptionDescriptions::FindListOrParameter(const std::string& OptName) const {
451 const OptionDescription& OptDesc = this->FindOption(OptName);
452 if (!OptDesc.isList() && !OptDesc.isParameter())
454 + ": incorrect option type - should be a list or parameter!";
458 void OptionDescriptions::InsertDescription (const OptionDescription& o) {
459 container_type::iterator I = Descriptions.find(o.Name);
460 if (I != Descriptions.end()) {
461 OptionDescription& D = I->second;
465 Descriptions[o.Name] = o;
469 /// HandlerTable - A base class for function objects implemented as
470 /// 'tables of handlers'.
471 template <typename Handler>
474 // Implementation details.
476 /// HandlerMap - A map from property names to property handlers
477 typedef StringMap<Handler> HandlerMap;
479 static HandlerMap Handlers_;
480 static bool staticMembersInitialized_;
484 Handler GetHandler (const std::string& HandlerName) const {
485 typename HandlerMap::iterator method = Handlers_.find(HandlerName);
487 if (method != Handlers_.end()) {
488 Handler h = method->second;
492 throw "No handler found for property " + HandlerName + "!";
496 void AddHandler(const char* Property, Handler H) {
497 Handlers_[Property] = H;
502 template <class FunctionObject>
503 void InvokeDagInitHandler(FunctionObject* Obj, Init* i) {
504 typedef void (FunctionObject::*Handler) (const DagInit*);
506 const DagInit& property = InitPtrToDag(i);
507 const std::string& property_name = GetOperatorName(property);
508 Handler h = Obj->GetHandler(property_name);
510 ((Obj)->*(h))(&property);
513 template <typename H>
514 typename HandlerTable<H>::HandlerMap HandlerTable<H>::Handlers_;
516 template <typename H>
517 bool HandlerTable<H>::staticMembersInitialized_ = false;
520 /// CollectOptionProperties - Function object for iterating over an
521 /// option property list.
522 class CollectOptionProperties;
523 typedef void (CollectOptionProperties::* CollectOptionPropertiesHandler)
526 class CollectOptionProperties
527 : public HandlerTable<CollectOptionPropertiesHandler>
531 /// optDescs_ - OptionDescriptions table. This is where the
532 /// information is stored.
533 OptionDescription& optDesc_;
537 explicit CollectOptionProperties(OptionDescription& OD)
540 if (!staticMembersInitialized_) {
541 AddHandler("extern", &CollectOptionProperties::onExtern);
542 AddHandler("help", &CollectOptionProperties::onHelp);
543 AddHandler("hidden", &CollectOptionProperties::onHidden);
544 AddHandler("init", &CollectOptionProperties::onInit);
545 AddHandler("multi_val", &CollectOptionProperties::onMultiVal);
546 AddHandler("one_or_more", &CollectOptionProperties::onOneOrMore);
547 AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
548 AddHandler("required", &CollectOptionProperties::onRequired);
549 AddHandler("optional", &CollectOptionProperties::onOptional);
550 AddHandler("comma_separated", &CollectOptionProperties::onCommaSeparated);
552 staticMembersInitialized_ = true;
556 /// operator() - Just forwards to the corresponding property
558 void operator() (Init* i) {
559 InvokeDagInitHandler(this, i);
564 /// Option property handlers --
565 /// Methods that handle option properties such as (help) or (hidden).
567 void onExtern (const DagInit* d) {
568 checkNumberOfArguments(d, 0);
569 optDesc_.setExtern();
572 void onHelp (const DagInit* d) {
573 checkNumberOfArguments(d, 1);
574 optDesc_.Help = InitPtrToString(d->getArg(0));
577 void onHidden (const DagInit* d) {
578 checkNumberOfArguments(d, 0);
579 optDesc_.setHidden();
582 void onReallyHidden (const DagInit* d) {
583 checkNumberOfArguments(d, 0);
584 optDesc_.setReallyHidden();
587 void onCommaSeparated (const DagInit* d) {
588 checkNumberOfArguments(d, 0);
589 if (!optDesc_.isList())
590 throw "'comma_separated' is valid only on list options!";
591 optDesc_.setCommaSeparated();
594 void onRequired (const DagInit* d) {
595 checkNumberOfArguments(d, 0);
596 if (optDesc_.isOneOrMore() || optDesc_.isOptional())
597 throw "Only one of (required), (optional) or "
598 "(one_or_more) properties is allowed!";
599 optDesc_.setRequired();
602 void onInit (const DagInit* d) {
603 checkNumberOfArguments(d, 1);
604 Init* i = d->getArg(0);
605 const std::string& str = i->getAsString();
607 bool correct = optDesc_.isParameter() && dynamic_cast<StringInit*>(i);
608 correct |= (optDesc_.isSwitch() && (str == "true" || str == "false"));
611 throw "Incorrect usage of the 'init' option property!";
613 optDesc_.InitVal = i;
616 void onOneOrMore (const DagInit* d) {
617 checkNumberOfArguments(d, 0);
618 if (optDesc_.isRequired() || optDesc_.isOptional())
619 throw "Only one of (required), (optional) or "
620 "(one_or_more) properties is allowed!";
621 if (!OptionType::IsList(optDesc_.Type))
622 llvm::errs() << "Warning: specifying the 'one_or_more' property "
623 "on a non-list option will have no effect.\n";
624 optDesc_.setOneOrMore();
627 void onOptional (const DagInit* d) {
628 checkNumberOfArguments(d, 0);
629 if (optDesc_.isRequired() || optDesc_.isOneOrMore())
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 'optional' property"
634 "on a non-list option will have no effect.\n";
635 optDesc_.setOptional();
638 void onMultiVal (const DagInit* d) {
639 checkNumberOfArguments(d, 1);
640 int val = InitPtrToInt(d->getArg(0));
642 throw "Error in the 'multi_val' property: "
643 "the value must be greater than 1!";
644 if (!OptionType::IsList(optDesc_.Type))
645 throw "The multi_val property is valid only on list options!";
646 optDesc_.MultiVal = val;
651 /// AddOption - A function object that is applied to every option
652 /// description. Used by CollectOptionDescriptions.
655 OptionDescriptions& OptDescs_;
658 explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
661 void operator()(const Init* i) {
662 const DagInit& d = InitPtrToDag(i);
663 checkNumberOfArguments(&d, 1);
665 const OptionType::OptionType Type =
666 stringToOptionType(GetOperatorName(d));
667 const std::string& Name = InitPtrToString(d.getArg(0));
669 OptionDescription OD(Type, Name);
672 checkNumberOfArguments(&d, 2);
675 // Aliases store the aliased option name in the 'Help' field.
676 OD.Help = InitPtrToString(d.getArg(1));
678 else if (!OD.isExtern()) {
679 processOptionProperties(&d, OD);
681 OptDescs_.InsertDescription(OD);
685 /// processOptionProperties - Go through the list of option
686 /// properties and call a corresponding handler for each.
687 static void processOptionProperties (const DagInit* d, OptionDescription& o) {
688 checkNumberOfArguments(d, 2);
689 DagInit::const_arg_iterator B = d->arg_begin();
690 // Skip the first argument: it's always the option name.
692 std::for_each(B, d->arg_end(), CollectOptionProperties(o));
697 /// CollectOptionDescriptions - Collects option properties from all
699 void CollectOptionDescriptions (RecordVector::const_iterator B,
700 RecordVector::const_iterator E,
701 OptionDescriptions& OptDescs)
703 // For every OptionList:
705 RecordVector::value_type T = *B;
706 // Throws an exception if the value does not exist.
707 ListInit* PropList = T->getValueAsListInit("options");
709 // For every option description in this list:
710 // collect the information and
711 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
715 // Tool information record
717 namespace ToolFlags {
718 enum ToolFlags { Join = 0x1, Sink = 0x2 };
721 struct ToolDescription : public RefCountedBase<ToolDescription> {
725 StrVector InLanguage;
726 std::string OutLanguage;
727 std::string OutputSuffix;
730 // Various boolean properties
731 void setSink() { Flags |= ToolFlags::Sink; }
732 bool isSink() const { return Flags & ToolFlags::Sink; }
733 void setJoin() { Flags |= ToolFlags::Join; }
734 bool isJoin() const { return Flags & ToolFlags::Join; }
736 // Default ctor here is needed because StringMap can only store
737 // DefaultConstructible objects
738 ToolDescription() : CmdLine(0), Actions(0), Flags(0) {}
739 ToolDescription (const std::string& n)
740 : Name(n), CmdLine(0), Actions(0), Flags(0)
744 /// ToolDescriptions - A list of Tool information records.
745 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
748 /// CollectToolProperties - Function object for iterating over a list of
749 /// tool property records.
751 class CollectToolProperties;
752 typedef void (CollectToolProperties::* CollectToolPropertiesHandler)
755 class CollectToolProperties : public HandlerTable<CollectToolPropertiesHandler>
759 /// toolDesc_ - Properties of the current Tool. This is where the
760 /// information is stored.
761 ToolDescription& toolDesc_;
765 explicit CollectToolProperties (ToolDescription& d)
768 if (!staticMembersInitialized_) {
770 AddHandler("actions", &CollectToolProperties::onActions);
771 AddHandler("cmd_line", &CollectToolProperties::onCmdLine);
772 AddHandler("in_language", &CollectToolProperties::onInLanguage);
773 AddHandler("join", &CollectToolProperties::onJoin);
774 AddHandler("out_language", &CollectToolProperties::onOutLanguage);
775 AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
776 AddHandler("sink", &CollectToolProperties::onSink);
778 staticMembersInitialized_ = true;
782 void operator() (Init* i) {
783 InvokeDagInitHandler(this, i);
788 /// Property handlers --
789 /// Functions that extract information about tool properties from
790 /// DAG representation.
792 void onActions (const DagInit* d) {
793 checkNumberOfArguments(d, 1);
794 Init* Case = d->getArg(0);
795 if (typeid(*Case) != typeid(DagInit) ||
796 GetOperatorName(static_cast<DagInit*>(Case)) != "case")
797 throw "The argument to (actions) should be a 'case' construct!";
798 toolDesc_.Actions = Case;
801 void onCmdLine (const DagInit* d) {
802 checkNumberOfArguments(d, 1);
803 toolDesc_.CmdLine = d->getArg(0);
806 void onInLanguage (const DagInit* d) {
807 checkNumberOfArguments(d, 1);
808 Init* arg = d->getArg(0);
810 // Find out the argument's type.
811 if (typeid(*arg) == typeid(StringInit)) {
813 toolDesc_.InLanguage.push_back(InitPtrToString(arg));
817 const ListInit& lst = InitPtrToList(arg);
818 StrVector& out = toolDesc_.InLanguage;
820 // Copy strings to the output vector.
821 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
823 out.push_back(InitPtrToString(*B));
826 // Remove duplicates.
827 std::sort(out.begin(), out.end());
828 StrVector::iterator newE = std::unique(out.begin(), out.end());
829 out.erase(newE, out.end());
833 void onJoin (const DagInit* d) {
834 checkNumberOfArguments(d, 0);
838 void onOutLanguage (const DagInit* d) {
839 checkNumberOfArguments(d, 1);
840 toolDesc_.OutLanguage = InitPtrToString(d->getArg(0));
843 void onOutputSuffix (const DagInit* d) {
844 checkNumberOfArguments(d, 1);
845 toolDesc_.OutputSuffix = InitPtrToString(d->getArg(0));
848 void onSink (const DagInit* d) {
849 checkNumberOfArguments(d, 0);
855 /// CollectToolDescriptions - Gather information about tool properties
856 /// from the parsed TableGen data (basically a wrapper for the
857 /// CollectToolProperties function object).
858 void CollectToolDescriptions (RecordVector::const_iterator B,
859 RecordVector::const_iterator E,
860 ToolDescriptions& ToolDescs)
862 // Iterate over a properties list of every Tool definition
864 const Record* T = *B;
865 // Throws an exception if the value does not exist.
866 ListInit* PropList = T->getValueAsListInit("properties");
868 IntrusiveRefCntPtr<ToolDescription>
869 ToolDesc(new ToolDescription(T->getName()));
871 std::for_each(PropList->begin(), PropList->end(),
872 CollectToolProperties(*ToolDesc));
873 ToolDescs.push_back(ToolDesc);
877 /// FillInEdgeVector - Merge all compilation graph definitions into
878 /// one single edge list.
879 void FillInEdgeVector(RecordVector::const_iterator B,
880 RecordVector::const_iterator E, RecordVector& Out) {
881 for (; B != E; ++B) {
882 const ListInit* edges = (*B)->getValueAsListInit("edges");
884 for (unsigned i = 0; i < edges->size(); ++i)
885 Out.push_back(edges->getElementAsRecord(i));
889 /// CalculatePriority - Calculate the priority of this plugin.
890 int CalculatePriority(RecordVector::const_iterator B,
891 RecordVector::const_iterator E) {
895 priority = static_cast<int>((*B)->getValueAsInt("priority"));
898 throw "More than one 'PluginPriority' instance found: "
899 "most probably an error!";
905 /// NotInGraph - Helper function object for FilterNotInGraph.
908 const llvm::StringSet<>& ToolsInGraph_;
911 NotInGraph(const llvm::StringSet<>& ToolsInGraph)
912 : ToolsInGraph_(ToolsInGraph)
915 bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
916 return (ToolsInGraph_.count(x->Name) == 0);
920 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
921 /// mentioned in the compilation graph definition.
922 void FilterNotInGraph (const RecordVector& EdgeVector,
923 ToolDescriptions& ToolDescs) {
925 // List all tools mentioned in the graph.
926 llvm::StringSet<> ToolsInGraph;
928 for (RecordVector::const_iterator B = EdgeVector.begin(),
929 E = EdgeVector.end(); B != E; ++B) {
931 const Record* Edge = *B;
932 const std::string& NodeA = Edge->getValueAsString("a");
933 const std::string& NodeB = Edge->getValueAsString("b");
936 ToolsInGraph.insert(NodeA);
937 ToolsInGraph.insert(NodeB);
940 // Filter ToolPropertiesList.
941 ToolDescriptions::iterator new_end =
942 std::remove_if(ToolDescs.begin(), ToolDescs.end(),
943 NotInGraph(ToolsInGraph));
944 ToolDescs.erase(new_end, ToolDescs.end());
947 /// FillInToolToLang - Fills in two tables that map tool names to
948 /// (input, output) languages. Helper function used by TypecheckGraph().
949 void FillInToolToLang (const ToolDescriptions& ToolDescs,
950 StringMap<StringSet<> >& ToolToInLang,
951 StringMap<std::string>& ToolToOutLang) {
952 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
953 E = ToolDescs.end(); B != E; ++B) {
954 const ToolDescription& D = *(*B);
955 for (StrVector::const_iterator B = D.InLanguage.begin(),
956 E = D.InLanguage.end(); B != E; ++B)
957 ToolToInLang[D.Name].insert(*B);
958 ToolToOutLang[D.Name] = D.OutLanguage;
962 /// TypecheckGraph - Check that names for output and input languages
963 /// on all edges do match. This doesn't do much when the information
964 /// about the whole graph is not available (i.e. when compiling most
966 void TypecheckGraph (const RecordVector& EdgeVector,
967 const ToolDescriptions& ToolDescs) {
968 StringMap<StringSet<> > ToolToInLang;
969 StringMap<std::string> ToolToOutLang;
971 FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
972 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
973 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
975 for (RecordVector::const_iterator B = EdgeVector.begin(),
976 E = EdgeVector.end(); B != E; ++B) {
977 const Record* Edge = *B;
978 const std::string& NodeA = Edge->getValueAsString("a");
979 const std::string& NodeB = Edge->getValueAsString("b");
980 StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
981 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
983 if (NodeA != "root") {
984 if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
985 throw "Edge " + NodeA + "->" + NodeB
986 + ": output->input language mismatch";
990 throw "Edges back to the root are not allowed!";
994 /// WalkCase - Walks the 'case' expression DAG and invokes
995 /// TestCallback on every test, and StatementCallback on every
996 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
997 /// combinators (that is, they are passed directly to TestCallback).
998 /// TestCallback must have type 'void TestCallback(const DagInit*, unsigned
999 /// IndentLevel, bool FirstTest)'.
1000 /// StatementCallback must have type 'void StatementCallback(const Init*,
1001 /// unsigned IndentLevel)'.
1002 template <typename F1, typename F2>
1003 void WalkCase(const Init* Case, F1 TestCallback, F2 StatementCallback,
1004 unsigned IndentLevel = 0)
1006 const DagInit& d = InitPtrToDag(Case);
1009 if (GetOperatorName(d) != "case")
1010 throw "WalkCase should be invoked only on 'case' expressions!";
1012 if (d.getNumArgs() < 2)
1013 throw "There should be at least one clause in the 'case' expression:\n"
1018 const unsigned numArgs = d.getNumArgs();
1020 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1027 const DagInit& Test = InitPtrToDag(arg);
1029 if (GetOperatorName(Test) == "default" && (i+1 != numArgs))
1030 throw "The 'default' clause should be the last in the "
1031 "'case' construct!";
1033 throw "Case construct handler: no corresponding action "
1034 "found for the test " + Test.getAsString() + '!';
1036 TestCallback(&Test, IndentLevel, (i == 1));
1040 if (dynamic_cast<DagInit*>(arg)
1041 && GetOperatorName(static_cast<DagInit*>(arg)) == "case") {
1043 WalkCase(arg, TestCallback, StatementCallback, IndentLevel + Indent1);
1046 // Handle statement.
1047 StatementCallback(arg, IndentLevel);
1055 /// ExtractOptionNames - A helper function object used by
1056 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
1057 class ExtractOptionNames {
1058 llvm::StringSet<>& OptionNames_;
1060 void processDag(const Init* Statement) {
1061 const DagInit& Stmt = InitPtrToDag(Statement);
1062 const std::string& ActionName = GetOperatorName(Stmt);
1063 if (ActionName == "forward" || ActionName == "forward_as" ||
1064 ActionName == "forward_value" ||
1065 ActionName == "forward_transformed_value" ||
1066 ActionName == "switch_on" || ActionName == "parameter_equals" ||
1067 ActionName == "element_in_list" || ActionName == "not_empty" ||
1068 ActionName == "empty") {
1069 checkNumberOfArguments(&Stmt, 1);
1070 const std::string& Name = InitPtrToString(Stmt.getArg(0));
1071 OptionNames_.insert(Name);
1073 else if (ActionName == "and" || ActionName == "or") {
1074 for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
1075 this->processDag(Stmt.getArg(i));
1081 ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
1084 void operator()(const Init* Statement) {
1085 if (typeid(*Statement) == typeid(ListInit)) {
1086 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1087 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1089 this->processDag(*B);
1092 this->processDag(Statement);
1096 void operator()(const DagInit* Test, unsigned, bool) {
1097 this->operator()(Test);
1099 void operator()(const Init* Statement, unsigned) {
1100 this->operator()(Statement);
1104 /// CheckForSuperfluousOptions - Check that there are no side
1105 /// effect-free options (specified only in the OptionList). Otherwise,
1106 /// output a warning.
1107 void CheckForSuperfluousOptions (const RecordVector& Edges,
1108 const ToolDescriptions& ToolDescs,
1109 const OptionDescriptions& OptDescs) {
1110 llvm::StringSet<> nonSuperfluousOptions;
1112 // Add all options mentioned in the ToolDesc.Actions to the set of
1113 // non-superfluous options.
1114 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1115 E = ToolDescs.end(); B != E; ++B) {
1116 const ToolDescription& TD = *(*B);
1117 ExtractOptionNames Callback(nonSuperfluousOptions);
1119 WalkCase(TD.Actions, Callback, Callback);
1122 // Add all options mentioned in the 'case' clauses of the
1123 // OptionalEdges of the compilation graph to the set of
1124 // non-superfluous options.
1125 for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
1127 const Record* Edge = *B;
1128 DagInit* Weight = Edge->getValueAsDag("weight");
1130 if (!isDagEmpty(Weight))
1131 WalkCase(Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
1134 // Check that all options in OptDescs belong to the set of
1135 // non-superfluous options.
1136 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
1137 E = OptDescs.end(); B != E; ++B) {
1138 const OptionDescription& Val = B->second;
1139 if (!nonSuperfluousOptions.count(Val.Name)
1140 && Val.Type != OptionType::Alias)
1141 llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! "
1142 "Probable cause: this option is specified only in the OptionList.\n";
1146 /// EmitCaseTest0Args - Helper function used by EmitCaseConstructHandler().
1147 bool EmitCaseTest0Args(const std::string& TestName, raw_ostream& O) {
1148 if (TestName == "single_input_file") {
1149 O << "InputFilenames.size() == 1";
1152 else if (TestName == "multiple_input_files") {
1153 O << "InputFilenames.size() > 1";
1160 /// EmitListTest - Helper function used by EmitCaseTest1ArgList().
1161 template <typename F>
1162 void EmitListTest(const ListInit& L, const char* LogicOp,
1163 F Callback, raw_ostream& O)
1165 // This is a lot like EmitLogicalOperationTest, but works on ListInits instead
1167 bool isFirst = true;
1168 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B) {
1173 Callback(InitPtrToString(*B), O);
1177 // Callbacks for use with EmitListTest.
1179 class EmitSwitchOn {
1180 const OptionDescriptions& OptDescs_;
1182 EmitSwitchOn(const OptionDescriptions& OptDescs) : OptDescs_(OptDescs)
1185 void operator()(const std::string& OptName, raw_ostream& O) const {
1186 const OptionDescription& OptDesc = OptDescs_.FindSwitch(OptName);
1187 O << OptDesc.GenVariableName();
1191 class EmitEmptyTest {
1193 const OptionDescriptions& OptDescs_;
1195 EmitEmptyTest(bool EmitNegate, const OptionDescriptions& OptDescs)
1196 : EmitNegate_(EmitNegate), OptDescs_(OptDescs)
1199 void operator()(const std::string& OptName, raw_ostream& O) const {
1200 const char* Neg = (EmitNegate_ ? "!" : "");
1201 if (OptName == "o") {
1202 O << Neg << "OutputFilename.empty()";
1204 else if (OptName == "save-temps") {
1205 O << Neg << "(SaveTemps == SaveTempsEnum::Unset)";
1208 const OptionDescription& OptDesc = OptDescs_.FindListOrParameter(OptName);
1209 O << Neg << OptDesc.GenVariableName() << ".empty()";
1215 /// EmitCaseTest1ArgList - Helper function used by EmitCaseTest1Arg();
1216 bool EmitCaseTest1ArgList(const std::string& TestName,
1218 const OptionDescriptions& OptDescs,
1220 const ListInit& L = *static_cast<ListInit*>(d.getArg(0));
1222 if (TestName == "any_switch_on") {
1223 EmitListTest(L, "||", EmitSwitchOn(OptDescs), O);
1226 else if (TestName == "switch_on") {
1227 EmitListTest(L, "&&", EmitSwitchOn(OptDescs), O);
1230 else if (TestName == "any_not_empty") {
1231 EmitListTest(L, "||", EmitEmptyTest(true, OptDescs), O);
1234 else if (TestName == "any_empty") {
1235 EmitListTest(L, "||", EmitEmptyTest(false, OptDescs), O);
1238 else if (TestName == "not_empty") {
1239 EmitListTest(L, "&&", EmitEmptyTest(true, OptDescs), O);
1242 else if (TestName == "empty") {
1243 EmitListTest(L, "&&", EmitEmptyTest(false, OptDescs), O);
1250 /// EmitCaseTest1ArgStr - Helper function used by EmitCaseTest1Arg();
1251 bool EmitCaseTest1ArgStr(const std::string& TestName,
1253 const OptionDescriptions& OptDescs,
1255 const std::string& OptName = InitPtrToString(d.getArg(0));
1257 if (TestName == "switch_on") {
1258 apply(EmitSwitchOn(OptDescs), OptName, O);
1261 else if (TestName == "input_languages_contain") {
1262 O << "InLangs.count(\"" << OptName << "\") != 0";
1265 else if (TestName == "in_language") {
1266 // This works only for single-argument Tool::GenerateAction. Join
1267 // tools can process several files in different languages simultaneously.
1269 // TODO: make this work with Edge::Weight (if possible).
1270 O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
1273 else if (TestName == "not_empty" || TestName == "empty") {
1274 bool EmitNegate = (TestName == "not_empty");
1275 apply(EmitEmptyTest(EmitNegate, OptDescs), OptName, O);
1282 /// EmitCaseTest1Arg - Helper function used by EmitCaseConstructHandler();
1283 bool EmitCaseTest1Arg(const std::string& TestName,
1285 const OptionDescriptions& OptDescs,
1287 checkNumberOfArguments(&d, 1);
1288 if (typeid(*d.getArg(0)) == typeid(ListInit))
1289 return EmitCaseTest1ArgList(TestName, d, OptDescs, O);
1291 return EmitCaseTest1ArgStr(TestName, d, OptDescs, O);
1294 /// EmitCaseTest2Args - Helper function used by EmitCaseConstructHandler().
1295 bool EmitCaseTest2Args(const std::string& TestName,
1297 unsigned IndentLevel,
1298 const OptionDescriptions& OptDescs,
1300 checkNumberOfArguments(&d, 2);
1301 const std::string& OptName = InitPtrToString(d.getArg(0));
1302 const std::string& OptArg = InitPtrToString(d.getArg(1));
1304 if (TestName == "parameter_equals") {
1305 const OptionDescription& OptDesc = OptDescs.FindParameter(OptName);
1306 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
1309 else if (TestName == "element_in_list") {
1310 const OptionDescription& OptDesc = OptDescs.FindList(OptName);
1311 const std::string& VarName = OptDesc.GenVariableName();
1312 O << "std::find(" << VarName << ".begin(),\n";
1313 O.indent(IndentLevel + Indent1)
1314 << VarName << ".end(), \""
1315 << OptArg << "\") != " << VarName << ".end()";
1322 // Forward declaration.
1323 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
1324 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1325 const OptionDescriptions& OptDescs,
1328 /// EmitLogicalOperationTest - Helper function used by
1329 /// EmitCaseConstructHandler.
1330 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
1331 unsigned IndentLevel,
1332 const OptionDescriptions& OptDescs,
1335 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
1336 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
1337 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1338 if (j != NumArgs - 1) {
1340 O.indent(IndentLevel + Indent1) << ' ' << LogicOp << " (";
1348 void EmitLogicalNot(const DagInit& d, unsigned IndentLevel,
1349 const OptionDescriptions& OptDescs, raw_ostream& O)
1351 checkNumberOfArguments(&d, 1);
1352 const DagInit& InnerTest = InitPtrToDag(d.getArg(0));
1354 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1358 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
1359 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1360 const OptionDescriptions& OptDescs,
1362 const std::string& TestName = GetOperatorName(d);
1364 if (TestName == "and")
1365 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
1366 else if (TestName == "or")
1367 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
1368 else if (TestName == "not")
1369 EmitLogicalNot(d, IndentLevel, OptDescs, O);
1370 else if (EmitCaseTest0Args(TestName, O))
1372 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
1374 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
1377 throw TestName + ": unknown edge property!";
1381 /// EmitCaseTestCallback - Callback used by EmitCaseConstructHandler.
1382 class EmitCaseTestCallback {
1384 const OptionDescriptions& OptDescs_;
1388 EmitCaseTestCallback(bool EmitElseIf,
1389 const OptionDescriptions& OptDescs, raw_ostream& O)
1390 : EmitElseIf_(EmitElseIf), OptDescs_(OptDescs), O_(O)
1393 void operator()(const DagInit* Test, unsigned IndentLevel, bool FirstTest)
1395 if (GetOperatorName(Test) == "default") {
1396 O_.indent(IndentLevel) << "else {\n";
1399 O_.indent(IndentLevel)
1400 << ((!FirstTest && EmitElseIf_) ? "else if (" : "if (");
1401 EmitCaseTest(*Test, IndentLevel, OptDescs_, O_);
1407 /// EmitCaseStatementCallback - Callback used by EmitCaseConstructHandler.
1408 template <typename F>
1409 class EmitCaseStatementCallback {
1414 EmitCaseStatementCallback(F Callback, raw_ostream& O)
1415 : Callback_(Callback), O_(O)
1418 void operator() (const Init* Statement, unsigned IndentLevel) {
1420 // Ignore nested 'case' DAG.
1421 if (!(dynamic_cast<const DagInit*>(Statement) &&
1422 GetOperatorName(static_cast<const DagInit*>(Statement)) == "case")) {
1423 if (typeid(*Statement) == typeid(ListInit)) {
1424 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1425 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1427 Callback_(*B, (IndentLevel + Indent1), O_);
1430 Callback_(Statement, (IndentLevel + Indent1), O_);
1433 O_.indent(IndentLevel) << "}\n";
1438 /// EmitCaseConstructHandler - Emit code that handles the 'case'
1439 /// construct. Takes a function object that should emit code for every case
1440 /// clause. Implemented on top of WalkCase.
1441 /// Callback's type is void F(Init* Statement, unsigned IndentLevel,
1442 /// raw_ostream& O).
1443 /// EmitElseIf parameter controls the type of condition that is emitted ('if
1444 /// (..) {..} else if (..) {} .. else {..}' vs. 'if (..) {..} if(..) {..}
1446 template <typename F>
1447 void EmitCaseConstructHandler(const Init* Case, unsigned IndentLevel,
1448 F Callback, bool EmitElseIf,
1449 const OptionDescriptions& OptDescs,
1451 WalkCase(Case, EmitCaseTestCallback(EmitElseIf, OptDescs, O),
1452 EmitCaseStatementCallback<F>(Callback, O), IndentLevel);
1455 /// TokenizeCmdline - converts from
1456 /// "$CALL(HookName, 'Arg1', 'Arg2')/path -arg1 -arg2" to
1457 /// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path", "-arg1", "-arg2"].
1458 void TokenizeCmdline(const std::string& CmdLine, StrVector& Out) {
1459 const char* Delimiters = " \t\n\v\f\r";
1461 { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1464 if (CmdLine.empty())
1468 std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1471 for (; B != E; ++B) {
1472 char cur_ch = CmdLine[B];
1476 if (cur_ch == '$') {
1477 cur_st = SpecialCommand;
1480 if (oneOf(Delimiters, cur_ch)) {
1482 B = CmdLine.find_first_not_of(Delimiters, B);
1483 if (B == std::string::npos) {
1494 case SpecialCommand:
1495 if (oneOf(Delimiters, cur_ch)) {
1500 if (cur_ch == '(') {
1502 cur_st = InsideSpecialCommand;
1507 case InsideSpecialCommand:
1508 if (oneOf(Delimiters, cur_ch)) {
1511 if (cur_ch == '\'') {
1512 cur_st = InsideQuotationMarks;
1516 if (cur_ch == ')') {
1520 if (cur_ch == ',') {
1526 case InsideQuotationMarks:
1527 if (cur_ch == '\'') {
1528 cur_st = InsideSpecialCommand;
1534 Out.back().push_back(cur_ch);
1538 /// SubstituteCall - Given "$CALL(HookName, [Arg1 [, Arg2 [...]]])", output
1539 /// "hooks::HookName([Arg1 [, Arg2 [, ...]]])". Helper function used by
1540 /// SubstituteSpecialCommands().
1541 StrVector::const_iterator
1542 SubstituteCall (StrVector::const_iterator Pos,
1543 StrVector::const_iterator End,
1544 bool IsJoin, raw_ostream& O)
1546 const char* errorMessage = "Syntax error in $CALL invocation!";
1547 checkedIncrement(Pos, End, errorMessage);
1548 const std::string& CmdName = *Pos;
1551 throw "$CALL invocation: empty argument list!";
1554 O << CmdName << "(";
1557 bool firstIteration = true;
1559 checkedIncrement(Pos, End, errorMessage);
1560 const std::string& Arg = *Pos;
1561 assert(Arg.size() != 0);
1567 firstIteration = false;
1571 if (Arg == "$INFILE") {
1573 throw "$CALL(Hook, $INFILE) can't be used with a Join tool!";
1575 O << "inFile.c_str()";
1578 O << '"' << Arg << '"';
1587 /// SubstituteEnv - Given '$ENV(VAR_NAME)', output 'getenv("VAR_NAME")'. Helper
1588 /// function used by SubstituteSpecialCommands().
1589 StrVector::const_iterator
1590 SubstituteEnv (StrVector::const_iterator Pos,
1591 StrVector::const_iterator End, raw_ostream& O)
1593 const char* errorMessage = "Syntax error in $ENV invocation!";
1594 checkedIncrement(Pos, End, errorMessage);
1595 const std::string& EnvName = *Pos;
1598 throw "$ENV invocation: empty argument list!";
1600 O << "checkCString(std::getenv(\"";
1604 checkedIncrement(Pos, End, errorMessage);
1609 /// SubstituteSpecialCommands - Given an invocation of $CALL or $ENV, output
1610 /// handler code. Helper function used by EmitCmdLineVecFill().
1611 StrVector::const_iterator
1612 SubstituteSpecialCommands (StrVector::const_iterator Pos,
1613 StrVector::const_iterator End,
1614 bool IsJoin, raw_ostream& O)
1617 const std::string& cmd = *Pos;
1619 // Perform substitution.
1620 if (cmd == "$CALL") {
1621 Pos = SubstituteCall(Pos, End, IsJoin, O);
1623 else if (cmd == "$ENV") {
1624 Pos = SubstituteEnv(Pos, End, O);
1627 throw "Unknown special command: " + cmd;
1630 // Handle '$CMD(ARG)/additional/text'.
1631 const std::string& Leftover = *Pos;
1632 assert(Leftover.at(0) == ')');
1633 if (Leftover.size() != 1)
1634 O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1639 /// EmitCmdLineVecFill - Emit code that fills in the command line
1640 /// vector. Helper function used by EmitGenerateActionMethod().
1641 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1642 bool IsJoin, unsigned IndentLevel,
1645 TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1648 throw "Tool '" + ToolName + "' has empty command line!";
1650 StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1652 // If there is a hook invocation on the place of the first command, skip it.
1653 assert(!StrVec[0].empty());
1654 if (StrVec[0][0] == '$') {
1655 while (I != E && (*I)[0] != ')' )
1658 // Skip the ')' symbol.
1665 bool hasINFILE = false;
1667 for (; I != E; ++I) {
1668 const std::string& cmd = *I;
1669 assert(!cmd.empty());
1670 O.indent(IndentLevel);
1671 if (cmd.at(0) == '$') {
1672 if (cmd == "$INFILE") {
1675 O << "for (PathVector::const_iterator B = inFiles.begin()"
1676 << ", E = inFiles.end();\n";
1677 O.indent(IndentLevel) << "B != E; ++B)\n";
1678 O.indent(IndentLevel + Indent1) << "vec.push_back(B->str());\n";
1681 O << "vec.push_back(inFile.str());\n";
1684 else if (cmd == "$OUTFILE") {
1685 O << "vec.push_back(\"\");\n";
1686 O.indent(IndentLevel) << "out_file_index = vec.size()-1;\n";
1689 O << "vec.push_back(";
1690 I = SubstituteSpecialCommands(I, E, IsJoin, O);
1695 O << "vec.push_back(\"" << cmd << "\");\n";
1699 throw "Tool '" + ToolName + "' doesn't take any input!";
1701 O.indent(IndentLevel) << "cmd = ";
1702 if (StrVec[0][0] == '$')
1703 SubstituteSpecialCommands(StrVec.begin(), StrVec.end(), IsJoin, O);
1705 O << '"' << StrVec[0] << '"';
1709 /// EmitCmdLineVecFillCallback - A function object wrapper around
1710 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1711 /// argument to EmitCaseConstructHandler().
1712 class EmitCmdLineVecFillCallback {
1714 const std::string& ToolName;
1716 EmitCmdLineVecFillCallback(bool J, const std::string& TN)
1717 : IsJoin(J), ToolName(TN) {}
1719 void operator()(const Init* Statement, unsigned IndentLevel,
1720 raw_ostream& O) const
1722 EmitCmdLineVecFill(Statement, ToolName, IsJoin, IndentLevel, O);
1726 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1727 /// implement EmitActionHandler. Emits code for
1728 /// handling the (forward) and (forward_as) option properties.
1729 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1730 unsigned IndentLevel,
1731 const std::string& NewName,
1733 const std::string& Name = NewName.empty()
1736 unsigned IndentLevel1 = IndentLevel + Indent1;
1739 case OptionType::Switch:
1740 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1742 case OptionType::Parameter:
1743 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1744 O.indent(IndentLevel) << "vec.push_back(" << D.GenVariableName() << ");\n";
1746 case OptionType::Prefix:
1747 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\" + "
1748 << D.GenVariableName() << ");\n";
1750 case OptionType::PrefixList:
1751 O.indent(IndentLevel)
1752 << "for (" << D.GenTypeDeclaration()
1753 << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1754 O.indent(IndentLevel)
1755 << "E = " << D.GenVariableName() << ".end(); B != E;) {\n";
1756 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\" + " << "*B);\n";
1757 O.indent(IndentLevel1) << "++B;\n";
1759 for (int i = 1, j = D.MultiVal; i < j; ++i) {
1760 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1761 O.indent(IndentLevel1) << "++B;\n";
1764 O.indent(IndentLevel) << "}\n";
1766 case OptionType::ParameterList:
1767 O.indent(IndentLevel)
1768 << "for (" << D.GenTypeDeclaration() << "::iterator B = "
1769 << D.GenVariableName() << ".begin(),\n";
1770 O.indent(IndentLevel) << "E = " << D.GenVariableName()
1771 << ".end() ; B != E;) {\n";
1772 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\");\n";
1774 for (int i = 0, j = D.MultiVal; i < j; ++i) {
1775 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1776 O.indent(IndentLevel1) << "++B;\n";
1779 O.indent(IndentLevel) << "}\n";
1781 case OptionType::Alias:
1783 throw "Aliases are not allowed in tool option descriptions!";
1787 /// ActionHandlingCallbackBase - Base class of EmitActionHandlersCallback and
1788 /// EmitPreprocessOptionsCallback.
1789 struct ActionHandlingCallbackBase {
1791 void onErrorDag(const DagInit& d,
1792 unsigned IndentLevel, raw_ostream& O) const
1794 O.indent(IndentLevel)
1795 << "throw std::runtime_error(\"" <<
1796 (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0))
1801 void onWarningDag(const DagInit& d,
1802 unsigned IndentLevel, raw_ostream& O) const
1804 checkNumberOfArguments(&d, 1);
1805 O.indent(IndentLevel) << "llvm::errs() << \""
1806 << InitPtrToString(d.getArg(0)) << "\";\n";
1811 /// EmitActionHandlersCallback - Emit code that handles actions. Used by
1812 /// EmitGenerateActionMethod() as an argument to EmitCaseConstructHandler().
1813 class EmitActionHandlersCallback;
1814 typedef void (EmitActionHandlersCallback::* EmitActionHandlersCallbackHandler)
1815 (const DagInit&, unsigned, raw_ostream&) const;
1817 class EmitActionHandlersCallback
1818 : public ActionHandlingCallbackBase,
1819 public HandlerTable<EmitActionHandlersCallbackHandler>
1821 const OptionDescriptions& OptDescs;
1822 typedef EmitActionHandlersCallbackHandler Handler;
1824 /// EmitHookInvocation - Common code for hook invocation from actions. Used by
1825 /// onAppendCmd and onOutputSuffix.
1826 void EmitHookInvocation(const std::string& Str,
1827 const char* BlockOpen, const char* BlockClose,
1828 unsigned IndentLevel, raw_ostream& O) const
1831 TokenizeCmdline(Str, Out);
1833 for (StrVector::const_iterator B = Out.begin(), E = Out.end();
1835 const std::string& cmd = *B;
1837 O.indent(IndentLevel) << BlockOpen;
1839 if (cmd.at(0) == '$')
1840 B = SubstituteSpecialCommands(B, E, /* IsJoin = */ true, O);
1842 O << '"' << cmd << '"';
1848 void onAppendCmd (const DagInit& Dag,
1849 unsigned IndentLevel, raw_ostream& O) const
1851 checkNumberOfArguments(&Dag, 1);
1852 this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
1853 "vec.push_back(", ");\n", IndentLevel, O);
1856 void onForward (const DagInit& Dag,
1857 unsigned IndentLevel, raw_ostream& O) const
1859 checkNumberOfArguments(&Dag, 1);
1860 const std::string& Name = InitPtrToString(Dag.getArg(0));
1861 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1862 IndentLevel, "", O);
1865 void onForwardAs (const DagInit& Dag,
1866 unsigned IndentLevel, raw_ostream& O) const
1868 checkNumberOfArguments(&Dag, 2);
1869 const std::string& Name = InitPtrToString(Dag.getArg(0));
1870 const std::string& NewName = InitPtrToString(Dag.getArg(1));
1871 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1872 IndentLevel, NewName, O);
1875 void onForwardValue (const DagInit& Dag,
1876 unsigned IndentLevel, raw_ostream& O) const
1878 checkNumberOfArguments(&Dag, 1);
1879 const std::string& Name = InitPtrToString(Dag.getArg(0));
1880 const OptionDescription& D = OptDescs.FindListOrParameter(Name);
1882 if (D.isParameter()) {
1883 O.indent(IndentLevel) << "vec.push_back("
1884 << D.GenVariableName() << ");\n";
1887 O.indent(IndentLevel) << "std::copy(" << D.GenVariableName()
1888 << ".begin(), " << D.GenVariableName()
1889 << ".end(), std::back_inserter(vec));\n";
1893 void onForwardTransformedValue (const DagInit& Dag,
1894 unsigned IndentLevel, raw_ostream& O) const
1896 checkNumberOfArguments(&Dag, 2);
1897 const std::string& Name = InitPtrToString(Dag.getArg(0));
1898 const std::string& Hook = InitPtrToString(Dag.getArg(1));
1899 const OptionDescription& D = OptDescs.FindListOrParameter(Name);
1901 O.indent(IndentLevel) << "vec.push_back(" << "hooks::"
1902 << Hook << "(" << D.GenVariableName()
1903 << (D.isParameter() ? ".c_str()" : "") << "));\n";
1906 void onOutputSuffix (const DagInit& Dag,
1907 unsigned IndentLevel, raw_ostream& O) const
1909 checkNumberOfArguments(&Dag, 1);
1910 this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
1911 "output_suffix = ", ";\n", IndentLevel, O);
1914 void onStopCompilation (const DagInit& Dag,
1915 unsigned IndentLevel, raw_ostream& O) const
1917 O.indent(IndentLevel) << "stop_compilation = true;\n";
1921 void onUnpackValues (const DagInit& Dag,
1922 unsigned IndentLevel, raw_ostream& O) const
1924 throw "'unpack_values' is deprecated. "
1925 "Use 'comma_separated' + 'forward_value' instead!";
1930 explicit EmitActionHandlersCallback(const OptionDescriptions& OD)
1933 if (!staticMembersInitialized_) {
1934 AddHandler("error", &EmitActionHandlersCallback::onErrorDag);
1935 AddHandler("warning", &EmitActionHandlersCallback::onWarningDag);
1936 AddHandler("append_cmd", &EmitActionHandlersCallback::onAppendCmd);
1937 AddHandler("forward", &EmitActionHandlersCallback::onForward);
1938 AddHandler("forward_as", &EmitActionHandlersCallback::onForwardAs);
1939 AddHandler("forward_value", &EmitActionHandlersCallback::onForwardValue);
1940 AddHandler("forward_transformed_value",
1941 &EmitActionHandlersCallback::onForwardTransformedValue);
1942 AddHandler("output_suffix", &EmitActionHandlersCallback::onOutputSuffix);
1943 AddHandler("stop_compilation",
1944 &EmitActionHandlersCallback::onStopCompilation);
1945 AddHandler("unpack_values",
1946 &EmitActionHandlersCallback::onUnpackValues);
1948 staticMembersInitialized_ = true;
1952 void operator()(const Init* Statement,
1953 unsigned IndentLevel, raw_ostream& O) const
1955 const DagInit& Dag = InitPtrToDag(Statement);
1956 const std::string& ActionName = GetOperatorName(Dag);
1957 Handler h = GetHandler(ActionName);
1959 ((this)->*(h))(Dag, IndentLevel, O);
1963 bool IsOutFileIndexCheckRequiredStr (const Init* CmdLine) {
1965 TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1967 for (StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1969 if (*I == "$OUTFILE")
1976 class IsOutFileIndexCheckRequiredStrCallback {
1980 IsOutFileIndexCheckRequiredStrCallback(bool* ret) : ret_(ret)
1983 void operator()(const Init* CmdLine) {
1984 // Ignore nested 'case' DAG.
1985 if (typeid(*CmdLine) == typeid(DagInit))
1988 if (IsOutFileIndexCheckRequiredStr(CmdLine))
1992 void operator()(const DagInit* Test, unsigned, bool) {
1993 this->operator()(Test);
1995 void operator()(const Init* Statement, unsigned) {
1996 this->operator()(Statement);
2000 bool IsOutFileIndexCheckRequiredCase (Init* CmdLine) {
2002 WalkCase(CmdLine, Id(), IsOutFileIndexCheckRequiredStrCallback(&ret));
2006 /// IsOutFileIndexCheckRequired - Should we emit an "out_file_index != -1" check
2007 /// in EmitGenerateActionMethod() ?
2008 bool IsOutFileIndexCheckRequired (Init* CmdLine) {
2009 if (typeid(*CmdLine) == typeid(StringInit))
2010 return IsOutFileIndexCheckRequiredStr(CmdLine);
2012 return IsOutFileIndexCheckRequiredCase(CmdLine);
2015 void EmitGenerateActionMethodHeader(const ToolDescription& D,
2016 bool IsJoin, raw_ostream& O)
2019 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
2021 O.indent(Indent1) << "Action GenerateAction(const sys::Path& inFile,\n";
2023 O.indent(Indent2) << "bool HasChildren,\n";
2024 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
2025 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
2026 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
2027 O.indent(Indent1) << "{\n";
2028 O.indent(Indent2) << "std::string cmd;\n";
2029 O.indent(Indent2) << "std::vector<std::string> vec;\n";
2030 O.indent(Indent2) << "bool stop_compilation = !HasChildren;\n";
2031 O.indent(Indent2) << "const char* output_suffix = \""
2032 << D.OutputSuffix << "\";\n";
2035 // EmitGenerateActionMethod - Emit either a normal or a "join" version of the
2036 // Tool::GenerateAction() method.
2037 void EmitGenerateActionMethod (const ToolDescription& D,
2038 const OptionDescriptions& OptDescs,
2039 bool IsJoin, raw_ostream& O) {
2041 EmitGenerateActionMethodHeader(D, IsJoin, O);
2044 throw "Tool " + D.Name + " has no cmd_line property!";
2046 bool IndexCheckRequired = IsOutFileIndexCheckRequired(D.CmdLine);
2047 O.indent(Indent2) << "int out_file_index"
2048 << (IndexCheckRequired ? " = -1" : "")
2051 // Process the cmd_line property.
2052 if (typeid(*D.CmdLine) == typeid(StringInit))
2053 EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
2055 EmitCaseConstructHandler(D.CmdLine, Indent2,
2056 EmitCmdLineVecFillCallback(IsJoin, D.Name),
2059 // For every understood option, emit handling code.
2061 EmitCaseConstructHandler(D.Actions, Indent2,
2062 EmitActionHandlersCallback(OptDescs),
2063 false, OptDescs, O);
2067 << "std::string out_file = OutFilename("
2068 << (IsJoin ? "sys::Path(),\n" : "inFile,\n");
2069 O.indent(Indent3) << "TempDir, stop_compilation, output_suffix).str();\n\n";
2071 if (IndexCheckRequired)
2072 O.indent(Indent2) << "if (out_file_index != -1)\n";
2073 O.indent(IndexCheckRequired ? Indent3 : Indent2)
2074 << "vec[out_file_index] = out_file;\n";
2076 // Handle the Sink property.
2078 O.indent(Indent2) << "if (!" << SinkOptionName << ".empty()) {\n";
2079 O.indent(Indent3) << "vec.insert(vec.end(), "
2080 << SinkOptionName << ".begin(), " << SinkOptionName
2082 O.indent(Indent2) << "}\n";
2085 O.indent(Indent2) << "return Action(cmd, vec, stop_compilation, out_file);\n";
2086 O.indent(Indent1) << "}\n\n";
2089 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
2090 /// a given Tool class.
2091 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
2092 const OptionDescriptions& OptDescs,
2094 if (!ToolDesc.isJoin()) {
2095 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
2096 O.indent(Indent2) << "bool HasChildren,\n";
2097 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
2098 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
2099 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
2100 O.indent(Indent1) << "{\n";
2101 O.indent(Indent2) << "throw std::runtime_error(\"" << ToolDesc.Name
2102 << " is not a Join tool!\");\n";
2103 O.indent(Indent1) << "}\n\n";
2106 EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
2109 EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
2112 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
2113 /// methods for a given Tool class.
2114 void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
2115 O.indent(Indent1) << "const char** InputLanguages() const {\n";
2116 O.indent(Indent2) << "return InputLanguages_;\n";
2117 O.indent(Indent1) << "}\n\n";
2119 if (D.OutLanguage.empty())
2120 throw "Tool " + D.Name + " has no 'out_language' property!";
2122 O.indent(Indent1) << "const char* OutputLanguage() const {\n";
2123 O.indent(Indent2) << "return \"" << D.OutLanguage << "\";\n";
2124 O.indent(Indent1) << "}\n\n";
2127 /// EmitNameMethod - Emit the Name() method for a given Tool class.
2128 void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
2129 O.indent(Indent1) << "const char* Name() const {\n";
2130 O.indent(Indent2) << "return \"" << D.Name << "\";\n";
2131 O.indent(Indent1) << "}\n\n";
2134 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
2136 void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
2137 O.indent(Indent1) << "bool IsJoin() const {\n";
2139 O.indent(Indent2) << "return true;\n";
2141 O.indent(Indent2) << "return false;\n";
2142 O.indent(Indent1) << "}\n\n";
2145 /// EmitStaticMemberDefinitions - Emit static member definitions for a
2146 /// given Tool class.
2147 void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
2148 if (D.InLanguage.empty())
2149 throw "Tool " + D.Name + " has no 'in_language' property!";
2151 O << "const char* " << D.Name << "::InputLanguages_[] = {";
2152 for (StrVector::const_iterator B = D.InLanguage.begin(),
2153 E = D.InLanguage.end(); B != E; ++B)
2154 O << '\"' << *B << "\", ";
2158 /// EmitToolClassDefinition - Emit a Tool class definition.
2159 void EmitToolClassDefinition (const ToolDescription& D,
2160 const OptionDescriptions& OptDescs,
2162 if (D.Name == "root")
2166 O << "class " << D.Name << " : public ";
2172 O << "{\nprivate:\n";
2173 O.indent(Indent1) << "static const char* InputLanguages_[];\n\n";
2176 EmitNameMethod(D, O);
2177 EmitInOutLanguageMethods(D, O);
2178 EmitIsJoinMethod(D, O);
2179 EmitGenerateActionMethods(D, OptDescs, O);
2181 // Close class definition
2184 EmitStaticMemberDefinitions(D, O);
2188 /// EmitOptionDefinitions - Iterate over a list of option descriptions
2189 /// and emit registration code.
2190 void EmitOptionDefinitions (const OptionDescriptions& descs,
2191 bool HasSink, bool HasExterns,
2194 std::vector<OptionDescription> Aliases;
2196 // Emit static cl::Option variables.
2197 for (OptionDescriptions::const_iterator B = descs.begin(),
2198 E = descs.end(); B!=E; ++B) {
2199 const OptionDescription& val = B->second;
2201 if (val.Type == OptionType::Alias) {
2202 Aliases.push_back(val);
2209 O << val.GenTypeDeclaration() << ' '
2210 << val.GenVariableName();
2212 if (val.isExtern()) {
2217 O << "(\"" << val.Name << "\"\n";
2219 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
2220 O << ", cl::Prefix";
2222 if (val.isRequired()) {
2223 if (val.isList() && !val.isMultiVal())
2224 O << ", cl::OneOrMore";
2226 O << ", cl::Required";
2228 else if (val.isOneOrMore() && val.isList()) {
2229 O << ", cl::OneOrMore";
2231 else if (val.isOptional() && val.isList()) {
2232 O << ", cl::Optional";
2235 if (val.isReallyHidden())
2236 O << ", cl::ReallyHidden";
2237 else if (val.isHidden())
2238 O << ", cl::Hidden";
2240 if (val.isCommaSeparated())
2241 O << ", cl::CommaSeparated";
2243 if (val.MultiVal > 1)
2244 O << ", cl::multi_val(" << val.MultiVal << ')';
2247 const std::string& str = val.InitVal->getAsString();
2248 O << ", cl::init(" << str << ')';
2251 if (!val.Help.empty())
2252 O << ", cl::desc(\"" << val.Help << "\")";
2257 // Emit the aliases (they should go after all the 'proper' options).
2258 for (std::vector<OptionDescription>::const_iterator
2259 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
2260 const OptionDescription& val = *B;
2262 O << val.GenTypeDeclaration() << ' '
2263 << val.GenVariableName()
2264 << "(\"" << val.Name << '\"';
2266 const OptionDescription& D = descs.FindOption(val.Help);
2267 O << ", cl::aliasopt(" << D.GenVariableName() << ")";
2269 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
2272 // Emit the sink option.
2274 O << (HasExterns ? "extern cl" : "cl")
2275 << "::list<std::string> " << SinkOptionName
2276 << (HasExterns ? ";\n" : "(cl::Sink);\n");
2281 /// EmitPreprocessOptionsCallback - Helper function passed to
2282 /// EmitCaseConstructHandler() by EmitPreprocessOptions().
2283 class EmitPreprocessOptionsCallback : ActionHandlingCallbackBase {
2284 const OptionDescriptions& OptDescs_;
2286 void onUnsetOption(Init* i, unsigned IndentLevel, raw_ostream& O) {
2287 const std::string& OptName = InitPtrToString(i);
2288 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2290 if (OptDesc.isSwitch()) {
2291 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = false;\n";
2293 else if (OptDesc.isParameter()) {
2294 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = \"\";\n";
2296 else if (OptDesc.isList()) {
2297 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2300 throw "Can't apply 'unset_option' to alias option '" + OptName + "'!";
2304 void processDag(const Init* I, unsigned IndentLevel, raw_ostream& O)
2306 const DagInit& d = InitPtrToDag(I);
2307 const std::string& OpName = GetOperatorName(d);
2309 if (OpName == "warning") {
2310 this->onWarningDag(d, IndentLevel, O);
2312 else if (OpName == "error") {
2313 this->onWarningDag(d, IndentLevel, O);
2315 else if (OpName == "unset_option") {
2316 checkNumberOfArguments(&d, 1);
2317 Init* I = d.getArg(0);
2318 if (typeid(*I) == typeid(ListInit)) {
2319 const ListInit& DagList = *static_cast<const ListInit*>(I);
2320 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
2322 this->onUnsetOption(*B, IndentLevel, O);
2325 this->onUnsetOption(I, IndentLevel, O);
2329 throw "Unknown operator in the option preprocessor: '" + OpName + "'!"
2330 "\nOnly 'warning', 'error' and 'unset_option' are allowed.";
2336 void operator()(const Init* I, unsigned IndentLevel, raw_ostream& O) {
2337 this->processDag(I, IndentLevel, O);
2340 EmitPreprocessOptionsCallback(const OptionDescriptions& OptDescs)
2341 : OptDescs_(OptDescs)
2345 /// EmitPreprocessOptions - Emit the PreprocessOptionsLocal() function.
2346 void EmitPreprocessOptions (const RecordKeeper& Records,
2347 const OptionDescriptions& OptDecs, raw_ostream& O)
2349 O << "void PreprocessOptionsLocal() {\n";
2351 const RecordVector& OptionPreprocessors =
2352 Records.getAllDerivedDefinitions("OptionPreprocessor");
2354 for (RecordVector::const_iterator B = OptionPreprocessors.begin(),
2355 E = OptionPreprocessors.end(); B!=E; ++B) {
2356 DagInit* Case = (*B)->getValueAsDag("preprocessor");
2357 EmitCaseConstructHandler(Case, Indent1,
2358 EmitPreprocessOptionsCallback(OptDecs),
2365 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMapLocal() function.
2366 void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
2368 O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
2370 // Get the relevant field out of RecordKeeper
2371 const Record* LangMapRecord = Records.getDef("LanguageMap");
2373 // It is allowed for a plugin to have no language map.
2374 if (LangMapRecord) {
2376 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
2377 if (!LangsToSuffixesList)
2378 throw "Error in the language map definition!";
2380 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
2381 const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
2383 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
2384 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
2386 for (unsigned i = 0; i < Suffixes->size(); ++i)
2387 O.indent(Indent1) << "langMap[\""
2388 << InitPtrToString(Suffixes->getElement(i))
2389 << "\"] = \"" << Lang << "\";\n";
2396 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
2397 /// by EmitEdgeClass().
2398 void IncDecWeight (const Init* i, unsigned IndentLevel,
2400 const DagInit& d = InitPtrToDag(i);
2401 const std::string& OpName = GetOperatorName(d);
2403 if (OpName == "inc_weight") {
2404 O.indent(IndentLevel) << "ret += ";
2406 else if (OpName == "dec_weight") {
2407 O.indent(IndentLevel) << "ret -= ";
2409 else if (OpName == "error") {
2410 checkNumberOfArguments(&d, 1);
2411 O.indent(IndentLevel) << "throw std::runtime_error(\""
2412 << InitPtrToString(d.getArg(0))
2417 throw "Unknown operator in edge properties list: '" + OpName + "'!"
2418 "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
2421 if (d.getNumArgs() > 0)
2422 O << InitPtrToInt(d.getArg(0)) << ";\n";
2428 /// EmitEdgeClass - Emit a single Edge# class.
2429 void EmitEdgeClass (unsigned N, const std::string& Target,
2430 DagInit* Case, const OptionDescriptions& OptDescs,
2433 // Class constructor.
2434 O << "class Edge" << N << ": public Edge {\n"
2436 O.indent(Indent1) << "Edge" << N << "() : Edge(\"" << Target
2439 // Function Weight().
2441 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n";
2442 O.indent(Indent2) << "unsigned ret = 0;\n";
2444 // Handle the 'case' construct.
2445 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
2447 O.indent(Indent2) << "return ret;\n";
2448 O.indent(Indent1) << "};\n\n};\n\n";
2451 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
2452 void EmitEdgeClasses (const RecordVector& EdgeVector,
2453 const OptionDescriptions& OptDescs,
2456 for (RecordVector::const_iterator B = EdgeVector.begin(),
2457 E = EdgeVector.end(); B != E; ++B) {
2458 const Record* Edge = *B;
2459 const std::string& NodeB = Edge->getValueAsString("b");
2460 DagInit* Weight = Edge->getValueAsDag("weight");
2462 if (!isDagEmpty(Weight))
2463 EmitEdgeClass(i, NodeB, Weight, OptDescs, O);
2468 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraphLocal()
2470 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
2471 const ToolDescriptions& ToolDescs,
2474 O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
2476 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2477 E = ToolDescs.end(); B != E; ++B)
2478 O.indent(Indent1) << "G.insertNode(new " << (*B)->Name << "());\n";
2485 for (RecordVector::const_iterator B = EdgeVector.begin(),
2486 E = EdgeVector.end(); B != E; ++B) {
2487 const Record* Edge = *B;
2488 const std::string& NodeA = Edge->getValueAsString("a");
2489 const std::string& NodeB = Edge->getValueAsString("b");
2490 DagInit* Weight = Edge->getValueAsDag("weight");
2492 O.indent(Indent1) << "G.insertEdge(\"" << NodeA << "\", ";
2494 if (isDagEmpty(Weight))
2495 O << "new SimpleEdge(\"" << NodeB << "\")";
2497 O << "new Edge" << i << "()";
2506 /// HookInfo - Information about the hook type and number of arguments.
2509 // A hook can either have a single parameter of type std::vector<std::string>,
2510 // or NumArgs parameters of type const char*.
2511 enum HookType { ListHook, ArgHook };
2516 HookInfo() : Type(ArgHook), NumArgs(1)
2519 HookInfo(HookType T) : Type(T), NumArgs(1)
2522 HookInfo(unsigned N) : Type(ArgHook), NumArgs(N)
2526 typedef llvm::StringMap<HookInfo> HookInfoMap;
2528 /// ExtractHookNames - Extract the hook names from all instances of
2529 /// $CALL(HookName) in the provided command line string/action. Helper
2530 /// function used by FillInHookNames().
2531 class ExtractHookNames {
2532 HookInfoMap& HookNames_;
2533 const OptionDescriptions& OptDescs_;
2535 ExtractHookNames(HookInfoMap& HookNames, const OptionDescriptions& OptDescs)
2536 : HookNames_(HookNames), OptDescs_(OptDescs)
2539 void onAction (const DagInit& Dag) {
2540 const std::string& Name = GetOperatorName(Dag);
2542 if (Name == "forward_transformed_value") {
2543 checkNumberOfArguments(Dag, 2);
2544 const std::string& OptName = InitPtrToString(Dag.getArg(0));
2545 const std::string& HookName = InitPtrToString(Dag.getArg(1));
2546 const OptionDescription& D = OptDescs_.FindOption(OptName);
2548 HookNames_[HookName] = HookInfo(D.isList() ? HookInfo::ListHook
2549 : HookInfo::ArgHook);
2551 else if (Name == "append_cmd" || Name == "output_suffix") {
2552 checkNumberOfArguments(Dag, 1);
2553 this->onCmdLine(InitPtrToString(Dag.getArg(0)));
2557 void onCmdLine(const std::string& Cmd) {
2559 TokenizeCmdline(Cmd, cmds);
2561 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
2563 const std::string& cmd = *B;
2565 if (cmd == "$CALL") {
2566 unsigned NumArgs = 0;
2567 checkedIncrement(B, E, "Syntax error in $CALL invocation!");
2568 const std::string& HookName = *B;
2570 if (HookName.at(0) == ')')
2571 throw "$CALL invoked with no arguments!";
2573 while (++B != E && B->at(0) != ')') {
2577 HookInfoMap::const_iterator H = HookNames_.find(HookName);
2579 if (H != HookNames_.end() && H->second.NumArgs != NumArgs &&
2580 H->second.Type != HookInfo::ArgHook)
2581 throw "Overloading of hooks is not allowed. Overloaded hook: "
2584 HookNames_[HookName] = HookInfo(NumArgs);
2589 void operator()(const Init* Arg) {
2591 // We're invoked on an action (either a dag or a dag list).
2592 if (typeid(*Arg) == typeid(DagInit)) {
2593 const DagInit& Dag = InitPtrToDag(Arg);
2594 this->onAction(Dag);
2597 else if (typeid(*Arg) == typeid(ListInit)) {
2598 const ListInit& List = InitPtrToList(Arg);
2599 for (ListInit::const_iterator B = List.begin(), E = List.end(); B != E;
2601 const DagInit& Dag = InitPtrToDag(*B);
2602 this->onAction(Dag);
2607 // We're invoked on a command line.
2608 this->onCmdLine(InitPtrToString(Arg));
2611 void operator()(const DagInit* Test, unsigned, bool) {
2612 this->operator()(Test);
2614 void operator()(const Init* Statement, unsigned) {
2615 this->operator()(Statement);
2619 /// FillInHookNames - Actually extract the hook names from all command
2620 /// line strings. Helper function used by EmitHookDeclarations().
2621 void FillInHookNames(const ToolDescriptions& ToolDescs,
2622 const OptionDescriptions& OptDescs,
2623 HookInfoMap& HookNames)
2625 // For all tool descriptions:
2626 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2627 E = ToolDescs.end(); B != E; ++B) {
2628 const ToolDescription& D = *(*B);
2630 // Look for 'forward_transformed_value' in 'actions'.
2632 WalkCase(D.Actions, Id(), ExtractHookNames(HookNames, OptDescs));
2634 // Look for hook invocations in 'cmd_line'.
2637 if (dynamic_cast<StringInit*>(D.CmdLine))
2638 // This is a string.
2639 ExtractHookNames(HookNames, OptDescs).operator()(D.CmdLine);
2641 // This is a 'case' construct.
2642 WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames, OptDescs));
2646 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
2647 /// property records and emit hook function declaration for each
2648 /// instance of $CALL(HookName).
2649 void EmitHookDeclarations(const ToolDescriptions& ToolDescs,
2650 const OptionDescriptions& OptDescs, raw_ostream& O) {
2651 HookInfoMap HookNames;
2653 FillInHookNames(ToolDescs, OptDescs, HookNames);
2654 if (HookNames.empty())
2657 O << "namespace hooks {\n";
2658 for (HookInfoMap::const_iterator B = HookNames.begin(),
2659 E = HookNames.end(); B != E; ++B) {
2660 const char* HookName = B->first();
2661 const HookInfo& Info = B->second;
2663 O.indent(Indent1) << "std::string " << HookName << "(";
2665 if (Info.Type == HookInfo::ArgHook) {
2666 for (unsigned i = 0, j = Info.NumArgs; i < j; ++i) {
2667 O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
2671 O << "const std::vector<std::string>& Arg";
2679 /// EmitRegisterPlugin - Emit code to register this plugin.
2680 void EmitRegisterPlugin(int Priority, raw_ostream& O) {
2681 O << "struct Plugin : public llvmc::BasePlugin {\n\n";
2682 O.indent(Indent1) << "int Priority() const { return "
2683 << Priority << "; }\n\n";
2684 O.indent(Indent1) << "void PreprocessOptions() const\n";
2685 O.indent(Indent1) << "{ PreprocessOptionsLocal(); }\n\n";
2686 O.indent(Indent1) << "void PopulateLanguageMap(LanguageMap& langMap) const\n";
2687 O.indent(Indent1) << "{ PopulateLanguageMapLocal(langMap); }\n\n";
2689 << "void PopulateCompilationGraph(CompilationGraph& graph) const\n";
2690 O.indent(Indent1) << "{ PopulateCompilationGraphLocal(graph); }\n"
2692 << "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
2695 /// EmitIncludes - Emit necessary #include directives and some
2696 /// additional declarations.
2697 void EmitIncludes(raw_ostream& O) {
2698 O << "#include \"llvm/CompilerDriver/BuiltinOptions.h\"\n"
2699 << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
2700 << "#include \"llvm/CompilerDriver/ForceLinkageMacros.h\"\n"
2701 << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
2702 << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
2704 << "#include \"llvm/Support/CommandLine.h\"\n"
2705 << "#include \"llvm/Support/raw_ostream.h\"\n\n"
2707 << "#include <algorithm>\n"
2708 << "#include <cstdlib>\n"
2709 << "#include <iterator>\n"
2710 << "#include <stdexcept>\n\n"
2712 << "using namespace llvm;\n"
2713 << "using namespace llvmc;\n\n"
2715 << "extern cl::opt<std::string> OutputFilename;\n\n"
2717 << "inline const char* checkCString(const char* s)\n"
2718 << "{ return s == NULL ? \"\" : s; }\n\n";
2722 /// PluginData - Holds all information about a plugin.
2724 OptionDescriptions OptDescs;
2727 ToolDescriptions ToolDescs;
2732 /// HasSink - Go through the list of tool descriptions and check if
2733 /// there are any with the 'sink' property set.
2734 bool HasSink(const ToolDescriptions& ToolDescs) {
2735 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2736 E = ToolDescs.end(); B != E; ++B)
2743 /// HasExterns - Go through the list of option descriptions and check
2744 /// if there are any external options.
2745 bool HasExterns(const OptionDescriptions& OptDescs) {
2746 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
2747 E = OptDescs.end(); B != E; ++B)
2748 if (B->second.isExtern())
2754 /// CollectPluginData - Collect tool and option properties,
2755 /// compilation graph edges and plugin priority from the parse tree.
2756 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
2757 // Collect option properties.
2758 const RecordVector& OptionLists =
2759 Records.getAllDerivedDefinitions("OptionList");
2760 CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
2763 // Collect tool properties.
2764 const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
2765 CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
2766 Data.HasSink = HasSink(Data.ToolDescs);
2767 Data.HasExterns = HasExterns(Data.OptDescs);
2769 // Collect compilation graph edges.
2770 const RecordVector& CompilationGraphs =
2771 Records.getAllDerivedDefinitions("CompilationGraph");
2772 FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
2775 // Calculate the priority of this plugin.
2776 const RecordVector& Priorities =
2777 Records.getAllDerivedDefinitions("PluginPriority");
2778 Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
2781 /// CheckPluginData - Perform some sanity checks on the collected data.
2782 void CheckPluginData(PluginData& Data) {
2783 // Filter out all tools not mentioned in the compilation graph.
2784 FilterNotInGraph(Data.Edges, Data.ToolDescs);
2786 // Typecheck the compilation graph.
2787 TypecheckGraph(Data.Edges, Data.ToolDescs);
2789 // Check that there are no options without side effects (specified
2790 // only in the OptionList).
2791 CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
2795 void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
2796 // Emit file header.
2799 // Emit global option registration code.
2800 EmitOptionDefinitions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
2802 // Emit hook declarations.
2803 EmitHookDeclarations(Data.ToolDescs, Data.OptDescs, O);
2805 O << "namespace {\n\n";
2807 // Emit PreprocessOptionsLocal() function.
2808 EmitPreprocessOptions(Records, Data.OptDescs, O);
2810 // Emit PopulateLanguageMapLocal() function
2811 // (language map maps from file extensions to language names).
2812 EmitPopulateLanguageMap(Records, O);
2814 // Emit Tool classes.
2815 for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
2816 E = Data.ToolDescs.end(); B!=E; ++B)
2817 EmitToolClassDefinition(*(*B), Data.OptDescs, O);
2819 // Emit Edge# classes.
2820 EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
2822 // Emit PopulateCompilationGraphLocal() function.
2823 EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
2825 // Emit code for plugin registration.
2826 EmitRegisterPlugin(Data.Priority, O);
2828 O << "} // End anonymous namespace.\n\n";
2830 // Force linkage magic.
2831 O << "namespace llvmc {\n";
2832 O << "LLVMC_FORCE_LINKAGE_DECL(LLVMC_PLUGIN_NAME) {}\n";
2839 // End of anonymous namespace
2842 /// run - The back-end entry point.
2843 void LLVMCConfigurationEmitter::run (raw_ostream &O) {
2847 CollectPluginData(Records, Data);
2848 CheckPluginData(Data);
2850 EmitSourceFileHeader("LLVMC Configuration Library", O);
2851 EmitPluginCode(Data, O);
2853 } catch (std::exception& Error) {
2854 throw Error.what() + std::string(" - usually this means a syntax error.");