Change the hook API back to prevent memory leaks.
[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 <stdexcept>
28 #include <string>
29 #include <typeinfo>
30
31 using namespace llvm;
32
33 namespace {
34
35 //===----------------------------------------------------------------------===//
36 /// Typedefs
37
38 typedef std::vector<Record*> RecordVector;
39 typedef std::vector<std::string> StrVector;
40
41 //===----------------------------------------------------------------------===//
42 /// Constants
43
44 // Indentation strings.
45 const char * Indent1 = "    ";
46 const char * Indent2 = "        ";
47 const char * Indent3 = "            ";
48
49 // Default help string.
50 const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
51
52 // Name for the "sink" option.
53 const char * SinkOptionName = "AutoGeneratedSinkOption";
54
55 //===----------------------------------------------------------------------===//
56 /// Helper functions
57
58 /// Id - An 'identity' function object.
59 struct Id {
60   template<typename T>
61   void operator()(const T&) const {
62   }
63 };
64
65 int InitPtrToInt(const Init* ptr) {
66   const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
67   return val.getValue();
68 }
69
70 const std::string& InitPtrToString(const Init* ptr) {
71   const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
72   return val.getValue();
73 }
74
75 const ListInit& InitPtrToList(const Init* ptr) {
76   const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
77   return val;
78 }
79
80 const DagInit& InitPtrToDag(const Init* ptr) {
81   const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
82   return val;
83 }
84
85 // checkNumberOfArguments - Ensure that the number of args in d is
86 // less than or equal to min_arguments, otherwise throw an exception.
87 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
88   if (!d || d->getNumArgs() < min_arguments)
89     throw "Property " + d->getOperator()->getAsString()
90       + " has too few arguments!";
91 }
92
93 // isDagEmpty - is this DAG marked with an empty marker?
94 bool isDagEmpty (const DagInit* d) {
95   return d->getOperator()->getAsString() == "empty";
96 }
97
98 // EscapeVariableName - Escape commas and other symbols not allowed
99 // in the C++ variable names. Makes it possible to use options named
100 // like "Wa," (useful for prefix options).
101 std::string EscapeVariableName(const std::string& Var) {
102   std::string ret;
103   for (unsigned i = 0; i != Var.size(); ++i) {
104     char cur_char = Var[i];
105     if (cur_char == ',') {
106       ret += "_comma_";
107     }
108     else if (cur_char == '+') {
109       ret += "_plus_";
110     }
111     else if (cur_char == '-') {
112       ret += "_dash_";
113     }
114     else {
115       ret.push_back(cur_char);
116     }
117   }
118   return ret;
119 }
120
121 /// oneOf - Does the input string contain this character?
122 bool oneOf(const char* lst, char c) {
123   while (*lst) {
124     if (*lst++ == c)
125       return true;
126   }
127   return false;
128 }
129
130 //===----------------------------------------------------------------------===//
131 /// Back-end specific code
132
133
134 /// OptionType - One of six different option types. See the
135 /// documentation for detailed description of differences.
136 /// Extern* options are those that are defined in some other plugin.
137 namespace OptionType {
138   enum OptionType { Alias, Switch, Parameter, ParameterList,
139                     Prefix, PrefixList};
140
141 bool IsList (OptionType t) {
142   return (t == ParameterList || t == PrefixList);
143 }
144
145 bool IsSwitch (OptionType t) {
146   return (t == Switch);
147 }
148
149 bool IsParameter (OptionType t) {
150   return (t == Parameter || t == Prefix);
151 }
152
153 }
154
155 OptionType::OptionType stringToOptionType(const std::string& T) {
156   if (T == "alias_option")
157     return OptionType::Alias;
158   else if (T == "switch_option")
159     return OptionType::Switch;
160   else if (T == "parameter_option")
161     return OptionType::Parameter;
162   else if (T == "parameter_list_option")
163     return OptionType::ParameterList;
164   else if (T == "prefix_option")
165     return OptionType::Prefix;
166   else if (T == "prefix_list_option")
167     return OptionType::PrefixList;
168   else
169     throw "Unknown option type: " + T + '!';
170 }
171
172 namespace OptionDescriptionFlags {
173   enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
174                                 ReallyHidden = 0x4, Extern = 0x8 };
175 }
176
177 /// OptionDescription - Represents data contained in a single
178 /// OptionList entry.
179 struct OptionDescription {
180   OptionType::OptionType Type;
181   std::string Name;
182   unsigned Flags;
183   std::string Help;
184
185   OptionDescription(OptionType::OptionType t = OptionType::Switch,
186                     const std::string& n = "",
187                     const std::string& h = DefaultHelpString)
188     : Type(t), Name(n), Flags(0x0), Help(h)
189   {}
190
191   /// GenTypeDeclaration - Returns the C++ variable type of this
192   /// option.
193   const char* GenTypeDeclaration() const;
194
195   /// GenVariableName - Returns the variable name used in the
196   /// generated C++ code.
197   std::string GenVariableName() const;
198
199   /// Merge - Merge two option descriptions.
200   void Merge (const OptionDescription& other);
201
202   // Misc convenient getters/setters.
203
204   bool isAlias() const;
205
206   bool isExtern() const;
207   void setExtern();
208
209   bool isRequired() const;
210   void setRequired();
211
212   bool isHidden() const;
213   void setHidden();
214
215   bool isReallyHidden() const;
216   void setReallyHidden();
217 };
218
219 void OptionDescription::Merge (const OptionDescription& other)
220 {
221   if (other.Type != Type)
222     throw "Conflicting definitions for the option " + Name + "!";
223
224   if (Help == other.Help || Help == DefaultHelpString)
225     Help = other.Help;
226   else if (other.Help != DefaultHelpString) {
227     llvm::cerr << "Warning: several different help strings"
228       " defined for option " + Name + "\n";
229   }
230
231   Flags |= other.Flags;
232 }
233
234 bool OptionDescription::isAlias() const {
235   return Type == OptionType::Alias;
236 }
237
238 bool OptionDescription::isExtern() const {
239   return Flags & OptionDescriptionFlags::Extern;
240 }
241 void OptionDescription::setExtern() {
242   Flags |= OptionDescriptionFlags::Extern;
243 }
244
245 bool OptionDescription::isRequired() const {
246   return Flags & OptionDescriptionFlags::Required;
247 }
248 void OptionDescription::setRequired() {
249   Flags |= OptionDescriptionFlags::Required;
250 }
251
252 bool OptionDescription::isHidden() const {
253   return Flags & OptionDescriptionFlags::Hidden;
254 }
255 void OptionDescription::setHidden() {
256   Flags |= OptionDescriptionFlags::Hidden;
257 }
258
259 bool OptionDescription::isReallyHidden() const {
260   return Flags & OptionDescriptionFlags::ReallyHidden;
261 }
262 void OptionDescription::setReallyHidden() {
263   Flags |= OptionDescriptionFlags::ReallyHidden;
264 }
265
266 const char* OptionDescription::GenTypeDeclaration() const {
267   switch (Type) {
268   case OptionType::Alias:
269     return "cl::alias";
270   case OptionType::PrefixList:
271   case OptionType::ParameterList:
272     return "cl::list<std::string>";
273   case OptionType::Switch:
274     return "cl::opt<bool>";
275   case OptionType::Parameter:
276   case OptionType::Prefix:
277   default:
278     return "cl::opt<std::string>";
279   }
280 }
281
282 std::string OptionDescription::GenVariableName() const {
283   const std::string& EscapedName = EscapeVariableName(Name);
284   switch (Type) {
285   case OptionType::Alias:
286     return "AutoGeneratedAlias_" + EscapedName;
287   case OptionType::PrefixList:
288   case OptionType::ParameterList:
289     return "AutoGeneratedList_" + EscapedName;
290   case OptionType::Switch:
291     return "AutoGeneratedSwitch_" + EscapedName;
292   case OptionType::Prefix:
293   case OptionType::Parameter:
294   default:
295     return "AutoGeneratedParameter_" + EscapedName;
296   }
297 }
298
299 /// OptionDescriptions - An OptionDescription array plus some helper
300 /// functions.
301 class OptionDescriptions {
302   typedef StringMap<OptionDescription> container_type;
303
304   /// Descriptions - A list of OptionDescriptions.
305   container_type Descriptions;
306
307 public:
308   /// FindOption - exception-throwing wrapper for find().
309   const OptionDescription& FindOption(const std::string& OptName) const;
310
311   /// insertDescription - Insert new OptionDescription into
312   /// OptionDescriptions list
313   void InsertDescription (const OptionDescription& o);
314
315   // Support for STL-style iteration
316   typedef container_type::const_iterator const_iterator;
317   const_iterator begin() const { return Descriptions.begin(); }
318   const_iterator end() const { return Descriptions.end(); }
319 };
320
321 const OptionDescription&
322 OptionDescriptions::FindOption(const std::string& OptName) const
323 {
324   const_iterator I = Descriptions.find(OptName);
325   if (I != Descriptions.end())
326     return I->second;
327   else
328     throw OptName + ": no such option!";
329 }
330
331 void OptionDescriptions::InsertDescription (const OptionDescription& o)
332 {
333   container_type::iterator I = Descriptions.find(o.Name);
334   if (I != Descriptions.end()) {
335     OptionDescription& D = I->second;
336     D.Merge(o);
337   }
338   else {
339     Descriptions[o.Name] = o;
340   }
341 }
342
343 /// HandlerTable - A base class for function objects implemented as
344 /// 'tables of handlers'.
345 template <class T>
346 class HandlerTable {
347 protected:
348   // Implementation details.
349
350   /// Handler -
351   typedef void (T::* Handler) (const DagInit*);
352   /// HandlerMap - A map from property names to property handlers
353   typedef StringMap<Handler> HandlerMap;
354
355   static HandlerMap Handlers_;
356   static bool staticMembersInitialized_;
357
358   T* childPtr;
359 public:
360
361   HandlerTable(T* cp) : childPtr(cp)
362   {}
363
364   /// operator() - Just forwards to the corresponding property
365   /// handler.
366   void operator() (Init* i) {
367     const DagInit& property = InitPtrToDag(i);
368     const std::string& property_name = property.getOperator()->getAsString();
369     typename HandlerMap::iterator method = Handlers_.find(property_name);
370
371     if (method != Handlers_.end()) {
372       Handler h = method->second;
373       (childPtr->*h)(&property);
374     }
375     else {
376       throw "No handler found for property " + property_name + "!";
377     }
378   }
379
380   void AddHandler(const char* Property, Handler Handl) {
381     Handlers_[Property] = Handl;
382   }
383 };
384
385 template <class T> typename HandlerTable<T>::HandlerMap
386 HandlerTable<T>::Handlers_;
387 template <class T> bool HandlerTable<T>::staticMembersInitialized_ = false;
388
389
390 /// CollectOptionProperties - Function object for iterating over an
391 /// option property list.
392 class CollectOptionProperties : public HandlerTable<CollectOptionProperties> {
393 private:
394
395   /// optDescs_ - OptionDescriptions table. This is where the
396   /// information is stored.
397   OptionDescription& optDesc_;
398
399 public:
400
401   explicit CollectOptionProperties(OptionDescription& OD)
402     : HandlerTable<CollectOptionProperties>(this), optDesc_(OD)
403   {
404     if (!staticMembersInitialized_) {
405       AddHandler("extern", &CollectOptionProperties::onExtern);
406       AddHandler("help", &CollectOptionProperties::onHelp);
407       AddHandler("hidden", &CollectOptionProperties::onHidden);
408       AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
409       AddHandler("required", &CollectOptionProperties::onRequired);
410
411       staticMembersInitialized_ = true;
412     }
413   }
414
415 private:
416
417   /// Option property handlers --
418   /// Methods that handle option properties such as (help) or (hidden).
419
420   void onExtern (const DagInit* d) {
421     checkNumberOfArguments(d, 0);
422     optDesc_.setExtern();
423   }
424
425   void onHelp (const DagInit* d) {
426     checkNumberOfArguments(d, 1);
427     optDesc_.Help = InitPtrToString(d->getArg(0));
428   }
429
430   void onHidden (const DagInit* d) {
431     checkNumberOfArguments(d, 0);
432     optDesc_.setHidden();
433   }
434
435   void onReallyHidden (const DagInit* d) {
436     checkNumberOfArguments(d, 0);
437     optDesc_.setReallyHidden();
438   }
439
440   void onRequired (const DagInit* d) {
441     checkNumberOfArguments(d, 0);
442     optDesc_.setRequired();
443   }
444
445 };
446
447 /// AddOption - A function object that is applied to every option
448 /// description. Used by CollectOptionDescriptions.
449 class AddOption {
450 private:
451   OptionDescriptions& OptDescs_;
452
453 public:
454   explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
455   {}
456
457   void operator()(const Init* i) {
458     const DagInit& d = InitPtrToDag(i);
459     checkNumberOfArguments(&d, 1);
460
461     const OptionType::OptionType Type =
462       stringToOptionType(d.getOperator()->getAsString());
463     const std::string& Name = InitPtrToString(d.getArg(0));
464
465     OptionDescription OD(Type, Name);
466
467     if (!OD.isExtern())
468       checkNumberOfArguments(&d, 2);
469
470     if (OD.isAlias()) {
471       // Aliases store the aliased option name in the 'Help' field.
472       OD.Help = InitPtrToString(d.getArg(1));
473     }
474     else if (!OD.isExtern()) {
475       processOptionProperties(&d, OD);
476     }
477     OptDescs_.InsertDescription(OD);
478   }
479
480 private:
481   /// processOptionProperties - Go through the list of option
482   /// properties and call a corresponding handler for each.
483   static void processOptionProperties (const DagInit* d, OptionDescription& o) {
484     checkNumberOfArguments(d, 2);
485     DagInit::const_arg_iterator B = d->arg_begin();
486     // Skip the first argument: it's always the option name.
487     ++B;
488     std::for_each(B, d->arg_end(), CollectOptionProperties(o));
489   }
490
491 };
492
493 /// CollectOptionDescriptions - Collects option properties from all
494 /// OptionLists.
495 void CollectOptionDescriptions (RecordVector::const_iterator B,
496                                 RecordVector::const_iterator E,
497                                 OptionDescriptions& OptDescs)
498 {
499   // For every OptionList:
500   for (; B!=E; ++B) {
501     RecordVector::value_type T = *B;
502     // Throws an exception if the value does not exist.
503     ListInit* PropList = T->getValueAsListInit("options");
504
505     // For every option description in this list:
506     // collect the information and
507     std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
508   }
509 }
510
511 // Tool information record
512
513 namespace ToolFlags {
514   enum ToolFlags { Join = 0x1, Sink = 0x2 };
515 }
516
517 struct ToolDescription : public RefCountedBase<ToolDescription> {
518   std::string Name;
519   Init* CmdLine;
520   Init* Actions;
521   StrVector InLanguage;
522   std::string OutLanguage;
523   std::string OutputSuffix;
524   unsigned Flags;
525
526   // Various boolean properties
527   void setSink()      { Flags |= ToolFlags::Sink; }
528   bool isSink() const { return Flags & ToolFlags::Sink; }
529   void setJoin()      { Flags |= ToolFlags::Join; }
530   bool isJoin() const { return Flags & ToolFlags::Join; }
531
532   // Default ctor here is needed because StringMap can only store
533   // DefaultConstructible objects
534   ToolDescription() : CmdLine(0), Actions(0), Flags(0) {}
535   ToolDescription (const std::string& n)
536   : Name(n), CmdLine(0), Actions(0), Flags(0)
537   {}
538 };
539
540 /// ToolDescriptions - A list of Tool information records.
541 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
542
543
544 /// CollectToolProperties - Function object for iterating over a list of
545 /// tool property records.
546 class CollectToolProperties : public HandlerTable<CollectToolProperties> {
547 private:
548
549   /// toolDesc_ - Properties of the current Tool. This is where the
550   /// information is stored.
551   ToolDescription& toolDesc_;
552
553 public:
554
555   explicit CollectToolProperties (ToolDescription& d)
556     : HandlerTable<CollectToolProperties>(this) , toolDesc_(d)
557   {
558     if (!staticMembersInitialized_) {
559
560       AddHandler("actions", &CollectToolProperties::onActions);
561       AddHandler("cmd_line", &CollectToolProperties::onCmdLine);
562       AddHandler("in_language", &CollectToolProperties::onInLanguage);
563       AddHandler("join", &CollectToolProperties::onJoin);
564       AddHandler("out_language", &CollectToolProperties::onOutLanguage);
565       AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
566       AddHandler("sink", &CollectToolProperties::onSink);
567
568       staticMembersInitialized_ = true;
569     }
570   }
571
572 private:
573
574   /// Property handlers --
575   /// Functions that extract information about tool properties from
576   /// DAG representation.
577
578   void onActions (const DagInit* d) {
579     checkNumberOfArguments(d, 1);
580     Init* Case = d->getArg(0);
581     if (typeid(*Case) != typeid(DagInit) ||
582         static_cast<DagInit*>(Case)->getOperator()->getAsString() != "case")
583       throw
584         std::string("The argument to (actions) should be a 'case' construct!");
585     toolDesc_.Actions = Case;
586   }
587
588   void onCmdLine (const DagInit* d) {
589     checkNumberOfArguments(d, 1);
590     toolDesc_.CmdLine = d->getArg(0);
591   }
592
593   void onInLanguage (const DagInit* d) {
594     checkNumberOfArguments(d, 1);
595     Init* arg = d->getArg(0);
596
597     // Find out the argument's type.
598     if (typeid(*arg) == typeid(StringInit)) {
599       // It's a string.
600       toolDesc_.InLanguage.push_back(InitPtrToString(arg));
601     }
602     else {
603       // It's a list.
604       const ListInit& lst = InitPtrToList(arg);
605       StrVector& out = toolDesc_.InLanguage;
606
607       // Copy strings to the output vector.
608       for (ListInit::const_iterator B = lst.begin(), E = lst.end();
609            B != E; ++B) {
610         out.push_back(InitPtrToString(*B));
611       }
612
613       // Remove duplicates.
614       std::sort(out.begin(), out.end());
615       StrVector::iterator newE = std::unique(out.begin(), out.end());
616       out.erase(newE, out.end());
617     }
618   }
619
620   void onJoin (const DagInit* d) {
621     checkNumberOfArguments(d, 0);
622     toolDesc_.setJoin();
623   }
624
625   void onOutLanguage (const DagInit* d) {
626     checkNumberOfArguments(d, 1);
627     toolDesc_.OutLanguage = InitPtrToString(d->getArg(0));
628   }
629
630   void onOutputSuffix (const DagInit* d) {
631     checkNumberOfArguments(d, 1);
632     toolDesc_.OutputSuffix = InitPtrToString(d->getArg(0));
633   }
634
635   void onSink (const DagInit* d) {
636     checkNumberOfArguments(d, 0);
637     toolDesc_.setSink();
638   }
639
640 };
641
642
643 /// CollectToolDescriptions - Gather information about tool properties
644 /// from the parsed TableGen data (basically a wrapper for the
645 /// CollectToolProperties function object).
646 void CollectToolDescriptions (RecordVector::const_iterator B,
647                               RecordVector::const_iterator E,
648                               ToolDescriptions& ToolDescs)
649 {
650   // Iterate over a properties list of every Tool definition
651   for (;B!=E;++B) {
652     const Record* T = *B;
653     // Throws an exception if the value does not exist.
654     ListInit* PropList = T->getValueAsListInit("properties");
655
656     IntrusiveRefCntPtr<ToolDescription>
657       ToolDesc(new ToolDescription(T->getName()));
658
659     std::for_each(PropList->begin(), PropList->end(),
660                   CollectToolProperties(*ToolDesc));
661     ToolDescs.push_back(ToolDesc);
662   }
663 }
664
665 /// FillInEdgeVector - Merge all compilation graph definitions into
666 /// one single edge list.
667 void FillInEdgeVector(RecordVector::const_iterator B,
668                       RecordVector::const_iterator E, RecordVector& Out) {
669   for (; B != E; ++B) {
670     const ListInit* edges = (*B)->getValueAsListInit("edges");
671
672     for (unsigned i = 0; i < edges->size(); ++i)
673       Out.push_back(edges->getElementAsRecord(i));
674   }
675 }
676
677 /// CalculatePriority - Calculate the priority of this plugin.
678 int CalculatePriority(RecordVector::const_iterator B,
679                       RecordVector::const_iterator E) {
680   int total = 0;
681   for (; B!=E; ++B) {
682     total += static_cast<int>((*B)->getValueAsInt("priority"));
683   }
684   return total;
685 }
686
687 /// NotInGraph - Helper function object for FilterNotInGraph.
688 struct NotInGraph {
689 private:
690   const llvm::StringSet<>& ToolsInGraph_;
691
692 public:
693   NotInGraph(const llvm::StringSet<>& ToolsInGraph)
694   : ToolsInGraph_(ToolsInGraph)
695   {}
696
697   bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
698     return (ToolsInGraph_.count(x->Name) == 0);
699   }
700 };
701
702 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
703 /// mentioned in the compilation graph definition.
704 void FilterNotInGraph (const RecordVector& EdgeVector,
705                        ToolDescriptions& ToolDescs) {
706
707   // List all tools mentioned in the graph.
708   llvm::StringSet<> ToolsInGraph;
709
710   for (RecordVector::const_iterator B = EdgeVector.begin(),
711          E = EdgeVector.end(); B != E; ++B) {
712
713     const Record* Edge = *B;
714     const std::string& NodeA = Edge->getValueAsString("a");
715     const std::string& NodeB = Edge->getValueAsString("b");
716
717     if (NodeA != "root")
718       ToolsInGraph.insert(NodeA);
719     ToolsInGraph.insert(NodeB);
720   }
721
722   // Filter ToolPropertiesList.
723   ToolDescriptions::iterator new_end =
724     std::remove_if(ToolDescs.begin(), ToolDescs.end(),
725                    NotInGraph(ToolsInGraph));
726   ToolDescs.erase(new_end, ToolDescs.end());
727 }
728
729 /// FillInToolToLang - Fills in two tables that map tool names to
730 /// (input, output) languages.  Helper function used by TypecheckGraph().
731 void FillInToolToLang (const ToolDescriptions& ToolDescs,
732                        StringMap<StringSet<> >& ToolToInLang,
733                        StringMap<std::string>& ToolToOutLang) {
734   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
735          E = ToolDescs.end(); B != E; ++B) {
736     const ToolDescription& D = *(*B);
737     for (StrVector::const_iterator B = D.InLanguage.begin(),
738            E = D.InLanguage.end(); B != E; ++B)
739       ToolToInLang[D.Name].insert(*B);
740     ToolToOutLang[D.Name] = D.OutLanguage;
741   }
742 }
743
744 /// TypecheckGraph - Check that names for output and input languages
745 /// on all edges do match. This doesn't do much when the information
746 /// about the whole graph is not available (i.e. when compiling most
747 /// plugins).
748 void TypecheckGraph (const RecordVector& EdgeVector,
749                      const ToolDescriptions& ToolDescs) {
750   StringMap<StringSet<> > ToolToInLang;
751   StringMap<std::string> ToolToOutLang;
752
753   FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
754   StringMap<std::string>::iterator IAE = ToolToOutLang.end();
755   StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
756
757   for (RecordVector::const_iterator B = EdgeVector.begin(),
758          E = EdgeVector.end(); B != E; ++B) {
759     const Record* Edge = *B;
760     const std::string& NodeA = Edge->getValueAsString("a");
761     const std::string& NodeB = Edge->getValueAsString("b");
762     StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
763     StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
764
765     if (NodeA != "root") {
766       if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
767         throw "Edge " + NodeA + "->" + NodeB
768           + ": output->input language mismatch";
769     }
770
771     if (NodeB == "root")
772       throw std::string("Edges back to the root are not allowed!");
773   }
774 }
775
776 /// WalkCase - Walks the 'case' expression DAG and invokes
777 /// TestCallback on every test, and StatementCallback on every
778 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
779 /// combinators.
780 // TODO: Re-implement EmitCaseConstructHandler on top of this function?
781 template <typename F1, typename F2>
782 void WalkCase(Init* Case, F1 TestCallback, F2 StatementCallback) {
783   const DagInit& d = InitPtrToDag(Case);
784   bool even = false;
785   for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
786        B != E; ++B) {
787     Init* arg = *B;
788     if (even && dynamic_cast<DagInit*>(arg)
789         && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
790       WalkCase(arg, TestCallback, StatementCallback);
791     else if (!even)
792       TestCallback(arg);
793     else
794       StatementCallback(arg);
795     even = !even;
796   }
797 }
798
799 /// ExtractOptionNames - A helper function object used by
800 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
801 class ExtractOptionNames {
802   llvm::StringSet<>& OptionNames_;
803
804   void processDag(const Init* Statement) {
805     const DagInit& Stmt = InitPtrToDag(Statement);
806     const std::string& ActionName = Stmt.getOperator()->getAsString();
807     if (ActionName == "forward" || ActionName == "forward_as" ||
808         ActionName == "unpack_values" || ActionName == "switch_on" ||
809         ActionName == "parameter_equals" || ActionName == "element_in_list" ||
810         ActionName == "not_empty" || ActionName == "empty") {
811       checkNumberOfArguments(&Stmt, 1);
812       const std::string& Name = InitPtrToString(Stmt.getArg(0));
813       OptionNames_.insert(Name);
814     }
815     else if (ActionName == "and" || ActionName == "or") {
816       for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
817         this->processDag(Stmt.getArg(i));
818       }
819     }
820   }
821
822 public:
823   ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
824   {}
825
826   void operator()(const Init* Statement) {
827     if (typeid(*Statement) == typeid(ListInit)) {
828       const ListInit& DagList = *static_cast<const ListInit*>(Statement);
829       for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
830            B != E; ++B)
831         this->processDag(*B);
832     }
833     else {
834       this->processDag(Statement);
835     }
836   }
837 };
838
839 /// CheckForSuperfluousOptions - Check that there are no side
840 /// effect-free options (specified only in the OptionList). Otherwise,
841 /// output a warning.
842 void CheckForSuperfluousOptions (const RecordVector& Edges,
843                                  const ToolDescriptions& ToolDescs,
844                                  const OptionDescriptions& OptDescs) {
845   llvm::StringSet<> nonSuperfluousOptions;
846
847   // Add all options mentioned in the ToolDesc.Actions to the set of
848   // non-superfluous options.
849   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
850          E = ToolDescs.end(); B != E; ++B) {
851     const ToolDescription& TD = *(*B);
852     ExtractOptionNames Callback(nonSuperfluousOptions);
853     if (TD.Actions)
854       WalkCase(TD.Actions, Callback, Callback);
855   }
856
857   // Add all options mentioned in the 'case' clauses of the
858   // OptionalEdges of the compilation graph to the set of
859   // non-superfluous options.
860   for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
861        B != E; ++B) {
862     const Record* Edge = *B;
863     DagInit* Weight = Edge->getValueAsDag("weight");
864
865     if (!isDagEmpty(Weight))
866       WalkCase(Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
867   }
868
869   // Check that all options in OptDescs belong to the set of
870   // non-superfluous options.
871   for (OptionDescriptions::const_iterator B = OptDescs.begin(),
872          E = OptDescs.end(); B != E; ++B) {
873     const OptionDescription& Val = B->second;
874     if (!nonSuperfluousOptions.count(Val.Name)
875         && Val.Type != OptionType::Alias)
876       llvm::cerr << "Warning: option '-" << Val.Name << "' has no effect! "
877         "Probable cause: this option is specified only in the OptionList.\n";
878   }
879 }
880
881 /// EmitCaseTest1Arg - Helper function used by
882 /// EmitCaseConstructHandler.
883 bool EmitCaseTest1Arg(const std::string& TestName,
884                       const DagInit& d,
885                       const OptionDescriptions& OptDescs,
886                       std::ostream& O) {
887   checkNumberOfArguments(&d, 1);
888   const std::string& OptName = InitPtrToString(d.getArg(0));
889
890   if (TestName == "switch_on") {
891     const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
892     if (!OptionType::IsSwitch(OptDesc.Type))
893       throw OptName + ": incorrect option type - should be a switch!";
894     O << OptDesc.GenVariableName();
895     return true;
896   } else if (TestName == "input_languages_contain") {
897     O << "InLangs.count(\"" << OptName << "\") != 0";
898     return true;
899   } else if (TestName == "in_language") {
900     // This works only for single-argument Tool::GenerateAction. Join
901     // tools can process several files in different languages simultaneously.
902
903     // TODO: make this work with Edge::Weight (if possible).
904     O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
905     return true;
906   } else if (TestName == "not_empty" || TestName == "empty") {
907     const char* Test = (TestName == "empty") ? "" : "!";
908
909     if (OptName == "o") {
910       O << Test << "OutputFilename.empty()";
911       return true;
912     }
913     else {
914       const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
915       if (OptionType::IsSwitch(OptDesc.Type))
916         throw OptName
917           + ": incorrect option type - should be a list or parameter!";
918       O << Test << OptDesc.GenVariableName() << ".empty()";
919       return true;
920     }
921   }
922
923   return false;
924 }
925
926 /// EmitCaseTest2Args - Helper function used by
927 /// EmitCaseConstructHandler.
928 bool EmitCaseTest2Args(const std::string& TestName,
929                        const DagInit& d,
930                        const char* IndentLevel,
931                        const OptionDescriptions& OptDescs,
932                        std::ostream& O) {
933   checkNumberOfArguments(&d, 2);
934   const std::string& OptName = InitPtrToString(d.getArg(0));
935   const std::string& OptArg = InitPtrToString(d.getArg(1));
936   const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
937
938   if (TestName == "parameter_equals") {
939     if (!OptionType::IsParameter(OptDesc.Type))
940       throw OptName + ": incorrect option type - should be a parameter!";
941     O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
942     return true;
943   }
944   else if (TestName == "element_in_list") {
945     if (!OptionType::IsList(OptDesc.Type))
946       throw OptName + ": incorrect option type - should be a list!";
947     const std::string& VarName = OptDesc.GenVariableName();
948     O << "std::find(" << VarName << ".begin(),\n"
949       << IndentLevel << Indent1 << VarName << ".end(), \""
950       << OptArg << "\") != " << VarName << ".end()";
951     return true;
952   }
953
954   return false;
955 }
956
957 // Forward declaration.
958 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
959 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
960                   const OptionDescriptions& OptDescs,
961                   std::ostream& O);
962
963 /// EmitLogicalOperationTest - Helper function used by
964 /// EmitCaseConstructHandler.
965 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
966                               const char* IndentLevel,
967                               const OptionDescriptions& OptDescs,
968                               std::ostream& O) {
969   O << '(';
970   for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
971     const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
972     EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
973     if (j != NumArgs - 1)
974       O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
975     else
976       O << ')';
977   }
978 }
979
980 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
981 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
982                   const OptionDescriptions& OptDescs,
983                   std::ostream& O) {
984   const std::string& TestName = d.getOperator()->getAsString();
985
986   if (TestName == "and")
987     EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
988   else if (TestName == "or")
989     EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
990   else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
991     return;
992   else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
993     return;
994   else
995     throw TestName + ": unknown edge property!";
996 }
997
998 // Emit code that handles the 'case' construct.
999 // Takes a function object that should emit code for every case clause.
1000 // Callback's type is
1001 // void F(Init* Statement, const char* IndentLevel, std::ostream& O).
1002 template <typename F>
1003 void EmitCaseConstructHandler(const Init* Dag, const char* IndentLevel,
1004                               F Callback, bool EmitElseIf,
1005                               const OptionDescriptions& OptDescs,
1006                               std::ostream& O) {
1007   const DagInit* d = &InitPtrToDag(Dag);
1008   if (d->getOperator()->getAsString() != "case")
1009     throw std::string("EmitCaseConstructHandler should be invoked"
1010                       " only on 'case' expressions!");
1011
1012   unsigned numArgs = d->getNumArgs();
1013   if (d->getNumArgs() < 2)
1014     throw "There should be at least one clause in the 'case' expression:\n"
1015       + d->getAsString();
1016
1017   for (unsigned i = 0; i != numArgs; ++i) {
1018     const DagInit& Test = InitPtrToDag(d->getArg(i));
1019
1020     // Emit the test.
1021     if (Test.getOperator()->getAsString() == "default") {
1022       if (i+2 != numArgs)
1023         throw std::string("The 'default' clause should be the last in the"
1024                           "'case' construct!");
1025       O << IndentLevel << "else {\n";
1026     }
1027     else {
1028       O << IndentLevel << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
1029       EmitCaseTest(Test, IndentLevel, OptDescs, O);
1030       O << ") {\n";
1031     }
1032
1033     // Emit the corresponding statement.
1034     ++i;
1035     if (i == numArgs)
1036       throw "Case construct handler: no corresponding action "
1037         "found for the test " + Test.getAsString() + '!';
1038
1039     Init* arg = d->getArg(i);
1040     const DagInit* nd = dynamic_cast<DagInit*>(arg);
1041     if (nd && (nd->getOperator()->getAsString() == "case")) {
1042       // Handle the nested 'case'.
1043       EmitCaseConstructHandler(nd, (std::string(IndentLevel) + Indent1).c_str(),
1044                                Callback, EmitElseIf, OptDescs, O);
1045     }
1046     else {
1047       Callback(arg, (std::string(IndentLevel) + Indent1).c_str(), O);
1048     }
1049     O << IndentLevel << "}\n";
1050   }
1051 }
1052
1053 /// TokenizeCmdline - converts from "$CALL(HookName, 'Arg1', 'Arg2')/path" to
1054 /// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path"] .
1055 /// Helper function used by EmitCmdLineVecFill and.
1056 void TokenizeCmdline(const std::string& CmdLine, StrVector& Out) {
1057   const char* Delimiters = " \t\n\v\f\r";
1058   enum TokenizerState
1059   { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1060   cur_st  = Normal;
1061   Out.push_back("");
1062
1063   std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1064     E = CmdLine.size();
1065   if (B == std::string::npos)
1066     throw "Empty command-line string!";
1067   for (; B != E; ++B) {
1068     char cur_ch = CmdLine[B];
1069
1070     switch (cur_st) {
1071     case Normal:
1072       if (cur_ch == '$') {
1073         cur_st = SpecialCommand;
1074         break;
1075       }
1076       if (oneOf(Delimiters, cur_ch)) {
1077         // Skip whitespace
1078         B = CmdLine.find_first_not_of(Delimiters, B);
1079         if (B == std::string::npos) {
1080           B = E-1;
1081           continue;
1082         }
1083         --B;
1084         Out.push_back("");
1085         continue;
1086       }
1087       break;
1088
1089
1090     case SpecialCommand:
1091       if (oneOf(Delimiters, cur_ch)) {
1092         cur_st = Normal;
1093         Out.push_back("");
1094         continue;
1095       }
1096       if (cur_ch == '(') {
1097         Out.push_back("");
1098         cur_st = InsideSpecialCommand;
1099         continue;
1100       }
1101       break;
1102
1103     case InsideSpecialCommand:
1104       if (oneOf(Delimiters, cur_ch)) {
1105         continue;
1106       }
1107       if (cur_ch == '\'') {
1108         cur_st = InsideQuotationMarks;
1109         Out.push_back("");
1110         continue;
1111       }
1112       if (cur_ch == ')') {
1113         cur_st = Normal;
1114         Out.push_back("");
1115       }
1116       if (cur_ch == ',') {
1117         continue;
1118       }
1119
1120       break;
1121
1122     case InsideQuotationMarks:
1123       if (cur_ch == '\'') {
1124         cur_st = InsideSpecialCommand;
1125         continue;
1126       }
1127       break;
1128     }
1129
1130     Out.back().push_back(cur_ch);
1131   }
1132 }
1133
1134 template <class I, class S>
1135 void checkedIncrement(I& P, I E, S ErrorString) {
1136   ++P;
1137   if (P == E)
1138     throw ErrorString;
1139 }
1140
1141 /// SubstituteSpecialCommands - Perform string substitution for $CALL
1142 /// and $ENV. Helper function used by EmitCmdLineVecFill().
1143 StrVector::const_iterator SubstituteSpecialCommands
1144 (StrVector::const_iterator Pos, StrVector::const_iterator End, std::ostream& O)
1145 {
1146
1147   const std::string& cmd = *Pos;
1148
1149   if (cmd == "$CALL") {
1150     checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1151     const std::string& CmdName = *Pos;
1152
1153     if (CmdName == ")")
1154       throw std::string("$CALL invocation: empty argument list!");
1155
1156     O << "hooks::";
1157     O << CmdName << "(";
1158
1159
1160     bool firstIteration = true;
1161     while (true) {
1162       checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1163       const std::string& Arg = *Pos;
1164       assert(Arg.size() != 0);
1165
1166       if (Arg[0] == ')')
1167         break;
1168
1169       if (firstIteration)
1170         firstIteration = false;
1171       else
1172         O << ", ";
1173
1174       O << '"' << Arg << '"';
1175     }
1176
1177     O << ')';
1178
1179   }
1180   else if (cmd == "$ENV") {
1181     checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1182     const std::string& EnvName = *Pos;
1183
1184     if (EnvName == ")")
1185       throw "$ENV invocation: empty argument list!";
1186
1187     O << "checkCString(std::getenv(\"";
1188     O << EnvName;
1189     O << "\"))";
1190
1191     checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1192   }
1193   else {
1194     throw "Unknown special command: " + cmd;
1195   }
1196
1197   const std::string& Leftover = *Pos;
1198   assert(Leftover.at(0) == ')');
1199   if (Leftover.size() != 1)
1200     O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1201   O << ')';
1202
1203   return Pos;
1204 }
1205
1206 /// EmitCmdLineVecFill - Emit code that fills in the command line
1207 /// vector. Helper function used by EmitGenerateActionMethod().
1208 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1209                         bool IsJoin, const char* IndentLevel,
1210                         std::ostream& O) {
1211   StrVector StrVec;
1212   TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1213
1214   if (StrVec.empty())
1215     throw "Tool " + ToolName + " has empty command line!";
1216
1217   StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1218
1219   // If there is a hook invocation on the place of the first command, skip it.
1220   if (StrVec[0][0] == '$') {
1221     while (I != E && (*I)[0] != ')' )
1222       ++I;
1223
1224     // Skip the ')' symbol.
1225     ++I;
1226   }
1227   else {
1228     ++I;
1229   }
1230
1231   for (; I != E; ++I) {
1232     const std::string& cmd = *I;
1233     //    std::cerr << cmd;
1234     O << IndentLevel;
1235     if (cmd.at(0) == '$') {
1236       if (cmd == "$INFILE") {
1237         if (IsJoin)
1238           O << "for (PathVector::const_iterator B = inFiles.begin()"
1239             << ", E = inFiles.end();\n"
1240             << IndentLevel << "B != E; ++B)\n"
1241             << IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
1242         else
1243           O << "vec.push_back(inFile.toString());\n";
1244       }
1245       else if (cmd == "$OUTFILE") {
1246         O << "vec.push_back(out_file);\n";
1247       }
1248       else {
1249         O << "vec.push_back(";
1250         I = SubstituteSpecialCommands(I, E, O);
1251         O << ");\n";
1252       }
1253     }
1254     else {
1255       O << "vec.push_back(\"" << cmd << "\");\n";
1256     }
1257   }
1258   O << IndentLevel << "cmd = ";
1259
1260   if (StrVec[0][0] == '$')
1261     SubstituteSpecialCommands(StrVec.begin(), StrVec.end(), O);
1262   else
1263     O << '"' << StrVec[0] << '"';
1264   O << ";\n";
1265 }
1266
1267 /// EmitCmdLineVecFillCallback - A function object wrapper around
1268 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1269 /// argument to EmitCaseConstructHandler().
1270 class EmitCmdLineVecFillCallback {
1271   bool IsJoin;
1272   const std::string& ToolName;
1273  public:
1274   EmitCmdLineVecFillCallback(bool J, const std::string& TN)
1275     : IsJoin(J), ToolName(TN) {}
1276
1277   void operator()(const Init* Statement, const char* IndentLevel,
1278                   std::ostream& O) const
1279   {
1280     EmitCmdLineVecFill(Statement, ToolName, IsJoin,
1281                        IndentLevel, O);
1282   }
1283 };
1284
1285 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1286 /// implement EmitActionHandler. Emits code for
1287 /// handling the (forward) and (forward_as) option properties.
1288 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1289                                             const char* Indent,
1290                                             const std::string& NewName,
1291                                             std::ostream& O) {
1292   const std::string& Name = NewName.empty()
1293     ? ("-" + D.Name)
1294     : NewName;
1295
1296   switch (D.Type) {
1297   case OptionType::Switch:
1298     O << Indent << "vec.push_back(\"" << Name << "\");\n";
1299     break;
1300   case OptionType::Parameter:
1301     O << Indent << "vec.push_back(\"" << Name << "\");\n";
1302     O << Indent << "vec.push_back(" << D.GenVariableName() << ");\n";
1303     break;
1304   case OptionType::Prefix:
1305     O << Indent << "vec.push_back(\"" << Name << "\" + "
1306       << D.GenVariableName() << ");\n";
1307     break;
1308   case OptionType::PrefixList:
1309     O << Indent << "for (" << D.GenTypeDeclaration()
1310       << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1311       << Indent << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
1312       << Indent << Indent1 << "vec.push_back(\"" << Name << "\" + "
1313       << "*B);\n";
1314     break;
1315   case OptionType::ParameterList:
1316     O << Indent << "for (" << D.GenTypeDeclaration()
1317       << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1318       << Indent << "E = " << D.GenVariableName()
1319       << ".end() ; B != E; ++B) {\n"
1320       << Indent << Indent1 << "vec.push_back(\"" << Name << "\");\n"
1321       << Indent << Indent1 << "vec.push_back(*B);\n"
1322       << Indent << "}\n";
1323     break;
1324   case OptionType::Alias:
1325   default:
1326     throw std::string("Aliases are not allowed in tool option descriptions!");
1327   }
1328 }
1329
1330 /// EmitActionHandler - Emit code that handles actions. Used by
1331 /// EmitGenerateActionMethod() as an argument to
1332 /// EmitCaseConstructHandler().
1333 class EmitActionHandler {
1334   const OptionDescriptions& OptDescs;
1335
1336   void processActionDag(const Init* Statement, const char* IndentLevel,
1337                         std::ostream& O) const
1338   {
1339     const DagInit& Dag = InitPtrToDag(Statement);
1340     const std::string& ActionName = Dag.getOperator()->getAsString();
1341
1342     if (ActionName == "append_cmd") {
1343       checkNumberOfArguments(&Dag, 1);
1344       const std::string& Cmd = InitPtrToString(Dag.getArg(0));
1345       O << IndentLevel << "vec.push_back(\"" << Cmd << "\");\n";
1346     }
1347     else if (ActionName == "error") {
1348       O << IndentLevel << "throw std::runtime_error(\"" <<
1349         (Dag.getNumArgs() >= 1 ? InitPtrToString(Dag.getArg(0))
1350          : "Unknown error!")
1351         << "\");\n";
1352     }
1353     else if (ActionName == "forward") {
1354       checkNumberOfArguments(&Dag, 1);
1355       const std::string& Name = InitPtrToString(Dag.getArg(0));
1356       EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1357                                             IndentLevel, "", O);
1358     }
1359     else if (ActionName == "forward_as") {
1360       checkNumberOfArguments(&Dag, 2);
1361       const std::string& Name = InitPtrToString(Dag.getArg(0));
1362       const std::string& NewName = InitPtrToString(Dag.getArg(0));
1363       EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1364                                             IndentLevel, NewName, O);
1365     }
1366     else if (ActionName == "output_suffix") {
1367       checkNumberOfArguments(&Dag, 1);
1368       const std::string& OutSuf = InitPtrToString(Dag.getArg(0));
1369       O << IndentLevel << "output_suffix = \"" << OutSuf << "\";\n";
1370     }
1371     else if (ActionName == "stop_compilation") {
1372       O << IndentLevel << "stop_compilation = true;\n";
1373     }
1374     else if (ActionName == "unpack_values") {
1375       checkNumberOfArguments(&Dag, 1);
1376       const std::string& Name = InitPtrToString(Dag.getArg(0));
1377       const OptionDescription& D = OptDescs.FindOption(Name);
1378
1379       if (OptionType::IsList(D.Type)) {
1380         O << IndentLevel << "for (" << D.GenTypeDeclaration()
1381           << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1382           << IndentLevel << "E = " << D.GenVariableName()
1383           << ".end(); B != E; ++B)\n"
1384           << IndentLevel << Indent1 << "llvm::SplitString(*B, vec, \",\");\n";
1385       }
1386       else if (OptionType::IsParameter(D.Type)){
1387         O << Indent3 << "llvm::SplitString("
1388           << D.GenVariableName() << ", vec, \",\");\n";
1389       }
1390       else {
1391         throw "Option '" + D.Name +
1392           "': switches can't have the 'unpack_values' property!";
1393       }
1394     }
1395     else {
1396       throw "Unknown action name: " + ActionName + "!";
1397     }
1398   }
1399  public:
1400   EmitActionHandler(const OptionDescriptions& OD)
1401     : OptDescs(OD) {}
1402
1403   void operator()(const Init* Statement, const char* IndentLevel,
1404                   std::ostream& O) const
1405   {
1406     if (typeid(*Statement) == typeid(ListInit)) {
1407       const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1408       for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1409            B != E; ++B)
1410         this->processActionDag(*B, IndentLevel, O);
1411     }
1412     else {
1413       this->processActionDag(Statement, IndentLevel, O);
1414     }
1415   }
1416 };
1417
1418 // EmitGenerateActionMethod - Emit one of two versions of the
1419 // Tool::GenerateAction() method.
1420 void EmitGenerateActionMethod (const ToolDescription& D,
1421                                const OptionDescriptions& OptDescs,
1422                                bool IsJoin, std::ostream& O) {
1423   if (IsJoin)
1424     O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
1425   else
1426     O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
1427
1428   O << Indent2 << "bool HasChildren,\n"
1429     << Indent2 << "const llvm::sys::Path& TempDir,\n"
1430     << Indent2 << "const InputLanguagesSet& InLangs,\n"
1431     << Indent2 << "const LanguageMap& LangMap) const\n"
1432     << Indent1 << "{\n"
1433     << Indent2 << "std::string cmd;\n"
1434     << Indent2 << "std::vector<std::string> vec;\n"
1435     << Indent2 << "bool stop_compilation = !HasChildren;\n"
1436     << Indent2 << "const char* output_suffix = \"" << D.OutputSuffix << "\";\n"
1437     << Indent2 << "std::string out_file;\n\n";
1438
1439   // For every understood option, emit handling code.
1440   if (D.Actions)
1441     EmitCaseConstructHandler(D.Actions, Indent2, EmitActionHandler(OptDescs),
1442                              false, OptDescs, O);
1443
1444   O << '\n' << Indent2
1445     << "out_file = OutFilename(" << (IsJoin ? "sys::Path(),\n" : "inFile,\n")
1446     << Indent3 << "TempDir, stop_compilation, output_suffix).toString();\n\n";
1447
1448   // cmd_line is either a string or a 'case' construct.
1449   if (!D.CmdLine)
1450     throw "Tool " + D.Name + " has no cmd_line property!";
1451   else if (typeid(*D.CmdLine) == typeid(StringInit))
1452     EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
1453   else
1454     EmitCaseConstructHandler(D.CmdLine, Indent2,
1455                              EmitCmdLineVecFillCallback(IsJoin, D.Name),
1456                              true, OptDescs, O);
1457
1458   // Handle the Sink property.
1459   if (D.isSink()) {
1460     O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
1461       << Indent3 << "vec.insert(vec.end(), "
1462       << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
1463       << Indent2 << "}\n";
1464   }
1465
1466   O << Indent2 << "return Action(cmd, vec, stop_compilation, out_file);\n"
1467     << Indent1 << "}\n\n";
1468 }
1469
1470 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1471 /// a given Tool class.
1472 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
1473                                 const OptionDescriptions& OptDescs,
1474                                 std::ostream& O) {
1475   if (!ToolDesc.isJoin())
1476     O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
1477       << Indent2 << "bool HasChildren,\n"
1478       << Indent2 << "const llvm::sys::Path& TempDir,\n"
1479       << Indent2 << "const InputLanguagesSet& InLangs,\n"
1480       << Indent2 << "const LanguageMap& LangMap) const\n"
1481       << Indent1 << "{\n"
1482       << Indent2 << "throw std::runtime_error(\"" << ToolDesc.Name
1483       << " is not a Join tool!\");\n"
1484       << Indent1 << "}\n\n";
1485   else
1486     EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
1487
1488   EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
1489 }
1490
1491 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1492 /// methods for a given Tool class.
1493 void EmitInOutLanguageMethods (const ToolDescription& D, std::ostream& O) {
1494   O << Indent1 << "const char** InputLanguages() const {\n"
1495     << Indent2 << "return InputLanguages_;\n"
1496     << Indent1 << "}\n\n";
1497
1498   if (D.OutLanguage.empty())
1499     throw "Tool " + D.Name + " has no 'out_language' property!";
1500
1501   O << Indent1 << "const char* OutputLanguage() const {\n"
1502     << Indent2 << "return \"" << D.OutLanguage << "\";\n"
1503     << Indent1 << "}\n\n";
1504 }
1505
1506 /// EmitNameMethod - Emit the Name() method for a given Tool class.
1507 void EmitNameMethod (const ToolDescription& D, std::ostream& O) {
1508   O << Indent1 << "const char* Name() const {\n"
1509     << Indent2 << "return \"" << D.Name << "\";\n"
1510     << Indent1 << "}\n\n";
1511 }
1512
1513 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1514 /// class.
1515 void EmitIsJoinMethod (const ToolDescription& D, std::ostream& O) {
1516   O << Indent1 << "bool IsJoin() const {\n";
1517   if (D.isJoin())
1518     O << Indent2 << "return true;\n";
1519   else
1520     O << Indent2 << "return false;\n";
1521   O << Indent1 << "}\n\n";
1522 }
1523
1524 /// EmitStaticMemberDefinitions - Emit static member definitions for a
1525 /// given Tool class.
1526 void EmitStaticMemberDefinitions(const ToolDescription& D, std::ostream& O) {
1527   if (D.InLanguage.empty())
1528     throw "Tool " + D.Name + " has no 'in_language' property!";
1529
1530   O << "const char* " << D.Name << "::InputLanguages_[] = {";
1531   for (StrVector::const_iterator B = D.InLanguage.begin(),
1532          E = D.InLanguage.end(); B != E; ++B)
1533     O << '\"' << *B << "\", ";
1534   O << "0};\n\n";
1535 }
1536
1537 /// EmitToolClassDefinition - Emit a Tool class definition.
1538 void EmitToolClassDefinition (const ToolDescription& D,
1539                               const OptionDescriptions& OptDescs,
1540                               std::ostream& O) {
1541   if (D.Name == "root")
1542     return;
1543
1544   // Header
1545   O << "class " << D.Name << " : public ";
1546   if (D.isJoin())
1547     O << "JoinTool";
1548   else
1549     O << "Tool";
1550
1551   O << "{\nprivate:\n"
1552     << Indent1 << "static const char* InputLanguages_[];\n\n";
1553
1554   O << "public:\n";
1555   EmitNameMethod(D, O);
1556   EmitInOutLanguageMethods(D, O);
1557   EmitIsJoinMethod(D, O);
1558   EmitGenerateActionMethods(D, OptDescs, O);
1559
1560   // Close class definition
1561   O << "};\n";
1562
1563   EmitStaticMemberDefinitions(D, O);
1564
1565 }
1566
1567 /// EmitOptionDefintions - Iterate over a list of option descriptions
1568 /// and emit registration code.
1569 void EmitOptionDefintions (const OptionDescriptions& descs,
1570                            bool HasSink, bool HasExterns,
1571                            std::ostream& O)
1572 {
1573   std::vector<OptionDescription> Aliases;
1574
1575   // Emit static cl::Option variables.
1576   for (OptionDescriptions::const_iterator B = descs.begin(),
1577          E = descs.end(); B!=E; ++B) {
1578     const OptionDescription& val = B->second;
1579
1580     if (val.Type == OptionType::Alias) {
1581       Aliases.push_back(val);
1582       continue;
1583     }
1584
1585     if (val.isExtern())
1586       O << "extern ";
1587
1588     O << val.GenTypeDeclaration() << ' '
1589       << val.GenVariableName();
1590
1591     if (val.isExtern()) {
1592       O << ";\n";
1593       continue;
1594     }
1595
1596     O << "(\"" << val.Name << '\"';
1597
1598     if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1599       O << ", cl::Prefix";
1600
1601     if (val.isRequired()) {
1602       switch (val.Type) {
1603       case OptionType::PrefixList:
1604       case OptionType::ParameterList:
1605         O << ", cl::OneOrMore";
1606         break;
1607       default:
1608         O << ", cl::Required";
1609       }
1610     }
1611
1612     if (val.isReallyHidden() || val.isHidden()) {
1613       if (val.isRequired())
1614         O << " |";
1615       else
1616         O << ",";
1617       if (val.isReallyHidden())
1618         O << " cl::ReallyHidden";
1619       else
1620         O << " cl::Hidden";
1621     }
1622
1623     if (!val.Help.empty())
1624       O << ", cl::desc(\"" << val.Help << "\")";
1625
1626     O << ");\n";
1627   }
1628
1629   // Emit the aliases (they should go after all the 'proper' options).
1630   for (std::vector<OptionDescription>::const_iterator
1631          B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
1632     const OptionDescription& val = *B;
1633
1634     O << val.GenTypeDeclaration() << ' '
1635       << val.GenVariableName()
1636       << "(\"" << val.Name << '\"';
1637
1638     const OptionDescription& D = descs.FindOption(val.Help);
1639     O << ", cl::aliasopt(" << D.GenVariableName() << ")";
1640
1641     O << ", cl::desc(\"" << "An alias for -" + val.Help  << "\"));\n";
1642   }
1643
1644   // Emit the sink option.
1645   if (HasSink)
1646     O << (HasExterns ? "extern cl" : "cl")
1647       << "::list<std::string> " << SinkOptionName
1648       << (HasExterns ? ";\n" : "(cl::Sink);\n");
1649
1650   O << '\n';
1651 }
1652
1653 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
1654 void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
1655 {
1656   // Generate code
1657   O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
1658
1659   // Get the relevant field out of RecordKeeper
1660   const Record* LangMapRecord = Records.getDef("LanguageMap");
1661
1662   // It is allowed for a plugin to have no language map.
1663   if (LangMapRecord) {
1664
1665     ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
1666     if (!LangsToSuffixesList)
1667       throw std::string("Error in the language map definition!");
1668
1669     for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
1670       const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
1671
1672       const std::string& Lang = LangToSuffixes->getValueAsString("lang");
1673       const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
1674
1675       for (unsigned i = 0; i < Suffixes->size(); ++i)
1676         O << Indent1 << "langMap[\""
1677           << InitPtrToString(Suffixes->getElement(i))
1678           << "\"] = \"" << Lang << "\";\n";
1679     }
1680   }
1681
1682   O << "}\n\n";
1683 }
1684
1685 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
1686 /// by EmitEdgeClass().
1687 void IncDecWeight (const Init* i, const char* IndentLevel,
1688                    std::ostream& O) {
1689   const DagInit& d = InitPtrToDag(i);
1690   const std::string& OpName = d.getOperator()->getAsString();
1691
1692   if (OpName == "inc_weight") {
1693     O << IndentLevel << "ret += ";
1694   }
1695   else if (OpName == "dec_weight") {
1696     O << IndentLevel << "ret -= ";
1697   }
1698   else if (OpName == "error") {
1699     O << IndentLevel << "throw std::runtime_error(\"" <<
1700         (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0))
1701          : "Unknown error!")
1702       << "\");\n";
1703     return;
1704   }
1705
1706   else
1707     throw "Unknown operator in edge properties list: " + OpName + '!' +
1708       "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
1709
1710   if (d.getNumArgs() > 0)
1711     O << InitPtrToInt(d.getArg(0)) << ";\n";
1712   else
1713     O << "2;\n";
1714
1715 }
1716
1717 /// EmitEdgeClass - Emit a single Edge# class.
1718 void EmitEdgeClass (unsigned N, const std::string& Target,
1719                     DagInit* Case, const OptionDescriptions& OptDescs,
1720                     std::ostream& O) {
1721
1722   // Class constructor.
1723   O << "class Edge" << N << ": public Edge {\n"
1724     << "public:\n"
1725     << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1726     << "\") {}\n\n"
1727
1728   // Function Weight().
1729     << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
1730     << Indent2 << "unsigned ret = 0;\n";
1731
1732   // Handle the 'case' construct.
1733   EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
1734
1735   O << Indent2 << "return ret;\n"
1736     << Indent1 << "};\n\n};\n\n";
1737 }
1738
1739 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
1740 void EmitEdgeClasses (const RecordVector& EdgeVector,
1741                       const OptionDescriptions& OptDescs,
1742                       std::ostream& O) {
1743   int i = 0;
1744   for (RecordVector::const_iterator B = EdgeVector.begin(),
1745          E = EdgeVector.end(); B != E; ++B) {
1746     const Record* Edge = *B;
1747     const std::string& NodeB = Edge->getValueAsString("b");
1748     DagInit* Weight = Edge->getValueAsDag("weight");
1749
1750     if (!isDagEmpty(Weight))
1751       EmitEdgeClass(i, NodeB, Weight, OptDescs, O);
1752     ++i;
1753   }
1754 }
1755
1756 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1757 /// function.
1758 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
1759                                    const ToolDescriptions& ToolDescs,
1760                                    std::ostream& O)
1761 {
1762   O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
1763
1764   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1765          E = ToolDescs.end(); B != E; ++B)
1766     O << Indent1 << "G.insertNode(new " << (*B)->Name << "());\n";
1767
1768   O << '\n';
1769
1770   // Insert edges.
1771
1772   int i = 0;
1773   for (RecordVector::const_iterator B = EdgeVector.begin(),
1774          E = EdgeVector.end(); B != E; ++B) {
1775     const Record* Edge = *B;
1776     const std::string& NodeA = Edge->getValueAsString("a");
1777     const std::string& NodeB = Edge->getValueAsString("b");
1778     DagInit* Weight = Edge->getValueAsDag("weight");
1779
1780     O << Indent1 << "G.insertEdge(\"" << NodeA << "\", ";
1781
1782     if (isDagEmpty(Weight))
1783       O << "new SimpleEdge(\"" << NodeB << "\")";
1784     else
1785       O << "new Edge" << i << "()";
1786
1787     O << ");\n";
1788     ++i;
1789   }
1790
1791   O << "}\n\n";
1792 }
1793
1794 /// ExtractHookNames - Extract the hook names from all instances of
1795 /// $CALL(HookName) in the provided command line string. Helper
1796 /// function used by FillInHookNames().
1797 class ExtractHookNames {
1798   llvm::StringMap<unsigned>& HookNames_;
1799 public:
1800   ExtractHookNames(llvm::StringMap<unsigned>& HookNames)
1801   : HookNames_(HookNames) {}
1802
1803   void operator()(const Init* CmdLine) {
1804     StrVector cmds;
1805     TokenizeCmdline(InitPtrToString(CmdLine), cmds);
1806     for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
1807          B != E; ++B) {
1808       const std::string& cmd = *B;
1809
1810       if (cmd == "$CALL") {
1811         unsigned NumArgs = 0;
1812         checkedIncrement(B, E, "Syntax error in $CALL invocation!");
1813         const std::string& HookName = *B;
1814
1815
1816         if (HookName.at(0) == ')')
1817           throw "$CALL invoked with no arguments!";
1818
1819         while (++B != E && B->at(0) != ')') {
1820           ++NumArgs;
1821         }
1822
1823         StringMap<unsigned>::const_iterator H = HookNames_.find(HookName);
1824
1825         if (H != HookNames_.end() && H->second != NumArgs)
1826           throw "Overloading of hooks is not allowed. Overloaded hook: "
1827             + HookName;
1828         else
1829           HookNames_[HookName] = NumArgs;
1830
1831       }
1832     }
1833   }
1834 };
1835
1836 /// FillInHookNames - Actually extract the hook names from all command
1837 /// line strings. Helper function used by EmitHookDeclarations().
1838 void FillInHookNames(const ToolDescriptions& ToolDescs,
1839                      llvm::StringMap<unsigned>& HookNames)
1840 {
1841   // For all command lines:
1842   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1843          E = ToolDescs.end(); B != E; ++B) {
1844     const ToolDescription& D = *(*B);
1845     if (!D.CmdLine)
1846       continue;
1847     if (dynamic_cast<StringInit*>(D.CmdLine))
1848       // This is a string.
1849       ExtractHookNames(HookNames).operator()(D.CmdLine);
1850     else
1851       // This is a 'case' construct.
1852       WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames));
1853   }
1854 }
1855
1856 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
1857 /// property records and emit hook function declaration for each
1858 /// instance of $CALL(HookName).
1859 void EmitHookDeclarations(const ToolDescriptions& ToolDescs, std::ostream& O) {
1860   llvm::StringMap<unsigned> HookNames;
1861
1862   FillInHookNames(ToolDescs, HookNames);
1863   if (HookNames.empty())
1864     return;
1865
1866   O << "namespace hooks {\n";
1867   for (StringMap<unsigned>::const_iterator B = HookNames.begin(),
1868          E = HookNames.end(); B != E; ++B) {
1869     O << Indent1 << "std::string " << B->first() << "(";
1870
1871     for (unsigned i = 0, j = B->second; i < j; ++i) {
1872       O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
1873     }
1874
1875     O <<");\n";
1876   }
1877   O << "}\n\n";
1878 }
1879
1880 /// EmitRegisterPlugin - Emit code to register this plugin.
1881 void EmitRegisterPlugin(int Priority, std::ostream& O) {
1882   O << "struct Plugin : public llvmc::BasePlugin {\n\n"
1883     << Indent1 << "int Priority() const { return " << Priority << "; }\n\n"
1884     << Indent1 << "void PopulateLanguageMap(LanguageMap& langMap) const\n"
1885     << Indent1 << "{ PopulateLanguageMapLocal(langMap); }\n\n"
1886     << Indent1
1887     << "void PopulateCompilationGraph(CompilationGraph& graph) const\n"
1888     << Indent1 << "{ PopulateCompilationGraphLocal(graph); }\n"
1889     << "};\n\n"
1890
1891     << "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
1892 }
1893
1894 /// EmitIncludes - Emit necessary #include directives and some
1895 /// additional declarations.
1896 void EmitIncludes(std::ostream& O) {
1897   O << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
1898     << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
1899     << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
1900
1901     << "#include \"llvm/ADT/StringExtras.h\"\n"
1902     << "#include \"llvm/Support/CommandLine.h\"\n\n"
1903
1904     << "#include <cstdlib>\n"
1905     << "#include <stdexcept>\n\n"
1906
1907     << "using namespace llvm;\n"
1908     << "using namespace llvmc;\n\n"
1909
1910     << "extern cl::opt<std::string> OutputFilename;\n\n"
1911
1912     << "inline const char* checkCString(const char* s)\n"
1913     << "{ return s == NULL ? \"\" : s; }\n\n";
1914 }
1915
1916
1917 /// PluginData - Holds all information about a plugin.
1918 struct PluginData {
1919   OptionDescriptions OptDescs;
1920   bool HasSink;
1921   bool HasExterns;
1922   ToolDescriptions ToolDescs;
1923   RecordVector Edges;
1924   int Priority;
1925 };
1926
1927 /// HasSink - Go through the list of tool descriptions and check if
1928 /// there are any with the 'sink' property set.
1929 bool HasSink(const ToolDescriptions& ToolDescs) {
1930   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1931          E = ToolDescs.end(); B != E; ++B)
1932     if ((*B)->isSink())
1933       return true;
1934
1935   return false;
1936 }
1937
1938 /// HasExterns - Go through the list of option descriptions and check
1939 /// if there are any external options.
1940 bool HasExterns(const OptionDescriptions& OptDescs) {
1941  for (OptionDescriptions::const_iterator B = OptDescs.begin(),
1942          E = OptDescs.end(); B != E; ++B)
1943     if (B->second.isExtern())
1944       return true;
1945
1946   return false;
1947 }
1948
1949 /// CollectPluginData - Collect tool and option properties,
1950 /// compilation graph edges and plugin priority from the parse tree.
1951 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
1952   // Collect option properties.
1953   const RecordVector& OptionLists =
1954     Records.getAllDerivedDefinitions("OptionList");
1955   CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
1956                             Data.OptDescs);
1957
1958   // Collect tool properties.
1959   const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
1960   CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
1961   Data.HasSink = HasSink(Data.ToolDescs);
1962   Data.HasExterns = HasExterns(Data.OptDescs);
1963
1964   // Collect compilation graph edges.
1965   const RecordVector& CompilationGraphs =
1966     Records.getAllDerivedDefinitions("CompilationGraph");
1967   FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
1968                    Data.Edges);
1969
1970   // Calculate the priority of this plugin.
1971   const RecordVector& Priorities =
1972     Records.getAllDerivedDefinitions("PluginPriority");
1973   Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
1974 }
1975
1976 /// CheckPluginData - Perform some sanity checks on the collected data.
1977 void CheckPluginData(PluginData& Data) {
1978   // Filter out all tools not mentioned in the compilation graph.
1979   FilterNotInGraph(Data.Edges, Data.ToolDescs);
1980
1981   // Typecheck the compilation graph.
1982   TypecheckGraph(Data.Edges, Data.ToolDescs);
1983
1984   // Check that there are no options without side effects (specified
1985   // only in the OptionList).
1986   CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
1987
1988 }
1989
1990 void EmitPluginCode(const PluginData& Data, std::ostream& O) {
1991   // Emit file header.
1992   EmitIncludes(O);
1993
1994   // Emit global option registration code.
1995   EmitOptionDefintions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
1996
1997   // Emit hook declarations.
1998   EmitHookDeclarations(Data.ToolDescs, O);
1999
2000   O << "namespace {\n\n";
2001
2002   // Emit PopulateLanguageMap() function
2003   // (a language map maps from file extensions to language names).
2004   EmitPopulateLanguageMap(Records, O);
2005
2006   // Emit Tool classes.
2007   for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
2008          E = Data.ToolDescs.end(); B!=E; ++B)
2009     EmitToolClassDefinition(*(*B), Data.OptDescs, O);
2010
2011   // Emit Edge# classes.
2012   EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
2013
2014   // Emit PopulateCompilationGraph() function.
2015   EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
2016
2017   // Emit code for plugin registration.
2018   EmitRegisterPlugin(Data.Priority, O);
2019
2020   O << "} // End anonymous namespace.\n";
2021   // EOF
2022 }
2023
2024
2025 // End of anonymous namespace
2026 }
2027
2028 /// run - The back-end entry point.
2029 void LLVMCConfigurationEmitter::run (std::ostream &O) {
2030   try {
2031   PluginData Data;
2032
2033   CollectPluginData(Records, Data);
2034   CheckPluginData(Data);
2035
2036   EmitSourceFileHeader("LLVMC Configuration Library", O);
2037   EmitPluginCode(Data, O);
2038
2039   } catch (std::exception& Error) {
2040     throw Error.what() + std::string(" - usually this means a syntax error.");
2041   }
2042 }