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/SmallVector.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringSet.h"
32 //===----------------------------------------------------------------------===//
35 typedef std::vector<Record*> RecordVector;
36 typedef std::vector<std::string> StrVector;
38 //===----------------------------------------------------------------------===//
42 static const unsigned TabWidth = 4;
43 static const unsigned Indent1 = TabWidth*1;
44 static const unsigned Indent2 = TabWidth*2;
45 static const unsigned Indent3 = TabWidth*3;
47 // Default help string.
48 static const char * const DefaultHelpString = "NO HELP MESSAGE PROVIDED";
50 // Name for the "sink" option.
51 static const char * const SinkOptionName = "AutoGeneratedSinkOption";
55 //===----------------------------------------------------------------------===//
58 /// Id - An 'identity' function object.
61 void operator()(const T0&) const {
63 template<typename T0, typename T1>
64 void operator()(const T0&, const T1&) const {
66 template<typename T0, typename T1, typename T2>
67 void operator()(const T0&, const T1&, const T2&) const {
71 int InitPtrToInt(const Init* ptr) {
72 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
73 return val.getValue();
76 const std::string& InitPtrToString(const Init* ptr) {
77 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
78 return val.getValue();
81 const ListInit& InitPtrToList(const Init* ptr) {
82 const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
86 const DagInit& InitPtrToDag(const Init* ptr) {
87 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
91 const std::string GetOperatorName(const DagInit* D) {
92 return D->getOperator()->getAsString();
95 const std::string GetOperatorName(const DagInit& D) {
96 return GetOperatorName(&D);
99 // checkNumberOfArguments - Ensure that the number of args in d is
100 // greater than or equal to min_arguments, otherwise throw an exception.
101 void checkNumberOfArguments (const DagInit* d, unsigned minArgs) {
102 if (!d || d->getNumArgs() < minArgs)
103 throw GetOperatorName(d) + ": too few arguments!";
105 void checkNumberOfArguments (const DagInit& d, unsigned minArgs) {
106 checkNumberOfArguments(&d, minArgs);
109 // isDagEmpty - is this DAG marked with an empty marker?
110 bool isDagEmpty (const DagInit* d) {
111 return GetOperatorName(d) == "empty_dag_marker";
114 // EscapeVariableName - Escape commas and other symbols not allowed
115 // in the C++ variable names. Makes it possible to use options named
116 // like "Wa," (useful for prefix options).
117 std::string EscapeVariableName(const std::string& Var) {
119 for (unsigned i = 0; i != Var.size(); ++i) {
120 char cur_char = Var[i];
121 if (cur_char == ',') {
124 else if (cur_char == '+') {
127 else if (cur_char == '-') {
131 ret.push_back(cur_char);
137 /// oneOf - Does the input string contain this character?
138 bool oneOf(const char* lst, char c) {
146 template <class I, class S>
147 void checkedIncrement(I& P, I E, S ErrorString) {
153 // apply is needed because C++'s syntax doesn't let us construct a function
154 // object and call it in the same statement.
155 template<typename F, typename T0>
156 void apply(F Fun, T0& Arg0) {
160 template<typename F, typename T0, typename T1>
161 void apply(F Fun, T0& Arg0, T1& Arg1) {
162 return Fun(Arg0, Arg1);
165 //===----------------------------------------------------------------------===//
166 /// Back-end specific code
169 /// OptionType - One of six different option types. See the
170 /// documentation for detailed description of differences.
171 namespace OptionType {
173 enum OptionType { Alias, Switch, Parameter, ParameterList,
176 bool IsAlias(OptionType t) {
180 bool IsList (OptionType t) {
181 return (t == ParameterList || t == PrefixList);
184 bool IsSwitch (OptionType t) {
185 return (t == Switch);
188 bool IsParameter (OptionType t) {
189 return (t == Parameter || t == Prefix);
194 OptionType::OptionType stringToOptionType(const std::string& T) {
195 if (T == "alias_option")
196 return OptionType::Alias;
197 else if (T == "switch_option")
198 return OptionType::Switch;
199 else if (T == "parameter_option")
200 return OptionType::Parameter;
201 else if (T == "parameter_list_option")
202 return OptionType::ParameterList;
203 else if (T == "prefix_option")
204 return OptionType::Prefix;
205 else if (T == "prefix_list_option")
206 return OptionType::PrefixList;
208 throw "Unknown option type: " + T + '!';
211 namespace OptionDescriptionFlags {
212 enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
213 ReallyHidden = 0x4, Extern = 0x8,
214 OneOrMore = 0x10, ZeroOrOne = 0x20,
215 CommaSeparated = 0x40 };
218 /// OptionDescription - Represents data contained in a single
219 /// OptionList entry.
220 struct OptionDescription {
221 OptionType::OptionType Type;
228 OptionDescription(OptionType::OptionType t = OptionType::Switch,
229 const std::string& n = "",
230 const std::string& h = DefaultHelpString)
231 : Type(t), Name(n), Flags(0x0), Help(h), MultiVal(1), InitVal(0)
234 /// GenTypeDeclaration - Returns the C++ variable type of this
236 const char* GenTypeDeclaration() const;
238 /// GenVariableName - Returns the variable name used in the
239 /// generated C++ code.
240 std::string GenVariableName() const;
242 /// Merge - Merge two option descriptions.
243 void Merge (const OptionDescription& other);
245 // Misc convenient getters/setters.
247 bool isAlias() const;
249 bool isMultiVal() const;
251 bool isCommaSeparated() const;
252 void setCommaSeparated();
254 bool isExtern() const;
257 bool isRequired() const;
260 bool isOneOrMore() const;
263 bool isZeroOrOne() const;
266 bool isHidden() const;
269 bool isReallyHidden() const;
270 void setReallyHidden();
272 bool isSwitch() const
273 { return OptionType::IsSwitch(this->Type); }
275 bool isParameter() const
276 { return OptionType::IsParameter(this->Type); }
279 { return OptionType::IsList(this->Type); }
283 void OptionDescription::Merge (const OptionDescription& other)
285 if (other.Type != Type)
286 throw "Conflicting definitions for the option " + Name + "!";
288 if (Help == other.Help || Help == DefaultHelpString)
290 else if (other.Help != DefaultHelpString) {
291 llvm::errs() << "Warning: several different help strings"
292 " defined for option " + Name + "\n";
295 Flags |= other.Flags;
298 bool OptionDescription::isAlias() const {
299 return OptionType::IsAlias(this->Type);
302 bool OptionDescription::isMultiVal() const {
306 bool OptionDescription::isCommaSeparated() const {
307 return Flags & OptionDescriptionFlags::CommaSeparated;
309 void OptionDescription::setCommaSeparated() {
310 Flags |= OptionDescriptionFlags::CommaSeparated;
313 bool OptionDescription::isExtern() const {
314 return Flags & OptionDescriptionFlags::Extern;
316 void OptionDescription::setExtern() {
317 Flags |= OptionDescriptionFlags::Extern;
320 bool OptionDescription::isRequired() const {
321 return Flags & OptionDescriptionFlags::Required;
323 void OptionDescription::setRequired() {
324 Flags |= OptionDescriptionFlags::Required;
327 bool OptionDescription::isOneOrMore() const {
328 return Flags & OptionDescriptionFlags::OneOrMore;
330 void OptionDescription::setOneOrMore() {
331 Flags |= OptionDescriptionFlags::OneOrMore;
334 bool OptionDescription::isZeroOrOne() const {
335 return Flags & OptionDescriptionFlags::ZeroOrOne;
337 void OptionDescription::setZeroOrOne() {
338 Flags |= OptionDescriptionFlags::ZeroOrOne;
341 bool OptionDescription::isHidden() const {
342 return Flags & OptionDescriptionFlags::Hidden;
344 void OptionDescription::setHidden() {
345 Flags |= OptionDescriptionFlags::Hidden;
348 bool OptionDescription::isReallyHidden() const {
349 return Flags & OptionDescriptionFlags::ReallyHidden;
351 void OptionDescription::setReallyHidden() {
352 Flags |= OptionDescriptionFlags::ReallyHidden;
355 const char* OptionDescription::GenTypeDeclaration() const {
357 case OptionType::Alias:
359 case OptionType::PrefixList:
360 case OptionType::ParameterList:
361 return "cl::list<std::string>";
362 case OptionType::Switch:
363 return "cl::opt<bool>";
364 case OptionType::Parameter:
365 case OptionType::Prefix:
367 return "cl::opt<std::string>";
371 std::string OptionDescription::GenVariableName() const {
372 const std::string& EscapedName = EscapeVariableName(Name);
374 case OptionType::Alias:
375 return "AutoGeneratedAlias_" + EscapedName;
376 case OptionType::PrefixList:
377 case OptionType::ParameterList:
378 return "AutoGeneratedList_" + EscapedName;
379 case OptionType::Switch:
380 return "AutoGeneratedSwitch_" + EscapedName;
381 case OptionType::Prefix:
382 case OptionType::Parameter:
384 return "AutoGeneratedParameter_" + EscapedName;
388 /// OptionDescriptions - An OptionDescription array plus some helper
390 class OptionDescriptions {
391 typedef StringMap<OptionDescription> container_type;
393 /// Descriptions - A list of OptionDescriptions.
394 container_type Descriptions;
397 /// FindOption - exception-throwing wrapper for find().
398 const OptionDescription& FindOption(const std::string& OptName) const;
400 // Wrappers for FindOption that throw an exception in case the option has a
402 const OptionDescription& FindSwitch(const std::string& OptName) const;
403 const OptionDescription& FindParameter(const std::string& OptName) const;
404 const OptionDescription& FindList(const std::string& OptName) const;
405 const OptionDescription&
406 FindListOrParameter(const std::string& OptName) const;
408 /// insertDescription - Insert new OptionDescription into
409 /// OptionDescriptions list
410 void InsertDescription (const OptionDescription& o);
412 // Support for STL-style iteration
413 typedef container_type::const_iterator const_iterator;
414 const_iterator begin() const { return Descriptions.begin(); }
415 const_iterator end() const { return Descriptions.end(); }
418 const OptionDescription&
419 OptionDescriptions::FindOption(const std::string& OptName) const {
420 const_iterator I = Descriptions.find(OptName);
421 if (I != Descriptions.end())
424 throw OptName + ": no such option!";
427 const OptionDescription&
428 OptionDescriptions::FindSwitch(const std::string& OptName) const {
429 const OptionDescription& OptDesc = this->FindOption(OptName);
430 if (!OptDesc.isSwitch())
431 throw OptName + ": incorrect option type - should be a switch!";
435 const OptionDescription&
436 OptionDescriptions::FindList(const std::string& OptName) const {
437 const OptionDescription& OptDesc = this->FindOption(OptName);
438 if (!OptDesc.isList())
439 throw OptName + ": incorrect option type - should be a list!";
443 const OptionDescription&
444 OptionDescriptions::FindParameter(const std::string& OptName) const {
445 const OptionDescription& OptDesc = this->FindOption(OptName);
446 if (!OptDesc.isParameter())
447 throw OptName + ": incorrect option type - should be a parameter!";
451 const OptionDescription&
452 OptionDescriptions::FindListOrParameter(const std::string& OptName) const {
453 const OptionDescription& OptDesc = this->FindOption(OptName);
454 if (!OptDesc.isList() && !OptDesc.isParameter())
456 + ": incorrect option type - should be a list or parameter!";
460 void OptionDescriptions::InsertDescription (const OptionDescription& o) {
461 container_type::iterator I = Descriptions.find(o.Name);
462 if (I != Descriptions.end()) {
463 OptionDescription& D = I->second;
467 Descriptions[o.Name] = o;
471 /// HandlerTable - A base class for function objects implemented as
472 /// 'tables of handlers'.
473 template <typename Handler>
476 // Implementation details.
478 /// HandlerMap - A map from property names to property handlers
479 typedef StringMap<Handler> HandlerMap;
481 static HandlerMap Handlers_;
482 static bool staticMembersInitialized_;
486 Handler GetHandler (const std::string& HandlerName) const {
487 typename HandlerMap::iterator method = Handlers_.find(HandlerName);
489 if (method != Handlers_.end()) {
490 Handler h = method->second;
494 throw "No handler found for property " + HandlerName + "!";
498 void AddHandler(const char* Property, Handler H) {
499 Handlers_[Property] = H;
504 template <class FunctionObject>
505 void InvokeDagInitHandler(FunctionObject* Obj, Init* i) {
506 typedef void (FunctionObject::*Handler) (const DagInit*);
508 const DagInit& property = InitPtrToDag(i);
509 const std::string& property_name = GetOperatorName(property);
510 Handler h = Obj->GetHandler(property_name);
512 ((Obj)->*(h))(&property);
515 template <typename H>
516 typename HandlerTable<H>::HandlerMap HandlerTable<H>::Handlers_;
518 template <typename H>
519 bool HandlerTable<H>::staticMembersInitialized_ = false;
522 /// CollectOptionProperties - Function object for iterating over an
523 /// option property list.
524 class CollectOptionProperties;
525 typedef void (CollectOptionProperties::* CollectOptionPropertiesHandler)
528 class CollectOptionProperties
529 : public HandlerTable<CollectOptionPropertiesHandler>
533 /// optDescs_ - OptionDescriptions table. This is where the
534 /// information is stored.
535 OptionDescription& optDesc_;
539 explicit CollectOptionProperties(OptionDescription& OD)
542 if (!staticMembersInitialized_) {
543 AddHandler("extern", &CollectOptionProperties::onExtern);
544 AddHandler("help", &CollectOptionProperties::onHelp);
545 AddHandler("hidden", &CollectOptionProperties::onHidden);
546 AddHandler("init", &CollectOptionProperties::onInit);
547 AddHandler("multi_val", &CollectOptionProperties::onMultiVal);
548 AddHandler("one_or_more", &CollectOptionProperties::onOneOrMore);
549 AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
550 AddHandler("required", &CollectOptionProperties::onRequired);
551 AddHandler("zero_or_one", &CollectOptionProperties::onZeroOrOne);
552 AddHandler("comma_separated", &CollectOptionProperties::onCommaSeparated);
554 staticMembersInitialized_ = true;
558 /// operator() - Just forwards to the corresponding property
560 void operator() (Init* i) {
561 InvokeDagInitHandler(this, i);
566 /// Option property handlers --
567 /// Methods that handle option properties such as (help) or (hidden).
569 void onExtern (const DagInit* d) {
570 checkNumberOfArguments(d, 0);
571 optDesc_.setExtern();
574 void onHelp (const DagInit* d) {
575 checkNumberOfArguments(d, 1);
576 optDesc_.Help = InitPtrToString(d->getArg(0));
579 void onHidden (const DagInit* d) {
580 checkNumberOfArguments(d, 0);
581 optDesc_.setHidden();
584 void onReallyHidden (const DagInit* d) {
585 checkNumberOfArguments(d, 0);
586 optDesc_.setReallyHidden();
589 void onCommaSeparated (const DagInit* d) {
590 checkNumberOfArguments(d, 0);
591 if (!optDesc_.isList())
592 throw "'comma_separated' is valid only on list options!";
593 optDesc_.setCommaSeparated();
596 void onRequired (const DagInit* d) {
597 checkNumberOfArguments(d, 0);
598 if (optDesc_.isOneOrMore() || optDesc_.isZeroOrOne())
599 throw "Only one of (required), (zero_or_one) or "
600 "(one_or_more) properties is allowed!";
601 optDesc_.setRequired();
604 void onInit (const DagInit* d) {
605 checkNumberOfArguments(d, 1);
606 Init* i = d->getArg(0);
607 const std::string& str = i->getAsString();
609 bool correct = optDesc_.isParameter() && dynamic_cast<StringInit*>(i);
610 correct |= (optDesc_.isSwitch() && (str == "true" || str == "false"));
613 throw "Incorrect usage of the 'init' option property!";
615 optDesc_.InitVal = i;
618 void onOneOrMore (const DagInit* d) {
619 checkNumberOfArguments(d, 0);
620 if (optDesc_.isRequired() || optDesc_.isZeroOrOne())
621 throw "Only one of (required), (zero_or_one) or "
622 "(one_or_more) properties is allowed!";
623 if (!OptionType::IsList(optDesc_.Type))
624 llvm::errs() << "Warning: specifying the 'one_or_more' property "
625 "on a non-list option will have no effect.\n";
626 optDesc_.setOneOrMore();
629 void onZeroOrOne (const DagInit* d) {
630 checkNumberOfArguments(d, 0);
631 if (optDesc_.isRequired() || optDesc_.isOneOrMore())
632 throw "Only one of (required), (zero_or_one) or "
633 "(one_or_more) properties is allowed!";
634 if (!OptionType::IsList(optDesc_.Type))
635 llvm::errs() << "Warning: specifying the 'zero_or_one' property"
636 "on a non-list option will have no effect.\n";
637 optDesc_.setZeroOrOne();
640 void onMultiVal (const DagInit* d) {
641 checkNumberOfArguments(d, 1);
642 int val = InitPtrToInt(d->getArg(0));
644 throw "Error in the 'multi_val' property: "
645 "the value must be greater than 1!";
646 if (!OptionType::IsList(optDesc_.Type))
647 throw "The multi_val property is valid only on list options!";
648 optDesc_.MultiVal = val;
653 /// AddOption - A function object that is applied to every option
654 /// description. Used by CollectOptionDescriptions.
657 OptionDescriptions& OptDescs_;
660 explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
663 void operator()(const Init* i) {
664 const DagInit& d = InitPtrToDag(i);
665 checkNumberOfArguments(&d, 1);
667 const OptionType::OptionType Type =
668 stringToOptionType(GetOperatorName(d));
669 const std::string& Name = InitPtrToString(d.getArg(0));
671 OptionDescription OD(Type, Name);
674 checkNumberOfArguments(&d, 2);
677 // Aliases store the aliased option name in the 'Help' field.
678 OD.Help = InitPtrToString(d.getArg(1));
680 else if (!OD.isExtern()) {
681 processOptionProperties(&d, OD);
683 OptDescs_.InsertDescription(OD);
687 /// processOptionProperties - Go through the list of option
688 /// properties and call a corresponding handler for each.
689 static void processOptionProperties (const DagInit* d, OptionDescription& o) {
690 checkNumberOfArguments(d, 2);
691 DagInit::const_arg_iterator B = d->arg_begin();
692 // Skip the first argument: it's always the option name.
694 std::for_each(B, d->arg_end(), CollectOptionProperties(o));
699 /// CollectOptionDescriptions - Collects option properties from all
701 void CollectOptionDescriptions (RecordVector::const_iterator B,
702 RecordVector::const_iterator E,
703 OptionDescriptions& OptDescs)
705 // For every OptionList:
707 RecordVector::value_type T = *B;
708 // Throws an exception if the value does not exist.
709 ListInit* PropList = T->getValueAsListInit("options");
711 // For every option description in this list:
712 // collect the information and
713 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
717 // Tool information record
719 namespace ToolFlags {
720 enum ToolFlags { Join = 0x1, Sink = 0x2 };
723 struct ToolDescription : public RefCountedBase<ToolDescription> {
727 StrVector InLanguage;
728 std::string OutLanguage;
729 std::string OutputSuffix;
732 // Various boolean properties
733 void setSink() { Flags |= ToolFlags::Sink; }
734 bool isSink() const { return Flags & ToolFlags::Sink; }
735 void setJoin() { Flags |= ToolFlags::Join; }
736 bool isJoin() const { return Flags & ToolFlags::Join; }
738 // Default ctor here is needed because StringMap can only store
739 // DefaultConstructible objects
740 ToolDescription() : CmdLine(0), Actions(0), Flags(0) {}
741 ToolDescription (const std::string& n)
742 : Name(n), CmdLine(0), Actions(0), Flags(0)
746 /// ToolDescriptions - A list of Tool information records.
747 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
750 /// CollectToolProperties - Function object for iterating over a list of
751 /// tool property records.
753 class CollectToolProperties;
754 typedef void (CollectToolProperties::* CollectToolPropertiesHandler)
757 class CollectToolProperties : public HandlerTable<CollectToolPropertiesHandler>
761 /// toolDesc_ - Properties of the current Tool. This is where the
762 /// information is stored.
763 ToolDescription& toolDesc_;
767 explicit CollectToolProperties (ToolDescription& d)
770 if (!staticMembersInitialized_) {
772 AddHandler("actions", &CollectToolProperties::onActions);
773 AddHandler("cmd_line", &CollectToolProperties::onCmdLine);
774 AddHandler("in_language", &CollectToolProperties::onInLanguage);
775 AddHandler("join", &CollectToolProperties::onJoin);
776 AddHandler("out_language", &CollectToolProperties::onOutLanguage);
777 AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
778 AddHandler("sink", &CollectToolProperties::onSink);
780 staticMembersInitialized_ = true;
784 void operator() (Init* i) {
785 InvokeDagInitHandler(this, i);
790 /// Property handlers --
791 /// Functions that extract information about tool properties from
792 /// DAG representation.
794 void onActions (const DagInit* d) {
795 checkNumberOfArguments(d, 1);
796 Init* Case = d->getArg(0);
797 if (typeid(*Case) != typeid(DagInit) ||
798 GetOperatorName(static_cast<DagInit*>(Case)) != "case")
799 throw "The argument to (actions) should be a 'case' construct!";
800 toolDesc_.Actions = Case;
803 void onCmdLine (const DagInit* d) {
804 checkNumberOfArguments(d, 1);
805 toolDesc_.CmdLine = d->getArg(0);
808 void onInLanguage (const DagInit* d) {
809 checkNumberOfArguments(d, 1);
810 Init* arg = d->getArg(0);
812 // Find out the argument's type.
813 if (typeid(*arg) == typeid(StringInit)) {
815 toolDesc_.InLanguage.push_back(InitPtrToString(arg));
819 const ListInit& lst = InitPtrToList(arg);
820 StrVector& out = toolDesc_.InLanguage;
822 // Copy strings to the output vector.
823 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
825 out.push_back(InitPtrToString(*B));
828 // Remove duplicates.
829 std::sort(out.begin(), out.end());
830 StrVector::iterator newE = std::unique(out.begin(), out.end());
831 out.erase(newE, out.end());
835 void onJoin (const DagInit* d) {
836 checkNumberOfArguments(d, 0);
840 void onOutLanguage (const DagInit* d) {
841 checkNumberOfArguments(d, 1);
842 toolDesc_.OutLanguage = InitPtrToString(d->getArg(0));
845 void onOutputSuffix (const DagInit* d) {
846 checkNumberOfArguments(d, 1);
847 toolDesc_.OutputSuffix = InitPtrToString(d->getArg(0));
850 void onSink (const DagInit* d) {
851 checkNumberOfArguments(d, 0);
857 /// CollectToolDescriptions - Gather information about tool properties
858 /// from the parsed TableGen data (basically a wrapper for the
859 /// CollectToolProperties function object).
860 void CollectToolDescriptions (RecordVector::const_iterator B,
861 RecordVector::const_iterator E,
862 ToolDescriptions& ToolDescs)
864 // Iterate over a properties list of every Tool definition
866 const Record* T = *B;
867 // Throws an exception if the value does not exist.
868 ListInit* PropList = T->getValueAsListInit("properties");
870 IntrusiveRefCntPtr<ToolDescription>
871 ToolDesc(new ToolDescription(T->getName()));
873 std::for_each(PropList->begin(), PropList->end(),
874 CollectToolProperties(*ToolDesc));
875 ToolDescs.push_back(ToolDesc);
879 /// FillInEdgeVector - Merge all compilation graph definitions into
880 /// one single edge list.
881 void FillInEdgeVector(RecordVector::const_iterator B,
882 RecordVector::const_iterator E, RecordVector& Out) {
883 for (; B != E; ++B) {
884 const ListInit* edges = (*B)->getValueAsListInit("edges");
886 for (unsigned i = 0; i < edges->size(); ++i)
887 Out.push_back(edges->getElementAsRecord(i));
891 /// CalculatePriority - Calculate the priority of this plugin.
892 int CalculatePriority(RecordVector::const_iterator B,
893 RecordVector::const_iterator E) {
897 priority = static_cast<int>((*B)->getValueAsInt("priority"));
900 throw "More than one 'PluginPriority' instance found: "
901 "most probably an error!";
907 /// NotInGraph - Helper function object for FilterNotInGraph.
910 const llvm::StringSet<>& ToolsInGraph_;
913 NotInGraph(const llvm::StringSet<>& ToolsInGraph)
914 : ToolsInGraph_(ToolsInGraph)
917 bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
918 return (ToolsInGraph_.count(x->Name) == 0);
922 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
923 /// mentioned in the compilation graph definition.
924 void FilterNotInGraph (const RecordVector& EdgeVector,
925 ToolDescriptions& ToolDescs) {
927 // List all tools mentioned in the graph.
928 llvm::StringSet<> ToolsInGraph;
930 for (RecordVector::const_iterator B = EdgeVector.begin(),
931 E = EdgeVector.end(); B != E; ++B) {
933 const Record* Edge = *B;
934 const std::string& NodeA = Edge->getValueAsString("a");
935 const std::string& NodeB = Edge->getValueAsString("b");
938 ToolsInGraph.insert(NodeA);
939 ToolsInGraph.insert(NodeB);
942 // Filter ToolPropertiesList.
943 ToolDescriptions::iterator new_end =
944 std::remove_if(ToolDescs.begin(), ToolDescs.end(),
945 NotInGraph(ToolsInGraph));
946 ToolDescs.erase(new_end, ToolDescs.end());
949 /// FillInToolToLang - Fills in two tables that map tool names to
950 /// (input, output) languages. Helper function used by TypecheckGraph().
951 void FillInToolToLang (const ToolDescriptions& ToolDescs,
952 StringMap<StringSet<> >& ToolToInLang,
953 StringMap<std::string>& ToolToOutLang) {
954 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
955 E = ToolDescs.end(); B != E; ++B) {
956 const ToolDescription& D = *(*B);
957 for (StrVector::const_iterator B = D.InLanguage.begin(),
958 E = D.InLanguage.end(); B != E; ++B)
959 ToolToInLang[D.Name].insert(*B);
960 ToolToOutLang[D.Name] = D.OutLanguage;
964 /// TypecheckGraph - Check that names for output and input languages
965 /// on all edges do match. This doesn't do much when the information
966 /// about the whole graph is not available (i.e. when compiling most
968 void TypecheckGraph (const RecordVector& EdgeVector,
969 const ToolDescriptions& ToolDescs) {
970 StringMap<StringSet<> > ToolToInLang;
971 StringMap<std::string> ToolToOutLang;
973 FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
974 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
975 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
977 for (RecordVector::const_iterator B = EdgeVector.begin(),
978 E = EdgeVector.end(); B != E; ++B) {
979 const Record* Edge = *B;
980 const std::string& NodeA = Edge->getValueAsString("a");
981 const std::string& NodeB = Edge->getValueAsString("b");
982 StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
983 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
985 if (NodeA != "root") {
986 if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
987 throw "Edge " + NodeA + "->" + NodeB
988 + ": output->input language mismatch";
992 throw "Edges back to the root are not allowed!";
996 /// WalkCase - Walks the 'case' expression DAG and invokes
997 /// TestCallback on every test, and StatementCallback on every
998 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
999 /// combinators (that is, they are passed directly to TestCallback).
1000 /// TestCallback must have type 'void TestCallback(const DagInit*, unsigned
1001 /// IndentLevel, bool FirstTest)'.
1002 /// StatementCallback must have type 'void StatementCallback(const Init*,
1003 /// unsigned IndentLevel)'.
1004 template <typename F1, typename F2>
1005 void WalkCase(const Init* Case, F1 TestCallback, F2 StatementCallback,
1006 unsigned IndentLevel = 0)
1008 const DagInit& d = InitPtrToDag(Case);
1011 if (GetOperatorName(d) != "case")
1012 throw "WalkCase should be invoked only on 'case' expressions!";
1014 if (d.getNumArgs() < 2)
1015 throw "There should be at least one clause in the 'case' expression:\n"
1020 const unsigned numArgs = d.getNumArgs();
1022 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1029 const DagInit& Test = InitPtrToDag(arg);
1031 if (GetOperatorName(Test) == "default" && (i+1 != numArgs))
1032 throw "The 'default' clause should be the last in the "
1033 "'case' construct!";
1035 throw "Case construct handler: no corresponding action "
1036 "found for the test " + Test.getAsString() + '!';
1038 TestCallback(&Test, IndentLevel, (i == 1));
1042 if (dynamic_cast<DagInit*>(arg)
1043 && GetOperatorName(static_cast<DagInit*>(arg)) == "case") {
1045 WalkCase(arg, TestCallback, StatementCallback, IndentLevel + Indent1);
1048 // Handle statement.
1049 StatementCallback(arg, IndentLevel);
1057 /// ExtractOptionNames - A helper function object used by
1058 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
1059 class ExtractOptionNames {
1060 llvm::StringSet<>& OptionNames_;
1062 void processDag(const Init* Statement) {
1063 const DagInit& Stmt = InitPtrToDag(Statement);
1064 const std::string& ActionName = GetOperatorName(Stmt);
1065 if (ActionName == "forward" || ActionName == "forward_as" ||
1066 ActionName == "forward_value" ||
1067 ActionName == "forward_transformed_value" ||
1068 ActionName == "switch_on" || ActionName == "parameter_equals" ||
1069 ActionName == "element_in_list" || ActionName == "not_empty" ||
1070 ActionName == "empty") {
1071 checkNumberOfArguments(&Stmt, 1);
1072 const std::string& Name = InitPtrToString(Stmt.getArg(0));
1073 OptionNames_.insert(Name);
1075 else if (ActionName == "and" || ActionName == "or") {
1076 for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
1077 this->processDag(Stmt.getArg(i));
1083 ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
1086 void operator()(const Init* Statement) {
1087 if (typeid(*Statement) == typeid(ListInit)) {
1088 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1089 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1091 this->processDag(*B);
1094 this->processDag(Statement);
1098 void operator()(const DagInit* Test, unsigned, bool) {
1099 this->operator()(Test);
1101 void operator()(const Init* Statement, unsigned) {
1102 this->operator()(Statement);
1106 /// CheckForSuperfluousOptions - Check that there are no side
1107 /// effect-free options (specified only in the OptionList). Otherwise,
1108 /// output a warning.
1109 void CheckForSuperfluousOptions (const RecordVector& Edges,
1110 const ToolDescriptions& ToolDescs,
1111 const OptionDescriptions& OptDescs) {
1112 llvm::StringSet<> nonSuperfluousOptions;
1114 // Add all options mentioned in the ToolDesc.Actions to the set of
1115 // non-superfluous options.
1116 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1117 E = ToolDescs.end(); B != E; ++B) {
1118 const ToolDescription& TD = *(*B);
1119 ExtractOptionNames Callback(nonSuperfluousOptions);
1121 WalkCase(TD.Actions, Callback, Callback);
1124 // Add all options mentioned in the 'case' clauses of the
1125 // OptionalEdges of the compilation graph to the set of
1126 // non-superfluous options.
1127 for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
1129 const Record* Edge = *B;
1130 DagInit* Weight = Edge->getValueAsDag("weight");
1132 if (!isDagEmpty(Weight))
1133 WalkCase(Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
1136 // Check that all options in OptDescs belong to the set of
1137 // non-superfluous options.
1138 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
1139 E = OptDescs.end(); B != E; ++B) {
1140 const OptionDescription& Val = B->second;
1141 if (!nonSuperfluousOptions.count(Val.Name)
1142 && Val.Type != OptionType::Alias)
1143 llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! "
1144 "Probable cause: this option is specified only in the OptionList.\n";
1148 /// EmitCaseTest0Args - Helper function used by EmitCaseConstructHandler().
1149 bool EmitCaseTest0Args(const std::string& TestName, raw_ostream& O) {
1150 if (TestName == "single_input_file") {
1151 O << "InputFilenames.size() == 1";
1154 else if (TestName == "multiple_input_files") {
1155 O << "InputFilenames.size() > 1";
1162 /// EmitListTest - Helper function used by EmitCaseTest1ArgList().
1163 template <typename F>
1164 void EmitListTest(const ListInit& L, const char* LogicOp,
1165 F Callback, raw_ostream& O)
1167 // This is a lot like EmitLogicalOperationTest, but works on ListInits instead
1169 bool isFirst = true;
1170 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B) {
1175 Callback(InitPtrToString(*B), O);
1179 // Callbacks for use with EmitListTest.
1181 class EmitSwitchOn {
1182 const OptionDescriptions& OptDescs_;
1184 EmitSwitchOn(const OptionDescriptions& OptDescs) : OptDescs_(OptDescs)
1187 void operator()(const std::string& OptName, raw_ostream& O) const {
1188 const OptionDescription& OptDesc = OptDescs_.FindSwitch(OptName);
1189 O << OptDesc.GenVariableName();
1193 class EmitEmptyTest {
1195 const OptionDescriptions& OptDescs_;
1197 EmitEmptyTest(bool EmitNegate, const OptionDescriptions& OptDescs)
1198 : EmitNegate_(EmitNegate), OptDescs_(OptDescs)
1201 void operator()(const std::string& OptName, raw_ostream& O) const {
1202 const char* Neg = (EmitNegate_ ? "!" : "");
1203 if (OptName == "o") {
1204 O << Neg << "OutputFilename.empty()";
1206 else if (OptName == "save-temps") {
1207 O << Neg << "(SaveTemps == SaveTempsEnum::Unset)";
1210 const OptionDescription& OptDesc = OptDescs_.FindListOrParameter(OptName);
1211 O << Neg << OptDesc.GenVariableName() << ".empty()";
1217 /// EmitCaseTest1ArgList - Helper function used by EmitCaseTest1Arg();
1218 bool EmitCaseTest1ArgList(const std::string& TestName,
1220 const OptionDescriptions& OptDescs,
1222 const ListInit& L = *static_cast<ListInit*>(d.getArg(0));
1224 if (TestName == "any_switch_on") {
1225 EmitListTest(L, "||", EmitSwitchOn(OptDescs), O);
1228 else if (TestName == "switch_on") {
1229 EmitListTest(L, "&&", EmitSwitchOn(OptDescs), O);
1232 else if (TestName == "any_not_empty") {
1233 EmitListTest(L, "||", EmitEmptyTest(true, OptDescs), O);
1236 else if (TestName == "any_empty") {
1237 EmitListTest(L, "||", EmitEmptyTest(false, OptDescs), O);
1240 else if (TestName == "not_empty") {
1241 EmitListTest(L, "&&", EmitEmptyTest(true, OptDescs), O);
1244 else if (TestName == "empty") {
1245 EmitListTest(L, "&&", EmitEmptyTest(false, OptDescs), O);
1252 /// EmitCaseTest1ArgStr - Helper function used by EmitCaseTest1Arg();
1253 bool EmitCaseTest1ArgStr(const std::string& TestName,
1255 const OptionDescriptions& OptDescs,
1257 const std::string& OptName = InitPtrToString(d.getArg(0));
1259 if (TestName == "switch_on") {
1260 apply(EmitSwitchOn(OptDescs), OptName, O);
1263 else if (TestName == "input_languages_contain") {
1264 O << "InLangs.count(\"" << OptName << "\") != 0";
1267 else if (TestName == "in_language") {
1268 // This works only for single-argument Tool::GenerateAction. Join
1269 // tools can process several files in different languages simultaneously.
1271 // TODO: make this work with Edge::Weight (if possible).
1272 O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
1275 else if (TestName == "not_empty" || TestName == "empty") {
1276 bool EmitNegate = (TestName == "not_empty");
1277 apply(EmitEmptyTest(EmitNegate, OptDescs), OptName, O);
1284 /// EmitCaseTest1Arg - Helper function used by EmitCaseConstructHandler();
1285 bool EmitCaseTest1Arg(const std::string& TestName,
1287 const OptionDescriptions& OptDescs,
1289 checkNumberOfArguments(&d, 1);
1290 if (typeid(*d.getArg(0)) == typeid(ListInit))
1291 return EmitCaseTest1ArgList(TestName, d, OptDescs, O);
1293 return EmitCaseTest1ArgStr(TestName, d, OptDescs, O);
1296 /// EmitCaseTest2Args - Helper function used by EmitCaseConstructHandler().
1297 bool EmitCaseTest2Args(const std::string& TestName,
1299 unsigned IndentLevel,
1300 const OptionDescriptions& OptDescs,
1302 checkNumberOfArguments(&d, 2);
1303 const std::string& OptName = InitPtrToString(d.getArg(0));
1304 const std::string& OptArg = InitPtrToString(d.getArg(1));
1306 if (TestName == "parameter_equals") {
1307 const OptionDescription& OptDesc = OptDescs.FindParameter(OptName);
1308 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
1311 else if (TestName == "element_in_list") {
1312 const OptionDescription& OptDesc = OptDescs.FindList(OptName);
1313 const std::string& VarName = OptDesc.GenVariableName();
1314 O << "std::find(" << VarName << ".begin(),\n";
1315 O.indent(IndentLevel + Indent1)
1316 << VarName << ".end(), \""
1317 << OptArg << "\") != " << VarName << ".end()";
1324 // Forward declaration.
1325 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
1326 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1327 const OptionDescriptions& OptDescs,
1330 /// EmitLogicalOperationTest - Helper function used by
1331 /// EmitCaseConstructHandler.
1332 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
1333 unsigned IndentLevel,
1334 const OptionDescriptions& OptDescs,
1337 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
1338 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
1339 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1340 if (j != NumArgs - 1) {
1342 O.indent(IndentLevel + Indent1) << ' ' << LogicOp << " (";
1350 void EmitLogicalNot(const DagInit& d, unsigned IndentLevel,
1351 const OptionDescriptions& OptDescs, raw_ostream& O)
1353 checkNumberOfArguments(&d, 1);
1354 const DagInit& InnerTest = InitPtrToDag(d.getArg(0));
1356 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1360 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
1361 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1362 const OptionDescriptions& OptDescs,
1364 const std::string& TestName = GetOperatorName(d);
1366 if (TestName == "and")
1367 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
1368 else if (TestName == "or")
1369 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
1370 else if (TestName == "not")
1371 EmitLogicalNot(d, IndentLevel, OptDescs, O);
1372 else if (EmitCaseTest0Args(TestName, O))
1374 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
1376 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
1379 throw TestName + ": unknown edge property!";
1383 /// EmitCaseTestCallback - Callback used by EmitCaseConstructHandler.
1384 class EmitCaseTestCallback {
1386 const OptionDescriptions& OptDescs_;
1390 EmitCaseTestCallback(bool EmitElseIf,
1391 const OptionDescriptions& OptDescs, raw_ostream& O)
1392 : EmitElseIf_(EmitElseIf), OptDescs_(OptDescs), O_(O)
1395 void operator()(const DagInit* Test, unsigned IndentLevel, bool FirstTest)
1397 if (GetOperatorName(Test) == "default") {
1398 O_.indent(IndentLevel) << "else {\n";
1401 O_.indent(IndentLevel)
1402 << ((!FirstTest && EmitElseIf_) ? "else if (" : "if (");
1403 EmitCaseTest(*Test, IndentLevel, OptDescs_, O_);
1409 /// EmitCaseStatementCallback - Callback used by EmitCaseConstructHandler.
1410 template <typename F>
1411 class EmitCaseStatementCallback {
1416 EmitCaseStatementCallback(F Callback, raw_ostream& O)
1417 : Callback_(Callback), O_(O)
1420 void operator() (const Init* Statement, unsigned IndentLevel) {
1422 // Ignore nested 'case' DAG.
1423 if (!(dynamic_cast<const DagInit*>(Statement) &&
1424 GetOperatorName(static_cast<const DagInit*>(Statement)) == "case")) {
1425 if (typeid(*Statement) == typeid(ListInit)) {
1426 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1427 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1429 Callback_(*B, (IndentLevel + Indent1), O_);
1432 Callback_(Statement, (IndentLevel + Indent1), O_);
1435 O_.indent(IndentLevel) << "}\n";
1440 /// EmitCaseConstructHandler - Emit code that handles the 'case'
1441 /// construct. Takes a function object that should emit code for every case
1442 /// clause. Implemented on top of WalkCase.
1443 /// Callback's type is void F(Init* Statement, unsigned IndentLevel,
1444 /// raw_ostream& O).
1445 /// EmitElseIf parameter controls the type of condition that is emitted ('if
1446 /// (..) {..} else if (..) {} .. else {..}' vs. 'if (..) {..} if(..) {..}
1448 template <typename F>
1449 void EmitCaseConstructHandler(const Init* Case, unsigned IndentLevel,
1450 F Callback, bool EmitElseIf,
1451 const OptionDescriptions& OptDescs,
1453 WalkCase(Case, EmitCaseTestCallback(EmitElseIf, OptDescs, O),
1454 EmitCaseStatementCallback<F>(Callback, O), IndentLevel);
1457 /// TokenizeCmdline - converts from "$CALL(HookName, 'Arg1', 'Arg2')/path" to
1458 /// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path"] .
1459 /// Helper function used by EmitCmdLineVecFill and.
1460 void TokenizeCmdline(const std::string& CmdLine, StrVector& Out) {
1461 const char* Delimiters = " \t\n\v\f\r";
1463 { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1466 if (CmdLine.empty())
1470 std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1473 for (; B != E; ++B) {
1474 char cur_ch = CmdLine[B];
1478 if (cur_ch == '$') {
1479 cur_st = SpecialCommand;
1482 if (oneOf(Delimiters, cur_ch)) {
1484 B = CmdLine.find_first_not_of(Delimiters, B);
1485 if (B == std::string::npos) {
1496 case SpecialCommand:
1497 if (oneOf(Delimiters, cur_ch)) {
1502 if (cur_ch == '(') {
1504 cur_st = InsideSpecialCommand;
1509 case InsideSpecialCommand:
1510 if (oneOf(Delimiters, cur_ch)) {
1513 if (cur_ch == '\'') {
1514 cur_st = InsideQuotationMarks;
1518 if (cur_ch == ')') {
1522 if (cur_ch == ',') {
1528 case InsideQuotationMarks:
1529 if (cur_ch == '\'') {
1530 cur_st = InsideSpecialCommand;
1536 Out.back().push_back(cur_ch);
1540 /// SubstituteSpecialCommands - Perform string substitution for $CALL
1541 /// and $ENV. Helper function used by EmitCmdLineVecFill().
1542 StrVector::const_iterator SubstituteSpecialCommands
1543 (StrVector::const_iterator Pos, StrVector::const_iterator End, raw_ostream& O)
1546 const std::string& cmd = *Pos;
1548 if (cmd == "$CALL") {
1549 checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1550 const std::string& CmdName = *Pos;
1553 throw "$CALL invocation: empty argument list!";
1556 O << CmdName << "(";
1559 bool firstIteration = true;
1561 checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1562 const std::string& Arg = *Pos;
1563 assert(Arg.size() != 0);
1569 firstIteration = false;
1573 O << '"' << Arg << '"';
1579 else if (cmd == "$ENV") {
1580 checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1581 const std::string& EnvName = *Pos;
1584 throw "$ENV invocation: empty argument list!";
1586 O << "checkCString(std::getenv(\"";
1590 checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1593 throw "Unknown special command: " + cmd;
1596 const std::string& Leftover = *Pos;
1597 assert(Leftover.at(0) == ')');
1598 if (Leftover.size() != 1)
1599 O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1604 /// EmitCmdLineVecFill - Emit code that fills in the command line
1605 /// vector. Helper function used by EmitGenerateActionMethod().
1606 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1607 bool IsJoin, unsigned IndentLevel,
1610 TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1613 throw "Tool '" + ToolName + "' has empty command line!";
1615 StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1617 // If there is a hook invocation on the place of the first command, skip it.
1618 assert(!StrVec[0].empty());
1619 if (StrVec[0][0] == '$') {
1620 while (I != E && (*I)[0] != ')' )
1623 // Skip the ')' symbol.
1630 bool hasINFILE = false;
1632 for (; I != E; ++I) {
1633 const std::string& cmd = *I;
1634 assert(!cmd.empty());
1635 O.indent(IndentLevel);
1636 if (cmd.at(0) == '$') {
1637 if (cmd == "$INFILE") {
1640 O << "for (PathVector::const_iterator B = inFiles.begin()"
1641 << ", E = inFiles.end();\n";
1642 O.indent(IndentLevel) << "B != E; ++B)\n";
1643 O.indent(IndentLevel + Indent1) << "vec.push_back(B->str());\n";
1646 O << "vec.push_back(inFile.str());\n";
1649 else if (cmd == "$OUTFILE") {
1650 O << "vec.push_back(\"\");\n";
1651 O.indent(IndentLevel) << "out_file_index = vec.size()-1;\n";
1654 O << "vec.push_back(";
1655 I = SubstituteSpecialCommands(I, E, O);
1660 O << "vec.push_back(\"" << cmd << "\");\n";
1664 throw "Tool '" + ToolName + "' doesn't take any input!";
1666 O.indent(IndentLevel) << "cmd = ";
1667 if (StrVec[0][0] == '$')
1668 SubstituteSpecialCommands(StrVec.begin(), StrVec.end(), O);
1670 O << '"' << StrVec[0] << '"';
1674 /// EmitCmdLineVecFillCallback - A function object wrapper around
1675 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1676 /// argument to EmitCaseConstructHandler().
1677 class EmitCmdLineVecFillCallback {
1679 const std::string& ToolName;
1681 EmitCmdLineVecFillCallback(bool J, const std::string& TN)
1682 : IsJoin(J), ToolName(TN) {}
1684 void operator()(const Init* Statement, unsigned IndentLevel,
1685 raw_ostream& O) const
1687 EmitCmdLineVecFill(Statement, ToolName, IsJoin, IndentLevel, O);
1691 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1692 /// implement EmitActionHandler. Emits code for
1693 /// handling the (forward) and (forward_as) option properties.
1694 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1695 unsigned IndentLevel,
1696 const std::string& NewName,
1698 const std::string& Name = NewName.empty()
1701 unsigned IndentLevel1 = IndentLevel + Indent1;
1704 case OptionType::Switch:
1705 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1707 case OptionType::Parameter:
1708 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1709 O.indent(IndentLevel) << "vec.push_back(" << D.GenVariableName() << ");\n";
1711 case OptionType::Prefix:
1712 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\" + "
1713 << D.GenVariableName() << ");\n";
1715 case OptionType::PrefixList:
1716 O.indent(IndentLevel)
1717 << "for (" << D.GenTypeDeclaration()
1718 << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1719 O.indent(IndentLevel)
1720 << "E = " << D.GenVariableName() << ".end(); B != E;) {\n";
1721 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\" + " << "*B);\n";
1722 O.indent(IndentLevel1) << "++B;\n";
1724 for (int i = 1, j = D.MultiVal; i < j; ++i) {
1725 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1726 O.indent(IndentLevel1) << "++B;\n";
1729 O.indent(IndentLevel) << "}\n";
1731 case OptionType::ParameterList:
1732 O.indent(IndentLevel)
1733 << "for (" << D.GenTypeDeclaration() << "::iterator B = "
1734 << D.GenVariableName() << ".begin(),\n";
1735 O.indent(IndentLevel) << "E = " << D.GenVariableName()
1736 << ".end() ; B != E;) {\n";
1737 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\");\n";
1739 for (int i = 0, j = D.MultiVal; i < j; ++i) {
1740 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1741 O.indent(IndentLevel1) << "++B;\n";
1744 O.indent(IndentLevel) << "}\n";
1746 case OptionType::Alias:
1748 throw "Aliases are not allowed in tool option descriptions!";
1752 /// ActionHandlingCallbackBase - Base class of EmitActionHandlersCallback and
1753 /// EmitPreprocessOptionsCallback.
1754 struct ActionHandlingCallbackBase {
1756 void onErrorDag(const DagInit& d,
1757 unsigned IndentLevel, raw_ostream& O) const
1759 O.indent(IndentLevel)
1760 << "throw std::runtime_error(\"" <<
1761 (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0))
1766 void onWarningDag(const DagInit& d,
1767 unsigned IndentLevel, raw_ostream& O) const
1769 checkNumberOfArguments(&d, 1);
1770 O.indent(IndentLevel) << "llvm::errs() << \""
1771 << InitPtrToString(d.getArg(0)) << "\";\n";
1776 /// EmitActionHandlersCallback - Emit code that handles actions. Used by
1777 /// EmitGenerateActionMethod() as an argument to EmitCaseConstructHandler().
1778 class EmitActionHandlersCallback;
1779 typedef void (EmitActionHandlersCallback::* EmitActionHandlersCallbackHandler)
1780 (const DagInit&, unsigned, raw_ostream&) const;
1782 class EmitActionHandlersCallback
1783 : public ActionHandlingCallbackBase,
1784 public HandlerTable<EmitActionHandlersCallbackHandler>
1786 const OptionDescriptions& OptDescs;
1787 typedef EmitActionHandlersCallbackHandler Handler;
1789 void onAppendCmd (const DagInit& Dag,
1790 unsigned IndentLevel, raw_ostream& O) const
1792 checkNumberOfArguments(&Dag, 1);
1793 const std::string& Cmd = InitPtrToString(Dag.getArg(0));
1795 llvm::SplitString(Cmd, Out);
1797 for (StrVector::const_iterator B = Out.begin(), E = Out.end();
1799 O.indent(IndentLevel) << "vec.push_back(\"" << *B << "\");\n";
1802 void onForward (const DagInit& Dag,
1803 unsigned IndentLevel, raw_ostream& O) const
1805 checkNumberOfArguments(&Dag, 1);
1806 const std::string& Name = InitPtrToString(Dag.getArg(0));
1807 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1808 IndentLevel, "", O);
1811 void onForwardAs (const DagInit& Dag,
1812 unsigned IndentLevel, raw_ostream& O) const
1814 checkNumberOfArguments(&Dag, 2);
1815 const std::string& Name = InitPtrToString(Dag.getArg(0));
1816 const std::string& NewName = InitPtrToString(Dag.getArg(1));
1817 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1818 IndentLevel, NewName, O);
1821 void onForwardValue (const DagInit& Dag,
1822 unsigned IndentLevel, raw_ostream& O) const
1824 checkNumberOfArguments(&Dag, 1);
1825 const std::string& Name = InitPtrToString(Dag.getArg(0));
1826 const OptionDescription& D = OptDescs.FindOption(Name);
1828 if (D.isParameter()) {
1829 O.indent(IndentLevel) << "vec.push_back("
1830 << D.GenVariableName() << ");\n";
1832 else if (D.isList()) {
1833 O.indent(IndentLevel) << "std::copy(" << D.GenVariableName()
1834 << ".begin(), " << D.GenVariableName()
1835 << ".end(), std::back_inserter(vec));\n";
1838 throw "'forward_value' used with a switch or an alias!";
1842 void onForwardTransformedValue (const DagInit& Dag,
1843 unsigned IndentLevel, raw_ostream& O) const
1845 checkNumberOfArguments(&Dag, 2);
1846 const std::string& Name = InitPtrToString(Dag.getArg(0));
1847 const std::string& Hook = InitPtrToString(Dag.getArg(1));
1848 const OptionDescription& D = OptDescs.FindOption(Name);
1850 if (D.isParameter() || D.isList()) {
1851 O.indent(IndentLevel) << "vec.push_back(" << "hooks::"
1852 << Hook << "(" << D.GenVariableName() << "));\n";
1855 throw "'forward_transformed_value' used with a switch or an alias!";
1860 void onOutputSuffix (const DagInit& Dag,
1861 unsigned IndentLevel, raw_ostream& O) const
1863 checkNumberOfArguments(&Dag, 1);
1864 const std::string& OutSuf = InitPtrToString(Dag.getArg(0));
1865 O.indent(IndentLevel) << "output_suffix = \"" << OutSuf << "\";\n";
1868 void onStopCompilation (const DagInit& Dag,
1869 unsigned IndentLevel, raw_ostream& O) const
1871 O.indent(IndentLevel) << "stop_compilation = true;\n";
1875 void onUnpackValues (const DagInit& Dag,
1876 unsigned IndentLevel, raw_ostream& O) const
1878 throw "'unpack_values' is deprecated. "
1879 "Use 'comma_separated' + 'forward_value' instead!";
1884 explicit EmitActionHandlersCallback(const OptionDescriptions& OD)
1887 if (!staticMembersInitialized_) {
1888 AddHandler("error", &EmitActionHandlersCallback::onErrorDag);
1889 AddHandler("warning", &EmitActionHandlersCallback::onWarningDag);
1890 AddHandler("append_cmd", &EmitActionHandlersCallback::onAppendCmd);
1891 AddHandler("forward", &EmitActionHandlersCallback::onForward);
1892 AddHandler("forward_as", &EmitActionHandlersCallback::onForwardAs);
1893 AddHandler("forward_value", &EmitActionHandlersCallback::onForwardValue);
1894 AddHandler("forward_transformed_value",
1895 &EmitActionHandlersCallback::onForwardTransformedValue);
1896 AddHandler("output_suffix", &EmitActionHandlersCallback::onOutputSuffix);
1897 AddHandler("stop_compilation",
1898 &EmitActionHandlersCallback::onStopCompilation);
1899 AddHandler("unpack_values",
1900 &EmitActionHandlersCallback::onUnpackValues);
1902 staticMembersInitialized_ = true;
1906 void operator()(const Init* Statement,
1907 unsigned IndentLevel, raw_ostream& O) const
1909 const DagInit& Dag = InitPtrToDag(Statement);
1910 const std::string& ActionName = GetOperatorName(Dag);
1911 Handler h = GetHandler(ActionName);
1913 ((this)->*(h))(Dag, IndentLevel, O);
1917 bool IsOutFileIndexCheckRequiredStr (const Init* CmdLine) {
1919 TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1921 for (StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1923 if (*I == "$OUTFILE")
1930 class IsOutFileIndexCheckRequiredStrCallback {
1934 IsOutFileIndexCheckRequiredStrCallback(bool* ret) : ret_(ret)
1937 void operator()(const Init* CmdLine) {
1938 // Ignore nested 'case' DAG.
1939 if (typeid(*CmdLine) == typeid(DagInit))
1942 if (IsOutFileIndexCheckRequiredStr(CmdLine))
1946 void operator()(const DagInit* Test, unsigned, bool) {
1947 this->operator()(Test);
1949 void operator()(const Init* Statement, unsigned) {
1950 this->operator()(Statement);
1954 bool IsOutFileIndexCheckRequiredCase (Init* CmdLine) {
1956 WalkCase(CmdLine, Id(), IsOutFileIndexCheckRequiredStrCallback(&ret));
1960 /// IsOutFileIndexCheckRequired - Should we emit an "out_file_index != -1" check
1961 /// in EmitGenerateActionMethod() ?
1962 bool IsOutFileIndexCheckRequired (Init* CmdLine) {
1963 if (typeid(*CmdLine) == typeid(StringInit))
1964 return IsOutFileIndexCheckRequiredStr(CmdLine);
1966 return IsOutFileIndexCheckRequiredCase(CmdLine);
1969 void EmitGenerateActionMethodHeader(const ToolDescription& D,
1970 bool IsJoin, raw_ostream& O)
1973 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
1975 O.indent(Indent1) << "Action GenerateAction(const sys::Path& inFile,\n";
1977 O.indent(Indent2) << "bool HasChildren,\n";
1978 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
1979 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
1980 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
1981 O.indent(Indent1) << "{\n";
1982 O.indent(Indent2) << "std::string cmd;\n";
1983 O.indent(Indent2) << "std::vector<std::string> vec;\n";
1984 O.indent(Indent2) << "bool stop_compilation = !HasChildren;\n";
1985 O.indent(Indent2) << "const char* output_suffix = \""
1986 << D.OutputSuffix << "\";\n";
1989 // EmitGenerateActionMethod - Emit either a normal or a "join" version of the
1990 // Tool::GenerateAction() method.
1991 void EmitGenerateActionMethod (const ToolDescription& D,
1992 const OptionDescriptions& OptDescs,
1993 bool IsJoin, raw_ostream& O) {
1995 EmitGenerateActionMethodHeader(D, IsJoin, O);
1998 throw "Tool " + D.Name + " has no cmd_line property!";
2000 bool IndexCheckRequired = IsOutFileIndexCheckRequired(D.CmdLine);
2001 O.indent(Indent2) << "int out_file_index"
2002 << (IndexCheckRequired ? " = -1" : "")
2005 // Process the cmd_line property.
2006 if (typeid(*D.CmdLine) == typeid(StringInit))
2007 EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
2009 EmitCaseConstructHandler(D.CmdLine, Indent2,
2010 EmitCmdLineVecFillCallback(IsJoin, D.Name),
2013 // For every understood option, emit handling code.
2015 EmitCaseConstructHandler(D.Actions, Indent2,
2016 EmitActionHandlersCallback(OptDescs),
2017 false, OptDescs, O);
2021 << "std::string out_file = OutFilename("
2022 << (IsJoin ? "sys::Path(),\n" : "inFile,\n");
2023 O.indent(Indent3) << "TempDir, stop_compilation, output_suffix).str();\n\n";
2025 if (IndexCheckRequired)
2026 O.indent(Indent2) << "if (out_file_index != -1)\n";
2027 O.indent(IndexCheckRequired ? Indent3 : Indent2)
2028 << "vec[out_file_index] = out_file;\n";
2030 // Handle the Sink property.
2032 O.indent(Indent2) << "if (!" << SinkOptionName << ".empty()) {\n";
2033 O.indent(Indent3) << "vec.insert(vec.end(), "
2034 << SinkOptionName << ".begin(), " << SinkOptionName
2036 O.indent(Indent2) << "}\n";
2039 O.indent(Indent2) << "return Action(cmd, vec, stop_compilation, out_file);\n";
2040 O.indent(Indent1) << "}\n\n";
2043 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
2044 /// a given Tool class.
2045 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
2046 const OptionDescriptions& OptDescs,
2048 if (!ToolDesc.isJoin()) {
2049 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
2050 O.indent(Indent2) << "bool HasChildren,\n";
2051 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
2052 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
2053 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
2054 O.indent(Indent1) << "{\n";
2055 O.indent(Indent2) << "throw std::runtime_error(\"" << ToolDesc.Name
2056 << " is not a Join tool!\");\n";
2057 O.indent(Indent1) << "}\n\n";
2060 EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
2063 EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
2066 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
2067 /// methods for a given Tool class.
2068 void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
2069 O.indent(Indent1) << "const char** InputLanguages() const {\n";
2070 O.indent(Indent2) << "return InputLanguages_;\n";
2071 O.indent(Indent1) << "}\n\n";
2073 if (D.OutLanguage.empty())
2074 throw "Tool " + D.Name + " has no 'out_language' property!";
2076 O.indent(Indent1) << "const char* OutputLanguage() const {\n";
2077 O.indent(Indent2) << "return \"" << D.OutLanguage << "\";\n";
2078 O.indent(Indent1) << "}\n\n";
2081 /// EmitNameMethod - Emit the Name() method for a given Tool class.
2082 void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
2083 O.indent(Indent1) << "const char* Name() const {\n";
2084 O.indent(Indent2) << "return \"" << D.Name << "\";\n";
2085 O.indent(Indent1) << "}\n\n";
2088 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
2090 void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
2091 O.indent(Indent1) << "bool IsJoin() const {\n";
2093 O.indent(Indent2) << "return true;\n";
2095 O.indent(Indent2) << "return false;\n";
2096 O.indent(Indent1) << "}\n\n";
2099 /// EmitStaticMemberDefinitions - Emit static member definitions for a
2100 /// given Tool class.
2101 void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
2102 if (D.InLanguage.empty())
2103 throw "Tool " + D.Name + " has no 'in_language' property!";
2105 O << "const char* " << D.Name << "::InputLanguages_[] = {";
2106 for (StrVector::const_iterator B = D.InLanguage.begin(),
2107 E = D.InLanguage.end(); B != E; ++B)
2108 O << '\"' << *B << "\", ";
2112 /// EmitToolClassDefinition - Emit a Tool class definition.
2113 void EmitToolClassDefinition (const ToolDescription& D,
2114 const OptionDescriptions& OptDescs,
2116 if (D.Name == "root")
2120 O << "class " << D.Name << " : public ";
2126 O << "{\nprivate:\n";
2127 O.indent(Indent1) << "static const char* InputLanguages_[];\n\n";
2130 EmitNameMethod(D, O);
2131 EmitInOutLanguageMethods(D, O);
2132 EmitIsJoinMethod(D, O);
2133 EmitGenerateActionMethods(D, OptDescs, O);
2135 // Close class definition
2138 EmitStaticMemberDefinitions(D, O);
2142 /// EmitOptionDefinitions - Iterate over a list of option descriptions
2143 /// and emit registration code.
2144 void EmitOptionDefinitions (const OptionDescriptions& descs,
2145 bool HasSink, bool HasExterns,
2148 std::vector<OptionDescription> Aliases;
2150 // Emit static cl::Option variables.
2151 for (OptionDescriptions::const_iterator B = descs.begin(),
2152 E = descs.end(); B!=E; ++B) {
2153 const OptionDescription& val = B->second;
2155 if (val.Type == OptionType::Alias) {
2156 Aliases.push_back(val);
2163 O << val.GenTypeDeclaration() << ' '
2164 << val.GenVariableName();
2166 if (val.isExtern()) {
2171 O << "(\"" << val.Name << "\"\n";
2173 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
2174 O << ", cl::Prefix";
2176 if (val.isRequired()) {
2177 if (val.isList() && !val.isMultiVal())
2178 O << ", cl::OneOrMore";
2180 O << ", cl::Required";
2182 else if (val.isOneOrMore() && val.isList()) {
2183 O << ", cl::OneOrMore";
2185 else if (val.isZeroOrOne() && val.isList()) {
2186 O << ", cl::ZeroOrOne";
2189 if (val.isReallyHidden())
2190 O << ", cl::ReallyHidden";
2191 else if (val.isHidden())
2192 O << ", cl::Hidden";
2194 if (val.isCommaSeparated())
2195 O << ", cl::CommaSeparated";
2197 if (val.MultiVal > 1)
2198 O << ", cl::multi_val(" << val.MultiVal << ')';
2201 const std::string& str = val.InitVal->getAsString();
2202 O << ", cl::init(" << str << ')';
2205 if (!val.Help.empty())
2206 O << ", cl::desc(\"" << val.Help << "\")";
2211 // Emit the aliases (they should go after all the 'proper' options).
2212 for (std::vector<OptionDescription>::const_iterator
2213 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
2214 const OptionDescription& val = *B;
2216 O << val.GenTypeDeclaration() << ' '
2217 << val.GenVariableName()
2218 << "(\"" << val.Name << '\"';
2220 const OptionDescription& D = descs.FindOption(val.Help);
2221 O << ", cl::aliasopt(" << D.GenVariableName() << ")";
2223 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
2226 // Emit the sink option.
2228 O << (HasExterns ? "extern cl" : "cl")
2229 << "::list<std::string> " << SinkOptionName
2230 << (HasExterns ? ";\n" : "(cl::Sink);\n");
2235 /// EmitPreprocessOptionsCallback - Helper function passed to
2236 /// EmitCaseConstructHandler() by EmitPreprocessOptions().
2237 class EmitPreprocessOptionsCallback : ActionHandlingCallbackBase {
2238 const OptionDescriptions& OptDescs_;
2240 void onUnsetOption(Init* i, unsigned IndentLevel, raw_ostream& O) {
2241 const std::string& OptName = InitPtrToString(i);
2242 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2244 if (OptDesc.isSwitch()) {
2245 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = false;\n";
2247 else if (OptDesc.isParameter()) {
2248 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = \"\";\n";
2250 else if (OptDesc.isList()) {
2251 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2254 throw "Can't apply 'unset_option' to alias option '" + OptName + "'!";
2258 void processDag(const Init* I, unsigned IndentLevel, raw_ostream& O)
2260 const DagInit& d = InitPtrToDag(I);
2261 const std::string& OpName = GetOperatorName(d);
2263 if (OpName == "warning") {
2264 this->onWarningDag(d, IndentLevel, O);
2266 else if (OpName == "error") {
2267 this->onWarningDag(d, IndentLevel, O);
2269 else if (OpName == "unset_option") {
2270 checkNumberOfArguments(&d, 1);
2271 Init* I = d.getArg(0);
2272 if (typeid(*I) == typeid(ListInit)) {
2273 const ListInit& DagList = *static_cast<const ListInit*>(I);
2274 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
2276 this->onUnsetOption(*B, IndentLevel, O);
2279 this->onUnsetOption(I, IndentLevel, O);
2283 throw "Unknown operator in the option preprocessor: '" + OpName + "'!"
2284 "\nOnly 'warning', 'error' and 'unset_option' are allowed.";
2290 void operator()(const Init* I, unsigned IndentLevel, raw_ostream& O) {
2291 this->processDag(I, IndentLevel, O);
2294 EmitPreprocessOptionsCallback(const OptionDescriptions& OptDescs)
2295 : OptDescs_(OptDescs)
2299 /// EmitPreprocessOptions - Emit the PreprocessOptionsLocal() function.
2300 void EmitPreprocessOptions (const RecordKeeper& Records,
2301 const OptionDescriptions& OptDecs, raw_ostream& O)
2303 O << "void PreprocessOptionsLocal() {\n";
2305 const RecordVector& OptionPreprocessors =
2306 Records.getAllDerivedDefinitions("OptionPreprocessor");
2308 for (RecordVector::const_iterator B = OptionPreprocessors.begin(),
2309 E = OptionPreprocessors.end(); B!=E; ++B) {
2310 DagInit* Case = (*B)->getValueAsDag("preprocessor");
2311 EmitCaseConstructHandler(Case, Indent1,
2312 EmitPreprocessOptionsCallback(OptDecs),
2319 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMapLocal() function.
2320 void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
2322 O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
2324 // Get the relevant field out of RecordKeeper
2325 const Record* LangMapRecord = Records.getDef("LanguageMap");
2327 // It is allowed for a plugin to have no language map.
2328 if (LangMapRecord) {
2330 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
2331 if (!LangsToSuffixesList)
2332 throw "Error in the language map definition!";
2334 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
2335 const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
2337 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
2338 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
2340 for (unsigned i = 0; i < Suffixes->size(); ++i)
2341 O.indent(Indent1) << "langMap[\""
2342 << InitPtrToString(Suffixes->getElement(i))
2343 << "\"] = \"" << Lang << "\";\n";
2350 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
2351 /// by EmitEdgeClass().
2352 void IncDecWeight (const Init* i, unsigned IndentLevel,
2354 const DagInit& d = InitPtrToDag(i);
2355 const std::string& OpName = GetOperatorName(d);
2357 if (OpName == "inc_weight") {
2358 O.indent(IndentLevel) << "ret += ";
2360 else if (OpName == "dec_weight") {
2361 O.indent(IndentLevel) << "ret -= ";
2363 else if (OpName == "error") {
2364 checkNumberOfArguments(&d, 1);
2365 O.indent(IndentLevel) << "throw std::runtime_error(\""
2366 << InitPtrToString(d.getArg(0))
2371 throw "Unknown operator in edge properties list: '" + OpName + "'!"
2372 "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
2375 if (d.getNumArgs() > 0)
2376 O << InitPtrToInt(d.getArg(0)) << ";\n";
2382 /// EmitEdgeClass - Emit a single Edge# class.
2383 void EmitEdgeClass (unsigned N, const std::string& Target,
2384 DagInit* Case, const OptionDescriptions& OptDescs,
2387 // Class constructor.
2388 O << "class Edge" << N << ": public Edge {\n"
2390 O.indent(Indent1) << "Edge" << N << "() : Edge(\"" << Target
2393 // Function Weight().
2395 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n";
2396 O.indent(Indent2) << "unsigned ret = 0;\n";
2398 // Handle the 'case' construct.
2399 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
2401 O.indent(Indent2) << "return ret;\n";
2402 O.indent(Indent1) << "};\n\n};\n\n";
2405 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
2406 void EmitEdgeClasses (const RecordVector& EdgeVector,
2407 const OptionDescriptions& OptDescs,
2410 for (RecordVector::const_iterator B = EdgeVector.begin(),
2411 E = EdgeVector.end(); B != E; ++B) {
2412 const Record* Edge = *B;
2413 const std::string& NodeB = Edge->getValueAsString("b");
2414 DagInit* Weight = Edge->getValueAsDag("weight");
2416 if (!isDagEmpty(Weight))
2417 EmitEdgeClass(i, NodeB, Weight, OptDescs, O);
2422 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraphLocal()
2424 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
2425 const ToolDescriptions& ToolDescs,
2428 O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
2430 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2431 E = ToolDescs.end(); B != E; ++B)
2432 O.indent(Indent1) << "G.insertNode(new " << (*B)->Name << "());\n";
2439 for (RecordVector::const_iterator B = EdgeVector.begin(),
2440 E = EdgeVector.end(); B != E; ++B) {
2441 const Record* Edge = *B;
2442 const std::string& NodeA = Edge->getValueAsString("a");
2443 const std::string& NodeB = Edge->getValueAsString("b");
2444 DagInit* Weight = Edge->getValueAsDag("weight");
2446 O.indent(Indent1) << "G.insertEdge(\"" << NodeA << "\", ";
2448 if (isDagEmpty(Weight))
2449 O << "new SimpleEdge(\"" << NodeB << "\")";
2451 O << "new Edge" << i << "()";
2460 /// HookInfo - Information about the hook type and number of arguments.
2463 // A hook can either have a single parameter of type std::vector<std::string>,
2464 // or NumArgs parameters of type const char*.
2465 enum HookType { ListHook, ArgHook };
2470 HookInfo() : Type(ArgHook), NumArgs(1)
2473 HookInfo(HookType T) : Type(T), NumArgs(1)
2476 HookInfo(unsigned N) : Type(ArgHook), NumArgs(N)
2480 typedef llvm::StringMap<HookInfo> HookInfoMap;
2482 /// ExtractHookNames - Extract the hook names from all instances of
2483 /// $CALL(HookName) in the provided command line string/action. Helper
2484 /// function used by FillInHookNames().
2485 class ExtractHookNames {
2486 HookInfoMap& HookNames_;
2487 const OptionDescriptions& OptDescs_;
2489 ExtractHookNames(HookInfoMap& HookNames, const OptionDescriptions& OptDescs)
2490 : HookNames_(HookNames), OptDescs_(OptDescs)
2493 void onAction (const DagInit& Dag) {
2494 if (GetOperatorName(Dag) == "forward_transformed_value") {
2495 checkNumberOfArguments(Dag, 2);
2496 const std::string& OptName = InitPtrToString(Dag.getArg(0));
2497 const std::string& HookName = InitPtrToString(Dag.getArg(1));
2498 const OptionDescription& D = OptDescs_.FindOption(OptName);
2500 HookNames_[HookName] = HookInfo(D.isList() ? HookInfo::ListHook
2501 : HookInfo::ArgHook);
2505 void operator()(const Init* Arg) {
2507 // We're invoked on an action (either a dag or a dag list).
2508 if (typeid(*Arg) == typeid(DagInit)) {
2509 const DagInit& Dag = InitPtrToDag(Arg);
2510 this->onAction(Dag);
2513 else if (typeid(*Arg) == typeid(ListInit)) {
2514 const ListInit& List = InitPtrToList(Arg);
2515 for (ListInit::const_iterator B = List.begin(), E = List.end(); B != E;
2517 const DagInit& Dag = InitPtrToDag(*B);
2518 this->onAction(Dag);
2523 // We're invoked on a command line.
2525 TokenizeCmdline(InitPtrToString(Arg), cmds);
2526 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
2528 const std::string& cmd = *B;
2530 if (cmd == "$CALL") {
2531 unsigned NumArgs = 0;
2532 checkedIncrement(B, E, "Syntax error in $CALL invocation!");
2533 const std::string& HookName = *B;
2536 if (HookName.at(0) == ')')
2537 throw "$CALL invoked with no arguments!";
2539 while (++B != E && B->at(0) != ')') {
2543 HookInfoMap::const_iterator H = HookNames_.find(HookName);
2545 if (H != HookNames_.end() && H->second.NumArgs != NumArgs &&
2546 H->second.Type != HookInfo::ArgHook)
2547 throw "Overloading of hooks is not allowed. Overloaded hook: "
2550 HookNames_[HookName] = HookInfo(NumArgs);
2556 void operator()(const DagInit* Test, unsigned, bool) {
2557 this->operator()(Test);
2559 void operator()(const Init* Statement, unsigned) {
2560 this->operator()(Statement);
2564 /// FillInHookNames - Actually extract the hook names from all command
2565 /// line strings. Helper function used by EmitHookDeclarations().
2566 void FillInHookNames(const ToolDescriptions& ToolDescs,
2567 const OptionDescriptions& OptDescs,
2568 HookInfoMap& HookNames)
2570 // For all tool descriptions:
2571 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2572 E = ToolDescs.end(); B != E; ++B) {
2573 const ToolDescription& D = *(*B);
2575 // Look for 'forward_transformed_value' in 'actions'.
2577 WalkCase(D.Actions, Id(), ExtractHookNames(HookNames, OptDescs));
2579 // Look for hook invocations in 'cmd_line'.
2582 if (dynamic_cast<StringInit*>(D.CmdLine))
2583 // This is a string.
2584 ExtractHookNames(HookNames, OptDescs).operator()(D.CmdLine);
2586 // This is a 'case' construct.
2587 WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames, OptDescs));
2591 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
2592 /// property records and emit hook function declaration for each
2593 /// instance of $CALL(HookName).
2594 void EmitHookDeclarations(const ToolDescriptions& ToolDescs,
2595 const OptionDescriptions& OptDescs, raw_ostream& O) {
2596 HookInfoMap HookNames;
2598 FillInHookNames(ToolDescs, OptDescs, HookNames);
2599 if (HookNames.empty())
2602 O << "namespace hooks {\n";
2603 for (HookInfoMap::const_iterator B = HookNames.begin(),
2604 E = HookNames.end(); B != E; ++B) {
2605 const char* HookName = B->first();
2606 const HookInfo& Info = B->second;
2608 O.indent(Indent1) << "std::string " << HookName << "(";
2610 if (Info.Type == HookInfo::ArgHook) {
2611 for (unsigned i = 0, j = Info.NumArgs; i < j; ++i) {
2612 O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
2616 O << "const std::vector<std::string>& Arg";
2624 /// EmitRegisterPlugin - Emit code to register this plugin.
2625 void EmitRegisterPlugin(int Priority, raw_ostream& O) {
2626 O << "struct Plugin : public llvmc::BasePlugin {\n\n";
2627 O.indent(Indent1) << "int Priority() const { return "
2628 << Priority << "; }\n\n";
2629 O.indent(Indent1) << "void PreprocessOptions() const\n";
2630 O.indent(Indent1) << "{ PreprocessOptionsLocal(); }\n\n";
2631 O.indent(Indent1) << "void PopulateLanguageMap(LanguageMap& langMap) const\n";
2632 O.indent(Indent1) << "{ PopulateLanguageMapLocal(langMap); }\n\n";
2634 << "void PopulateCompilationGraph(CompilationGraph& graph) const\n";
2635 O.indent(Indent1) << "{ PopulateCompilationGraphLocal(graph); }\n"
2637 << "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
2640 /// EmitIncludes - Emit necessary #include directives and some
2641 /// additional declarations.
2642 void EmitIncludes(raw_ostream& O) {
2643 O << "#include \"llvm/CompilerDriver/BuiltinOptions.h\"\n"
2644 << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
2645 << "#include \"llvm/CompilerDriver/ForceLinkageMacros.h\"\n"
2646 << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
2647 << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
2649 << "#include \"llvm/Support/CommandLine.h\"\n"
2650 << "#include \"llvm/Support/raw_ostream.h\"\n\n"
2652 << "#include <algorithm>\n"
2653 << "#include <cstdlib>\n"
2654 << "#include <iterator>\n"
2655 << "#include <stdexcept>\n\n"
2657 << "using namespace llvm;\n"
2658 << "using namespace llvmc;\n\n"
2660 << "extern cl::opt<std::string> OutputFilename;\n\n"
2662 << "inline const char* checkCString(const char* s)\n"
2663 << "{ return s == NULL ? \"\" : s; }\n\n";
2667 /// PluginData - Holds all information about a plugin.
2669 OptionDescriptions OptDescs;
2672 ToolDescriptions ToolDescs;
2677 /// HasSink - Go through the list of tool descriptions and check if
2678 /// there are any with the 'sink' property set.
2679 bool HasSink(const ToolDescriptions& ToolDescs) {
2680 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2681 E = ToolDescs.end(); B != E; ++B)
2688 /// HasExterns - Go through the list of option descriptions and check
2689 /// if there are any external options.
2690 bool HasExterns(const OptionDescriptions& OptDescs) {
2691 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
2692 E = OptDescs.end(); B != E; ++B)
2693 if (B->second.isExtern())
2699 /// CollectPluginData - Collect tool and option properties,
2700 /// compilation graph edges and plugin priority from the parse tree.
2701 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
2702 // Collect option properties.
2703 const RecordVector& OptionLists =
2704 Records.getAllDerivedDefinitions("OptionList");
2705 CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
2708 // Collect tool properties.
2709 const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
2710 CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
2711 Data.HasSink = HasSink(Data.ToolDescs);
2712 Data.HasExterns = HasExterns(Data.OptDescs);
2714 // Collect compilation graph edges.
2715 const RecordVector& CompilationGraphs =
2716 Records.getAllDerivedDefinitions("CompilationGraph");
2717 FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
2720 // Calculate the priority of this plugin.
2721 const RecordVector& Priorities =
2722 Records.getAllDerivedDefinitions("PluginPriority");
2723 Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
2726 /// CheckPluginData - Perform some sanity checks on the collected data.
2727 void CheckPluginData(PluginData& Data) {
2728 // Filter out all tools not mentioned in the compilation graph.
2729 FilterNotInGraph(Data.Edges, Data.ToolDescs);
2731 // Typecheck the compilation graph.
2732 TypecheckGraph(Data.Edges, Data.ToolDescs);
2734 // Check that there are no options without side effects (specified
2735 // only in the OptionList).
2736 CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
2740 void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
2741 // Emit file header.
2744 // Emit global option registration code.
2745 EmitOptionDefinitions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
2747 // Emit hook declarations.
2748 EmitHookDeclarations(Data.ToolDescs, Data.OptDescs, O);
2750 O << "namespace {\n\n";
2752 // Emit PreprocessOptionsLocal() function.
2753 EmitPreprocessOptions(Records, Data.OptDescs, O);
2755 // Emit PopulateLanguageMapLocal() function
2756 // (language map maps from file extensions to language names).
2757 EmitPopulateLanguageMap(Records, O);
2759 // Emit Tool classes.
2760 for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
2761 E = Data.ToolDescs.end(); B!=E; ++B)
2762 EmitToolClassDefinition(*(*B), Data.OptDescs, O);
2764 // Emit Edge# classes.
2765 EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
2767 // Emit PopulateCompilationGraphLocal() function.
2768 EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
2770 // Emit code for plugin registration.
2771 EmitRegisterPlugin(Data.Priority, O);
2773 O << "} // End anonymous namespace.\n\n";
2775 // Force linkage magic.
2776 O << "namespace llvmc {\n";
2777 O << "LLVMC_FORCE_LINKAGE_DECL(LLVMC_PLUGIN_NAME) {}\n";
2784 // End of anonymous namespace
2787 /// run - The back-end entry point.
2788 void LLVMCConfigurationEmitter::run (raw_ostream &O) {
2792 CollectPluginData(Records, Data);
2793 CheckPluginData(Data);
2795 EmitSourceFileHeader("LLVMC Configuration Library", O);
2796 EmitPluginCode(Data, O);
2798 } catch (std::exception& Error) {
2799 throw Error.what() + std::string(" - usually this means a syntax error.");