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 std::string InitPtrToString(Init* ptr) {
57 StringInit& val = dynamic_cast<StringInit&>(*ptr);
58 return val.getValue();
61 int InitPtrToInt(Init* ptr) {
62 IntInit& val = dynamic_cast<IntInit&>(*ptr);
63 return val.getValue();
66 const DagInit& InitPtrToDagInitRef(Init* ptr) {
67 DagInit& val = dynamic_cast<DagInit&>(*ptr);
72 // checkNumberOfArguments - Ensure that the number of args in d is
73 // less than or equal to min_arguments, otherwise throw an exception .
74 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
75 if (d->getNumArgs() < min_arguments)
76 throw "Property " + d->getOperator()->getAsString()
77 + " has too few arguments!";
81 //===----------------------------------------------------------------------===//
82 /// Back-end specific code
84 // A command-line option can have one of the following types:
86 // Switch - a simple switch w/o arguments, e.g. -O2
88 // Parameter - an option that takes one(and only one) argument, e.g. -o file,
91 // ParameterList - same as Parameter, but more than one occurence
92 // of the option is allowed, e.g. -lm -lpthread
94 // Prefix - argument is everything after the prefix,
95 // e.g. -Wa,-foo,-bar, -DNAME=VALUE
97 // PrefixList - same as Prefix, but more than one option occurence is
100 namespace OptionType {
101 enum OptionType { Switch, Parameter, ParameterList, Prefix, PrefixList};
104 bool IsListOptionType (OptionType::OptionType t) {
105 return (t == OptionType::ParameterList || t == OptionType::PrefixList);
108 // Code duplication here is necessary because one option can affect
109 // several tools and those tools may have different actions associated
110 // with this option. GlobalOptionDescriptions are used to generate
111 // the option registration code, while ToolOptionDescriptions are used
112 // to generate tool-specific code.
114 /// OptionDescription - Base class for option descriptions.
115 struct OptionDescription {
116 OptionType::OptionType Type;
119 OptionDescription(OptionType::OptionType t = OptionType::Switch,
120 const std::string& n = "")
124 const char* GenTypeDeclaration() const {
126 case OptionType::PrefixList:
127 case OptionType::ParameterList:
128 return "cl::list<std::string>";
129 case OptionType::Switch:
130 return "cl::opt<bool>";
131 case OptionType::Parameter:
132 case OptionType::Prefix:
134 return "cl::opt<std::string>";
138 // Escape commas and other symbols not allowed in the C++ variable
139 // names. Makes it possible to use options with names like "Wa,"
140 // (useful for prefix options).
141 std::string EscapeVariableName(const std::string& Var) const {
143 for (unsigned i = 0; i != Var.size(); ++i) {
148 ret.push_back(Var[i]);
154 std::string GenVariableName() const {
155 const std::string& EscapedName = EscapeVariableName(Name);
157 case OptionType::Switch:
158 return "AutoGeneratedSwitch" + EscapedName;
159 case OptionType::Prefix:
160 return "AutoGeneratedPrefix" + EscapedName;
161 case OptionType::PrefixList:
162 return "AutoGeneratedPrefixList" + EscapedName;
163 case OptionType::Parameter:
164 return "AutoGeneratedParameter" + EscapedName;
165 case OptionType::ParameterList:
167 return "AutoGeneratedParameterList" + EscapedName;
173 // Global option description.
175 namespace GlobalOptionDescriptionFlags {
176 enum GlobalOptionDescriptionFlags { Required = 0x1 };
179 struct GlobalOptionDescription : public OptionDescription {
183 // We need to provide a default constructor because
184 // StringMap can only store DefaultConstructible objects.
185 GlobalOptionDescription() : OptionDescription(), Flags(0)
188 GlobalOptionDescription (OptionType::OptionType t, const std::string& n)
189 : OptionDescription(t, n), Help(DefaultHelpString), Flags(0)
192 bool isRequired() const {
193 return Flags & GlobalOptionDescriptionFlags::Required;
196 Flags |= GlobalOptionDescriptionFlags::Required;
199 /// Merge - Merge two option descriptions.
200 void Merge (const GlobalOptionDescription& other)
202 if (other.Type != Type)
203 throw "Conflicting definitions for the option " + Name + "!";
205 if (Help == DefaultHelpString)
207 else if (other.Help != DefaultHelpString) {
208 llvm::cerr << "Warning: more than one help string defined for option "
212 Flags |= other.Flags;
216 /// GlobalOptionDescriptions - A GlobalOptionDescription array
217 /// together with some flags affecting generation of option
219 struct GlobalOptionDescriptions {
220 typedef StringMap<GlobalOptionDescription> container_type;
221 typedef container_type::const_iterator const_iterator;
223 /// Descriptions - A list of GlobalOptionDescriptions.
224 container_type Descriptions;
225 /// HasSink - Should the emitter generate a "cl::sink" option?
228 const GlobalOptionDescription& FindOption(const std::string& OptName) const {
229 const_iterator I = Descriptions.find(OptName);
230 if (I != Descriptions.end())
233 throw OptName + ": no such option!";
236 // Support for STL-style iteration
237 const_iterator begin() const { return Descriptions.begin(); }
238 const_iterator end() const { return Descriptions.end(); }
242 // Tool-local option description.
244 // Properties without arguments are implemented as flags.
245 namespace ToolOptionDescriptionFlags {
246 enum ToolOptionDescriptionFlags { StopCompilation = 0x1,
247 Forward = 0x2, UnpackValues = 0x4};
249 namespace OptionPropertyType {
250 enum OptionPropertyType { AppendCmd };
253 typedef std::pair<OptionPropertyType::OptionPropertyType, std::string>
255 typedef SmallVector<OptionProperty, 4> OptionPropertyList;
257 struct ToolOptionDescription : public OptionDescription {
259 OptionPropertyList Props;
261 // StringMap can only store DefaultConstructible objects
262 ToolOptionDescription() : OptionDescription(), Flags(0) {}
264 ToolOptionDescription (OptionType::OptionType t, const std::string& n)
265 : OptionDescription(t, n)
268 // Various boolean properties
269 bool isStopCompilation() const {
270 return Flags & ToolOptionDescriptionFlags::StopCompilation;
272 void setStopCompilation() {
273 Flags |= ToolOptionDescriptionFlags::StopCompilation;
276 bool isForward() const {
277 return Flags & ToolOptionDescriptionFlags::Forward;
280 Flags |= ToolOptionDescriptionFlags::Forward;
283 bool isUnpackValues() const {
284 return Flags & ToolOptionDescriptionFlags::UnpackValues;
286 void setUnpackValues() {
287 Flags |= ToolOptionDescriptionFlags::UnpackValues;
290 void AddProperty (OptionPropertyType::OptionPropertyType t,
291 const std::string& val)
293 Props.push_back(std::make_pair(t, val));
297 typedef StringMap<ToolOptionDescription> ToolOptionDescriptions;
299 // Tool information record
301 namespace ToolFlags {
302 enum ToolFlags { Join = 0x1, Sink = 0x2 };
305 struct ToolProperties : public RefCountedBase<ToolProperties> {
308 std::string InLanguage;
309 std::string OutLanguage;
310 std::string OutputSuffix;
312 ToolOptionDescriptions OptDescs;
314 // Various boolean properties
315 void setSink() { Flags |= ToolFlags::Sink; }
316 bool isSink() const { return Flags & ToolFlags::Sink; }
317 void setJoin() { Flags |= ToolFlags::Join; }
318 bool isJoin() const { return Flags & ToolFlags::Join; }
320 // Default ctor here is needed because StringMap can only store
321 // DefaultConstructible objects
322 ToolProperties() : Flags(0) {}
323 ToolProperties (const std::string& n) : Name(n), Flags(0) {}
327 /// ToolPropertiesList - A list of Tool information records
328 /// IntrusiveRefCntPtrs are used here because StringMap has no copy
329 /// constructor (and we want to avoid copying ToolProperties anyway).
330 typedef std::vector<IntrusiveRefCntPtr<ToolProperties> > ToolPropertiesList;
333 /// CollectProperties - Function object for iterating over a list of
334 /// tool property records.
335 class CollectProperties {
338 /// Implementation details
340 /// PropertyHandler - a function that extracts information
341 /// about a given tool property from its DAG representation
342 typedef void (CollectProperties::*PropertyHandler)(const DagInit*);
344 /// PropertyHandlerMap - A map from property names to property
346 typedef StringMap<PropertyHandler> PropertyHandlerMap;
348 /// OptionPropertyHandler - a function that extracts information
349 /// about a given option property from its DAG representation.
350 typedef void (CollectProperties::* OptionPropertyHandler)
351 (const DagInit*, GlobalOptionDescription &);
353 /// OptionPropertyHandlerMap - A map from option property names to
354 /// option property handlers
355 typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
357 // Static maps from strings to CollectProperties methods("handlers")
358 static PropertyHandlerMap propertyHandlers_;
359 static OptionPropertyHandlerMap optionPropertyHandlers_;
360 static bool staticMembersInitialized_;
363 /// This is where the information is stored
365 /// toolProps_ - Properties of the current Tool.
366 ToolProperties& toolProps_;
367 /// optDescs_ - OptionDescriptions table (used to register options
369 GlobalOptionDescriptions& optDescs_;
373 explicit CollectProperties (ToolProperties& p, GlobalOptionDescriptions& d)
374 : toolProps_(p), optDescs_(d)
376 if (!staticMembersInitialized_) {
377 // Init tool property handlers
378 propertyHandlers_["cmd_line"] = &CollectProperties::onCmdLine;
379 propertyHandlers_["in_language"] = &CollectProperties::onInLanguage;
380 propertyHandlers_["join"] = &CollectProperties::onJoin;
381 propertyHandlers_["out_language"] = &CollectProperties::onOutLanguage;
382 propertyHandlers_["output_suffix"] = &CollectProperties::onOutputSuffix;
383 propertyHandlers_["parameter_option"]
384 = &CollectProperties::onParameter;
385 propertyHandlers_["parameter_list_option"] =
386 &CollectProperties::onParameterList;
387 propertyHandlers_["prefix_option"] = &CollectProperties::onPrefix;
388 propertyHandlers_["prefix_list_option"] =
389 &CollectProperties::onPrefixList;
390 propertyHandlers_["sink"] = &CollectProperties::onSink;
391 propertyHandlers_["switch_option"] = &CollectProperties::onSwitch;
393 // Init option property handlers
394 optionPropertyHandlers_["append_cmd"] = &CollectProperties::onAppendCmd;
395 optionPropertyHandlers_["forward"] = &CollectProperties::onForward;
396 optionPropertyHandlers_["help"] = &CollectProperties::onHelp;
397 optionPropertyHandlers_["required"] = &CollectProperties::onRequired;
398 optionPropertyHandlers_["stop_compilation"] =
399 &CollectProperties::onStopCompilation;
400 optionPropertyHandlers_["unpack_values"] =
401 &CollectProperties::onUnpackValues;
403 staticMembersInitialized_ = true;
407 /// operator() - Gets called for every tool property; Just forwards
408 /// to the corresponding property handler.
409 void operator() (Init* i) {
410 const DagInit& d = InitPtrToDagInitRef(i);
411 const std::string& property_name = d.getOperator()->getAsString();
412 PropertyHandlerMap::iterator method
413 = propertyHandlers_.find(property_name);
415 if (method != propertyHandlers_.end()) {
416 PropertyHandler h = method->second;
420 throw "Unknown tool property: " + property_name + "!";
426 /// Property handlers --
427 /// Functions that extract information about tool properties from
428 /// DAG representation.
430 void onCmdLine (const DagInit* d) {
431 checkNumberOfArguments(d, 1);
432 SplitString(InitPtrToString(d->getArg(0)), toolProps_.CmdLine);
433 if (toolProps_.CmdLine.empty())
434 throw "Tool " + toolProps_.Name + " has empty command line!";
437 void onInLanguage (const DagInit* d) {
438 checkNumberOfArguments(d, 1);
439 toolProps_.InLanguage = InitPtrToString(d->getArg(0));
442 void onJoin (const DagInit* d) {
443 checkNumberOfArguments(d, 0);
444 toolProps_.setJoin();
447 void onOutLanguage (const DagInit* d) {
448 checkNumberOfArguments(d, 1);
449 toolProps_.OutLanguage = InitPtrToString(d->getArg(0));
452 void onOutputSuffix (const DagInit* d) {
453 checkNumberOfArguments(d, 1);
454 toolProps_.OutputSuffix = InitPtrToString(d->getArg(0));
457 void onSink (const DagInit* d) {
458 checkNumberOfArguments(d, 0);
459 optDescs_.HasSink = true;
460 toolProps_.setSink();
463 void onSwitch (const DagInit* d) {
464 addOption(d, OptionType::Switch);
467 void onParameter (const DagInit* d) {
468 addOption(d, OptionType::Parameter);
471 void onParameterList (const DagInit* d) {
472 addOption(d, OptionType::ParameterList);
475 void onPrefix (const DagInit* d) {
476 addOption(d, OptionType::Prefix);
479 void onPrefixList (const DagInit* d) {
480 addOption(d, OptionType::PrefixList);
483 /// Option property handlers --
484 /// Methods that handle properties that are common for all types of
485 /// options (like append_cmd, stop_compilation)
487 void onAppendCmd (const DagInit* d, GlobalOptionDescription& o) {
488 checkNumberOfArguments(d, 1);
489 std::string const& cmd = InitPtrToString(d->getArg(0));
491 toolProps_.OptDescs[o.Name].AddProperty(OptionPropertyType::AppendCmd, cmd);
494 void onForward (const DagInit* d, GlobalOptionDescription& o) {
495 checkNumberOfArguments(d, 0);
496 toolProps_.OptDescs[o.Name].setForward();
499 void onHelp (const DagInit* d, GlobalOptionDescription& o) {
500 checkNumberOfArguments(d, 1);
501 const std::string& help_message = InitPtrToString(d->getArg(0));
503 o.Help = help_message;
506 void onRequired (const DagInit* d, GlobalOptionDescription& o) {
507 checkNumberOfArguments(d, 0);
511 void onStopCompilation (const DagInit* d, GlobalOptionDescription& o) {
512 checkNumberOfArguments(d, 0);
513 if (o.Type != OptionType::Switch)
514 throw std::string("Only options of type Switch can stop compilation!");
515 toolProps_.OptDescs[o.Name].setStopCompilation();
518 void onUnpackValues (const DagInit* d, GlobalOptionDescription& o) {
519 checkNumberOfArguments(d, 0);
520 toolProps_.OptDescs[o.Name].setUnpackValues();
525 // Add an option of type t
526 void addOption (const DagInit* d, OptionType::OptionType t) {
527 checkNumberOfArguments(d, 2);
528 const std::string& name = InitPtrToString(d->getArg(0));
530 GlobalOptionDescription o(t, name);
531 toolProps_.OptDescs[name].Type = t;
532 toolProps_.OptDescs[name].Name = name;
533 processOptionProperties(d, o);
534 insertDescription(o);
537 // Insert new GlobalOptionDescription into GlobalOptionDescriptions list
538 void insertDescription (const GlobalOptionDescription& o)
540 if (optDescs_.Descriptions.count(o.Name)) {
541 GlobalOptionDescription& D = optDescs_.Descriptions[o.Name];
545 optDescs_.Descriptions[o.Name] = o;
549 /// processOptionProperties - Go through the list of option
550 /// properties and call a corresponding handler for each.
553 /// name - option name
554 /// d - option property list
555 void processOptionProperties (const DagInit* d, GlobalOptionDescription& o) {
556 // First argument is option name
557 checkNumberOfArguments(d, 2);
559 for (unsigned B = 1, E = d->getNumArgs(); B!=E; ++B) {
560 const DagInit& option_property
561 = InitPtrToDagInitRef(d->getArg(B));
562 const std::string& option_property_name
563 = option_property.getOperator()->getAsString();
564 OptionPropertyHandlerMap::iterator method
565 = optionPropertyHandlers_.find(option_property_name);
567 if (method != optionPropertyHandlers_.end()) {
568 OptionPropertyHandler h = method->second;
569 (this->*h)(&option_property, o);
572 throw "Unknown option property: " + option_property_name + "!";
578 // Static members of CollectProperties
579 CollectProperties::PropertyHandlerMap
580 CollectProperties::propertyHandlers_;
582 CollectProperties::OptionPropertyHandlerMap
583 CollectProperties::optionPropertyHandlers_;
585 bool CollectProperties::staticMembersInitialized_ = false;
588 /// CollectToolProperties - Gather information from the parsed
589 /// TableGen data (basically a wrapper for the CollectProperties
590 /// function object).
591 void CollectToolProperties (RecordVector::const_iterator B,
592 RecordVector::const_iterator E,
593 ToolPropertiesList& TPList,
594 GlobalOptionDescriptions& OptDescs)
596 // Iterate over a properties list of every Tool definition
598 RecordVector::value_type T = *B;
599 ListInit* PropList = T->getValueAsListInit("properties");
601 IntrusiveRefCntPtr<ToolProperties>
602 ToolProps(new ToolProperties(T->getName()));
604 std::for_each(PropList->begin(), PropList->end(),
605 CollectProperties(*ToolProps, OptDescs));
606 TPList.push_back(ToolProps);
610 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
611 /// implement EmitOptionPropertyHandlingCode(). Emits code for
612 /// handling the (forward) option property.
613 void EmitForwardOptionPropertyHandlingCode (const ToolOptionDescription& D,
616 case OptionType::Switch:
617 O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
619 case OptionType::Parameter:
620 O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
621 O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
623 case OptionType::Prefix:
624 O << Indent3 << "vec.push_back(\"-" << D.Name << "\" + "
625 << D.GenVariableName() << ");\n";
627 case OptionType::PrefixList:
628 O << Indent3 << "for (" << D.GenTypeDeclaration()
629 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
630 << Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
631 << Indent4 << "vec.push_back(\"-" << D.Name << "\" + "
634 case OptionType::ParameterList:
635 O << Indent3 << "for (" << D.GenTypeDeclaration()
636 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
637 << Indent3 << "E = " << D.GenVariableName()
638 << ".end() ; B != E; ++B) {\n"
639 << Indent4 << "vec.push_back(\"-" << D.Name << "\");\n"
640 << Indent4 << "vec.push_back(*B);\n"
646 /// EmitOptionPropertyHandlingCode - Helper function used by
647 /// EmitGenerateActionMethod(). Emits code that handles option
649 void EmitOptionPropertyHandlingCode (const ToolProperties& P,
650 const ToolOptionDescription& D,
653 // Start of the if-clause.
654 O << Indent2 << "if (";
655 if (D.Type == OptionType::Switch)
656 O << D.GenVariableName();
658 O << '!' << D.GenVariableName() << ".empty()";
662 // Handle option properties that take an argument.
663 for (OptionPropertyList::const_iterator B = D.Props.begin(),
664 E = D.Props.end(); B!=E; ++B) {
665 const OptionProperty& val = *B;
668 // (append_cmd cmd) property
669 case OptionPropertyType::AppendCmd:
670 O << Indent3 << "vec.push_back(\"" << val.second << "\");\n";
672 // Other properties with argument
680 // (forward) property
682 EmitForwardOptionPropertyHandlingCode(D, O);
684 // (unpack_values) property
685 if (D.isUnpackValues()) {
686 if (IsListOptionType(D.Type)) {
687 O << Indent3 << "for (" << D.GenTypeDeclaration()
688 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
689 << Indent3 << "E = " << D.GenVariableName()
690 << ".end(); B != E; ++B)\n"
691 << Indent4 << "llvm::SplitString(*B, vec, \",\");\n";
693 else if (D.Type == OptionType::Prefix || D.Type == OptionType::Parameter){
694 O << Indent3 << "llvm::SplitString("
695 << D.GenVariableName() << ", vec, \",\");\n";
698 // TOFIX: move this to the type-checking phase
699 throw std::string("Switches can't have unpack_values property!");
703 // End of the if-clause.
704 O << Indent2 << "}\n";
707 // EmitGenerateActionMethod - Emit one of two versions of the
708 // Tool::GenerateAction() method.
709 void EmitGenerateActionMethod (const ToolProperties& P, bool V, std::ostream& O)
712 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
714 O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
716 O << Indent2 << "const sys::Path& outFile) const\n"
718 << Indent2 << "std::vector<std::string> vec;\n";
720 // Parse CmdLine tool property
721 if(P.CmdLine.empty())
722 throw "Tool " + P.Name + " has empty command line!";
724 StrVector::const_iterator I = P.CmdLine.begin();
726 for (StrVector::const_iterator E = P.CmdLine.end(); I != E; ++I) {
727 const std::string& cmd = *I;
729 if (cmd == "$INFILE") {
731 O << "for (PathVector::const_iterator B = inFiles.begin()"
732 << ", E = inFiles.end();\n"
733 << Indent2 << "B != E; ++B)\n"
734 << Indent3 << "vec.push_back(B->toString());\n";
736 O << "vec.push_back(inFile.toString());\n";
738 else if (cmd == "$OUTFILE") {
739 O << "vec.push_back(outFile.toString());\n";
742 O << "vec.push_back(\"" << cmd << "\");\n";
746 // For every understood option, emit handling code.
747 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
748 E = P.OptDescs.end(); B != E; ++B) {
749 const ToolOptionDescription& val = B->second;
750 EmitOptionPropertyHandlingCode(P, val, O);
753 // Handle the Sink property.
755 O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
756 << Indent3 << "vec.insert(vec.end(), "
757 << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
761 O << Indent2 << "return Action(\"" << P.CmdLine.at(0) << "\", vec);\n"
762 << Indent1 << "}\n\n";
765 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
766 /// a given Tool class.
767 void EmitGenerateActionMethods (const ToolProperties& P, std::ostream& O) {
770 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
771 << Indent2 << "const llvm::sys::Path& outFile) const\n"
773 << Indent2 << "throw std::runtime_error(\"" << P.Name
774 << " is not a Join tool!\");\n"
775 << Indent1 << "}\n\n";
777 EmitGenerateActionMethod(P, true, O);
779 EmitGenerateActionMethod(P, false, O);
782 /// EmitIsLastMethod - Emit the IsLast() method for a given Tool
784 void EmitIsLastMethod (const ToolProperties& P, std::ostream& O) {
785 O << Indent1 << "bool IsLast() const {\n"
786 << Indent2 << "bool last = false;\n";
788 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
789 E = P.OptDescs.end(); B != E; ++B) {
790 const ToolOptionDescription& val = B->second;
792 if (val.isStopCompilation())
794 << "if (" << val.GenVariableName()
795 << ")\n" << Indent3 << "last = true;\n";
798 O << Indent2 << "return last;\n"
799 << Indent1 << "}\n\n";
802 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
803 /// methods for a given Tool class.
804 void EmitInOutLanguageMethods (const ToolProperties& P, std::ostream& O) {
805 O << Indent1 << "const char* InputLanguage() const {\n"
806 << Indent2 << "return \"" << P.InLanguage << "\";\n"
807 << Indent1 << "}\n\n";
809 O << Indent1 << "const char* OutputLanguage() const {\n"
810 << Indent2 << "return \"" << P.OutLanguage << "\";\n"
811 << Indent1 << "}\n\n";
814 /// EmitOutputSuffixMethod - Emit the OutputSuffix() method for a
815 /// given Tool class.
816 void EmitOutputSuffixMethod (const ToolProperties& P, std::ostream& O) {
817 O << Indent1 << "const char* OutputSuffix() const {\n"
818 << Indent2 << "return \"" << P.OutputSuffix << "\";\n"
819 << Indent1 << "}\n\n";
822 /// EmitNameMethod - Emit the Name() method for a given Tool class.
823 void EmitNameMethod (const ToolProperties& P, std::ostream& O) {
824 O << Indent1 << "const char* Name() const {\n"
825 << Indent2 << "return \"" << P.Name << "\";\n"
826 << Indent1 << "}\n\n";
829 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
831 void EmitIsJoinMethod (const ToolProperties& P, std::ostream& O) {
832 O << Indent1 << "bool IsJoin() const {\n";
834 O << Indent2 << "return true;\n";
836 O << Indent2 << "return false;\n";
837 O << Indent1 << "}\n\n";
840 /// EmitToolClassDefinition - Emit a Tool class definition.
841 void EmitToolClassDefinition (const ToolProperties& P, std::ostream& O) {
847 O << "class " << P.Name << " : public ";
852 O << " {\npublic:\n";
854 EmitNameMethod(P, O);
855 EmitInOutLanguageMethods(P, O);
856 EmitOutputSuffixMethod(P, O);
857 EmitIsJoinMethod(P, O);
858 EmitGenerateActionMethods(P, O);
859 EmitIsLastMethod(P, O);
861 // Close class definition
865 /// EmitOptionDescriptions - Iterate over a list of option
866 /// descriptions and emit registration code.
867 void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
870 // Emit static cl::Option variables
871 for (GlobalOptionDescriptions::const_iterator B = descs.begin(),
872 E = descs.end(); B!=E; ++B) {
873 const GlobalOptionDescription& val = B->second;
875 O << val.GenTypeDeclaration() << ' '
876 << val.GenVariableName()
877 << "(\"" << val.Name << '\"';
879 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
882 if (val.isRequired()) {
884 case OptionType::PrefixList:
885 case OptionType::ParameterList:
886 O << ", cl::OneOrMore";
889 O << ", cl::Required";
893 O << ", cl::desc(\"" << val.Help << "\"));\n";
897 O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
902 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
903 void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
905 // Get the relevant field out of RecordKeeper
906 Record* LangMapRecord = Records.getDef("LanguageMap");
908 throw std::string("Language map definition not found!");
910 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
911 if (!LangsToSuffixesList)
912 throw std::string("Error in the language map definition!");
915 O << "void llvmc::PopulateLanguageMap(LanguageMap& language_map) {\n";
917 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
918 Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
920 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
921 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
923 for (unsigned i = 0; i < Suffixes->size(); ++i)
924 O << Indent1 << "language_map[\""
925 << InitPtrToString(Suffixes->getElement(i))
926 << "\"] = \"" << Lang << "\";\n";
932 /// FillInToolToLang - Fills in two tables that map tool names to
933 /// (input, output) languages. Used by the typechecker.
934 void FillInToolToLang (const ToolPropertiesList& TPList,
935 StringMap<std::string>& ToolToInLang,
936 StringMap<std::string>& ToolToOutLang) {
937 for (ToolPropertiesList::const_iterator B = TPList.begin(), E = TPList.end();
939 const ToolProperties& P = *(*B);
940 ToolToInLang[P.Name] = P.InLanguage;
941 ToolToOutLang[P.Name] = P.OutLanguage;
945 /// TypecheckGraph - Check that names for output and input languages
946 /// on all edges do match.
947 // TOFIX: check for cycles.
948 // TOFIX: check for multiple default edges.
949 void TypecheckGraph (Record* CompilationGraph,
950 const ToolPropertiesList& TPList) {
951 StringMap<std::string> ToolToInLang;
952 StringMap<std::string> ToolToOutLang;
954 FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
955 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
956 StringMap<std::string>::iterator IAE = ToolToInLang.end();
957 StringMap<std::string>::iterator IBE = ToolToOutLang.end();
959 for (unsigned i = 0; i < edges->size(); ++i) {
960 Record* Edge = edges->getElementAsRecord(i);
961 Record* A = Edge->getValueAsDef("a");
962 Record* B = Edge->getValueAsDef("b");
963 StringMap<std::string>::iterator IA = ToolToOutLang.find(A->getName());
964 StringMap<std::string>::iterator IB = ToolToInLang.find(B->getName());
966 throw A->getName() + ": no such tool!";
968 throw B->getName() + ": no such tool!";
969 if(A->getName() != "root" && IA->second != IB->second)
970 throw "Edge " + A->getName() + "->" + B->getName()
971 + ": output->input language mismatch";
972 if(B->getName() == "root")
973 throw std::string("Edges back to the root are not allowed!");
977 /// EmitEdgePropertyTest1Arg - Helper function used by
978 /// EmitEdgePropertyTest.
979 bool EmitEdgePropertyTest1Arg(const std::string& PropName,
981 const GlobalOptionDescriptions& OptDescs,
983 checkNumberOfArguments(&Prop, 1);
984 const std::string& OptName = InitPtrToString(Prop.getArg(0));
985 if (PropName == "switch_on") {
986 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
987 if (OptDesc.Type != OptionType::Switch)
988 throw OptName + ": incorrect option type!";
989 O << OptDesc.GenVariableName();
991 } else if (PropName == "if_input_languages_contain") {
992 O << "InLangs.count(\"" << OptName << "\") != 0";
999 /// EmitEdgePropertyTest2Args - Helper function used by
1000 /// EmitEdgePropertyTest.
1001 bool EmitEdgePropertyTest2Args(const std::string& PropName,
1002 const DagInit& Prop,
1003 const GlobalOptionDescriptions& OptDescs,
1005 checkNumberOfArguments(&Prop, 2);
1006 const std::string& OptName = InitPtrToString(Prop.getArg(0));
1007 const std::string& OptArg = InitPtrToString(Prop.getArg(1));
1008 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
1010 if (PropName == "parameter_equals") {
1011 if (OptDesc.Type != OptionType::Parameter
1012 && OptDesc.Type != OptionType::Prefix)
1013 throw OptName + ": incorrect option type!";
1014 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
1017 else if (PropName == "element_in_list") {
1018 if (OptDesc.Type != OptionType::ParameterList
1019 && OptDesc.Type != OptionType::PrefixList)
1020 throw OptName + ": incorrect option type!";
1021 const std::string& VarName = OptDesc.GenVariableName();
1022 O << "std::find(" << VarName << ".begin(),\n"
1023 << Indent3 << VarName << ".end(), \""
1024 << OptArg << "\") != " << VarName << ".end()";
1031 // Forward declaration.
1032 void EmitEdgePropertyTest(const DagInit& Prop,
1033 const GlobalOptionDescriptions& OptDescs,
1036 /// EmitLogicalOperationTest - Helper function used by
1037 /// EmitEdgePropertyTest.
1038 void EmitLogicalOperationTest(const DagInit& Prop, const char* LogicOp,
1039 const GlobalOptionDescriptions& OptDescs,
1042 for (unsigned j = 0, NumArgs = Prop.getNumArgs(); j < NumArgs; ++j) {
1043 const DagInit& InnerProp = InitPtrToDagInitRef(Prop.getArg(j));
1044 EmitEdgePropertyTest(InnerProp, OptDescs, O);
1045 if (j != NumArgs - 1)
1046 O << ")\n" << Indent3 << ' ' << LogicOp << " (";
1052 /// EmitEdgePropertyTest - Helper function used by EmitEdgeClass.
1053 void EmitEdgePropertyTest(const DagInit& Prop,
1054 const GlobalOptionDescriptions& OptDescs,
1056 const std::string& PropName = Prop.getOperator()->getAsString();
1058 if (PropName == "and")
1059 EmitLogicalOperationTest(Prop, "&&", OptDescs, O);
1060 else if (PropName == "or")
1061 EmitLogicalOperationTest(Prop, "||", OptDescs, O);
1062 else if (EmitEdgePropertyTest1Arg(PropName, Prop, OptDescs, O))
1064 else if (EmitEdgePropertyTest2Args(PropName, Prop, OptDescs, O))
1067 throw PropName + ": unknown edge property!";
1070 /// EmitEdgeClass - Emit a single Edge# class.
1071 void EmitEdgeClass(unsigned N, const std::string& Target,
1072 ListInit* Props, const GlobalOptionDescriptions& OptDescs,
1075 // Class constructor.
1076 O << "class Edge" << N << ": public Edge {\n"
1078 << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1081 // Function Weight().
1082 << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
1083 << Indent2 << "unsigned ret = 0;\n";
1085 // Emit tests for every edge property.
1086 for (size_t i = 0, PropsSize = Props->size(); i < PropsSize; ++i) {
1087 const DagInit& Prop = InitPtrToDagInitRef(Props->getElement(i));
1088 const std::string& PropName = Prop.getOperator()->getAsString();
1091 O << Indent2 << "if (";
1093 if (PropName == "weight") {
1094 checkNumberOfArguments(&Prop, 2);
1095 N = InitPtrToInt(Prop.getArg(0));
1096 const DagInit& InnerProp = InitPtrToDagInitRef(Prop.getArg(1));
1097 EmitEdgePropertyTest(InnerProp, OptDescs, O);
1100 EmitEdgePropertyTest(Prop, OptDescs, O);
1103 O << ")\n" << Indent3 << "ret += " << N << ";\n";
1106 O << Indent2 << "return ret;\n"
1107 << Indent1 << "};\n\n};\n\n";
1110 // Emit Edge* classes that represent graph edges.
1111 void EmitEdgeClasses (Record* CompilationGraph,
1112 const GlobalOptionDescriptions& OptDescs,
1114 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1116 for (unsigned i = 0; i < edges->size(); ++i) {
1117 Record* Edge = edges->getElementAsRecord(i);
1118 Record* B = Edge->getValueAsDef("b");
1119 ListInit* Props = Edge->getValueAsListInit("props");
1124 EmitEdgeClass(i, B->getName(), Props, OptDescs, O);
1128 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1130 void EmitPopulateCompilationGraph (Record* CompilationGraph,
1133 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1136 O << "void llvmc::PopulateCompilationGraph(CompilationGraph& G) {\n"
1137 << Indent1 << "PopulateLanguageMap(G.ExtsToLangs);\n\n";
1141 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1143 throw std::string("No tool definitions found!");
1145 for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
1146 const std::string& Name = (*B)->getName();
1148 O << Indent1 << "G.insertNode(new "
1149 << Name << "());\n";
1155 for (unsigned i = 0; i < edges->size(); ++i) {
1156 Record* Edge = edges->getElementAsRecord(i);
1157 Record* A = Edge->getValueAsDef("a");
1158 Record* B = Edge->getValueAsDef("b");
1159 ListInit* Props = Edge->getValueAsListInit("props");
1161 O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
1164 O << "new SimpleEdge(\"" << B->getName() << "\")";
1166 O << "new Edge" << i << "()";
1175 // End of anonymous namespace
1178 /// run - The back-end entry point.
1179 void LLVMCConfigurationEmitter::run (std::ostream &O) {
1181 // Emit file header.
1182 EmitSourceFileHeader("LLVMC Configuration Library", O);
1184 // Get a list of all defined Tools.
1185 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1187 throw std::string("No tool definitions found!");
1189 // Gather information from the Tool description dags.
1190 ToolPropertiesList tool_props;
1191 GlobalOptionDescriptions opt_descs;
1192 CollectToolProperties(Tools.begin(), Tools.end(), tool_props, opt_descs);
1194 // Emit global option registration code.
1195 EmitOptionDescriptions(opt_descs, O);
1197 // Emit PopulateLanguageMap() function
1198 // (a language map maps from file extensions to language names).
1199 EmitPopulateLanguageMap(Records, O);
1201 // Emit Tool classes.
1202 for (ToolPropertiesList::const_iterator B = tool_props.begin(),
1203 E = tool_props.end(); B!=E; ++B)
1204 EmitToolClassDefinition(*(*B), O);
1206 Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
1207 if (!CompilationGraphRecord)
1208 throw std::string("Compilation graph description not found!");
1210 // Typecheck the compilation graph.
1211 TypecheckGraph(CompilationGraphRecord, tool_props);
1213 // Emit Edge# classes.
1214 EmitEdgeClasses(CompilationGraphRecord, opt_descs, O);
1216 // Emit PopulateCompilationGraph() function.
1217 EmitPopulateCompilationGraph(CompilationGraphRecord, O);