1 //===- LLVMCConfigurationEmitter.cpp - Generate LLVMCC 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 LLVMCC configuration code.
12 //===----------------------------------------------------------------------===//
14 #include "LLVMCCConfigurationEmitter.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 std::string InitPtrToString(Init* ptr) {
57 StringInit& val = dynamic_cast<StringInit&>(*ptr);
58 return val.getValue();
61 //===----------------------------------------------------------------------===//
62 /// Back-end specific code
64 // A command-line option can have one of the following types:
66 // Switch - a simple switch w/o arguments, e.g. -O2
68 // Parameter - an option that takes one(and only one) argument, e.g. -o file,
71 // ParameterList - same as Parameter, but more than one occurence
72 // of the option is allowed, e.g. -lm -lpthread
74 // Prefix - argument is everything after the prefix,
75 // e.g. -Wa,-foo,-bar, -DNAME=VALUE
77 // PrefixList - same as Prefix, but more than one option occurence is
80 namespace OptionType {
81 enum OptionType { Switch, Parameter, ParameterList, Prefix, PrefixList};
84 bool IsListOptionType (OptionType::OptionType t) {
85 return (t == OptionType::ParameterList || t == OptionType::PrefixList);
88 // Code duplication here is necessary because one option can affect
89 // several tools and those tools may have different actions associated
90 // with this option. GlobalOptionDescriptions are used to generate
91 // the option registration code, while ToolOptionDescriptions are used
92 // to generate tool-specific code.
94 // Base class for option descriptions
96 struct OptionDescription {
97 OptionType::OptionType Type;
100 OptionDescription(OptionType::OptionType t = OptionType::Switch,
101 const std::string& n = "")
105 const char* GenTypeDeclaration() const {
107 case OptionType::PrefixList:
108 case OptionType::ParameterList:
109 return "cl::list<std::string>";
110 case OptionType::Switch:
111 return "cl::opt<bool>";
112 case OptionType::Parameter:
113 case OptionType::Prefix:
115 return "cl::opt<std::string>";
119 std::string GenVariableName() const {
121 case OptionType::Switch:
122 return "AutoGeneratedSwitch" + Name;
123 case OptionType::Prefix:
124 return "AutoGeneratedPrefix" + Name;
125 case OptionType::PrefixList:
126 return "AutoGeneratedPrefixList" + Name;
127 case OptionType::Parameter:
128 return "AutoGeneratedParameter" + Name;
129 case OptionType::ParameterList:
131 return "AutoGeneratedParameterList" + Name;
137 // Global option description
139 namespace GlobalOptionDescriptionFlags {
140 enum GlobalOptionDescriptionFlags { Required = 0x1 };
143 struct GlobalOptionDescription : public OptionDescription {
147 // We need t provide a default constructor since
148 // StringMap can only store DefaultConstructible objects
149 GlobalOptionDescription() : OptionDescription(), Flags(0)
152 GlobalOptionDescription (OptionType::OptionType t, const std::string& n)
153 : OptionDescription(t, n), Help(DefaultHelpString), Flags(0)
156 bool isRequired() const {
157 return Flags & GlobalOptionDescriptionFlags::Required;
160 Flags |= GlobalOptionDescriptionFlags::Required;
163 // Merge two option descriptions
164 void Merge (const GlobalOptionDescription& other)
166 if (other.Type != Type)
167 throw "Conflicting definitions for the option " + Name + "!";
169 if (Help.empty() && !other.Help.empty())
171 else if (!Help.empty() && !other.Help.empty())
172 cerr << "Warning: more than one help string defined for option "
175 Flags |= other.Flags;
179 // A GlobalOptionDescription array
180 // + some flags affecting generation of option declarations
181 struct GlobalOptionDescriptions {
182 typedef StringMap<GlobalOptionDescription> container_type;
183 typedef container_type::const_iterator const_iterator;
185 // A list of GlobalOptionDescriptions
186 container_type Descriptions;
187 // Should the emitter generate a "cl::sink" option?
190 // Support for STL-style iteration
191 const_iterator begin() const { return Descriptions.begin(); }
192 const_iterator end() const { return Descriptions.end(); }
196 // Tool-local option description
198 // Properties without arguments are implemented as flags
199 namespace ToolOptionDescriptionFlags {
200 enum ToolOptionDescriptionFlags { StopCompilation = 0x1,
201 Forward = 0x2, UnpackValues = 0x4};
203 namespace OptionPropertyType {
204 enum OptionPropertyType { AppendCmd };
207 typedef std::pair<OptionPropertyType::OptionPropertyType, std::string>
209 typedef SmallVector<OptionProperty, 4> OptionPropertyList;
211 struct ToolOptionDescription : public OptionDescription {
213 OptionPropertyList Props;
215 // StringMap can only store DefaultConstructible objects
216 ToolOptionDescription() : OptionDescription(), Flags(0) {}
218 ToolOptionDescription (OptionType::OptionType t, const std::string& n)
219 : OptionDescription(t, n)
222 // Various boolean properties
223 bool isStopCompilation() const {
224 return Flags & ToolOptionDescriptionFlags::StopCompilation;
226 void setStopCompilation() {
227 Flags |= ToolOptionDescriptionFlags::StopCompilation;
230 bool isForward() const {
231 return Flags & ToolOptionDescriptionFlags::Forward;
234 Flags |= ToolOptionDescriptionFlags::Forward;
237 bool isUnpackValues() const {
238 return Flags & ToolOptionDescriptionFlags::UnpackValues;
240 void setUnpackValues() {
241 Flags |= ToolOptionDescriptionFlags::UnpackValues;
244 void AddProperty (OptionPropertyType::OptionPropertyType t,
245 const std::string& val)
247 Props.push_back(std::make_pair(t, val));
251 typedef StringMap<ToolOptionDescription> ToolOptionDescriptions;
253 // Tool information record
255 namespace ToolFlags {
256 enum ToolFlags { Join = 0x1, Sink = 0x2 };
259 struct ToolProperties : public RefCountedBase<ToolProperties> {
262 std::string InLanguage;
263 std::string OutLanguage;
264 std::string OutputSuffix;
266 ToolOptionDescriptions OptDescs;
268 // Various boolean properties
269 void setSink() { Flags |= ToolFlags::Sink; }
270 bool isSink() const { return Flags & ToolFlags::Sink; }
271 void setJoin() { Flags |= ToolFlags::Join; }
272 bool isJoin() const { return Flags & ToolFlags::Join; }
274 // Default ctor here is needed because StringMap can only store
275 // DefaultConstructible objects
277 ToolProperties (const std::string& n) : Name(n) {}
281 // A list of Tool information records
282 // IntrusiveRefCntPtrs are used because StringMap has no copy constructor
283 // (and we want to avoid copying ToolProperties anyway)
284 typedef std::vector<IntrusiveRefCntPtr<ToolProperties> > ToolPropertiesList;
287 // Function object for iterating over a list of tool property records
288 class CollectProperties {
291 /// Implementation details
293 // "Property handler" - a function that extracts information
294 // about a given tool property from its DAG representation
295 typedef void (CollectProperties::*PropertyHandler)(DagInit*);
297 // Map from property names -> property handlers
298 typedef StringMap<PropertyHandler> PropertyHandlerMap;
300 // "Option property handler" - a function that extracts information
301 // about a given option property from its DAG representation
302 typedef void (CollectProperties::*
303 OptionPropertyHandler)(DagInit*, GlobalOptionDescription &);
305 // Map from option property names -> option property handlers
306 typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
308 // Static maps from strings to CollectProperties methods("handlers")
309 static PropertyHandlerMap propertyHandlers_;
310 static OptionPropertyHandlerMap optionPropertyHandlers_;
311 static bool staticMembersInitialized_;
314 /// This is where the information is stored
316 // Current Tool properties
317 ToolProperties& toolProps_;
318 // OptionDescriptions table(used to register options globally)
319 GlobalOptionDescriptions& optDescs_;
323 explicit CollectProperties (ToolProperties& p, GlobalOptionDescriptions& d)
324 : toolProps_(p), optDescs_(d)
326 if (!staticMembersInitialized_) {
327 // Init tool property handlers
328 propertyHandlers_["cmd_line"] = &CollectProperties::onCmdLine;
329 propertyHandlers_["in_language"] = &CollectProperties::onInLanguage;
330 propertyHandlers_["join"] = &CollectProperties::onJoin;
331 propertyHandlers_["out_language"] = &CollectProperties::onOutLanguage;
332 propertyHandlers_["output_suffix"] = &CollectProperties::onOutputSuffix;
333 propertyHandlers_["parameter_option"]
334 = &CollectProperties::onParameter;
335 propertyHandlers_["parameter_list_option"] =
336 &CollectProperties::onParameterList;
337 propertyHandlers_["prefix_option"] = &CollectProperties::onPrefix;
338 propertyHandlers_["prefix_list_option"] =
339 &CollectProperties::onPrefixList;
340 propertyHandlers_["sink"] = &CollectProperties::onSink;
341 propertyHandlers_["switch_option"] = &CollectProperties::onSwitch;
343 // Init option property handlers
344 optionPropertyHandlers_["append_cmd"] = &CollectProperties::onAppendCmd;
345 optionPropertyHandlers_["forward"] = &CollectProperties::onForward;
346 optionPropertyHandlers_["help"] = &CollectProperties::onHelp;
347 optionPropertyHandlers_["required"] = &CollectProperties::onRequired;
348 optionPropertyHandlers_["stop_compilation"] =
349 &CollectProperties::onStopCompilation;
350 optionPropertyHandlers_["unpack_values"] =
351 &CollectProperties::onUnpackValues;
353 staticMembersInitialized_ = true;
357 // Gets called for every tool property;
358 // Just forwards to the corresponding property handler.
359 void operator() (Init* i) {
360 DagInit& d = dynamic_cast<DagInit&>(*i);
361 std::string property_name = d.getOperator()->getAsString();
362 PropertyHandlerMap::iterator method
363 = propertyHandlers_.find(property_name);
365 if (method != propertyHandlers_.end()) {
366 PropertyHandler h = method->second;
370 throw "Unknown tool property: " + property_name + "!";
376 /// Property handlers --
377 /// Functions that extract information about tool properties from
378 /// DAG representation.
380 void onCmdLine (DagInit* d) {
381 checkNumberOfArguments(d, 1);
382 SplitString(InitPtrToString(d->getArg(0)), toolProps_.CmdLine);
383 if (toolProps_.CmdLine.empty())
384 throw "Tool " + toolProps_.Name + " has empty command line!";
387 void onInLanguage (DagInit* d) {
388 checkNumberOfArguments(d, 1);
389 toolProps_.InLanguage = InitPtrToString(d->getArg(0));
392 void onJoin (DagInit* d) {
393 checkNumberOfArguments(d, 0);
394 toolProps_.setJoin();
397 void onOutLanguage (DagInit* d) {
398 checkNumberOfArguments(d, 1);
399 toolProps_.OutLanguage = InitPtrToString(d->getArg(0));
402 void onOutputSuffix (DagInit* d) {
403 checkNumberOfArguments(d, 1);
404 toolProps_.OutputSuffix = InitPtrToString(d->getArg(0));
407 void onSink (DagInit* d) {
408 checkNumberOfArguments(d, 0);
409 optDescs_.HasSink = true;
410 toolProps_.setSink();
413 void onSwitch (DagInit* d) { addOption(d, OptionType::Switch); }
414 void onParameter (DagInit* d) { addOption(d, OptionType::Parameter); }
415 void onParameterList (DagInit* d) { addOption(d, OptionType::ParameterList); }
416 void onPrefix (DagInit* d) { addOption(d, OptionType::Prefix); }
417 void onPrefixList (DagInit* d) { addOption(d, OptionType::PrefixList); }
419 /// Option property handlers --
420 /// Methods that handle properties that are common for all types of
421 /// options (like append_cmd, stop_compilation)
423 void onAppendCmd (DagInit* d, GlobalOptionDescription& o) {
424 checkNumberOfArguments(d, 1);
425 std::string const& cmd = InitPtrToString(d->getArg(0));
427 toolProps_.OptDescs[o.Name].AddProperty(OptionPropertyType::AppendCmd, cmd);
430 void onForward (DagInit* d, GlobalOptionDescription& o) {
431 checkNumberOfArguments(d, 0);
432 toolProps_.OptDescs[o.Name].setForward();
435 void onHelp (DagInit* d, GlobalOptionDescription& o) {
436 checkNumberOfArguments(d, 1);
437 const std::string& help_message = InitPtrToString(d->getArg(0));
439 o.Help = help_message;
442 void onRequired (DagInit* d, GlobalOptionDescription& o) {
443 checkNumberOfArguments(d, 0);
447 void onStopCompilation (DagInit* d, GlobalOptionDescription& o) {
448 checkNumberOfArguments(d, 0);
449 if (o.Type != OptionType::Switch)
450 throw std::string("Only options of type Switch can stop compilation!");
451 toolProps_.OptDescs[o.Name].setStopCompilation();
454 void onUnpackValues (DagInit* d, GlobalOptionDescription& o) {
455 checkNumberOfArguments(d, 0);
456 toolProps_.OptDescs[o.Name].setUnpackValues();
461 // Add an option of type t
462 void addOption (DagInit* d, OptionType::OptionType t) {
463 checkNumberOfArguments(d, 2);
464 const std::string& name = InitPtrToString(d->getArg(0));
466 GlobalOptionDescription o(t, name);
467 toolProps_.OptDescs[name].Type = t;
468 toolProps_.OptDescs[name].Name = name;
469 processOptionProperties(d, o);
470 insertDescription(o);
473 // Ensure that the number of args in d is <= min_arguments,
474 // throw exception otherwise
475 void checkNumberOfArguments (DagInit* d, unsigned min_arguments) {
476 if (d->getNumArgs() < min_arguments)
477 throw "Property " + d->getOperator()->getAsString()
478 + " has too few arguments!";
481 // Insert new GlobalOptionDescription into GlobalOptionDescriptions list
482 void insertDescription (const GlobalOptionDescription& o)
484 if (optDescs_.Descriptions.count(o.Name)) {
485 GlobalOptionDescription& D = optDescs_.Descriptions[o.Name];
489 optDescs_.Descriptions[o.Name] = o;
493 // Go through the list of option properties and call a corresponding
497 // name - option name
498 // d - option property list
499 void processOptionProperties (DagInit* d, GlobalOptionDescription& o) {
500 // First argument is option name
501 checkNumberOfArguments(d, 2);
503 for (unsigned B = 1, E = d->getNumArgs(); B!=E; ++B) {
504 DagInit& option_property
505 = dynamic_cast<DagInit&>(*d->getArg(B));
506 const std::string& option_property_name
507 = option_property.getOperator()->getAsString();
508 OptionPropertyHandlerMap::iterator method
509 = optionPropertyHandlers_.find(option_property_name);
511 if (method != optionPropertyHandlers_.end()) {
512 OptionPropertyHandler h = method->second;
513 (this->*h)(&option_property, o);
516 throw "Unknown option property: " + option_property_name + "!";
522 // Static members of CollectProperties
523 CollectProperties::PropertyHandlerMap
524 CollectProperties::propertyHandlers_;
526 CollectProperties::OptionPropertyHandlerMap
527 CollectProperties::optionPropertyHandlers_;
529 bool CollectProperties::staticMembersInitialized_ = false;
532 // Gather information from the parsed TableGen data
533 // (Basically a wrapper for CollectProperties)
534 void CollectToolProperties (RecordVector::const_iterator B,
535 RecordVector::const_iterator E,
536 ToolPropertiesList& TPList,
537 GlobalOptionDescriptions& OptDescs)
539 // Iterate over a properties list of every Tool definition
541 RecordVector::value_type T = *B;
542 ListInit* PropList = T->getValueAsListInit("properties");
544 IntrusiveRefCntPtr<ToolProperties>
545 ToolProps(new ToolProperties(T->getName()));
547 std::for_each(PropList->begin(), PropList->end(),
548 CollectProperties(*ToolProps, OptDescs));
549 TPList.push_back(ToolProps);
553 // Used by EmitGenerateActionMethod
554 void EmitOptionPropertyHandlingCode (const ToolProperties& P,
555 const ToolOptionDescription& D,
559 O << Indent2 << "if (";
560 if (D.Type == OptionType::Switch)
561 O << D.GenVariableName();
563 O << '!' << D.GenVariableName() << ".empty()";
567 // Handle option properties that take an argument
568 for (OptionPropertyList::const_iterator B = D.Props.begin(),
569 E = D.Props.end(); B!=E; ++B) {
570 const OptionProperty& val = *B;
573 // (append_cmd cmd) property
574 case OptionPropertyType::AppendCmd:
575 O << Indent3 << "vec.push_back(\"" << val.second << "\");\n";
577 // Other properties with argument
585 // (forward) property
588 case OptionType::Switch:
589 O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
591 case OptionType::Parameter:
592 O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
593 O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
595 case OptionType::Prefix:
596 O << Indent3 << "vec.push_back(\"-" << D.Name << "\" + "
597 << D.GenVariableName() << ");\n";
599 case OptionType::PrefixList:
600 O << Indent3 << "for (" << D.GenTypeDeclaration()
601 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
602 << Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
603 << Indent4 << "vec.push_back(\"-" << D.Name << "\" + "
606 case OptionType::ParameterList:
607 O << Indent3 << "for (" << D.GenTypeDeclaration()
608 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
609 << Indent3 << "E = " << D.GenVariableName()
610 << ".end() ; B != E; ++B) {\n"
611 << Indent4 << "vec.push_back(\"-" << D.Name << "\");\n"
612 << Indent4 << "vec.push_back(*B);\n"
618 // (unpack_values) property
619 if (D.isUnpackValues()) {
620 if (IsListOptionType(D.Type)) {
621 O << Indent3 << "for (" << D.GenTypeDeclaration()
622 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
623 << Indent3 << "E = " << D.GenVariableName()
624 << ".end(); B != E; ++B)\n"
625 << Indent4 << "Tool::UnpackValues(*B, vec);\n";
627 else if (D.Type == OptionType::Prefix || D.Type == OptionType::Parameter){
628 O << Indent3 << "Tool::UnpackValues("
629 << D.GenVariableName() << ", vec);\n";
632 // TOFIX: move this to the type-checking phase
633 throw std::string("Switches can't have unpack_values property!");
638 O << Indent2 << "}\n";
641 // Emite one of two versions of GenerateAction method
642 void EmitGenerateActionMethod (const ToolProperties& P, int V, std::ostream& O)
644 assert(V==1 || V==2);
646 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
648 O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
650 O << Indent2 << "const sys::Path& outFile) const\n"
652 << Indent2 << "std::vector<std::string> vec;\n";
654 // Parse CmdLine tool property
655 if(P.CmdLine.empty())
656 throw "Tool " + P.Name + " has empty command line!";
658 StrVector::const_iterator I = P.CmdLine.begin();
660 for (StrVector::const_iterator E = P.CmdLine.end(); I != E; ++I) {
661 const std::string& cmd = *I;
663 if (cmd == "$INFILE") {
665 O << "for (PathVector::const_iterator B = inFiles.begin()"
666 << ", E = inFiles.end();\n"
667 << Indent2 << "B != E; ++B)\n"
668 << Indent3 << "vec.push_back(B->toString());\n";
670 O << "vec.push_back(inFile.toString());\n";
672 else if (cmd == "$OUTFILE") {
673 O << "vec.push_back(outFile.toString());\n";
676 O << "vec.push_back(\"" << cmd << "\");\n";
680 // For every understood option, emit handling code
681 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
682 E = P.OptDescs.end(); B != E; ++B) {
683 const ToolOptionDescription& val = B->second;
684 EmitOptionPropertyHandlingCode(P, val, O);
687 // Handle Sink property
689 O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
690 << Indent3 << "vec.insert(vec.end(), "
691 << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
695 O << Indent2 << "return Action(\"" << P.CmdLine.at(0) << "\", vec);\n"
696 << Indent1 << "}\n\n";
699 // Emit GenerateAction methods for Tool classes
700 void EmitGenerateActionMethods (const ToolProperties& P, std::ostream& O) {
703 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
704 << Indent2 << "const llvm::sys::Path& outFile) const\n"
706 << Indent2 << "throw std::runtime_error(\"" << P.Name
707 << " is not a Join tool!\");\n"
708 << Indent1 << "}\n\n";
710 EmitGenerateActionMethod(P, 1, O);
712 EmitGenerateActionMethod(P, 2, O);
715 // Emit IsLast() method for Tool classes
716 void EmitIsLastMethod (const ToolProperties& P, std::ostream& O) {
717 O << Indent1 << "bool IsLast() const {\n"
718 << Indent2 << "bool last = false;\n";
720 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
721 E = P.OptDescs.end(); B != E; ++B) {
722 const ToolOptionDescription& val = B->second;
724 if (val.isStopCompilation())
726 << "if (" << val.GenVariableName()
727 << ")\n" << Indent3 << "last = true;\n";
730 O << Indent2 << "return last;\n"
731 << Indent1 << "}\n\n";
734 // Emit static [Input,Output]Language() methods for Tool classes
735 void EmitInOutLanguageMethods (const ToolProperties& P, std::ostream& O) {
736 O << Indent1 << "std::string InputLanguage() const {\n"
737 << Indent2 << "return \"" << P.InLanguage << "\";\n"
738 << Indent1 << "}\n\n";
740 O << Indent1 << "std::string OutputLanguage() const {\n"
741 << Indent2 << "return \"" << P.OutLanguage << "\";\n"
742 << Indent1 << "}\n\n";
745 // Emit static [Input,Output]Language() methods for Tool classes
746 void EmitOutputSuffixMethod (const ToolProperties& P, std::ostream& O) {
747 O << Indent1 << "std::string OutputSuffix() const {\n"
748 << Indent2 << "return \"" << P.OutputSuffix << "\";\n"
749 << Indent1 << "}\n\n";
752 // Emit static Name() method for Tool classes
753 void EmitNameMethod (const ToolProperties& P, std::ostream& O) {
754 O << Indent1 << "std::string Name() const {\n"
755 << Indent2 << "return \"" << P.Name << "\";\n"
756 << Indent1 << "}\n\n";
759 // Emit static Name() method for Tool classes
760 void EmitIsJoinMethod (const ToolProperties& P, std::ostream& O) {
761 O << Indent1 << "bool IsJoin() const {\n";
763 O << Indent2 << "return true;\n";
765 O << Indent2 << "return false;\n";
766 O << Indent1 << "}\n\n";
769 // Emit a Tool class definition
770 void EmitToolClassDefinition (const ToolProperties& P, std::ostream& O) {
776 O << "class " << P.Name << " : public Tool {\n"
779 EmitNameMethod(P, O);
780 EmitInOutLanguageMethods(P, O);
781 EmitOutputSuffixMethod(P, O);
782 EmitIsJoinMethod(P, O);
783 EmitGenerateActionMethods(P, O);
784 EmitIsLastMethod(P, O);
786 // Close class definition
790 // Iterate over a list of option descriptions and emit registration code
791 void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
794 // Emit static cl::Option variables
795 for (GlobalOptionDescriptions::const_iterator B = descs.begin(),
796 E = descs.end(); B!=E; ++B) {
797 const GlobalOptionDescription& val = B->second;
799 O << val.GenTypeDeclaration() << ' '
800 << val.GenVariableName()
801 << "(\"" << val.Name << '\"';
803 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
806 if (val.isRequired()) {
808 case OptionType::PrefixList:
809 case OptionType::ParameterList:
810 O << ", cl::OneOrMore";
813 O << ", cl::Required";
817 O << ", cl::desc(\"" << val.Help << "\"));\n";
821 O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
826 void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
828 // Get the relevant field out of RecordKeeper
829 Record* LangMapRecord = Records.getDef("LanguageMap");
831 throw std::string("Language map definition not found!");
833 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
834 if (!LangsToSuffixesList)
835 throw std::string("Error in the language map definition!");
838 O << "void llvmcc::PopulateLanguageMap(LanguageMap& language_map) {\n";
840 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
841 Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
843 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
844 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
846 for (unsigned i = 0; i < Suffixes->size(); ++i)
847 O << Indent1 << "language_map[\""
848 << InitPtrToString(Suffixes->getElement(i))
849 << "\"] = \"" << Lang << "\";\n";
855 // Fills in two tables that map tool names to (input, output) languages.
856 // Used by the typechecker.
857 void FillInToolToLang (const ToolPropertiesList& TPList,
858 StringMap<std::string>& ToolToInLang,
859 StringMap<std::string>& ToolToOutLang) {
860 for (ToolPropertiesList::const_iterator B = TPList.begin(), E = TPList.end();
862 const ToolProperties& P = *(*B);
863 ToolToInLang[P.Name] = P.InLanguage;
864 ToolToOutLang[P.Name] = P.OutLanguage;
868 // Check that all output and input language names match.
869 // TOFIX: check for cycles.
870 // TOFIX: check for multiple default edges.
871 void TypecheckGraph (Record* CompilationGraph,
872 const ToolPropertiesList& TPList) {
873 StringMap<std::string> ToolToInLang;
874 StringMap<std::string> ToolToOutLang;
876 FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
877 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
878 StringMap<std::string>::iterator IAE = ToolToInLang.end();
879 StringMap<std::string>::iterator IBE = ToolToOutLang.end();
881 for (unsigned i = 0; i < edges->size(); ++i) {
882 Record* Edge = edges->getElementAsRecord(i);
883 Record* A = Edge->getValueAsDef("a");
884 Record* B = Edge->getValueAsDef("b");
885 StringMap<std::string>::iterator IA = ToolToOutLang.find(A->getName());
886 StringMap<std::string>::iterator IB = ToolToInLang.find(B->getName());
888 throw A->getName() + ": no such tool!";
890 throw B->getName() + ": no such tool!";
891 if(A->getName() != "root" && IA->second != IB->second)
892 throw "Edge " + A->getName() + "->" + B->getName()
893 + ": output->input language mismatch";
894 if(B->getName() == "root")
895 throw std::string("Edges back to the root are not allowed!");
899 // Emit Edge* classes that represent edges in the graph.
900 // TOFIX: add edge properties.
901 void EmitEdgeClasses (Record* CompilationGraph,
902 const GlobalOptionDescriptions& OptDescs,
904 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
906 for (unsigned i = 0; i < edges->size(); ++i) {
907 Record* Edge = edges->getElementAsRecord(i);
908 Record* B = Edge->getValueAsDef("b");
909 ListInit* Props = Edge->getValueAsListInit("props");
914 O << "class Edge" << i << ": public Edge {\n"
916 << Indent1 << "Edge" << i << "() : Edge(\"" << B->getName()
919 O << Indent1 << "bool isEnabled() const { return true; }\n";
921 O << Indent1 << "bool isDefault() const { return false; }\n";
927 void EmitPopulateCompilationGraph (Record* CompilationGraph,
930 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
933 O << "void llvmcc::PopulateCompilationGraph(CompilationGraph& G) {\n"
934 << Indent1 << "PopulateLanguageMap(G.ExtsToLangs);\n\n";
938 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
940 throw std::string("No tool definitions found!");
942 for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
943 const std::string& Name = (*B)->getName();
945 O << Indent1 << "G.insertNode(new "
952 for (unsigned i = 0; i < edges->size(); ++i) {
953 Record* Edge = edges->getElementAsRecord(i);
954 Record* A = Edge->getValueAsDef("a");
955 Record* B = Edge->getValueAsDef("b");
956 ListInit* Props = Edge->getValueAsListInit("props");
958 O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
961 O << "new SimpleEdge(\"" << B->getName() << "\")";
963 O << "new Edge" << i << "()";
972 // End of anonymous namespace
975 // Back-end entry point
976 void LLVMCCConfigurationEmitter::run (std::ostream &O) {
978 EmitSourceFileHeader("LLVMCC Configuration Library", O);
980 // Get a list of all defined Tools
981 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
983 throw std::string("No tool definitions found!");
985 // Gather information from the Tool descriptions
986 ToolPropertiesList tool_props;
987 GlobalOptionDescriptions opt_descs;
988 CollectToolProperties(Tools.begin(), Tools.end(), tool_props, opt_descs);
990 // Emit global option registration code
991 EmitOptionDescriptions(opt_descs, O);
993 // Emit PopulateLanguageMap function
994 // (a language map maps from file extensions to language names)
995 EmitPopulateLanguageMap(Records, O);
998 for (ToolPropertiesList::const_iterator B = tool_props.begin(),
999 E = tool_props.end(); B!=E; ++B)
1000 EmitToolClassDefinition(*(*B), O);
1002 Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
1003 if (!CompilationGraphRecord)
1004 throw std::string("Compilation graph description not found!");
1006 // Typecheck the compilation graph.
1007 TypecheckGraph(CompilationGraphRecord, tool_props);
1009 // Emit Edge* classes.
1010 EmitEdgeClasses(CompilationGraphRecord, opt_descs, O);
1012 // Emit PopulateCompilationGraph function
1013 EmitPopulateCompilationGraph(CompilationGraphRecord, O);