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