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"
22 #include "llvm/Support/Streams.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 = " ";
46 const char * Indent4 = " ";
48 // Default help string.
49 const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
51 // Name for the "sink" option.
52 const char * SinkOptionName = "AutoGeneratedSinkOption";
54 //===----------------------------------------------------------------------===//
57 int InitPtrToInt(const Init* ptr) {
58 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
59 return val.getValue();
62 const std::string& InitPtrToString(const Init* ptr) {
63 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
64 return val.getValue();
67 const ListInit& InitPtrToList(const Init* ptr) {
68 const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
72 const DagInit& InitPtrToDag(const Init* ptr) {
73 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
77 // checkNumberOfArguments - Ensure that the number of args in d is
78 // less than or equal to min_arguments, otherwise throw an exception.
79 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
80 if (d->getNumArgs() < min_arguments)
81 throw "Property " + d->getOperator()->getAsString()
82 + " has too few arguments!";
85 // isDagEmpty - is this DAG marked with an empty marker?
86 bool isDagEmpty (const DagInit* d) {
87 return d->getOperator()->getAsString() == "empty";
90 //===----------------------------------------------------------------------===//
91 /// Back-end specific code
93 // A command-line option can have one of the following types:
95 // Alias - an alias for another option.
97 // Switch - a simple switch without arguments, e.g. -O2
99 // Parameter - an option that takes one(and only one) argument, e.g. -o file,
102 // ParameterList - same as Parameter, but more than one occurence
103 // of the option is allowed, e.g. -lm -lpthread
105 // Prefix - argument is everything after the prefix,
106 // e.g. -Wa,-foo,-bar, -DNAME=VALUE
108 // PrefixList - same as Prefix, but more than one option occurence is
111 namespace OptionType {
112 enum OptionType { Alias, Switch,
113 Parameter, ParameterList, Prefix, PrefixList};
116 bool IsListOptionType (OptionType::OptionType t) {
117 return (t == OptionType::ParameterList || t == OptionType::PrefixList);
120 // Code duplication here is necessary because one option can affect
121 // several tools and those tools may have different actions associated
122 // with this option. GlobalOptionDescriptions are used to generate
123 // the option registration code, while ToolOptionDescriptions are used
124 // to generate tool-specific code.
126 /// OptionDescription - Base class for option descriptions.
127 struct OptionDescription {
128 OptionType::OptionType Type;
131 OptionDescription(OptionType::OptionType t = OptionType::Switch,
132 const std::string& n = "")
136 const char* GenTypeDeclaration() const {
138 case OptionType::Alias:
140 case OptionType::PrefixList:
141 case OptionType::ParameterList:
142 return "cl::list<std::string>";
143 case OptionType::Switch:
144 return "cl::opt<bool>";
145 case OptionType::Parameter:
146 case OptionType::Prefix:
148 return "cl::opt<std::string>";
152 // Escape commas and other symbols not allowed in the C++ variable
153 // names. Makes it possible to use options with names like "Wa,"
154 // (useful for prefix options).
155 std::string EscapeVariableName(const std::string& Var) const {
157 for (unsigned i = 0; i != Var.size(); ++i) {
162 ret.push_back(Var[i]);
168 std::string GenVariableName() const {
169 const std::string& EscapedName = EscapeVariableName(Name);
171 case OptionType::Alias:
172 return "AutoGeneratedAlias" + EscapedName;
173 case OptionType::Switch:
174 return "AutoGeneratedSwitch" + EscapedName;
175 case OptionType::Prefix:
176 return "AutoGeneratedPrefix" + EscapedName;
177 case OptionType::PrefixList:
178 return "AutoGeneratedPrefixList" + EscapedName;
179 case OptionType::Parameter:
180 return "AutoGeneratedParameter" + EscapedName;
181 case OptionType::ParameterList:
183 return "AutoGeneratedParameterList" + EscapedName;
189 // Global option description.
191 namespace GlobalOptionDescriptionFlags {
192 enum GlobalOptionDescriptionFlags { Required = 0x1 };
195 struct GlobalOptionDescription : public OptionDescription {
199 // We need to provide a default constructor because
200 // StringMap can only store DefaultConstructible objects.
201 GlobalOptionDescription() : OptionDescription(), Flags(0)
204 GlobalOptionDescription (OptionType::OptionType t, const std::string& n,
205 const std::string& h = DefaultHelpString)
206 : OptionDescription(t, n), Help(h), Flags(0)
209 bool isRequired() const {
210 return Flags & GlobalOptionDescriptionFlags::Required;
213 Flags |= GlobalOptionDescriptionFlags::Required;
216 /// Merge - Merge two option descriptions.
217 void Merge (const GlobalOptionDescription& other)
219 if (other.Type != Type)
220 throw "Conflicting definitions for the option " + Name + "!";
222 if (Help == DefaultHelpString)
224 else if (other.Help != DefaultHelpString) {
225 llvm::cerr << "Warning: more than one help string defined for option "
229 Flags |= other.Flags;
233 /// GlobalOptionDescriptions - A GlobalOptionDescription array
234 /// together with some flags affecting generation of option
236 struct GlobalOptionDescriptions {
237 typedef StringMap<GlobalOptionDescription> container_type;
238 typedef container_type::const_iterator const_iterator;
240 /// Descriptions - A list of GlobalOptionDescriptions.
241 container_type Descriptions;
242 /// HasSink - Should the emitter generate a "cl::sink" option?
245 /// FindOption - exception-throwing wrapper for find().
246 const GlobalOptionDescription& FindOption(const std::string& OptName) const {
247 const_iterator I = Descriptions.find(OptName);
248 if (I != Descriptions.end())
251 throw OptName + ": no such option!";
254 /// insertDescription - Insert new GlobalOptionDescription into
255 /// GlobalOptionDescriptions list
256 void insertDescription (const GlobalOptionDescription& o)
258 container_type::iterator I = Descriptions.find(o.Name);
259 if (I != Descriptions.end()) {
260 GlobalOptionDescription& D = I->second;
264 Descriptions[o.Name] = o;
268 // Support for STL-style iteration
269 const_iterator begin() const { return Descriptions.begin(); }
270 const_iterator end() const { return Descriptions.end(); }
274 // Tool-local option description.
276 // Properties without arguments are implemented as flags.
277 namespace ToolOptionDescriptionFlags {
278 enum ToolOptionDescriptionFlags { StopCompilation = 0x1,
279 Forward = 0x2, UnpackValues = 0x4};
281 namespace OptionPropertyType {
282 enum OptionPropertyType { AppendCmd, OutputSuffix };
285 typedef std::pair<OptionPropertyType::OptionPropertyType, std::string>
287 typedef SmallVector<OptionProperty, 4> OptionPropertyList;
289 struct ToolOptionDescription : public OptionDescription {
291 OptionPropertyList Props;
293 // StringMap can only store DefaultConstructible objects
294 ToolOptionDescription() : OptionDescription(), Flags(0) {}
296 ToolOptionDescription (OptionType::OptionType t, const std::string& n)
297 : OptionDescription(t, n)
300 // Various boolean properties
301 bool isStopCompilation() const {
302 return Flags & ToolOptionDescriptionFlags::StopCompilation;
304 void setStopCompilation() {
305 Flags |= ToolOptionDescriptionFlags::StopCompilation;
308 bool isForward() const {
309 return Flags & ToolOptionDescriptionFlags::Forward;
312 Flags |= ToolOptionDescriptionFlags::Forward;
315 bool isUnpackValues() const {
316 return Flags & ToolOptionDescriptionFlags::UnpackValues;
318 void setUnpackValues() {
319 Flags |= ToolOptionDescriptionFlags::UnpackValues;
322 void AddProperty (OptionPropertyType::OptionPropertyType t,
323 const std::string& val)
325 Props.push_back(std::make_pair(t, val));
329 typedef StringMap<ToolOptionDescription> ToolOptionDescriptions;
331 // Tool information record
333 namespace ToolFlags {
334 enum ToolFlags { Join = 0x1, Sink = 0x2 };
337 struct ToolProperties : public RefCountedBase<ToolProperties> {
340 StrVector InLanguage;
341 std::string OutLanguage;
342 std::string OutputSuffix;
344 ToolOptionDescriptions OptDescs;
346 // Various boolean properties
347 void setSink() { Flags |= ToolFlags::Sink; }
348 bool isSink() const { return Flags & ToolFlags::Sink; }
349 void setJoin() { Flags |= ToolFlags::Join; }
350 bool isJoin() const { return Flags & ToolFlags::Join; }
352 // Default ctor here is needed because StringMap can only store
353 // DefaultConstructible objects
354 ToolProperties() : CmdLine(0), Flags(0) {}
355 ToolProperties (const std::string& n) : Name(n), CmdLine(0), Flags(0) {}
359 /// ToolPropertiesList - A list of Tool information records
360 /// IntrusiveRefCntPtrs are used here because StringMap has no copy
361 /// constructor (and we want to avoid copying ToolProperties anyway).
362 typedef std::vector<IntrusiveRefCntPtr<ToolProperties> > ToolPropertiesList;
365 /// CollectOptionProperties - Function object for iterating over a
366 /// list (usually, a DAG) of option property records.
367 class CollectOptionProperties {
369 // Implementation details.
371 /// OptionPropertyHandler - a function that extracts information
372 /// about a given option property from its DAG representation.
373 typedef void (CollectOptionProperties::* OptionPropertyHandler)
376 /// OptionPropertyHandlerMap - A map from option property names to
377 /// option property handlers
378 typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
380 static OptionPropertyHandlerMap optionPropertyHandlers_;
381 static bool staticMembersInitialized_;
383 /// This is where the information is stored
385 /// toolProps_ - Properties of the current Tool.
386 ToolProperties* toolProps_;
387 /// optDescs_ - OptionDescriptions table (used to register options
389 GlobalOptionDescription& optDesc_;
393 explicit CollectOptionProperties(ToolProperties* TP,
394 GlobalOptionDescription& OD)
395 : toolProps_(TP), optDesc_(OD)
397 if (!staticMembersInitialized_) {
398 optionPropertyHandlers_["append_cmd"] =
399 &CollectOptionProperties::onAppendCmd;
400 optionPropertyHandlers_["forward"] =
401 &CollectOptionProperties::onForward;
402 optionPropertyHandlers_["help"] =
403 &CollectOptionProperties::onHelp;
404 optionPropertyHandlers_["output_suffix"] =
405 &CollectOptionProperties::onOutputSuffix;
406 optionPropertyHandlers_["required"] =
407 &CollectOptionProperties::onRequired;
408 optionPropertyHandlers_["stop_compilation"] =
409 &CollectOptionProperties::onStopCompilation;
410 optionPropertyHandlers_["unpack_values"] =
411 &CollectOptionProperties::onUnpackValues;
413 staticMembersInitialized_ = true;
417 /// operator() - Gets called for every option property; Just forwards
418 /// to the corresponding property handler.
419 void operator() (Init* i) {
420 const DagInit& option_property = InitPtrToDag(i);
421 const std::string& option_property_name
422 = option_property.getOperator()->getAsString();
423 OptionPropertyHandlerMap::iterator method
424 = optionPropertyHandlers_.find(option_property_name);
426 if (method != optionPropertyHandlers_.end()) {
427 OptionPropertyHandler h = method->second;
428 (this->*h)(&option_property);
431 throw "Unknown option property: " + option_property_name + "!";
437 /// Option property handlers --
438 /// Methods that handle properties that are common for all types of
439 /// options (like append_cmd, stop_compilation)
441 void onAppendCmd (const DagInit* d) {
442 checkNumberOfArguments(d, 1);
444 const std::string& cmd = InitPtrToString(d->getArg(0));
446 toolProps_->OptDescs[optDesc_.Name].
447 AddProperty(OptionPropertyType::AppendCmd, cmd);
450 void onOutputSuffix (const DagInit* d) {
451 checkNumberOfArguments(d, 1);
453 const std::string& suf = InitPtrToString(d->getArg(0));
455 if (toolProps_->OptDescs[optDesc_.Name].Type != OptionType::Switch)
456 throw "Option " + optDesc_.Name
457 + " can't have 'output_suffix' property since it isn't a switch!";
459 toolProps_->OptDescs[optDesc_.Name].AddProperty
460 (OptionPropertyType::OutputSuffix, suf);
463 void onForward (const DagInit* d) {
464 checkNumberOfArguments(d, 0);
466 toolProps_->OptDescs[optDesc_.Name].setForward();
469 void onHelp (const DagInit* d) {
470 checkNumberOfArguments(d, 1);
471 const std::string& help_message = InitPtrToString(d->getArg(0));
473 optDesc_.Help = help_message;
476 void onRequired (const DagInit* d) {
477 checkNumberOfArguments(d, 0);
479 optDesc_.setRequired();
482 void onStopCompilation (const DagInit* d) {
483 checkNumberOfArguments(d, 0);
485 if (optDesc_.Type != OptionType::Switch)
486 throw std::string("Only options of type Switch can stop compilation!");
487 toolProps_->OptDescs[optDesc_.Name].setStopCompilation();
490 void onUnpackValues (const DagInit* d) {
491 checkNumberOfArguments(d, 0);
493 toolProps_->OptDescs[optDesc_.Name].setUnpackValues();
498 /// checkToolProps - Throw an error if toolProps_ == 0.
499 void checkToolProps(const DagInit* d) {
501 throw "Option property " + d->getOperator()->getAsString()
502 + " can't be used in this context";
507 CollectOptionProperties::OptionPropertyHandlerMap
508 CollectOptionProperties::optionPropertyHandlers_;
510 bool CollectOptionProperties::staticMembersInitialized_ = false;
513 /// processOptionProperties - Go through the list of option
514 /// properties and call a corresponding handler for each.
515 void processOptionProperties (const DagInit* d, ToolProperties* t,
516 GlobalOptionDescription& o) {
517 checkNumberOfArguments(d, 2);
518 DagInit::const_arg_iterator B = d->arg_begin();
519 // Skip the first argument: it's always the option name.
521 std::for_each(B, d->arg_end(), CollectOptionProperties(t, o));
524 /// AddOption - A function object wrapper for
525 /// processOptionProperties. Used by CollectProperties and
526 /// CollectPropertiesFromOptionList.
529 GlobalOptionDescriptions& OptDescs_;
530 ToolProperties* ToolProps_;
533 explicit AddOption(GlobalOptionDescriptions& OD, ToolProperties* TP = 0)
534 : OptDescs_(OD), ToolProps_(TP)
537 void operator()(const Init* i) {
538 const DagInit& d = InitPtrToDag(i);
539 checkNumberOfArguments(&d, 2);
541 const OptionType::OptionType Type =
542 getOptionType(d.getOperator()->getAsString());
543 const std::string& Name = InitPtrToString(d.getArg(0));
545 GlobalOptionDescription OD(Type, Name);
546 if (Type != OptionType::Alias) {
547 processOptionProperties(&d, ToolProps_, OD);
549 ToolProps_->OptDescs[Name].Type = Type;
550 ToolProps_->OptDescs[Name].Name = Name;
554 OD.Help = InitPtrToString(d.getArg(1));
556 OptDescs_.insertDescription(OD);
560 OptionType::OptionType getOptionType(const std::string& T) const {
561 if (T == "alias_option")
562 return OptionType::Alias;
563 else if (T == "switch_option")
564 return OptionType::Switch;
565 else if (T == "parameter_option")
566 return OptionType::Parameter;
567 else if (T == "parameter_list_option")
568 return OptionType::ParameterList;
569 else if (T == "prefix_option")
570 return OptionType::Prefix;
571 else if (T == "prefix_list_option")
572 return OptionType::PrefixList;
574 throw "Unknown option type: " + T + '!';
579 /// CollectProperties - Function object for iterating over a list of
580 /// tool property records.
581 class CollectProperties {
584 // Implementation details
586 /// PropertyHandler - a function that extracts information
587 /// about a given tool property from its DAG representation
588 typedef void (CollectProperties::*PropertyHandler)(const DagInit*);
590 /// PropertyHandlerMap - A map from property names to property
592 typedef StringMap<PropertyHandler> PropertyHandlerMap;
594 // Static maps from strings to CollectProperties methods("handlers")
595 static PropertyHandlerMap propertyHandlers_;
596 static bool staticMembersInitialized_;
599 /// This is where the information is stored
601 /// toolProps_ - Properties of the current Tool.
602 ToolProperties& toolProps_;
603 /// optDescs_ - OptionDescriptions table (used to register options
605 GlobalOptionDescriptions& optDescs_;
609 explicit CollectProperties (ToolProperties& p, GlobalOptionDescriptions& d)
610 : toolProps_(p), optDescs_(d)
612 if (!staticMembersInitialized_) {
613 propertyHandlers_["cmd_line"] = &CollectProperties::onCmdLine;
614 propertyHandlers_["in_language"] = &CollectProperties::onInLanguage;
615 propertyHandlers_["join"] = &CollectProperties::onJoin;
616 propertyHandlers_["out_language"] = &CollectProperties::onOutLanguage;
617 propertyHandlers_["output_suffix"] = &CollectProperties::onOutputSuffix;
618 propertyHandlers_["parameter_option"]
619 = &CollectProperties::addOption;
620 propertyHandlers_["parameter_list_option"] =
621 &CollectProperties::addOption;
622 propertyHandlers_["prefix_option"] = &CollectProperties::addOption;
623 propertyHandlers_["prefix_list_option"] =
624 &CollectProperties::addOption;
625 propertyHandlers_["sink"] = &CollectProperties::onSink;
626 propertyHandlers_["switch_option"] = &CollectProperties::addOption;
627 propertyHandlers_["alias_option"] = &CollectProperties::addOption;
629 staticMembersInitialized_ = true;
633 /// operator() - Gets called for every tool property; Just forwards
634 /// to the corresponding property handler.
635 void operator() (Init* i) {
636 const DagInit& d = InitPtrToDag(i);
637 const std::string& property_name = d.getOperator()->getAsString();
638 PropertyHandlerMap::iterator method
639 = propertyHandlers_.find(property_name);
641 if (method != propertyHandlers_.end()) {
642 PropertyHandler h = method->second;
646 throw "Unknown tool property: " + property_name + "!";
652 /// Property handlers --
653 /// Functions that extract information about tool properties from
654 /// DAG representation.
656 void onCmdLine (const DagInit* d) {
657 checkNumberOfArguments(d, 1);
658 toolProps_.CmdLine = d->getArg(0);
661 void onInLanguage (const DagInit* d) {
662 checkNumberOfArguments(d, 1);
663 Init* arg = d->getArg(0);
665 // Find out the argument's type.
666 if (typeid(*arg) == typeid(StringInit)) {
668 toolProps_.InLanguage.push_back(InitPtrToString(arg));
672 const ListInit& lst = InitPtrToList(arg);
673 StrVector& out = toolProps_.InLanguage;
675 // Copy strings to the output vector.
676 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
678 out.push_back(InitPtrToString(*B));
681 // Remove duplicates.
682 std::sort(out.begin(), out.end());
683 StrVector::iterator newE = std::unique(out.begin(), out.end());
684 out.erase(newE, out.end());
688 void onJoin (const DagInit* d) {
689 checkNumberOfArguments(d, 0);
690 toolProps_.setJoin();
693 void onOutLanguage (const DagInit* d) {
694 checkNumberOfArguments(d, 1);
695 toolProps_.OutLanguage = InitPtrToString(d->getArg(0));
698 void onOutputSuffix (const DagInit* d) {
699 checkNumberOfArguments(d, 1);
700 toolProps_.OutputSuffix = InitPtrToString(d->getArg(0));
703 void onSink (const DagInit* d) {
704 checkNumberOfArguments(d, 0);
705 optDescs_.HasSink = true;
706 toolProps_.setSink();
709 // Just forwards to the AddOption function object. Somewhat
710 // non-optimal, but avoids code duplication.
711 void addOption (const DagInit* d) {
712 checkNumberOfArguments(d, 2);
713 AddOption(optDescs_, &toolProps_)(d);
718 // Defintions of static members of CollectProperties.
719 CollectProperties::PropertyHandlerMap CollectProperties::propertyHandlers_;
720 bool CollectProperties::staticMembersInitialized_ = false;
723 /// CollectToolProperties - Gather information about tool properties
724 /// from the parsed TableGen data (basically a wrapper for the
725 /// CollectProperties function object).
726 void CollectToolProperties (RecordVector::const_iterator B,
727 RecordVector::const_iterator E,
728 ToolPropertiesList& TPList,
729 GlobalOptionDescriptions& OptDescs)
731 // Iterate over a properties list of every Tool definition
734 // Throws an exception if the value does not exist.
735 ListInit* PropList = T->getValueAsListInit("properties");
737 IntrusiveRefCntPtr<ToolProperties>
738 ToolProps(new ToolProperties(T->getName()));
740 std::for_each(PropList->begin(), PropList->end(),
741 CollectProperties(*ToolProps, OptDescs));
742 TPList.push_back(ToolProps);
747 /// CollectPropertiesFromOptionList - Gather information about
748 /// *global* option properties from the OptionList.
749 void CollectPropertiesFromOptionList (RecordVector::const_iterator B,
750 RecordVector::const_iterator E,
751 GlobalOptionDescriptions& OptDescs)
753 // Iterate over a properties list of every Tool definition
755 RecordVector::value_type T = *B;
756 // Throws an exception if the value does not exist.
757 ListInit* PropList = T->getValueAsListInit("options");
759 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
763 /// CheckForSuperfluousOptions - Check that there are no side
764 /// effect-free options (specified only in the OptionList). Otherwise,
765 /// output a warning.
766 void CheckForSuperfluousOptions (const ToolPropertiesList& TPList,
767 const GlobalOptionDescriptions& OptDescs) {
768 llvm::StringSet<> nonSuperfluousOptions;
770 // Add all options mentioned in the TPList to the set of
771 // non-superfluous options.
772 for (ToolPropertiesList::const_iterator B = TPList.begin(),
773 E = TPList.end(); B != E; ++B) {
774 const ToolProperties& TP = *(*B);
775 for (ToolOptionDescriptions::const_iterator B = TP.OptDescs.begin(),
776 E = TP.OptDescs.end(); B != E; ++B) {
777 nonSuperfluousOptions.insert(B->first());
781 // Check that all options in OptDescs belong to the set of
782 // non-superfluous options.
783 for (GlobalOptionDescriptions::const_iterator B = OptDescs.begin(),
784 E = OptDescs.end(); B != E; ++B) {
785 const GlobalOptionDescription& Val = B->second;
786 if (!nonSuperfluousOptions.count(Val.Name)
787 && Val.Type != OptionType::Alias)
788 cerr << "Warning: option '-" << Val.Name << "' has no effect! "
789 "Probable cause: this option is specified only in the OptionList.\n";
793 /// EmitCaseTest1Arg - Helper function used by
794 /// EmitCaseConstructHandler.
795 bool EmitCaseTest1Arg(const std::string& TestName,
797 const GlobalOptionDescriptions& OptDescs,
799 // TOFIX - Add a mechanism for OS detection.
800 checkNumberOfArguments(&d, 1);
801 const std::string& OptName = InitPtrToString(d.getArg(0));
802 if (TestName == "switch_on") {
803 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
804 if (OptDesc.Type != OptionType::Switch)
805 throw OptName + ": incorrect option type!";
806 O << OptDesc.GenVariableName();
808 } else if (TestName == "input_languages_contain") {
809 O << "InLangs.count(\"" << OptName << "\") != 0";
811 } else if (TestName == "in_language") {
812 // Works only for cmd_line!
813 O << "GetLanguage(inFile) == \"" << OptName << '\"';
815 } else if (TestName == "not_empty") {
816 if (OptName == "o") {
817 O << "!OutputFilename.empty()";
821 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
822 if (OptDesc.Type == OptionType::Switch)
823 throw OptName + ": incorrect option type!";
824 O << '!' << OptDesc.GenVariableName() << ".empty()";
832 /// EmitCaseTest2Args - Helper function used by
833 /// EmitCaseConstructHandler.
834 bool EmitCaseTest2Args(const std::string& TestName,
836 const char* IndentLevel,
837 const GlobalOptionDescriptions& OptDescs,
839 checkNumberOfArguments(&d, 2);
840 const std::string& OptName = InitPtrToString(d.getArg(0));
841 const std::string& OptArg = InitPtrToString(d.getArg(1));
842 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
844 if (TestName == "parameter_equals") {
845 if (OptDesc.Type != OptionType::Parameter
846 && OptDesc.Type != OptionType::Prefix)
847 throw OptName + ": incorrect option type!";
848 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
851 else if (TestName == "element_in_list") {
852 if (OptDesc.Type != OptionType::ParameterList
853 && OptDesc.Type != OptionType::PrefixList)
854 throw OptName + ": incorrect option type!";
855 const std::string& VarName = OptDesc.GenVariableName();
856 O << "std::find(" << VarName << ".begin(),\n"
857 << IndentLevel << Indent1 << VarName << ".end(), \""
858 << OptArg << "\") != " << VarName << ".end()";
865 // Forward declaration.
866 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
867 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
868 const GlobalOptionDescriptions& OptDescs,
871 /// EmitLogicalOperationTest - Helper function used by
872 /// EmitCaseConstructHandler.
873 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
874 const char* IndentLevel,
875 const GlobalOptionDescriptions& OptDescs,
878 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
879 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
880 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
881 if (j != NumArgs - 1)
882 O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
888 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
889 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
890 const GlobalOptionDescriptions& OptDescs,
892 const std::string& TestName = d.getOperator()->getAsString();
894 if (TestName == "and")
895 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
896 else if (TestName == "or")
897 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
898 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
900 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
903 throw TestName + ": unknown edge property!";
906 // Emit code that handles the 'case' construct.
907 // Takes a function object that should emit code for every case clause.
908 // Callback's type is
909 // void F(Init* Statement, const char* IndentLevel, std::ostream& O).
910 template <typename F>
911 void EmitCaseConstructHandler(const DagInit* d, const char* IndentLevel,
912 F Callback, bool EmitElseIf,
913 const GlobalOptionDescriptions& OptDescs,
915 assert(d->getOperator()->getAsString() == "case");
917 unsigned numArgs = d->getNumArgs();
918 if (d->getNumArgs() < 2)
919 throw "There should be at least one clause in the 'case' expression:\n"
922 for (unsigned i = 0; i != numArgs; ++i) {
923 const DagInit& Test = InitPtrToDag(d->getArg(i));
926 if (Test.getOperator()->getAsString() == "default") {
928 throw std::string("The 'default' clause should be the last in the"
929 "'case' construct!");
930 O << IndentLevel << "else {\n";
933 O << IndentLevel << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
934 EmitCaseTest(Test, IndentLevel, OptDescs, O);
938 // Emit the corresponding statement.
941 throw "Case construct handler: no corresponding action "
942 "found for the test " + Test.getAsString() + '!';
944 Init* arg = d->getArg(i);
945 if (dynamic_cast<DagInit*>(arg)
946 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case") {
947 EmitCaseConstructHandler(static_cast<DagInit*>(arg),
948 (std::string(IndentLevel) + Indent1).c_str(),
949 Callback, EmitElseIf, OptDescs, O);
952 Callback(arg, IndentLevel, O);
954 O << IndentLevel << "}\n";
958 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
959 /// implement EmitOptionPropertyHandlingCode(). Emits code for
960 /// handling the (forward) option property.
961 void EmitForwardOptionPropertyHandlingCode (const ToolOptionDescription& D,
964 case OptionType::Switch:
965 O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
967 case OptionType::Parameter:
968 O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
969 O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
971 case OptionType::Prefix:
972 O << Indent3 << "vec.push_back(\"-" << D.Name << "\" + "
973 << D.GenVariableName() << ");\n";
975 case OptionType::PrefixList:
976 O << Indent3 << "for (" << D.GenTypeDeclaration()
977 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
978 << Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
979 << Indent4 << "vec.push_back(\"-" << D.Name << "\" + "
982 case OptionType::ParameterList:
983 O << Indent3 << "for (" << D.GenTypeDeclaration()
984 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
985 << Indent3 << "E = " << D.GenVariableName()
986 << ".end() ; B != E; ++B) {\n"
987 << Indent4 << "vec.push_back(\"-" << D.Name << "\");\n"
988 << Indent4 << "vec.push_back(*B);\n"
991 case OptionType::Alias:
993 throw std::string("Aliases are not allowed in tool option descriptions!");
997 // ToolOptionHasInterestingProperties - A helper function used by
998 // EmitOptionPropertyHandlingCode() that tells us whether we should
999 // emit any property handling code at all.
1000 bool ToolOptionHasInterestingProperties(const ToolOptionDescription& D) {
1002 for (OptionPropertyList::const_iterator B = D.Props.begin(),
1003 E = D.Props.end(); B != E; ++B) {
1004 const OptionProperty& OptProp = *B;
1005 if (OptProp.first == OptionPropertyType::AppendCmd)
1008 if (D.isForward() || D.isUnpackValues())
1013 /// EmitOptionPropertyHandlingCode - Helper function used by
1014 /// EmitGenerateActionMethod(). Emits code that handles option
1016 void EmitOptionPropertyHandlingCode (const ToolOptionDescription& D,
1019 if (!ToolOptionHasInterestingProperties(D))
1021 // Start of the if-clause.
1022 O << Indent2 << "if (";
1023 if (D.Type == OptionType::Switch)
1024 O << D.GenVariableName();
1026 O << '!' << D.GenVariableName() << ".empty()";
1030 // Handle option properties that take an argument.
1031 for (OptionPropertyList::const_iterator B = D.Props.begin(),
1032 E = D.Props.end(); B!=E; ++B) {
1033 const OptionProperty& val = *B;
1035 switch (val.first) {
1036 // (append_cmd cmd) property
1037 case OptionPropertyType::AppendCmd:
1038 O << Indent3 << "vec.push_back(\"" << val.second << "\");\n";
1040 // Other properties with argument
1048 // (forward) property
1050 EmitForwardOptionPropertyHandlingCode(D, O);
1052 // (unpack_values) property
1053 if (D.isUnpackValues()) {
1054 if (IsListOptionType(D.Type)) {
1055 O << Indent3 << "for (" << D.GenTypeDeclaration()
1056 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1057 << Indent3 << "E = " << D.GenVariableName()
1058 << ".end(); B != E; ++B)\n"
1059 << Indent4 << "llvm::SplitString(*B, vec, \",\");\n";
1061 else if (D.Type == OptionType::Prefix || D.Type == OptionType::Parameter){
1062 O << Indent3 << "llvm::SplitString("
1063 << D.GenVariableName() << ", vec, \",\");\n";
1066 throw std::string("Switches can't have unpack_values property!");
1070 // End of the if-clause.
1071 O << Indent2 << "}\n";
1074 /// SubstituteSpecialCommands - Perform string substitution for $CALL
1075 /// and $ENV. Helper function used by EmitCmdLineVecFill().
1076 std::string SubstituteSpecialCommands(const std::string& cmd) {
1077 size_t cparen = cmd.find(")");
1080 if (cmd.find("$CALL(") == 0) {
1081 if (cmd.size() == 6)
1082 throw std::string("$CALL invocation: empty argument list!");
1085 ret += std::string(cmd.begin() + 6, cmd.begin() + cparen);
1088 else if (cmd.find("$ENV(") == 0) {
1089 if (cmd.size() == 5)
1090 throw std::string("$ENV invocation: empty argument list!");
1092 ret += "std::getenv(\"";
1093 ret += std::string(cmd.begin() + 5, cmd.begin() + cparen);
1097 throw "Unknown special command: " + cmd;
1100 if (cmd.begin() + cparen + 1 != cmd.end()) {
1101 ret += " + std::string(\"";
1102 ret += (cmd.c_str() + cparen + 1);
1109 /// EmitCmdLineVecFill - Emit code that fills in the command line
1110 /// vector. Helper function used by EmitGenerateActionMethod().
1111 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1112 bool Version, const char* IndentLevel,
1115 SplitString(InitPtrToString(CmdLine), StrVec);
1117 throw "Tool " + ToolName + " has empty command line!";
1119 StrVector::const_iterator I = StrVec.begin();
1121 for (StrVector::const_iterator E = StrVec.end(); I != E; ++I) {
1122 const std::string& cmd = *I;
1124 if (cmd.at(0) == '$') {
1125 if (cmd == "$INFILE") {
1127 O << "for (PathVector::const_iterator B = inFiles.begin()"
1128 << ", E = inFiles.end();\n"
1129 << IndentLevel << "B != E; ++B)\n"
1130 << IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
1132 O << "vec.push_back(inFile.toString());\n";
1134 else if (cmd == "$OUTFILE") {
1135 O << "vec.push_back(outFile.toString());\n";
1138 O << "vec.push_back(" << SubstituteSpecialCommands(cmd);
1143 O << "vec.push_back(\"" << cmd << "\");\n";
1146 O << IndentLevel << "cmd = "
1147 << ((StrVec[0][0] == '$') ? SubstituteSpecialCommands(StrVec[0])
1148 : "\"" + StrVec[0] + "\"")
1152 /// EmitCmdLineVecFillCallback - A function object wrapper around
1153 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1154 /// argument to EmitCaseConstructHandler().
1155 class EmitCmdLineVecFillCallback {
1157 const std::string& ToolName;
1159 EmitCmdLineVecFillCallback(bool Ver, const std::string& TN)
1160 : Version(Ver), ToolName(TN) {}
1162 void operator()(const Init* Statement, const char* IndentLevel,
1163 std::ostream& O) const
1165 EmitCmdLineVecFill(Statement, ToolName, Version,
1166 (std::string(IndentLevel) + Indent1).c_str(), O);
1170 // EmitGenerateActionMethod - Emit one of two versions of the
1171 // Tool::GenerateAction() method.
1172 void EmitGenerateActionMethod (const ToolProperties& P,
1173 const GlobalOptionDescriptions& OptDescs,
1174 bool Version, std::ostream& O) {
1176 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
1178 O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
1180 O << Indent2 << "const sys::Path& outFile,\n"
1181 << Indent2 << "const InputLanguagesSet& InLangs) const\n"
1183 << Indent2 << "const char* cmd;\n"
1184 << Indent2 << "std::vector<std::string> vec;\n";
1186 // cmd_line is either a string or a 'case' construct.
1187 if (typeid(*P.CmdLine) == typeid(StringInit))
1188 EmitCmdLineVecFill(P.CmdLine, P.Name, Version, Indent2, O);
1190 EmitCaseConstructHandler(&InitPtrToDag(P.CmdLine), Indent2,
1191 EmitCmdLineVecFillCallback(Version, P.Name),
1194 // For every understood option, emit handling code.
1195 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1196 E = P.OptDescs.end(); B != E; ++B) {
1197 const ToolOptionDescription& val = B->second;
1198 EmitOptionPropertyHandlingCode(val, O);
1201 // Handle the Sink property.
1203 O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
1204 << Indent3 << "vec.insert(vec.end(), "
1205 << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
1206 << Indent2 << "}\n";
1209 O << Indent2 << "return Action(cmd, vec);\n"
1210 << Indent1 << "}\n\n";
1213 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1214 /// a given Tool class.
1215 void EmitGenerateActionMethods (const ToolProperties& P,
1216 const GlobalOptionDescriptions& OptDescs,
1219 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
1220 << Indent2 << "const llvm::sys::Path& outFile,\n"
1221 << Indent2 << "const InputLanguagesSet& InLangs) const\n"
1223 << Indent2 << "throw std::runtime_error(\"" << P.Name
1224 << " is not a Join tool!\");\n"
1225 << Indent1 << "}\n\n";
1227 EmitGenerateActionMethod(P, OptDescs, true, O);
1229 EmitGenerateActionMethod(P, OptDescs, false, O);
1232 /// EmitIsLastMethod - Emit the IsLast() method for a given Tool
1234 void EmitIsLastMethod (const ToolProperties& P, std::ostream& O) {
1235 O << Indent1 << "bool IsLast() const {\n"
1236 << Indent2 << "bool last = false;\n";
1238 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1239 E = P.OptDescs.end(); B != E; ++B) {
1240 const ToolOptionDescription& val = B->second;
1242 if (val.isStopCompilation())
1244 << "if (" << val.GenVariableName()
1245 << ")\n" << Indent3 << "last = true;\n";
1248 O << Indent2 << "return last;\n"
1249 << Indent1 << "}\n\n";
1252 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1253 /// methods for a given Tool class.
1254 void EmitInOutLanguageMethods (const ToolProperties& P, std::ostream& O) {
1255 O << Indent1 << "const char** InputLanguages() const {\n"
1256 << Indent2 << "return InputLanguages_;\n"
1257 << Indent1 << "}\n\n";
1259 O << Indent1 << "const char* OutputLanguage() const {\n"
1260 << Indent2 << "return \"" << P.OutLanguage << "\";\n"
1261 << Indent1 << "}\n\n";
1264 /// EmitOutputSuffixMethod - Emit the OutputSuffix() method for a
1265 /// given Tool class.
1266 void EmitOutputSuffixMethod (const ToolProperties& P, std::ostream& O) {
1267 O << Indent1 << "const char* OutputSuffix() const {\n"
1268 << Indent2 << "const char* ret = \"" << P.OutputSuffix << "\";\n";
1270 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1271 E = P.OptDescs.end(); B != E; ++B) {
1272 const ToolOptionDescription& OptDesc = B->second;
1273 for (OptionPropertyList::const_iterator B = OptDesc.Props.begin(),
1274 E = OptDesc.Props.end(); B != E; ++B) {
1275 const OptionProperty& OptProp = *B;
1276 if (OptProp.first == OptionPropertyType::OutputSuffix) {
1277 O << Indent2 << "if (" << OptDesc.GenVariableName() << ")\n"
1278 << Indent3 << "ret = \"" << OptProp.second << "\";\n";
1283 O << Indent2 << "return ret;\n"
1284 << Indent1 << "}\n\n";
1287 /// EmitNameMethod - Emit the Name() method for a given Tool class.
1288 void EmitNameMethod (const ToolProperties& P, std::ostream& O) {
1289 O << Indent1 << "const char* Name() const {\n"
1290 << Indent2 << "return \"" << P.Name << "\";\n"
1291 << Indent1 << "}\n\n";
1294 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1296 void EmitIsJoinMethod (const ToolProperties& P, std::ostream& O) {
1297 O << Indent1 << "bool IsJoin() const {\n";
1299 O << Indent2 << "return true;\n";
1301 O << Indent2 << "return false;\n";
1302 O << Indent1 << "}\n\n";
1305 /// EmitStaticMemberDefinitions - Emit static member definitions for a
1306 /// given Tool class.
1307 void EmitStaticMemberDefinitions(const ToolProperties& P, std::ostream& O) {
1308 O << "const char* " << P.Name << "::InputLanguages_[] = {";
1309 for (StrVector::const_iterator B = P.InLanguage.begin(),
1310 E = P.InLanguage.end(); B != E; ++B)
1311 O << '\"' << *B << "\", ";
1315 /// EmitToolClassDefinition - Emit a Tool class definition.
1316 void EmitToolClassDefinition (const ToolProperties& P,
1317 const GlobalOptionDescriptions& OptDescs,
1319 if (P.Name == "root")
1323 O << "class " << P.Name << " : public ";
1329 O << "{\nprivate:\n"
1330 << Indent1 << "static const char* InputLanguages_[];\n\n";
1333 EmitNameMethod(P, O);
1334 EmitInOutLanguageMethods(P, O);
1335 EmitOutputSuffixMethod(P, O);
1336 EmitIsJoinMethod(P, O);
1337 EmitGenerateActionMethods(P, OptDescs, O);
1338 EmitIsLastMethod(P, O);
1340 // Close class definition
1343 EmitStaticMemberDefinitions(P, O);
1347 /// EmitOptionDescriptions - Iterate over a list of option
1348 /// descriptions and emit registration code.
1349 void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
1352 std::vector<GlobalOptionDescription> Aliases;
1354 // Emit static cl::Option variables.
1355 for (GlobalOptionDescriptions::const_iterator B = descs.begin(),
1356 E = descs.end(); B!=E; ++B) {
1357 const GlobalOptionDescription& val = B->second;
1359 if (val.Type == OptionType::Alias) {
1360 Aliases.push_back(val);
1364 O << val.GenTypeDeclaration() << ' '
1365 << val.GenVariableName()
1366 << "(\"" << val.Name << '\"';
1368 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1369 O << ", cl::Prefix";
1371 if (val.isRequired()) {
1373 case OptionType::PrefixList:
1374 case OptionType::ParameterList:
1375 O << ", cl::OneOrMore";
1378 O << ", cl::Required";
1382 if (!val.Help.empty())
1383 O << ", cl::desc(\"" << val.Help << "\")";
1388 // Emit the aliases (they should go after all the 'proper' options).
1389 for (std::vector<GlobalOptionDescription>::const_iterator
1390 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
1391 const GlobalOptionDescription& val = *B;
1393 O << val.GenTypeDeclaration() << ' '
1394 << val.GenVariableName()
1395 << "(\"" << val.Name << '\"';
1397 GlobalOptionDescriptions::container_type
1398 ::const_iterator F = descs.Descriptions.find(val.Help);
1399 if (F != descs.Descriptions.end())
1400 O << ", cl::aliasopt(" << F->second.GenVariableName() << ")";
1402 throw val.Name + ": alias to an unknown option!";
1404 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
1407 // Emit the sink option.
1409 O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
1414 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
1415 void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
1417 // Get the relevant field out of RecordKeeper
1418 Record* LangMapRecord = Records.getDef("LanguageMap");
1420 throw std::string("Language map definition not found!");
1422 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
1423 if (!LangsToSuffixesList)
1424 throw std::string("Error in the language map definition!");
1427 O << "void llvmc::PopulateLanguageMap() {\n";
1429 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
1430 Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
1432 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
1433 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
1435 for (unsigned i = 0; i < Suffixes->size(); ++i)
1436 O << Indent1 << "GlobalLanguageMap[\""
1437 << InitPtrToString(Suffixes->getElement(i))
1438 << "\"] = \"" << Lang << "\";\n";
1444 /// FillInToolToLang - Fills in two tables that map tool names to
1445 /// (input, output) languages. Used by the typechecker.
1446 void FillInToolToLang (const ToolPropertiesList& TPList,
1447 StringMap<StringSet<> >& ToolToInLang,
1448 StringMap<std::string>& ToolToOutLang) {
1449 for (ToolPropertiesList::const_iterator B = TPList.begin(), E = TPList.end();
1451 const ToolProperties& P = *(*B);
1452 for (StrVector::const_iterator B = P.InLanguage.begin(),
1453 E = P.InLanguage.end(); B != E; ++B)
1454 ToolToInLang[P.Name].insert(*B);
1455 ToolToOutLang[P.Name] = P.OutLanguage;
1459 /// TypecheckGraph - Check that names for output and input languages
1460 /// on all edges do match.
1461 // TOFIX: It would be nice if this function also checked for cycles
1462 // and multiple default edges in the graph (better error
1463 // reporting). Unfortunately, it is awkward to do right now because
1464 // our intermediate representation is not sufficiently
1465 // sofisticated. Algorithms like these should be run on a real graph
1467 void TypecheckGraph (Record* CompilationGraph,
1468 const ToolPropertiesList& TPList) {
1469 StringMap<StringSet<> > ToolToInLang;
1470 StringMap<std::string> ToolToOutLang;
1472 FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
1473 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1474 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
1475 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
1477 for (unsigned i = 0; i < edges->size(); ++i) {
1478 Record* Edge = edges->getElementAsRecord(i);
1479 Record* A = Edge->getValueAsDef("a");
1480 Record* B = Edge->getValueAsDef("b");
1481 StringMap<std::string>::iterator IA = ToolToOutLang.find(A->getName());
1482 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(B->getName());
1484 throw A->getName() + ": no such tool!";
1486 throw B->getName() + ": no such tool!";
1487 if (A->getName() != "root" && IB->second.count(IA->second) == 0)
1488 throw "Edge " + A->getName() + "->" + B->getName()
1489 + ": output->input language mismatch";
1490 if (B->getName() == "root")
1491 throw std::string("Edges back to the root are not allowed!");
1495 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
1496 /// by EmitEdgeClass().
1497 void IncDecWeight (const Init* i, const char* IndentLevel,
1499 const DagInit& d = InitPtrToDag(i);
1500 const std::string& OpName = d.getOperator()->getAsString();
1502 if (OpName == "inc_weight")
1503 O << IndentLevel << Indent1 << "ret += ";
1504 else if (OpName == "dec_weight")
1505 O << IndentLevel << Indent1 << "ret -= ";
1507 throw "Unknown operator in edge properties list: " + OpName + '!';
1509 if (d.getNumArgs() > 0)
1510 O << InitPtrToInt(d.getArg(0)) << ";\n";
1516 /// EmitEdgeClass - Emit a single Edge# class.
1517 void EmitEdgeClass (unsigned N, const std::string& Target,
1518 DagInit* Case, const GlobalOptionDescriptions& OptDescs,
1521 // Class constructor.
1522 O << "class Edge" << N << ": public Edge {\n"
1524 << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1527 // Function Weight().
1528 << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
1529 << Indent2 << "unsigned ret = 0;\n";
1531 // Handle the 'case' construct.
1532 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
1534 O << Indent2 << "return ret;\n"
1535 << Indent1 << "};\n\n};\n\n";
1538 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
1539 void EmitEdgeClasses (Record* CompilationGraph,
1540 const GlobalOptionDescriptions& OptDescs,
1542 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1544 for (unsigned i = 0; i < edges->size(); ++i) {
1545 Record* Edge = edges->getElementAsRecord(i);
1546 Record* B = Edge->getValueAsDef("b");
1547 DagInit* Weight = Edge->getValueAsDag("weight");
1549 if (isDagEmpty(Weight))
1552 EmitEdgeClass(i, B->getName(), Weight, OptDescs, O);
1556 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1558 void EmitPopulateCompilationGraph (Record* CompilationGraph,
1561 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1564 O << "void llvmc::PopulateCompilationGraph(CompilationGraph& G) {\n"
1565 << Indent1 << "PopulateLanguageMap();\n\n";
1569 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1571 throw std::string("No tool definitions found!");
1573 for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
1574 const std::string& Name = (*B)->getName();
1576 O << Indent1 << "G.insertNode(new "
1577 << Name << "());\n";
1583 for (unsigned i = 0; i < edges->size(); ++i) {
1584 Record* Edge = edges->getElementAsRecord(i);
1585 Record* A = Edge->getValueAsDef("a");
1586 Record* B = Edge->getValueAsDef("b");
1587 DagInit* Weight = Edge->getValueAsDag("weight");
1589 O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
1591 if (isDagEmpty(Weight))
1592 O << "new SimpleEdge(\"" << B->getName() << "\")";
1594 O << "new Edge" << i << "()";
1602 /// ExtractHookNames - Extract the hook names from all instances of
1603 /// $CALL(HookName) in the provided command line string. Helper
1604 /// function used by FillInHookNames().
1605 void ExtractHookNames(const Init* CmdLine, StrVector& HookNames) {
1607 llvm::SplitString(InitPtrToString(CmdLine), cmds);
1608 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
1610 const std::string& cmd = *B;
1611 if (cmd.find("$CALL(") == 0) {
1612 if (cmd.size() == 6)
1613 throw std::string("$CALL invocation: empty argument list!");
1614 HookNames.push_back(std::string(cmd.begin() + 6,
1615 cmd.begin() + cmd.find(")")));
1620 /// ExtractHookNamesFromCaseConstruct - Extract hook names from the
1621 /// 'case' expression, handle nesting. Helper function used by
1622 /// FillInHookNames().
1623 void ExtractHookNamesFromCaseConstruct(Init* Case, StrVector& HookNames) {
1624 const DagInit& d = InitPtrToDag(Case);
1626 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1629 if (even && dynamic_cast<DagInit*>(arg)
1630 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
1631 ExtractHookNamesFromCaseConstruct(arg, HookNames);
1633 ExtractHookNames(arg, HookNames);
1638 /// FillInHookNames - Actually extract the hook names from all command
1639 /// line strings. Helper function used by EmitHookDeclarations().
1640 void FillInHookNames(const ToolPropertiesList& TPList,
1641 StrVector& HookNames) {
1642 // For all command lines:
1643 for (ToolPropertiesList::const_iterator B = TPList.begin(),
1644 E = TPList.end(); B != E; ++B) {
1645 const ToolProperties& P = *(*B);
1648 if (dynamic_cast<StringInit*>(P.CmdLine))
1649 // This is a string.
1650 ExtractHookNames(P.CmdLine, HookNames);
1652 // This is a 'case' construct.
1653 ExtractHookNamesFromCaseConstruct(P.CmdLine, HookNames);
1657 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
1658 /// property records and emit hook function declaration for each
1659 /// instance of $CALL(HookName).
1660 void EmitHookDeclarations(const ToolPropertiesList& ToolProps,
1662 StrVector HookNames;
1663 FillInHookNames(ToolProps, HookNames);
1664 if (HookNames.empty())
1666 std::sort(HookNames.begin(), HookNames.end());
1667 StrVector::const_iterator E = std::unique(HookNames.begin(), HookNames.end());
1669 O << "namespace hooks {\n";
1670 for (StrVector::const_iterator B = HookNames.begin(); B != E; ++B)
1671 O << Indent1 << "std::string " << *B << "();\n";
1676 // End of anonymous namespace
1679 /// run - The back-end entry point.
1680 void LLVMCConfigurationEmitter::run (std::ostream &O) {
1683 // Emit file header.
1684 EmitSourceFileHeader("LLVMC Configuration Library", O);
1686 // Get a list of all defined Tools.
1687 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1689 throw std::string("No tool definitions found!");
1691 // Gather information from the Tool description dags.
1692 ToolPropertiesList tool_props;
1693 GlobalOptionDescriptions opt_descs;
1694 CollectToolProperties(Tools.begin(), Tools.end(), tool_props, opt_descs);
1696 RecordVector OptionLists = Records.getAllDerivedDefinitions("OptionList");
1697 CollectPropertiesFromOptionList(OptionLists.begin(), OptionLists.end(),
1700 // Check that there are no options without side effects (specified
1701 // only in the OptionList).
1702 CheckForSuperfluousOptions(tool_props, opt_descs);
1704 // Emit global option registration code.
1705 EmitOptionDescriptions(opt_descs, O);
1707 // Emit hook declarations.
1708 EmitHookDeclarations(tool_props, O);
1710 // Emit PopulateLanguageMap() function
1711 // (a language map maps from file extensions to language names).
1712 EmitPopulateLanguageMap(Records, O);
1714 // Emit Tool classes.
1715 for (ToolPropertiesList::const_iterator B = tool_props.begin(),
1716 E = tool_props.end(); B!=E; ++B)
1717 EmitToolClassDefinition(*(*B), opt_descs, O);
1719 Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
1720 if (!CompilationGraphRecord)
1721 throw std::string("Compilation graph description not found!");
1723 // Typecheck the compilation graph.
1724 TypecheckGraph(CompilationGraphRecord, tool_props);
1726 // Emit Edge# classes.
1727 EmitEdgeClasses(CompilationGraphRecord, opt_descs, O);
1729 // Emit PopulateCompilationGraph() function.
1730 EmitPopulateCompilationGraph(CompilationGraphRecord, O);
1733 } catch (std::exception& Error) {
1734 throw Error.what() + std::string(" - usually this means a syntax error.");