1 //===- LLVMCConfigurationEmitter.cpp - Generate LLVMC config ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open
6 // Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend is responsible for emitting LLVMC configuration code.
12 //===----------------------------------------------------------------------===//
14 #include "LLVMCConfigurationEmitter.h"
17 #include "llvm/ADT/IntrusiveRefCntPtr.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/ADT/StringSet.h"
32 //===----------------------------------------------------------------------===//
35 typedef std::vector<Record*> RecordVector;
36 typedef std::vector<std::string> StrVector;
38 //===----------------------------------------------------------------------===//
42 const unsigned TabWidth = 4;
43 const unsigned Indent1 = TabWidth*1;
44 const unsigned Indent2 = TabWidth*2;
45 const unsigned Indent3 = TabWidth*3;
46 const unsigned Indent4 = TabWidth*4;
48 // Default help string.
49 const char * const DefaultHelpString = "NO HELP MESSAGE PROVIDED";
51 // Name for the "sink" option.
52 const char * const SinkOptionName = "AutoGeneratedSinkOption";
54 //===----------------------------------------------------------------------===//
57 /// Id - An 'identity' function object.
60 void operator()(const T0&) const {
62 template<typename T0, typename T1>
63 void operator()(const T0&, const T1&) const {
65 template<typename T0, typename T1, typename T2>
66 void operator()(const T0&, const T1&, const T2&) const {
70 int InitPtrToInt(const Init* ptr) {
71 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
72 return val.getValue();
75 const std::string& InitPtrToString(const Init* ptr) {
76 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
77 return val.getValue();
80 const ListInit& InitPtrToList(const Init* ptr) {
81 const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
85 const DagInit& InitPtrToDag(const Init* ptr) {
86 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
90 const std::string GetOperatorName(const DagInit& D) {
91 return D.getOperator()->getAsString();
94 /// CheckBooleanConstant - Check that the provided value is a boolean constant.
95 void CheckBooleanConstant(const Init* I) {
96 const DefInit& val = dynamic_cast<const DefInit&>(*I);
97 const std::string& str = val.getAsString();
99 if (str != "true" && str != "false") {
100 throw "Incorrect boolean value: '" + str +
101 "': must be either 'true' or 'false'";
105 // CheckNumberOfArguments - Ensure that the number of args in d is
106 // greater than or equal to min_arguments, otherwise throw an exception.
107 void CheckNumberOfArguments (const DagInit& d, unsigned minArgs) {
108 if (d.getNumArgs() < minArgs)
109 throw GetOperatorName(d) + ": too few arguments!";
112 // IsDagEmpty - is this DAG marked with an empty marker?
113 bool IsDagEmpty (const DagInit& d) {
114 return GetOperatorName(d) == "empty_dag_marker";
117 // EscapeVariableName - Escape commas and other symbols not allowed
118 // in the C++ variable names. Makes it possible to use options named
119 // like "Wa," (useful for prefix options).
120 std::string EscapeVariableName (const std::string& Var) {
122 for (unsigned i = 0; i != Var.size(); ++i) {
123 char cur_char = Var[i];
124 if (cur_char == ',') {
127 else if (cur_char == '+') {
130 else if (cur_char == '-') {
134 ret.push_back(cur_char);
140 /// EscapeQuotes - Replace '"' with '\"'.
141 std::string EscapeQuotes (const std::string& Var) {
143 for (unsigned i = 0; i != Var.size(); ++i) {
144 char cur_char = Var[i];
145 if (cur_char == '"') {
149 ret.push_back(cur_char);
155 /// OneOf - Does the input string contain this character?
156 bool OneOf(const char* lst, char c) {
164 template <class I, class S>
165 void CheckedIncrement(I& P, I E, S ErrorString) {
171 // apply is needed because C++'s syntax doesn't let us construct a function
172 // object and call it in the same statement.
173 template<typename F, typename T0>
174 void apply(F Fun, T0& Arg0) {
178 template<typename F, typename T0, typename T1>
179 void apply(F Fun, T0& Arg0, T1& Arg1) {
180 return Fun(Arg0, Arg1);
183 //===----------------------------------------------------------------------===//
184 /// Back-end specific code
187 /// OptionType - One of six different option types. See the
188 /// documentation for detailed description of differences.
189 namespace OptionType {
191 enum OptionType { Alias, Switch, SwitchList,
192 Parameter, ParameterList, Prefix, PrefixList };
194 bool IsAlias(OptionType t) {
198 bool IsList (OptionType t) {
199 return (t == SwitchList || t == ParameterList || t == PrefixList);
202 bool IsSwitch (OptionType t) {
203 return (t == Switch);
206 bool IsSwitchList (OptionType t) {
207 return (t == SwitchList);
210 bool IsParameter (OptionType t) {
211 return (t == Parameter || t == Prefix);
216 OptionType::OptionType stringToOptionType(const std::string& T) {
217 if (T == "alias_option")
218 return OptionType::Alias;
219 else if (T == "switch_option")
220 return OptionType::Switch;
221 else if (T == "switch_list_option")
222 return OptionType::SwitchList;
223 else if (T == "parameter_option")
224 return OptionType::Parameter;
225 else if (T == "parameter_list_option")
226 return OptionType::ParameterList;
227 else if (T == "prefix_option")
228 return OptionType::Prefix;
229 else if (T == "prefix_list_option")
230 return OptionType::PrefixList;
232 throw "Unknown option type: " + T + '!';
235 namespace OptionDescriptionFlags {
236 enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
237 ReallyHidden = 0x4, Extern = 0x8,
238 OneOrMore = 0x10, Optional = 0x20,
239 CommaSeparated = 0x40, ForwardNotSplit = 0x80,
240 ZeroOrMore = 0x100 };
243 /// OptionDescription - Represents data contained in a single
244 /// OptionList entry.
245 struct OptionDescription {
246 OptionType::OptionType Type;
253 OptionDescription(OptionType::OptionType t = OptionType::Switch,
254 const std::string& n = "",
255 const std::string& h = DefaultHelpString)
256 : Type(t), Name(n), Flags(0x0), Help(h), MultiVal(1), InitVal(0)
259 /// GenTypeDeclaration - Returns the C++ variable type of this
261 const char* GenTypeDeclaration() const;
263 /// GenVariableName - Returns the variable name used in the
264 /// generated C++ code.
265 std::string GenVariableName() const;
267 /// Merge - Merge two option descriptions.
268 void Merge (const OptionDescription& other);
270 /// CheckConsistency - Check that the flags are consistent.
271 void CheckConsistency() const;
273 // Misc convenient getters/setters.
275 bool isAlias() const;
277 bool isMultiVal() const;
279 bool isCommaSeparated() const;
280 void setCommaSeparated();
282 bool isExtern() const;
285 bool isForwardNotSplit() const;
286 void setForwardNotSplit();
288 bool isRequired() const;
291 bool isOneOrMore() const;
294 bool isZeroOrMore() const;
295 void setZeroOrMore();
297 bool isOptional() const;
300 bool isHidden() const;
303 bool isReallyHidden() const;
304 void setReallyHidden();
306 bool isSwitch() const
307 { return OptionType::IsSwitch(this->Type); }
309 bool isSwitchList() const
310 { return OptionType::IsSwitchList(this->Type); }
312 bool isParameter() const
313 { return OptionType::IsParameter(this->Type); }
316 { return OptionType::IsList(this->Type); }
318 bool isParameterList() const
319 { return (OptionType::IsList(this->Type)
320 && !OptionType::IsSwitchList(this->Type)); }
324 void OptionDescription::CheckConsistency() const {
327 i += this->isRequired();
328 i += this->isOptional();
329 i += this->isOneOrMore();
330 i += this->isZeroOrMore();
333 throw "Only one of (required), (optional), (one_or_more) or "
334 "(zero_or_more) properties is allowed!";
338 void OptionDescription::Merge (const OptionDescription& other)
340 if (other.Type != Type)
341 throw "Conflicting definitions for the option " + Name + "!";
343 if (Help == other.Help || Help == DefaultHelpString)
345 else if (other.Help != DefaultHelpString) {
346 llvm::errs() << "Warning: several different help strings"
347 " defined for option " + Name + "\n";
350 Flags |= other.Flags;
353 bool OptionDescription::isAlias() const {
354 return OptionType::IsAlias(this->Type);
357 bool OptionDescription::isMultiVal() const {
361 bool OptionDescription::isCommaSeparated() const {
362 return Flags & OptionDescriptionFlags::CommaSeparated;
364 void OptionDescription::setCommaSeparated() {
365 Flags |= OptionDescriptionFlags::CommaSeparated;
368 bool OptionDescription::isForwardNotSplit() const {
369 return Flags & OptionDescriptionFlags::ForwardNotSplit;
371 void OptionDescription::setForwardNotSplit() {
372 Flags |= OptionDescriptionFlags::ForwardNotSplit;
375 bool OptionDescription::isExtern() const {
376 return Flags & OptionDescriptionFlags::Extern;
378 void OptionDescription::setExtern() {
379 Flags |= OptionDescriptionFlags::Extern;
382 bool OptionDescription::isRequired() const {
383 return Flags & OptionDescriptionFlags::Required;
385 void OptionDescription::setRequired() {
386 Flags |= OptionDescriptionFlags::Required;
389 bool OptionDescription::isOneOrMore() const {
390 return Flags & OptionDescriptionFlags::OneOrMore;
392 void OptionDescription::setOneOrMore() {
393 Flags |= OptionDescriptionFlags::OneOrMore;
396 bool OptionDescription::isZeroOrMore() const {
397 return Flags & OptionDescriptionFlags::ZeroOrMore;
399 void OptionDescription::setZeroOrMore() {
400 Flags |= OptionDescriptionFlags::ZeroOrMore;
403 bool OptionDescription::isOptional() const {
404 return Flags & OptionDescriptionFlags::Optional;
406 void OptionDescription::setOptional() {
407 Flags |= OptionDescriptionFlags::Optional;
410 bool OptionDescription::isHidden() const {
411 return Flags & OptionDescriptionFlags::Hidden;
413 void OptionDescription::setHidden() {
414 Flags |= OptionDescriptionFlags::Hidden;
417 bool OptionDescription::isReallyHidden() const {
418 return Flags & OptionDescriptionFlags::ReallyHidden;
420 void OptionDescription::setReallyHidden() {
421 Flags |= OptionDescriptionFlags::ReallyHidden;
424 const char* OptionDescription::GenTypeDeclaration() const {
426 case OptionType::Alias:
428 case OptionType::PrefixList:
429 case OptionType::ParameterList:
430 return "cl::list<std::string>";
431 case OptionType::Switch:
432 return "cl::opt<bool>";
433 case OptionType::SwitchList:
434 return "cl::list<bool>";
435 case OptionType::Parameter:
436 case OptionType::Prefix:
438 return "cl::opt<std::string>";
442 std::string OptionDescription::GenVariableName() const {
443 const std::string& EscapedName = EscapeVariableName(Name);
445 case OptionType::Alias:
446 return "AutoGeneratedAlias_" + EscapedName;
447 case OptionType::PrefixList:
448 case OptionType::ParameterList:
449 return "AutoGeneratedList_" + EscapedName;
450 case OptionType::Switch:
451 return "AutoGeneratedSwitch_" + EscapedName;
452 case OptionType::SwitchList:
453 return "AutoGeneratedSwitchList_" + EscapedName;
454 case OptionType::Prefix:
455 case OptionType::Parameter:
457 return "AutoGeneratedParameter_" + EscapedName;
461 /// OptionDescriptions - An OptionDescription array plus some helper
463 class OptionDescriptions {
464 typedef StringMap<OptionDescription> container_type;
466 /// Descriptions - A list of OptionDescriptions.
467 container_type Descriptions;
470 /// FindOption - exception-throwing wrapper for find().
471 const OptionDescription& FindOption(const std::string& OptName) const;
473 // Wrappers for FindOption that throw an exception in case the option has a
475 const OptionDescription& FindSwitch(const std::string& OptName) const;
476 const OptionDescription& FindParameter(const std::string& OptName) const;
477 const OptionDescription& FindList(const std::string& OptName) const;
478 const OptionDescription& FindParameterList(const std::string& OptName) const;
479 const OptionDescription&
480 FindListOrParameter(const std::string& OptName) const;
481 const OptionDescription&
482 FindParameterListOrParameter(const std::string& OptName) const;
484 /// insertDescription - Insert new OptionDescription into
485 /// OptionDescriptions list
486 void InsertDescription (const OptionDescription& o);
488 // Support for STL-style iteration
489 typedef container_type::const_iterator const_iterator;
490 const_iterator begin() const { return Descriptions.begin(); }
491 const_iterator end() const { return Descriptions.end(); }
494 const OptionDescription&
495 OptionDescriptions::FindOption(const std::string& OptName) const {
496 const_iterator I = Descriptions.find(OptName);
497 if (I != Descriptions.end())
500 throw OptName + ": no such option!";
503 const OptionDescription&
504 OptionDescriptions::FindSwitch(const std::string& OptName) const {
505 const OptionDescription& OptDesc = this->FindOption(OptName);
506 if (!OptDesc.isSwitch())
507 throw OptName + ": incorrect option type - should be a switch!";
511 const OptionDescription&
512 OptionDescriptions::FindList(const std::string& OptName) const {
513 const OptionDescription& OptDesc = this->FindOption(OptName);
514 if (!OptDesc.isList())
515 throw OptName + ": incorrect option type - should be a list!";
519 const OptionDescription&
520 OptionDescriptions::FindParameterList(const std::string& OptName) const {
521 const OptionDescription& OptDesc = this->FindOption(OptName);
522 if (!OptDesc.isList() || OptDesc.isSwitchList())
523 throw OptName + ": incorrect option type - should be a parameter list!";
527 const OptionDescription&
528 OptionDescriptions::FindParameter(const std::string& OptName) const {
529 const OptionDescription& OptDesc = this->FindOption(OptName);
530 if (!OptDesc.isParameter())
531 throw OptName + ": incorrect option type - should be a parameter!";
535 const OptionDescription&
536 OptionDescriptions::FindListOrParameter(const std::string& OptName) const {
537 const OptionDescription& OptDesc = this->FindOption(OptName);
538 if (!OptDesc.isList() && !OptDesc.isParameter())
540 + ": incorrect option type - should be a list or parameter!";
544 const OptionDescription&
545 OptionDescriptions::FindParameterListOrParameter
546 (const std::string& OptName) const {
547 const OptionDescription& OptDesc = this->FindOption(OptName);
548 if ((!OptDesc.isList() && !OptDesc.isParameter()) || OptDesc.isSwitchList())
550 + ": incorrect option type - should be a parameter list or parameter!";
554 void OptionDescriptions::InsertDescription (const OptionDescription& o) {
555 container_type::iterator I = Descriptions.find(o.Name);
556 if (I != Descriptions.end()) {
557 OptionDescription& D = I->second;
561 Descriptions[o.Name] = o;
565 /// HandlerTable - A base class for function objects implemented as
566 /// 'tables of handlers'.
567 template <typename Handler>
570 // Implementation details.
572 /// HandlerMap - A map from property names to property handlers
573 typedef StringMap<Handler> HandlerMap;
575 static HandlerMap Handlers_;
576 static bool staticMembersInitialized_;
580 Handler GetHandler (const std::string& HandlerName) const {
581 typename HandlerMap::iterator method = Handlers_.find(HandlerName);
583 if (method != Handlers_.end()) {
584 Handler h = method->second;
588 throw "No handler found for property " + HandlerName + "!";
592 void AddHandler(const char* Property, Handler H) {
593 Handlers_[Property] = H;
598 template <class Handler, class FunctionObject>
599 Handler GetHandler(FunctionObject* Obj, const DagInit& Dag) {
600 const std::string& HandlerName = GetOperatorName(Dag);
601 return Obj->GetHandler(HandlerName);
604 template <class FunctionObject>
605 void InvokeDagInitHandler(FunctionObject* Obj, Init* I) {
606 typedef void (FunctionObject::*Handler) (const DagInit&);
608 const DagInit& Dag = InitPtrToDag(I);
609 Handler h = GetHandler<Handler>(Obj, Dag);
614 template <class FunctionObject>
615 void InvokeDagInitHandler(const FunctionObject* const Obj,
616 const Init* I, unsigned IndentLevel, raw_ostream& O)
618 typedef void (FunctionObject::*Handler)
619 (const DagInit&, unsigned IndentLevel, raw_ostream& O) const;
621 const DagInit& Dag = InitPtrToDag(I);
622 Handler h = GetHandler<Handler>(Obj, Dag);
624 ((Obj)->*(h))(Dag, IndentLevel, O);
628 template <typename H>
629 typename HandlerTable<H>::HandlerMap HandlerTable<H>::Handlers_;
631 template <typename H>
632 bool HandlerTable<H>::staticMembersInitialized_ = false;
635 /// CollectOptionProperties - Function object for iterating over an
636 /// option property list.
637 class CollectOptionProperties;
638 typedef void (CollectOptionProperties::* CollectOptionPropertiesHandler)
641 class CollectOptionProperties
642 : public HandlerTable<CollectOptionPropertiesHandler>
646 /// optDescs_ - OptionDescriptions table. This is where the
647 /// information is stored.
648 OptionDescription& optDesc_;
652 explicit CollectOptionProperties(OptionDescription& OD)
655 if (!staticMembersInitialized_) {
656 AddHandler("extern", &CollectOptionProperties::onExtern);
657 AddHandler("help", &CollectOptionProperties::onHelp);
658 AddHandler("hidden", &CollectOptionProperties::onHidden);
659 AddHandler("init", &CollectOptionProperties::onInit);
660 AddHandler("multi_val", &CollectOptionProperties::onMultiVal);
661 AddHandler("one_or_more", &CollectOptionProperties::onOneOrMore);
662 AddHandler("zero_or_more", &CollectOptionProperties::onZeroOrMore);
663 AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
664 AddHandler("required", &CollectOptionProperties::onRequired);
665 AddHandler("optional", &CollectOptionProperties::onOptional);
666 AddHandler("comma_separated", &CollectOptionProperties::onCommaSeparated);
667 AddHandler("forward_not_split",
668 &CollectOptionProperties::onForwardNotSplit);
670 staticMembersInitialized_ = true;
674 /// operator() - Just forwards to the corresponding property
676 void operator() (Init* I) {
677 InvokeDagInitHandler(this, I);
682 /// Option property handlers --
683 /// Methods that handle option properties such as (help) or (hidden).
685 void onExtern (const DagInit& d) {
686 CheckNumberOfArguments(d, 0);
687 optDesc_.setExtern();
690 void onHelp (const DagInit& d) {
691 CheckNumberOfArguments(d, 1);
692 optDesc_.Help = EscapeQuotes(InitPtrToString(d.getArg(0)));
695 void onHidden (const DagInit& d) {
696 CheckNumberOfArguments(d, 0);
697 optDesc_.setHidden();
700 void onReallyHidden (const DagInit& d) {
701 CheckNumberOfArguments(d, 0);
702 optDesc_.setReallyHidden();
705 void onCommaSeparated (const DagInit& d) {
706 CheckNumberOfArguments(d, 0);
707 if (!optDesc_.isParameterList())
708 throw "'comma_separated' is valid only on parameter list options!";
709 optDesc_.setCommaSeparated();
712 void onForwardNotSplit (const DagInit& d) {
713 CheckNumberOfArguments(d, 0);
714 if (!optDesc_.isParameter())
715 throw "'forward_not_split' is valid only for parameter options!";
716 optDesc_.setForwardNotSplit();
719 void onRequired (const DagInit& d) {
720 CheckNumberOfArguments(d, 0);
722 optDesc_.setRequired();
723 optDesc_.CheckConsistency();
726 void onInit (const DagInit& d) {
727 CheckNumberOfArguments(d, 1);
728 Init* i = d.getArg(0);
729 const std::string& str = i->getAsString();
731 bool correct = optDesc_.isParameter() && dynamic_cast<StringInit*>(i);
732 correct |= (optDesc_.isSwitch() && (str == "true" || str == "false"));
735 throw "Incorrect usage of the 'init' option property!";
737 optDesc_.InitVal = i;
740 void onOneOrMore (const DagInit& d) {
741 CheckNumberOfArguments(d, 0);
743 optDesc_.setOneOrMore();
744 optDesc_.CheckConsistency();
747 void onZeroOrMore (const DagInit& d) {
748 CheckNumberOfArguments(d, 0);
750 if (optDesc_.isList())
751 llvm::errs() << "Warning: specifying the 'zero_or_more' property "
752 "on a list option has no effect.\n";
754 optDesc_.setZeroOrMore();
755 optDesc_.CheckConsistency();
758 void onOptional (const DagInit& d) {
759 CheckNumberOfArguments(d, 0);
761 if (!optDesc_.isList())
762 llvm::errs() << "Warning: specifying the 'optional' property"
763 "on a non-list option has no effect.\n";
765 optDesc_.setOptional();
766 optDesc_.CheckConsistency();
769 void onMultiVal (const DagInit& d) {
770 CheckNumberOfArguments(d, 1);
771 int val = InitPtrToInt(d.getArg(0));
773 throw "Error in the 'multi_val' property: "
774 "the value must be greater than 1!";
775 if (!optDesc_.isParameterList())
776 throw "The multi_val property is valid only on list options!";
777 optDesc_.MultiVal = val;
782 /// AddOption - A function object that is applied to every option
783 /// description. Used by CollectOptionDescriptions.
786 OptionDescriptions& OptDescs_;
789 explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
792 void operator()(const Init* i) {
793 const DagInit& d = InitPtrToDag(i);
794 CheckNumberOfArguments(d, 1);
796 const OptionType::OptionType Type =
797 stringToOptionType(GetOperatorName(d));
798 const std::string& Name = InitPtrToString(d.getArg(0));
800 OptionDescription OD(Type, Name);
803 CheckNumberOfArguments(d, 2);
806 // Aliases store the aliased option name in the 'Help' field.
807 OD.Help = InitPtrToString(d.getArg(1));
809 else if (!OD.isExtern()) {
810 processOptionProperties(d, OD);
812 OptDescs_.InsertDescription(OD);
816 /// processOptionProperties - Go through the list of option
817 /// properties and call a corresponding handler for each.
818 static void processOptionProperties (const DagInit& d, OptionDescription& o) {
819 CheckNumberOfArguments(d, 2);
820 DagInit::const_arg_iterator B = d.arg_begin();
821 // Skip the first argument: it's always the option name.
823 std::for_each(B, d.arg_end(), CollectOptionProperties(o));
828 /// CollectOptionDescriptions - Collects option properties from all
830 void CollectOptionDescriptions (RecordVector::const_iterator B,
831 RecordVector::const_iterator E,
832 OptionDescriptions& OptDescs)
834 // For every OptionList:
836 RecordVector::value_type T = *B;
837 // Throws an exception if the value does not exist.
838 ListInit* PropList = T->getValueAsListInit("options");
840 // For every option description in this list:
841 // collect the information and
842 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
846 // Tool information record
848 namespace ToolFlags {
849 enum ToolFlags { Join = 0x1, Sink = 0x2 };
852 struct ToolDescription : public RefCountedBase<ToolDescription> {
856 StrVector InLanguage;
857 std::string InFileOption;
858 std::string OutFileOption;
859 std::string OutLanguage;
860 std::string OutputSuffix;
864 // Various boolean properties
865 void setSink() { Flags |= ToolFlags::Sink; }
866 bool isSink() const { return Flags & ToolFlags::Sink; }
867 void setJoin() { Flags |= ToolFlags::Join; }
868 bool isJoin() const { return Flags & ToolFlags::Join; }
870 // Default ctor here is needed because StringMap can only store
871 // DefaultConstructible objects
873 : CmdLine(0), Actions(0), OutFileOption("-o"),
876 ToolDescription (const std::string& n)
877 : Name(n), CmdLine(0), Actions(0), OutFileOption("-o"),
882 /// ToolDescriptions - A list of Tool information records.
883 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
886 /// CollectToolProperties - Function object for iterating over a list of
887 /// tool property records.
889 class CollectToolProperties;
890 typedef void (CollectToolProperties::* CollectToolPropertiesHandler)
893 class CollectToolProperties : public HandlerTable<CollectToolPropertiesHandler>
897 /// toolDesc_ - Properties of the current Tool. This is where the
898 /// information is stored.
899 ToolDescription& toolDesc_;
903 explicit CollectToolProperties (ToolDescription& d)
906 if (!staticMembersInitialized_) {
908 AddHandler("actions", &CollectToolProperties::onActions);
909 AddHandler("command", &CollectToolProperties::onCommand);
910 AddHandler("in_language", &CollectToolProperties::onInLanguage);
911 AddHandler("join", &CollectToolProperties::onJoin);
912 AddHandler("out_language", &CollectToolProperties::onOutLanguage);
914 AddHandler("out_file_option", &CollectToolProperties::onOutFileOption);
915 AddHandler("in_file_option", &CollectToolProperties::onInFileOption);
917 AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
918 AddHandler("sink", &CollectToolProperties::onSink);
919 AddHandler("works_on_empty", &CollectToolProperties::onWorksOnEmpty);
921 staticMembersInitialized_ = true;
925 void operator() (Init* I) {
926 InvokeDagInitHandler(this, I);
931 /// Property handlers --
932 /// Functions that extract information about tool properties from
933 /// DAG representation.
935 void onActions (const DagInit& d) {
936 CheckNumberOfArguments(d, 1);
937 Init* Case = d.getArg(0);
938 if (typeid(*Case) != typeid(DagInit) ||
939 GetOperatorName(static_cast<DagInit&>(*Case)) != "case")
940 throw "The argument to (actions) should be a 'case' construct!";
941 toolDesc_.Actions = Case;
944 void onCommand (const DagInit& d) {
945 CheckNumberOfArguments(d, 1);
946 toolDesc_.CmdLine = d.getArg(0);
949 void onInLanguage (const DagInit& d) {
950 CheckNumberOfArguments(d, 1);
951 Init* arg = d.getArg(0);
953 // Find out the argument's type.
954 if (typeid(*arg) == typeid(StringInit)) {
956 toolDesc_.InLanguage.push_back(InitPtrToString(arg));
960 const ListInit& lst = InitPtrToList(arg);
961 StrVector& out = toolDesc_.InLanguage;
963 // Copy strings to the output vector.
964 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
966 out.push_back(InitPtrToString(*B));
969 // Remove duplicates.
970 std::sort(out.begin(), out.end());
971 StrVector::iterator newE = std::unique(out.begin(), out.end());
972 out.erase(newE, out.end());
976 void onJoin (const DagInit& d) {
977 CheckNumberOfArguments(d, 0);
981 void onOutLanguage (const DagInit& d) {
982 CheckNumberOfArguments(d, 1);
983 toolDesc_.OutLanguage = InitPtrToString(d.getArg(0));
986 void onOutFileOption (const DagInit& d) {
987 CheckNumberOfArguments(d, 1);
988 toolDesc_.OutFileOption = InitPtrToString(d.getArg(0));
991 void onInFileOption (const DagInit& d) {
992 CheckNumberOfArguments(d, 1);
993 toolDesc_.InFileOption = InitPtrToString(d.getArg(0));
996 void onOutputSuffix (const DagInit& d) {
997 CheckNumberOfArguments(d, 1);
998 toolDesc_.OutputSuffix = InitPtrToString(d.getArg(0));
1001 void onSink (const DagInit& d) {
1002 CheckNumberOfArguments(d, 0);
1003 toolDesc_.setSink();
1006 void onWorksOnEmpty (const DagInit& d) {
1007 toolDesc_.OnEmpty = d.getArg(0);
1012 /// CollectToolDescriptions - Gather information about tool properties
1013 /// from the parsed TableGen data (basically a wrapper for the
1014 /// CollectToolProperties function object).
1015 void CollectToolDescriptions (RecordVector::const_iterator B,
1016 RecordVector::const_iterator E,
1017 ToolDescriptions& ToolDescs)
1019 // Iterate over a properties list of every Tool definition
1021 const Record* T = *B;
1022 // Throws an exception if the value does not exist.
1023 ListInit* PropList = T->getValueAsListInit("properties");
1025 IntrusiveRefCntPtr<ToolDescription>
1026 ToolDesc(new ToolDescription(T->getName()));
1028 std::for_each(PropList->begin(), PropList->end(),
1029 CollectToolProperties(*ToolDesc));
1030 ToolDescs.push_back(ToolDesc);
1034 /// FillInEdgeVector - Merge all compilation graph definitions into
1035 /// one single edge list.
1036 void FillInEdgeVector(RecordVector::const_iterator B,
1037 RecordVector::const_iterator E, RecordVector& Out) {
1038 for (; B != E; ++B) {
1039 const ListInit* edges = (*B)->getValueAsListInit("edges");
1041 for (unsigned i = 0; i < edges->size(); ++i)
1042 Out.push_back(edges->getElementAsRecord(i));
1046 /// CalculatePriority - Calculate the priority of this plugin.
1047 int CalculatePriority(RecordVector::const_iterator B,
1048 RecordVector::const_iterator E) {
1052 priority = static_cast<int>((*B)->getValueAsInt("priority"));
1055 throw "More than one 'PluginPriority' instance found: "
1056 "most probably an error!";
1062 /// NotInGraph - Helper function object for FilterNotInGraph.
1065 const llvm::StringSet<>& ToolsInGraph_;
1068 NotInGraph(const llvm::StringSet<>& ToolsInGraph)
1069 : ToolsInGraph_(ToolsInGraph)
1072 bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
1073 return (ToolsInGraph_.count(x->Name) == 0);
1077 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
1078 /// mentioned in the compilation graph definition.
1079 void FilterNotInGraph (const RecordVector& EdgeVector,
1080 ToolDescriptions& ToolDescs) {
1082 // List all tools mentioned in the graph.
1083 llvm::StringSet<> ToolsInGraph;
1085 for (RecordVector::const_iterator B = EdgeVector.begin(),
1086 E = EdgeVector.end(); B != E; ++B) {
1088 const Record* Edge = *B;
1089 const std::string& NodeA = Edge->getValueAsString("a");
1090 const std::string& NodeB = Edge->getValueAsString("b");
1092 if (NodeA != "root")
1093 ToolsInGraph.insert(NodeA);
1094 ToolsInGraph.insert(NodeB);
1097 // Filter ToolPropertiesList.
1098 ToolDescriptions::iterator new_end =
1099 std::remove_if(ToolDescs.begin(), ToolDescs.end(),
1100 NotInGraph(ToolsInGraph));
1101 ToolDescs.erase(new_end, ToolDescs.end());
1104 /// FillInToolToLang - Fills in two tables that map tool names to
1105 /// (input, output) languages. Helper function used by TypecheckGraph().
1106 void FillInToolToLang (const ToolDescriptions& ToolDescs,
1107 StringMap<StringSet<> >& ToolToInLang,
1108 StringMap<std::string>& ToolToOutLang) {
1109 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1110 E = ToolDescs.end(); B != E; ++B) {
1111 const ToolDescription& D = *(*B);
1112 for (StrVector::const_iterator B = D.InLanguage.begin(),
1113 E = D.InLanguage.end(); B != E; ++B)
1114 ToolToInLang[D.Name].insert(*B);
1115 ToolToOutLang[D.Name] = D.OutLanguage;
1119 /// TypecheckGraph - Check that names for output and input languages
1120 /// on all edges do match. This doesn't do much when the information
1121 /// about the whole graph is not available (i.e. when compiling most
1123 void TypecheckGraph (const RecordVector& EdgeVector,
1124 const ToolDescriptions& ToolDescs) {
1125 StringMap<StringSet<> > ToolToInLang;
1126 StringMap<std::string> ToolToOutLang;
1128 FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
1129 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
1130 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
1132 for (RecordVector::const_iterator B = EdgeVector.begin(),
1133 E = EdgeVector.end(); B != E; ++B) {
1134 const Record* Edge = *B;
1135 const std::string& NodeA = Edge->getValueAsString("a");
1136 const std::string& NodeB = Edge->getValueAsString("b");
1137 StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
1138 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
1140 if (NodeA != "root") {
1141 if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
1142 throw "Edge " + NodeA + "->" + NodeB
1143 + ": output->input language mismatch";
1146 if (NodeB == "root")
1147 throw "Edges back to the root are not allowed!";
1151 /// WalkCase - Walks the 'case' expression DAG and invokes
1152 /// TestCallback on every test, and StatementCallback on every
1153 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
1154 /// combinators (that is, they are passed directly to TestCallback).
1155 /// TestCallback must have type 'void TestCallback(const DagInit*, unsigned
1156 /// IndentLevel, bool FirstTest)'.
1157 /// StatementCallback must have type 'void StatementCallback(const Init*,
1158 /// unsigned IndentLevel)'.
1159 template <typename F1, typename F2>
1160 void WalkCase(const Init* Case, F1 TestCallback, F2 StatementCallback,
1161 unsigned IndentLevel = 0)
1163 const DagInit& d = InitPtrToDag(Case);
1166 if (GetOperatorName(d) != "case")
1167 throw "WalkCase should be invoked only on 'case' expressions!";
1169 if (d.getNumArgs() < 2)
1170 throw "There should be at least one clause in the 'case' expression:\n"
1175 const unsigned numArgs = d.getNumArgs();
1177 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1184 const DagInit& Test = InitPtrToDag(arg);
1186 if (GetOperatorName(Test) == "default" && (i+1 != numArgs))
1187 throw "The 'default' clause should be the last in the "
1188 "'case' construct!";
1190 throw "Case construct handler: no corresponding action "
1191 "found for the test " + Test.getAsString() + '!';
1193 TestCallback(Test, IndentLevel, (i == 1));
1197 if (dynamic_cast<DagInit*>(arg)
1198 && GetOperatorName(static_cast<DagInit&>(*arg)) == "case") {
1200 WalkCase(arg, TestCallback, StatementCallback, IndentLevel + Indent1);
1203 // Handle statement.
1204 StatementCallback(arg, IndentLevel);
1212 /// ExtractOptionNames - A helper function object used by
1213 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
1214 class ExtractOptionNames {
1215 llvm::StringSet<>& OptionNames_;
1217 void processDag(const Init* Statement) {
1218 const DagInit& Stmt = InitPtrToDag(Statement);
1219 const std::string& ActionName = GetOperatorName(Stmt);
1220 if (ActionName == "forward" || ActionName == "forward_as" ||
1221 ActionName == "forward_value" ||
1222 ActionName == "forward_transformed_value" ||
1223 ActionName == "switch_on" || ActionName == "any_switch_on" ||
1224 ActionName == "parameter_equals" ||
1225 ActionName == "element_in_list" || ActionName == "not_empty" ||
1226 ActionName == "empty") {
1227 CheckNumberOfArguments(Stmt, 1);
1229 Init* Arg = Stmt.getArg(0);
1230 if (typeid(*Arg) == typeid(StringInit)) {
1231 const std::string& Name = InitPtrToString(Arg);
1232 OptionNames_.insert(Name);
1236 const ListInit& List = InitPtrToList(Arg);
1237 for (ListInit::const_iterator B = List.begin(), E = List.end();
1239 const std::string& Name = InitPtrToString(*B);
1240 OptionNames_.insert(Name);
1244 else if (ActionName == "and" || ActionName == "or" || ActionName == "not") {
1245 for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
1246 this->processDag(Stmt.getArg(i));
1252 ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
1255 void operator()(const Init* Statement) {
1256 if (typeid(*Statement) == typeid(ListInit)) {
1257 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1258 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1260 this->processDag(*B);
1263 this->processDag(Statement);
1267 void operator()(const DagInit& Test, unsigned, bool) {
1268 this->operator()(&Test);
1270 void operator()(const Init* Statement, unsigned) {
1271 this->operator()(Statement);
1275 /// CheckForSuperfluousOptions - Check that there are no side
1276 /// effect-free options (specified only in the OptionList). Otherwise,
1277 /// output a warning.
1278 void CheckForSuperfluousOptions (const RecordVector& Edges,
1279 const ToolDescriptions& ToolDescs,
1280 const OptionDescriptions& OptDescs) {
1281 llvm::StringSet<> nonSuperfluousOptions;
1283 // Add all options mentioned in the ToolDesc.Actions to the set of
1284 // non-superfluous options.
1285 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1286 E = ToolDescs.end(); B != E; ++B) {
1287 const ToolDescription& TD = *(*B);
1288 ExtractOptionNames Callback(nonSuperfluousOptions);
1290 WalkCase(TD.Actions, Callback, Callback);
1293 // Add all options mentioned in the 'case' clauses of the
1294 // OptionalEdges of the compilation graph to the set of
1295 // non-superfluous options.
1296 for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
1298 const Record* Edge = *B;
1299 DagInit& Weight = *Edge->getValueAsDag("weight");
1301 if (!IsDagEmpty(Weight))
1302 WalkCase(&Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
1305 // Check that all options in OptDescs belong to the set of
1306 // non-superfluous options.
1307 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
1308 E = OptDescs.end(); B != E; ++B) {
1309 const OptionDescription& Val = B->second;
1310 if (!nonSuperfluousOptions.count(Val.Name)
1311 && Val.Type != OptionType::Alias)
1312 llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! "
1313 "Probable cause: this option is specified only in the OptionList.\n";
1317 /// EmitCaseTest0Args - Helper function used by EmitCaseConstructHandler().
1318 bool EmitCaseTest0Args(const std::string& TestName, raw_ostream& O) {
1319 if (TestName == "single_input_file") {
1320 O << "InputFilenames.size() == 1";
1323 else if (TestName == "multiple_input_files") {
1324 O << "InputFilenames.size() > 1";
1331 /// EmitListTest - Helper function used by EmitCaseTest1ArgList().
1332 template <typename F>
1333 void EmitListTest(const ListInit& L, const char* LogicOp,
1334 F Callback, raw_ostream& O)
1336 // This is a lot like EmitLogicalOperationTest, but works on ListInits instead
1338 bool isFirst = true;
1339 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B) {
1343 O << ' ' << LogicOp << ' ';
1344 Callback(InitPtrToString(*B), O);
1348 // Callbacks for use with EmitListTest.
1350 class EmitSwitchOn {
1351 const OptionDescriptions& OptDescs_;
1353 EmitSwitchOn(const OptionDescriptions& OptDescs) : OptDescs_(OptDescs)
1356 void operator()(const std::string& OptName, raw_ostream& O) const {
1357 const OptionDescription& OptDesc = OptDescs_.FindSwitch(OptName);
1358 O << OptDesc.GenVariableName();
1362 class EmitEmptyTest {
1364 const OptionDescriptions& OptDescs_;
1366 EmitEmptyTest(bool EmitNegate, const OptionDescriptions& OptDescs)
1367 : EmitNegate_(EmitNegate), OptDescs_(OptDescs)
1370 void operator()(const std::string& OptName, raw_ostream& O) const {
1371 const char* Neg = (EmitNegate_ ? "!" : "");
1372 if (OptName == "o") {
1373 O << Neg << "OutputFilename.empty()";
1375 else if (OptName == "save-temps") {
1376 O << Neg << "(SaveTemps == SaveTempsEnum::Unset)";
1379 const OptionDescription& OptDesc = OptDescs_.FindListOrParameter(OptName);
1380 O << Neg << OptDesc.GenVariableName() << ".empty()";
1386 /// EmitCaseTest1ArgList - Helper function used by EmitCaseTest1Arg();
1387 bool EmitCaseTest1ArgList(const std::string& TestName,
1389 const OptionDescriptions& OptDescs,
1391 const ListInit& L = InitPtrToList(d.getArg(0));
1393 if (TestName == "any_switch_on") {
1394 EmitListTest(L, "||", EmitSwitchOn(OptDescs), O);
1397 else if (TestName == "switch_on") {
1398 EmitListTest(L, "&&", EmitSwitchOn(OptDescs), O);
1401 else if (TestName == "any_not_empty") {
1402 EmitListTest(L, "||", EmitEmptyTest(true, OptDescs), O);
1405 else if (TestName == "any_empty") {
1406 EmitListTest(L, "||", EmitEmptyTest(false, OptDescs), O);
1409 else if (TestName == "not_empty") {
1410 EmitListTest(L, "&&", EmitEmptyTest(true, OptDescs), O);
1413 else if (TestName == "empty") {
1414 EmitListTest(L, "&&", EmitEmptyTest(false, OptDescs), O);
1421 /// EmitCaseTest1ArgStr - Helper function used by EmitCaseTest1Arg();
1422 bool EmitCaseTest1ArgStr(const std::string& TestName,
1424 const OptionDescriptions& OptDescs,
1426 const std::string& OptName = InitPtrToString(d.getArg(0));
1428 if (TestName == "switch_on") {
1429 apply(EmitSwitchOn(OptDescs), OptName, O);
1432 else if (TestName == "input_languages_contain") {
1433 O << "InLangs.count(\"" << OptName << "\") != 0";
1436 else if (TestName == "in_language") {
1437 // This works only for single-argument Tool::GenerateAction. Join
1438 // tools can process several files in different languages simultaneously.
1440 // TODO: make this work with Edge::Weight (if possible).
1441 O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
1444 else if (TestName == "not_empty" || TestName == "empty") {
1445 bool EmitNegate = (TestName == "not_empty");
1446 apply(EmitEmptyTest(EmitNegate, OptDescs), OptName, O);
1453 /// EmitCaseTest1Arg - Helper function used by EmitCaseConstructHandler();
1454 bool EmitCaseTest1Arg(const std::string& TestName,
1456 const OptionDescriptions& OptDescs,
1458 CheckNumberOfArguments(d, 1);
1459 if (typeid(*d.getArg(0)) == typeid(ListInit))
1460 return EmitCaseTest1ArgList(TestName, d, OptDescs, O);
1462 return EmitCaseTest1ArgStr(TestName, d, OptDescs, O);
1465 /// EmitCaseTest2Args - Helper function used by EmitCaseConstructHandler().
1466 bool EmitCaseTest2Args(const std::string& TestName,
1468 unsigned IndentLevel,
1469 const OptionDescriptions& OptDescs,
1471 CheckNumberOfArguments(d, 2);
1472 const std::string& OptName = InitPtrToString(d.getArg(0));
1473 const std::string& OptArg = InitPtrToString(d.getArg(1));
1475 if (TestName == "parameter_equals") {
1476 const OptionDescription& OptDesc = OptDescs.FindParameter(OptName);
1477 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
1480 else if (TestName == "element_in_list") {
1481 const OptionDescription& OptDesc = OptDescs.FindParameterList(OptName);
1482 const std::string& VarName = OptDesc.GenVariableName();
1483 O << "std::find(" << VarName << ".begin(),\n";
1484 O.indent(IndentLevel + Indent1)
1485 << VarName << ".end(), \""
1486 << OptArg << "\") != " << VarName << ".end()";
1493 // Forward declaration.
1494 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
1495 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1496 const OptionDescriptions& OptDescs,
1499 /// EmitLogicalOperationTest - Helper function used by
1500 /// EmitCaseConstructHandler.
1501 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
1502 unsigned IndentLevel,
1503 const OptionDescriptions& OptDescs,
1506 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
1507 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
1508 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1509 if (j != NumArgs - 1) {
1511 O.indent(IndentLevel + Indent1) << ' ' << LogicOp << " (";
1519 void EmitLogicalNot(const DagInit& d, unsigned IndentLevel,
1520 const OptionDescriptions& OptDescs, raw_ostream& O)
1522 CheckNumberOfArguments(d, 1);
1523 const DagInit& InnerTest = InitPtrToDag(d.getArg(0));
1525 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1529 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
1530 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1531 const OptionDescriptions& OptDescs,
1533 const std::string& TestName = GetOperatorName(d);
1535 if (TestName == "and")
1536 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
1537 else if (TestName == "or")
1538 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
1539 else if (TestName == "not")
1540 EmitLogicalNot(d, IndentLevel, OptDescs, O);
1541 else if (EmitCaseTest0Args(TestName, O))
1543 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
1545 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
1548 throw "Unknown test '" + TestName + "' used in the 'case' construct!";
1552 /// EmitCaseTestCallback - Callback used by EmitCaseConstructHandler.
1553 class EmitCaseTestCallback {
1555 const OptionDescriptions& OptDescs_;
1559 EmitCaseTestCallback(bool EmitElseIf,
1560 const OptionDescriptions& OptDescs, raw_ostream& O)
1561 : EmitElseIf_(EmitElseIf), OptDescs_(OptDescs), O_(O)
1564 void operator()(const DagInit& Test, unsigned IndentLevel, bool FirstTest)
1566 if (GetOperatorName(Test) == "default") {
1567 O_.indent(IndentLevel) << "else {\n";
1570 O_.indent(IndentLevel)
1571 << ((!FirstTest && EmitElseIf_) ? "else if (" : "if (");
1572 EmitCaseTest(Test, IndentLevel, OptDescs_, O_);
1578 /// EmitCaseStatementCallback - Callback used by EmitCaseConstructHandler.
1579 template <typename F>
1580 class EmitCaseStatementCallback {
1585 EmitCaseStatementCallback(F Callback, raw_ostream& O)
1586 : Callback_(Callback), O_(O)
1589 void operator() (const Init* Statement, unsigned IndentLevel) {
1591 // Ignore nested 'case' DAG.
1592 if (!(dynamic_cast<const DagInit*>(Statement) &&
1593 GetOperatorName(static_cast<const DagInit&>(*Statement)) == "case")) {
1594 if (typeid(*Statement) == typeid(ListInit)) {
1595 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1596 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1598 Callback_(*B, (IndentLevel + Indent1), O_);
1601 Callback_(Statement, (IndentLevel + Indent1), O_);
1604 O_.indent(IndentLevel) << "}\n";
1609 /// EmitCaseConstructHandler - Emit code that handles the 'case'
1610 /// construct. Takes a function object that should emit code for every case
1611 /// clause. Implemented on top of WalkCase.
1612 /// Callback's type is void F(const Init* Statement, unsigned IndentLevel,
1613 /// raw_ostream& O).
1614 /// EmitElseIf parameter controls the type of condition that is emitted ('if
1615 /// (..) {..} else if (..) {} .. else {..}' vs. 'if (..) {..} if(..) {..}
1617 template <typename F>
1618 void EmitCaseConstructHandler(const Init* Case, unsigned IndentLevel,
1619 F Callback, bool EmitElseIf,
1620 const OptionDescriptions& OptDescs,
1622 WalkCase(Case, EmitCaseTestCallback(EmitElseIf, OptDescs, O),
1623 EmitCaseStatementCallback<F>(Callback, O), IndentLevel);
1626 /// TokenizeCmdLine - converts from
1627 /// "$CALL(HookName, 'Arg1', 'Arg2')/path -arg1 -arg2" to
1628 /// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path", "-arg1", "-arg2"].
1629 void TokenizeCmdLine(const std::string& CmdLine, StrVector& Out) {
1630 const char* Delimiters = " \t\n\v\f\r";
1632 { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1635 if (CmdLine.empty())
1639 std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1642 for (; B != E; ++B) {
1643 char cur_ch = CmdLine[B];
1647 if (cur_ch == '$') {
1648 cur_st = SpecialCommand;
1651 if (OneOf(Delimiters, cur_ch)) {
1653 B = CmdLine.find_first_not_of(Delimiters, B);
1654 if (B == std::string::npos) {
1665 case SpecialCommand:
1666 if (OneOf(Delimiters, cur_ch)) {
1671 if (cur_ch == '(') {
1673 cur_st = InsideSpecialCommand;
1678 case InsideSpecialCommand:
1679 if (OneOf(Delimiters, cur_ch)) {
1682 if (cur_ch == '\'') {
1683 cur_st = InsideQuotationMarks;
1687 if (cur_ch == ')') {
1691 if (cur_ch == ',') {
1697 case InsideQuotationMarks:
1698 if (cur_ch == '\'') {
1699 cur_st = InsideSpecialCommand;
1705 Out.back().push_back(cur_ch);
1709 /// SubstituteCall - Given "$CALL(HookName, [Arg1 [, Arg2 [...]]])", output
1710 /// "hooks::HookName([Arg1 [, Arg2 [, ...]]])". Helper function used by
1711 /// SubstituteSpecialCommands().
1712 StrVector::const_iterator
1713 SubstituteCall (StrVector::const_iterator Pos,
1714 StrVector::const_iterator End,
1715 bool IsJoin, raw_ostream& O)
1717 const char* errorMessage = "Syntax error in $CALL invocation!";
1718 CheckedIncrement(Pos, End, errorMessage);
1719 const std::string& CmdName = *Pos;
1722 throw "$CALL invocation: empty argument list!";
1725 O << CmdName << "(";
1728 bool firstIteration = true;
1730 CheckedIncrement(Pos, End, errorMessage);
1731 const std::string& Arg = *Pos;
1732 assert(Arg.size() != 0);
1738 firstIteration = false;
1742 if (Arg == "$INFILE") {
1744 throw "$CALL(Hook, $INFILE) can't be used with a Join tool!";
1746 O << "inFile.c_str()";
1749 O << '"' << Arg << '"';
1758 /// SubstituteEnv - Given '$ENV(VAR_NAME)', output 'getenv("VAR_NAME")'. Helper
1759 /// function used by SubstituteSpecialCommands().
1760 StrVector::const_iterator
1761 SubstituteEnv (StrVector::const_iterator Pos,
1762 StrVector::const_iterator End, raw_ostream& O)
1764 const char* errorMessage = "Syntax error in $ENV invocation!";
1765 CheckedIncrement(Pos, End, errorMessage);
1766 const std::string& EnvName = *Pos;
1769 throw "$ENV invocation: empty argument list!";
1771 O << "checkCString(std::getenv(\"";
1775 CheckedIncrement(Pos, End, errorMessage);
1780 /// SubstituteSpecialCommands - Given an invocation of $CALL or $ENV, output
1781 /// handler code. Helper function used by EmitCmdLineVecFill().
1782 StrVector::const_iterator
1783 SubstituteSpecialCommands (StrVector::const_iterator Pos,
1784 StrVector::const_iterator End,
1785 bool IsJoin, raw_ostream& O)
1788 const std::string& cmd = *Pos;
1790 // Perform substitution.
1791 if (cmd == "$CALL") {
1792 Pos = SubstituteCall(Pos, End, IsJoin, O);
1794 else if (cmd == "$ENV") {
1795 Pos = SubstituteEnv(Pos, End, O);
1798 throw "Unknown special command: " + cmd;
1801 // Handle '$CMD(ARG)/additional/text'.
1802 const std::string& Leftover = *Pos;
1803 assert(Leftover.at(0) == ')');
1804 if (Leftover.size() != 1)
1805 O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1810 /// EmitCmdLineVecFill - Emit code that fills in the command line
1811 /// vector. Helper function used by EmitGenerateActionMethod().
1812 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1813 bool IsJoin, unsigned IndentLevel,
1816 TokenizeCmdLine(InitPtrToString(CmdLine), StrVec);
1819 throw "Tool '" + ToolName + "' has empty command line!";
1821 StrVector::const_iterator B = StrVec.begin(), E = StrVec.end();
1823 // Emit the command itself.
1824 assert(!StrVec[0].empty());
1825 O.indent(IndentLevel) << "cmd = ";
1826 if (StrVec[0][0] == '$') {
1827 B = SubstituteSpecialCommands(B, E, IsJoin, O);
1831 O << '"' << StrVec[0] << '"';
1836 // Go through the command arguments.
1838 for (; B != E; ++B) {
1839 const std::string& cmd = *B;
1841 assert(!cmd.empty());
1842 O.indent(IndentLevel);
1844 if (cmd.at(0) == '$') {
1845 O << "vec.push_back(std::make_pair(0, ";
1846 B = SubstituteSpecialCommands(B, E, IsJoin, O);
1850 O << "vec.push_back(std::make_pair(0, \"" << cmd << "\"));\n";
1856 /// EmitForEachListElementCycleHeader - Emit common code for iterating through
1857 /// all elements of a list. Helper function used by
1858 /// EmitForwardOptionPropertyHandlingCode.
1859 void EmitForEachListElementCycleHeader (const OptionDescription& D,
1860 unsigned IndentLevel,
1862 unsigned IndentLevel1 = IndentLevel + Indent1;
1864 O.indent(IndentLevel)
1865 << "for (" << D.GenTypeDeclaration()
1866 << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1867 O.indent(IndentLevel)
1868 << "E = " << D.GenVariableName() << ".end(); B != E;) {\n";
1869 O.indent(IndentLevel1) << "unsigned pos = " << D.GenVariableName()
1870 << ".getPosition(B - " << D.GenVariableName()
1874 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1875 /// implement EmitActionHandler. Emits code for
1876 /// handling the (forward) and (forward_as) option properties.
1877 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1878 unsigned IndentLevel,
1879 const std::string& NewName,
1881 const std::string& Name = NewName.empty()
1884 unsigned IndentLevel1 = IndentLevel + Indent1;
1887 case OptionType::Switch:
1888 O.indent(IndentLevel)
1889 << "vec.push_back(std::make_pair(" << D.GenVariableName()
1890 << ".getPosition(), \"" << Name << "\"));\n";
1892 case OptionType::Parameter:
1893 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
1894 << D.GenVariableName()
1895 <<".getPosition(), \"" << Name;
1897 if (!D.isForwardNotSplit()) {
1899 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
1900 << D.GenVariableName() << ".getPosition(), "
1901 << D.GenVariableName() << "));\n";
1904 O << "=\" + " << D.GenVariableName() << "));\n";
1907 case OptionType::Prefix:
1908 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
1909 << D.GenVariableName() << ".getPosition(), \""
1911 << D.GenVariableName() << "));\n";
1913 case OptionType::PrefixList:
1914 EmitForEachListElementCycleHeader(D, IndentLevel, O);
1915 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, \""
1916 << Name << "\" + " << "*B));\n";
1917 O.indent(IndentLevel1) << "++B;\n";
1919 for (int i = 1, j = D.MultiVal; i < j; ++i) {
1920 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, *B));\n";
1921 O.indent(IndentLevel1) << "++B;\n";
1924 O.indent(IndentLevel) << "}\n";
1926 case OptionType::ParameterList:
1927 EmitForEachListElementCycleHeader(D, IndentLevel, O);
1928 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, \""
1929 << Name << "\"));\n";
1931 for (int i = 0, j = D.MultiVal; i < j; ++i) {
1932 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, *B));\n";
1933 O.indent(IndentLevel1) << "++B;\n";
1936 O.indent(IndentLevel) << "}\n";
1938 case OptionType::SwitchList:
1939 EmitForEachListElementCycleHeader(D, IndentLevel, O);
1940 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, \""
1941 << Name << "\"));\n";
1942 O.indent(IndentLevel1) << "++B;\n";
1943 O.indent(IndentLevel) << "}\n";
1945 case OptionType::Alias:
1947 throw "Aliases are not allowed in tool option descriptions!";
1951 /// ActionHandlingCallbackBase - Base class of EmitActionHandlersCallback and
1952 /// EmitPreprocessOptionsCallback.
1953 struct ActionHandlingCallbackBase
1956 void onErrorDag(const DagInit& d,
1957 unsigned IndentLevel, raw_ostream& O) const
1959 O.indent(IndentLevel)
1961 << (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0)) : "Unknown error!")
1963 O.indent(IndentLevel) << "return 1;\n";
1966 void onWarningDag(const DagInit& d,
1967 unsigned IndentLevel, raw_ostream& O) const
1969 CheckNumberOfArguments(d, 1);
1970 O.indent(IndentLevel) << "llvm::errs() << \""
1971 << InitPtrToString(d.getArg(0)) << "\";\n";
1976 /// EmitActionHandlersCallback - Emit code that handles actions. Used by
1977 /// EmitGenerateActionMethod() as an argument to EmitCaseConstructHandler().
1979 class EmitActionHandlersCallback;
1981 typedef void (EmitActionHandlersCallback::* EmitActionHandlersCallbackHandler)
1982 (const DagInit&, unsigned, raw_ostream&) const;
1984 class EmitActionHandlersCallback :
1985 public ActionHandlingCallbackBase,
1986 public HandlerTable<EmitActionHandlersCallbackHandler>
1988 typedef EmitActionHandlersCallbackHandler Handler;
1990 const OptionDescriptions& OptDescs;
1992 /// EmitHookInvocation - Common code for hook invocation from actions. Used by
1993 /// onAppendCmd and onOutputSuffix.
1994 void EmitHookInvocation(const std::string& Str,
1995 const char* BlockOpen, const char* BlockClose,
1996 unsigned IndentLevel, raw_ostream& O) const
1999 TokenizeCmdLine(Str, Out);
2001 for (StrVector::const_iterator B = Out.begin(), E = Out.end();
2003 const std::string& cmd = *B;
2005 O.indent(IndentLevel) << BlockOpen;
2007 if (cmd.at(0) == '$')
2008 B = SubstituteSpecialCommands(B, E, /* IsJoin = */ true, O);
2010 O << '"' << cmd << '"';
2016 void onAppendCmd (const DagInit& Dag,
2017 unsigned IndentLevel, raw_ostream& O) const
2019 CheckNumberOfArguments(Dag, 1);
2020 this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
2021 "vec.push_back(std::make_pair(65536, ", "));\n",
2025 void onForward (const DagInit& Dag,
2026 unsigned IndentLevel, raw_ostream& O) const
2028 CheckNumberOfArguments(Dag, 1);
2029 const std::string& Name = InitPtrToString(Dag.getArg(0));
2030 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
2031 IndentLevel, "", O);
2034 void onForwardAs (const DagInit& Dag,
2035 unsigned IndentLevel, raw_ostream& O) const
2037 CheckNumberOfArguments(Dag, 2);
2038 const std::string& Name = InitPtrToString(Dag.getArg(0));
2039 const std::string& NewName = InitPtrToString(Dag.getArg(1));
2040 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
2041 IndentLevel, NewName, O);
2044 void onForwardValue (const DagInit& Dag,
2045 unsigned IndentLevel, raw_ostream& O) const
2047 CheckNumberOfArguments(Dag, 1);
2048 const std::string& Name = InitPtrToString(Dag.getArg(0));
2049 const OptionDescription& D = OptDescs.FindParameterListOrParameter(Name);
2051 if (D.isSwitchList()) {
2052 throw std::runtime_error
2053 ("forward_value is not allowed with switch_list");
2056 if (D.isParameter()) {
2057 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
2058 << D.GenVariableName() << ".getPosition(), "
2059 << D.GenVariableName() << "));\n";
2062 O.indent(IndentLevel) << "for (" << D.GenTypeDeclaration()
2063 << "::iterator B = " << D.GenVariableName()
2065 O.indent(IndentLevel + Indent1) << " E = " << D.GenVariableName()
2066 << ".end(); B != E; ++B)\n";
2067 O.indent(IndentLevel) << "{\n";
2068 O.indent(IndentLevel + Indent1)
2069 << "unsigned pos = " << D.GenVariableName()
2070 << ".getPosition(B - " << D.GenVariableName()
2072 O.indent(IndentLevel + Indent1)
2073 << "vec.push_back(std::make_pair(pos, *B));\n";
2074 O.indent(IndentLevel) << "}\n";
2078 void onForwardTransformedValue (const DagInit& Dag,
2079 unsigned IndentLevel, raw_ostream& O) const
2081 CheckNumberOfArguments(Dag, 2);
2082 const std::string& Name = InitPtrToString(Dag.getArg(0));
2083 const std::string& Hook = InitPtrToString(Dag.getArg(1));
2084 const OptionDescription& D = OptDescs.FindParameterListOrParameter(Name);
2086 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
2087 << D.GenVariableName() << ".getPosition("
2088 << (D.isList() ? "0" : "") << "), "
2089 << "hooks::" << Hook << "(" << D.GenVariableName()
2090 << (D.isParameter() ? ".c_str()" : "") << ")));\n";
2093 void onNoOutFile (const DagInit& Dag,
2094 unsigned IndentLevel, raw_ostream& O) const
2096 CheckNumberOfArguments(Dag, 0);
2097 O.indent(IndentLevel) << "no_out_file = true;\n";
2100 void onOutputSuffix (const DagInit& Dag,
2101 unsigned IndentLevel, raw_ostream& O) const
2103 CheckNumberOfArguments(Dag, 1);
2104 this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
2105 "output_suffix = ", ";\n", IndentLevel, O);
2108 void onStopCompilation (const DagInit& Dag,
2109 unsigned IndentLevel, raw_ostream& O) const
2111 O.indent(IndentLevel) << "stop_compilation = true;\n";
2115 void onUnpackValues (const DagInit& Dag,
2116 unsigned IndentLevel, raw_ostream& O) const
2118 throw "'unpack_values' is deprecated. "
2119 "Use 'comma_separated' + 'forward_value' instead!";
2124 explicit EmitActionHandlersCallback(const OptionDescriptions& OD)
2127 if (!staticMembersInitialized_) {
2128 AddHandler("error", &EmitActionHandlersCallback::onErrorDag);
2129 AddHandler("warning", &EmitActionHandlersCallback::onWarningDag);
2130 AddHandler("append_cmd", &EmitActionHandlersCallback::onAppendCmd);
2131 AddHandler("forward", &EmitActionHandlersCallback::onForward);
2132 AddHandler("forward_as", &EmitActionHandlersCallback::onForwardAs);
2133 AddHandler("forward_value", &EmitActionHandlersCallback::onForwardValue);
2134 AddHandler("forward_transformed_value",
2135 &EmitActionHandlersCallback::onForwardTransformedValue);
2136 AddHandler("no_out_file",
2137 &EmitActionHandlersCallback::onNoOutFile);
2138 AddHandler("output_suffix", &EmitActionHandlersCallback::onOutputSuffix);
2139 AddHandler("stop_compilation",
2140 &EmitActionHandlersCallback::onStopCompilation);
2141 AddHandler("unpack_values",
2142 &EmitActionHandlersCallback::onUnpackValues);
2145 staticMembersInitialized_ = true;
2149 void operator()(const Init* I,
2150 unsigned IndentLevel, raw_ostream& O) const
2152 InvokeDagInitHandler(this, I, IndentLevel, O);
2156 void EmitGenerateActionMethodHeader(const ToolDescription& D,
2157 bool IsJoin, bool Naked,
2160 O.indent(Indent1) << "int GenerateAction(Action& Out,\n";
2163 O.indent(Indent2) << "const PathVector& inFiles,\n";
2165 O.indent(Indent2) << "const sys::Path& inFile,\n";
2167 O.indent(Indent2) << "const bool HasChildren,\n";
2168 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
2169 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
2170 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
2171 O.indent(Indent1) << "{\n";
2174 O.indent(Indent2) << "std::string cmd;\n";
2175 O.indent(Indent2) << "std::string out_file;\n";
2177 << "std::vector<std::pair<unsigned, std::string> > vec;\n";
2178 O.indent(Indent2) << "bool stop_compilation = !HasChildren;\n";
2179 O.indent(Indent2) << "bool no_out_file = false;\n";
2180 O.indent(Indent2) << "const char* output_suffix = \""
2181 << D.OutputSuffix << "\";\n";
2185 // EmitGenerateActionMethod - Emit either a normal or a "join" version of the
2186 // Tool::GenerateAction() method.
2187 void EmitGenerateActionMethod (const ToolDescription& D,
2188 const OptionDescriptions& OptDescs,
2189 bool IsJoin, raw_ostream& O) {
2191 EmitGenerateActionMethodHeader(D, IsJoin, /* Naked = */ false, O);
2194 throw "Tool " + D.Name + " has no cmd_line property!";
2196 // Process the 'command' property.
2198 EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
2201 // Process the 'actions' list of this tool.
2203 EmitCaseConstructHandler(D.Actions, Indent2,
2204 EmitActionHandlersCallback(OptDescs),
2205 false, OptDescs, O);
2209 if (!D.InFileOption.empty()) {
2211 << "vec.push_back(std::make_pair(InputFilenames.getPosition(0), \""
2212 << D.InFileOption << "\");\n";
2217 << "for (PathVector::const_iterator B = inFiles.begin(),\n";
2218 O.indent(Indent3) << "E = inFiles.end(); B != E; ++B)\n";
2219 O.indent(Indent2) << "{\n";
2220 O.indent(Indent3) << "vec.push_back(std::make_pair("
2221 << "InputFilenames.getPosition(B - inFiles.begin()), "
2223 O.indent(Indent2) << "}\n";
2226 O.indent(Indent2) << "vec.push_back(std::make_pair("
2227 << "InputFilenames.getPosition(0), inFile.str()));\n";
2231 O.indent(Indent2) << "if (!no_out_file) {\n";
2232 if (!D.OutFileOption.empty())
2233 O.indent(Indent3) << "vec.push_back(std::make_pair(65536, \""
2234 << D.OutFileOption << "\"));\n";
2236 O.indent(Indent3) << "out_file = this->OutFilename("
2237 << (IsJoin ? "sys::Path(),\n" : "inFile,\n");
2238 O.indent(Indent4) << "TempDir, stop_compilation, output_suffix).str();\n\n";
2239 O.indent(Indent3) << "vec.push_back(std::make_pair(65536, out_file));\n";
2241 O.indent(Indent2) << "}\n\n";
2243 // Handle the Sink property.
2245 O.indent(Indent2) << "if (!" << SinkOptionName << ".empty()) {\n";
2246 O.indent(Indent3) << "for (cl::list<std::string>::iterator B = "
2247 << SinkOptionName << ".begin(), E = " << SinkOptionName
2248 << ".end(); B != E; ++B)\n";
2249 O.indent(Indent4) << "vec.push_back(std::make_pair(" << SinkOptionName
2250 << ".getPosition(B - " << SinkOptionName
2251 << ".begin()), *B));\n";
2252 O.indent(Indent2) << "}\n";
2255 O.indent(Indent2) << "Out.Construct(cmd, this->SortArgs(vec), "
2256 << "stop_compilation, out_file);\n";
2257 O.indent(Indent2) << "return 0;\n";
2258 O.indent(Indent1) << "}\n\n";
2261 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
2262 /// a given Tool class.
2263 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
2264 const OptionDescriptions& OptDescs,
2266 if (!ToolDesc.isJoin()) {
2267 EmitGenerateActionMethodHeader(ToolDesc, /* IsJoin = */ true,
2268 /* Naked = */ true, O);
2269 O.indent(Indent2) << "PrintError(\"" << ToolDesc.Name
2270 << " is not a Join tool!\");\n";
2271 O.indent(Indent2) << "return -1;\n";
2272 O.indent(Indent1) << "}\n\n";
2275 EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
2278 EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
2281 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
2282 /// methods for a given Tool class.
2283 void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
2284 O.indent(Indent1) << "const char** InputLanguages() const {\n";
2285 O.indent(Indent2) << "return InputLanguages_;\n";
2286 O.indent(Indent1) << "}\n\n";
2288 if (D.OutLanguage.empty())
2289 throw "Tool " + D.Name + " has no 'out_language' property!";
2291 O.indent(Indent1) << "const char* OutputLanguage() const {\n";
2292 O.indent(Indent2) << "return \"" << D.OutLanguage << "\";\n";
2293 O.indent(Indent1) << "}\n\n";
2296 /// EmitNameMethod - Emit the Name() method for a given Tool class.
2297 void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
2298 O.indent(Indent1) << "const char* Name() const {\n";
2299 O.indent(Indent2) << "return \"" << D.Name << "\";\n";
2300 O.indent(Indent1) << "}\n\n";
2303 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
2305 void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
2306 O.indent(Indent1) << "bool IsJoin() const {\n";
2308 O.indent(Indent2) << "return true;\n";
2310 O.indent(Indent2) << "return false;\n";
2311 O.indent(Indent1) << "}\n\n";
2314 /// EmitWorksOnEmptyCallback - Callback used by EmitWorksOnEmptyMethod in
2315 /// conjunction with EmitCaseConstructHandler.
2316 void EmitWorksOnEmptyCallback (const Init* Value,
2317 unsigned IndentLevel, raw_ostream& O) {
2318 CheckBooleanConstant(Value);
2319 O.indent(IndentLevel) << "return " << Value->getAsString() << ";\n";
2322 /// EmitWorksOnEmptyMethod - Emit the WorksOnEmpty() method for a given Tool
2324 void EmitWorksOnEmptyMethod (const ToolDescription& D,
2325 const OptionDescriptions& OptDescs,
2328 O.indent(Indent1) << "bool WorksOnEmpty() const {\n";
2330 O.indent(Indent2) << "return false;\n";
2332 EmitCaseConstructHandler(D.OnEmpty, Indent2, EmitWorksOnEmptyCallback,
2333 /*EmitElseIf = */ true, OptDescs, O);
2334 O.indent(Indent1) << "}\n\n";
2337 /// EmitStaticMemberDefinitions - Emit static member definitions for a
2338 /// given Tool class.
2339 void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
2340 if (D.InLanguage.empty())
2341 throw "Tool " + D.Name + " has no 'in_language' property!";
2343 O << "const char* " << D.Name << "::InputLanguages_[] = {";
2344 for (StrVector::const_iterator B = D.InLanguage.begin(),
2345 E = D.InLanguage.end(); B != E; ++B)
2346 O << '\"' << *B << "\", ";
2350 /// EmitToolClassDefinition - Emit a Tool class definition.
2351 void EmitToolClassDefinition (const ToolDescription& D,
2352 const OptionDescriptions& OptDescs,
2354 if (D.Name == "root")
2358 O << "class " << D.Name << " : public ";
2364 O << " {\nprivate:\n";
2365 O.indent(Indent1) << "static const char* InputLanguages_[];\n\n";
2368 EmitNameMethod(D, O);
2369 EmitInOutLanguageMethods(D, O);
2370 EmitIsJoinMethod(D, O);
2371 EmitWorksOnEmptyMethod(D, OptDescs, O);
2372 EmitGenerateActionMethods(D, OptDescs, O);
2374 // Close class definition
2377 EmitStaticMemberDefinitions(D, O);
2381 /// EmitOptionDefinitions - Iterate over a list of option descriptions
2382 /// and emit registration code.
2383 void EmitOptionDefinitions (const OptionDescriptions& descs,
2384 bool HasSink, bool HasExterns,
2387 std::vector<OptionDescription> Aliases;
2389 // Emit static cl::Option variables.
2390 for (OptionDescriptions::const_iterator B = descs.begin(),
2391 E = descs.end(); B!=E; ++B) {
2392 const OptionDescription& val = B->second;
2394 if (val.Type == OptionType::Alias) {
2395 Aliases.push_back(val);
2402 O << val.GenTypeDeclaration() << ' '
2403 << val.GenVariableName();
2405 if (val.isExtern()) {
2410 O << "(\"" << val.Name << "\"\n";
2412 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
2413 O << ", cl::Prefix";
2415 if (val.isRequired()) {
2416 if (val.isList() && !val.isMultiVal())
2417 O << ", cl::OneOrMore";
2419 O << ", cl::Required";
2422 if (val.isOptional())
2423 O << ", cl::Optional";
2425 if (val.isOneOrMore())
2426 O << ", cl::OneOrMore";
2428 if (val.isZeroOrMore())
2429 O << ", cl::ZeroOrMore";
2431 if (val.isReallyHidden())
2432 O << ", cl::ReallyHidden";
2433 else if (val.isHidden())
2434 O << ", cl::Hidden";
2436 if (val.isCommaSeparated())
2437 O << ", cl::CommaSeparated";
2439 if (val.MultiVal > 1)
2440 O << ", cl::multi_val(" << val.MultiVal << ')';
2443 const std::string& str = val.InitVal->getAsString();
2444 O << ", cl::init(" << str << ')';
2447 if (!val.Help.empty())
2448 O << ", cl::desc(\"" << val.Help << "\")";
2453 // Emit the aliases (they should go after all the 'proper' options).
2454 for (std::vector<OptionDescription>::const_iterator
2455 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
2456 const OptionDescription& val = *B;
2458 O << val.GenTypeDeclaration() << ' '
2459 << val.GenVariableName()
2460 << "(\"" << val.Name << '\"';
2462 const OptionDescription& D = descs.FindOption(val.Help);
2463 O << ", cl::aliasopt(" << D.GenVariableName() << ")";
2465 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
2468 // Emit the sink option.
2470 O << (HasExterns ? "extern cl" : "cl")
2471 << "::list<std::string> " << SinkOptionName
2472 << (HasExterns ? ";\n" : "(cl::Sink);\n");
2477 /// EmitPreprocessOptionsCallback - Helper function passed to
2478 /// EmitCaseConstructHandler() by EmitPreprocessOptions().
2480 class EmitPreprocessOptionsCallback;
2483 (EmitPreprocessOptionsCallback::* EmitPreprocessOptionsCallbackHandler)
2484 (const DagInit&, unsigned, raw_ostream&) const;
2486 class EmitPreprocessOptionsCallback :
2487 public ActionHandlingCallbackBase,
2488 public HandlerTable<EmitPreprocessOptionsCallbackHandler>
2490 typedef EmitPreprocessOptionsCallbackHandler Handler;
2492 (EmitPreprocessOptionsCallback::* HandlerImpl)
2493 (const Init*, unsigned, raw_ostream&) const;
2495 const OptionDescriptions& OptDescs_;
2497 void onListOrDag(const DagInit& d, HandlerImpl h,
2498 unsigned IndentLevel, raw_ostream& O) const
2500 CheckNumberOfArguments(d, 1);
2501 const Init* I = d.getArg(0);
2503 // If I is a list, apply h to each element.
2504 if (typeid(*I) == typeid(ListInit)) {
2505 const ListInit& L = *static_cast<const ListInit*>(I);
2506 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B)
2507 ((this)->*(h))(*B, IndentLevel, O);
2509 // Otherwise, apply h to I.
2511 ((this)->*(h))(I, IndentLevel, O);
2515 void onUnsetOptionImpl(const Init* I,
2516 unsigned IndentLevel, raw_ostream& O) const
2518 const std::string& OptName = InitPtrToString(I);
2519 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2521 if (OptDesc.isSwitch()) {
2522 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = false;\n";
2524 else if (OptDesc.isParameter()) {
2525 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = \"\";\n";
2527 else if (OptDesc.isList()) {
2528 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2531 throw "Can't apply 'unset_option' to alias option '" + OptName + "'!";
2535 void onUnsetOption(const DagInit& d,
2536 unsigned IndentLevel, raw_ostream& O) const
2538 this->onListOrDag(d, &EmitPreprocessOptionsCallback::onUnsetOptionImpl,
2542 void onSetOptionImpl(const DagInit& d,
2543 unsigned IndentLevel, raw_ostream& O) const {
2544 CheckNumberOfArguments(d, 2);
2545 const std::string& OptName = InitPtrToString(d.getArg(0));
2546 const Init* Value = d.getArg(1);
2547 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2549 if (OptDesc.isList()) {
2550 const ListInit& List = InitPtrToList(Value);
2552 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2553 for (ListInit::const_iterator B = List.begin(), E = List.end();
2555 const Init* CurElem = *B;
2556 if (OptDesc.isSwitchList())
2557 CheckBooleanConstant(CurElem);
2559 O.indent(IndentLevel)
2560 << OptDesc.GenVariableName() << ".push_back(\""
2561 << (OptDesc.isSwitchList() ? CurElem->getAsString()
2562 : InitPtrToString(CurElem))
2566 else if (OptDesc.isSwitch()) {
2567 CheckBooleanConstant(Value);
2568 O.indent(IndentLevel) << OptDesc.GenVariableName()
2569 << " = " << Value->getAsString() << ";\n";
2571 else if (OptDesc.isParameter()) {
2572 const std::string& Str = InitPtrToString(Value);
2573 O.indent(IndentLevel) << OptDesc.GenVariableName()
2574 << " = \"" << Str << "\";\n";
2577 throw "Can't apply 'set_option' to alias option -" + OptName + " !";
2581 void onSetSwitch(const Init* I,
2582 unsigned IndentLevel, raw_ostream& O) const {
2583 const std::string& OptName = InitPtrToString(I);
2584 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2586 if (OptDesc.isSwitch())
2587 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = true;\n";
2589 throw "set_option: -" + OptName + " is not a switch option!";
2592 void onSetOption(const DagInit& d,
2593 unsigned IndentLevel, raw_ostream& O) const
2595 CheckNumberOfArguments(d, 1);
2597 // Two arguments: (set_option "parameter", VALUE), where VALUE can be a
2598 // boolean, a string or a string list.
2599 if (d.getNumArgs() > 1)
2600 this->onSetOptionImpl(d, IndentLevel, O);
2601 // One argument: (set_option "switch")
2602 // or (set_option ["switch1", "switch2", ...])
2604 this->onListOrDag(d, &EmitPreprocessOptionsCallback::onSetSwitch,
2610 EmitPreprocessOptionsCallback(const OptionDescriptions& OptDescs)
2611 : OptDescs_(OptDescs)
2613 if (!staticMembersInitialized_) {
2614 AddHandler("error", &EmitPreprocessOptionsCallback::onErrorDag);
2615 AddHandler("warning", &EmitPreprocessOptionsCallback::onWarningDag);
2616 AddHandler("unset_option", &EmitPreprocessOptionsCallback::onUnsetOption);
2617 AddHandler("set_option", &EmitPreprocessOptionsCallback::onSetOption);
2619 staticMembersInitialized_ = true;
2623 void operator()(const Init* I,
2624 unsigned IndentLevel, raw_ostream& O) const
2626 InvokeDagInitHandler(this, I, IndentLevel, O);
2631 /// EmitPreprocessOptions - Emit the PreprocessOptionsLocal() function.
2632 void EmitPreprocessOptions (const RecordKeeper& Records,
2633 const OptionDescriptions& OptDecs, raw_ostream& O)
2635 O << "int PreprocessOptionsLocal() {\n";
2637 const RecordVector& OptionPreprocessors =
2638 Records.getAllDerivedDefinitions("OptionPreprocessor");
2640 for (RecordVector::const_iterator B = OptionPreprocessors.begin(),
2641 E = OptionPreprocessors.end(); B!=E; ++B) {
2642 DagInit* Case = (*B)->getValueAsDag("preprocessor");
2643 EmitCaseConstructHandler(Case, Indent1,
2644 EmitPreprocessOptionsCallback(OptDecs),
2649 O.indent(Indent1) << "return 0;\n";
2653 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMapLocal() function.
2654 void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
2656 O << "int PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
2658 // Get the relevant field out of RecordKeeper
2659 const Record* LangMapRecord = Records.getDef("LanguageMap");
2661 // It is allowed for a plugin to have no language map.
2662 if (LangMapRecord) {
2664 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
2665 if (!LangsToSuffixesList)
2666 throw "Error in the language map definition!";
2668 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
2669 const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
2671 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
2672 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
2674 for (unsigned i = 0; i < Suffixes->size(); ++i)
2675 O.indent(Indent1) << "langMap[\""
2676 << InitPtrToString(Suffixes->getElement(i))
2677 << "\"] = \"" << Lang << "\";\n";
2682 O.indent(Indent1) << "return 0;\n";
2686 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
2687 /// by EmitEdgeClass().
2688 void IncDecWeight (const Init* i, unsigned IndentLevel,
2690 const DagInit& d = InitPtrToDag(i);
2691 const std::string& OpName = GetOperatorName(d);
2693 if (OpName == "inc_weight") {
2694 O.indent(IndentLevel) << "ret += ";
2696 else if (OpName == "dec_weight") {
2697 O.indent(IndentLevel) << "ret -= ";
2699 else if (OpName == "error") {
2701 CheckNumberOfArguments(d, 1);
2702 O.indent(IndentLevel) << "PrintError(\""
2703 << InitPtrToString(d.getArg(0))
2705 O.indent(IndentLevel) << "return -1;\n";
2709 throw "Unknown operator in edge properties list: '" + OpName + "'!"
2710 "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
2713 if (d.getNumArgs() > 0)
2714 O << InitPtrToInt(d.getArg(0)) << ";\n";
2720 /// EmitEdgeClass - Emit a single Edge# class.
2721 void EmitEdgeClass (unsigned N, const std::string& Target,
2722 DagInit* Case, const OptionDescriptions& OptDescs,
2725 // Class constructor.
2726 O << "class Edge" << N << ": public Edge {\n"
2728 O.indent(Indent1) << "Edge" << N << "() : Edge(\"" << Target
2731 // Function Weight().
2733 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n";
2734 O.indent(Indent2) << "unsigned ret = 0;\n";
2736 // Handle the 'case' construct.
2737 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
2739 O.indent(Indent2) << "return ret;\n";
2740 O.indent(Indent1) << "}\n\n};\n\n";
2743 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
2744 void EmitEdgeClasses (const RecordVector& EdgeVector,
2745 const OptionDescriptions& OptDescs,
2748 for (RecordVector::const_iterator B = EdgeVector.begin(),
2749 E = EdgeVector.end(); B != E; ++B) {
2750 const Record* Edge = *B;
2751 const std::string& NodeB = Edge->getValueAsString("b");
2752 DagInit& Weight = *Edge->getValueAsDag("weight");
2754 if (!IsDagEmpty(Weight))
2755 EmitEdgeClass(i, NodeB, &Weight, OptDescs, O);
2760 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraphLocal()
2762 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
2763 const ToolDescriptions& ToolDescs,
2766 O << "int PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
2768 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2769 E = ToolDescs.end(); B != E; ++B)
2770 O.indent(Indent1) << "G.insertNode(new " << (*B)->Name << "());\n";
2777 for (RecordVector::const_iterator B = EdgeVector.begin(),
2778 E = EdgeVector.end(); B != E; ++B) {
2779 const Record* Edge = *B;
2780 const std::string& NodeA = Edge->getValueAsString("a");
2781 const std::string& NodeB = Edge->getValueAsString("b");
2782 DagInit& Weight = *Edge->getValueAsDag("weight");
2784 O.indent(Indent1) << "if (int ret = G.insertEdge(\"" << NodeA << "\", ";
2786 if (IsDagEmpty(Weight))
2787 O << "new SimpleEdge(\"" << NodeB << "\")";
2789 O << "new Edge" << i << "()";
2792 O.indent(Indent2) << "return ret;\n";
2798 O.indent(Indent1) << "return 0;\n";
2802 /// HookInfo - Information about the hook type and number of arguments.
2805 // A hook can either have a single parameter of type std::vector<std::string>,
2806 // or NumArgs parameters of type const char*.
2807 enum HookType { ListHook, ArgHook };
2812 HookInfo() : Type(ArgHook), NumArgs(1)
2815 HookInfo(HookType T) : Type(T), NumArgs(1)
2818 HookInfo(unsigned N) : Type(ArgHook), NumArgs(N)
2822 typedef llvm::StringMap<HookInfo> HookInfoMap;
2824 /// ExtractHookNames - Extract the hook names from all instances of
2825 /// $CALL(HookName) in the provided command line string/action. Helper
2826 /// function used by FillInHookNames().
2827 class ExtractHookNames {
2828 HookInfoMap& HookNames_;
2829 const OptionDescriptions& OptDescs_;
2831 ExtractHookNames(HookInfoMap& HookNames, const OptionDescriptions& OptDescs)
2832 : HookNames_(HookNames), OptDescs_(OptDescs)
2835 void onAction (const DagInit& Dag) {
2836 const std::string& Name = GetOperatorName(Dag);
2838 if (Name == "forward_transformed_value") {
2839 CheckNumberOfArguments(Dag, 2);
2840 const std::string& OptName = InitPtrToString(Dag.getArg(0));
2841 const std::string& HookName = InitPtrToString(Dag.getArg(1));
2842 const OptionDescription& D =
2843 OptDescs_.FindParameterListOrParameter(OptName);
2845 HookNames_[HookName] = HookInfo(D.isList() ? HookInfo::ListHook
2846 : HookInfo::ArgHook);
2848 else if (Name == "append_cmd" || Name == "output_suffix") {
2849 CheckNumberOfArguments(Dag, 1);
2850 this->onCmdLine(InitPtrToString(Dag.getArg(0)));
2854 void onCmdLine(const std::string& Cmd) {
2856 TokenizeCmdLine(Cmd, cmds);
2858 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
2860 const std::string& cmd = *B;
2862 if (cmd == "$CALL") {
2863 unsigned NumArgs = 0;
2864 CheckedIncrement(B, E, "Syntax error in $CALL invocation!");
2865 const std::string& HookName = *B;
2867 if (HookName.at(0) == ')')
2868 throw "$CALL invoked with no arguments!";
2870 while (++B != E && B->at(0) != ')') {
2874 HookInfoMap::const_iterator H = HookNames_.find(HookName);
2876 if (H != HookNames_.end() && H->second.NumArgs != NumArgs &&
2877 H->second.Type != HookInfo::ArgHook)
2878 throw "Overloading of hooks is not allowed. Overloaded hook: "
2881 HookNames_[HookName] = HookInfo(NumArgs);
2886 void operator()(const Init* Arg) {
2888 // We're invoked on an action (either a dag or a dag list).
2889 if (typeid(*Arg) == typeid(DagInit)) {
2890 const DagInit& Dag = InitPtrToDag(Arg);
2891 this->onAction(Dag);
2894 else if (typeid(*Arg) == typeid(ListInit)) {
2895 const ListInit& List = InitPtrToList(Arg);
2896 for (ListInit::const_iterator B = List.begin(), E = List.end(); B != E;
2898 const DagInit& Dag = InitPtrToDag(*B);
2899 this->onAction(Dag);
2904 // We're invoked on a command line.
2905 this->onCmdLine(InitPtrToString(Arg));
2908 void operator()(const DagInit* Test, unsigned, bool) {
2909 this->operator()(Test);
2911 void operator()(const Init* Statement, unsigned) {
2912 this->operator()(Statement);
2916 /// FillInHookNames - Actually extract the hook names from all command
2917 /// line strings. Helper function used by EmitHookDeclarations().
2918 void FillInHookNames(const ToolDescriptions& ToolDescs,
2919 const OptionDescriptions& OptDescs,
2920 HookInfoMap& HookNames)
2922 // For all tool descriptions:
2923 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2924 E = ToolDescs.end(); B != E; ++B) {
2925 const ToolDescription& D = *(*B);
2927 // Look for 'forward_transformed_value' in 'actions'.
2929 WalkCase(D.Actions, Id(), ExtractHookNames(HookNames, OptDescs));
2931 // Look for hook invocations in 'cmd_line'.
2934 if (dynamic_cast<StringInit*>(D.CmdLine))
2935 // This is a string.
2936 ExtractHookNames(HookNames, OptDescs).operator()(D.CmdLine);
2938 // This is a 'case' construct.
2939 WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames, OptDescs));
2943 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
2944 /// property records and emit hook function declaration for each
2945 /// instance of $CALL(HookName).
2946 void EmitHookDeclarations(const ToolDescriptions& ToolDescs,
2947 const OptionDescriptions& OptDescs, raw_ostream& O) {
2948 HookInfoMap HookNames;
2950 FillInHookNames(ToolDescs, OptDescs, HookNames);
2951 if (HookNames.empty())
2954 O << "namespace hooks {\n";
2955 for (HookInfoMap::const_iterator B = HookNames.begin(),
2956 E = HookNames.end(); B != E; ++B) {
2957 const char* HookName = B->first();
2958 const HookInfo& Info = B->second;
2960 O.indent(Indent1) << "std::string " << HookName << "(";
2962 if (Info.Type == HookInfo::ArgHook) {
2963 for (unsigned i = 0, j = Info.NumArgs; i < j; ++i) {
2964 O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
2968 O << "const std::vector<std::string>& Arg";
2976 /// EmitRegisterPlugin - Emit code to register this plugin.
2977 void EmitRegisterPlugin(int Priority, raw_ostream& O) {
2978 O << "struct Plugin : public llvmc::BasePlugin {\n\n";
2979 O.indent(Indent1) << "int Priority() const { return "
2980 << Priority << "; }\n\n";
2981 O.indent(Indent1) << "int PreprocessOptions() const\n";
2982 O.indent(Indent1) << "{ return PreprocessOptionsLocal(); }\n\n";
2983 O.indent(Indent1) << "int PopulateLanguageMap(LanguageMap& langMap) const\n";
2984 O.indent(Indent1) << "{ return PopulateLanguageMapLocal(langMap); }\n\n";
2986 << "int PopulateCompilationGraph(CompilationGraph& graph) const\n";
2987 O.indent(Indent1) << "{ return PopulateCompilationGraphLocal(graph); }\n"
2989 << "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
2992 /// EmitIncludes - Emit necessary #include directives and some
2993 /// additional declarations.
2994 void EmitIncludes(raw_ostream& O) {
2995 O << "#include \"llvm/CompilerDriver/BuiltinOptions.h\"\n"
2996 << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
2997 << "#include \"llvm/CompilerDriver/Error.h\"\n"
2998 << "#include \"llvm/CompilerDriver/ForceLinkageMacros.h\"\n"
2999 << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
3000 << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
3002 << "#include \"llvm/Support/CommandLine.h\"\n"
3003 << "#include \"llvm/Support/raw_ostream.h\"\n\n"
3005 << "#include <algorithm>\n"
3006 << "#include <cstdlib>\n"
3007 << "#include <iterator>\n"
3008 << "#include <stdexcept>\n\n"
3010 << "using namespace llvm;\n"
3011 << "using namespace llvmc;\n\n"
3013 << "extern cl::opt<std::string> OutputFilename;\n\n"
3015 << "inline const char* checkCString(const char* s)\n"
3016 << "{ return s == NULL ? \"\" : s; }\n\n";
3020 /// PluginData - Holds all information about a plugin.
3022 OptionDescriptions OptDescs;
3025 ToolDescriptions ToolDescs;
3030 /// HasSink - Go through the list of tool descriptions and check if
3031 /// there are any with the 'sink' property set.
3032 bool HasSink(const ToolDescriptions& ToolDescs) {
3033 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
3034 E = ToolDescs.end(); B != E; ++B)
3041 /// HasExterns - Go through the list of option descriptions and check
3042 /// if there are any external options.
3043 bool HasExterns(const OptionDescriptions& OptDescs) {
3044 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
3045 E = OptDescs.end(); B != E; ++B)
3046 if (B->second.isExtern())
3052 /// CollectPluginData - Collect tool and option properties,
3053 /// compilation graph edges and plugin priority from the parse tree.
3054 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
3055 // Collect option properties.
3056 const RecordVector& OptionLists =
3057 Records.getAllDerivedDefinitions("OptionList");
3058 CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
3061 // Collect tool properties.
3062 const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
3063 CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
3064 Data.HasSink = HasSink(Data.ToolDescs);
3065 Data.HasExterns = HasExterns(Data.OptDescs);
3067 // Collect compilation graph edges.
3068 const RecordVector& CompilationGraphs =
3069 Records.getAllDerivedDefinitions("CompilationGraph");
3070 FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
3073 // Calculate the priority of this plugin.
3074 const RecordVector& Priorities =
3075 Records.getAllDerivedDefinitions("PluginPriority");
3076 Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
3079 /// CheckPluginData - Perform some sanity checks on the collected data.
3080 void CheckPluginData(PluginData& Data) {
3081 // Filter out all tools not mentioned in the compilation graph.
3082 FilterNotInGraph(Data.Edges, Data.ToolDescs);
3084 // Typecheck the compilation graph.
3085 TypecheckGraph(Data.Edges, Data.ToolDescs);
3087 // Check that there are no options without side effects (specified
3088 // only in the OptionList).
3089 CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
3092 void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
3093 // Emit file header.
3096 // Emit global option registration code.
3097 EmitOptionDefinitions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
3099 // Emit hook declarations.
3100 EmitHookDeclarations(Data.ToolDescs, Data.OptDescs, O);
3102 O << "namespace {\n\n";
3104 // Emit PreprocessOptionsLocal() function.
3105 EmitPreprocessOptions(Records, Data.OptDescs, O);
3107 // Emit PopulateLanguageMapLocal() function
3108 // (language map maps from file extensions to language names).
3109 EmitPopulateLanguageMap(Records, O);
3111 // Emit Tool classes.
3112 for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
3113 E = Data.ToolDescs.end(); B!=E; ++B)
3114 EmitToolClassDefinition(*(*B), Data.OptDescs, O);
3116 // Emit Edge# classes.
3117 EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
3119 // Emit PopulateCompilationGraphLocal() function.
3120 EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
3122 // Emit code for plugin registration.
3123 EmitRegisterPlugin(Data.Priority, O);
3125 O << "} // End anonymous namespace.\n\n";
3127 // Force linkage magic.
3128 O << "namespace llvmc {\n";
3129 O << "LLVMC_FORCE_LINKAGE_DECL(LLVMC_PLUGIN_NAME) {}\n";
3136 // End of anonymous namespace
3139 /// run - The back-end entry point.
3140 void LLVMCConfigurationEmitter::run (raw_ostream &O) {
3144 CollectPluginData(Records, Data);
3145 CheckPluginData(Data);
3147 this->EmitSourceFileHeader("LLVMC Configuration Library", O);
3148 EmitPluginCode(Data, O);
3150 } catch (std::exception& Error) {
3151 throw Error.what() + std::string(" - usually this means a syntax error.");