b0ecab35b7e67c4e0c1d66f58e9cb9082f8d20e4
[oota-llvm.git] / utils / TableGen / LLVMCCConfigurationEmitter.cpp
1 //===- LLVMCConfigurationEmitter.cpp - Generate LLVMCC config -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open
6 // Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This tablegen backend is responsible for emitting LLVMCC configuration code.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "LLVMCCConfigurationEmitter.h"
15 #include "Record.h"
16
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"
22
23 #include <algorithm>
24 #include <cassert>
25 #include <functional>
26 #include <string>
27
28 using namespace llvm;
29
30 //namespace {
31
32 //===----------------------------------------------------------------------===//
33 /// Typedefs
34
35 typedef std::vector<Record*> RecordVector;
36 typedef std::vector<std::string> StrVector;
37
38 //===----------------------------------------------------------------------===//
39 /// Constants
40
41 // Indentation strings
42 const char * Indent1 = "    ";
43 const char * Indent2 = "        ";
44 const char * Indent3 = "            ";
45 const char * Indent4 = "                ";
46
47 // Default help string
48 const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
49
50 // Name for the "sink" option
51 const char * SinkOptionName = "AutoGeneratedSinkOption";
52
53 //===----------------------------------------------------------------------===//
54 /// Helper functions
55
56 std::string InitPtrToString(Init* ptr) {
57   StringInit& val = dynamic_cast<StringInit&>(*ptr);
58   return val.getValue();
59 }
60
61 // Ensure that the number of args in d is <= min_arguments,
62 // throw exception otherwise
63 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
64   if (d->getNumArgs() < min_arguments)
65     throw "Property " + d->getOperator()->getAsString()
66       + " has too few arguments!";
67 }
68
69
70 //===----------------------------------------------------------------------===//
71 /// Back-end specific code
72
73 // A command-line option can have one of the following types:
74 //
75 // Switch - a simple switch w/o arguments, e.g. -O2
76 //
77 // Parameter - an option that takes one(and only one) argument, e.g. -o file,
78 // --output=file
79 //
80 // ParameterList - same as Parameter, but more than one occurence
81 // of the option is allowed, e.g. -lm -lpthread
82 //
83 // Prefix - argument is everything after the prefix,
84 // e.g. -Wa,-foo,-bar, -DNAME=VALUE
85 //
86 // PrefixList - same as Prefix, but more than one option occurence is
87 // allowed
88
89 namespace OptionType {
90   enum OptionType { Switch, Parameter, ParameterList, Prefix, PrefixList};
91 }
92
93 bool IsListOptionType (OptionType::OptionType t) {
94   return (t == OptionType::ParameterList || t == OptionType::PrefixList);
95 }
96
97 // Code duplication here is necessary because one option can affect
98 // several tools and those tools may have different actions associated
99 // with this option. GlobalOptionDescriptions are used to generate
100 // the option registration code, while ToolOptionDescriptions are used
101 // to generate tool-specific code.
102
103 // Base class for option descriptions
104
105 struct OptionDescription {
106   OptionType::OptionType Type;
107   std::string Name;
108
109   OptionDescription(OptionType::OptionType t = OptionType::Switch,
110                     const std::string& n = "")
111   : Type(t), Name(n)
112   {}
113
114   const char* GenTypeDeclaration() const {
115     switch (Type) {
116     case OptionType::PrefixList:
117     case OptionType::ParameterList:
118       return "cl::list<std::string>";
119     case OptionType::Switch:
120       return "cl::opt<bool>";
121     case OptionType::Parameter:
122     case OptionType::Prefix:
123     default:
124       return "cl::opt<std::string>";
125     }
126   }
127
128   std::string GenVariableName() const {
129     switch (Type) {
130     case OptionType::Switch:
131      return "AutoGeneratedSwitch" + Name;
132    case OptionType::Prefix:
133      return "AutoGeneratedPrefix" + Name;
134    case OptionType::PrefixList:
135      return "AutoGeneratedPrefixList" + Name;
136    case OptionType::Parameter:
137      return "AutoGeneratedParameter" + Name;
138    case OptionType::ParameterList:
139    default:
140      return "AutoGeneratedParameterList" + Name;
141    }
142   }
143
144 };
145
146 // Global option description
147
148 namespace GlobalOptionDescriptionFlags {
149   enum GlobalOptionDescriptionFlags { Required = 0x1 };
150 }
151
152 struct GlobalOptionDescription : public OptionDescription {
153   std::string Help;
154   unsigned Flags;
155
156   // We need t provide a default constructor since
157   // StringMap can only store DefaultConstructible objects
158   GlobalOptionDescription() : OptionDescription(), Flags(0)
159   {}
160
161   GlobalOptionDescription (OptionType::OptionType t, const std::string& n)
162     : OptionDescription(t, n), Help(DefaultHelpString), Flags(0)
163   {}
164
165   bool isRequired() const {
166     return Flags & GlobalOptionDescriptionFlags::Required;
167   }
168   void setRequired() {
169     Flags |= GlobalOptionDescriptionFlags::Required;
170   }
171
172   // Merge two option descriptions
173   void Merge (const GlobalOptionDescription& other)
174   {
175     if (other.Type != Type)
176       throw "Conflicting definitions for the option " + Name + "!";
177
178     if (Help.empty() && !other.Help.empty())
179       Help = other.Help;
180     else if (!Help.empty() && !other.Help.empty())
181       cerr << "Warning: more than one help string defined for option "
182         + Name + "\n";
183
184     Flags |= other.Flags;
185   }
186 };
187
188 // A GlobalOptionDescription array
189 // + some flags affecting generation of option declarations
190 struct GlobalOptionDescriptions {
191   typedef StringMap<GlobalOptionDescription> container_type;
192   typedef container_type::const_iterator const_iterator;
193
194   // A list of GlobalOptionDescriptions
195   container_type Descriptions;
196   // Should the emitter generate a "cl::sink" option?
197   bool HasSink;
198
199   const GlobalOptionDescription& FindOption(const std::string& OptName) const {
200     const_iterator I = Descriptions.find(OptName);
201     if (I != Descriptions.end())
202       return I->second;
203     else
204       throw OptName + ": no such option!";
205   }
206
207   // Support for STL-style iteration
208   const_iterator begin() const { return Descriptions.begin(); }
209   const_iterator end() const { return Descriptions.end(); }
210 };
211
212
213 // Tool-local option description
214
215 // Properties without arguments are implemented as flags
216 namespace ToolOptionDescriptionFlags {
217   enum ToolOptionDescriptionFlags { StopCompilation = 0x1,
218                                     Forward = 0x2, UnpackValues = 0x4};
219 }
220 namespace OptionPropertyType {
221   enum OptionPropertyType { AppendCmd };
222 }
223
224 typedef std::pair<OptionPropertyType::OptionPropertyType, std::string>
225 OptionProperty;
226 typedef SmallVector<OptionProperty, 4> OptionPropertyList;
227
228 struct ToolOptionDescription : public OptionDescription {
229   unsigned Flags;
230   OptionPropertyList Props;
231
232   // StringMap can only store DefaultConstructible objects
233   ToolOptionDescription() : OptionDescription(), Flags(0) {}
234
235   ToolOptionDescription (OptionType::OptionType t, const std::string& n)
236     : OptionDescription(t, n)
237   {}
238
239   // Various boolean properties
240   bool isStopCompilation() const {
241     return Flags & ToolOptionDescriptionFlags::StopCompilation;
242   }
243   void setStopCompilation() {
244     Flags |= ToolOptionDescriptionFlags::StopCompilation;
245   }
246
247   bool isForward() const {
248     return Flags & ToolOptionDescriptionFlags::Forward;
249   }
250   void setForward() {
251     Flags |= ToolOptionDescriptionFlags::Forward;
252   }
253
254   bool isUnpackValues() const {
255     return Flags & ToolOptionDescriptionFlags::UnpackValues;
256   }
257   void setUnpackValues() {
258     Flags |= ToolOptionDescriptionFlags::UnpackValues;
259   }
260
261   void AddProperty (OptionPropertyType::OptionPropertyType t,
262                     const std::string& val)
263   {
264     Props.push_back(std::make_pair(t, val));
265   }
266 };
267
268 typedef StringMap<ToolOptionDescription> ToolOptionDescriptions;
269
270 // Tool information record
271
272 namespace ToolFlags {
273   enum ToolFlags { Join = 0x1, Sink = 0x2 };
274 }
275
276 struct ToolProperties : public RefCountedBase<ToolProperties> {
277   std::string Name;
278   StrVector CmdLine;
279   std::string InLanguage;
280   std::string OutLanguage;
281   std::string OutputSuffix;
282   unsigned Flags;
283   ToolOptionDescriptions OptDescs;
284
285   // Various boolean properties
286   void setSink()      { Flags |= ToolFlags::Sink; }
287   bool isSink() const { return Flags & ToolFlags::Sink; }
288   void setJoin()      { Flags |= ToolFlags::Join; }
289   bool isJoin() const { return Flags & ToolFlags::Join; }
290
291   // Default ctor here is needed because StringMap can only store
292   // DefaultConstructible objects
293   ToolProperties() {}
294   ToolProperties (const std::string& n) : Name(n) {}
295 };
296
297
298 // A list of Tool information records
299 // IntrusiveRefCntPtrs are used because StringMap has no copy constructor
300 // (and we want to avoid copying ToolProperties anyway)
301 typedef std::vector<IntrusiveRefCntPtr<ToolProperties> > ToolPropertiesList;
302
303
304 // Function object for iterating over a list of tool property records
305 class CollectProperties {
306 private:
307
308   /// Implementation details
309
310   // "Property handler" - a function that extracts information
311   // about a given tool property from its DAG representation
312   typedef void (CollectProperties::*PropertyHandler)(DagInit*);
313
314   // Map from property names -> property handlers
315   typedef StringMap<PropertyHandler> PropertyHandlerMap;
316
317   // "Option property handler" - a function that extracts information
318   // about a given option property from its DAG representation
319   typedef void (CollectProperties::*
320                 OptionPropertyHandler)(DagInit*, GlobalOptionDescription &);
321
322   // Map from option property names -> option property handlers
323   typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
324
325   // Static maps from strings to CollectProperties methods("handlers")
326   static PropertyHandlerMap propertyHandlers_;
327   static OptionPropertyHandlerMap optionPropertyHandlers_;
328   static bool staticMembersInitialized_;
329
330
331   /// This is where the information is stored
332
333   // Current Tool properties
334   ToolProperties& toolProps_;
335   // OptionDescriptions table(used to register options globally)
336   GlobalOptionDescriptions& optDescs_;
337
338 public:
339
340   explicit CollectProperties (ToolProperties& p, GlobalOptionDescriptions& d)
341     : toolProps_(p), optDescs_(d)
342   {
343     if (!staticMembersInitialized_) {
344       // Init tool property handlers
345       propertyHandlers_["cmd_line"] = &CollectProperties::onCmdLine;
346       propertyHandlers_["in_language"] = &CollectProperties::onInLanguage;
347       propertyHandlers_["join"] = &CollectProperties::onJoin;
348       propertyHandlers_["out_language"] = &CollectProperties::onOutLanguage;
349       propertyHandlers_["output_suffix"] = &CollectProperties::onOutputSuffix;
350       propertyHandlers_["parameter_option"]
351         = &CollectProperties::onParameter;
352       propertyHandlers_["parameter_list_option"] =
353         &CollectProperties::onParameterList;
354       propertyHandlers_["prefix_option"] = &CollectProperties::onPrefix;
355       propertyHandlers_["prefix_list_option"] =
356         &CollectProperties::onPrefixList;
357       propertyHandlers_["sink"] = &CollectProperties::onSink;
358       propertyHandlers_["switch_option"] = &CollectProperties::onSwitch;
359
360       // Init option property handlers
361       optionPropertyHandlers_["append_cmd"] = &CollectProperties::onAppendCmd;
362       optionPropertyHandlers_["forward"] = &CollectProperties::onForward;
363       optionPropertyHandlers_["help"] = &CollectProperties::onHelp;
364       optionPropertyHandlers_["required"] = &CollectProperties::onRequired;
365       optionPropertyHandlers_["stop_compilation"] =
366         &CollectProperties::onStopCompilation;
367       optionPropertyHandlers_["unpack_values"] =
368         &CollectProperties::onUnpackValues;
369
370       staticMembersInitialized_ = true;
371     }
372   }
373
374   // Gets called for every tool property;
375   // Just forwards to the corresponding property handler.
376   void operator() (Init* i) {
377     DagInit& d = dynamic_cast<DagInit&>(*i);
378     const std::string& property_name = d.getOperator()->getAsString();
379     PropertyHandlerMap::iterator method
380       = propertyHandlers_.find(property_name);
381
382     if (method != propertyHandlers_.end()) {
383       PropertyHandler h = method->second;
384       (this->*h)(&d);
385     }
386     else {
387       throw "Unknown tool property: " + property_name + "!";
388     }
389   }
390
391 private:
392
393   /// Property handlers --
394   /// Functions that extract information about tool properties from
395   /// DAG representation.
396
397   void onCmdLine (DagInit* d) {
398     checkNumberOfArguments(d, 1);
399     SplitString(InitPtrToString(d->getArg(0)), toolProps_.CmdLine);
400     if (toolProps_.CmdLine.empty())
401       throw "Tool " + toolProps_.Name + " has empty command line!";
402   }
403
404   void onInLanguage (DagInit* d) {
405     checkNumberOfArguments(d, 1);
406     toolProps_.InLanguage = InitPtrToString(d->getArg(0));
407   }
408
409   void onJoin (DagInit* d) {
410     checkNumberOfArguments(d, 0);
411     toolProps_.setJoin();
412   }
413
414   void onOutLanguage (DagInit* d) {
415     checkNumberOfArguments(d, 1);
416     toolProps_.OutLanguage = InitPtrToString(d->getArg(0));
417   }
418
419   void onOutputSuffix (DagInit* d) {
420     checkNumberOfArguments(d, 1);
421     toolProps_.OutputSuffix = InitPtrToString(d->getArg(0));
422   }
423
424   void onSink (DagInit* d) {
425     checkNumberOfArguments(d, 0);
426     optDescs_.HasSink = true;
427     toolProps_.setSink();
428   }
429
430   void onSwitch (DagInit* d)        { addOption(d, OptionType::Switch); }
431   void onParameter (DagInit* d)     { addOption(d, OptionType::Parameter); }
432   void onParameterList (DagInit* d) { addOption(d, OptionType::ParameterList); }
433   void onPrefix (DagInit* d)        { addOption(d, OptionType::Prefix); }
434   void onPrefixList (DagInit* d)    { addOption(d, OptionType::PrefixList); }
435
436   /// Option property handlers --
437   /// Methods that handle properties that are common for all types of
438   /// options (like append_cmd, stop_compilation)
439
440   void onAppendCmd (DagInit* d, GlobalOptionDescription& o) {
441     checkNumberOfArguments(d, 1);
442     std::string const& cmd = InitPtrToString(d->getArg(0));
443
444     toolProps_.OptDescs[o.Name].AddProperty(OptionPropertyType::AppendCmd, cmd);
445   }
446
447   void onForward (DagInit* d, GlobalOptionDescription& o) {
448     checkNumberOfArguments(d, 0);
449     toolProps_.OptDescs[o.Name].setForward();
450   }
451
452   void onHelp (DagInit* d, GlobalOptionDescription& o) {
453     checkNumberOfArguments(d, 1);
454     const std::string& help_message = InitPtrToString(d->getArg(0));
455
456     o.Help = help_message;
457   }
458
459   void onRequired (DagInit* d, GlobalOptionDescription& o) {
460     checkNumberOfArguments(d, 0);
461     o.setRequired();
462   }
463
464   void onStopCompilation (DagInit* d, GlobalOptionDescription& o) {
465     checkNumberOfArguments(d, 0);
466     if (o.Type != OptionType::Switch)
467       throw std::string("Only options of type Switch can stop compilation!");
468     toolProps_.OptDescs[o.Name].setStopCompilation();
469   }
470
471   void onUnpackValues (DagInit* d, GlobalOptionDescription& o) {
472     checkNumberOfArguments(d, 0);
473     toolProps_.OptDescs[o.Name].setUnpackValues();
474   }
475
476   /// Helper functions
477
478   // Add an option of type t
479   void addOption (DagInit* d, OptionType::OptionType t) {
480     checkNumberOfArguments(d, 2);
481     const std::string& name = InitPtrToString(d->getArg(0));
482
483     GlobalOptionDescription o(t, name);
484     toolProps_.OptDescs[name].Type = t;
485     toolProps_.OptDescs[name].Name = name;
486     processOptionProperties(d, o);
487     insertDescription(o);
488   }
489
490   // Insert new GlobalOptionDescription into GlobalOptionDescriptions list
491   void insertDescription (const GlobalOptionDescription& o)
492   {
493     if (optDescs_.Descriptions.count(o.Name)) {
494       GlobalOptionDescription& D = optDescs_.Descriptions[o.Name];
495       D.Merge(o);
496     }
497     else {
498       optDescs_.Descriptions[o.Name] = o;
499     }
500   }
501
502   // Go through the list of option properties and call a corresponding
503   // handler for each.
504   //
505   // Parameters:
506   // name - option name
507   // d - option property list
508   void processOptionProperties (DagInit* d, GlobalOptionDescription& o) {
509     // First argument is option name
510     checkNumberOfArguments(d, 2);
511
512     for (unsigned B = 1, E = d->getNumArgs(); B!=E; ++B) {
513       DagInit& option_property
514         = dynamic_cast<DagInit&>(*d->getArg(B));
515       const std::string& option_property_name
516         = option_property.getOperator()->getAsString();
517       OptionPropertyHandlerMap::iterator method
518         = optionPropertyHandlers_.find(option_property_name);
519
520       if (method != optionPropertyHandlers_.end()) {
521         OptionPropertyHandler h = method->second;
522         (this->*h)(&option_property, o);
523       }
524       else {
525         throw "Unknown option property: " + option_property_name + "!";
526       }
527     }
528   }
529 };
530
531 // Static members of CollectProperties
532 CollectProperties::PropertyHandlerMap
533 CollectProperties::propertyHandlers_;
534
535 CollectProperties::OptionPropertyHandlerMap
536 CollectProperties::optionPropertyHandlers_;
537
538 bool CollectProperties::staticMembersInitialized_ = false;
539
540
541 // Gather information from the parsed TableGen data
542 // (Basically a wrapper for CollectProperties)
543 void CollectToolProperties (RecordVector::const_iterator B,
544                             RecordVector::const_iterator E,
545                             ToolPropertiesList& TPList,
546                             GlobalOptionDescriptions& OptDescs)
547 {
548   // Iterate over a properties list of every Tool definition
549   for (;B!=E;++B) {
550     RecordVector::value_type T = *B;
551     ListInit* PropList = T->getValueAsListInit("properties");
552
553     IntrusiveRefCntPtr<ToolProperties>
554       ToolProps(new ToolProperties(T->getName()));
555
556     std::for_each(PropList->begin(), PropList->end(),
557                   CollectProperties(*ToolProps, OptDescs));
558     TPList.push_back(ToolProps);
559   }
560 }
561
562 // Used by EmitGenerateActionMethod
563 void EmitOptionPropertyHandlingCode (const ToolProperties& P,
564                                      const ToolOptionDescription& D,
565                                      std::ostream& O)
566 {
567   // if clause
568   O << Indent2 << "if (";
569   if (D.Type == OptionType::Switch)
570     O << D.GenVariableName();
571   else
572     O << '!' << D.GenVariableName() << ".empty()";
573
574   O <<") {\n";
575
576   // Handle option properties that take an argument
577   for (OptionPropertyList::const_iterator B = D.Props.begin(),
578         E = D.Props.end(); B!=E; ++B) {
579     const OptionProperty& val = *B;
580
581     switch (val.first) {
582       // (append_cmd cmd) property
583     case OptionPropertyType::AppendCmd:
584       O << Indent3 << "vec.push_back(\"" << val.second << "\");\n";
585       break;
586       // Other properties with argument
587     default:
588       break;
589     }
590   }
591
592   // Handle flags
593
594   // (forward) property
595   if (D.isForward()) {
596     switch (D.Type) {
597     case OptionType::Switch:
598       O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
599       break;
600     case OptionType::Parameter:
601       O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
602       O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
603       break;
604     case OptionType::Prefix:
605       O << Indent3 << "vec.push_back(\"-" << D.Name << "\" + "
606         << D.GenVariableName() << ");\n";
607       break;
608     case OptionType::PrefixList:
609       O << Indent3 << "for (" << D.GenTypeDeclaration()
610         << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
611         << Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
612         << Indent4 << "vec.push_back(\"-" << D.Name << "\" + "
613         << "*B);\n";
614       break;
615     case OptionType::ParameterList:
616       O << Indent3 << "for (" << D.GenTypeDeclaration()
617         << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
618         << Indent3 << "E = " << D.GenVariableName()
619         << ".end() ; B != E; ++B) {\n"
620         << Indent4 << "vec.push_back(\"-" << D.Name << "\");\n"
621         << Indent4 << "vec.push_back(*B);\n"
622         << Indent3 << "}\n";
623       break;
624     }
625   }
626
627   // (unpack_values) property
628   if (D.isUnpackValues()) {
629     if (IsListOptionType(D.Type)) {
630       O << Indent3 << "for (" << D.GenTypeDeclaration()
631         << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
632         << Indent3 << "E = " << D.GenVariableName()
633         << ".end(); B != E; ++B)\n"
634         << Indent4 << "Tool::UnpackValues(*B, vec);\n";
635     }
636     else if (D.Type == OptionType::Prefix || D.Type == OptionType::Parameter){
637       O << Indent3 << "Tool::UnpackValues("
638         << D.GenVariableName() << ", vec);\n";
639     }
640     else {
641       // TOFIX: move this to the type-checking phase
642       throw std::string("Switches can't have unpack_values property!");
643     }
644   }
645
646   // close if clause
647   O << Indent2 << "}\n";
648 }
649
650 // Emite one of two versions of GenerateAction method
651 void EmitGenerateActionMethod (const ToolProperties& P, int V, std::ostream& O)
652 {
653   assert(V==1 || V==2);
654   if (V==1)
655     O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
656   else
657     O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
658
659   O << Indent2 << "const sys::Path& outFile) const\n"
660     << Indent1 << "{\n"
661     << Indent2 << "std::vector<std::string> vec;\n";
662
663   // Parse CmdLine tool property
664   if(P.CmdLine.empty())
665     throw "Tool " + P.Name + " has empty command line!";
666
667   StrVector::const_iterator I = P.CmdLine.begin();
668   ++I;
669   for (StrVector::const_iterator E = P.CmdLine.end(); I != E; ++I) {
670     const std::string& cmd = *I;
671     O << Indent2;
672     if (cmd == "$INFILE") {
673       if (V==1)
674         O << "for (PathVector::const_iterator B = inFiles.begin()"
675           << ", E = inFiles.end();\n"
676           << Indent2 << "B != E; ++B)\n"
677           << Indent3 << "vec.push_back(B->toString());\n";
678       else
679         O << "vec.push_back(inFile.toString());\n";
680     }
681     else if (cmd == "$OUTFILE") {
682       O << "vec.push_back(outFile.toString());\n";
683     }
684     else {
685       O << "vec.push_back(\"" << cmd << "\");\n";
686     }
687   }
688
689   // For every understood option, emit handling code
690   for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
691         E = P.OptDescs.end(); B != E; ++B) {
692     const ToolOptionDescription& val = B->second;
693     EmitOptionPropertyHandlingCode(P, val, O);
694   }
695
696   // Handle Sink property
697   if (P.isSink()) {
698     O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
699       << Indent3 << "vec.insert(vec.end(), "
700       << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
701       << Indent2 << "}\n";
702   }
703
704   O << Indent2 << "return Action(\"" << P.CmdLine.at(0) << "\", vec);\n"
705     << Indent1 << "}\n\n";
706 }
707
708 // Emit GenerateAction methods for Tool classes
709 void EmitGenerateActionMethods (const ToolProperties& P, std::ostream& O) {
710
711   if (!P.isJoin())
712     O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
713       << Indent2 << "const llvm::sys::Path& outFile) const\n"
714       << Indent1 << "{\n"
715       << Indent2 << "throw std::runtime_error(\"" << P.Name
716       << " is not a Join tool!\");\n"
717       << Indent1 << "}\n\n";
718   else
719     EmitGenerateActionMethod(P, 1, O);
720
721   EmitGenerateActionMethod(P, 2, O);
722 }
723
724 // Emit IsLast() method for Tool classes
725 void EmitIsLastMethod (const ToolProperties& P, std::ostream& O) {
726   O << Indent1 << "bool IsLast() const {\n"
727     << Indent2 << "bool last = false;\n";
728
729   for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
730         E = P.OptDescs.end(); B != E; ++B) {
731     const ToolOptionDescription& val = B->second;
732
733     if (val.isStopCompilation())
734       O << Indent2
735         << "if (" << val.GenVariableName()
736         << ")\n" << Indent3 << "last = true;\n";
737   }
738
739   O << Indent2 << "return last;\n"
740     << Indent1 <<  "}\n\n";
741 }
742
743 // Emit static [Input,Output]Language() methods for Tool classes
744 void EmitInOutLanguageMethods (const ToolProperties& P, std::ostream& O) {
745   O << Indent1 << "const char* InputLanguage() const {\n"
746     << Indent2 << "return \"" << P.InLanguage << "\";\n"
747     << Indent1 << "}\n\n";
748
749   O << Indent1 << "const char* OutputLanguage() const {\n"
750     << Indent2 << "return \"" << P.OutLanguage << "\";\n"
751     << Indent1 << "}\n\n";
752 }
753
754 // Emit static [Input,Output]Language() methods for Tool classes
755 void EmitOutputSuffixMethod (const ToolProperties& P, std::ostream& O) {
756   O << Indent1 << "const char* OutputSuffix() const {\n"
757     << Indent2 << "return \"" << P.OutputSuffix << "\";\n"
758     << Indent1 << "}\n\n";
759 }
760
761 // Emit static Name() method for Tool classes
762 void EmitNameMethod (const ToolProperties& P, std::ostream& O) {
763   O << Indent1 << "const char* Name() const {\n"
764     << Indent2 << "return \"" << P.Name << "\";\n"
765     << Indent1 << "}\n\n";
766 }
767
768 // Emit static Name() method for Tool classes
769 void EmitIsJoinMethod (const ToolProperties& P, std::ostream& O) {
770   O << Indent1 << "bool IsJoin() const {\n";
771   if (P.isJoin())
772     O << Indent2 << "return true;\n";
773   else
774     O << Indent2 << "return false;\n";
775   O << Indent1 << "}\n\n";
776 }
777
778 // Emit a Tool class definition
779 void EmitToolClassDefinition (const ToolProperties& P, std::ostream& O) {
780
781   if(P.Name == "root")
782     return;
783
784   // Header
785   O << "class " << P.Name << " : public ";
786   if (P.isJoin())
787     O << "JoinTool";
788   else
789     O << "Tool";
790   O << "{\npublic:\n";
791
792   EmitNameMethod(P, O);
793   EmitInOutLanguageMethods(P, O);
794   EmitOutputSuffixMethod(P, O);
795   EmitIsJoinMethod(P, O);
796   EmitGenerateActionMethods(P, O);
797   EmitIsLastMethod(P, O);
798
799   // Close class definition
800   O << "};\n\n";
801 }
802
803 // Iterate over a list of option descriptions and emit registration code
804 void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
805                              std::ostream& O)
806 {
807   // Emit static cl::Option variables
808   for (GlobalOptionDescriptions::const_iterator B = descs.begin(),
809          E = descs.end(); B!=E; ++B) {
810     const GlobalOptionDescription& val = B->second;
811
812     O << val.GenTypeDeclaration() << ' '
813       << val.GenVariableName()
814       << "(\"" << val.Name << '\"';
815
816     if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
817       O << ", cl::Prefix";
818
819     if (val.isRequired()) {
820       switch (val.Type) {
821       case OptionType::PrefixList:
822       case OptionType::ParameterList:
823         O << ", cl::OneOrMore";
824         break;
825       default:
826         O << ", cl::Required";
827       }
828     }
829
830     O << ", cl::desc(\"" << val.Help << "\"));\n";
831   }
832
833   if (descs.HasSink)
834     O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
835
836   O << '\n';
837 }
838
839 void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
840 {
841   // Get the relevant field out of RecordKeeper
842   Record* LangMapRecord = Records.getDef("LanguageMap");
843   if (!LangMapRecord)
844     throw std::string("Language map definition not found!");
845
846   ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
847   if (!LangsToSuffixesList)
848     throw std::string("Error in the language map definition!");
849
850   // Generate code
851   O << "void llvmcc::PopulateLanguageMap(LanguageMap& language_map) {\n";
852
853   for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
854     Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
855
856     const std::string& Lang = LangToSuffixes->getValueAsString("lang");
857     const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
858
859     for (unsigned i = 0; i < Suffixes->size(); ++i)
860       O << Indent1 << "language_map[\""
861         << InitPtrToString(Suffixes->getElement(i))
862         << "\"] = \"" << Lang << "\";\n";
863   }
864
865   O << "}\n\n";
866 }
867
868 // Fills in two tables that map tool names to (input, output) languages.
869 // Used by the typechecker.
870 void FillInToolToLang (const ToolPropertiesList& TPList,
871                        StringMap<std::string>& ToolToInLang,
872                        StringMap<std::string>& ToolToOutLang) {
873   for (ToolPropertiesList::const_iterator B = TPList.begin(), E = TPList.end();
874        B != E; ++B) {
875     const ToolProperties& P = *(*B);
876     ToolToInLang[P.Name] = P.InLanguage;
877     ToolToOutLang[P.Name] = P.OutLanguage;
878   }
879 }
880
881 // Check that all output and input language names match.
882 // TOFIX: check for cycles.
883 // TOFIX: check for multiple default edges.
884 void TypecheckGraph (Record* CompilationGraph,
885                      const ToolPropertiesList& TPList) {
886   StringMap<std::string> ToolToInLang;
887   StringMap<std::string> ToolToOutLang;
888
889   FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
890   ListInit* edges = CompilationGraph->getValueAsListInit("edges");
891   StringMap<std::string>::iterator IAE = ToolToInLang.end();
892   StringMap<std::string>::iterator IBE = ToolToOutLang.end();
893
894   for (unsigned i = 0; i < edges->size(); ++i) {
895     Record* Edge = edges->getElementAsRecord(i);
896     Record* A = Edge->getValueAsDef("a");
897     Record* B = Edge->getValueAsDef("b");
898     StringMap<std::string>::iterator IA = ToolToOutLang.find(A->getName());
899     StringMap<std::string>::iterator IB = ToolToInLang.find(B->getName());
900     if(IA == IAE)
901       throw A->getName() + ": no such tool!";
902     if(IB == IBE)
903       throw B->getName() + ": no such tool!";
904     if(A->getName() != "root" && IA->second != IB->second)
905       throw "Edge " + A->getName() + "->" + B->getName()
906         + ": output->input language mismatch";
907     if(B->getName() == "root")
908       throw std::string("Edges back to the root are not allowed!");
909   }
910 }
911
912 // Helper function used by EmitEdgePropertyTest.
913 void EmitEdgePropertyTest1Arg(const DagInit& Prop,
914                               const GlobalOptionDescriptions& OptDescs,
915                               std::ostream& O) {
916   checkNumberOfArguments(&Prop, 1);
917   const std::string& OptName = InitPtrToString(Prop.getArg(0));
918   const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
919   if (OptDesc.Type != OptionType::Switch)
920     throw OptName + ": incorrect option type!";
921   O << OptDesc.GenVariableName();
922 }
923
924 // Helper function used by EmitEdgePropertyTest.
925 void EmitEdgePropertyTest2Args(const std::string& PropName,
926                                const DagInit& Prop,
927                                const GlobalOptionDescriptions& OptDescs,
928                                std::ostream& O) {
929   checkNumberOfArguments(&Prop, 2);
930   const std::string& OptName = InitPtrToString(Prop.getArg(0));
931   const std::string& OptArg = InitPtrToString(Prop.getArg(1));
932   const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
933
934   if (PropName == "parameter_equals") {
935     if (OptDesc.Type != OptionType::Parameter
936         && OptDesc.Type != OptionType::Prefix)
937       throw OptName + ": incorrect option type!";
938     O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
939   }
940   else if (PropName == "element_in_list") {
941     if (OptDesc.Type != OptionType::ParameterList
942         && OptDesc.Type != OptionType::PrefixList)
943       throw OptName + ": incorrect option type!";
944     const std::string& VarName = OptDesc.GenVariableName();
945     O << "std::find(" << VarName << ".begin(),\n"
946       << Indent3 << VarName << ".end(), \""
947       << OptArg << "\") != " << VarName << ".end()";
948   }
949   else
950     throw PropName + ": unknown edge property!";
951 }
952
953 // Helper function used by EmitEdgeClass.
954 void EmitEdgePropertyTest(const std::string& PropName,
955                           const DagInit& Prop,
956                           const GlobalOptionDescriptions& OptDescs,
957                           std::ostream& O) {
958   if (PropName == "switch_on")
959     EmitEdgePropertyTest1Arg(Prop, OptDescs, O);
960   else
961     EmitEdgePropertyTest2Args(PropName, Prop, OptDescs, O);
962 }
963
964 // Emit a single Edge* class.
965 void EmitEdgeClass(unsigned N, const std::string& Target,
966                    ListInit* Props, const GlobalOptionDescriptions& OptDescs,
967                    std::ostream& O) {
968   bool IsDefault = false;
969
970   // Class constructor.
971   O << "class Edge" << N << ": public Edge {\n"
972     << "public:\n"
973     << Indent1 << "Edge" << N << "() : Edge(\"" << Target
974     << "\") {}\n\n"
975
976     // Function isEnabled().
977     << Indent1 << "bool isEnabled() const {\n"
978     << Indent2 << "bool ret = false;\n";
979
980   for (size_t i = 0, PropsSize = Props->size(); i < PropsSize; ++i) {
981     const DagInit& Prop = dynamic_cast<DagInit&>(*Props->getElement(i));
982     const std::string& PropName = Prop.getOperator()->getAsString();
983
984     if (PropName == "default")
985       IsDefault = true;
986
987     O << Indent2 << "if (ret || (";
988     if (PropName == "and") {
989       O << '(';
990       for (unsigned j = 0, NumArgs = Prop.getNumArgs(); j < NumArgs; ++j) {
991         const DagInit& InnerProp = dynamic_cast<DagInit&>(*Prop.getArg(j));
992         const std::string& InnerPropName =
993           InnerProp.getOperator()->getAsString();
994         EmitEdgePropertyTest(InnerPropName, InnerProp, OptDescs, O);
995         if (j != NumArgs - 1)
996           O << ")\n" << Indent3 << " && (";
997         else
998           O << ')';
999       }
1000     }
1001     else {
1002       EmitEdgePropertyTest(PropName, Prop, OptDescs, O);
1003     }
1004     O << "))\n" << Indent3 << "ret = true;\n";
1005   }
1006
1007   O << Indent2 << "return ret;\n"
1008     << Indent1 << "};\n\n"
1009
1010   // Function isDefault().
1011     << Indent1 << "bool isDefault() const { return ";
1012   if (IsDefault)
1013     O << "true";
1014   else
1015     O << "false";
1016   O <<"; }\n};\n\n";
1017 }
1018
1019 // Emit Edge* classes that represent graph edges.
1020 void EmitEdgeClasses (Record* CompilationGraph,
1021                       const GlobalOptionDescriptions& OptDescs,
1022                       std::ostream& O) {
1023   ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1024
1025   for (unsigned i = 0; i < edges->size(); ++i) {
1026     Record* Edge = edges->getElementAsRecord(i);
1027     Record* B = Edge->getValueAsDef("b");
1028     ListInit* Props = Edge->getValueAsListInit("props");
1029
1030     if (Props->empty())
1031       continue;
1032
1033     EmitEdgeClass(i, B->getName(), Props, OptDescs, O);
1034   }
1035 }
1036
1037 void EmitPopulateCompilationGraph (Record* CompilationGraph,
1038                                    std::ostream& O)
1039 {
1040   ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1041
1042   // Generate code
1043   O << "void llvmcc::PopulateCompilationGraph(CompilationGraph& G) {\n"
1044     << Indent1 << "PopulateLanguageMap(G.ExtsToLangs);\n\n";
1045
1046   // Insert vertices
1047
1048   RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1049   if (Tools.empty())
1050     throw std::string("No tool definitions found!");
1051
1052   for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
1053     const std::string& Name = (*B)->getName();
1054     if(Name != "root")
1055       O << Indent1 << "G.insertNode(new "
1056         << Name << "());\n";
1057   }
1058
1059   O << '\n';
1060
1061   // Insert edges
1062   for (unsigned i = 0; i < edges->size(); ++i) {
1063     Record* Edge = edges->getElementAsRecord(i);
1064     Record* A = Edge->getValueAsDef("a");
1065     Record* B = Edge->getValueAsDef("b");
1066     ListInit* Props = Edge->getValueAsListInit("props");
1067
1068     O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
1069
1070     if (Props->empty())
1071       O << "new SimpleEdge(\"" << B->getName() << "\")";
1072     else
1073       O << "new Edge" << i << "()";
1074
1075     O << ");\n";
1076   }
1077
1078   O << "}\n\n";
1079 }
1080
1081
1082 // End of anonymous namespace
1083 //}
1084
1085 // Back-end entry point
1086 void LLVMCCConfigurationEmitter::run (std::ostream &O) {
1087   // Emit file header
1088   EmitSourceFileHeader("LLVMCC Configuration Library", O);
1089
1090   // Get a list of all defined Tools
1091   RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1092   if (Tools.empty())
1093     throw std::string("No tool definitions found!");
1094
1095   // Gather information from the Tool descriptions
1096   ToolPropertiesList tool_props;
1097   GlobalOptionDescriptions opt_descs;
1098   CollectToolProperties(Tools.begin(), Tools.end(), tool_props, opt_descs);
1099
1100   // Emit global option registration code
1101   EmitOptionDescriptions(opt_descs, O);
1102
1103   // Emit PopulateLanguageMap function
1104   // (a language map maps from file extensions to language names)
1105   EmitPopulateLanguageMap(Records, O);
1106
1107   // Emit Tool classes
1108   for (ToolPropertiesList::const_iterator B = tool_props.begin(),
1109          E = tool_props.end(); B!=E; ++B)
1110     EmitToolClassDefinition(*(*B), O);
1111
1112   Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
1113   if (!CompilationGraphRecord)
1114     throw std::string("Compilation graph description not found!");
1115
1116   // Typecheck the compilation graph.
1117   TypecheckGraph(CompilationGraphRecord, tool_props);
1118
1119   // Emit Edge* classes.
1120   EmitEdgeClasses(CompilationGraphRecord, opt_descs, O);
1121
1122   // Emit PopulateCompilationGraph function
1123   EmitPopulateCompilationGraph(CompilationGraphRecord, O);
1124
1125   // EOF
1126 }