1 //===- LLVMCConfigurationEmitter.cpp - Generate LLVMC config --------------===//
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/Support/Streams.h"
32 //===----------------------------------------------------------------------===//
35 typedef std::vector<Record*> RecordVector;
36 typedef std::vector<std::string> StrVector;
38 //===----------------------------------------------------------------------===//
41 // Indentation strings.
42 const char * Indent1 = " ";
43 const char * Indent2 = " ";
44 const char * Indent3 = " ";
45 const char * Indent4 = " ";
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 const std::string& InitPtrToString(const Init* ptr) {
57 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
58 return val.getValue();
61 int InitPtrToInt(const Init* ptr) {
62 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
63 return val.getValue();
66 const DagInit& InitPtrToDagInitRef(const Init* ptr) {
67 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
71 // checkNumberOfArguments - Ensure that the number of args in d is
72 // less than or equal to min_arguments, otherwise throw an exception.
73 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
74 if (d->getNumArgs() < min_arguments)
75 throw "Property " + d->getOperator()->getAsString()
76 + " has too few arguments!";
79 // isDagEmpty - is this DAG marked with an empty marker?
80 bool isDagEmpty (const DagInit* d) {
81 return d->getOperator()->getAsString() == "empty";
84 //===----------------------------------------------------------------------===//
85 /// Back-end specific code
87 // A command-line option can have one of the following types:
89 // Switch - a simple switch w/o arguments, e.g. -O2
91 // Parameter - an option that takes one(and only one) argument, e.g. -o file,
94 // ParameterList - same as Parameter, but more than one occurence
95 // of the option is allowed, e.g. -lm -lpthread
97 // Prefix - argument is everything after the prefix,
98 // e.g. -Wa,-foo,-bar, -DNAME=VALUE
100 // PrefixList - same as Prefix, but more than one option occurence is
103 namespace OptionType {
104 enum OptionType { Switch, Parameter, ParameterList, Prefix, PrefixList};
107 bool IsListOptionType (OptionType::OptionType t) {
108 return (t == OptionType::ParameterList || t == OptionType::PrefixList);
111 // Code duplication here is necessary because one option can affect
112 // several tools and those tools may have different actions associated
113 // with this option. GlobalOptionDescriptions are used to generate
114 // the option registration code, while ToolOptionDescriptions are used
115 // to generate tool-specific code.
117 /// OptionDescription - Base class for option descriptions.
118 struct OptionDescription {
119 OptionType::OptionType Type;
122 OptionDescription(OptionType::OptionType t = OptionType::Switch,
123 const std::string& n = "")
127 const char* GenTypeDeclaration() const {
129 case OptionType::PrefixList:
130 case OptionType::ParameterList:
131 return "cl::list<std::string>";
132 case OptionType::Switch:
133 return "cl::opt<bool>";
134 case OptionType::Parameter:
135 case OptionType::Prefix:
137 return "cl::opt<std::string>";
141 // Escape commas and other symbols not allowed in the C++ variable
142 // names. Makes it possible to use options with names like "Wa,"
143 // (useful for prefix options).
144 std::string EscapeVariableName(const std::string& Var) const {
146 for (unsigned i = 0; i != Var.size(); ++i) {
151 ret.push_back(Var[i]);
157 std::string GenVariableName() const {
158 const std::string& EscapedName = EscapeVariableName(Name);
160 case OptionType::Switch:
161 return "AutoGeneratedSwitch" + EscapedName;
162 case OptionType::Prefix:
163 return "AutoGeneratedPrefix" + EscapedName;
164 case OptionType::PrefixList:
165 return "AutoGeneratedPrefixList" + EscapedName;
166 case OptionType::Parameter:
167 return "AutoGeneratedParameter" + EscapedName;
168 case OptionType::ParameterList:
170 return "AutoGeneratedParameterList" + EscapedName;
176 // Global option description.
178 namespace GlobalOptionDescriptionFlags {
179 enum GlobalOptionDescriptionFlags { Required = 0x1 };
182 struct GlobalOptionDescription : public OptionDescription {
186 // We need to provide a default constructor because
187 // StringMap can only store DefaultConstructible objects.
188 GlobalOptionDescription() : OptionDescription(), Flags(0)
191 GlobalOptionDescription (OptionType::OptionType t, const std::string& n)
192 : OptionDescription(t, n), Help(DefaultHelpString), Flags(0)
195 bool isRequired() const {
196 return Flags & GlobalOptionDescriptionFlags::Required;
199 Flags |= GlobalOptionDescriptionFlags::Required;
202 /// Merge - Merge two option descriptions.
203 void Merge (const GlobalOptionDescription& other)
205 if (other.Type != Type)
206 throw "Conflicting definitions for the option " + Name + "!";
208 if (Help == DefaultHelpString)
210 else if (other.Help != DefaultHelpString) {
211 llvm::cerr << "Warning: more than one help string defined for option "
215 Flags |= other.Flags;
219 /// GlobalOptionDescriptions - A GlobalOptionDescription array
220 /// together with some flags affecting generation of option
222 struct GlobalOptionDescriptions {
223 typedef StringMap<GlobalOptionDescription> container_type;
224 typedef container_type::const_iterator const_iterator;
226 /// Descriptions - A list of GlobalOptionDescriptions.
227 container_type Descriptions;
228 /// HasSink - Should the emitter generate a "cl::sink" option?
231 const GlobalOptionDescription& FindOption(const std::string& OptName) const {
232 const_iterator I = Descriptions.find(OptName);
233 if (I != Descriptions.end())
236 throw OptName + ": no such option!";
239 // Support for STL-style iteration
240 const_iterator begin() const { return Descriptions.begin(); }
241 const_iterator end() const { return Descriptions.end(); }
245 // Tool-local option description.
247 // Properties without arguments are implemented as flags.
248 namespace ToolOptionDescriptionFlags {
249 enum ToolOptionDescriptionFlags { StopCompilation = 0x1,
250 Forward = 0x2, UnpackValues = 0x4};
252 namespace OptionPropertyType {
253 enum OptionPropertyType { AppendCmd, OutputSuffix };
256 typedef std::pair<OptionPropertyType::OptionPropertyType, std::string>
258 typedef SmallVector<OptionProperty, 4> OptionPropertyList;
260 struct ToolOptionDescription : public OptionDescription {
262 OptionPropertyList Props;
264 // StringMap can only store DefaultConstructible objects
265 ToolOptionDescription() : OptionDescription(), Flags(0) {}
267 ToolOptionDescription (OptionType::OptionType t, const std::string& n)
268 : OptionDescription(t, n)
271 // Various boolean properties
272 bool isStopCompilation() const {
273 return Flags & ToolOptionDescriptionFlags::StopCompilation;
275 void setStopCompilation() {
276 Flags |= ToolOptionDescriptionFlags::StopCompilation;
279 bool isForward() const {
280 return Flags & ToolOptionDescriptionFlags::Forward;
283 Flags |= ToolOptionDescriptionFlags::Forward;
286 bool isUnpackValues() const {
287 return Flags & ToolOptionDescriptionFlags::UnpackValues;
289 void setUnpackValues() {
290 Flags |= ToolOptionDescriptionFlags::UnpackValues;
293 void AddProperty (OptionPropertyType::OptionPropertyType t,
294 const std::string& val)
296 Props.push_back(std::make_pair(t, val));
300 typedef StringMap<ToolOptionDescription> ToolOptionDescriptions;
302 // Tool information record
304 namespace ToolFlags {
305 enum ToolFlags { Join = 0x1, Sink = 0x2 };
308 struct ToolProperties : public RefCountedBase<ToolProperties> {
311 std::string InLanguage;
312 std::string OutLanguage;
313 std::string OutputSuffix;
315 ToolOptionDescriptions OptDescs;
317 // Various boolean properties
318 void setSink() { Flags |= ToolFlags::Sink; }
319 bool isSink() const { return Flags & ToolFlags::Sink; }
320 void setJoin() { Flags |= ToolFlags::Join; }
321 bool isJoin() const { return Flags & ToolFlags::Join; }
323 // Default ctor here is needed because StringMap can only store
324 // DefaultConstructible objects
325 ToolProperties() : Flags(0) {}
326 ToolProperties (const std::string& n) : Name(n), Flags(0) {}
330 /// ToolPropertiesList - A list of Tool information records
331 /// IntrusiveRefCntPtrs are used here because StringMap has no copy
332 /// constructor (and we want to avoid copying ToolProperties anyway).
333 typedef std::vector<IntrusiveRefCntPtr<ToolProperties> > ToolPropertiesList;
336 /// CollectProperties - Function object for iterating over a list of
337 /// tool property records.
338 class CollectProperties {
341 /// Implementation details
343 /// PropertyHandler - a function that extracts information
344 /// about a given tool property from its DAG representation
345 typedef void (CollectProperties::*PropertyHandler)(const DagInit*);
347 /// PropertyHandlerMap - A map from property names to property
349 typedef StringMap<PropertyHandler> PropertyHandlerMap;
351 /// OptionPropertyHandler - a function that extracts information
352 /// about a given option property from its DAG representation.
353 typedef void (CollectProperties::* OptionPropertyHandler)
354 (const DagInit*, GlobalOptionDescription &);
356 /// OptionPropertyHandlerMap - A map from option property names to
357 /// option property handlers
358 typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
360 // Static maps from strings to CollectProperties methods("handlers")
361 static PropertyHandlerMap propertyHandlers_;
362 static OptionPropertyHandlerMap optionPropertyHandlers_;
363 static bool staticMembersInitialized_;
366 /// This is where the information is stored
368 /// toolProps_ - Properties of the current Tool.
369 ToolProperties& toolProps_;
370 /// optDescs_ - OptionDescriptions table (used to register options
372 GlobalOptionDescriptions& optDescs_;
376 explicit CollectProperties (ToolProperties& p, GlobalOptionDescriptions& d)
377 : toolProps_(p), optDescs_(d)
379 if (!staticMembersInitialized_) {
380 // Init tool property handlers
381 propertyHandlers_["cmd_line"] = &CollectProperties::onCmdLine;
382 propertyHandlers_["in_language"] = &CollectProperties::onInLanguage;
383 propertyHandlers_["join"] = &CollectProperties::onJoin;
384 propertyHandlers_["out_language"] = &CollectProperties::onOutLanguage;
385 propertyHandlers_["output_suffix"] = &CollectProperties::onOutputSuffix;
386 propertyHandlers_["parameter_option"]
387 = &CollectProperties::onParameter;
388 propertyHandlers_["parameter_list_option"] =
389 &CollectProperties::onParameterList;
390 propertyHandlers_["prefix_option"] = &CollectProperties::onPrefix;
391 propertyHandlers_["prefix_list_option"] =
392 &CollectProperties::onPrefixList;
393 propertyHandlers_["sink"] = &CollectProperties::onSink;
394 propertyHandlers_["switch_option"] = &CollectProperties::onSwitch;
396 // Init option property handlers
397 optionPropertyHandlers_["append_cmd"] = &CollectProperties::onAppendCmd;
398 optionPropertyHandlers_["forward"] = &CollectProperties::onForward;
399 optionPropertyHandlers_["help"] = &CollectProperties::onHelp;
400 optionPropertyHandlers_["output_suffix"] =
401 &CollectProperties::onOutputSuffixOptionProp;
402 optionPropertyHandlers_["required"] = &CollectProperties::onRequired;
403 optionPropertyHandlers_["stop_compilation"] =
404 &CollectProperties::onStopCompilation;
405 optionPropertyHandlers_["unpack_values"] =
406 &CollectProperties::onUnpackValues;
408 staticMembersInitialized_ = true;
412 /// operator() - Gets called for every tool property; Just forwards
413 /// to the corresponding property handler.
414 void operator() (Init* i) {
415 const DagInit& d = InitPtrToDagInitRef(i);
416 const std::string& property_name = d.getOperator()->getAsString();
417 PropertyHandlerMap::iterator method
418 = propertyHandlers_.find(property_name);
420 if (method != propertyHandlers_.end()) {
421 PropertyHandler h = method->second;
425 throw "Unknown tool property: " + property_name + "!";
431 /// Property handlers --
432 /// Functions that extract information about tool properties from
433 /// DAG representation.
435 void onCmdLine (const DagInit* d) {
436 checkNumberOfArguments(d, 1);
437 toolProps_.CmdLine = d->getArg(0);
440 void onInLanguage (const DagInit* d) {
441 checkNumberOfArguments(d, 1);
442 toolProps_.InLanguage = InitPtrToString(d->getArg(0));
445 void onJoin (const DagInit* d) {
446 checkNumberOfArguments(d, 0);
447 toolProps_.setJoin();
450 void onOutLanguage (const DagInit* d) {
451 checkNumberOfArguments(d, 1);
452 toolProps_.OutLanguage = InitPtrToString(d->getArg(0));
455 void onOutputSuffix (const DagInit* d) {
456 checkNumberOfArguments(d, 1);
457 toolProps_.OutputSuffix = InitPtrToString(d->getArg(0));
460 void onSink (const DagInit* d) {
461 checkNumberOfArguments(d, 0);
462 optDescs_.HasSink = true;
463 toolProps_.setSink();
466 void onSwitch (const DagInit* d) {
467 addOption(d, OptionType::Switch);
470 void onParameter (const DagInit* d) {
471 addOption(d, OptionType::Parameter);
474 void onParameterList (const DagInit* d) {
475 addOption(d, OptionType::ParameterList);
478 void onPrefix (const DagInit* d) {
479 addOption(d, OptionType::Prefix);
482 void onPrefixList (const DagInit* d) {
483 addOption(d, OptionType::PrefixList);
486 /// Option property handlers --
487 /// Methods that handle properties that are common for all types of
488 /// options (like append_cmd, stop_compilation)
490 void onAppendCmd (const DagInit* d, GlobalOptionDescription& o) {
491 checkNumberOfArguments(d, 1);
492 const std::string& cmd = InitPtrToString(d->getArg(0));
494 toolProps_.OptDescs[o.Name].AddProperty(OptionPropertyType::AppendCmd, cmd);
497 void onOutputSuffixOptionProp (const DagInit* d, GlobalOptionDescription& o) {
498 checkNumberOfArguments(d, 1);
499 const std::string& suf = InitPtrToString(d->getArg(0));
501 if (toolProps_.OptDescs[o.Name].Type != OptionType::Switch)
502 throw "Option " + o.Name
503 + " can't have 'output_suffix' property since it isn't a switch!";
505 toolProps_.OptDescs[o.Name].AddProperty
506 (OptionPropertyType::OutputSuffix, suf);
509 void onForward (const DagInit* d, GlobalOptionDescription& o) {
510 checkNumberOfArguments(d, 0);
511 toolProps_.OptDescs[o.Name].setForward();
514 void onHelp (const DagInit* d, GlobalOptionDescription& o) {
515 checkNumberOfArguments(d, 1);
516 const std::string& help_message = InitPtrToString(d->getArg(0));
518 o.Help = help_message;
521 void onRequired (const DagInit* d, GlobalOptionDescription& o) {
522 checkNumberOfArguments(d, 0);
526 void onStopCompilation (const DagInit* d, GlobalOptionDescription& o) {
527 checkNumberOfArguments(d, 0);
528 if (o.Type != OptionType::Switch)
529 throw std::string("Only options of type Switch can stop compilation!");
530 toolProps_.OptDescs[o.Name].setStopCompilation();
533 void onUnpackValues (const DagInit* d, GlobalOptionDescription& o) {
534 checkNumberOfArguments(d, 0);
535 toolProps_.OptDescs[o.Name].setUnpackValues();
540 // Add an option of type t
541 void addOption (const DagInit* d, OptionType::OptionType t) {
542 checkNumberOfArguments(d, 2);
543 const std::string& name = InitPtrToString(d->getArg(0));
545 GlobalOptionDescription o(t, name);
546 toolProps_.OptDescs[name].Type = t;
547 toolProps_.OptDescs[name].Name = name;
548 processOptionProperties(d, o);
549 insertDescription(o);
552 // Insert new GlobalOptionDescription into GlobalOptionDescriptions list
553 void insertDescription (const GlobalOptionDescription& o)
555 if (optDescs_.Descriptions.count(o.Name)) {
556 GlobalOptionDescription& D = optDescs_.Descriptions[o.Name];
560 optDescs_.Descriptions[o.Name] = o;
564 /// processOptionProperties - Go through the list of option
565 /// properties and call a corresponding handler for each.
568 /// name - option name
569 /// d - option property list
570 void processOptionProperties (const DagInit* d, GlobalOptionDescription& o) {
571 // First argument is option name
572 checkNumberOfArguments(d, 2);
574 for (unsigned B = 1, E = d->getNumArgs(); B!=E; ++B) {
575 const DagInit& option_property
576 = InitPtrToDagInitRef(d->getArg(B));
577 const std::string& option_property_name
578 = option_property.getOperator()->getAsString();
579 OptionPropertyHandlerMap::iterator method
580 = optionPropertyHandlers_.find(option_property_name);
582 if (method != optionPropertyHandlers_.end()) {
583 OptionPropertyHandler h = method->second;
584 (this->*h)(&option_property, o);
587 throw "Unknown option property: " + option_property_name + "!";
593 // Static members of CollectProperties
594 CollectProperties::PropertyHandlerMap
595 CollectProperties::propertyHandlers_;
597 CollectProperties::OptionPropertyHandlerMap
598 CollectProperties::optionPropertyHandlers_;
600 bool CollectProperties::staticMembersInitialized_ = false;
603 /// CollectToolProperties - Gather information from the parsed
604 /// TableGen data (basically a wrapper for the CollectProperties
605 /// function object).
606 void CollectToolProperties (RecordVector::const_iterator B,
607 RecordVector::const_iterator E,
608 ToolPropertiesList& TPList,
609 GlobalOptionDescriptions& OptDescs)
611 // Iterate over a properties list of every Tool definition
613 RecordVector::value_type T = *B;
614 ListInit* PropList = T->getValueAsListInit("properties");
616 IntrusiveRefCntPtr<ToolProperties>
617 ToolProps(new ToolProperties(T->getName()));
619 std::for_each(PropList->begin(), PropList->end(),
620 CollectProperties(*ToolProps, OptDescs));
621 TPList.push_back(ToolProps);
625 /// EmitCaseTest1Arg - Helper function used by
626 /// EmitCaseConstructHandler.
627 bool EmitCaseTest1Arg(const std::string& TestName,
629 const GlobalOptionDescriptions& OptDescs,
631 checkNumberOfArguments(&d, 1);
632 const std::string& OptName = InitPtrToString(d.getArg(0));
633 if (TestName == "switch_on") {
634 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
635 if (OptDesc.Type != OptionType::Switch)
636 throw OptName + ": incorrect option type!";
637 O << OptDesc.GenVariableName();
639 } else if (TestName == "input_languages_contain") {
640 O << "InLangs.count(\"" << OptName << "\") != 0";
647 /// EmitCaseTest2Args - Helper function used by
648 /// EmitCaseConstructHandler.
649 bool EmitCaseTest2Args(const std::string& TestName,
651 const char* IndentLevel,
652 const GlobalOptionDescriptions& OptDescs,
654 checkNumberOfArguments(&d, 2);
655 const std::string& OptName = InitPtrToString(d.getArg(0));
656 const std::string& OptArg = InitPtrToString(d.getArg(1));
657 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
659 if (TestName == "parameter_equals") {
660 if (OptDesc.Type != OptionType::Parameter
661 && OptDesc.Type != OptionType::Prefix)
662 throw OptName + ": incorrect option type!";
663 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
666 else if (TestName == "element_in_list") {
667 if (OptDesc.Type != OptionType::ParameterList
668 && OptDesc.Type != OptionType::PrefixList)
669 throw OptName + ": incorrect option type!";
670 const std::string& VarName = OptDesc.GenVariableName();
671 O << "std::find(" << VarName << ".begin(),\n"
672 << IndentLevel << Indent1 << VarName << ".end(), \""
673 << OptArg << "\") != " << VarName << ".end()";
680 // Forward declaration.
681 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
682 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
683 const GlobalOptionDescriptions& OptDescs,
686 /// EmitLogicalOperationTest - Helper function used by
687 /// EmitCaseConstructHandler.
688 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
689 const char* IndentLevel,
690 const GlobalOptionDescriptions& OptDescs,
693 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
694 const DagInit& InnerTest = InitPtrToDagInitRef(d.getArg(j));
695 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
696 if (j != NumArgs - 1)
697 O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
703 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
704 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
705 const GlobalOptionDescriptions& OptDescs,
707 const std::string& TestName = d.getOperator()->getAsString();
709 if (TestName == "and")
710 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
711 else if (TestName == "or")
712 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
713 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
715 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
718 throw TestName + ": unknown edge property!";
721 // Emit code that handles the 'case' construct.
722 // Takes a function object that should emit code for every case clause.
723 // Callback's type is
724 // void F(Init* Statement, const char* IndentLevel, std::ostream& O).
725 template <typename F>
726 void EmitCaseConstructHandler(const DagInit* d, const char* IndentLevel,
728 const GlobalOptionDescriptions& OptDescs,
730 assert(d->getOperator()->getAsString() == "case");
732 for (unsigned i = 0, numArgs = d->getNumArgs(); i != numArgs; ++i) {
733 const DagInit& Test = InitPtrToDagInitRef(d->getArg(i));
735 if (Test.getOperator()->getAsString() == "default") {
737 throw std::string("The 'default' clause should be the last in the"
738 "'case' construct!");
739 O << IndentLevel << "else {\n";
742 O << IndentLevel << "if (";
743 EmitCaseTest(Test, IndentLevel, OptDescs, O);
749 throw "Case construct handler: no corresponding action "
750 "found for the test " + Test.getAsString() + '!';
752 Callback(d->getArg(i), IndentLevel, O);
753 O << IndentLevel << "}\n";
757 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
758 /// implement EmitOptionPropertyHandlingCode(). Emits code for
759 /// handling the (forward) option property.
760 void EmitForwardOptionPropertyHandlingCode (const ToolOptionDescription& D,
763 case OptionType::Switch:
764 O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
766 case OptionType::Parameter:
767 O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
768 O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
770 case OptionType::Prefix:
771 O << Indent3 << "vec.push_back(\"-" << D.Name << "\" + "
772 << D.GenVariableName() << ");\n";
774 case OptionType::PrefixList:
775 O << Indent3 << "for (" << D.GenTypeDeclaration()
776 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
777 << Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
778 << Indent4 << "vec.push_back(\"-" << D.Name << "\" + "
781 case OptionType::ParameterList:
782 O << Indent3 << "for (" << D.GenTypeDeclaration()
783 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
784 << Indent3 << "E = " << D.GenVariableName()
785 << ".end() ; B != E; ++B) {\n"
786 << Indent4 << "vec.push_back(\"-" << D.Name << "\");\n"
787 << Indent4 << "vec.push_back(*B);\n"
793 // ToolOptionHasInterestingProperties - A helper function used by
794 // EmitOptionPropertyHandlingCode() that tells us whether we should
795 // emit any property handling code at all.
796 bool ToolOptionHasInterestingProperties(const ToolOptionDescription& D) {
798 for (OptionPropertyList::const_iterator B = D.Props.begin(),
799 E = D.Props.end(); B != E; ++B) {
800 const OptionProperty& OptProp = *B;
801 if (OptProp.first == OptionPropertyType::AppendCmd)
804 if (D.isForward() || D.isUnpackValues())
809 /// EmitOptionPropertyHandlingCode - Helper function used by
810 /// EmitGenerateActionMethod(). Emits code that handles option
812 void EmitOptionPropertyHandlingCode (const ToolOptionDescription& D,
815 if (!ToolOptionHasInterestingProperties(D))
817 // Start of the if-clause.
818 O << Indent2 << "if (";
819 if (D.Type == OptionType::Switch)
820 O << D.GenVariableName();
822 O << '!' << D.GenVariableName() << ".empty()";
826 // Handle option properties that take an argument.
827 for (OptionPropertyList::const_iterator B = D.Props.begin(),
828 E = D.Props.end(); B!=E; ++B) {
829 const OptionProperty& val = *B;
832 // (append_cmd cmd) property
833 case OptionPropertyType::AppendCmd:
834 O << Indent3 << "vec.push_back(\"" << val.second << "\");\n";
836 // Other properties with argument
844 // (forward) property
846 EmitForwardOptionPropertyHandlingCode(D, O);
848 // (unpack_values) property
849 if (D.isUnpackValues()) {
850 if (IsListOptionType(D.Type)) {
851 O << Indent3 << "for (" << D.GenTypeDeclaration()
852 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
853 << Indent3 << "E = " << D.GenVariableName()
854 << ".end(); B != E; ++B)\n"
855 << Indent4 << "llvm::SplitString(*B, vec, \",\");\n";
857 else if (D.Type == OptionType::Prefix || D.Type == OptionType::Parameter){
858 O << Indent3 << "llvm::SplitString("
859 << D.GenVariableName() << ", vec, \",\");\n";
862 throw std::string("Switches can't have unpack_values property!");
866 // End of the if-clause.
867 O << Indent2 << "}\n";
870 /// SubstituteSpecialCommands - Perform string substitution for $CALL
871 /// and $ENV. Helper function used by EmitCmdLineVecFill().
872 std::string SubstituteSpecialCommands(const std::string& cmd) {
873 size_t cparen = cmd.find(")");
876 if (cmd.find("$CALL(") == 0) {
878 throw std::string("$CALL invocation: empty argument list!");
881 ret += std::string(cmd.begin() + 6, cmd.begin() + cparen);
884 else if (cmd.find("$ENV(") == 0) {
886 throw std::string("$ENV invocation: empty argument list!");
888 ret += "std::getenv(\"";
889 ret += std::string(cmd.begin() + 5, cmd.begin() + cparen);
893 throw "Unknown special command: " + cmd;
896 if (cmd.begin() + cparen + 1 != cmd.end()) {
897 ret += " + std::string(\"";
898 ret += (cmd.c_str() + cparen + 1);
905 /// EmitCmdLineVecFill - Emit code that fills in the command line
906 /// vector. Helper function used by EmitGenerateActionMethod().
907 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
908 bool Version, const char* IndentLevel,
911 SplitString(InitPtrToString(CmdLine), StrVec);
913 throw "Tool " + ToolName + " has empty command line!";
915 StrVector::const_iterator I = StrVec.begin();
917 for (StrVector::const_iterator E = StrVec.end(); I != E; ++I) {
918 const std::string& cmd = *I;
920 if (cmd.at(0) == '$') {
921 if (cmd == "$INFILE") {
923 O << "for (PathVector::const_iterator B = inFiles.begin()"
924 << ", E = inFiles.end();\n"
925 << IndentLevel << "B != E; ++B)\n"
926 << IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
928 O << "vec.push_back(inFile.toString());\n";
930 else if (cmd == "$OUTFILE") {
931 O << "vec.push_back(outFile.toString());\n";
934 O << "vec.push_back(" << SubstituteSpecialCommands(cmd);
939 O << "vec.push_back(\"" << cmd << "\");\n";
942 O << IndentLevel << "ret = Action("
943 << ((StrVec[0][0] == '$') ? SubstituteSpecialCommands(StrVec[0])
944 : "\"" + StrVec[0] + "\"")
948 /// EmitCmdLineVecFillCallback - A function object wrapper around
949 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
950 /// argument to EmitCaseConstructHandler().
951 class EmitCmdLineVecFillCallback {
953 const std::string& ToolName;
955 EmitCmdLineVecFillCallback(bool Ver, const std::string& TN)
956 : Version(Ver), ToolName(TN) {}
958 void operator()(const Init* Statement, const char* IndentLevel,
959 std::ostream& O) const
961 EmitCmdLineVecFill(Statement, ToolName, Version,
962 (std::string(IndentLevel) + Indent1).c_str(), O);
966 // EmitGenerateActionMethod - Emit one of two versions of the
967 // Tool::GenerateAction() method.
968 void EmitGenerateActionMethod (const ToolProperties& P,
969 const GlobalOptionDescriptions& OptDescs,
970 bool Version, std::ostream& O) {
972 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
974 O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
976 O << Indent2 << "const sys::Path& outFile,\n"
977 << Indent2 << "const InputLanguagesSet& InLangs) const\n"
979 << Indent2 << "Action ret;\n"
980 << Indent2 << "std::vector<std::string> vec;\n";
982 // cmd_line is either a string or a 'case' construct.
983 if (typeid(*P.CmdLine) == typeid(StringInit))
984 EmitCmdLineVecFill(P.CmdLine, P.Name, Version, Indent2, O);
986 EmitCaseConstructHandler(&InitPtrToDagInitRef(P.CmdLine), Indent2,
987 EmitCmdLineVecFillCallback(Version, P.Name),
990 // For every understood option, emit handling code.
991 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
992 E = P.OptDescs.end(); B != E; ++B) {
993 const ToolOptionDescription& val = B->second;
994 EmitOptionPropertyHandlingCode(val, O);
997 // Handle the Sink property.
999 O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
1000 << Indent3 << "vec.insert(vec.end(), "
1001 << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
1002 << Indent2 << "}\n";
1005 O << Indent2 << "return ret;\n"
1006 << Indent1 << "}\n\n";
1009 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1010 /// a given Tool class.
1011 void EmitGenerateActionMethods (const ToolProperties& P,
1012 const GlobalOptionDescriptions& OptDescs,
1015 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
1016 << Indent2 << "const llvm::sys::Path& outFile,\n"
1017 << Indent2 << "const InputLanguagesSet& InLangs) const\n"
1019 << Indent2 << "throw std::runtime_error(\"" << P.Name
1020 << " is not a Join tool!\");\n"
1021 << Indent1 << "}\n\n";
1023 EmitGenerateActionMethod(P, OptDescs, true, O);
1025 EmitGenerateActionMethod(P, OptDescs, false, O);
1028 /// EmitIsLastMethod - Emit the IsLast() method for a given Tool
1030 void EmitIsLastMethod (const ToolProperties& P, std::ostream& O) {
1031 O << Indent1 << "bool IsLast() const {\n"
1032 << Indent2 << "bool last = false;\n";
1034 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1035 E = P.OptDescs.end(); B != E; ++B) {
1036 const ToolOptionDescription& val = B->second;
1038 if (val.isStopCompilation())
1040 << "if (" << val.GenVariableName()
1041 << ")\n" << Indent3 << "last = true;\n";
1044 O << Indent2 << "return last;\n"
1045 << Indent1 << "}\n\n";
1048 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1049 /// methods for a given Tool class.
1050 void EmitInOutLanguageMethods (const ToolProperties& P, std::ostream& O) {
1051 O << Indent1 << "const char* InputLanguage() const {\n"
1052 << Indent2 << "return \"" << P.InLanguage << "\";\n"
1053 << Indent1 << "}\n\n";
1055 O << Indent1 << "const char* OutputLanguage() const {\n"
1056 << Indent2 << "return \"" << P.OutLanguage << "\";\n"
1057 << Indent1 << "}\n\n";
1060 /// EmitOutputSuffixMethod - Emit the OutputSuffix() method for a
1061 /// given Tool class.
1062 void EmitOutputSuffixMethod (const ToolProperties& P, std::ostream& O) {
1063 O << Indent1 << "const char* OutputSuffix() const {\n"
1064 << Indent2 << "const char* ret = \"" << P.OutputSuffix << "\";\n";
1066 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1067 E = P.OptDescs.end(); B != E; ++B) {
1068 const ToolOptionDescription& OptDesc = B->second;
1069 for (OptionPropertyList::const_iterator B = OptDesc.Props.begin(),
1070 E = OptDesc.Props.end(); B != E; ++B) {
1071 const OptionProperty& OptProp = *B;
1072 if (OptProp.first == OptionPropertyType::OutputSuffix) {
1073 O << Indent2 << "if (" << OptDesc.GenVariableName() << ")\n"
1074 << Indent3 << "ret = \"" << OptProp.second << "\";\n";
1079 O << Indent2 << "return ret;\n"
1080 << Indent1 << "}\n\n";
1083 /// EmitNameMethod - Emit the Name() method for a given Tool class.
1084 void EmitNameMethod (const ToolProperties& P, std::ostream& O) {
1085 O << Indent1 << "const char* Name() const {\n"
1086 << Indent2 << "return \"" << P.Name << "\";\n"
1087 << Indent1 << "}\n\n";
1090 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1092 void EmitIsJoinMethod (const ToolProperties& P, std::ostream& O) {
1093 O << Indent1 << "bool IsJoin() const {\n";
1095 O << Indent2 << "return true;\n";
1097 O << Indent2 << "return false;\n";
1098 O << Indent1 << "}\n\n";
1101 /// EmitToolClassDefinition - Emit a Tool class definition.
1102 void EmitToolClassDefinition (const ToolProperties& P,
1103 const GlobalOptionDescriptions& OptDescs,
1105 if (P.Name == "root")
1109 O << "class " << P.Name << " : public ";
1114 O << " {\npublic:\n";
1116 EmitNameMethod(P, O);
1117 EmitInOutLanguageMethods(P, O);
1118 EmitOutputSuffixMethod(P, O);
1119 EmitIsJoinMethod(P, O);
1120 EmitGenerateActionMethods(P, OptDescs, O);
1121 EmitIsLastMethod(P, O);
1123 // Close class definition
1127 /// EmitOptionDescriptions - Iterate over a list of option
1128 /// descriptions and emit registration code.
1129 void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
1132 // Emit static cl::Option variables
1133 for (GlobalOptionDescriptions::const_iterator B = descs.begin(),
1134 E = descs.end(); B!=E; ++B) {
1135 const GlobalOptionDescription& val = B->second;
1137 O << val.GenTypeDeclaration() << ' '
1138 << val.GenVariableName()
1139 << "(\"" << val.Name << '\"';
1141 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1142 O << ", cl::Prefix";
1144 if (val.isRequired()) {
1146 case OptionType::PrefixList:
1147 case OptionType::ParameterList:
1148 O << ", cl::OneOrMore";
1151 O << ", cl::Required";
1155 O << ", cl::desc(\"" << val.Help << "\"));\n";
1159 O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
1164 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
1165 void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
1167 // Get the relevant field out of RecordKeeper
1168 Record* LangMapRecord = Records.getDef("LanguageMap");
1170 throw std::string("Language map definition not found!");
1172 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
1173 if (!LangsToSuffixesList)
1174 throw std::string("Error in the language map definition!");
1177 O << "void llvmc::PopulateLanguageMap(LanguageMap& language_map) {\n";
1179 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
1180 Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
1182 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
1183 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
1185 for (unsigned i = 0; i < Suffixes->size(); ++i)
1186 O << Indent1 << "language_map[\""
1187 << InitPtrToString(Suffixes->getElement(i))
1188 << "\"] = \"" << Lang << "\";\n";
1194 /// FillInToolToLang - Fills in two tables that map tool names to
1195 /// (input, output) languages. Used by the typechecker.
1196 void FillInToolToLang (const ToolPropertiesList& TPList,
1197 StringMap<std::string>& ToolToInLang,
1198 StringMap<std::string>& ToolToOutLang) {
1199 for (ToolPropertiesList::const_iterator B = TPList.begin(), E = TPList.end();
1201 const ToolProperties& P = *(*B);
1202 ToolToInLang[P.Name] = P.InLanguage;
1203 ToolToOutLang[P.Name] = P.OutLanguage;
1207 /// TypecheckGraph - Check that names for output and input languages
1208 /// on all edges do match.
1209 // TOFIX: check for cycles.
1210 // TOFIX: check for multiple default edges.
1211 void TypecheckGraph (Record* CompilationGraph,
1212 const ToolPropertiesList& TPList) {
1213 StringMap<std::string> ToolToInLang;
1214 StringMap<std::string> ToolToOutLang;
1216 FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
1217 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1218 StringMap<std::string>::iterator IAE = ToolToInLang.end();
1219 StringMap<std::string>::iterator IBE = ToolToOutLang.end();
1221 for (unsigned i = 0; i < edges->size(); ++i) {
1222 Record* Edge = edges->getElementAsRecord(i);
1223 Record* A = Edge->getValueAsDef("a");
1224 Record* B = Edge->getValueAsDef("b");
1225 StringMap<std::string>::iterator IA = ToolToOutLang.find(A->getName());
1226 StringMap<std::string>::iterator IB = ToolToInLang.find(B->getName());
1228 throw A->getName() + ": no such tool!";
1230 throw B->getName() + ": no such tool!";
1231 if (A->getName() != "root" && IA->second != IB->second)
1232 throw "Edge " + A->getName() + "->" + B->getName()
1233 + ": output->input language mismatch";
1234 if (B->getName() == "root")
1235 throw std::string("Edges back to the root are not allowed!");
1239 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
1240 /// by EmitEdgeClass().
1241 void IncDecWeight (const Init* i, const char* IndentLevel,
1243 const DagInit& d = InitPtrToDagInitRef(i);
1244 const std::string& OpName = d.getOperator()->getAsString();
1246 if (OpName == "inc_weight")
1247 O << IndentLevel << Indent1 << "ret += ";
1248 else if (OpName == "dec_weight")
1249 O << IndentLevel << Indent1 << "ret -= ";
1251 throw "Unknown operator in edge properties list: " + OpName + '!';
1253 if (d.getNumArgs() > 0)
1254 O << InitPtrToInt(d.getArg(0)) << ";\n";
1260 /// EmitEdgeClass - Emit a single Edge# class.
1261 void EmitEdgeClass (unsigned N, const std::string& Target,
1262 DagInit* Case, const GlobalOptionDescriptions& OptDescs,
1265 // Class constructor.
1266 O << "class Edge" << N << ": public Edge {\n"
1268 << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1271 // Function Weight().
1272 << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
1273 << Indent2 << "unsigned ret = 0;\n";
1275 // Handle the 'case' construct.
1276 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, OptDescs, O);
1278 O << Indent2 << "return ret;\n"
1279 << Indent1 << "};\n\n};\n\n";
1282 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
1283 void EmitEdgeClasses (Record* CompilationGraph,
1284 const GlobalOptionDescriptions& OptDescs,
1286 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1288 for (unsigned i = 0; i < edges->size(); ++i) {
1289 Record* Edge = edges->getElementAsRecord(i);
1290 Record* B = Edge->getValueAsDef("b");
1291 DagInit* Weight = Edge->getValueAsDag("weight");
1293 if (isDagEmpty(Weight))
1296 EmitEdgeClass(i, B->getName(), Weight, OptDescs, O);
1300 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1302 void EmitPopulateCompilationGraph (Record* CompilationGraph,
1305 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1308 O << "void llvmc::PopulateCompilationGraph(CompilationGraph& G) {\n"
1309 << Indent1 << "PopulateLanguageMap(G.ExtsToLangs);\n\n";
1313 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1315 throw std::string("No tool definitions found!");
1317 for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
1318 const std::string& Name = (*B)->getName();
1320 O << Indent1 << "G.insertNode(new "
1321 << Name << "());\n";
1327 for (unsigned i = 0; i < edges->size(); ++i) {
1328 Record* Edge = edges->getElementAsRecord(i);
1329 Record* A = Edge->getValueAsDef("a");
1330 Record* B = Edge->getValueAsDef("b");
1331 DagInit* Weight = Edge->getValueAsDag("weight");
1333 O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
1335 if (isDagEmpty(Weight))
1336 O << "new SimpleEdge(\"" << B->getName() << "\")";
1338 O << "new Edge" << i << "()";
1346 /// ExtractHookNames - Extract the hook names from all instances of
1347 /// $CALL(HookName) in the provided command line string. Helper
1348 /// function used by FillInHookNames().
1349 void ExtractHookNames(const Init* CmdLine, StrVector& HookNames) {
1351 llvm::SplitString(InitPtrToString(CmdLine), cmds);
1352 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
1354 const std::string& cmd = *B;
1355 if (cmd.find("$CALL(") == 0) {
1356 if (cmd.size() == 6)
1357 throw std::string("$CALL invocation: empty argument list!");
1358 HookNames.push_back(std::string(cmd.begin() + 6,
1359 cmd.begin() + cmd.find(")")));
1364 /// FillInHookNames - Actually extract the hook names from all command
1365 /// line strings. Helper function used by EmitHookDeclarations().
1366 void FillInHookNames(const ToolPropertiesList& TPList,
1367 StrVector& HookNames) {
1368 for (ToolPropertiesList::const_iterator B = TPList.begin(),
1369 E = TPList.end(); B != E; ++B) {
1370 const ToolProperties& P = *(*B);
1373 if (typeid(*P.CmdLine) == typeid(StringInit)) {
1374 // This is a string.
1375 ExtractHookNames(P.CmdLine, HookNames);
1378 // This is a 'case' construct.
1379 const DagInit& d = InitPtrToDagInitRef(P.CmdLine);
1381 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1384 ExtractHookNames(*B, HookNames);
1391 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
1392 /// property records and emit hook function declaration for each
1393 /// instance of $CALL(HookName).
1394 void EmitHookDeclarations(const ToolPropertiesList& ToolProps,
1396 StrVector HookNames;
1397 FillInHookNames(ToolProps, HookNames);
1398 if (HookNames.empty())
1400 std::sort(HookNames.begin(), HookNames.end());
1401 StrVector::const_iterator E = std::unique(HookNames.begin(), HookNames.end());
1403 O << "namespace hooks {\n";
1404 for (StrVector::const_iterator B = HookNames.begin(); B != E; ++B)
1405 O << Indent1 << "std::string " << *B << "();\n";
1410 // End of anonymous namespace
1413 /// run - The back-end entry point.
1414 void LLVMCConfigurationEmitter::run (std::ostream &O) {
1416 // Emit file header.
1417 EmitSourceFileHeader("LLVMC Configuration Library", O);
1419 // Get a list of all defined Tools.
1420 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1422 throw std::string("No tool definitions found!");
1424 // Gather information from the Tool description dags.
1425 ToolPropertiesList tool_props;
1426 GlobalOptionDescriptions opt_descs;
1427 CollectToolProperties(Tools.begin(), Tools.end(), tool_props, opt_descs);
1429 // Emit global option registration code.
1430 EmitOptionDescriptions(opt_descs, O);
1432 // Emit hook declarations.
1433 EmitHookDeclarations(tool_props, O);
1435 // Emit PopulateLanguageMap() function
1436 // (a language map maps from file extensions to language names).
1437 EmitPopulateLanguageMap(Records, O);
1439 // Emit Tool classes.
1440 for (ToolPropertiesList::const_iterator B = tool_props.begin(),
1441 E = tool_props.end(); B!=E; ++B)
1442 EmitToolClassDefinition(*(*B), opt_descs, O);
1444 Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
1445 if (!CompilationGraphRecord)
1446 throw std::string("Compilation graph description not found!");
1448 // Typecheck the compilation graph.
1449 TypecheckGraph(CompilationGraphRecord, tool_props);
1451 // Emit Edge# classes.
1452 EmitEdgeClasses(CompilationGraphRecord, opt_descs, O);
1454 // Emit PopulateCompilationGraph() function.
1455 EmitPopulateCompilationGraph(CompilationGraphRecord, O);