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"
33 //===----------------------------------------------------------------------===//
36 typedef std::vector<Record*> RecordVector;
37 typedef std::vector<std::string> StrVector;
39 //===----------------------------------------------------------------------===//
42 // Indentation strings.
43 const char * Indent1 = " ";
44 const char * Indent2 = " ";
45 const char * Indent3 = " ";
47 // Default help string.
48 const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
50 // Name for the "sink" option.
51 const char * SinkOptionName = "AutoGeneratedSinkOption";
53 //===----------------------------------------------------------------------===//
56 /// Id - An 'identity' function object.
59 void operator()(const T&) const {
63 int InitPtrToInt(const Init* ptr) {
64 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
65 return val.getValue();
68 const std::string& InitPtrToString(const Init* ptr) {
69 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
70 return val.getValue();
73 const ListInit& InitPtrToList(const Init* ptr) {
74 const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
78 const DagInit& InitPtrToDag(const Init* ptr) {
79 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
83 // checkNumberOfArguments - Ensure that the number of args in d is
84 // greater than or equal to min_arguments, otherwise throw an exception.
85 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
86 if (!d || d->getNumArgs() < min_arguments)
87 throw d->getOperator()->getAsString() + ": too few arguments!";
90 // isDagEmpty - is this DAG marked with an empty marker?
91 bool isDagEmpty (const DagInit* d) {
92 return d->getOperator()->getAsString() == "empty";
95 // EscapeVariableName - Escape commas and other symbols not allowed
96 // in the C++ variable names. Makes it possible to use options named
97 // like "Wa," (useful for prefix options).
98 std::string EscapeVariableName(const std::string& Var) {
100 for (unsigned i = 0; i != Var.size(); ++i) {
101 char cur_char = Var[i];
102 if (cur_char == ',') {
105 else if (cur_char == '+') {
108 else if (cur_char == '-') {
112 ret.push_back(cur_char);
118 /// oneOf - Does the input string contain this character?
119 bool oneOf(const char* lst, char c) {
127 template <class I, class S>
128 void checkedIncrement(I& P, I E, S ErrorString) {
134 //===----------------------------------------------------------------------===//
135 /// Back-end specific code
138 /// OptionType - One of six different option types. See the
139 /// documentation for detailed description of differences.
140 namespace OptionType {
141 enum OptionType { Alias, Switch, Parameter, ParameterList,
144 bool IsList (OptionType t) {
145 return (t == ParameterList || t == PrefixList);
148 bool IsSwitch (OptionType t) {
149 return (t == Switch);
152 bool IsParameter (OptionType t) {
153 return (t == Parameter || t == Prefix);
158 OptionType::OptionType stringToOptionType(const std::string& T) {
159 if (T == "alias_option")
160 return OptionType::Alias;
161 else if (T == "switch_option")
162 return OptionType::Switch;
163 else if (T == "parameter_option")
164 return OptionType::Parameter;
165 else if (T == "parameter_list_option")
166 return OptionType::ParameterList;
167 else if (T == "prefix_option")
168 return OptionType::Prefix;
169 else if (T == "prefix_list_option")
170 return OptionType::PrefixList;
172 throw "Unknown option type: " + T + '!';
175 namespace OptionDescriptionFlags {
176 enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
177 ReallyHidden = 0x4, Extern = 0x8,
178 OneOrMore = 0x10, ZeroOrOne = 0x20 };
181 /// OptionDescription - Represents data contained in a single
182 /// OptionList entry.
183 struct OptionDescription {
184 OptionType::OptionType Type;
190 OptionDescription(OptionType::OptionType t = OptionType::Switch,
191 const std::string& n = "",
192 const std::string& h = DefaultHelpString)
193 : Type(t), Name(n), Flags(0x0), Help(h), MultiVal(1)
196 /// GenTypeDeclaration - Returns the C++ variable type of this
198 const char* GenTypeDeclaration() const;
200 /// GenVariableName - Returns the variable name used in the
201 /// generated C++ code.
202 std::string GenVariableName() const;
204 /// Merge - Merge two option descriptions.
205 void Merge (const OptionDescription& other);
207 // Misc convenient getters/setters.
209 bool isAlias() const;
211 bool isMultiVal() const;
213 bool isExtern() const;
216 bool isRequired() const;
219 bool isOneOrMore() const;
222 bool isZeroOrOne() const;
225 bool isHidden() const;
228 bool isReallyHidden() const;
229 void setReallyHidden();
233 void OptionDescription::Merge (const OptionDescription& other)
235 if (other.Type != Type)
236 throw "Conflicting definitions for the option " + Name + "!";
238 if (Help == other.Help || Help == DefaultHelpString)
240 else if (other.Help != DefaultHelpString) {
241 llvm::errs() << "Warning: several different help strings"
242 " defined for option " + Name + "\n";
245 Flags |= other.Flags;
248 bool OptionDescription::isAlias() const {
249 return Type == OptionType::Alias;
252 bool OptionDescription::isMultiVal() const {
256 bool OptionDescription::isExtern() const {
257 return Flags & OptionDescriptionFlags::Extern;
259 void OptionDescription::setExtern() {
260 Flags |= OptionDescriptionFlags::Extern;
263 bool OptionDescription::isRequired() const {
264 return Flags & OptionDescriptionFlags::Required;
266 void OptionDescription::setRequired() {
267 Flags |= OptionDescriptionFlags::Required;
270 bool OptionDescription::isOneOrMore() const {
271 return Flags & OptionDescriptionFlags::OneOrMore;
273 void OptionDescription::setOneOrMore() {
274 Flags |= OptionDescriptionFlags::OneOrMore;
277 bool OptionDescription::isZeroOrOne() const {
278 return Flags & OptionDescriptionFlags::ZeroOrOne;
280 void OptionDescription::setZeroOrOne() {
281 Flags |= OptionDescriptionFlags::ZeroOrOne;
284 bool OptionDescription::isHidden() const {
285 return Flags & OptionDescriptionFlags::Hidden;
287 void OptionDescription::setHidden() {
288 Flags |= OptionDescriptionFlags::Hidden;
291 bool OptionDescription::isReallyHidden() const {
292 return Flags & OptionDescriptionFlags::ReallyHidden;
294 void OptionDescription::setReallyHidden() {
295 Flags |= OptionDescriptionFlags::ReallyHidden;
298 const char* OptionDescription::GenTypeDeclaration() const {
300 case OptionType::Alias:
302 case OptionType::PrefixList:
303 case OptionType::ParameterList:
304 return "cl::list<std::string>";
305 case OptionType::Switch:
306 return "cl::opt<bool>";
307 case OptionType::Parameter:
308 case OptionType::Prefix:
310 return "cl::opt<std::string>";
314 std::string OptionDescription::GenVariableName() const {
315 const std::string& EscapedName = EscapeVariableName(Name);
317 case OptionType::Alias:
318 return "AutoGeneratedAlias_" + EscapedName;
319 case OptionType::PrefixList:
320 case OptionType::ParameterList:
321 return "AutoGeneratedList_" + EscapedName;
322 case OptionType::Switch:
323 return "AutoGeneratedSwitch_" + EscapedName;
324 case OptionType::Prefix:
325 case OptionType::Parameter:
327 return "AutoGeneratedParameter_" + EscapedName;
331 /// OptionDescriptions - An OptionDescription array plus some helper
333 class OptionDescriptions {
334 typedef StringMap<OptionDescription> container_type;
336 /// Descriptions - A list of OptionDescriptions.
337 container_type Descriptions;
340 /// FindOption - exception-throwing wrapper for find().
341 const OptionDescription& FindOption(const std::string& OptName) const;
343 /// insertDescription - Insert new OptionDescription into
344 /// OptionDescriptions list
345 void InsertDescription (const OptionDescription& o);
347 // Support for STL-style iteration
348 typedef container_type::const_iterator const_iterator;
349 const_iterator begin() const { return Descriptions.begin(); }
350 const_iterator end() const { return Descriptions.end(); }
353 const OptionDescription&
354 OptionDescriptions::FindOption(const std::string& OptName) const
356 const_iterator I = Descriptions.find(OptName);
357 if (I != Descriptions.end())
360 throw OptName + ": no such option!";
363 void OptionDescriptions::InsertDescription (const OptionDescription& o)
365 container_type::iterator I = Descriptions.find(o.Name);
366 if (I != Descriptions.end()) {
367 OptionDescription& D = I->second;
371 Descriptions[o.Name] = o;
375 /// HandlerTable - A base class for function objects implemented as
376 /// 'tables of handlers'.
380 // Implementation details.
383 typedef void (T::* Handler) (const DagInit*);
384 /// HandlerMap - A map from property names to property handlers
385 typedef StringMap<Handler> HandlerMap;
387 static HandlerMap Handlers_;
388 static bool staticMembersInitialized_;
393 HandlerTable(T* cp) : childPtr(cp)
396 /// operator() - Just forwards to the corresponding property
398 void operator() (Init* i) {
399 const DagInit& property = InitPtrToDag(i);
400 const std::string& property_name = property.getOperator()->getAsString();
401 typename HandlerMap::iterator method = Handlers_.find(property_name);
403 if (method != Handlers_.end()) {
404 Handler h = method->second;
405 (childPtr->*h)(&property);
408 throw "No handler found for property " + property_name + "!";
412 void AddHandler(const char* Property, Handler Handl) {
413 Handlers_[Property] = Handl;
417 template <class T> typename HandlerTable<T>::HandlerMap
418 HandlerTable<T>::Handlers_;
419 template <class T> bool HandlerTable<T>::staticMembersInitialized_ = false;
422 /// CollectOptionProperties - Function object for iterating over an
423 /// option property list.
424 class CollectOptionProperties : public HandlerTable<CollectOptionProperties> {
427 /// optDescs_ - OptionDescriptions table. This is where the
428 /// information is stored.
429 OptionDescription& optDesc_;
433 explicit CollectOptionProperties(OptionDescription& OD)
434 : HandlerTable<CollectOptionProperties>(this), optDesc_(OD)
436 if (!staticMembersInitialized_) {
437 AddHandler("extern", &CollectOptionProperties::onExtern);
438 AddHandler("help", &CollectOptionProperties::onHelp);
439 AddHandler("hidden", &CollectOptionProperties::onHidden);
440 AddHandler("multi_val", &CollectOptionProperties::onMultiVal);
441 AddHandler("one_or_more", &CollectOptionProperties::onOneOrMore);
442 AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
443 AddHandler("required", &CollectOptionProperties::onRequired);
444 AddHandler("zero_or_one", &CollectOptionProperties::onZeroOrOne);
446 staticMembersInitialized_ = true;
452 /// Option property handlers --
453 /// Methods that handle option properties such as (help) or (hidden).
455 void onExtern (const DagInit* d) {
456 checkNumberOfArguments(d, 0);
457 optDesc_.setExtern();
460 void onHelp (const DagInit* d) {
461 checkNumberOfArguments(d, 1);
462 optDesc_.Help = InitPtrToString(d->getArg(0));
465 void onHidden (const DagInit* d) {
466 checkNumberOfArguments(d, 0);
467 optDesc_.setHidden();
470 void onReallyHidden (const DagInit* d) {
471 checkNumberOfArguments(d, 0);
472 optDesc_.setReallyHidden();
475 void onRequired (const DagInit* d) {
476 checkNumberOfArguments(d, 0);
477 if (optDesc_.isOneOrMore())
478 throw std::string("An option can't have both (required) "
479 "and (one_or_more) properties!");
480 optDesc_.setRequired();
483 void onOneOrMore (const DagInit* d) {
484 checkNumberOfArguments(d, 0);
485 if (optDesc_.isRequired() || optDesc_.isZeroOrOne())
486 throw std::string("Only one of (required), (zero_or_one) or "
487 "(one_or_more) properties is allowed!");
488 if (!OptionType::IsList(optDesc_.Type))
489 llvm::errs() << "Warning: specifying the 'one_or_more' property "
490 "on a non-list option will have no effect.\n";
491 optDesc_.setOneOrMore();
494 void onZeroOrOne (const DagInit* d) {
495 checkNumberOfArguments(d, 0);
496 if (optDesc_.isRequired() || optDesc_.isOneOrMore())
497 throw std::string("Only one of (required), (zero_or_one) or "
498 "(one_or_more) properties is allowed!");
499 if (!OptionType::IsList(optDesc_.Type))
500 llvm::errs() << "Warning: specifying the 'zero_or_one' property"
501 "on a non-list option will have no effect.\n";
502 optDesc_.setZeroOrOne();
505 void onMultiVal (const DagInit* d) {
506 checkNumberOfArguments(d, 1);
507 int val = InitPtrToInt(d->getArg(0));
509 throw std::string("Error in the 'multi_val' property: "
510 "the value must be greater than 1!");
511 if (!OptionType::IsList(optDesc_.Type))
512 throw std::string("The multi_val property is valid only "
514 optDesc_.MultiVal = val;
519 /// AddOption - A function object that is applied to every option
520 /// description. Used by CollectOptionDescriptions.
523 OptionDescriptions& OptDescs_;
526 explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
529 void operator()(const Init* i) {
530 const DagInit& d = InitPtrToDag(i);
531 checkNumberOfArguments(&d, 1);
533 const OptionType::OptionType Type =
534 stringToOptionType(d.getOperator()->getAsString());
535 const std::string& Name = InitPtrToString(d.getArg(0));
537 OptionDescription OD(Type, Name);
540 checkNumberOfArguments(&d, 2);
543 // Aliases store the aliased option name in the 'Help' field.
544 OD.Help = InitPtrToString(d.getArg(1));
546 else if (!OD.isExtern()) {
547 processOptionProperties(&d, OD);
549 OptDescs_.InsertDescription(OD);
553 /// processOptionProperties - Go through the list of option
554 /// properties and call a corresponding handler for each.
555 static void processOptionProperties (const DagInit* d, OptionDescription& o) {
556 checkNumberOfArguments(d, 2);
557 DagInit::const_arg_iterator B = d->arg_begin();
558 // Skip the first argument: it's always the option name.
560 std::for_each(B, d->arg_end(), CollectOptionProperties(o));
565 /// CollectOptionDescriptions - Collects option properties from all
567 void CollectOptionDescriptions (RecordVector::const_iterator B,
568 RecordVector::const_iterator E,
569 OptionDescriptions& OptDescs)
571 // For every OptionList:
573 RecordVector::value_type T = *B;
574 // Throws an exception if the value does not exist.
575 ListInit* PropList = T->getValueAsListInit("options");
577 // For every option description in this list:
578 // collect the information and
579 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
583 // Tool information record
585 namespace ToolFlags {
586 enum ToolFlags { Join = 0x1, Sink = 0x2 };
589 struct ToolDescription : public RefCountedBase<ToolDescription> {
593 StrVector InLanguage;
594 std::string OutLanguage;
595 std::string OutputSuffix;
598 // Various boolean properties
599 void setSink() { Flags |= ToolFlags::Sink; }
600 bool isSink() const { return Flags & ToolFlags::Sink; }
601 void setJoin() { Flags |= ToolFlags::Join; }
602 bool isJoin() const { return Flags & ToolFlags::Join; }
604 // Default ctor here is needed because StringMap can only store
605 // DefaultConstructible objects
606 ToolDescription() : CmdLine(0), Actions(0), Flags(0) {}
607 ToolDescription (const std::string& n)
608 : Name(n), CmdLine(0), Actions(0), Flags(0)
612 /// ToolDescriptions - A list of Tool information records.
613 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
616 /// CollectToolProperties - Function object for iterating over a list of
617 /// tool property records.
618 class CollectToolProperties : public HandlerTable<CollectToolProperties> {
621 /// toolDesc_ - Properties of the current Tool. This is where the
622 /// information is stored.
623 ToolDescription& toolDesc_;
627 explicit CollectToolProperties (ToolDescription& d)
628 : HandlerTable<CollectToolProperties>(this) , toolDesc_(d)
630 if (!staticMembersInitialized_) {
632 AddHandler("actions", &CollectToolProperties::onActions);
633 AddHandler("cmd_line", &CollectToolProperties::onCmdLine);
634 AddHandler("in_language", &CollectToolProperties::onInLanguage);
635 AddHandler("join", &CollectToolProperties::onJoin);
636 AddHandler("out_language", &CollectToolProperties::onOutLanguage);
637 AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
638 AddHandler("sink", &CollectToolProperties::onSink);
640 staticMembersInitialized_ = true;
646 /// Property handlers --
647 /// Functions that extract information about tool properties from
648 /// DAG representation.
650 void onActions (const DagInit* d) {
651 checkNumberOfArguments(d, 1);
652 Init* Case = d->getArg(0);
653 if (typeid(*Case) != typeid(DagInit) ||
654 static_cast<DagInit*>(Case)->getOperator()->getAsString() != "case")
656 std::string("The argument to (actions) should be a 'case' construct!");
657 toolDesc_.Actions = Case;
660 void onCmdLine (const DagInit* d) {
661 checkNumberOfArguments(d, 1);
662 toolDesc_.CmdLine = d->getArg(0);
665 void onInLanguage (const DagInit* d) {
666 checkNumberOfArguments(d, 1);
667 Init* arg = d->getArg(0);
669 // Find out the argument's type.
670 if (typeid(*arg) == typeid(StringInit)) {
672 toolDesc_.InLanguage.push_back(InitPtrToString(arg));
676 const ListInit& lst = InitPtrToList(arg);
677 StrVector& out = toolDesc_.InLanguage;
679 // Copy strings to the output vector.
680 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
682 out.push_back(InitPtrToString(*B));
685 // Remove duplicates.
686 std::sort(out.begin(), out.end());
687 StrVector::iterator newE = std::unique(out.begin(), out.end());
688 out.erase(newE, out.end());
692 void onJoin (const DagInit* d) {
693 checkNumberOfArguments(d, 0);
697 void onOutLanguage (const DagInit* d) {
698 checkNumberOfArguments(d, 1);
699 toolDesc_.OutLanguage = InitPtrToString(d->getArg(0));
702 void onOutputSuffix (const DagInit* d) {
703 checkNumberOfArguments(d, 1);
704 toolDesc_.OutputSuffix = InitPtrToString(d->getArg(0));
707 void onSink (const DagInit* d) {
708 checkNumberOfArguments(d, 0);
714 /// CollectToolDescriptions - Gather information about tool properties
715 /// from the parsed TableGen data (basically a wrapper for the
716 /// CollectToolProperties function object).
717 void CollectToolDescriptions (RecordVector::const_iterator B,
718 RecordVector::const_iterator E,
719 ToolDescriptions& ToolDescs)
721 // Iterate over a properties list of every Tool definition
723 const Record* T = *B;
724 // Throws an exception if the value does not exist.
725 ListInit* PropList = T->getValueAsListInit("properties");
727 IntrusiveRefCntPtr<ToolDescription>
728 ToolDesc(new ToolDescription(T->getName()));
730 std::for_each(PropList->begin(), PropList->end(),
731 CollectToolProperties(*ToolDesc));
732 ToolDescs.push_back(ToolDesc);
736 /// FillInEdgeVector - Merge all compilation graph definitions into
737 /// one single edge list.
738 void FillInEdgeVector(RecordVector::const_iterator B,
739 RecordVector::const_iterator E, RecordVector& Out) {
740 for (; B != E; ++B) {
741 const ListInit* edges = (*B)->getValueAsListInit("edges");
743 for (unsigned i = 0; i < edges->size(); ++i)
744 Out.push_back(edges->getElementAsRecord(i));
748 /// CalculatePriority - Calculate the priority of this plugin.
749 int CalculatePriority(RecordVector::const_iterator B,
750 RecordVector::const_iterator E) {
753 total += static_cast<int>((*B)->getValueAsInt("priority"));
758 /// NotInGraph - Helper function object for FilterNotInGraph.
761 const llvm::StringSet<>& ToolsInGraph_;
764 NotInGraph(const llvm::StringSet<>& ToolsInGraph)
765 : ToolsInGraph_(ToolsInGraph)
768 bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
769 return (ToolsInGraph_.count(x->Name) == 0);
773 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
774 /// mentioned in the compilation graph definition.
775 void FilterNotInGraph (const RecordVector& EdgeVector,
776 ToolDescriptions& ToolDescs) {
778 // List all tools mentioned in the graph.
779 llvm::StringSet<> ToolsInGraph;
781 for (RecordVector::const_iterator B = EdgeVector.begin(),
782 E = EdgeVector.end(); B != E; ++B) {
784 const Record* Edge = *B;
785 const std::string& NodeA = Edge->getValueAsString("a");
786 const std::string& NodeB = Edge->getValueAsString("b");
789 ToolsInGraph.insert(NodeA);
790 ToolsInGraph.insert(NodeB);
793 // Filter ToolPropertiesList.
794 ToolDescriptions::iterator new_end =
795 std::remove_if(ToolDescs.begin(), ToolDescs.end(),
796 NotInGraph(ToolsInGraph));
797 ToolDescs.erase(new_end, ToolDescs.end());
800 /// FillInToolToLang - Fills in two tables that map tool names to
801 /// (input, output) languages. Helper function used by TypecheckGraph().
802 void FillInToolToLang (const ToolDescriptions& ToolDescs,
803 StringMap<StringSet<> >& ToolToInLang,
804 StringMap<std::string>& ToolToOutLang) {
805 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
806 E = ToolDescs.end(); B != E; ++B) {
807 const ToolDescription& D = *(*B);
808 for (StrVector::const_iterator B = D.InLanguage.begin(),
809 E = D.InLanguage.end(); B != E; ++B)
810 ToolToInLang[D.Name].insert(*B);
811 ToolToOutLang[D.Name] = D.OutLanguage;
815 /// TypecheckGraph - Check that names for output and input languages
816 /// on all edges do match. This doesn't do much when the information
817 /// about the whole graph is not available (i.e. when compiling most
819 void TypecheckGraph (const RecordVector& EdgeVector,
820 const ToolDescriptions& ToolDescs) {
821 StringMap<StringSet<> > ToolToInLang;
822 StringMap<std::string> ToolToOutLang;
824 FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
825 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
826 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
828 for (RecordVector::const_iterator B = EdgeVector.begin(),
829 E = EdgeVector.end(); B != E; ++B) {
830 const Record* Edge = *B;
831 const std::string& NodeA = Edge->getValueAsString("a");
832 const std::string& NodeB = Edge->getValueAsString("b");
833 StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
834 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
836 if (NodeA != "root") {
837 if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
838 throw "Edge " + NodeA + "->" + NodeB
839 + ": output->input language mismatch";
843 throw std::string("Edges back to the root are not allowed!");
847 /// WalkCase - Walks the 'case' expression DAG and invokes
848 /// TestCallback on every test, and StatementCallback on every
849 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
851 // TODO: Re-implement EmitCaseConstructHandler on top of this function?
852 template <typename F1, typename F2>
853 void WalkCase(Init* Case, F1 TestCallback, F2 StatementCallback) {
854 const DagInit& d = InitPtrToDag(Case);
856 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
859 if (even && dynamic_cast<DagInit*>(arg)
860 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
861 WalkCase(arg, TestCallback, StatementCallback);
865 StatementCallback(arg);
870 /// ExtractOptionNames - A helper function object used by
871 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
872 class ExtractOptionNames {
873 llvm::StringSet<>& OptionNames_;
875 void processDag(const Init* Statement) {
876 const DagInit& Stmt = InitPtrToDag(Statement);
877 const std::string& ActionName = Stmt.getOperator()->getAsString();
878 if (ActionName == "forward" || ActionName == "forward_as" ||
879 ActionName == "unpack_values" || ActionName == "switch_on" ||
880 ActionName == "parameter_equals" || ActionName == "element_in_list" ||
881 ActionName == "not_empty" || ActionName == "empty") {
882 checkNumberOfArguments(&Stmt, 1);
883 const std::string& Name = InitPtrToString(Stmt.getArg(0));
884 OptionNames_.insert(Name);
886 else if (ActionName == "and" || ActionName == "or") {
887 for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
888 this->processDag(Stmt.getArg(i));
894 ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
897 void operator()(const Init* Statement) {
898 if (typeid(*Statement) == typeid(ListInit)) {
899 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
900 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
902 this->processDag(*B);
905 this->processDag(Statement);
910 /// CheckForSuperfluousOptions - Check that there are no side
911 /// effect-free options (specified only in the OptionList). Otherwise,
912 /// output a warning.
913 void CheckForSuperfluousOptions (const RecordVector& Edges,
914 const ToolDescriptions& ToolDescs,
915 const OptionDescriptions& OptDescs) {
916 llvm::StringSet<> nonSuperfluousOptions;
918 // Add all options mentioned in the ToolDesc.Actions to the set of
919 // non-superfluous options.
920 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
921 E = ToolDescs.end(); B != E; ++B) {
922 const ToolDescription& TD = *(*B);
923 ExtractOptionNames Callback(nonSuperfluousOptions);
925 WalkCase(TD.Actions, Callback, Callback);
928 // Add all options mentioned in the 'case' clauses of the
929 // OptionalEdges of the compilation graph to the set of
930 // non-superfluous options.
931 for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
933 const Record* Edge = *B;
934 DagInit* Weight = Edge->getValueAsDag("weight");
936 if (!isDagEmpty(Weight))
937 WalkCase(Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
940 // Check that all options in OptDescs belong to the set of
941 // non-superfluous options.
942 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
943 E = OptDescs.end(); B != E; ++B) {
944 const OptionDescription& Val = B->second;
945 if (!nonSuperfluousOptions.count(Val.Name)
946 && Val.Type != OptionType::Alias)
947 llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! "
948 "Probable cause: this option is specified only in the OptionList.\n";
952 /// EmitCaseTest1Arg - Helper function used by
953 /// EmitCaseConstructHandler.
954 bool EmitCaseTest1Arg(const std::string& TestName,
956 const OptionDescriptions& OptDescs,
958 checkNumberOfArguments(&d, 1);
959 const std::string& OptName = InitPtrToString(d.getArg(0));
961 if (TestName == "switch_on") {
962 const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
963 if (!OptionType::IsSwitch(OptDesc.Type))
964 throw OptName + ": incorrect option type - should be a switch!";
965 O << OptDesc.GenVariableName();
967 } else if (TestName == "input_languages_contain") {
968 O << "InLangs.count(\"" << OptName << "\") != 0";
970 } else if (TestName == "in_language") {
971 // This works only for single-argument Tool::GenerateAction. Join
972 // tools can process several files in different languages simultaneously.
974 // TODO: make this work with Edge::Weight (if possible).
975 O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
977 } else if (TestName == "not_empty" || TestName == "empty") {
978 const char* Test = (TestName == "empty") ? "" : "!";
980 if (OptName == "o") {
981 O << Test << "OutputFilename.empty()";
985 const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
986 if (OptionType::IsSwitch(OptDesc.Type))
988 + ": incorrect option type - should be a list or parameter!";
989 O << Test << OptDesc.GenVariableName() << ".empty()";
997 /// EmitCaseTest2Args - Helper function used by
998 /// EmitCaseConstructHandler.
999 bool EmitCaseTest2Args(const std::string& TestName,
1001 const char* IndentLevel,
1002 const OptionDescriptions& OptDescs,
1004 checkNumberOfArguments(&d, 2);
1005 const std::string& OptName = InitPtrToString(d.getArg(0));
1006 const std::string& OptArg = InitPtrToString(d.getArg(1));
1007 const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
1009 if (TestName == "parameter_equals") {
1010 if (!OptionType::IsParameter(OptDesc.Type))
1011 throw OptName + ": incorrect option type - should be a parameter!";
1012 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
1015 else if (TestName == "element_in_list") {
1016 if (!OptionType::IsList(OptDesc.Type))
1017 throw OptName + ": incorrect option type - should be a list!";
1018 const std::string& VarName = OptDesc.GenVariableName();
1019 O << "std::find(" << VarName << ".begin(),\n"
1020 << IndentLevel << Indent1 << VarName << ".end(), \""
1021 << OptArg << "\") != " << VarName << ".end()";
1028 // Forward declaration.
1029 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
1030 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
1031 const OptionDescriptions& OptDescs,
1034 /// EmitLogicalOperationTest - Helper function used by
1035 /// EmitCaseConstructHandler.
1036 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
1037 const char* IndentLevel,
1038 const OptionDescriptions& OptDescs,
1041 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
1042 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
1043 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1044 if (j != NumArgs - 1)
1045 O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
1051 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
1052 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
1053 const OptionDescriptions& OptDescs,
1055 const std::string& TestName = d.getOperator()->getAsString();
1057 if (TestName == "and")
1058 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
1059 else if (TestName == "or")
1060 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
1061 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
1063 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
1066 throw TestName + ": unknown edge property!";
1069 // Emit code that handles the 'case' construct.
1070 // Takes a function object that should emit code for every case clause.
1071 // Callback's type is
1072 // void F(Init* Statement, const char* IndentLevel, raw_ostream& O).
1073 template <typename F>
1074 void EmitCaseConstructHandler(const Init* Dag, const char* IndentLevel,
1075 F Callback, bool EmitElseIf,
1076 const OptionDescriptions& OptDescs,
1078 const DagInit* d = &InitPtrToDag(Dag);
1079 if (d->getOperator()->getAsString() != "case")
1080 throw std::string("EmitCaseConstructHandler should be invoked"
1081 " only on 'case' expressions!");
1083 unsigned numArgs = d->getNumArgs();
1084 if (d->getNumArgs() < 2)
1085 throw "There should be at least one clause in the 'case' expression:\n"
1088 for (unsigned i = 0; i != numArgs; ++i) {
1089 const DagInit& Test = InitPtrToDag(d->getArg(i));
1092 if (Test.getOperator()->getAsString() == "default") {
1094 throw std::string("The 'default' clause should be the last in the"
1095 "'case' construct!");
1096 O << IndentLevel << "else {\n";
1099 O << IndentLevel << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
1100 EmitCaseTest(Test, IndentLevel, OptDescs, O);
1104 // Emit the corresponding statement.
1107 throw "Case construct handler: no corresponding action "
1108 "found for the test " + Test.getAsString() + '!';
1110 Init* arg = d->getArg(i);
1111 const DagInit* nd = dynamic_cast<DagInit*>(arg);
1112 if (nd && (nd->getOperator()->getAsString() == "case")) {
1113 // Handle the nested 'case'.
1114 EmitCaseConstructHandler(nd, (std::string(IndentLevel) + Indent1).c_str(),
1115 Callback, EmitElseIf, OptDescs, O);
1118 Callback(arg, (std::string(IndentLevel) + Indent1).c_str(), O);
1120 O << IndentLevel << "}\n";
1124 /// TokenizeCmdline - converts from "$CALL(HookName, 'Arg1', 'Arg2')/path" to
1125 /// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path"] .
1126 /// Helper function used by EmitCmdLineVecFill and.
1127 void TokenizeCmdline(const std::string& CmdLine, StrVector& Out) {
1128 const char* Delimiters = " \t\n\v\f\r";
1130 { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1133 if (CmdLine.empty())
1137 std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1140 for (; B != E; ++B) {
1141 char cur_ch = CmdLine[B];
1145 if (cur_ch == '$') {
1146 cur_st = SpecialCommand;
1149 if (oneOf(Delimiters, cur_ch)) {
1151 B = CmdLine.find_first_not_of(Delimiters, B);
1152 if (B == std::string::npos) {
1163 case SpecialCommand:
1164 if (oneOf(Delimiters, cur_ch)) {
1169 if (cur_ch == '(') {
1171 cur_st = InsideSpecialCommand;
1176 case InsideSpecialCommand:
1177 if (oneOf(Delimiters, cur_ch)) {
1180 if (cur_ch == '\'') {
1181 cur_st = InsideQuotationMarks;
1185 if (cur_ch == ')') {
1189 if (cur_ch == ',') {
1195 case InsideQuotationMarks:
1196 if (cur_ch == '\'') {
1197 cur_st = InsideSpecialCommand;
1203 Out.back().push_back(cur_ch);
1207 /// SubstituteSpecialCommands - Perform string substitution for $CALL
1208 /// and $ENV. Helper function used by EmitCmdLineVecFill().
1209 StrVector::const_iterator SubstituteSpecialCommands
1210 (StrVector::const_iterator Pos, StrVector::const_iterator End, raw_ostream& O)
1213 const std::string& cmd = *Pos;
1215 if (cmd == "$CALL") {
1216 checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1217 const std::string& CmdName = *Pos;
1220 throw std::string("$CALL invocation: empty argument list!");
1223 O << CmdName << "(";
1226 bool firstIteration = true;
1228 checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1229 const std::string& Arg = *Pos;
1230 assert(Arg.size() != 0);
1236 firstIteration = false;
1240 O << '"' << Arg << '"';
1246 else if (cmd == "$ENV") {
1247 checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1248 const std::string& EnvName = *Pos;
1251 throw "$ENV invocation: empty argument list!";
1253 O << "checkCString(std::getenv(\"";
1257 checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1260 throw "Unknown special command: " + cmd;
1263 const std::string& Leftover = *Pos;
1264 assert(Leftover.at(0) == ')');
1265 if (Leftover.size() != 1)
1266 O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1271 /// EmitCmdLineVecFill - Emit code that fills in the command line
1272 /// vector. Helper function used by EmitGenerateActionMethod().
1273 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1274 bool IsJoin, const char* IndentLevel,
1277 TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1280 throw "Tool '" + ToolName + "' has empty command line!";
1282 StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1284 // If there is a hook invocation on the place of the first command, skip it.
1285 assert(!StrVec[0].empty());
1286 if (StrVec[0][0] == '$') {
1287 while (I != E && (*I)[0] != ')' )
1290 // Skip the ')' symbol.
1297 for (; I != E; ++I) {
1298 const std::string& cmd = *I;
1299 assert(!cmd.empty());
1301 if (cmd.at(0) == '$') {
1302 if (cmd == "$INFILE") {
1304 O << "for (PathVector::const_iterator B = inFiles.begin()"
1305 << ", E = inFiles.end();\n"
1306 << IndentLevel << "B != E; ++B)\n"
1307 << IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
1309 O << "vec.push_back(inFile.toString());\n";
1311 else if (cmd == "$OUTFILE") {
1312 O << "vec.push_back(out_file);\n";
1315 O << "vec.push_back(";
1316 I = SubstituteSpecialCommands(I, E, O);
1321 O << "vec.push_back(\"" << cmd << "\");\n";
1324 O << IndentLevel << "cmd = ";
1326 if (StrVec[0][0] == '$')
1327 SubstituteSpecialCommands(StrVec.begin(), StrVec.end(), O);
1329 O << '"' << StrVec[0] << '"';
1333 /// EmitCmdLineVecFillCallback - A function object wrapper around
1334 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1335 /// argument to EmitCaseConstructHandler().
1336 class EmitCmdLineVecFillCallback {
1338 const std::string& ToolName;
1340 EmitCmdLineVecFillCallback(bool J, const std::string& TN)
1341 : IsJoin(J), ToolName(TN) {}
1343 void operator()(const Init* Statement, const char* IndentLevel,
1344 raw_ostream& O) const
1346 EmitCmdLineVecFill(Statement, ToolName, IsJoin,
1351 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1352 /// implement EmitActionHandler. Emits code for
1353 /// handling the (forward) and (forward_as) option properties.
1354 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1356 const std::string& NewName,
1358 const std::string& Name = NewName.empty()
1363 case OptionType::Switch:
1364 O << Indent << "vec.push_back(\"" << Name << "\");\n";
1366 case OptionType::Parameter:
1367 O << Indent << "vec.push_back(\"" << Name << "\");\n";
1368 O << Indent << "vec.push_back(" << D.GenVariableName() << ");\n";
1370 case OptionType::Prefix:
1371 O << Indent << "vec.push_back(\"" << Name << "\" + "
1372 << D.GenVariableName() << ");\n";
1374 case OptionType::PrefixList:
1375 O << Indent << "for (" << D.GenTypeDeclaration()
1376 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1377 << Indent << "E = " << D.GenVariableName() << ".end(); B != E;) {\n"
1378 << Indent << Indent1 << "vec.push_back(\"" << Name << "\" + "
1380 << Indent << Indent1 << "++B;\n";
1382 for (int i = 1, j = D.MultiVal; i < j; ++i) {
1383 O << Indent << Indent1 << "vec.push_back(*B);\n"
1384 << Indent << Indent1 << "++B;\n";
1387 O << Indent << "}\n";
1389 case OptionType::ParameterList:
1390 O << Indent << "for (" << D.GenTypeDeclaration()
1391 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1392 << Indent << "E = " << D.GenVariableName()
1393 << ".end() ; B != E;) {\n"
1394 << Indent << Indent1 << "vec.push_back(\"" << Name << "\");\n";
1396 for (int i = 0, j = D.MultiVal; i < j; ++i) {
1397 O << Indent << Indent1 << "vec.push_back(*B);\n"
1398 << Indent << Indent1 << "++B;\n";
1401 O << Indent << "}\n";
1403 case OptionType::Alias:
1405 throw std::string("Aliases are not allowed in tool option descriptions!");
1409 /// EmitActionHandler - Emit code that handles actions. Used by
1410 /// EmitGenerateActionMethod() as an argument to
1411 /// EmitCaseConstructHandler().
1412 class EmitActionHandler {
1413 const OptionDescriptions& OptDescs;
1415 void processActionDag(const Init* Statement, const char* IndentLevel,
1416 raw_ostream& O) const
1418 const DagInit& Dag = InitPtrToDag(Statement);
1419 const std::string& ActionName = Dag.getOperator()->getAsString();
1421 if (ActionName == "append_cmd") {
1422 checkNumberOfArguments(&Dag, 1);
1423 const std::string& Cmd = InitPtrToString(Dag.getArg(0));
1425 llvm::SplitString(Cmd, Out);
1427 for (StrVector::const_iterator B = Out.begin(), E = Out.end();
1429 O << IndentLevel << "vec.push_back(\"" << *B << "\");\n";
1431 else if (ActionName == "error") {
1432 O << IndentLevel << "throw std::runtime_error(\"" <<
1433 (Dag.getNumArgs() >= 1 ? InitPtrToString(Dag.getArg(0))
1437 else if (ActionName == "forward") {
1438 checkNumberOfArguments(&Dag, 1);
1439 const std::string& Name = InitPtrToString(Dag.getArg(0));
1440 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1441 IndentLevel, "", O);
1443 else if (ActionName == "forward_as") {
1444 checkNumberOfArguments(&Dag, 2);
1445 const std::string& Name = InitPtrToString(Dag.getArg(0));
1446 const std::string& NewName = InitPtrToString(Dag.getArg(1));
1447 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1448 IndentLevel, NewName, O);
1450 else if (ActionName == "output_suffix") {
1451 checkNumberOfArguments(&Dag, 1);
1452 const std::string& OutSuf = InitPtrToString(Dag.getArg(0));
1453 O << IndentLevel << "output_suffix = \"" << OutSuf << "\";\n";
1455 else if (ActionName == "stop_compilation") {
1456 O << IndentLevel << "stop_compilation = true;\n";
1458 else if (ActionName == "unpack_values") {
1459 checkNumberOfArguments(&Dag, 1);
1460 const std::string& Name = InitPtrToString(Dag.getArg(0));
1461 const OptionDescription& D = OptDescs.FindOption(Name);
1464 throw std::string("Can't use unpack_values with multi-valued options!");
1466 if (OptionType::IsList(D.Type)) {
1467 O << IndentLevel << "for (" << D.GenTypeDeclaration()
1468 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1469 << IndentLevel << "E = " << D.GenVariableName()
1470 << ".end(); B != E; ++B)\n"
1471 << IndentLevel << Indent1 << "llvm::SplitString(*B, vec, \",\");\n";
1473 else if (OptionType::IsParameter(D.Type)){
1474 O << Indent3 << "llvm::SplitString("
1475 << D.GenVariableName() << ", vec, \",\");\n";
1478 throw "Option '" + D.Name +
1479 "': switches can't have the 'unpack_values' property!";
1483 throw "Unknown action name: " + ActionName + "!";
1487 EmitActionHandler(const OptionDescriptions& OD)
1490 void operator()(const Init* Statement, const char* IndentLevel,
1491 raw_ostream& O) const
1493 if (typeid(*Statement) == typeid(ListInit)) {
1494 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1495 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1497 this->processActionDag(*B, IndentLevel, O);
1500 this->processActionDag(Statement, IndentLevel, O);
1505 // EmitGenerateActionMethod - Emit one of two versions of the
1506 // Tool::GenerateAction() method.
1507 void EmitGenerateActionMethod (const ToolDescription& D,
1508 const OptionDescriptions& OptDescs,
1509 bool IsJoin, raw_ostream& O) {
1511 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
1513 O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
1515 O << Indent2 << "bool HasChildren,\n"
1516 << Indent2 << "const llvm::sys::Path& TempDir,\n"
1517 << Indent2 << "const InputLanguagesSet& InLangs,\n"
1518 << Indent2 << "const LanguageMap& LangMap) const\n"
1520 << Indent2 << "std::string cmd;\n"
1521 << Indent2 << "std::vector<std::string> vec;\n"
1522 << Indent2 << "bool stop_compilation = !HasChildren;\n"
1523 << Indent2 << "const char* output_suffix = \"" << D.OutputSuffix << "\";\n"
1524 << Indent2 << "std::string out_file;\n\n";
1526 // For every understood option, emit handling code.
1528 EmitCaseConstructHandler(D.Actions, Indent2, EmitActionHandler(OptDescs),
1529 false, OptDescs, O);
1531 O << '\n' << Indent2
1532 << "out_file = OutFilename(" << (IsJoin ? "sys::Path(),\n" : "inFile,\n")
1533 << Indent3 << "TempDir, stop_compilation, output_suffix).toString();\n\n";
1535 // cmd_line is either a string or a 'case' construct.
1537 throw "Tool " + D.Name + " has no cmd_line property!";
1538 else if (typeid(*D.CmdLine) == typeid(StringInit))
1539 EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
1541 EmitCaseConstructHandler(D.CmdLine, Indent2,
1542 EmitCmdLineVecFillCallback(IsJoin, D.Name),
1545 // Handle the Sink property.
1547 O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
1548 << Indent3 << "vec.insert(vec.end(), "
1549 << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
1550 << Indent2 << "}\n";
1553 O << Indent2 << "return Action(cmd, vec, stop_compilation, out_file);\n"
1554 << Indent1 << "}\n\n";
1557 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1558 /// a given Tool class.
1559 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
1560 const OptionDescriptions& OptDescs,
1562 if (!ToolDesc.isJoin())
1563 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
1564 << Indent2 << "bool HasChildren,\n"
1565 << Indent2 << "const llvm::sys::Path& TempDir,\n"
1566 << Indent2 << "const InputLanguagesSet& InLangs,\n"
1567 << Indent2 << "const LanguageMap& LangMap) const\n"
1569 << Indent2 << "throw std::runtime_error(\"" << ToolDesc.Name
1570 << " is not a Join tool!\");\n"
1571 << Indent1 << "}\n\n";
1573 EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
1575 EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
1578 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1579 /// methods for a given Tool class.
1580 void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
1581 O << Indent1 << "const char** InputLanguages() const {\n"
1582 << Indent2 << "return InputLanguages_;\n"
1583 << Indent1 << "}\n\n";
1585 if (D.OutLanguage.empty())
1586 throw "Tool " + D.Name + " has no 'out_language' property!";
1588 O << Indent1 << "const char* OutputLanguage() const {\n"
1589 << Indent2 << "return \"" << D.OutLanguage << "\";\n"
1590 << Indent1 << "}\n\n";
1593 /// EmitNameMethod - Emit the Name() method for a given Tool class.
1594 void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
1595 O << Indent1 << "const char* Name() const {\n"
1596 << Indent2 << "return \"" << D.Name << "\";\n"
1597 << Indent1 << "}\n\n";
1600 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1602 void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
1603 O << Indent1 << "bool IsJoin() const {\n";
1605 O << Indent2 << "return true;\n";
1607 O << Indent2 << "return false;\n";
1608 O << Indent1 << "}\n\n";
1611 /// EmitStaticMemberDefinitions - Emit static member definitions for a
1612 /// given Tool class.
1613 void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
1614 if (D.InLanguage.empty())
1615 throw "Tool " + D.Name + " has no 'in_language' property!";
1617 O << "const char* " << D.Name << "::InputLanguages_[] = {";
1618 for (StrVector::const_iterator B = D.InLanguage.begin(),
1619 E = D.InLanguage.end(); B != E; ++B)
1620 O << '\"' << *B << "\", ";
1624 /// EmitToolClassDefinition - Emit a Tool class definition.
1625 void EmitToolClassDefinition (const ToolDescription& D,
1626 const OptionDescriptions& OptDescs,
1628 if (D.Name == "root")
1632 O << "class " << D.Name << " : public ";
1638 O << "{\nprivate:\n"
1639 << Indent1 << "static const char* InputLanguages_[];\n\n";
1642 EmitNameMethod(D, O);
1643 EmitInOutLanguageMethods(D, O);
1644 EmitIsJoinMethod(D, O);
1645 EmitGenerateActionMethods(D, OptDescs, O);
1647 // Close class definition
1650 EmitStaticMemberDefinitions(D, O);
1654 /// EmitOptionDefinitions - Iterate over a list of option descriptions
1655 /// and emit registration code.
1656 void EmitOptionDefinitions (const OptionDescriptions& descs,
1657 bool HasSink, bool HasExterns,
1660 std::vector<OptionDescription> Aliases;
1662 // Emit static cl::Option variables.
1663 for (OptionDescriptions::const_iterator B = descs.begin(),
1664 E = descs.end(); B!=E; ++B) {
1665 const OptionDescription& val = B->second;
1667 if (val.Type == OptionType::Alias) {
1668 Aliases.push_back(val);
1675 O << val.GenTypeDeclaration() << ' '
1676 << val.GenVariableName();
1678 if (val.isExtern()) {
1683 O << "(\"" << val.Name << "\"\n";
1685 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1686 O << ", cl::Prefix";
1688 if (val.isRequired()) {
1689 if (OptionType::IsList(val.Type) && !val.isMultiVal())
1690 O << ", cl::OneOrMore";
1692 O << ", cl::Required";
1694 else if (val.isOneOrMore() && OptionType::IsList(val.Type)) {
1695 O << ", cl::OneOrMore";
1697 else if (val.isZeroOrOne() && OptionType::IsList(val.Type)) {
1698 O << ", cl::ZeroOrOne";
1701 if (val.isReallyHidden()) {
1702 O << ", cl::ReallyHidden";
1704 else if (val.isHidden()) {
1705 O << ", cl::Hidden";
1708 if (val.MultiVal > 1)
1709 O << ", cl::multi_val(" << val.MultiVal << ")";
1711 if (!val.Help.empty())
1712 O << ", cl::desc(\"" << val.Help << "\")";
1717 // Emit the aliases (they should go after all the 'proper' options).
1718 for (std::vector<OptionDescription>::const_iterator
1719 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
1720 const OptionDescription& val = *B;
1722 O << val.GenTypeDeclaration() << ' '
1723 << val.GenVariableName()
1724 << "(\"" << val.Name << '\"';
1726 const OptionDescription& D = descs.FindOption(val.Help);
1727 O << ", cl::aliasopt(" << D.GenVariableName() << ")";
1729 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
1732 // Emit the sink option.
1734 O << (HasExterns ? "extern cl" : "cl")
1735 << "::list<std::string> " << SinkOptionName
1736 << (HasExterns ? ";\n" : "(cl::Sink);\n");
1741 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
1742 void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
1745 O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
1747 // Get the relevant field out of RecordKeeper
1748 const Record* LangMapRecord = Records.getDef("LanguageMap");
1750 // It is allowed for a plugin to have no language map.
1751 if (LangMapRecord) {
1753 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
1754 if (!LangsToSuffixesList)
1755 throw std::string("Error in the language map definition!");
1757 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
1758 const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
1760 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
1761 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
1763 for (unsigned i = 0; i < Suffixes->size(); ++i)
1764 O << Indent1 << "langMap[\""
1765 << InitPtrToString(Suffixes->getElement(i))
1766 << "\"] = \"" << Lang << "\";\n";
1773 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
1774 /// by EmitEdgeClass().
1775 void IncDecWeight (const Init* i, const char* IndentLevel,
1777 const DagInit& d = InitPtrToDag(i);
1778 const std::string& OpName = d.getOperator()->getAsString();
1780 if (OpName == "inc_weight") {
1781 O << IndentLevel << "ret += ";
1783 else if (OpName == "dec_weight") {
1784 O << IndentLevel << "ret -= ";
1786 else if (OpName == "error") {
1787 O << IndentLevel << "throw std::runtime_error(\"" <<
1788 (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0))
1795 throw "Unknown operator in edge properties list: " + OpName + '!' +
1796 "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
1798 if (d.getNumArgs() > 0)
1799 O << InitPtrToInt(d.getArg(0)) << ";\n";
1805 /// EmitEdgeClass - Emit a single Edge# class.
1806 void EmitEdgeClass (unsigned N, const std::string& Target,
1807 DagInit* Case, const OptionDescriptions& OptDescs,
1810 // Class constructor.
1811 O << "class Edge" << N << ": public Edge {\n"
1813 << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1816 // Function Weight().
1817 << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
1818 << Indent2 << "unsigned ret = 0;\n";
1820 // Handle the 'case' construct.
1821 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
1823 O << Indent2 << "return ret;\n"
1824 << Indent1 << "};\n\n};\n\n";
1827 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
1828 void EmitEdgeClasses (const RecordVector& EdgeVector,
1829 const OptionDescriptions& OptDescs,
1832 for (RecordVector::const_iterator B = EdgeVector.begin(),
1833 E = EdgeVector.end(); B != E; ++B) {
1834 const Record* Edge = *B;
1835 const std::string& NodeB = Edge->getValueAsString("b");
1836 DagInit* Weight = Edge->getValueAsDag("weight");
1838 if (!isDagEmpty(Weight))
1839 EmitEdgeClass(i, NodeB, Weight, OptDescs, O);
1844 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1846 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
1847 const ToolDescriptions& ToolDescs,
1850 O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
1852 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1853 E = ToolDescs.end(); B != E; ++B)
1854 O << Indent1 << "G.insertNode(new " << (*B)->Name << "());\n";
1861 for (RecordVector::const_iterator B = EdgeVector.begin(),
1862 E = EdgeVector.end(); B != E; ++B) {
1863 const Record* Edge = *B;
1864 const std::string& NodeA = Edge->getValueAsString("a");
1865 const std::string& NodeB = Edge->getValueAsString("b");
1866 DagInit* Weight = Edge->getValueAsDag("weight");
1868 O << Indent1 << "G.insertEdge(\"" << NodeA << "\", ";
1870 if (isDagEmpty(Weight))
1871 O << "new SimpleEdge(\"" << NodeB << "\")";
1873 O << "new Edge" << i << "()";
1882 /// ExtractHookNames - Extract the hook names from all instances of
1883 /// $CALL(HookName) in the provided command line string. Helper
1884 /// function used by FillInHookNames().
1885 class ExtractHookNames {
1886 llvm::StringMap<unsigned>& HookNames_;
1888 ExtractHookNames(llvm::StringMap<unsigned>& HookNames)
1889 : HookNames_(HookNames) {}
1891 void operator()(const Init* CmdLine) {
1893 TokenizeCmdline(InitPtrToString(CmdLine), cmds);
1894 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
1896 const std::string& cmd = *B;
1898 if (cmd == "$CALL") {
1899 unsigned NumArgs = 0;
1900 checkedIncrement(B, E, "Syntax error in $CALL invocation!");
1901 const std::string& HookName = *B;
1904 if (HookName.at(0) == ')')
1905 throw "$CALL invoked with no arguments!";
1907 while (++B != E && B->at(0) != ')') {
1911 StringMap<unsigned>::const_iterator H = HookNames_.find(HookName);
1913 if (H != HookNames_.end() && H->second != NumArgs)
1914 throw "Overloading of hooks is not allowed. Overloaded hook: "
1917 HookNames_[HookName] = NumArgs;
1924 /// FillInHookNames - Actually extract the hook names from all command
1925 /// line strings. Helper function used by EmitHookDeclarations().
1926 void FillInHookNames(const ToolDescriptions& ToolDescs,
1927 llvm::StringMap<unsigned>& HookNames)
1929 // For all command lines:
1930 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1931 E = ToolDescs.end(); B != E; ++B) {
1932 const ToolDescription& D = *(*B);
1935 if (dynamic_cast<StringInit*>(D.CmdLine))
1936 // This is a string.
1937 ExtractHookNames(HookNames).operator()(D.CmdLine);
1939 // This is a 'case' construct.
1940 WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames));
1944 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
1945 /// property records and emit hook function declaration for each
1946 /// instance of $CALL(HookName).
1947 void EmitHookDeclarations(const ToolDescriptions& ToolDescs, raw_ostream& O) {
1948 llvm::StringMap<unsigned> HookNames;
1950 FillInHookNames(ToolDescs, HookNames);
1951 if (HookNames.empty())
1954 O << "namespace hooks {\n";
1955 for (StringMap<unsigned>::const_iterator B = HookNames.begin(),
1956 E = HookNames.end(); B != E; ++B) {
1957 O << Indent1 << "std::string " << B->first() << "(";
1959 for (unsigned i = 0, j = B->second; i < j; ++i) {
1960 O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
1968 /// EmitRegisterPlugin - Emit code to register this plugin.
1969 void EmitRegisterPlugin(int Priority, raw_ostream& O) {
1970 O << "struct Plugin : public llvmc::BasePlugin {\n\n"
1971 << Indent1 << "int Priority() const { return " << Priority << "; }\n\n"
1972 << Indent1 << "void PopulateLanguageMap(LanguageMap& langMap) const\n"
1973 << Indent1 << "{ PopulateLanguageMapLocal(langMap); }\n\n"
1975 << "void PopulateCompilationGraph(CompilationGraph& graph) const\n"
1976 << Indent1 << "{ PopulateCompilationGraphLocal(graph); }\n"
1979 << "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
1982 /// EmitIncludes - Emit necessary #include directives and some
1983 /// additional declarations.
1984 void EmitIncludes(raw_ostream& O) {
1985 O << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
1986 << "#include \"llvm/CompilerDriver/ForceLinkageMacros.h\"\n"
1987 << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
1988 << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
1990 << "#include \"llvm/ADT/StringExtras.h\"\n"
1991 << "#include \"llvm/Support/CommandLine.h\"\n\n"
1993 << "#include <cstdlib>\n"
1994 << "#include <stdexcept>\n\n"
1996 << "using namespace llvm;\n"
1997 << "using namespace llvmc;\n\n"
1999 << "extern cl::opt<std::string> OutputFilename;\n\n"
2001 << "inline const char* checkCString(const char* s)\n"
2002 << "{ return s == NULL ? \"\" : s; }\n\n";
2006 /// PluginData - Holds all information about a plugin.
2008 OptionDescriptions OptDescs;
2011 ToolDescriptions ToolDescs;
2016 /// HasSink - Go through the list of tool descriptions and check if
2017 /// there are any with the 'sink' property set.
2018 bool HasSink(const ToolDescriptions& ToolDescs) {
2019 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2020 E = ToolDescs.end(); B != E; ++B)
2027 /// HasExterns - Go through the list of option descriptions and check
2028 /// if there are any external options.
2029 bool HasExterns(const OptionDescriptions& OptDescs) {
2030 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
2031 E = OptDescs.end(); B != E; ++B)
2032 if (B->second.isExtern())
2038 /// CollectPluginData - Collect tool and option properties,
2039 /// compilation graph edges and plugin priority from the parse tree.
2040 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
2041 // Collect option properties.
2042 const RecordVector& OptionLists =
2043 Records.getAllDerivedDefinitions("OptionList");
2044 CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
2047 // Collect tool properties.
2048 const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
2049 CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
2050 Data.HasSink = HasSink(Data.ToolDescs);
2051 Data.HasExterns = HasExterns(Data.OptDescs);
2053 // Collect compilation graph edges.
2054 const RecordVector& CompilationGraphs =
2055 Records.getAllDerivedDefinitions("CompilationGraph");
2056 FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
2059 // Calculate the priority of this plugin.
2060 const RecordVector& Priorities =
2061 Records.getAllDerivedDefinitions("PluginPriority");
2062 Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
2065 /// CheckPluginData - Perform some sanity checks on the collected data.
2066 void CheckPluginData(PluginData& Data) {
2067 // Filter out all tools not mentioned in the compilation graph.
2068 FilterNotInGraph(Data.Edges, Data.ToolDescs);
2070 // Typecheck the compilation graph.
2071 TypecheckGraph(Data.Edges, Data.ToolDescs);
2073 // Check that there are no options without side effects (specified
2074 // only in the OptionList).
2075 CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
2079 void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
2080 // Emit file header.
2083 // Emit global option registration code.
2084 EmitOptionDefinitions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
2086 // Emit hook declarations.
2087 EmitHookDeclarations(Data.ToolDescs, O);
2089 O << "namespace {\n\n";
2091 // Emit PopulateLanguageMap() function
2092 // (a language map maps from file extensions to language names).
2093 EmitPopulateLanguageMap(Records, O);
2095 // Emit Tool classes.
2096 for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
2097 E = Data.ToolDescs.end(); B!=E; ++B)
2098 EmitToolClassDefinition(*(*B), Data.OptDescs, O);
2100 // Emit Edge# classes.
2101 EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
2103 // Emit PopulateCompilationGraph() function.
2104 EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
2106 // Emit code for plugin registration.
2107 EmitRegisterPlugin(Data.Priority, O);
2109 O << "} // End anonymous namespace.\n\n";
2111 // Force linkage magic.
2112 O << "namespace llvmc {\n";
2113 O << "LLVMC_FORCE_LINKAGE_DECL(LLVMC_PLUGIN_NAME) {}\n";
2120 // End of anonymous namespace
2123 /// run - The back-end entry point.
2124 void LLVMCConfigurationEmitter::run (raw_ostream &O) {
2128 CollectPluginData(Records, Data);
2129 CheckPluginData(Data);
2131 EmitSourceFileHeader("LLVMC Configuration Library", O);
2132 EmitPluginCode(Data, O);
2134 } catch (std::exception& Error) {
2135 throw Error.what() + std::string(" - usually this means a syntax error.");