f296e7bd79f427eb45cfc74903ed78603c6f0a3b
[oota-llvm.git] / utils / TableGen / LLVMCConfigurationEmitter.cpp
1 //===- LLVMCConfigurationEmitter.cpp - Generate LLVMC config ----*- C++ -*-===//
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 LLVMC configuration code.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "LLVMCConfigurationEmitter.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/ADT/StringSet.h"
22 #include "llvm/Support/Streams.h"
23
24 #include <algorithm>
25 #include <cassert>
26 #include <functional>
27 #include <string>
28
29 using namespace llvm;
30
31 namespace {
32
33 //===----------------------------------------------------------------------===//
34 /// Typedefs
35
36 typedef std::vector<Record*> RecordVector;
37 typedef std::vector<std::string> StrVector;
38
39 //===----------------------------------------------------------------------===//
40 /// Constants
41
42 // Indentation strings.
43 const char * Indent1 = "    ";
44 const char * Indent2 = "        ";
45 const char * Indent3 = "            ";
46 const char * Indent4 = "                ";
47
48 // Default help string.
49 const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
50
51 // Name for the "sink" option.
52 const char * SinkOptionName = "AutoGeneratedSinkOption";
53
54 //===----------------------------------------------------------------------===//
55 /// Helper functions
56
57 int InitPtrToInt(const Init* ptr) {
58   const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
59   return val.getValue();
60 }
61
62 const std::string& InitPtrToString(const Init* ptr) {
63   const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
64   return val.getValue();
65 }
66
67 const ListInit& InitPtrToList(const Init* ptr) {
68   const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
69   return val;
70 }
71
72 const DagInit& InitPtrToDag(const Init* ptr) {
73   const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
74   return val;
75 }
76
77 // checkNumberOfArguments - Ensure that the number of args in d is
78 // less than or equal to min_arguments, otherwise throw an exception.
79 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
80   if (d->getNumArgs() < min_arguments)
81     throw "Property " + d->getOperator()->getAsString()
82       + " has too few arguments!";
83 }
84
85 // isDagEmpty - is this DAG marked with an empty marker?
86 bool isDagEmpty (const DagInit* d) {
87   return d->getOperator()->getAsString() == "empty";
88 }
89
90 //===----------------------------------------------------------------------===//
91 /// Back-end specific code
92
93 // A command-line option can have one of the following types:
94 //
95 // Switch - a simple switch w/o arguments, e.g. -O2
96 //
97 // Parameter - an option that takes one(and only one) argument, e.g. -o file,
98 // --output=file
99 //
100 // ParameterList - same as Parameter, but more than one occurence
101 // of the option is allowed, e.g. -lm -lpthread
102 //
103 // Prefix - argument is everything after the prefix,
104 // e.g. -Wa,-foo,-bar, -DNAME=VALUE
105 //
106 // PrefixList - same as Prefix, but more than one option occurence is
107 // allowed
108
109 namespace OptionType {
110   enum OptionType { Switch, Parameter, ParameterList, Prefix, PrefixList};
111 }
112
113 bool IsListOptionType (OptionType::OptionType t) {
114   return (t == OptionType::ParameterList || t == OptionType::PrefixList);
115 }
116
117 // Code duplication here is necessary because one option can affect
118 // several tools and those tools may have different actions associated
119 // with this option. GlobalOptionDescriptions are used to generate
120 // the option registration code, while ToolOptionDescriptions are used
121 // to generate tool-specific code.
122
123 /// OptionDescription - Base class for option descriptions.
124 struct OptionDescription {
125   OptionType::OptionType Type;
126   std::string Name;
127
128   OptionDescription(OptionType::OptionType t = OptionType::Switch,
129                     const std::string& n = "")
130   : Type(t), Name(n)
131   {}
132
133   const char* GenTypeDeclaration() const {
134     switch (Type) {
135     case OptionType::PrefixList:
136     case OptionType::ParameterList:
137       return "cl::list<std::string>";
138     case OptionType::Switch:
139       return "cl::opt<bool>";
140     case OptionType::Parameter:
141     case OptionType::Prefix:
142     default:
143       return "cl::opt<std::string>";
144     }
145   }
146
147   // Escape commas and other symbols not allowed in the C++ variable
148   // names. Makes it possible to use options with names like "Wa,"
149   // (useful for prefix options).
150   std::string EscapeVariableName(const std::string& Var) const {
151     std::string ret;
152     for (unsigned i = 0; i != Var.size(); ++i) {
153       if (Var[i] == ',') {
154         ret += "_comma_";
155       }
156       else {
157         ret.push_back(Var[i]);
158       }
159     }
160     return ret;
161   }
162
163   std::string GenVariableName() const {
164     const std::string& EscapedName = EscapeVariableName(Name);
165     switch (Type) {
166     case OptionType::Switch:
167      return "AutoGeneratedSwitch" + EscapedName;
168    case OptionType::Prefix:
169      return "AutoGeneratedPrefix" + EscapedName;
170    case OptionType::PrefixList:
171      return "AutoGeneratedPrefixList" + EscapedName;
172    case OptionType::Parameter:
173      return "AutoGeneratedParameter" + EscapedName;
174    case OptionType::ParameterList:
175    default:
176      return "AutoGeneratedParameterList" + EscapedName;
177    }
178   }
179
180 };
181
182 // Global option description.
183
184 namespace GlobalOptionDescriptionFlags {
185   enum GlobalOptionDescriptionFlags { Required = 0x1 };
186 }
187
188 struct GlobalOptionDescription : public OptionDescription {
189   std::string Help;
190   unsigned Flags;
191
192   // We need to provide a default constructor because
193   // StringMap can only store DefaultConstructible objects.
194   GlobalOptionDescription() : OptionDescription(), Flags(0)
195   {}
196
197   GlobalOptionDescription (OptionType::OptionType t, const std::string& n)
198     : OptionDescription(t, n), Help(DefaultHelpString), Flags(0)
199   {}
200
201   bool isRequired() const {
202     return Flags & GlobalOptionDescriptionFlags::Required;
203   }
204   void setRequired() {
205     Flags |= GlobalOptionDescriptionFlags::Required;
206   }
207
208   /// Merge - Merge two option descriptions.
209   void Merge (const GlobalOptionDescription& other)
210   {
211     if (other.Type != Type)
212       throw "Conflicting definitions for the option " + Name + "!";
213
214     if (Help == DefaultHelpString)
215       Help = other.Help;
216     else if (other.Help != DefaultHelpString) {
217       llvm::cerr << "Warning: more than one help string defined for option "
218         + Name + "\n";
219     }
220
221     Flags |= other.Flags;
222   }
223 };
224
225 /// GlobalOptionDescriptions - A GlobalOptionDescription array
226 /// together with some flags affecting generation of option
227 /// declarations.
228 struct GlobalOptionDescriptions {
229   typedef StringMap<GlobalOptionDescription> container_type;
230   typedef container_type::const_iterator const_iterator;
231
232   /// Descriptions - A list of GlobalOptionDescriptions.
233   container_type Descriptions;
234   /// HasSink - Should the emitter generate a "cl::sink" option?
235   bool HasSink;
236
237   const GlobalOptionDescription& FindOption(const std::string& OptName) const {
238     const_iterator I = Descriptions.find(OptName);
239     if (I != Descriptions.end())
240       return I->second;
241     else
242       throw OptName + ": no such option!";
243   }
244
245   // Support for STL-style iteration
246   const_iterator begin() const { return Descriptions.begin(); }
247   const_iterator end() const { return Descriptions.end(); }
248 };
249
250
251 // Tool-local option description.
252
253 // Properties without arguments are implemented as flags.
254 namespace ToolOptionDescriptionFlags {
255   enum ToolOptionDescriptionFlags { StopCompilation = 0x1,
256                                     Forward = 0x2, UnpackValues = 0x4};
257 }
258 namespace OptionPropertyType {
259   enum OptionPropertyType { AppendCmd, OutputSuffix };
260 }
261
262 typedef std::pair<OptionPropertyType::OptionPropertyType, std::string>
263 OptionProperty;
264 typedef SmallVector<OptionProperty, 4> OptionPropertyList;
265
266 struct ToolOptionDescription : public OptionDescription {
267   unsigned Flags;
268   OptionPropertyList Props;
269
270   // StringMap can only store DefaultConstructible objects
271   ToolOptionDescription() : OptionDescription(), Flags(0) {}
272
273   ToolOptionDescription (OptionType::OptionType t, const std::string& n)
274     : OptionDescription(t, n)
275   {}
276
277   // Various boolean properties
278   bool isStopCompilation() const {
279     return Flags & ToolOptionDescriptionFlags::StopCompilation;
280   }
281   void setStopCompilation() {
282     Flags |= ToolOptionDescriptionFlags::StopCompilation;
283   }
284
285   bool isForward() const {
286     return Flags & ToolOptionDescriptionFlags::Forward;
287   }
288   void setForward() {
289     Flags |= ToolOptionDescriptionFlags::Forward;
290   }
291
292   bool isUnpackValues() const {
293     return Flags & ToolOptionDescriptionFlags::UnpackValues;
294   }
295   void setUnpackValues() {
296     Flags |= ToolOptionDescriptionFlags::UnpackValues;
297   }
298
299   void AddProperty (OptionPropertyType::OptionPropertyType t,
300                     const std::string& val)
301   {
302     Props.push_back(std::make_pair(t, val));
303   }
304 };
305
306 typedef StringMap<ToolOptionDescription> ToolOptionDescriptions;
307
308 // Tool information record
309
310 namespace ToolFlags {
311   enum ToolFlags { Join = 0x1, Sink = 0x2 };
312 }
313
314 struct ToolProperties : public RefCountedBase<ToolProperties> {
315   std::string Name;
316   Init* CmdLine;
317   StrVector InLanguage;
318   std::string OutLanguage;
319   std::string OutputSuffix;
320   unsigned Flags;
321   ToolOptionDescriptions OptDescs;
322
323   // Various boolean properties
324   void setSink()      { Flags |= ToolFlags::Sink; }
325   bool isSink() const { return Flags & ToolFlags::Sink; }
326   void setJoin()      { Flags |= ToolFlags::Join; }
327   bool isJoin() const { return Flags & ToolFlags::Join; }
328
329   // Default ctor here is needed because StringMap can only store
330   // DefaultConstructible objects
331   ToolProperties() : Flags(0) {}
332   ToolProperties (const std::string& n) : Name(n), Flags(0) {}
333 };
334
335
336 /// ToolPropertiesList - A list of Tool information records
337 /// IntrusiveRefCntPtrs are used here because StringMap has no copy
338 /// constructor (and we want to avoid copying ToolProperties anyway).
339 typedef std::vector<IntrusiveRefCntPtr<ToolProperties> > ToolPropertiesList;
340
341
342 /// CollectProperties - Function object for iterating over a list of
343 /// tool property records.
344 class CollectProperties {
345 private:
346
347   /// Implementation details
348
349   /// PropertyHandler - a function that extracts information
350   /// about a given tool property from its DAG representation
351   typedef void (CollectProperties::*PropertyHandler)(const DagInit*);
352
353   /// PropertyHandlerMap - A map from property names to property
354   /// handlers.
355   typedef StringMap<PropertyHandler> PropertyHandlerMap;
356
357   /// OptionPropertyHandler - a function that extracts information
358   /// about a given option property from its DAG representation.
359   typedef void (CollectProperties::* OptionPropertyHandler)
360   (const DagInit*, GlobalOptionDescription &);
361
362   /// OptionPropertyHandlerMap - A map from option property names to
363   /// option property handlers
364   typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
365
366   // Static maps from strings to CollectProperties methods("handlers")
367   static PropertyHandlerMap propertyHandlers_;
368   static OptionPropertyHandlerMap optionPropertyHandlers_;
369   static bool staticMembersInitialized_;
370
371
372   /// This is where the information is stored
373
374   /// toolProps_ -  Properties of the current Tool.
375   ToolProperties& toolProps_;
376   /// optDescs_ - OptionDescriptions table (used to register options
377   /// globally).
378   GlobalOptionDescriptions& optDescs_;
379
380 public:
381
382   explicit CollectProperties (ToolProperties& p, GlobalOptionDescriptions& d)
383     : toolProps_(p), optDescs_(d)
384   {
385     if (!staticMembersInitialized_) {
386       // Init tool property handlers
387       propertyHandlers_["cmd_line"] = &CollectProperties::onCmdLine;
388       propertyHandlers_["in_language"] = &CollectProperties::onInLanguage;
389       propertyHandlers_["join"] = &CollectProperties::onJoin;
390       propertyHandlers_["out_language"] = &CollectProperties::onOutLanguage;
391       propertyHandlers_["output_suffix"] = &CollectProperties::onOutputSuffix;
392       propertyHandlers_["parameter_option"]
393         = &CollectProperties::onParameter;
394       propertyHandlers_["parameter_list_option"] =
395         &CollectProperties::onParameterList;
396       propertyHandlers_["prefix_option"] = &CollectProperties::onPrefix;
397       propertyHandlers_["prefix_list_option"] =
398         &CollectProperties::onPrefixList;
399       propertyHandlers_["sink"] = &CollectProperties::onSink;
400       propertyHandlers_["switch_option"] = &CollectProperties::onSwitch;
401
402       // Init option property handlers
403       optionPropertyHandlers_["append_cmd"] = &CollectProperties::onAppendCmd;
404       optionPropertyHandlers_["forward"] = &CollectProperties::onForward;
405       optionPropertyHandlers_["help"] = &CollectProperties::onHelp;
406       optionPropertyHandlers_["output_suffix"] =
407         &CollectProperties::onOutputSuffixOptionProp;
408       optionPropertyHandlers_["required"] = &CollectProperties::onRequired;
409       optionPropertyHandlers_["stop_compilation"] =
410         &CollectProperties::onStopCompilation;
411       optionPropertyHandlers_["unpack_values"] =
412         &CollectProperties::onUnpackValues;
413
414       staticMembersInitialized_ = true;
415     }
416   }
417
418   /// operator() - Gets called for every tool property; Just forwards
419   /// to the corresponding property handler.
420   void operator() (Init* i) {
421     const DagInit& d = InitPtrToDag(i);
422     const std::string& property_name = d.getOperator()->getAsString();
423     PropertyHandlerMap::iterator method
424       = propertyHandlers_.find(property_name);
425
426     if (method != propertyHandlers_.end()) {
427       PropertyHandler h = method->second;
428       (this->*h)(&d);
429     }
430     else {
431       throw "Unknown tool property: " + property_name + "!";
432     }
433   }
434
435 private:
436
437   /// Property handlers --
438   /// Functions that extract information about tool properties from
439   /// DAG representation.
440
441   void onCmdLine (const DagInit* d) {
442     checkNumberOfArguments(d, 1);
443     toolProps_.CmdLine = d->getArg(0);
444   }
445
446   void onInLanguage (const DagInit* d) {
447     checkNumberOfArguments(d, 1);
448     Init* arg = d->getArg(0);
449
450     // Find out the argument's type.
451     if (typeid(*arg) == typeid(StringInit)) {
452       // It's a string.
453       toolProps_.InLanguage.push_back(InitPtrToString(arg));
454     }
455     else {
456       // It's a list.
457       const ListInit& lst = InitPtrToList(arg);
458       StrVector& out = toolProps_.InLanguage;
459
460       // Copy strings to the output vector.
461       for (ListInit::const_iterator B = lst.begin(), E = lst.end();
462            B != E; ++B) {
463         out.push_back(InitPtrToString(*B));
464       }
465
466       // Remove duplicates.
467       std::sort(out.begin(), out.end());
468       StrVector::iterator newE = std::unique(out.begin(), out.end());
469       out.erase(newE, out.end());
470     }
471   }
472
473   void onJoin (const DagInit* d) {
474     checkNumberOfArguments(d, 0);
475     toolProps_.setJoin();
476   }
477
478   void onOutLanguage (const DagInit* d) {
479     checkNumberOfArguments(d, 1);
480     toolProps_.OutLanguage = InitPtrToString(d->getArg(0));
481   }
482
483   void onOutputSuffix (const DagInit* d) {
484     checkNumberOfArguments(d, 1);
485     toolProps_.OutputSuffix = InitPtrToString(d->getArg(0));
486   }
487
488   void onSink (const DagInit* d) {
489     checkNumberOfArguments(d, 0);
490     optDescs_.HasSink = true;
491     toolProps_.setSink();
492   }
493
494   void onSwitch (const DagInit* d) {
495     addOption(d, OptionType::Switch);
496   }
497
498   void onParameter (const DagInit* d) {
499     addOption(d, OptionType::Parameter);
500   }
501
502   void onParameterList (const DagInit* d) {
503     addOption(d, OptionType::ParameterList);
504   }
505
506   void onPrefix (const DagInit* d) {
507     addOption(d, OptionType::Prefix);
508   }
509
510   void onPrefixList (const DagInit* d) {
511     addOption(d, OptionType::PrefixList);
512   }
513
514   /// Option property handlers --
515   /// Methods that handle properties that are common for all types of
516   /// options (like append_cmd, stop_compilation)
517
518   void onAppendCmd (const DagInit* d, GlobalOptionDescription& o) {
519     checkNumberOfArguments(d, 1);
520     const std::string& cmd = InitPtrToString(d->getArg(0));
521
522     toolProps_.OptDescs[o.Name].AddProperty(OptionPropertyType::AppendCmd, cmd);
523   }
524
525   void onOutputSuffixOptionProp (const DagInit* d, GlobalOptionDescription& o) {
526     checkNumberOfArguments(d, 1);
527     const std::string& suf = InitPtrToString(d->getArg(0));
528
529     if (toolProps_.OptDescs[o.Name].Type != OptionType::Switch)
530       throw "Option " + o.Name
531         + " can't have 'output_suffix' property since it isn't a switch!";
532
533     toolProps_.OptDescs[o.Name].AddProperty
534       (OptionPropertyType::OutputSuffix, suf);
535   }
536
537   void onForward (const DagInit* d, GlobalOptionDescription& o) {
538     checkNumberOfArguments(d, 0);
539     toolProps_.OptDescs[o.Name].setForward();
540   }
541
542   void onHelp (const DagInit* d, GlobalOptionDescription& o) {
543     checkNumberOfArguments(d, 1);
544     const std::string& help_message = InitPtrToString(d->getArg(0));
545
546     o.Help = help_message;
547   }
548
549   void onRequired (const DagInit* d, GlobalOptionDescription& o) {
550     checkNumberOfArguments(d, 0);
551     o.setRequired();
552   }
553
554   void onStopCompilation (const DagInit* d, GlobalOptionDescription& o) {
555     checkNumberOfArguments(d, 0);
556     if (o.Type != OptionType::Switch)
557       throw std::string("Only options of type Switch can stop compilation!");
558     toolProps_.OptDescs[o.Name].setStopCompilation();
559   }
560
561   void onUnpackValues (const DagInit* d, GlobalOptionDescription& o) {
562     checkNumberOfArguments(d, 0);
563     toolProps_.OptDescs[o.Name].setUnpackValues();
564   }
565
566   /// Helper functions
567
568   // Add an option of type t
569   void addOption (const DagInit* d, OptionType::OptionType t) {
570     checkNumberOfArguments(d, 2);
571     const std::string& name = InitPtrToString(d->getArg(0));
572
573     GlobalOptionDescription o(t, name);
574     toolProps_.OptDescs[name].Type = t;
575     toolProps_.OptDescs[name].Name = name;
576     processOptionProperties(d, o);
577     insertDescription(o);
578   }
579
580   // Insert new GlobalOptionDescription into GlobalOptionDescriptions list
581   void insertDescription (const GlobalOptionDescription& o)
582   {
583     if (optDescs_.Descriptions.count(o.Name)) {
584       GlobalOptionDescription& D = optDescs_.Descriptions[o.Name];
585       D.Merge(o);
586     }
587     else {
588       optDescs_.Descriptions[o.Name] = o;
589     }
590   }
591
592   /// processOptionProperties - Go through the list of option
593   /// properties and call a corresponding handler for each.
594   ///
595   /// Parameters:
596   /// name - option name
597   /// d - option property list
598   void processOptionProperties (const DagInit* d, GlobalOptionDescription& o) {
599     // First argument is option name
600     checkNumberOfArguments(d, 2);
601
602     for (unsigned B = 1, E = d->getNumArgs(); B!=E; ++B) {
603       const DagInit& option_property
604         = InitPtrToDag(d->getArg(B));
605       const std::string& option_property_name
606         = option_property.getOperator()->getAsString();
607       OptionPropertyHandlerMap::iterator method
608         = optionPropertyHandlers_.find(option_property_name);
609
610       if (method != optionPropertyHandlers_.end()) {
611         OptionPropertyHandler h = method->second;
612         (this->*h)(&option_property, o);
613       }
614       else {
615         throw "Unknown option property: " + option_property_name + "!";
616       }
617     }
618   }
619 };
620
621 // Static members of CollectProperties
622 CollectProperties::PropertyHandlerMap
623 CollectProperties::propertyHandlers_;
624
625 CollectProperties::OptionPropertyHandlerMap
626 CollectProperties::optionPropertyHandlers_;
627
628 bool CollectProperties::staticMembersInitialized_ = false;
629
630
631 /// CollectToolProperties - Gather information from the parsed
632 /// TableGen data (basically a wrapper for the CollectProperties
633 /// function object).
634 void CollectToolProperties (RecordVector::const_iterator B,
635                             RecordVector::const_iterator E,
636                             ToolPropertiesList& TPList,
637                             GlobalOptionDescriptions& OptDescs)
638 {
639   // Iterate over a properties list of every Tool definition
640   for (;B!=E;++B) {
641     RecordVector::value_type T = *B;
642     ListInit* PropList = T->getValueAsListInit("properties");
643
644     IntrusiveRefCntPtr<ToolProperties>
645       ToolProps(new ToolProperties(T->getName()));
646
647     std::for_each(PropList->begin(), PropList->end(),
648                   CollectProperties(*ToolProps, OptDescs));
649     TPList.push_back(ToolProps);
650   }
651 }
652
653 /// EmitCaseTest1Arg - Helper function used by
654 /// EmitCaseConstructHandler.
655 bool EmitCaseTest1Arg(const std::string& TestName,
656                       const DagInit& d,
657                       const GlobalOptionDescriptions& OptDescs,
658                       std::ostream& O) {
659   checkNumberOfArguments(&d, 1);
660   const std::string& OptName = InitPtrToString(d.getArg(0));
661   if (TestName == "switch_on") {
662     const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
663     if (OptDesc.Type != OptionType::Switch)
664       throw OptName + ": incorrect option type!";
665     O << OptDesc.GenVariableName();
666     return true;
667   } else if (TestName == "input_languages_contain") {
668     O << "InLangs.count(\"" << OptName << "\") != 0";
669     return true;
670   } else if (TestName == "in_language") {
671     // Works only for cmd_line!
672     O << "GetLanguage(inFile) == \"" << OptName << '\"';
673     return true;
674   } else if (TestName == "not_empty") {
675     const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
676     if (OptDesc.Type == OptionType::Switch)
677       throw OptName + ": incorrect option type!";
678     O << '!' << OptDesc.GenVariableName() << ".empty()";
679     return true;
680   }
681
682   return false;
683 }
684
685 /// EmitCaseTest2Args - Helper function used by
686 /// EmitCaseConstructHandler.
687 bool EmitCaseTest2Args(const std::string& TestName,
688                        const DagInit& d,
689                        const char* IndentLevel,
690                        const GlobalOptionDescriptions& OptDescs,
691                        std::ostream& O) {
692   checkNumberOfArguments(&d, 2);
693   const std::string& OptName = InitPtrToString(d.getArg(0));
694   const std::string& OptArg = InitPtrToString(d.getArg(1));
695   const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
696
697   if (TestName == "parameter_equals") {
698     if (OptDesc.Type != OptionType::Parameter
699         && OptDesc.Type != OptionType::Prefix)
700       throw OptName + ": incorrect option type!";
701     O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
702     return true;
703   }
704   else if (TestName == "element_in_list") {
705     if (OptDesc.Type != OptionType::ParameterList
706         && OptDesc.Type != OptionType::PrefixList)
707       throw OptName + ": incorrect option type!";
708     const std::string& VarName = OptDesc.GenVariableName();
709     O << "std::find(" << VarName << ".begin(),\n"
710       << IndentLevel << Indent1 << VarName << ".end(), \""
711       << OptArg << "\") != " << VarName << ".end()";
712     return true;
713   }
714
715   return false;
716 }
717
718 // Forward declaration.
719 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
720 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
721                   const GlobalOptionDescriptions& OptDescs,
722                   std::ostream& O);
723
724 /// EmitLogicalOperationTest - Helper function used by
725 /// EmitCaseConstructHandler.
726 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
727                               const char* IndentLevel,
728                               const GlobalOptionDescriptions& OptDescs,
729                               std::ostream& O) {
730   O << '(';
731   for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
732     const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
733     EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
734     if (j != NumArgs - 1)
735       O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
736     else
737       O << ')';
738   }
739 }
740
741 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
742 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
743                   const GlobalOptionDescriptions& OptDescs,
744                   std::ostream& O) {
745   const std::string& TestName = d.getOperator()->getAsString();
746
747   if (TestName == "and")
748     EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
749   else if (TestName == "or")
750     EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
751   else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
752     return;
753   else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
754     return;
755   else
756     throw TestName + ": unknown edge property!";
757 }
758
759 // Emit code that handles the 'case' construct.
760 // Takes a function object that should emit code for every case clause.
761 // Callback's type is
762 // void F(Init* Statement, const char* IndentLevel, std::ostream& O).
763 template <typename F>
764 void EmitCaseConstructHandler(const DagInit* d, const char* IndentLevel,
765                               const F& Callback, bool DefaultRequired,
766                               const GlobalOptionDescriptions& OptDescs,
767                               std::ostream& O) {
768   assert(d->getOperator()->getAsString() == "case");
769
770   bool DefaultProvided = false;
771   unsigned numArgs = d->getNumArgs();
772   if (d->getNumArgs() < 2)
773     throw "There should be at least one clause in the 'case' expression:\n"
774       + d->getAsString();
775
776   for (unsigned i = 0; i != numArgs; ++i) {
777     const DagInit& Test = InitPtrToDag(d->getArg(i));
778
779     // Emit the test.
780     if (Test.getOperator()->getAsString() == "default") {
781       DefaultProvided = true;
782       if (i+2 != numArgs)
783         throw std::string("The 'default' clause should be the last in the"
784                           "'case' construct!");
785       O << IndentLevel << "else {\n";
786     }
787     else {
788       O << IndentLevel << "if (";
789       EmitCaseTest(Test, IndentLevel, OptDescs, O);
790       O << ") {\n";
791     }
792
793     // Emit the corresponding statement.
794     ++i;
795     if (i == numArgs)
796       throw "Case construct handler: no corresponding action "
797         "found for the test " + Test.getAsString() + '!';
798
799     Callback(d->getArg(i), IndentLevel, O);
800     O << IndentLevel << "}\n";
801   }
802
803   if (DefaultRequired && !DefaultProvided)
804     throw "Case expression: the 'default' clause is required in this case:\n"
805       + d->getAsString();
806 }
807
808 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
809 /// implement EmitOptionPropertyHandlingCode(). Emits code for
810 /// handling the (forward) option property.
811 void EmitForwardOptionPropertyHandlingCode (const ToolOptionDescription& D,
812                                             std::ostream& O) {
813   switch (D.Type) {
814   case OptionType::Switch:
815     O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
816     break;
817   case OptionType::Parameter:
818     O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
819     O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
820     break;
821   case OptionType::Prefix:
822     O << Indent3 << "vec.push_back(\"-" << D.Name << "\" + "
823       << D.GenVariableName() << ");\n";
824     break;
825   case OptionType::PrefixList:
826     O << Indent3 << "for (" << D.GenTypeDeclaration()
827       << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
828       << Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
829       << Indent4 << "vec.push_back(\"-" << D.Name << "\" + "
830       << "*B);\n";
831     break;
832   case OptionType::ParameterList:
833     O << Indent3 << "for (" << D.GenTypeDeclaration()
834       << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
835       << Indent3 << "E = " << D.GenVariableName()
836       << ".end() ; B != E; ++B) {\n"
837       << Indent4 << "vec.push_back(\"-" << D.Name << "\");\n"
838       << Indent4 << "vec.push_back(*B);\n"
839       << Indent3 << "}\n";
840     break;
841   }
842 }
843
844 // ToolOptionHasInterestingProperties - A helper function used by
845 // EmitOptionPropertyHandlingCode() that tells us whether we should
846 // emit any property handling code at all.
847 bool ToolOptionHasInterestingProperties(const ToolOptionDescription& D) {
848   bool ret = false;
849   for (OptionPropertyList::const_iterator B = D.Props.begin(),
850          E = D.Props.end(); B != E; ++B) {
851       const OptionProperty& OptProp = *B;
852       if (OptProp.first == OptionPropertyType::AppendCmd)
853         ret = true;
854     }
855   if (D.isForward() || D.isUnpackValues())
856     ret = true;
857   return ret;
858 }
859
860 /// EmitOptionPropertyHandlingCode - Helper function used by
861 /// EmitGenerateActionMethod(). Emits code that handles option
862 /// properties.
863 void EmitOptionPropertyHandlingCode (const ToolOptionDescription& D,
864                                      std::ostream& O)
865 {
866   if (!ToolOptionHasInterestingProperties(D))
867     return;
868   // Start of the if-clause.
869   O << Indent2 << "if (";
870   if (D.Type == OptionType::Switch)
871     O << D.GenVariableName();
872   else
873     O << '!' << D.GenVariableName() << ".empty()";
874
875   O <<") {\n";
876
877   // Handle option properties that take an argument.
878   for (OptionPropertyList::const_iterator B = D.Props.begin(),
879         E = D.Props.end(); B!=E; ++B) {
880     const OptionProperty& val = *B;
881
882     switch (val.first) {
883       // (append_cmd cmd) property
884     case OptionPropertyType::AppendCmd:
885       O << Indent3 << "vec.push_back(\"" << val.second << "\");\n";
886       break;
887       // Other properties with argument
888     default:
889       break;
890     }
891   }
892
893   // Handle flags
894
895   // (forward) property
896   if (D.isForward())
897     EmitForwardOptionPropertyHandlingCode(D, O);
898
899   // (unpack_values) property
900   if (D.isUnpackValues()) {
901     if (IsListOptionType(D.Type)) {
902       O << Indent3 << "for (" << D.GenTypeDeclaration()
903         << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
904         << Indent3 << "E = " << D.GenVariableName()
905         << ".end(); B != E; ++B)\n"
906         << Indent4 << "llvm::SplitString(*B, vec, \",\");\n";
907     }
908     else if (D.Type == OptionType::Prefix || D.Type == OptionType::Parameter){
909       O << Indent3 << "llvm::SplitString("
910         << D.GenVariableName() << ", vec, \",\");\n";
911     }
912     else {
913       throw std::string("Switches can't have unpack_values property!");
914     }
915   }
916
917   // End of the if-clause.
918   O << Indent2 << "}\n";
919 }
920
921 /// SubstituteSpecialCommands - Perform string substitution for $CALL
922 /// and $ENV. Helper function used by EmitCmdLineVecFill().
923 std::string SubstituteSpecialCommands(const std::string& cmd) {
924   size_t cparen = cmd.find(")");
925   std::string ret;
926
927   if (cmd.find("$CALL(") == 0) {
928     if (cmd.size() == 6)
929       throw std::string("$CALL invocation: empty argument list!");
930
931     ret += "hooks::";
932     ret += std::string(cmd.begin() + 6, cmd.begin() + cparen);
933     ret += "()";
934   }
935   else if (cmd.find("$ENV(") == 0) {
936     if (cmd.size() == 5)
937       throw std::string("$ENV invocation: empty argument list!");
938
939     ret += "std::getenv(\"";
940     ret += std::string(cmd.begin() + 5, cmd.begin() + cparen);
941     ret += "\")";
942   }
943   else {
944     throw "Unknown special command: " + cmd;
945   }
946
947   if (cmd.begin() + cparen + 1 != cmd.end()) {
948     ret += " + std::string(\"";
949     ret += (cmd.c_str() + cparen + 1);
950     ret += "\")";
951   }
952
953   return ret;
954 }
955
956 /// EmitCmdLineVecFill - Emit code that fills in the command line
957 /// vector. Helper function used by EmitGenerateActionMethod().
958 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
959                         bool Version, const char* IndentLevel,
960                         std::ostream& O) {
961   StrVector StrVec;
962   SplitString(InitPtrToString(CmdLine), StrVec);
963   if (StrVec.empty())
964     throw "Tool " + ToolName + " has empty command line!";
965
966   StrVector::const_iterator I = StrVec.begin();
967   ++I;
968   for (StrVector::const_iterator E = StrVec.end(); I != E; ++I) {
969     const std::string& cmd = *I;
970     O << IndentLevel;
971     if (cmd.at(0) == '$') {
972       if (cmd == "$INFILE") {
973         if (Version)
974           O << "for (PathVector::const_iterator B = inFiles.begin()"
975             << ", E = inFiles.end();\n"
976             << IndentLevel << "B != E; ++B)\n"
977             << IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
978         else
979           O << "vec.push_back(inFile.toString());\n";
980       }
981       else if (cmd == "$OUTFILE") {
982         O << "vec.push_back(outFile.toString());\n";
983       }
984       else {
985         O << "vec.push_back(" << SubstituteSpecialCommands(cmd);
986         O << ");\n";
987       }
988     }
989     else {
990       O << "vec.push_back(\"" << cmd << "\");\n";
991     }
992   }
993   O << IndentLevel << "ret = Action("
994     << ((StrVec[0][0] == '$') ? SubstituteSpecialCommands(StrVec[0])
995         : "\"" + StrVec[0] + "\"")
996     << ", vec);\n";
997 }
998
999 /// EmitCmdLineVecFillCallback - A function object wrapper around
1000 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1001 /// argument to EmitCaseConstructHandler().
1002 class EmitCmdLineVecFillCallback {
1003   bool Version;
1004   const std::string& ToolName;
1005  public:
1006   EmitCmdLineVecFillCallback(bool Ver, const std::string& TN)
1007     : Version(Ver), ToolName(TN) {}
1008
1009   void operator()(const Init* Statement, const char* IndentLevel,
1010                   std::ostream& O) const
1011   {
1012     EmitCmdLineVecFill(Statement, ToolName, Version,
1013                        (std::string(IndentLevel) + Indent1).c_str(), O);
1014   }
1015 };
1016
1017 // EmitGenerateActionMethod - Emit one of two versions of the
1018 // Tool::GenerateAction() method.
1019 void EmitGenerateActionMethod (const ToolProperties& P,
1020                                const GlobalOptionDescriptions& OptDescs,
1021                                bool Version, std::ostream& O) {
1022   if (Version)
1023     O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
1024   else
1025     O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
1026
1027   O << Indent2 << "const sys::Path& outFile,\n"
1028     << Indent2 << "const InputLanguagesSet& InLangs) const\n"
1029     << Indent1 << "{\n"
1030     << Indent2 << "Action ret;\n"
1031     << Indent2 << "std::vector<std::string> vec;\n";
1032
1033   // cmd_line is either a string or a 'case' construct.
1034   if (typeid(*P.CmdLine) == typeid(StringInit))
1035     EmitCmdLineVecFill(P.CmdLine, P.Name, Version, Indent2, O);
1036   else
1037     EmitCaseConstructHandler(&InitPtrToDag(P.CmdLine), Indent2,
1038                              EmitCmdLineVecFillCallback(Version, P.Name),
1039                              false, OptDescs, O);
1040
1041   // For every understood option, emit handling code.
1042   for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1043         E = P.OptDescs.end(); B != E; ++B) {
1044     const ToolOptionDescription& val = B->second;
1045     EmitOptionPropertyHandlingCode(val, O);
1046   }
1047
1048   // Handle the Sink property.
1049   if (P.isSink()) {
1050     O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
1051       << Indent3 << "vec.insert(vec.end(), "
1052       << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
1053       << Indent2 << "}\n";
1054   }
1055
1056   O << Indent2 << "return ret;\n"
1057     << Indent1 << "}\n\n";
1058 }
1059
1060 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1061 /// a given Tool class.
1062 void EmitGenerateActionMethods (const ToolProperties& P,
1063                                 const GlobalOptionDescriptions& OptDescs,
1064                                 std::ostream& O) {
1065   if (!P.isJoin())
1066     O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
1067       << Indent2 << "const llvm::sys::Path& outFile,\n"
1068       << Indent2 << "const InputLanguagesSet& InLangs) const\n"
1069       << Indent1 << "{\n"
1070       << Indent2 << "throw std::runtime_error(\"" << P.Name
1071       << " is not a Join tool!\");\n"
1072       << Indent1 << "}\n\n";
1073   else
1074     EmitGenerateActionMethod(P, OptDescs, true, O);
1075
1076   EmitGenerateActionMethod(P, OptDescs, false, O);
1077 }
1078
1079 /// EmitIsLastMethod - Emit the IsLast() method for a given Tool
1080 /// class.
1081 void EmitIsLastMethod (const ToolProperties& P, std::ostream& O) {
1082   O << Indent1 << "bool IsLast() const {\n"
1083     << Indent2 << "bool last = false;\n";
1084
1085   for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1086         E = P.OptDescs.end(); B != E; ++B) {
1087     const ToolOptionDescription& val = B->second;
1088
1089     if (val.isStopCompilation())
1090       O << Indent2
1091         << "if (" << val.GenVariableName()
1092         << ")\n" << Indent3 << "last = true;\n";
1093   }
1094
1095   O << Indent2 << "return last;\n"
1096     << Indent1 <<  "}\n\n";
1097 }
1098
1099 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1100 /// methods for a given Tool class.
1101 void EmitInOutLanguageMethods (const ToolProperties& P, std::ostream& O) {
1102   O << Indent1 << "StrVector InputLanguages() const {\n"
1103     << Indent2 << "StrVector ret;\n";
1104
1105   for (StrVector::const_iterator B = P.InLanguage.begin(),
1106          E = P.InLanguage.end(); B != E; ++B) {
1107     O << Indent2 << "ret.push_back(\"" << *B << "\");\n";
1108   }
1109
1110   O << Indent2 << "return ret;\n"
1111     << Indent1 << "}\n\n";
1112
1113   O << Indent1 << "const char* OutputLanguage() const {\n"
1114     << Indent2 << "return \"" << P.OutLanguage << "\";\n"
1115     << Indent1 << "}\n\n";
1116 }
1117
1118 /// EmitOutputSuffixMethod - Emit the OutputSuffix() method for a
1119 /// given Tool class.
1120 void EmitOutputSuffixMethod (const ToolProperties& P, std::ostream& O) {
1121   O << Indent1 << "const char* OutputSuffix() const {\n"
1122     << Indent2 << "const char* ret = \"" << P.OutputSuffix << "\";\n";
1123
1124   for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1125          E = P.OptDescs.end(); B != E; ++B) {
1126     const ToolOptionDescription& OptDesc = B->second;
1127     for (OptionPropertyList::const_iterator B = OptDesc.Props.begin(),
1128            E = OptDesc.Props.end(); B != E; ++B) {
1129       const OptionProperty& OptProp = *B;
1130       if (OptProp.first == OptionPropertyType::OutputSuffix) {
1131         O << Indent2 << "if (" << OptDesc.GenVariableName() << ")\n"
1132           << Indent3 << "ret = \"" << OptProp.second << "\";\n";
1133       }
1134     }
1135   }
1136
1137   O << Indent2 << "return ret;\n"
1138     << Indent1 << "}\n\n";
1139 }
1140
1141 /// EmitNameMethod - Emit the Name() method for a given Tool class.
1142 void EmitNameMethod (const ToolProperties& P, std::ostream& O) {
1143   O << Indent1 << "const char* Name() const {\n"
1144     << Indent2 << "return \"" << P.Name << "\";\n"
1145     << Indent1 << "}\n\n";
1146 }
1147
1148 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1149 /// class.
1150 void EmitIsJoinMethod (const ToolProperties& P, std::ostream& O) {
1151   O << Indent1 << "bool IsJoin() const {\n";
1152   if (P.isJoin())
1153     O << Indent2 << "return true;\n";
1154   else
1155     O << Indent2 << "return false;\n";
1156   O << Indent1 << "}\n\n";
1157 }
1158
1159 /// EmitToolClassDefinition - Emit a Tool class definition.
1160 void EmitToolClassDefinition (const ToolProperties& P,
1161                               const GlobalOptionDescriptions& OptDescs,
1162                               std::ostream& O) {
1163   if (P.Name == "root")
1164     return;
1165
1166   // Header
1167   O << "class " << P.Name << " : public ";
1168   if (P.isJoin())
1169     O << "JoinTool";
1170   else
1171     O << "Tool";
1172   O << " {\npublic:\n";
1173
1174   EmitNameMethod(P, O);
1175   EmitInOutLanguageMethods(P, O);
1176   EmitOutputSuffixMethod(P, O);
1177   EmitIsJoinMethod(P, O);
1178   EmitGenerateActionMethods(P, OptDescs, O);
1179   EmitIsLastMethod(P, O);
1180
1181   // Close class definition
1182   O << "};\n\n";
1183 }
1184
1185 /// EmitOptionDescriptions - Iterate over a list of option
1186 /// descriptions and emit registration code.
1187 void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
1188                              std::ostream& O)
1189 {
1190   // Emit static cl::Option variables
1191   for (GlobalOptionDescriptions::const_iterator B = descs.begin(),
1192          E = descs.end(); B!=E; ++B) {
1193     const GlobalOptionDescription& val = B->second;
1194
1195     O << val.GenTypeDeclaration() << ' '
1196       << val.GenVariableName()
1197       << "(\"" << val.Name << '\"';
1198
1199     if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1200       O << ", cl::Prefix";
1201
1202     if (val.isRequired()) {
1203       switch (val.Type) {
1204       case OptionType::PrefixList:
1205       case OptionType::ParameterList:
1206         O << ", cl::OneOrMore";
1207         break;
1208       default:
1209         O << ", cl::Required";
1210       }
1211     }
1212
1213     O << ", cl::desc(\"" << val.Help << "\"));\n";
1214   }
1215
1216   if (descs.HasSink)
1217     O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
1218
1219   O << '\n';
1220 }
1221
1222 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
1223 void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
1224 {
1225   // Get the relevant field out of RecordKeeper
1226   Record* LangMapRecord = Records.getDef("LanguageMap");
1227   if (!LangMapRecord)
1228     throw std::string("Language map definition not found!");
1229
1230   ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
1231   if (!LangsToSuffixesList)
1232     throw std::string("Error in the language map definition!");
1233
1234   // Generate code
1235   O << "void llvmc::PopulateLanguageMap() {\n";
1236
1237   for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
1238     Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
1239
1240     const std::string& Lang = LangToSuffixes->getValueAsString("lang");
1241     const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
1242
1243     for (unsigned i = 0; i < Suffixes->size(); ++i)
1244       O << Indent1 << "GlobalLanguageMap[\""
1245         << InitPtrToString(Suffixes->getElement(i))
1246         << "\"] = \"" << Lang << "\";\n";
1247   }
1248
1249   O << "}\n\n";
1250 }
1251
1252 /// FillInToolToLang - Fills in two tables that map tool names to
1253 /// (input, output) languages.  Used by the typechecker.
1254 void FillInToolToLang (const ToolPropertiesList& TPList,
1255                        StringMap<StringSet<> >& ToolToInLang,
1256                        StringMap<std::string>& ToolToOutLang) {
1257   for (ToolPropertiesList::const_iterator B = TPList.begin(), E = TPList.end();
1258        B != E; ++B) {
1259     const ToolProperties& P = *(*B);
1260     for (StrVector::const_iterator B = P.InLanguage.begin(),
1261            E = P.InLanguage.end(); B != E; ++B)
1262       ToolToInLang[P.Name].insert(*B);
1263     ToolToOutLang[P.Name] = P.OutLanguage;
1264   }
1265 }
1266
1267 /// TypecheckGraph - Check that names for output and input languages
1268 /// on all edges do match.
1269 // TOFIX: It would be nice if this function also checked for cycles
1270 // and multiple default edges in the graph (better error
1271 // reporting). Unfortunately, it is awkward to do right now because
1272 // our intermediate representation is not sufficiently
1273 // sofisticated. Algorithms like these should be run on a real graph
1274 // instead of AST.
1275 void TypecheckGraph (Record* CompilationGraph,
1276                      const ToolPropertiesList& TPList) {
1277   StringMap<StringSet<> > ToolToInLang;
1278   StringMap<std::string> ToolToOutLang;
1279
1280   FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
1281   ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1282   StringMap<std::string>::iterator IAE = ToolToOutLang.end();
1283   StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
1284
1285   for (unsigned i = 0; i < edges->size(); ++i) {
1286     Record* Edge = edges->getElementAsRecord(i);
1287     Record* A = Edge->getValueAsDef("a");
1288     Record* B = Edge->getValueAsDef("b");
1289     StringMap<std::string>::iterator IA = ToolToOutLang.find(A->getName());
1290     StringMap<StringSet<> >::iterator IB = ToolToInLang.find(B->getName());
1291     if (IA == IAE)
1292       throw A->getName() + ": no such tool!";
1293     if (IB == IBE)
1294       throw B->getName() + ": no such tool!";
1295     if (A->getName() != "root" && IB->second.count(IA->second) == 0)
1296       throw "Edge " + A->getName() + "->" + B->getName()
1297         + ": output->input language mismatch";
1298     if (B->getName() == "root")
1299       throw std::string("Edges back to the root are not allowed!");
1300   }
1301 }
1302
1303 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
1304 /// by EmitEdgeClass().
1305 void IncDecWeight (const Init* i, const char* IndentLevel,
1306                    std::ostream& O) {
1307   const DagInit& d = InitPtrToDag(i);
1308   const std::string& OpName = d.getOperator()->getAsString();
1309
1310   if (OpName == "inc_weight")
1311     O << IndentLevel << Indent1 << "ret += ";
1312   else if (OpName == "dec_weight")
1313     O << IndentLevel << Indent1 << "ret -= ";
1314   else
1315     throw "Unknown operator in edge properties list: " + OpName + '!';
1316
1317   if (d.getNumArgs() > 0)
1318     O << InitPtrToInt(d.getArg(0)) << ";\n";
1319   else
1320     O << "2;\n";
1321
1322 }
1323
1324 /// EmitEdgeClass - Emit a single Edge# class.
1325 void EmitEdgeClass (unsigned N, const std::string& Target,
1326                     DagInit* Case, const GlobalOptionDescriptions& OptDescs,
1327                     std::ostream& O) {
1328
1329   // Class constructor.
1330   O << "class Edge" << N << ": public Edge {\n"
1331     << "public:\n"
1332     << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1333     << "\") {}\n\n"
1334
1335   // Function Weight().
1336     << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
1337     << Indent2 << "unsigned ret = 0;\n";
1338
1339   // Handle the 'case' construct.
1340   EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
1341
1342   O << Indent2 << "return ret;\n"
1343     << Indent1 << "};\n\n};\n\n";
1344 }
1345
1346 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
1347 void EmitEdgeClasses (Record* CompilationGraph,
1348                       const GlobalOptionDescriptions& OptDescs,
1349                       std::ostream& O) {
1350   ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1351
1352   for (unsigned i = 0; i < edges->size(); ++i) {
1353     Record* Edge = edges->getElementAsRecord(i);
1354     Record* B = Edge->getValueAsDef("b");
1355     DagInit* Weight = Edge->getValueAsDag("weight");
1356
1357     if (isDagEmpty(Weight))
1358       continue;
1359
1360     EmitEdgeClass(i, B->getName(), Weight, OptDescs, O);
1361   }
1362 }
1363
1364 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1365 /// function.
1366 void EmitPopulateCompilationGraph (Record* CompilationGraph,
1367                                    std::ostream& O)
1368 {
1369   ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1370
1371   // Generate code
1372   O << "void llvmc::PopulateCompilationGraph(CompilationGraph& G) {\n"
1373     << Indent1 << "PopulateLanguageMap();\n\n";
1374
1375   // Insert vertices
1376
1377   RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1378   if (Tools.empty())
1379     throw std::string("No tool definitions found!");
1380
1381   for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
1382     const std::string& Name = (*B)->getName();
1383     if (Name != "root")
1384       O << Indent1 << "G.insertNode(new "
1385         << Name << "());\n";
1386   }
1387
1388   O << '\n';
1389
1390   // Insert edges
1391   for (unsigned i = 0; i < edges->size(); ++i) {
1392     Record* Edge = edges->getElementAsRecord(i);
1393     Record* A = Edge->getValueAsDef("a");
1394     Record* B = Edge->getValueAsDef("b");
1395     DagInit* Weight = Edge->getValueAsDag("weight");
1396
1397     O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
1398
1399     if (isDagEmpty(Weight))
1400       O << "new SimpleEdge(\"" << B->getName() << "\")";
1401     else
1402       O << "new Edge" << i << "()";
1403
1404     O << ");\n";
1405   }
1406
1407   O << "}\n\n";
1408 }
1409
1410 /// ExtractHookNames - Extract the hook names from all instances of
1411 /// $CALL(HookName) in the provided command line string. Helper
1412 /// function used by FillInHookNames().
1413 void ExtractHookNames(const Init* CmdLine, StrVector& HookNames) {
1414   StrVector cmds;
1415   llvm::SplitString(InitPtrToString(CmdLine), cmds);
1416   for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
1417        B != E; ++B) {
1418     const std::string& cmd = *B;
1419     if (cmd.find("$CALL(") == 0) {
1420       if (cmd.size() == 6)
1421         throw std::string("$CALL invocation: empty argument list!");
1422       HookNames.push_back(std::string(cmd.begin() + 6,
1423                                       cmd.begin() + cmd.find(")")));
1424     }
1425   }
1426 }
1427
1428 /// FillInHookNames - Actually extract the hook names from all command
1429 /// line strings. Helper function used by EmitHookDeclarations().
1430 void FillInHookNames(const ToolPropertiesList& TPList,
1431                      StrVector& HookNames) {
1432   for (ToolPropertiesList::const_iterator B = TPList.begin(),
1433          E = TPList.end(); B != E; ++B) {
1434     const ToolProperties& P = *(*B);
1435     if (!P.CmdLine)
1436       continue;
1437     if (typeid(*P.CmdLine) == typeid(StringInit)) {
1438       // This is a string.
1439       ExtractHookNames(P.CmdLine, HookNames);
1440     }
1441     else {
1442       // This is a 'case' construct.
1443       const DagInit& d = InitPtrToDag(P.CmdLine);
1444       bool even = false;
1445       for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1446            B != E; ++B) {
1447         if (even)
1448           ExtractHookNames(*B, HookNames);
1449         even = !even;
1450       }
1451     }
1452   }
1453 }
1454
1455 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
1456 /// property records and emit hook function declaration for each
1457 /// instance of $CALL(HookName).
1458 void EmitHookDeclarations(const ToolPropertiesList& ToolProps,
1459                           std::ostream& O) {
1460   StrVector HookNames;
1461   FillInHookNames(ToolProps, HookNames);
1462   if (HookNames.empty())
1463     return;
1464   std::sort(HookNames.begin(), HookNames.end());
1465   StrVector::const_iterator E = std::unique(HookNames.begin(), HookNames.end());
1466
1467   O << "namespace hooks {\n";
1468   for (StrVector::const_iterator B = HookNames.begin(); B != E; ++B)
1469     O << Indent1 << "std::string " << *B << "();\n";
1470
1471   O << "}\n\n";
1472 }
1473
1474 // End of anonymous namespace
1475 }
1476
1477 /// run - The back-end entry point.
1478 void LLVMCConfigurationEmitter::run (std::ostream &O) {
1479
1480   // Emit file header.
1481   EmitSourceFileHeader("LLVMC Configuration Library", O);
1482
1483   // Get a list of all defined Tools.
1484   RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1485   if (Tools.empty())
1486     throw std::string("No tool definitions found!");
1487
1488   // Gather information from the Tool description dags.
1489   ToolPropertiesList tool_props;
1490   GlobalOptionDescriptions opt_descs;
1491   CollectToolProperties(Tools.begin(), Tools.end(), tool_props, opt_descs);
1492
1493   // Emit global option registration code.
1494   EmitOptionDescriptions(opt_descs, O);
1495
1496   // Emit hook declarations.
1497   EmitHookDeclarations(tool_props, O);
1498
1499   // Emit PopulateLanguageMap() function
1500   // (a language map maps from file extensions to language names).
1501   EmitPopulateLanguageMap(Records, O);
1502
1503   // Emit Tool classes.
1504   for (ToolPropertiesList::const_iterator B = tool_props.begin(),
1505          E = tool_props.end(); B!=E; ++B)
1506     EmitToolClassDefinition(*(*B), opt_descs, O);
1507
1508   Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
1509   if (!CompilationGraphRecord)
1510     throw std::string("Compilation graph description not found!");
1511
1512   // Typecheck the compilation graph.
1513   TypecheckGraph(CompilationGraphRecord, tool_props);
1514
1515   // Emit Edge# classes.
1516   EmitEdgeClasses(CompilationGraphRecord, opt_descs, O);
1517
1518   // Emit PopulateCompilationGraph() function.
1519   EmitPopulateCompilationGraph(CompilationGraphRecord, O);
1520
1521   // EOF
1522 }