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"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/System/Path.h"
32 extern cl::opt<std::string> InputFilename;
36 //===----------------------------------------------------------------------===//
39 typedef std::vector<Record*> RecordVector;
40 typedef std::vector<std::string> StrVector;
42 //===----------------------------------------------------------------------===//
46 const unsigned TabWidth = 4;
47 const unsigned Indent1 = TabWidth*1;
48 const unsigned Indent2 = TabWidth*2;
49 const unsigned Indent3 = TabWidth*3;
50 const unsigned Indent4 = TabWidth*4;
52 // Default help string.
53 const char * const DefaultHelpString = "NO HELP MESSAGE PROVIDED";
55 // Name for the "sink" option.
56 const char * const SinkOptionName = "AutoGeneratedSinkOption";
58 //===----------------------------------------------------------------------===//
61 /// Id - An 'identity' function object.
64 void operator()(const T0&) const {
66 template<typename T0, typename T1>
67 void operator()(const T0&, const T1&) const {
69 template<typename T0, typename T1, typename T2>
70 void operator()(const T0&, const T1&, const T2&) const {
74 int InitPtrToInt(const Init* ptr) {
75 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
76 return val.getValue();
79 const std::string& InitPtrToString(const Init* ptr) {
80 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
81 return val.getValue();
84 const ListInit& InitPtrToList(const Init* ptr) {
85 const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
89 const DagInit& InitPtrToDag(const Init* ptr) {
90 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
94 const std::string GetOperatorName(const DagInit& D) {
95 return D.getOperator()->getAsString();
98 /// CheckBooleanConstant - Check that the provided value is a boolean constant.
99 void CheckBooleanConstant(const Init* I) {
100 const DefInit& val = dynamic_cast<const DefInit&>(*I);
101 const std::string& str = val.getAsString();
103 if (str != "true" && str != "false") {
104 throw "Incorrect boolean value: '" + str +
105 "': must be either 'true' or 'false'";
109 // CheckNumberOfArguments - Ensure that the number of args in d is
110 // greater than or equal to min_arguments, otherwise throw an exception.
111 void CheckNumberOfArguments (const DagInit& d, unsigned minArgs) {
112 if (d.getNumArgs() < minArgs)
113 throw GetOperatorName(d) + ": too few arguments!";
116 // IsDagEmpty - is this DAG marked with an empty marker?
117 bool IsDagEmpty (const DagInit& d) {
118 return GetOperatorName(d) == "empty_dag_marker";
121 // EscapeVariableName - Escape commas and other symbols not allowed
122 // in the C++ variable names. Makes it possible to use options named
123 // like "Wa," (useful for prefix options).
124 std::string EscapeVariableName (const std::string& Var) {
126 for (unsigned i = 0; i != Var.size(); ++i) {
127 char cur_char = Var[i];
128 if (cur_char == ',') {
131 else if (cur_char == '+') {
134 else if (cur_char == '-') {
138 ret.push_back(cur_char);
144 /// EscapeQuotes - Replace '"' with '\"'.
145 std::string EscapeQuotes (const std::string& Var) {
147 for (unsigned i = 0; i != Var.size(); ++i) {
148 char cur_char = Var[i];
149 if (cur_char == '"') {
153 ret.push_back(cur_char);
159 /// OneOf - Does the input string contain this character?
160 bool OneOf(const char* lst, char c) {
168 template <class I, class S>
169 void CheckedIncrement(I& P, I E, S ErrorString) {
175 // apply is needed because C++'s syntax doesn't let us construct a function
176 // object and call it in the same statement.
177 template<typename F, typename T0>
178 void apply(F Fun, T0& Arg0) {
182 template<typename F, typename T0, typename T1>
183 void apply(F Fun, T0& Arg0, T1& Arg1) {
184 return Fun(Arg0, Arg1);
187 //===----------------------------------------------------------------------===//
188 /// Back-end specific code
191 /// OptionType - One of six different option types. See the
192 /// documentation for detailed description of differences.
193 namespace OptionType {
195 enum OptionType { Alias, Switch, SwitchList,
196 Parameter, ParameterList, Prefix, PrefixList };
198 bool IsAlias(OptionType t) {
202 bool IsList (OptionType t) {
203 return (t == SwitchList || t == ParameterList || t == PrefixList);
206 bool IsSwitch (OptionType t) {
207 return (t == Switch);
210 bool IsSwitchList (OptionType t) {
211 return (t == SwitchList);
214 bool IsParameter (OptionType t) {
215 return (t == Parameter || t == Prefix);
220 OptionType::OptionType stringToOptionType(const std::string& T) {
221 if (T == "alias_option")
222 return OptionType::Alias;
223 else if (T == "switch_option")
224 return OptionType::Switch;
225 else if (T == "switch_list_option")
226 return OptionType::SwitchList;
227 else if (T == "parameter_option")
228 return OptionType::Parameter;
229 else if (T == "parameter_list_option")
230 return OptionType::ParameterList;
231 else if (T == "prefix_option")
232 return OptionType::Prefix;
233 else if (T == "prefix_list_option")
234 return OptionType::PrefixList;
236 throw "Unknown option type: " + T + '!';
239 namespace OptionDescriptionFlags {
240 enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
241 ReallyHidden = 0x4, Extern = 0x8,
242 OneOrMore = 0x10, Optional = 0x20,
243 CommaSeparated = 0x40, ForwardNotSplit = 0x80,
244 ZeroOrMore = 0x100 };
247 /// OptionDescription - Represents data contained in a single
248 /// OptionList entry.
249 struct OptionDescription {
250 OptionType::OptionType Type;
257 OptionDescription(OptionType::OptionType t = OptionType::Switch,
258 const std::string& n = "",
259 const std::string& h = DefaultHelpString)
260 : Type(t), Name(n), Flags(0x0), Help(h), MultiVal(1), InitVal(0)
263 /// GenTypeDeclaration - Returns the C++ variable type of this
265 const char* GenTypeDeclaration() const;
267 /// GenVariableName - Returns the variable name used in the
268 /// generated C++ code.
269 std::string GenVariableName() const;
271 /// Merge - Merge two option descriptions.
272 void Merge (const OptionDescription& other);
274 /// CheckConsistency - Check that the flags are consistent.
275 void CheckConsistency() const;
277 // Misc convenient getters/setters.
279 bool isAlias() const;
281 bool isMultiVal() const;
283 bool isCommaSeparated() const;
284 void setCommaSeparated();
286 bool isExtern() const;
289 bool isForwardNotSplit() const;
290 void setForwardNotSplit();
292 bool isRequired() const;
295 bool isOneOrMore() const;
298 bool isZeroOrMore() const;
299 void setZeroOrMore();
301 bool isOptional() const;
304 bool isHidden() const;
307 bool isReallyHidden() const;
308 void setReallyHidden();
310 bool isSwitch() const
311 { return OptionType::IsSwitch(this->Type); }
313 bool isSwitchList() const
314 { return OptionType::IsSwitchList(this->Type); }
316 bool isParameter() const
317 { return OptionType::IsParameter(this->Type); }
320 { return OptionType::IsList(this->Type); }
322 bool isParameterList() const
323 { return (OptionType::IsList(this->Type)
324 && !OptionType::IsSwitchList(this->Type)); }
328 void OptionDescription::CheckConsistency() const {
331 i += this->isRequired();
332 i += this->isOptional();
333 i += this->isOneOrMore();
334 i += this->isZeroOrMore();
337 throw "Only one of (required), (optional), (one_or_more) or "
338 "(zero_or_more) properties is allowed!";
342 void OptionDescription::Merge (const OptionDescription& other)
344 if (other.Type != Type)
345 throw "Conflicting definitions for the option " + Name + "!";
347 if (Help == other.Help || Help == DefaultHelpString)
349 else if (other.Help != DefaultHelpString) {
350 llvm::errs() << "Warning: several different help strings"
351 " defined for option " + Name + "\n";
354 Flags |= other.Flags;
357 bool OptionDescription::isAlias() const {
358 return OptionType::IsAlias(this->Type);
361 bool OptionDescription::isMultiVal() const {
365 bool OptionDescription::isCommaSeparated() const {
366 return Flags & OptionDescriptionFlags::CommaSeparated;
368 void OptionDescription::setCommaSeparated() {
369 Flags |= OptionDescriptionFlags::CommaSeparated;
372 bool OptionDescription::isForwardNotSplit() const {
373 return Flags & OptionDescriptionFlags::ForwardNotSplit;
375 void OptionDescription::setForwardNotSplit() {
376 Flags |= OptionDescriptionFlags::ForwardNotSplit;
379 bool OptionDescription::isExtern() const {
380 return Flags & OptionDescriptionFlags::Extern;
382 void OptionDescription::setExtern() {
383 Flags |= OptionDescriptionFlags::Extern;
386 bool OptionDescription::isRequired() const {
387 return Flags & OptionDescriptionFlags::Required;
389 void OptionDescription::setRequired() {
390 Flags |= OptionDescriptionFlags::Required;
393 bool OptionDescription::isOneOrMore() const {
394 return Flags & OptionDescriptionFlags::OneOrMore;
396 void OptionDescription::setOneOrMore() {
397 Flags |= OptionDescriptionFlags::OneOrMore;
400 bool OptionDescription::isZeroOrMore() const {
401 return Flags & OptionDescriptionFlags::ZeroOrMore;
403 void OptionDescription::setZeroOrMore() {
404 Flags |= OptionDescriptionFlags::ZeroOrMore;
407 bool OptionDescription::isOptional() const {
408 return Flags & OptionDescriptionFlags::Optional;
410 void OptionDescription::setOptional() {
411 Flags |= OptionDescriptionFlags::Optional;
414 bool OptionDescription::isHidden() const {
415 return Flags & OptionDescriptionFlags::Hidden;
417 void OptionDescription::setHidden() {
418 Flags |= OptionDescriptionFlags::Hidden;
421 bool OptionDescription::isReallyHidden() const {
422 return Flags & OptionDescriptionFlags::ReallyHidden;
424 void OptionDescription::setReallyHidden() {
425 Flags |= OptionDescriptionFlags::ReallyHidden;
428 const char* OptionDescription::GenTypeDeclaration() const {
430 case OptionType::Alias:
432 case OptionType::PrefixList:
433 case OptionType::ParameterList:
434 return "cl::list<std::string>";
435 case OptionType::Switch:
436 return "cl::opt<bool>";
437 case OptionType::SwitchList:
438 return "cl::list<bool>";
439 case OptionType::Parameter:
440 case OptionType::Prefix:
442 return "cl::opt<std::string>";
446 std::string OptionDescription::GenVariableName() const {
447 const std::string& EscapedName = EscapeVariableName(Name);
449 case OptionType::Alias:
450 return "AutoGeneratedAlias_" + EscapedName;
451 case OptionType::PrefixList:
452 case OptionType::ParameterList:
453 return "AutoGeneratedList_" + EscapedName;
454 case OptionType::Switch:
455 return "AutoGeneratedSwitch_" + EscapedName;
456 case OptionType::SwitchList:
457 return "AutoGeneratedSwitchList_" + EscapedName;
458 case OptionType::Prefix:
459 case OptionType::Parameter:
461 return "AutoGeneratedParameter_" + EscapedName;
465 /// OptionDescriptions - An OptionDescription array plus some helper
467 class OptionDescriptions {
468 typedef StringMap<OptionDescription> container_type;
470 /// Descriptions - A list of OptionDescriptions.
471 container_type Descriptions;
474 /// FindOption - exception-throwing wrapper for find().
475 const OptionDescription& FindOption(const std::string& OptName) const;
477 // Wrappers for FindOption that throw an exception in case the option has a
479 const OptionDescription& FindSwitch(const std::string& OptName) const;
480 const OptionDescription& FindParameter(const std::string& OptName) const;
481 const OptionDescription& FindList(const std::string& OptName) const;
482 const OptionDescription& FindParameterList(const std::string& OptName) const;
483 const OptionDescription&
484 FindListOrParameter(const std::string& OptName) const;
485 const OptionDescription&
486 FindParameterListOrParameter(const std::string& OptName) const;
488 /// insertDescription - Insert new OptionDescription into
489 /// OptionDescriptions list
490 void InsertDescription (const OptionDescription& o);
492 // Support for STL-style iteration
493 typedef container_type::const_iterator const_iterator;
494 const_iterator begin() const { return Descriptions.begin(); }
495 const_iterator end() const { return Descriptions.end(); }
498 const OptionDescription&
499 OptionDescriptions::FindOption(const std::string& OptName) const {
500 const_iterator I = Descriptions.find(OptName);
501 if (I != Descriptions.end())
504 throw OptName + ": no such option!";
507 const OptionDescription&
508 OptionDescriptions::FindSwitch(const std::string& OptName) const {
509 const OptionDescription& OptDesc = this->FindOption(OptName);
510 if (!OptDesc.isSwitch())
511 throw OptName + ": incorrect option type - should be a switch!";
515 const OptionDescription&
516 OptionDescriptions::FindList(const std::string& OptName) const {
517 const OptionDescription& OptDesc = this->FindOption(OptName);
518 if (!OptDesc.isList())
519 throw OptName + ": incorrect option type - should be a list!";
523 const OptionDescription&
524 OptionDescriptions::FindParameterList(const std::string& OptName) const {
525 const OptionDescription& OptDesc = this->FindOption(OptName);
526 if (!OptDesc.isList() || OptDesc.isSwitchList())
527 throw OptName + ": incorrect option type - should be a parameter list!";
531 const OptionDescription&
532 OptionDescriptions::FindParameter(const std::string& OptName) const {
533 const OptionDescription& OptDesc = this->FindOption(OptName);
534 if (!OptDesc.isParameter())
535 throw OptName + ": incorrect option type - should be a parameter!";
539 const OptionDescription&
540 OptionDescriptions::FindListOrParameter(const std::string& OptName) const {
541 const OptionDescription& OptDesc = this->FindOption(OptName);
542 if (!OptDesc.isList() && !OptDesc.isParameter())
544 + ": incorrect option type - should be a list or parameter!";
548 const OptionDescription&
549 OptionDescriptions::FindParameterListOrParameter
550 (const std::string& OptName) const {
551 const OptionDescription& OptDesc = this->FindOption(OptName);
552 if ((!OptDesc.isList() && !OptDesc.isParameter()) || OptDesc.isSwitchList())
554 + ": incorrect option type - should be a parameter list or parameter!";
558 void OptionDescriptions::InsertDescription (const OptionDescription& o) {
559 container_type::iterator I = Descriptions.find(o.Name);
560 if (I != Descriptions.end()) {
561 OptionDescription& D = I->second;
565 Descriptions[o.Name] = o;
569 /// HandlerTable - A base class for function objects implemented as
570 /// 'tables of handlers'.
571 template <typename Handler>
574 // Implementation details.
576 /// HandlerMap - A map from property names to property handlers
577 typedef StringMap<Handler> HandlerMap;
579 static HandlerMap Handlers_;
580 static bool staticMembersInitialized_;
584 Handler GetHandler (const std::string& HandlerName) const {
585 typename HandlerMap::iterator method = Handlers_.find(HandlerName);
587 if (method != Handlers_.end()) {
588 Handler h = method->second;
592 throw "No handler found for property " + HandlerName + "!";
596 void AddHandler(const char* Property, Handler H) {
597 Handlers_[Property] = H;
602 template <class Handler, class FunctionObject>
603 Handler GetHandler(FunctionObject* Obj, const DagInit& Dag) {
604 const std::string& HandlerName = GetOperatorName(Dag);
605 return Obj->GetHandler(HandlerName);
608 template <class FunctionObject>
609 void InvokeDagInitHandler(FunctionObject* Obj, Init* I) {
610 typedef void (FunctionObject::*Handler) (const DagInit&);
612 const DagInit& Dag = InitPtrToDag(I);
613 Handler h = GetHandler<Handler>(Obj, Dag);
618 template <class FunctionObject>
619 void InvokeDagInitHandler(const FunctionObject* const Obj,
620 const Init* I, unsigned IndentLevel, raw_ostream& O)
622 typedef void (FunctionObject::*Handler)
623 (const DagInit&, unsigned IndentLevel, raw_ostream& O) const;
625 const DagInit& Dag = InitPtrToDag(I);
626 Handler h = GetHandler<Handler>(Obj, Dag);
628 ((Obj)->*(h))(Dag, IndentLevel, O);
632 template <typename H>
633 typename HandlerTable<H>::HandlerMap HandlerTable<H>::Handlers_;
635 template <typename H>
636 bool HandlerTable<H>::staticMembersInitialized_ = false;
639 /// CollectOptionProperties - Function object for iterating over an
640 /// option property list.
641 class CollectOptionProperties;
642 typedef void (CollectOptionProperties::* CollectOptionPropertiesHandler)
645 class CollectOptionProperties
646 : public HandlerTable<CollectOptionPropertiesHandler>
650 /// optDescs_ - OptionDescriptions table. This is where the
651 /// information is stored.
652 OptionDescription& optDesc_;
656 explicit CollectOptionProperties(OptionDescription& OD)
659 if (!staticMembersInitialized_) {
660 AddHandler("extern", &CollectOptionProperties::onExtern);
661 AddHandler("help", &CollectOptionProperties::onHelp);
662 AddHandler("hidden", &CollectOptionProperties::onHidden);
663 AddHandler("init", &CollectOptionProperties::onInit);
664 AddHandler("multi_val", &CollectOptionProperties::onMultiVal);
665 AddHandler("one_or_more", &CollectOptionProperties::onOneOrMore);
666 AddHandler("zero_or_more", &CollectOptionProperties::onZeroOrMore);
667 AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
668 AddHandler("required", &CollectOptionProperties::onRequired);
669 AddHandler("optional", &CollectOptionProperties::onOptional);
670 AddHandler("comma_separated", &CollectOptionProperties::onCommaSeparated);
671 AddHandler("forward_not_split",
672 &CollectOptionProperties::onForwardNotSplit);
674 staticMembersInitialized_ = true;
678 /// operator() - Just forwards to the corresponding property
680 void operator() (Init* I) {
681 InvokeDagInitHandler(this, I);
686 /// Option property handlers --
687 /// Methods that handle option properties such as (help) or (hidden).
689 void onExtern (const DagInit& d) {
690 CheckNumberOfArguments(d, 0);
691 optDesc_.setExtern();
694 void onHelp (const DagInit& d) {
695 CheckNumberOfArguments(d, 1);
696 optDesc_.Help = EscapeQuotes(InitPtrToString(d.getArg(0)));
699 void onHidden (const DagInit& d) {
700 CheckNumberOfArguments(d, 0);
701 optDesc_.setHidden();
704 void onReallyHidden (const DagInit& d) {
705 CheckNumberOfArguments(d, 0);
706 optDesc_.setReallyHidden();
709 void onCommaSeparated (const DagInit& d) {
710 CheckNumberOfArguments(d, 0);
711 if (!optDesc_.isParameterList())
712 throw "'comma_separated' is valid only on parameter list options!";
713 optDesc_.setCommaSeparated();
716 void onForwardNotSplit (const DagInit& d) {
717 CheckNumberOfArguments(d, 0);
718 if (!optDesc_.isParameter())
719 throw "'forward_not_split' is valid only for parameter options!";
720 optDesc_.setForwardNotSplit();
723 void onRequired (const DagInit& d) {
724 CheckNumberOfArguments(d, 0);
726 optDesc_.setRequired();
727 optDesc_.CheckConsistency();
730 void onInit (const DagInit& d) {
731 CheckNumberOfArguments(d, 1);
732 Init* i = d.getArg(0);
733 const std::string& str = i->getAsString();
735 bool correct = optDesc_.isParameter() && dynamic_cast<StringInit*>(i);
736 correct |= (optDesc_.isSwitch() && (str == "true" || str == "false"));
739 throw "Incorrect usage of the 'init' option property!";
741 optDesc_.InitVal = i;
744 void onOneOrMore (const DagInit& d) {
745 CheckNumberOfArguments(d, 0);
747 optDesc_.setOneOrMore();
748 optDesc_.CheckConsistency();
751 void onZeroOrMore (const DagInit& d) {
752 CheckNumberOfArguments(d, 0);
754 if (optDesc_.isList())
755 llvm::errs() << "Warning: specifying the 'zero_or_more' property "
756 "on a list option has no effect.\n";
758 optDesc_.setZeroOrMore();
759 optDesc_.CheckConsistency();
762 void onOptional (const DagInit& d) {
763 CheckNumberOfArguments(d, 0);
765 if (!optDesc_.isList())
766 llvm::errs() << "Warning: specifying the 'optional' property"
767 "on a non-list option has no effect.\n";
769 optDesc_.setOptional();
770 optDesc_.CheckConsistency();
773 void onMultiVal (const DagInit& d) {
774 CheckNumberOfArguments(d, 1);
775 int val = InitPtrToInt(d.getArg(0));
777 throw "Error in the 'multi_val' property: "
778 "the value must be greater than 1!";
779 if (!optDesc_.isParameterList())
780 throw "The multi_val property is valid only on list options!";
781 optDesc_.MultiVal = val;
786 /// AddOption - A function object that is applied to every option
787 /// description. Used by CollectOptionDescriptions.
790 OptionDescriptions& OptDescs_;
793 explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
796 void operator()(const Init* i) {
797 const DagInit& d = InitPtrToDag(i);
798 CheckNumberOfArguments(d, 1);
800 const OptionType::OptionType Type =
801 stringToOptionType(GetOperatorName(d));
802 const std::string& Name = InitPtrToString(d.getArg(0));
804 OptionDescription OD(Type, Name);
807 CheckNumberOfArguments(d, 2);
810 // Aliases store the aliased option name in the 'Help' field.
811 OD.Help = InitPtrToString(d.getArg(1));
813 else if (!OD.isExtern()) {
814 processOptionProperties(d, OD);
816 OptDescs_.InsertDescription(OD);
820 /// processOptionProperties - Go through the list of option
821 /// properties and call a corresponding handler for each.
822 static void processOptionProperties (const DagInit& d, OptionDescription& o) {
823 CheckNumberOfArguments(d, 2);
824 DagInit::const_arg_iterator B = d.arg_begin();
825 // Skip the first argument: it's always the option name.
827 std::for_each(B, d.arg_end(), CollectOptionProperties(o));
832 /// CollectOptionDescriptions - Collects option properties from all
834 void CollectOptionDescriptions (RecordVector::const_iterator B,
835 RecordVector::const_iterator E,
836 OptionDescriptions& OptDescs)
838 // For every OptionList:
840 RecordVector::value_type T = *B;
841 // Throws an exception if the value does not exist.
842 ListInit* PropList = T->getValueAsListInit("options");
844 // For every option description in this list:
845 // collect the information and
846 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
850 // Tool information record
852 namespace ToolFlags {
853 enum ToolFlags { Join = 0x1, Sink = 0x2 };
856 struct ToolDescription : public RefCountedBase<ToolDescription> {
860 StrVector InLanguage;
861 std::string InFileOption;
862 std::string OutFileOption;
863 std::string OutLanguage;
864 std::string OutputSuffix;
868 // Various boolean properties
869 void setSink() { Flags |= ToolFlags::Sink; }
870 bool isSink() const { return Flags & ToolFlags::Sink; }
871 void setJoin() { Flags |= ToolFlags::Join; }
872 bool isJoin() const { return Flags & ToolFlags::Join; }
874 // Default ctor here is needed because StringMap can only store
875 // DefaultConstructible objects
877 : CmdLine(0), Actions(0), OutFileOption("-o"),
880 ToolDescription (const std::string& n)
881 : Name(n), CmdLine(0), Actions(0), OutFileOption("-o"),
886 /// ToolDescriptions - A list of Tool information records.
887 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
890 /// CollectToolProperties - Function object for iterating over a list of
891 /// tool property records.
893 class CollectToolProperties;
894 typedef void (CollectToolProperties::* CollectToolPropertiesHandler)
897 class CollectToolProperties : public HandlerTable<CollectToolPropertiesHandler>
901 /// toolDesc_ - Properties of the current Tool. This is where the
902 /// information is stored.
903 ToolDescription& toolDesc_;
907 explicit CollectToolProperties (ToolDescription& d)
910 if (!staticMembersInitialized_) {
912 AddHandler("actions", &CollectToolProperties::onActions);
913 AddHandler("command", &CollectToolProperties::onCommand);
914 AddHandler("in_language", &CollectToolProperties::onInLanguage);
915 AddHandler("join", &CollectToolProperties::onJoin);
916 AddHandler("out_language", &CollectToolProperties::onOutLanguage);
918 AddHandler("out_file_option", &CollectToolProperties::onOutFileOption);
919 AddHandler("in_file_option", &CollectToolProperties::onInFileOption);
921 AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
922 AddHandler("sink", &CollectToolProperties::onSink);
923 AddHandler("works_on_empty", &CollectToolProperties::onWorksOnEmpty);
925 staticMembersInitialized_ = true;
929 void operator() (Init* I) {
930 InvokeDagInitHandler(this, I);
935 /// Property handlers --
936 /// Functions that extract information about tool properties from
937 /// DAG representation.
939 void onActions (const DagInit& d) {
940 CheckNumberOfArguments(d, 1);
941 Init* Case = d.getArg(0);
942 if (typeid(*Case) != typeid(DagInit) ||
943 GetOperatorName(static_cast<DagInit&>(*Case)) != "case")
944 throw "The argument to (actions) should be a 'case' construct!";
945 toolDesc_.Actions = Case;
948 void onCommand (const DagInit& d) {
949 CheckNumberOfArguments(d, 1);
950 toolDesc_.CmdLine = d.getArg(0);
953 void onInLanguage (const DagInit& d) {
954 CheckNumberOfArguments(d, 1);
955 Init* arg = d.getArg(0);
957 // Find out the argument's type.
958 if (typeid(*arg) == typeid(StringInit)) {
960 toolDesc_.InLanguage.push_back(InitPtrToString(arg));
964 const ListInit& lst = InitPtrToList(arg);
965 StrVector& out = toolDesc_.InLanguage;
967 // Copy strings to the output vector.
968 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
970 out.push_back(InitPtrToString(*B));
973 // Remove duplicates.
974 std::sort(out.begin(), out.end());
975 StrVector::iterator newE = std::unique(out.begin(), out.end());
976 out.erase(newE, out.end());
980 void onJoin (const DagInit& d) {
981 CheckNumberOfArguments(d, 0);
985 void onOutLanguage (const DagInit& d) {
986 CheckNumberOfArguments(d, 1);
987 toolDesc_.OutLanguage = InitPtrToString(d.getArg(0));
990 void onOutFileOption (const DagInit& d) {
991 CheckNumberOfArguments(d, 1);
992 toolDesc_.OutFileOption = InitPtrToString(d.getArg(0));
995 void onInFileOption (const DagInit& d) {
996 CheckNumberOfArguments(d, 1);
997 toolDesc_.InFileOption = InitPtrToString(d.getArg(0));
1000 void onOutputSuffix (const DagInit& d) {
1001 CheckNumberOfArguments(d, 1);
1002 toolDesc_.OutputSuffix = InitPtrToString(d.getArg(0));
1005 void onSink (const DagInit& d) {
1006 CheckNumberOfArguments(d, 0);
1007 toolDesc_.setSink();
1010 void onWorksOnEmpty (const DagInit& d) {
1011 toolDesc_.OnEmpty = d.getArg(0);
1016 /// CollectToolDescriptions - Gather information about tool properties
1017 /// from the parsed TableGen data (basically a wrapper for the
1018 /// CollectToolProperties function object).
1019 void CollectToolDescriptions (RecordVector::const_iterator B,
1020 RecordVector::const_iterator E,
1021 ToolDescriptions& ToolDescs)
1023 // Iterate over a properties list of every Tool definition
1025 const Record* T = *B;
1026 // Throws an exception if the value does not exist.
1027 ListInit* PropList = T->getValueAsListInit("properties");
1029 IntrusiveRefCntPtr<ToolDescription>
1030 ToolDesc(new ToolDescription(T->getName()));
1032 std::for_each(PropList->begin(), PropList->end(),
1033 CollectToolProperties(*ToolDesc));
1034 ToolDescs.push_back(ToolDesc);
1038 /// FillInEdgeVector - Merge all compilation graph definitions into
1039 /// one single edge list.
1040 void FillInEdgeVector(RecordVector::const_iterator B,
1041 RecordVector::const_iterator E, RecordVector& Out) {
1042 for (; B != E; ++B) {
1043 const ListInit* edges = (*B)->getValueAsListInit("edges");
1045 for (unsigned i = 0; i < edges->size(); ++i)
1046 Out.push_back(edges->getElementAsRecord(i));
1050 /// CalculatePriority - Calculate the priority of this plugin.
1051 int CalculatePriority(RecordVector::const_iterator B,
1052 RecordVector::const_iterator E) {
1056 priority = static_cast<int>((*B)->getValueAsInt("priority"));
1059 throw "More than one 'PluginPriority' instance found: "
1060 "most probably an error!";
1066 /// NotInGraph - Helper function object for FilterNotInGraph.
1069 const llvm::StringSet<>& ToolsInGraph_;
1072 NotInGraph(const llvm::StringSet<>& ToolsInGraph)
1073 : ToolsInGraph_(ToolsInGraph)
1076 bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
1077 return (ToolsInGraph_.count(x->Name) == 0);
1081 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
1082 /// mentioned in the compilation graph definition.
1083 void FilterNotInGraph (const RecordVector& EdgeVector,
1084 ToolDescriptions& ToolDescs) {
1086 // List all tools mentioned in the graph.
1087 llvm::StringSet<> ToolsInGraph;
1089 for (RecordVector::const_iterator B = EdgeVector.begin(),
1090 E = EdgeVector.end(); B != E; ++B) {
1092 const Record* Edge = *B;
1093 const std::string& NodeA = Edge->getValueAsString("a");
1094 const std::string& NodeB = Edge->getValueAsString("b");
1096 if (NodeA != "root")
1097 ToolsInGraph.insert(NodeA);
1098 ToolsInGraph.insert(NodeB);
1101 // Filter ToolPropertiesList.
1102 ToolDescriptions::iterator new_end =
1103 std::remove_if(ToolDescs.begin(), ToolDescs.end(),
1104 NotInGraph(ToolsInGraph));
1105 ToolDescs.erase(new_end, ToolDescs.end());
1108 /// FillInToolToLang - Fills in two tables that map tool names to
1109 /// (input, output) languages. Helper function used by TypecheckGraph().
1110 void FillInToolToLang (const ToolDescriptions& ToolDescs,
1111 StringMap<StringSet<> >& ToolToInLang,
1112 StringMap<std::string>& ToolToOutLang) {
1113 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1114 E = ToolDescs.end(); B != E; ++B) {
1115 const ToolDescription& D = *(*B);
1116 for (StrVector::const_iterator B = D.InLanguage.begin(),
1117 E = D.InLanguage.end(); B != E; ++B)
1118 ToolToInLang[D.Name].insert(*B);
1119 ToolToOutLang[D.Name] = D.OutLanguage;
1123 /// TypecheckGraph - Check that names for output and input languages
1124 /// on all edges do match. This doesn't do much when the information
1125 /// about the whole graph is not available (i.e. when compiling most
1127 void TypecheckGraph (const RecordVector& EdgeVector,
1128 const ToolDescriptions& ToolDescs) {
1129 StringMap<StringSet<> > ToolToInLang;
1130 StringMap<std::string> ToolToOutLang;
1132 FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
1133 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
1134 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
1136 for (RecordVector::const_iterator B = EdgeVector.begin(),
1137 E = EdgeVector.end(); B != E; ++B) {
1138 const Record* Edge = *B;
1139 const std::string& NodeA = Edge->getValueAsString("a");
1140 const std::string& NodeB = Edge->getValueAsString("b");
1141 StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
1142 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
1144 if (NodeA != "root") {
1145 if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
1146 throw "Edge " + NodeA + "->" + NodeB
1147 + ": output->input language mismatch";
1150 if (NodeB == "root")
1151 throw "Edges back to the root are not allowed!";
1155 /// WalkCase - Walks the 'case' expression DAG and invokes
1156 /// TestCallback on every test, and StatementCallback on every
1157 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
1158 /// combinators (that is, they are passed directly to TestCallback).
1159 /// TestCallback must have type 'void TestCallback(const DagInit*, unsigned
1160 /// IndentLevel, bool FirstTest)'.
1161 /// StatementCallback must have type 'void StatementCallback(const Init*,
1162 /// unsigned IndentLevel)'.
1163 template <typename F1, typename F2>
1164 void WalkCase(const Init* Case, F1 TestCallback, F2 StatementCallback,
1165 unsigned IndentLevel = 0)
1167 const DagInit& d = InitPtrToDag(Case);
1170 if (GetOperatorName(d) != "case")
1171 throw "WalkCase should be invoked only on 'case' expressions!";
1173 if (d.getNumArgs() < 2)
1174 throw "There should be at least one clause in the 'case' expression:\n"
1179 const unsigned numArgs = d.getNumArgs();
1181 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1188 const DagInit& Test = InitPtrToDag(arg);
1190 if (GetOperatorName(Test) == "default" && (i+1 != numArgs))
1191 throw "The 'default' clause should be the last in the "
1192 "'case' construct!";
1194 throw "Case construct handler: no corresponding action "
1195 "found for the test " + Test.getAsString() + '!';
1197 TestCallback(Test, IndentLevel, (i == 1));
1201 if (dynamic_cast<DagInit*>(arg)
1202 && GetOperatorName(static_cast<DagInit&>(*arg)) == "case") {
1204 WalkCase(arg, TestCallback, StatementCallback, IndentLevel + Indent1);
1207 // Handle statement.
1208 StatementCallback(arg, IndentLevel);
1216 /// ExtractOptionNames - A helper function object used by
1217 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
1218 class ExtractOptionNames {
1219 llvm::StringSet<>& OptionNames_;
1221 void processDag(const Init* Statement) {
1222 const DagInit& Stmt = InitPtrToDag(Statement);
1223 const std::string& ActionName = GetOperatorName(Stmt);
1224 if (ActionName == "forward" || ActionName == "forward_as" ||
1225 ActionName == "forward_value" ||
1226 ActionName == "forward_transformed_value" ||
1227 ActionName == "switch_on" || ActionName == "any_switch_on" ||
1228 ActionName == "parameter_equals" ||
1229 ActionName == "element_in_list" || ActionName == "not_empty" ||
1230 ActionName == "empty") {
1231 CheckNumberOfArguments(Stmt, 1);
1233 Init* Arg = Stmt.getArg(0);
1234 if (typeid(*Arg) == typeid(StringInit)) {
1235 const std::string& Name = InitPtrToString(Arg);
1236 OptionNames_.insert(Name);
1240 const ListInit& List = InitPtrToList(Arg);
1241 for (ListInit::const_iterator B = List.begin(), E = List.end();
1243 const std::string& Name = InitPtrToString(*B);
1244 OptionNames_.insert(Name);
1248 else if (ActionName == "and" || ActionName == "or" || ActionName == "not") {
1249 for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
1250 this->processDag(Stmt.getArg(i));
1256 ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
1259 void operator()(const Init* Statement) {
1260 if (typeid(*Statement) == typeid(ListInit)) {
1261 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1262 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1264 this->processDag(*B);
1267 this->processDag(Statement);
1271 void operator()(const DagInit& Test, unsigned, bool) {
1272 this->operator()(&Test);
1274 void operator()(const Init* Statement, unsigned) {
1275 this->operator()(Statement);
1279 /// CheckForSuperfluousOptions - Check that there are no side
1280 /// effect-free options (specified only in the OptionList). Otherwise,
1281 /// output a warning.
1282 void CheckForSuperfluousOptions (const RecordVector& Edges,
1283 const ToolDescriptions& ToolDescs,
1284 const OptionDescriptions& OptDescs) {
1285 llvm::StringSet<> nonSuperfluousOptions;
1287 // Add all options mentioned in the ToolDesc.Actions to the set of
1288 // non-superfluous options.
1289 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1290 E = ToolDescs.end(); B != E; ++B) {
1291 const ToolDescription& TD = *(*B);
1292 ExtractOptionNames Callback(nonSuperfluousOptions);
1294 WalkCase(TD.Actions, Callback, Callback);
1297 // Add all options mentioned in the 'case' clauses of the
1298 // OptionalEdges of the compilation graph to the set of
1299 // non-superfluous options.
1300 for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
1302 const Record* Edge = *B;
1303 DagInit& Weight = *Edge->getValueAsDag("weight");
1305 if (!IsDagEmpty(Weight))
1306 WalkCase(&Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
1309 // Check that all options in OptDescs belong to the set of
1310 // non-superfluous options.
1311 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
1312 E = OptDescs.end(); B != E; ++B) {
1313 const OptionDescription& Val = B->second;
1314 if (!nonSuperfluousOptions.count(Val.Name)
1315 && Val.Type != OptionType::Alias)
1316 llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! "
1317 "Probable cause: this option is specified only in the OptionList.\n";
1321 /// EmitCaseTest0Args - Helper function used by EmitCaseConstructHandler().
1322 bool EmitCaseTest0Args(const std::string& TestName, raw_ostream& O) {
1323 if (TestName == "single_input_file") {
1324 O << "InputFilenames.size() == 1";
1327 else if (TestName == "multiple_input_files") {
1328 O << "InputFilenames.size() > 1";
1335 /// EmitListTest - Helper function used by EmitCaseTest1ArgList().
1336 template <typename F>
1337 void EmitListTest(const ListInit& L, const char* LogicOp,
1338 F Callback, raw_ostream& O)
1340 // This is a lot like EmitLogicalOperationTest, but works on ListInits instead
1342 bool isFirst = true;
1343 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B) {
1347 O << ' ' << LogicOp << ' ';
1348 Callback(InitPtrToString(*B), O);
1352 // Callbacks for use with EmitListTest.
1354 class EmitSwitchOn {
1355 const OptionDescriptions& OptDescs_;
1357 EmitSwitchOn(const OptionDescriptions& OptDescs) : OptDescs_(OptDescs)
1360 void operator()(const std::string& OptName, raw_ostream& O) const {
1361 const OptionDescription& OptDesc = OptDescs_.FindSwitch(OptName);
1362 O << OptDesc.GenVariableName();
1366 class EmitEmptyTest {
1368 const OptionDescriptions& OptDescs_;
1370 EmitEmptyTest(bool EmitNegate, const OptionDescriptions& OptDescs)
1371 : EmitNegate_(EmitNegate), OptDescs_(OptDescs)
1374 void operator()(const std::string& OptName, raw_ostream& O) const {
1375 const char* Neg = (EmitNegate_ ? "!" : "");
1376 if (OptName == "o") {
1377 O << Neg << "OutputFilename.empty()";
1379 else if (OptName == "save-temps") {
1380 O << Neg << "(SaveTemps == SaveTempsEnum::Unset)";
1383 const OptionDescription& OptDesc = OptDescs_.FindListOrParameter(OptName);
1384 O << Neg << OptDesc.GenVariableName() << ".empty()";
1390 /// EmitCaseTest1ArgList - Helper function used by EmitCaseTest1Arg();
1391 bool EmitCaseTest1ArgList(const std::string& TestName,
1393 const OptionDescriptions& OptDescs,
1395 const ListInit& L = InitPtrToList(d.getArg(0));
1397 if (TestName == "any_switch_on") {
1398 EmitListTest(L, "||", EmitSwitchOn(OptDescs), O);
1401 else if (TestName == "switch_on") {
1402 EmitListTest(L, "&&", EmitSwitchOn(OptDescs), O);
1405 else if (TestName == "any_not_empty") {
1406 EmitListTest(L, "||", EmitEmptyTest(true, OptDescs), O);
1409 else if (TestName == "any_empty") {
1410 EmitListTest(L, "||", EmitEmptyTest(false, OptDescs), O);
1413 else if (TestName == "not_empty") {
1414 EmitListTest(L, "&&", EmitEmptyTest(true, OptDescs), O);
1417 else if (TestName == "empty") {
1418 EmitListTest(L, "&&", EmitEmptyTest(false, OptDescs), O);
1425 /// EmitCaseTest1ArgStr - Helper function used by EmitCaseTest1Arg();
1426 bool EmitCaseTest1ArgStr(const std::string& TestName,
1428 const OptionDescriptions& OptDescs,
1430 const std::string& OptName = InitPtrToString(d.getArg(0));
1432 if (TestName == "switch_on") {
1433 apply(EmitSwitchOn(OptDescs), OptName, O);
1436 else if (TestName == "input_languages_contain") {
1437 O << "InLangs.count(\"" << OptName << "\") != 0";
1440 else if (TestName == "in_language") {
1441 // This works only for single-argument Tool::GenerateAction. Join
1442 // tools can process several files in different languages simultaneously.
1444 // TODO: make this work with Edge::Weight (if possible).
1445 O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
1448 else if (TestName == "not_empty" || TestName == "empty") {
1449 bool EmitNegate = (TestName == "not_empty");
1450 apply(EmitEmptyTest(EmitNegate, OptDescs), OptName, O);
1457 /// EmitCaseTest1Arg - Helper function used by EmitCaseConstructHandler();
1458 bool EmitCaseTest1Arg(const std::string& TestName,
1460 const OptionDescriptions& OptDescs,
1462 CheckNumberOfArguments(d, 1);
1463 if (typeid(*d.getArg(0)) == typeid(ListInit))
1464 return EmitCaseTest1ArgList(TestName, d, OptDescs, O);
1466 return EmitCaseTest1ArgStr(TestName, d, OptDescs, O);
1469 /// EmitCaseTest2Args - Helper function used by EmitCaseConstructHandler().
1470 bool EmitCaseTest2Args(const std::string& TestName,
1472 unsigned IndentLevel,
1473 const OptionDescriptions& OptDescs,
1475 CheckNumberOfArguments(d, 2);
1476 const std::string& OptName = InitPtrToString(d.getArg(0));
1477 const std::string& OptArg = InitPtrToString(d.getArg(1));
1479 if (TestName == "parameter_equals") {
1480 const OptionDescription& OptDesc = OptDescs.FindParameter(OptName);
1481 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
1484 else if (TestName == "element_in_list") {
1485 const OptionDescription& OptDesc = OptDescs.FindParameterList(OptName);
1486 const std::string& VarName = OptDesc.GenVariableName();
1487 O << "std::find(" << VarName << ".begin(),\n";
1488 O.indent(IndentLevel + Indent1)
1489 << VarName << ".end(), \""
1490 << OptArg << "\") != " << VarName << ".end()";
1497 // Forward declaration.
1498 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
1499 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1500 const OptionDescriptions& OptDescs,
1503 /// EmitLogicalOperationTest - Helper function used by
1504 /// EmitCaseConstructHandler.
1505 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
1506 unsigned IndentLevel,
1507 const OptionDescriptions& OptDescs,
1510 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
1511 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
1512 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1513 if (j != NumArgs - 1) {
1515 O.indent(IndentLevel + Indent1) << ' ' << LogicOp << " (";
1523 void EmitLogicalNot(const DagInit& d, unsigned IndentLevel,
1524 const OptionDescriptions& OptDescs, raw_ostream& O)
1526 CheckNumberOfArguments(d, 1);
1527 const DagInit& InnerTest = InitPtrToDag(d.getArg(0));
1529 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1533 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
1534 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1535 const OptionDescriptions& OptDescs,
1537 const std::string& TestName = GetOperatorName(d);
1539 if (TestName == "and")
1540 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
1541 else if (TestName == "or")
1542 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
1543 else if (TestName == "not")
1544 EmitLogicalNot(d, IndentLevel, OptDescs, O);
1545 else if (EmitCaseTest0Args(TestName, O))
1547 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
1549 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
1552 throw "Unknown test '" + TestName + "' used in the 'case' construct!";
1556 /// EmitCaseTestCallback - Callback used by EmitCaseConstructHandler.
1557 class EmitCaseTestCallback {
1559 const OptionDescriptions& OptDescs_;
1563 EmitCaseTestCallback(bool EmitElseIf,
1564 const OptionDescriptions& OptDescs, raw_ostream& O)
1565 : EmitElseIf_(EmitElseIf), OptDescs_(OptDescs), O_(O)
1568 void operator()(const DagInit& Test, unsigned IndentLevel, bool FirstTest)
1570 if (GetOperatorName(Test) == "default") {
1571 O_.indent(IndentLevel) << "else {\n";
1574 O_.indent(IndentLevel)
1575 << ((!FirstTest && EmitElseIf_) ? "else if (" : "if (");
1576 EmitCaseTest(Test, IndentLevel, OptDescs_, O_);
1582 /// EmitCaseStatementCallback - Callback used by EmitCaseConstructHandler.
1583 template <typename F>
1584 class EmitCaseStatementCallback {
1589 EmitCaseStatementCallback(F Callback, raw_ostream& O)
1590 : Callback_(Callback), O_(O)
1593 void operator() (const Init* Statement, unsigned IndentLevel) {
1595 // Ignore nested 'case' DAG.
1596 if (!(dynamic_cast<const DagInit*>(Statement) &&
1597 GetOperatorName(static_cast<const DagInit&>(*Statement)) == "case")) {
1598 if (typeid(*Statement) == typeid(ListInit)) {
1599 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1600 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1602 Callback_(*B, (IndentLevel + Indent1), O_);
1605 Callback_(Statement, (IndentLevel + Indent1), O_);
1608 O_.indent(IndentLevel) << "}\n";
1613 /// EmitCaseConstructHandler - Emit code that handles the 'case'
1614 /// construct. Takes a function object that should emit code for every case
1615 /// clause. Implemented on top of WalkCase.
1616 /// Callback's type is void F(const Init* Statement, unsigned IndentLevel,
1617 /// raw_ostream& O).
1618 /// EmitElseIf parameter controls the type of condition that is emitted ('if
1619 /// (..) {..} else if (..) {} .. else {..}' vs. 'if (..) {..} if(..) {..}
1621 template <typename F>
1622 void EmitCaseConstructHandler(const Init* Case, unsigned IndentLevel,
1623 F Callback, bool EmitElseIf,
1624 const OptionDescriptions& OptDescs,
1626 WalkCase(Case, EmitCaseTestCallback(EmitElseIf, OptDescs, O),
1627 EmitCaseStatementCallback<F>(Callback, O), IndentLevel);
1630 /// TokenizeCmdLine - converts from
1631 /// "$CALL(HookName, 'Arg1', 'Arg2')/path -arg1 -arg2" to
1632 /// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path", "-arg1", "-arg2"].
1633 void TokenizeCmdLine(const std::string& CmdLine, StrVector& Out) {
1634 const char* Delimiters = " \t\n\v\f\r";
1636 { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1639 if (CmdLine.empty())
1643 std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1646 for (; B != E; ++B) {
1647 char cur_ch = CmdLine[B];
1651 if (cur_ch == '$') {
1652 cur_st = SpecialCommand;
1655 if (OneOf(Delimiters, cur_ch)) {
1657 B = CmdLine.find_first_not_of(Delimiters, B);
1658 if (B == std::string::npos) {
1669 case SpecialCommand:
1670 if (OneOf(Delimiters, cur_ch)) {
1675 if (cur_ch == '(') {
1677 cur_st = InsideSpecialCommand;
1682 case InsideSpecialCommand:
1683 if (OneOf(Delimiters, cur_ch)) {
1686 if (cur_ch == '\'') {
1687 cur_st = InsideQuotationMarks;
1691 if (cur_ch == ')') {
1695 if (cur_ch == ',') {
1701 case InsideQuotationMarks:
1702 if (cur_ch == '\'') {
1703 cur_st = InsideSpecialCommand;
1709 Out.back().push_back(cur_ch);
1713 /// SubstituteCall - Given "$CALL(HookName, [Arg1 [, Arg2 [...]]])", output
1714 /// "hooks::HookName([Arg1 [, Arg2 [, ...]]])". Helper function used by
1715 /// SubstituteSpecialCommands().
1716 StrVector::const_iterator
1717 SubstituteCall (StrVector::const_iterator Pos,
1718 StrVector::const_iterator End,
1719 bool IsJoin, raw_ostream& O)
1721 const char* errorMessage = "Syntax error in $CALL invocation!";
1722 CheckedIncrement(Pos, End, errorMessage);
1723 const std::string& CmdName = *Pos;
1726 throw "$CALL invocation: empty argument list!";
1729 O << CmdName << "(";
1732 bool firstIteration = true;
1734 CheckedIncrement(Pos, End, errorMessage);
1735 const std::string& Arg = *Pos;
1736 assert(Arg.size() != 0);
1742 firstIteration = false;
1746 if (Arg == "$INFILE") {
1748 throw "$CALL(Hook, $INFILE) can't be used with a Join tool!";
1750 O << "inFile.c_str()";
1753 O << '"' << Arg << '"';
1762 /// SubstituteEnv - Given '$ENV(VAR_NAME)', output 'getenv("VAR_NAME")'. Helper
1763 /// function used by SubstituteSpecialCommands().
1764 StrVector::const_iterator
1765 SubstituteEnv (StrVector::const_iterator Pos,
1766 StrVector::const_iterator End, raw_ostream& O)
1768 const char* errorMessage = "Syntax error in $ENV invocation!";
1769 CheckedIncrement(Pos, End, errorMessage);
1770 const std::string& EnvName = *Pos;
1773 throw "$ENV invocation: empty argument list!";
1775 O << "checkCString(std::getenv(\"";
1779 CheckedIncrement(Pos, End, errorMessage);
1784 /// SubstituteSpecialCommands - Given an invocation of $CALL or $ENV, output
1785 /// handler code. Helper function used by EmitCmdLineVecFill().
1786 StrVector::const_iterator
1787 SubstituteSpecialCommands (StrVector::const_iterator Pos,
1788 StrVector::const_iterator End,
1789 bool IsJoin, raw_ostream& O)
1792 const std::string& cmd = *Pos;
1794 // Perform substitution.
1795 if (cmd == "$CALL") {
1796 Pos = SubstituteCall(Pos, End, IsJoin, O);
1798 else if (cmd == "$ENV") {
1799 Pos = SubstituteEnv(Pos, End, O);
1802 throw "Unknown special command: " + cmd;
1805 // Handle '$CMD(ARG)/additional/text'.
1806 const std::string& Leftover = *Pos;
1807 assert(Leftover.at(0) == ')');
1808 if (Leftover.size() != 1)
1809 O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1814 /// EmitCmdLineVecFill - Emit code that fills in the command line
1815 /// vector. Helper function used by EmitGenerateActionMethod().
1816 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1817 bool IsJoin, unsigned IndentLevel,
1820 TokenizeCmdLine(InitPtrToString(CmdLine), StrVec);
1823 throw "Tool '" + ToolName + "' has empty command line!";
1825 StrVector::const_iterator B = StrVec.begin(), E = StrVec.end();
1827 // Emit the command itself.
1828 assert(!StrVec[0].empty());
1829 O.indent(IndentLevel) << "cmd = ";
1830 if (StrVec[0][0] == '$') {
1831 B = SubstituteSpecialCommands(B, E, IsJoin, O);
1835 O << '"' << StrVec[0] << '"';
1840 // Go through the command arguments.
1842 for (; B != E; ++B) {
1843 const std::string& cmd = *B;
1845 assert(!cmd.empty());
1846 O.indent(IndentLevel);
1848 if (cmd.at(0) == '$') {
1849 O << "vec.push_back(std::make_pair(0, ";
1850 B = SubstituteSpecialCommands(B, E, IsJoin, O);
1854 O << "vec.push_back(std::make_pair(0, \"" << cmd << "\"));\n";
1860 /// EmitForEachListElementCycleHeader - Emit common code for iterating through
1861 /// all elements of a list. Helper function used by
1862 /// EmitForwardOptionPropertyHandlingCode.
1863 void EmitForEachListElementCycleHeader (const OptionDescription& D,
1864 unsigned IndentLevel,
1866 unsigned IndentLevel1 = IndentLevel + Indent1;
1868 O.indent(IndentLevel)
1869 << "for (" << D.GenTypeDeclaration()
1870 << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1871 O.indent(IndentLevel)
1872 << "E = " << D.GenVariableName() << ".end(); B != E;) {\n";
1873 O.indent(IndentLevel1) << "unsigned pos = " << D.GenVariableName()
1874 << ".getPosition(B - " << D.GenVariableName()
1878 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1879 /// implement EmitActionHandler. Emits code for
1880 /// handling the (forward) and (forward_as) option properties.
1881 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1882 unsigned IndentLevel,
1883 const std::string& NewName,
1885 const std::string& Name = NewName.empty()
1888 unsigned IndentLevel1 = IndentLevel + Indent1;
1891 case OptionType::Switch:
1892 O.indent(IndentLevel)
1893 << "vec.push_back(std::make_pair(" << D.GenVariableName()
1894 << ".getPosition(), \"" << Name << "\"));\n";
1896 case OptionType::Parameter:
1897 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
1898 << D.GenVariableName()
1899 <<".getPosition(), \"" << Name;
1901 if (!D.isForwardNotSplit()) {
1903 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
1904 << D.GenVariableName() << ".getPosition(), "
1905 << D.GenVariableName() << "));\n";
1908 O << "=\" + " << D.GenVariableName() << "));\n";
1911 case OptionType::Prefix:
1912 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
1913 << D.GenVariableName() << ".getPosition(), \""
1915 << D.GenVariableName() << "));\n";
1917 case OptionType::PrefixList:
1918 EmitForEachListElementCycleHeader(D, IndentLevel, O);
1919 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, \""
1920 << Name << "\" + " << "*B));\n";
1921 O.indent(IndentLevel1) << "++B;\n";
1923 for (int i = 1, j = D.MultiVal; i < j; ++i) {
1924 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, *B));\n";
1925 O.indent(IndentLevel1) << "++B;\n";
1928 O.indent(IndentLevel) << "}\n";
1930 case OptionType::ParameterList:
1931 EmitForEachListElementCycleHeader(D, IndentLevel, O);
1932 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, \""
1933 << Name << "\"));\n";
1935 for (int i = 0, j = D.MultiVal; i < j; ++i) {
1936 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, *B));\n";
1937 O.indent(IndentLevel1) << "++B;\n";
1940 O.indent(IndentLevel) << "}\n";
1942 case OptionType::SwitchList:
1943 EmitForEachListElementCycleHeader(D, IndentLevel, O);
1944 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, \""
1945 << Name << "\"));\n";
1946 O.indent(IndentLevel1) << "++B;\n";
1947 O.indent(IndentLevel) << "}\n";
1949 case OptionType::Alias:
1951 throw "Aliases are not allowed in tool option descriptions!";
1955 /// ActionHandlingCallbackBase - Base class of EmitActionHandlersCallback and
1956 /// EmitPreprocessOptionsCallback.
1957 struct ActionHandlingCallbackBase
1960 void onErrorDag(const DagInit& d,
1961 unsigned IndentLevel, raw_ostream& O) const
1963 O.indent(IndentLevel)
1965 << (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0)) : "Unknown error!")
1967 O.indent(IndentLevel) << "return 1;\n";
1970 void onWarningDag(const DagInit& d,
1971 unsigned IndentLevel, raw_ostream& O) const
1973 CheckNumberOfArguments(d, 1);
1974 O.indent(IndentLevel) << "llvm::errs() << \""
1975 << InitPtrToString(d.getArg(0)) << "\";\n";
1980 /// EmitActionHandlersCallback - Emit code that handles actions. Used by
1981 /// EmitGenerateActionMethod() as an argument to EmitCaseConstructHandler().
1983 class EmitActionHandlersCallback;
1985 typedef void (EmitActionHandlersCallback::* EmitActionHandlersCallbackHandler)
1986 (const DagInit&, unsigned, raw_ostream&) const;
1988 class EmitActionHandlersCallback :
1989 public ActionHandlingCallbackBase,
1990 public HandlerTable<EmitActionHandlersCallbackHandler>
1992 typedef EmitActionHandlersCallbackHandler Handler;
1994 const OptionDescriptions& OptDescs;
1996 /// EmitHookInvocation - Common code for hook invocation from actions. Used by
1997 /// onAppendCmd and onOutputSuffix.
1998 void EmitHookInvocation(const std::string& Str,
1999 const char* BlockOpen, const char* BlockClose,
2000 unsigned IndentLevel, raw_ostream& O) const
2003 TokenizeCmdLine(Str, Out);
2005 for (StrVector::const_iterator B = Out.begin(), E = Out.end();
2007 const std::string& cmd = *B;
2009 O.indent(IndentLevel) << BlockOpen;
2011 if (cmd.at(0) == '$')
2012 B = SubstituteSpecialCommands(B, E, /* IsJoin = */ true, O);
2014 O << '"' << cmd << '"';
2020 void onAppendCmd (const DagInit& Dag,
2021 unsigned IndentLevel, raw_ostream& O) const
2023 CheckNumberOfArguments(Dag, 1);
2024 this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
2025 "vec.push_back(std::make_pair(65536, ", "));\n",
2029 void onForward (const DagInit& Dag,
2030 unsigned IndentLevel, raw_ostream& O) const
2032 CheckNumberOfArguments(Dag, 1);
2033 const std::string& Name = InitPtrToString(Dag.getArg(0));
2034 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
2035 IndentLevel, "", O);
2038 void onForwardAs (const DagInit& Dag,
2039 unsigned IndentLevel, raw_ostream& O) const
2041 CheckNumberOfArguments(Dag, 2);
2042 const std::string& Name = InitPtrToString(Dag.getArg(0));
2043 const std::string& NewName = InitPtrToString(Dag.getArg(1));
2044 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
2045 IndentLevel, NewName, O);
2048 void onForwardValue (const DagInit& Dag,
2049 unsigned IndentLevel, raw_ostream& O) const
2051 CheckNumberOfArguments(Dag, 1);
2052 const std::string& Name = InitPtrToString(Dag.getArg(0));
2053 const OptionDescription& D = OptDescs.FindParameterListOrParameter(Name);
2055 if (D.isSwitchList()) {
2056 throw std::runtime_error
2057 ("forward_value is not allowed with switch_list");
2060 if (D.isParameter()) {
2061 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
2062 << D.GenVariableName() << ".getPosition(), "
2063 << D.GenVariableName() << "));\n";
2066 O.indent(IndentLevel) << "for (" << D.GenTypeDeclaration()
2067 << "::iterator B = " << D.GenVariableName()
2069 O.indent(IndentLevel + Indent1) << " E = " << D.GenVariableName()
2070 << ".end(); B != E; ++B)\n";
2071 O.indent(IndentLevel) << "{\n";
2072 O.indent(IndentLevel + Indent1)
2073 << "unsigned pos = " << D.GenVariableName()
2074 << ".getPosition(B - " << D.GenVariableName()
2076 O.indent(IndentLevel + Indent1)
2077 << "vec.push_back(std::make_pair(pos, *B));\n";
2078 O.indent(IndentLevel) << "}\n";
2082 void onForwardTransformedValue (const DagInit& Dag,
2083 unsigned IndentLevel, raw_ostream& O) const
2085 CheckNumberOfArguments(Dag, 2);
2086 const std::string& Name = InitPtrToString(Dag.getArg(0));
2087 const std::string& Hook = InitPtrToString(Dag.getArg(1));
2088 const OptionDescription& D = OptDescs.FindParameterListOrParameter(Name);
2090 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
2091 << D.GenVariableName() << ".getPosition("
2092 << (D.isList() ? "0" : "") << "), "
2093 << "hooks::" << Hook << "(" << D.GenVariableName()
2094 << (D.isParameter() ? ".c_str()" : "") << ")));\n";
2097 void onNoOutFile (const DagInit& Dag,
2098 unsigned IndentLevel, raw_ostream& O) const
2100 CheckNumberOfArguments(Dag, 0);
2101 O.indent(IndentLevel) << "no_out_file = true;\n";
2104 void onOutputSuffix (const DagInit& Dag,
2105 unsigned IndentLevel, raw_ostream& O) const
2107 CheckNumberOfArguments(Dag, 1);
2108 this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
2109 "output_suffix = ", ";\n", IndentLevel, O);
2112 void onStopCompilation (const DagInit& Dag,
2113 unsigned IndentLevel, raw_ostream& O) const
2115 O.indent(IndentLevel) << "stop_compilation = true;\n";
2119 void onUnpackValues (const DagInit& Dag,
2120 unsigned IndentLevel, raw_ostream& O) const
2122 throw "'unpack_values' is deprecated. "
2123 "Use 'comma_separated' + 'forward_value' instead!";
2128 explicit EmitActionHandlersCallback(const OptionDescriptions& OD)
2131 if (!staticMembersInitialized_) {
2132 AddHandler("error", &EmitActionHandlersCallback::onErrorDag);
2133 AddHandler("warning", &EmitActionHandlersCallback::onWarningDag);
2134 AddHandler("append_cmd", &EmitActionHandlersCallback::onAppendCmd);
2135 AddHandler("forward", &EmitActionHandlersCallback::onForward);
2136 AddHandler("forward_as", &EmitActionHandlersCallback::onForwardAs);
2137 AddHandler("forward_value", &EmitActionHandlersCallback::onForwardValue);
2138 AddHandler("forward_transformed_value",
2139 &EmitActionHandlersCallback::onForwardTransformedValue);
2140 AddHandler("no_out_file",
2141 &EmitActionHandlersCallback::onNoOutFile);
2142 AddHandler("output_suffix", &EmitActionHandlersCallback::onOutputSuffix);
2143 AddHandler("stop_compilation",
2144 &EmitActionHandlersCallback::onStopCompilation);
2145 AddHandler("unpack_values",
2146 &EmitActionHandlersCallback::onUnpackValues);
2149 staticMembersInitialized_ = true;
2153 void operator()(const Init* I,
2154 unsigned IndentLevel, raw_ostream& O) const
2156 InvokeDagInitHandler(this, I, IndentLevel, O);
2160 void EmitGenerateActionMethodHeader(const ToolDescription& D,
2161 bool IsJoin, bool Naked,
2164 O.indent(Indent1) << "int GenerateAction(Action& Out,\n";
2167 O.indent(Indent2) << "const PathVector& inFiles,\n";
2169 O.indent(Indent2) << "const sys::Path& inFile,\n";
2171 O.indent(Indent2) << "const bool HasChildren,\n";
2172 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
2173 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
2174 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
2175 O.indent(Indent1) << "{\n";
2178 O.indent(Indent2) << "std::string cmd;\n";
2179 O.indent(Indent2) << "std::string out_file;\n";
2181 << "std::vector<std::pair<unsigned, std::string> > vec;\n";
2182 O.indent(Indent2) << "bool stop_compilation = !HasChildren;\n";
2183 O.indent(Indent2) << "bool no_out_file = false;\n";
2184 O.indent(Indent2) << "std::string output_suffix(\""
2185 << D.OutputSuffix << "\");\n";
2189 // EmitGenerateActionMethod - Emit either a normal or a "join" version of the
2190 // Tool::GenerateAction() method.
2191 void EmitGenerateActionMethod (const ToolDescription& D,
2192 const OptionDescriptions& OptDescs,
2193 bool IsJoin, raw_ostream& O) {
2195 EmitGenerateActionMethodHeader(D, IsJoin, /* Naked = */ false, O);
2198 throw "Tool " + D.Name + " has no cmd_line property!";
2200 // Process the 'command' property.
2202 EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
2205 // Process the 'actions' list of this tool.
2207 EmitCaseConstructHandler(D.Actions, Indent2,
2208 EmitActionHandlersCallback(OptDescs),
2209 false, OptDescs, O);
2213 if (!D.InFileOption.empty()) {
2215 << "vec.push_back(std::make_pair(InputFilenames.getPosition(0), \""
2216 << D.InFileOption << "\");\n";
2221 << "for (PathVector::const_iterator B = inFiles.begin(),\n";
2222 O.indent(Indent3) << "E = inFiles.end(); B != E; ++B)\n";
2223 O.indent(Indent2) << "{\n";
2224 O.indent(Indent3) << "vec.push_back(std::make_pair("
2225 << "InputFilenames.getPosition(B - inFiles.begin()), "
2227 O.indent(Indent2) << "}\n";
2230 O.indent(Indent2) << "vec.push_back(std::make_pair("
2231 << "InputFilenames.getPosition(0), inFile.str()));\n";
2235 O.indent(Indent2) << "if (!no_out_file) {\n";
2236 if (!D.OutFileOption.empty())
2237 O.indent(Indent3) << "vec.push_back(std::make_pair(65536, \""
2238 << D.OutFileOption << "\"));\n";
2240 O.indent(Indent3) << "out_file = this->OutFilename("
2241 << (IsJoin ? "sys::Path(),\n" : "inFile,\n");
2242 O.indent(Indent4) <<
2243 "TempDir, stop_compilation, output_suffix.c_str()).str();\n\n";
2244 O.indent(Indent3) << "vec.push_back(std::make_pair(65536, out_file));\n";
2246 O.indent(Indent2) << "}\n\n";
2248 // Handle the Sink property.
2250 O.indent(Indent2) << "if (!" << SinkOptionName << ".empty()) {\n";
2251 O.indent(Indent3) << "for (cl::list<std::string>::iterator B = "
2252 << SinkOptionName << ".begin(), E = " << SinkOptionName
2253 << ".end(); B != E; ++B)\n";
2254 O.indent(Indent4) << "vec.push_back(std::make_pair(" << SinkOptionName
2255 << ".getPosition(B - " << SinkOptionName
2256 << ".begin()), *B));\n";
2257 O.indent(Indent2) << "}\n";
2260 O.indent(Indent2) << "Out.Construct(cmd, this->SortArgs(vec), "
2261 << "stop_compilation, out_file);\n";
2262 O.indent(Indent2) << "return 0;\n";
2263 O.indent(Indent1) << "}\n\n";
2266 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
2267 /// a given Tool class.
2268 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
2269 const OptionDescriptions& OptDescs,
2271 if (!ToolDesc.isJoin()) {
2272 EmitGenerateActionMethodHeader(ToolDesc, /* IsJoin = */ true,
2273 /* Naked = */ true, O);
2274 O.indent(Indent2) << "PrintError(\"" << ToolDesc.Name
2275 << " is not a Join tool!\");\n";
2276 O.indent(Indent2) << "return -1;\n";
2277 O.indent(Indent1) << "}\n\n";
2280 EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
2283 EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
2286 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
2287 /// methods for a given Tool class.
2288 void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
2289 O.indent(Indent1) << "const char** InputLanguages() const {\n";
2290 O.indent(Indent2) << "return InputLanguages_;\n";
2291 O.indent(Indent1) << "}\n\n";
2293 if (D.OutLanguage.empty())
2294 throw "Tool " + D.Name + " has no 'out_language' property!";
2296 O.indent(Indent1) << "const char* OutputLanguage() const {\n";
2297 O.indent(Indent2) << "return \"" << D.OutLanguage << "\";\n";
2298 O.indent(Indent1) << "}\n\n";
2301 /// EmitNameMethod - Emit the Name() method for a given Tool class.
2302 void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
2303 O.indent(Indent1) << "const char* Name() const {\n";
2304 O.indent(Indent2) << "return \"" << D.Name << "\";\n";
2305 O.indent(Indent1) << "}\n\n";
2308 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
2310 void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
2311 O.indent(Indent1) << "bool IsJoin() const {\n";
2313 O.indent(Indent2) << "return true;\n";
2315 O.indent(Indent2) << "return false;\n";
2316 O.indent(Indent1) << "}\n\n";
2319 /// EmitWorksOnEmptyCallback - Callback used by EmitWorksOnEmptyMethod in
2320 /// conjunction with EmitCaseConstructHandler.
2321 void EmitWorksOnEmptyCallback (const Init* Value,
2322 unsigned IndentLevel, raw_ostream& O) {
2323 CheckBooleanConstant(Value);
2324 O.indent(IndentLevel) << "return " << Value->getAsString() << ";\n";
2327 /// EmitWorksOnEmptyMethod - Emit the WorksOnEmpty() method for a given Tool
2329 void EmitWorksOnEmptyMethod (const ToolDescription& D,
2330 const OptionDescriptions& OptDescs,
2333 O.indent(Indent1) << "bool WorksOnEmpty() const {\n";
2335 O.indent(Indent2) << "return false;\n";
2337 EmitCaseConstructHandler(D.OnEmpty, Indent2, EmitWorksOnEmptyCallback,
2338 /*EmitElseIf = */ true, OptDescs, O);
2339 O.indent(Indent1) << "}\n\n";
2342 /// EmitStaticMemberDefinitions - Emit static member definitions for a
2343 /// given Tool class.
2344 void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
2345 if (D.InLanguage.empty())
2346 throw "Tool " + D.Name + " has no 'in_language' property!";
2348 O << "const char* " << D.Name << "::InputLanguages_[] = {";
2349 for (StrVector::const_iterator B = D.InLanguage.begin(),
2350 E = D.InLanguage.end(); B != E; ++B)
2351 O << '\"' << *B << "\", ";
2355 /// EmitToolClassDefinition - Emit a Tool class definition.
2356 void EmitToolClassDefinition (const ToolDescription& D,
2357 const OptionDescriptions& OptDescs,
2359 if (D.Name == "root")
2363 O << "class " << D.Name << " : public ";
2369 O << " {\nprivate:\n";
2370 O.indent(Indent1) << "static const char* InputLanguages_[];\n\n";
2373 EmitNameMethod(D, O);
2374 EmitInOutLanguageMethods(D, O);
2375 EmitIsJoinMethod(D, O);
2376 EmitWorksOnEmptyMethod(D, OptDescs, O);
2377 EmitGenerateActionMethods(D, OptDescs, O);
2379 // Close class definition
2382 EmitStaticMemberDefinitions(D, O);
2386 /// EmitOptionDefinitions - Iterate over a list of option descriptions
2387 /// and emit registration code.
2388 void EmitOptionDefinitions (const OptionDescriptions& descs,
2389 bool HasSink, bool HasExterns,
2392 std::vector<OptionDescription> Aliases;
2394 // Emit static cl::Option variables.
2395 for (OptionDescriptions::const_iterator B = descs.begin(),
2396 E = descs.end(); B!=E; ++B) {
2397 const OptionDescription& val = B->second;
2399 if (val.Type == OptionType::Alias) {
2400 Aliases.push_back(val);
2407 O << val.GenTypeDeclaration() << ' '
2408 << val.GenVariableName();
2410 if (val.isExtern()) {
2415 O << "(\"" << val.Name << "\"\n";
2417 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
2418 O << ", cl::Prefix";
2420 if (val.isRequired()) {
2421 if (val.isList() && !val.isMultiVal())
2422 O << ", cl::OneOrMore";
2424 O << ", cl::Required";
2427 if (val.isOptional())
2428 O << ", cl::Optional";
2430 if (val.isOneOrMore())
2431 O << ", cl::OneOrMore";
2433 if (val.isZeroOrMore())
2434 O << ", cl::ZeroOrMore";
2436 if (val.isReallyHidden())
2437 O << ", cl::ReallyHidden";
2438 else if (val.isHidden())
2439 O << ", cl::Hidden";
2441 if (val.isCommaSeparated())
2442 O << ", cl::CommaSeparated";
2444 if (val.MultiVal > 1)
2445 O << ", cl::multi_val(" << val.MultiVal << ')';
2448 const std::string& str = val.InitVal->getAsString();
2449 O << ", cl::init(" << str << ')';
2452 if (!val.Help.empty())
2453 O << ", cl::desc(\"" << val.Help << "\")";
2458 // Emit the aliases (they should go after all the 'proper' options).
2459 for (std::vector<OptionDescription>::const_iterator
2460 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
2461 const OptionDescription& val = *B;
2463 O << val.GenTypeDeclaration() << ' '
2464 << val.GenVariableName()
2465 << "(\"" << val.Name << '\"';
2467 const OptionDescription& D = descs.FindOption(val.Help);
2468 O << ", cl::aliasopt(" << D.GenVariableName() << ")";
2470 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
2473 // Emit the sink option.
2475 O << (HasExterns ? "extern cl" : "cl")
2476 << "::list<std::string> " << SinkOptionName
2477 << (HasExterns ? ";\n" : "(cl::Sink);\n");
2482 /// EmitPreprocessOptionsCallback - Helper function passed to
2483 /// EmitCaseConstructHandler() by EmitPreprocessOptions().
2485 class EmitPreprocessOptionsCallback;
2488 (EmitPreprocessOptionsCallback::* EmitPreprocessOptionsCallbackHandler)
2489 (const DagInit&, unsigned, raw_ostream&) const;
2491 class EmitPreprocessOptionsCallback :
2492 public ActionHandlingCallbackBase,
2493 public HandlerTable<EmitPreprocessOptionsCallbackHandler>
2495 typedef EmitPreprocessOptionsCallbackHandler Handler;
2497 (EmitPreprocessOptionsCallback::* HandlerImpl)
2498 (const Init*, unsigned, raw_ostream&) const;
2500 const OptionDescriptions& OptDescs_;
2502 void onListOrDag(const DagInit& d, HandlerImpl h,
2503 unsigned IndentLevel, raw_ostream& O) const
2505 CheckNumberOfArguments(d, 1);
2506 const Init* I = d.getArg(0);
2508 // If I is a list, apply h to each element.
2509 if (typeid(*I) == typeid(ListInit)) {
2510 const ListInit& L = *static_cast<const ListInit*>(I);
2511 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B)
2512 ((this)->*(h))(*B, IndentLevel, O);
2514 // Otherwise, apply h to I.
2516 ((this)->*(h))(I, IndentLevel, O);
2520 void onUnsetOptionImpl(const Init* I,
2521 unsigned IndentLevel, raw_ostream& O) const
2523 const std::string& OptName = InitPtrToString(I);
2524 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2526 if (OptDesc.isSwitch()) {
2527 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = false;\n";
2529 else if (OptDesc.isParameter()) {
2530 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = \"\";\n";
2532 else if (OptDesc.isList()) {
2533 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2536 throw "Can't apply 'unset_option' to alias option '" + OptName + "'!";
2540 void onUnsetOption(const DagInit& d,
2541 unsigned IndentLevel, raw_ostream& O) const
2543 this->onListOrDag(d, &EmitPreprocessOptionsCallback::onUnsetOptionImpl,
2547 void onSetOptionImpl(const DagInit& d,
2548 unsigned IndentLevel, raw_ostream& O) const {
2549 CheckNumberOfArguments(d, 2);
2550 const std::string& OptName = InitPtrToString(d.getArg(0));
2551 const Init* Value = d.getArg(1);
2552 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2554 if (OptDesc.isList()) {
2555 const ListInit& List = InitPtrToList(Value);
2557 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2558 for (ListInit::const_iterator B = List.begin(), E = List.end();
2560 const Init* CurElem = *B;
2561 if (OptDesc.isSwitchList())
2562 CheckBooleanConstant(CurElem);
2564 O.indent(IndentLevel)
2565 << OptDesc.GenVariableName() << ".push_back(\""
2566 << (OptDesc.isSwitchList() ? CurElem->getAsString()
2567 : InitPtrToString(CurElem))
2571 else if (OptDesc.isSwitch()) {
2572 CheckBooleanConstant(Value);
2573 O.indent(IndentLevel) << OptDesc.GenVariableName()
2574 << " = " << Value->getAsString() << ";\n";
2576 else if (OptDesc.isParameter()) {
2577 const std::string& Str = InitPtrToString(Value);
2578 O.indent(IndentLevel) << OptDesc.GenVariableName()
2579 << " = \"" << Str << "\";\n";
2582 throw "Can't apply 'set_option' to alias option -" + OptName + " !";
2586 void onSetSwitch(const Init* I,
2587 unsigned IndentLevel, raw_ostream& O) const {
2588 const std::string& OptName = InitPtrToString(I);
2589 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2591 if (OptDesc.isSwitch())
2592 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = true;\n";
2594 throw "set_option: -" + OptName + " is not a switch option!";
2597 void onSetOption(const DagInit& d,
2598 unsigned IndentLevel, raw_ostream& O) const
2600 CheckNumberOfArguments(d, 1);
2602 // Two arguments: (set_option "parameter", VALUE), where VALUE can be a
2603 // boolean, a string or a string list.
2604 if (d.getNumArgs() > 1)
2605 this->onSetOptionImpl(d, IndentLevel, O);
2606 // One argument: (set_option "switch")
2607 // or (set_option ["switch1", "switch2", ...])
2609 this->onListOrDag(d, &EmitPreprocessOptionsCallback::onSetSwitch,
2615 EmitPreprocessOptionsCallback(const OptionDescriptions& OptDescs)
2616 : OptDescs_(OptDescs)
2618 if (!staticMembersInitialized_) {
2619 AddHandler("error", &EmitPreprocessOptionsCallback::onErrorDag);
2620 AddHandler("warning", &EmitPreprocessOptionsCallback::onWarningDag);
2621 AddHandler("unset_option", &EmitPreprocessOptionsCallback::onUnsetOption);
2622 AddHandler("set_option", &EmitPreprocessOptionsCallback::onSetOption);
2624 staticMembersInitialized_ = true;
2628 void operator()(const Init* I,
2629 unsigned IndentLevel, raw_ostream& O) const
2631 InvokeDagInitHandler(this, I, IndentLevel, O);
2636 /// EmitPreprocessOptions - Emit the PreprocessOptionsLocal() function.
2637 void EmitPreprocessOptions (const RecordKeeper& Records,
2638 const OptionDescriptions& OptDecs, raw_ostream& O)
2640 O << "int PreprocessOptionsLocal() {\n";
2642 const RecordVector& OptionPreprocessors =
2643 Records.getAllDerivedDefinitions("OptionPreprocessor");
2645 for (RecordVector::const_iterator B = OptionPreprocessors.begin(),
2646 E = OptionPreprocessors.end(); B!=E; ++B) {
2647 DagInit* Case = (*B)->getValueAsDag("preprocessor");
2648 EmitCaseConstructHandler(Case, Indent1,
2649 EmitPreprocessOptionsCallback(OptDecs),
2654 O.indent(Indent1) << "return 0;\n";
2658 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMapLocal() function.
2659 void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
2661 O << "int PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
2663 // Get the relevant field out of RecordKeeper
2664 const Record* LangMapRecord = Records.getDef("LanguageMap");
2666 // It is allowed for a plugin to have no language map.
2667 if (LangMapRecord) {
2669 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
2670 if (!LangsToSuffixesList)
2671 throw "Error in the language map definition!";
2673 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
2674 const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
2676 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
2677 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
2679 for (unsigned i = 0; i < Suffixes->size(); ++i)
2680 O.indent(Indent1) << "langMap[\""
2681 << InitPtrToString(Suffixes->getElement(i))
2682 << "\"] = \"" << Lang << "\";\n";
2687 O.indent(Indent1) << "return 0;\n";
2691 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
2692 /// by EmitEdgeClass().
2693 void IncDecWeight (const Init* i, unsigned IndentLevel,
2695 const DagInit& d = InitPtrToDag(i);
2696 const std::string& OpName = GetOperatorName(d);
2698 if (OpName == "inc_weight") {
2699 O.indent(IndentLevel) << "ret += ";
2701 else if (OpName == "dec_weight") {
2702 O.indent(IndentLevel) << "ret -= ";
2704 else if (OpName == "error") {
2706 CheckNumberOfArguments(d, 1);
2707 O.indent(IndentLevel) << "PrintError(\""
2708 << InitPtrToString(d.getArg(0))
2710 O.indent(IndentLevel) << "return -1;\n";
2714 throw "Unknown operator in edge properties list: '" + OpName + "'!"
2715 "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
2718 if (d.getNumArgs() > 0)
2719 O << InitPtrToInt(d.getArg(0)) << ";\n";
2725 /// EmitEdgeClass - Emit a single Edge# class.
2726 void EmitEdgeClass (unsigned N, const std::string& Target,
2727 DagInit* Case, const OptionDescriptions& OptDescs,
2730 // Class constructor.
2731 O << "class Edge" << N << ": public Edge {\n"
2733 O.indent(Indent1) << "Edge" << N << "() : Edge(\"" << Target
2736 // Function Weight().
2738 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n";
2739 O.indent(Indent2) << "unsigned ret = 0;\n";
2741 // Handle the 'case' construct.
2742 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
2744 O.indent(Indent2) << "return ret;\n";
2745 O.indent(Indent1) << "}\n\n};\n\n";
2748 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
2749 void EmitEdgeClasses (const RecordVector& EdgeVector,
2750 const OptionDescriptions& OptDescs,
2753 for (RecordVector::const_iterator B = EdgeVector.begin(),
2754 E = EdgeVector.end(); B != E; ++B) {
2755 const Record* Edge = *B;
2756 const std::string& NodeB = Edge->getValueAsString("b");
2757 DagInit& Weight = *Edge->getValueAsDag("weight");
2759 if (!IsDagEmpty(Weight))
2760 EmitEdgeClass(i, NodeB, &Weight, OptDescs, O);
2765 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraphLocal()
2767 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
2768 const ToolDescriptions& ToolDescs,
2771 O << "int PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
2773 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2774 E = ToolDescs.end(); B != E; ++B)
2775 O.indent(Indent1) << "G.insertNode(new " << (*B)->Name << "());\n";
2782 for (RecordVector::const_iterator B = EdgeVector.begin(),
2783 E = EdgeVector.end(); B != E; ++B) {
2784 const Record* Edge = *B;
2785 const std::string& NodeA = Edge->getValueAsString("a");
2786 const std::string& NodeB = Edge->getValueAsString("b");
2787 DagInit& Weight = *Edge->getValueAsDag("weight");
2789 O.indent(Indent1) << "if (int ret = G.insertEdge(\"" << NodeA << "\", ";
2791 if (IsDagEmpty(Weight))
2792 O << "new SimpleEdge(\"" << NodeB << "\")";
2794 O << "new Edge" << i << "()";
2797 O.indent(Indent2) << "return ret;\n";
2803 O.indent(Indent1) << "return 0;\n";
2807 /// HookInfo - Information about the hook type and number of arguments.
2810 // A hook can either have a single parameter of type std::vector<std::string>,
2811 // or NumArgs parameters of type const char*.
2812 enum HookType { ListHook, ArgHook };
2817 HookInfo() : Type(ArgHook), NumArgs(1)
2820 HookInfo(HookType T) : Type(T), NumArgs(1)
2823 HookInfo(unsigned N) : Type(ArgHook), NumArgs(N)
2827 typedef llvm::StringMap<HookInfo> HookInfoMap;
2829 /// ExtractHookNames - Extract the hook names from all instances of
2830 /// $CALL(HookName) in the provided command line string/action. Helper
2831 /// function used by FillInHookNames().
2832 class ExtractHookNames {
2833 HookInfoMap& HookNames_;
2834 const OptionDescriptions& OptDescs_;
2836 ExtractHookNames(HookInfoMap& HookNames, const OptionDescriptions& OptDescs)
2837 : HookNames_(HookNames), OptDescs_(OptDescs)
2840 void onAction (const DagInit& Dag) {
2841 const std::string& Name = GetOperatorName(Dag);
2843 if (Name == "forward_transformed_value") {
2844 CheckNumberOfArguments(Dag, 2);
2845 const std::string& OptName = InitPtrToString(Dag.getArg(0));
2846 const std::string& HookName = InitPtrToString(Dag.getArg(1));
2847 const OptionDescription& D =
2848 OptDescs_.FindParameterListOrParameter(OptName);
2850 HookNames_[HookName] = HookInfo(D.isList() ? HookInfo::ListHook
2851 : HookInfo::ArgHook);
2853 else if (Name == "append_cmd" || Name == "output_suffix") {
2854 CheckNumberOfArguments(Dag, 1);
2855 this->onCmdLine(InitPtrToString(Dag.getArg(0)));
2859 void onCmdLine(const std::string& Cmd) {
2861 TokenizeCmdLine(Cmd, cmds);
2863 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
2865 const std::string& cmd = *B;
2867 if (cmd == "$CALL") {
2868 unsigned NumArgs = 0;
2869 CheckedIncrement(B, E, "Syntax error in $CALL invocation!");
2870 const std::string& HookName = *B;
2872 if (HookName.at(0) == ')')
2873 throw "$CALL invoked with no arguments!";
2875 while (++B != E && B->at(0) != ')') {
2879 HookInfoMap::const_iterator H = HookNames_.find(HookName);
2881 if (H != HookNames_.end() && H->second.NumArgs != NumArgs &&
2882 H->second.Type != HookInfo::ArgHook)
2883 throw "Overloading of hooks is not allowed. Overloaded hook: "
2886 HookNames_[HookName] = HookInfo(NumArgs);
2891 void operator()(const Init* Arg) {
2893 // We're invoked on an action (either a dag or a dag list).
2894 if (typeid(*Arg) == typeid(DagInit)) {
2895 const DagInit& Dag = InitPtrToDag(Arg);
2896 this->onAction(Dag);
2899 else if (typeid(*Arg) == typeid(ListInit)) {
2900 const ListInit& List = InitPtrToList(Arg);
2901 for (ListInit::const_iterator B = List.begin(), E = List.end(); B != E;
2903 const DagInit& Dag = InitPtrToDag(*B);
2904 this->onAction(Dag);
2909 // We're invoked on a command line.
2910 this->onCmdLine(InitPtrToString(Arg));
2913 void operator()(const DagInit* Test, unsigned, bool) {
2914 this->operator()(Test);
2916 void operator()(const Init* Statement, unsigned) {
2917 this->operator()(Statement);
2921 /// FillInHookNames - Actually extract the hook names from all command
2922 /// line strings. Helper function used by EmitHookDeclarations().
2923 void FillInHookNames(const ToolDescriptions& ToolDescs,
2924 const OptionDescriptions& OptDescs,
2925 HookInfoMap& HookNames)
2927 // For all tool descriptions:
2928 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2929 E = ToolDescs.end(); B != E; ++B) {
2930 const ToolDescription& D = *(*B);
2932 // Look for 'forward_transformed_value' in 'actions'.
2934 WalkCase(D.Actions, Id(), ExtractHookNames(HookNames, OptDescs));
2936 // Look for hook invocations in 'cmd_line'.
2939 if (dynamic_cast<StringInit*>(D.CmdLine))
2940 // This is a string.
2941 ExtractHookNames(HookNames, OptDescs).operator()(D.CmdLine);
2943 // This is a 'case' construct.
2944 WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames, OptDescs));
2948 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
2949 /// property records and emit hook function declaration for each
2950 /// instance of $CALL(HookName).
2951 void EmitHookDeclarations(const ToolDescriptions& ToolDescs,
2952 const OptionDescriptions& OptDescs, raw_ostream& O) {
2953 HookInfoMap HookNames;
2955 FillInHookNames(ToolDescs, OptDescs, HookNames);
2956 if (HookNames.empty())
2959 O << "namespace hooks {\n";
2960 for (HookInfoMap::const_iterator B = HookNames.begin(),
2961 E = HookNames.end(); B != E; ++B) {
2962 const char* HookName = B->first();
2963 const HookInfo& Info = B->second;
2965 O.indent(Indent1) << "std::string " << HookName << "(";
2967 if (Info.Type == HookInfo::ArgHook) {
2968 for (unsigned i = 0, j = Info.NumArgs; i < j; ++i) {
2969 O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
2973 O << "const std::vector<std::string>& Arg";
2981 std::string GetPluginName() {
2982 if (!InputFilename.empty()) {
2983 return sys::Path(InputFilename).getBasename();
2989 /// EmitRegisterPlugin - Emit code to register this plugin.
2990 void EmitRegisterPlugin(int Priority, raw_ostream& O) {
2991 O << "struct Plugin" << GetPluginName()
2992 << " : public llvmc::BasePlugin {\n\n";
2993 O.indent(Indent1) << "int Priority() const { return "
2994 << Priority << "; }\n\n";
2995 O.indent(Indent1) << "int PreprocessOptions() const\n";
2996 O.indent(Indent1) << "{ return PreprocessOptionsLocal(); }\n\n";
2997 O.indent(Indent1) << "int PopulateLanguageMap(LanguageMap& langMap) const\n";
2998 O.indent(Indent1) << "{ return PopulateLanguageMapLocal(langMap); }\n\n";
3000 << "int PopulateCompilationGraph(CompilationGraph& graph) const\n";
3001 O.indent(Indent1) << "{ return PopulateCompilationGraphLocal(graph); }\n"
3003 << "static llvmc::RegisterPlugin<Plugin"
3004 << GetPluginName()<< "> RP;\n\n";
3007 /// EmitIncludes - Emit necessary #include directives and some
3008 /// additional declarations.
3009 void EmitIncludes(raw_ostream& O) {
3010 O << "#include \"llvm/CompilerDriver/BuiltinOptions.h\"\n"
3011 << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
3012 << "#include \"llvm/CompilerDriver/Error.h\"\n"
3013 << "#include \"llvm/CompilerDriver/ForceLinkageMacros.h\"\n"
3014 << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
3015 << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
3017 << "#include \"llvm/Support/CommandLine.h\"\n"
3018 << "#include \"llvm/Support/raw_ostream.h\"\n\n"
3020 << "#include <algorithm>\n"
3021 << "#include <cstdlib>\n"
3022 << "#include <iterator>\n"
3023 << "#include <stdexcept>\n\n"
3025 << "using namespace llvm;\n"
3026 << "using namespace llvmc;\n\n"
3028 << "extern cl::opt<std::string> OutputFilename;\n\n"
3030 << "inline const char* checkCString(const char* s)\n"
3031 << "{ return s == NULL ? \"\" : s; }\n\n";
3035 /// PluginData - Holds all information about a plugin.
3037 OptionDescriptions OptDescs;
3040 ToolDescriptions ToolDescs;
3045 /// HasSink - Go through the list of tool descriptions and check if
3046 /// there are any with the 'sink' property set.
3047 bool HasSink(const ToolDescriptions& ToolDescs) {
3048 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
3049 E = ToolDescs.end(); B != E; ++B)
3056 /// HasExterns - Go through the list of option descriptions and check
3057 /// if there are any external options.
3058 bool HasExterns(const OptionDescriptions& OptDescs) {
3059 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
3060 E = OptDescs.end(); B != E; ++B)
3061 if (B->second.isExtern())
3067 /// CollectPluginData - Collect tool and option properties,
3068 /// compilation graph edges and plugin priority from the parse tree.
3069 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
3070 // Collect option properties.
3071 const RecordVector& OptionLists =
3072 Records.getAllDerivedDefinitions("OptionList");
3073 CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
3076 // Collect tool properties.
3077 const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
3078 CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
3079 Data.HasSink = HasSink(Data.ToolDescs);
3080 Data.HasExterns = HasExterns(Data.OptDescs);
3082 // Collect compilation graph edges.
3083 const RecordVector& CompilationGraphs =
3084 Records.getAllDerivedDefinitions("CompilationGraph");
3085 FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
3088 // Calculate the priority of this plugin.
3089 const RecordVector& Priorities =
3090 Records.getAllDerivedDefinitions("PluginPriority");
3091 Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
3094 /// CheckPluginData - Perform some sanity checks on the collected data.
3095 void CheckPluginData(PluginData& Data) {
3096 // Filter out all tools not mentioned in the compilation graph.
3097 FilterNotInGraph(Data.Edges, Data.ToolDescs);
3099 // Typecheck the compilation graph.
3100 TypecheckGraph(Data.Edges, Data.ToolDescs);
3102 // Check that there are no options without side effects (specified
3103 // only in the OptionList).
3104 CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
3107 void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
3108 // Emit file header.
3111 // Emit global option registration code.
3112 EmitOptionDefinitions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
3114 // Emit hook declarations.
3115 EmitHookDeclarations(Data.ToolDescs, Data.OptDescs, O);
3117 O << "namespace {\n\n";
3119 // Emit PreprocessOptionsLocal() function.
3120 EmitPreprocessOptions(Records, Data.OptDescs, O);
3122 // Emit PopulateLanguageMapLocal() function
3123 // (language map maps from file extensions to language names).
3124 EmitPopulateLanguageMap(Records, O);
3126 // Emit Tool classes.
3127 for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
3128 E = Data.ToolDescs.end(); B!=E; ++B)
3129 EmitToolClassDefinition(*(*B), Data.OptDescs, O);
3131 // Emit Edge# classes.
3132 EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
3134 // Emit PopulateCompilationGraphLocal() function.
3135 EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
3137 // Emit code for plugin registration.
3138 EmitRegisterPlugin(Data.Priority, O);
3140 O << "} // End anonymous namespace.\n\n";
3142 // Force linkage magic.
3143 O << "namespace llvmc {\n";
3144 O << "LLVMC_FORCE_LINKAGE_DECL(LLVMC_PLUGIN_NAME) {}\n";
3151 // End of anonymous namespace
3154 /// run - The back-end entry point.
3155 void LLVMCConfigurationEmitter::run (raw_ostream &O) {
3159 CollectPluginData(Records, Data);
3160 CheckPluginData(Data);
3162 this->EmitSourceFileHeader("LLVMC Configuration Library", O);
3163 EmitPluginCode(Data, O);
3165 } catch (std::exception& Error) {
3166 throw Error.what() + std::string(" - usually this means a syntax error.");