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