1c7e5d0891fcecd92f00ff4a76c9dbbe1827e7f4
[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/StringMap.h"
19 #include "llvm/ADT/StringSet.h"
20
21 #include <algorithm>
22 #include <cassert>
23 #include <functional>
24 #include <stdexcept>
25 #include <string>
26 #include <typeinfo>
27
28 using namespace llvm;
29
30 namespace {
31
32 //===----------------------------------------------------------------------===//
33 /// Typedefs
34
35 typedef std::vector<Record*> RecordVector;
36 typedef std::vector<std::string> StrVector;
37
38 //===----------------------------------------------------------------------===//
39 /// Constants
40
41 // Indentation.
42 const unsigned TabWidth = 4;
43 const unsigned Indent1  = TabWidth*1;
44 const unsigned Indent2  = TabWidth*2;
45 const unsigned Indent3  = TabWidth*3;
46
47 // Default help string.
48 const char * const DefaultHelpString = "NO HELP MESSAGE PROVIDED";
49
50 // Name for the "sink" option.
51 const char * const SinkOptionName = "AutoGeneratedSinkOption";
52
53 //===----------------------------------------------------------------------===//
54 /// Helper functions
55
56 /// Id - An 'identity' function object.
57 struct Id {
58   template<typename T0>
59   void operator()(const T0&) const {
60   }
61   template<typename T0, typename T1>
62   void operator()(const T0&, const T1&) const {
63   }
64   template<typename T0, typename T1, typename T2>
65   void operator()(const T0&, const T1&, const T2&) const {
66   }
67 };
68
69 int InitPtrToInt(const Init* ptr) {
70   const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
71   return val.getValue();
72 }
73
74 const std::string& InitPtrToString(const Init* ptr) {
75   const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
76   return val.getValue();
77 }
78
79 const ListInit& InitPtrToList(const Init* ptr) {
80   const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
81   return val;
82 }
83
84 const DagInit& InitPtrToDag(const Init* ptr) {
85   const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
86   return val;
87 }
88
89 const std::string GetOperatorName(const DagInit& D) {
90   return D.getOperator()->getAsString();
91 }
92
93 /// CheckBooleanConstant - Check that the provided value is a boolean constant.
94 void CheckBooleanConstant(const Init* I) {
95   const DefInit& val = dynamic_cast<const DefInit&>(*I);
96   const std::string& str = val.getAsString();
97
98   if (str != "true" && str != "false") {
99     throw "Incorrect boolean value: '" + str +
100       "': must be either 'true' or 'false'";
101   }
102 }
103
104 // CheckNumberOfArguments - Ensure that the number of args in d is
105 // greater than or equal to min_arguments, otherwise throw an exception.
106 void CheckNumberOfArguments (const DagInit& d, unsigned minArgs) {
107   if (d.getNumArgs() < minArgs)
108     throw GetOperatorName(d) + ": too few arguments!";
109 }
110
111 // IsDagEmpty - is this DAG marked with an empty marker?
112 bool IsDagEmpty (const DagInit& d) {
113   return GetOperatorName(d) == "empty_dag_marker";
114 }
115
116 // EscapeVariableName - Escape commas and other symbols not allowed
117 // in the C++ variable names. Makes it possible to use options named
118 // like "Wa," (useful for prefix options).
119 std::string EscapeVariableName(const std::string& Var) {
120   std::string ret;
121   for (unsigned i = 0; i != Var.size(); ++i) {
122     char cur_char = Var[i];
123     if (cur_char == ',') {
124       ret += "_comma_";
125     }
126     else if (cur_char == '+') {
127       ret += "_plus_";
128     }
129     else if (cur_char == '-') {
130       ret += "_dash_";
131     }
132     else {
133       ret.push_back(cur_char);
134     }
135   }
136   return ret;
137 }
138
139 /// OneOf - Does the input string contain this character?
140 bool OneOf(const char* lst, char c) {
141   while (*lst) {
142     if (*lst++ == c)
143       return true;
144   }
145   return false;
146 }
147
148 template <class I, class S>
149 void CheckedIncrement(I& P, I E, S ErrorString) {
150   ++P;
151   if (P == E)
152     throw ErrorString;
153 }
154
155 // apply is needed because C++'s syntax doesn't let us construct a function
156 // object and call it in the same statement.
157 template<typename F, typename T0>
158 void apply(F Fun, T0& Arg0) {
159   return Fun(Arg0);
160 }
161
162 template<typename F, typename T0, typename T1>
163 void apply(F Fun, T0& Arg0, T1& Arg1) {
164   return Fun(Arg0, Arg1);
165 }
166
167 //===----------------------------------------------------------------------===//
168 /// Back-end specific code
169
170
171 /// OptionType - One of six different option types. See the
172 /// documentation for detailed description of differences.
173 namespace OptionType {
174
175   enum OptionType { Alias, Switch, Parameter, ParameterList,
176                     Prefix, PrefixList};
177
178   bool IsAlias(OptionType t) {
179     return (t == Alias);
180   }
181
182   bool IsList (OptionType t) {
183     return (t == ParameterList || t == PrefixList);
184   }
185
186   bool IsSwitch (OptionType t) {
187     return (t == Switch);
188   }
189
190   bool IsParameter (OptionType t) {
191     return (t == Parameter || t == Prefix);
192   }
193
194 }
195
196 OptionType::OptionType stringToOptionType(const std::string& T) {
197   if (T == "alias_option")
198     return OptionType::Alias;
199   else if (T == "switch_option")
200     return OptionType::Switch;
201   else if (T == "parameter_option")
202     return OptionType::Parameter;
203   else if (T == "parameter_list_option")
204     return OptionType::ParameterList;
205   else if (T == "prefix_option")
206     return OptionType::Prefix;
207   else if (T == "prefix_list_option")
208     return OptionType::PrefixList;
209   else
210     throw "Unknown option type: " + T + '!';
211 }
212
213 namespace OptionDescriptionFlags {
214   enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
215                                 ReallyHidden = 0x4, Extern = 0x8,
216                                 OneOrMore = 0x10, Optional = 0x20,
217                                 CommaSeparated = 0x40 };
218 }
219
220 /// OptionDescription - Represents data contained in a single
221 /// OptionList entry.
222 struct OptionDescription {
223   OptionType::OptionType Type;
224   std::string Name;
225   unsigned Flags;
226   std::string Help;
227   unsigned MultiVal;
228   Init* InitVal;
229
230   OptionDescription(OptionType::OptionType t = OptionType::Switch,
231                     const std::string& n = "",
232                     const std::string& h = DefaultHelpString)
233     : Type(t), Name(n), Flags(0x0), Help(h), MultiVal(1), InitVal(0)
234   {}
235
236   /// GenTypeDeclaration - Returns the C++ variable type of this
237   /// option.
238   const char* GenTypeDeclaration() const;
239
240   /// GenVariableName - Returns the variable name used in the
241   /// generated C++ code.
242   std::string GenVariableName() const;
243
244   /// Merge - Merge two option descriptions.
245   void Merge (const OptionDescription& other);
246
247   // Misc convenient getters/setters.
248
249   bool isAlias() const;
250
251   bool isMultiVal() const;
252
253   bool isCommaSeparated() const;
254   void setCommaSeparated();
255
256   bool isExtern() const;
257   void setExtern();
258
259   bool isRequired() const;
260   void setRequired();
261
262   bool isOneOrMore() const;
263   void setOneOrMore();
264
265   bool isOptional() const;
266   void setOptional();
267
268   bool isHidden() const;
269   void setHidden();
270
271   bool isReallyHidden() const;
272   void setReallyHidden();
273
274   bool isSwitch() const
275   { return OptionType::IsSwitch(this->Type); }
276
277   bool isParameter() const
278   { return OptionType::IsParameter(this->Type); }
279
280   bool isList() const
281   { return OptionType::IsList(this->Type); }
282
283 };
284
285 void OptionDescription::Merge (const OptionDescription& other)
286 {
287   if (other.Type != Type)
288     throw "Conflicting definitions for the option " + Name + "!";
289
290   if (Help == other.Help || Help == DefaultHelpString)
291     Help = other.Help;
292   else if (other.Help != DefaultHelpString) {
293     llvm::errs() << "Warning: several different help strings"
294       " defined for option " + Name + "\n";
295   }
296
297   Flags |= other.Flags;
298 }
299
300 bool OptionDescription::isAlias() const {
301   return OptionType::IsAlias(this->Type);
302 }
303
304 bool OptionDescription::isMultiVal() const {
305   return MultiVal > 1;
306 }
307
308 bool OptionDescription::isCommaSeparated() const {
309   return Flags & OptionDescriptionFlags::CommaSeparated;
310 }
311 void OptionDescription::setCommaSeparated() {
312   Flags |= OptionDescriptionFlags::CommaSeparated;
313 }
314
315 bool OptionDescription::isExtern() const {
316   return Flags & OptionDescriptionFlags::Extern;
317 }
318 void OptionDescription::setExtern() {
319   Flags |= OptionDescriptionFlags::Extern;
320 }
321
322 bool OptionDescription::isRequired() const {
323   return Flags & OptionDescriptionFlags::Required;
324 }
325 void OptionDescription::setRequired() {
326   Flags |= OptionDescriptionFlags::Required;
327 }
328
329 bool OptionDescription::isOneOrMore() const {
330   return Flags & OptionDescriptionFlags::OneOrMore;
331 }
332 void OptionDescription::setOneOrMore() {
333   Flags |= OptionDescriptionFlags::OneOrMore;
334 }
335
336 bool OptionDescription::isOptional() const {
337   return Flags & OptionDescriptionFlags::Optional;
338 }
339 void OptionDescription::setOptional() {
340   Flags |= OptionDescriptionFlags::Optional;
341 }
342
343 bool OptionDescription::isHidden() const {
344   return Flags & OptionDescriptionFlags::Hidden;
345 }
346 void OptionDescription::setHidden() {
347   Flags |= OptionDescriptionFlags::Hidden;
348 }
349
350 bool OptionDescription::isReallyHidden() const {
351   return Flags & OptionDescriptionFlags::ReallyHidden;
352 }
353 void OptionDescription::setReallyHidden() {
354   Flags |= OptionDescriptionFlags::ReallyHidden;
355 }
356
357 const char* OptionDescription::GenTypeDeclaration() const {
358   switch (Type) {
359   case OptionType::Alias:
360     return "cl::alias";
361   case OptionType::PrefixList:
362   case OptionType::ParameterList:
363     return "cl::list<std::string>";
364   case OptionType::Switch:
365     return "cl::opt<bool>";
366   case OptionType::Parameter:
367   case OptionType::Prefix:
368   default:
369     return "cl::opt<std::string>";
370   }
371 }
372
373 std::string OptionDescription::GenVariableName() const {
374   const std::string& EscapedName = EscapeVariableName(Name);
375   switch (Type) {
376   case OptionType::Alias:
377     return "AutoGeneratedAlias_" + EscapedName;
378   case OptionType::PrefixList:
379   case OptionType::ParameterList:
380     return "AutoGeneratedList_" + EscapedName;
381   case OptionType::Switch:
382     return "AutoGeneratedSwitch_" + EscapedName;
383   case OptionType::Prefix:
384   case OptionType::Parameter:
385   default:
386     return "AutoGeneratedParameter_" + EscapedName;
387   }
388 }
389
390 /// OptionDescriptions - An OptionDescription array plus some helper
391 /// functions.
392 class OptionDescriptions {
393   typedef StringMap<OptionDescription> container_type;
394
395   /// Descriptions - A list of OptionDescriptions.
396   container_type Descriptions;
397
398 public:
399   /// FindOption - exception-throwing wrapper for find().
400   const OptionDescription& FindOption(const std::string& OptName) const;
401
402   // Wrappers for FindOption that throw an exception in case the option has a
403   // wrong type.
404   const OptionDescription& FindSwitch(const std::string& OptName) const;
405   const OptionDescription& FindParameter(const std::string& OptName) const;
406   const OptionDescription& FindList(const std::string& OptName) const;
407   const OptionDescription&
408   FindListOrParameter(const std::string& OptName) const;
409
410   /// insertDescription - Insert new OptionDescription into
411   /// OptionDescriptions list
412   void InsertDescription (const OptionDescription& o);
413
414   // Support for STL-style iteration
415   typedef container_type::const_iterator const_iterator;
416   const_iterator begin() const { return Descriptions.begin(); }
417   const_iterator end() const { return Descriptions.end(); }
418 };
419
420 const OptionDescription&
421 OptionDescriptions::FindOption(const std::string& OptName) const {
422   const_iterator I = Descriptions.find(OptName);
423   if (I != Descriptions.end())
424     return I->second;
425   else
426     throw OptName + ": no such option!";
427 }
428
429 const OptionDescription&
430 OptionDescriptions::FindSwitch(const std::string& OptName) const {
431   const OptionDescription& OptDesc = this->FindOption(OptName);
432   if (!OptDesc.isSwitch())
433     throw OptName + ": incorrect option type - should be a switch!";
434   return OptDesc;
435 }
436
437 const OptionDescription&
438 OptionDescriptions::FindList(const std::string& OptName) const {
439   const OptionDescription& OptDesc = this->FindOption(OptName);
440   if (!OptDesc.isList())
441     throw OptName + ": incorrect option type - should be a list!";
442   return OptDesc;
443 }
444
445 const OptionDescription&
446 OptionDescriptions::FindParameter(const std::string& OptName) const {
447   const OptionDescription& OptDesc = this->FindOption(OptName);
448   if (!OptDesc.isParameter())
449     throw OptName + ": incorrect option type - should be a parameter!";
450   return OptDesc;
451 }
452
453 const OptionDescription&
454 OptionDescriptions::FindListOrParameter(const std::string& OptName) const {
455   const OptionDescription& OptDesc = this->FindOption(OptName);
456   if (!OptDesc.isList() && !OptDesc.isParameter())
457     throw OptName
458       + ": incorrect option type - should be a list or parameter!";
459   return OptDesc;
460 }
461
462 void OptionDescriptions::InsertDescription (const OptionDescription& o) {
463   container_type::iterator I = Descriptions.find(o.Name);
464   if (I != Descriptions.end()) {
465     OptionDescription& D = I->second;
466     D.Merge(o);
467   }
468   else {
469     Descriptions[o.Name] = o;
470   }
471 }
472
473 /// HandlerTable - A base class for function objects implemented as
474 /// 'tables of handlers'.
475 template <typename Handler>
476 class HandlerTable {
477 protected:
478   // Implementation details.
479
480   /// HandlerMap - A map from property names to property handlers
481   typedef StringMap<Handler> HandlerMap;
482
483   static HandlerMap Handlers_;
484   static bool staticMembersInitialized_;
485
486 public:
487
488   Handler GetHandler (const std::string& HandlerName) const {
489     typename HandlerMap::iterator method = Handlers_.find(HandlerName);
490
491     if (method != Handlers_.end()) {
492       Handler h = method->second;
493       return h;
494     }
495     else {
496       throw "No handler found for property " + HandlerName + "!";
497     }
498   }
499
500   void AddHandler(const char* Property, Handler H) {
501     Handlers_[Property] = H;
502   }
503
504 };
505
506 template <class Handler, class FunctionObject>
507 Handler GetHandler(FunctionObject* Obj, const DagInit& Dag) {
508   const std::string& HandlerName = GetOperatorName(Dag);
509   return Obj->GetHandler(HandlerName);
510 }
511
512 template <class FunctionObject>
513 void InvokeDagInitHandler(FunctionObject* Obj, Init* I) {
514   typedef void (FunctionObject::*Handler) (const DagInit&);
515
516   const DagInit& Dag = InitPtrToDag(I);
517   Handler h = GetHandler<Handler>(Obj, Dag);
518
519   ((Obj)->*(h))(Dag);
520 }
521
522 template <class FunctionObject>
523 void InvokeDagInitHandler(const FunctionObject* const Obj,
524                           const Init* I, unsigned IndentLevel, raw_ostream& O)
525 {
526   typedef void (FunctionObject::*Handler)
527     (const DagInit&, unsigned IndentLevel, raw_ostream& O) const;
528
529   const DagInit& Dag = InitPtrToDag(I);
530   Handler h = GetHandler<Handler>(Obj, Dag);
531
532   ((Obj)->*(h))(Dag, IndentLevel, O);
533 }
534
535
536 template <typename H>
537 typename HandlerTable<H>::HandlerMap HandlerTable<H>::Handlers_;
538
539 template <typename H>
540 bool HandlerTable<H>::staticMembersInitialized_ = false;
541
542
543 /// CollectOptionProperties - Function object for iterating over an
544 /// option property list.
545 class CollectOptionProperties;
546 typedef void (CollectOptionProperties::* CollectOptionPropertiesHandler)
547 (const DagInit&);
548
549 class CollectOptionProperties
550 : public HandlerTable<CollectOptionPropertiesHandler>
551 {
552 private:
553
554   /// optDescs_ - OptionDescriptions table. This is where the
555   /// information is stored.
556   OptionDescription& optDesc_;
557
558 public:
559
560   explicit CollectOptionProperties(OptionDescription& OD)
561     : optDesc_(OD)
562   {
563     if (!staticMembersInitialized_) {
564       AddHandler("extern", &CollectOptionProperties::onExtern);
565       AddHandler("help", &CollectOptionProperties::onHelp);
566       AddHandler("hidden", &CollectOptionProperties::onHidden);
567       AddHandler("init", &CollectOptionProperties::onInit);
568       AddHandler("multi_val", &CollectOptionProperties::onMultiVal);
569       AddHandler("one_or_more", &CollectOptionProperties::onOneOrMore);
570       AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
571       AddHandler("required", &CollectOptionProperties::onRequired);
572       AddHandler("optional", &CollectOptionProperties::onOptional);
573       AddHandler("comma_separated", &CollectOptionProperties::onCommaSeparated);
574
575       staticMembersInitialized_ = true;
576     }
577   }
578
579   /// operator() - Just forwards to the corresponding property
580   /// handler.
581   void operator() (Init* I) {
582     InvokeDagInitHandler(this, I);
583   }
584
585 private:
586
587   /// Option property handlers --
588   /// Methods that handle option properties such as (help) or (hidden).
589
590   void onExtern (const DagInit& d) {
591     CheckNumberOfArguments(d, 0);
592     optDesc_.setExtern();
593   }
594
595   void onHelp (const DagInit& d) {
596     CheckNumberOfArguments(d, 1);
597     optDesc_.Help = InitPtrToString(d.getArg(0));
598   }
599
600   void onHidden (const DagInit& d) {
601     CheckNumberOfArguments(d, 0);
602     optDesc_.setHidden();
603   }
604
605   void onReallyHidden (const DagInit& d) {
606     CheckNumberOfArguments(d, 0);
607     optDesc_.setReallyHidden();
608   }
609
610   void onCommaSeparated (const DagInit& d) {
611     CheckNumberOfArguments(d, 0);
612     if (!optDesc_.isList())
613       throw "'comma_separated' is valid only on list options!";
614     optDesc_.setCommaSeparated();
615   }
616
617   void onRequired (const DagInit& d) {
618     CheckNumberOfArguments(d, 0);
619     if (optDesc_.isOneOrMore() || optDesc_.isOptional())
620       throw "Only one of (required), (optional) or "
621         "(one_or_more) properties is allowed!";
622     optDesc_.setRequired();
623   }
624
625   void onInit (const DagInit& d) {
626     CheckNumberOfArguments(d, 1);
627     Init* i = d.getArg(0);
628     const std::string& str = i->getAsString();
629
630     bool correct = optDesc_.isParameter() && dynamic_cast<StringInit*>(i);
631     correct |= (optDesc_.isSwitch() && (str == "true" || str == "false"));
632
633     if (!correct)
634       throw "Incorrect usage of the 'init' option property!";
635
636     optDesc_.InitVal = i;
637   }
638
639   void onOneOrMore (const DagInit& d) {
640     CheckNumberOfArguments(d, 0);
641     if (optDesc_.isRequired() || optDesc_.isOptional())
642       throw "Only one of (required), (optional) or "
643         "(one_or_more) properties is allowed!";
644     if (!OptionType::IsList(optDesc_.Type))
645       llvm::errs() << "Warning: specifying the 'one_or_more' property "
646         "on a non-list option will have no effect.\n";
647     optDesc_.setOneOrMore();
648   }
649
650   void onOptional (const DagInit& d) {
651     CheckNumberOfArguments(d, 0);
652     if (optDesc_.isRequired() || optDesc_.isOneOrMore())
653       throw "Only one of (required), (optional) or "
654         "(one_or_more) properties is allowed!";
655     if (!OptionType::IsList(optDesc_.Type))
656       llvm::errs() << "Warning: specifying the 'optional' property"
657         "on a non-list option will have no effect.\n";
658     optDesc_.setOptional();
659   }
660
661   void onMultiVal (const DagInit& d) {
662     CheckNumberOfArguments(d, 1);
663     int val = InitPtrToInt(d.getArg(0));
664     if (val < 2)
665       throw "Error in the 'multi_val' property: "
666         "the value must be greater than 1!";
667     if (!OptionType::IsList(optDesc_.Type))
668       throw "The multi_val property is valid only on list options!";
669     optDesc_.MultiVal = val;
670   }
671
672 };
673
674 /// AddOption - A function object that is applied to every option
675 /// description. Used by CollectOptionDescriptions.
676 class AddOption {
677 private:
678   OptionDescriptions& OptDescs_;
679
680 public:
681   explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
682   {}
683
684   void operator()(const Init* i) {
685     const DagInit& d = InitPtrToDag(i);
686     CheckNumberOfArguments(d, 1);
687
688     const OptionType::OptionType Type =
689       stringToOptionType(GetOperatorName(d));
690     const std::string& Name = InitPtrToString(d.getArg(0));
691
692     OptionDescription OD(Type, Name);
693
694     if (!OD.isExtern())
695       CheckNumberOfArguments(d, 2);
696
697     if (OD.isAlias()) {
698       // Aliases store the aliased option name in the 'Help' field.
699       OD.Help = InitPtrToString(d.getArg(1));
700     }
701     else if (!OD.isExtern()) {
702       processOptionProperties(d, OD);
703     }
704     OptDescs_.InsertDescription(OD);
705   }
706
707 private:
708   /// processOptionProperties - Go through the list of option
709   /// properties and call a corresponding handler for each.
710   static void processOptionProperties (const DagInit& d, OptionDescription& o) {
711     CheckNumberOfArguments(d, 2);
712     DagInit::const_arg_iterator B = d.arg_begin();
713     // Skip the first argument: it's always the option name.
714     ++B;
715     std::for_each(B, d.arg_end(), CollectOptionProperties(o));
716   }
717
718 };
719
720 /// CollectOptionDescriptions - Collects option properties from all
721 /// OptionLists.
722 void CollectOptionDescriptions (RecordVector::const_iterator B,
723                                 RecordVector::const_iterator E,
724                                 OptionDescriptions& OptDescs)
725 {
726   // For every OptionList:
727   for (; B!=E; ++B) {
728     RecordVector::value_type T = *B;
729     // Throws an exception if the value does not exist.
730     ListInit* PropList = T->getValueAsListInit("options");
731
732     // For every option description in this list:
733     // collect the information and
734     std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
735   }
736 }
737
738 // Tool information record
739
740 namespace ToolFlags {
741   enum ToolFlags { Join = 0x1, Sink = 0x2 };
742 }
743
744 struct ToolDescription : public RefCountedBase<ToolDescription> {
745   std::string Name;
746   Init* CmdLine;
747   Init* Actions;
748   StrVector InLanguage;
749   std::string OutLanguage;
750   std::string OutputSuffix;
751   unsigned Flags;
752
753   // Various boolean properties
754   void setSink()      { Flags |= ToolFlags::Sink; }
755   bool isSink() const { return Flags & ToolFlags::Sink; }
756   void setJoin()      { Flags |= ToolFlags::Join; }
757   bool isJoin() const { return Flags & ToolFlags::Join; }
758
759   // Default ctor here is needed because StringMap can only store
760   // DefaultConstructible objects
761   ToolDescription() : CmdLine(0), Actions(0), Flags(0) {}
762   ToolDescription (const std::string& n)
763   : Name(n), CmdLine(0), Actions(0), Flags(0)
764   {}
765 };
766
767 /// ToolDescriptions - A list of Tool information records.
768 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
769
770
771 /// CollectToolProperties - Function object for iterating over a list of
772 /// tool property records.
773
774 class CollectToolProperties;
775 typedef void (CollectToolProperties::* CollectToolPropertiesHandler)
776 (const DagInit&);
777
778 class CollectToolProperties : public HandlerTable<CollectToolPropertiesHandler>
779 {
780 private:
781
782   /// toolDesc_ - Properties of the current Tool. This is where the
783   /// information is stored.
784   ToolDescription& toolDesc_;
785
786 public:
787
788   explicit CollectToolProperties (ToolDescription& d)
789     : toolDesc_(d)
790   {
791     if (!staticMembersInitialized_) {
792
793       AddHandler("actions", &CollectToolProperties::onActions);
794       AddHandler("cmd_line", &CollectToolProperties::onCmdLine);
795       AddHandler("in_language", &CollectToolProperties::onInLanguage);
796       AddHandler("join", &CollectToolProperties::onJoin);
797       AddHandler("out_language", &CollectToolProperties::onOutLanguage);
798       AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
799       AddHandler("sink", &CollectToolProperties::onSink);
800
801       staticMembersInitialized_ = true;
802     }
803   }
804
805   void operator() (Init* I) {
806     InvokeDagInitHandler(this, I);
807   }
808
809 private:
810
811   /// Property handlers --
812   /// Functions that extract information about tool properties from
813   /// DAG representation.
814
815   void onActions (const DagInit& d) {
816     CheckNumberOfArguments(d, 1);
817     Init* Case = d.getArg(0);
818     if (typeid(*Case) != typeid(DagInit) ||
819         GetOperatorName(static_cast<DagInit&>(*Case)) != "case")
820       throw "The argument to (actions) should be a 'case' construct!";
821     toolDesc_.Actions = Case;
822   }
823
824   void onCmdLine (const DagInit& d) {
825     CheckNumberOfArguments(d, 1);
826     toolDesc_.CmdLine = d.getArg(0);
827   }
828
829   void onInLanguage (const DagInit& d) {
830     CheckNumberOfArguments(d, 1);
831     Init* arg = d.getArg(0);
832
833     // Find out the argument's type.
834     if (typeid(*arg) == typeid(StringInit)) {
835       // It's a string.
836       toolDesc_.InLanguage.push_back(InitPtrToString(arg));
837     }
838     else {
839       // It's a list.
840       const ListInit& lst = InitPtrToList(arg);
841       StrVector& out = toolDesc_.InLanguage;
842
843       // Copy strings to the output vector.
844       for (ListInit::const_iterator B = lst.begin(), E = lst.end();
845            B != E; ++B) {
846         out.push_back(InitPtrToString(*B));
847       }
848
849       // Remove duplicates.
850       std::sort(out.begin(), out.end());
851       StrVector::iterator newE = std::unique(out.begin(), out.end());
852       out.erase(newE, out.end());
853     }
854   }
855
856   void onJoin (const DagInit& d) {
857     CheckNumberOfArguments(d, 0);
858     toolDesc_.setJoin();
859   }
860
861   void onOutLanguage (const DagInit& d) {
862     CheckNumberOfArguments(d, 1);
863     toolDesc_.OutLanguage = InitPtrToString(d.getArg(0));
864   }
865
866   void onOutputSuffix (const DagInit& d) {
867     CheckNumberOfArguments(d, 1);
868     toolDesc_.OutputSuffix = InitPtrToString(d.getArg(0));
869   }
870
871   void onSink (const DagInit& d) {
872     CheckNumberOfArguments(d, 0);
873     toolDesc_.setSink();
874   }
875
876 };
877
878 /// CollectToolDescriptions - Gather information about tool properties
879 /// from the parsed TableGen data (basically a wrapper for the
880 /// CollectToolProperties function object).
881 void CollectToolDescriptions (RecordVector::const_iterator B,
882                               RecordVector::const_iterator E,
883                               ToolDescriptions& ToolDescs)
884 {
885   // Iterate over a properties list of every Tool definition
886   for (;B!=E;++B) {
887     const Record* T = *B;
888     // Throws an exception if the value does not exist.
889     ListInit* PropList = T->getValueAsListInit("properties");
890
891     IntrusiveRefCntPtr<ToolDescription>
892       ToolDesc(new ToolDescription(T->getName()));
893
894     std::for_each(PropList->begin(), PropList->end(),
895                   CollectToolProperties(*ToolDesc));
896     ToolDescs.push_back(ToolDesc);
897   }
898 }
899
900 /// FillInEdgeVector - Merge all compilation graph definitions into
901 /// one single edge list.
902 void FillInEdgeVector(RecordVector::const_iterator B,
903                       RecordVector::const_iterator E, RecordVector& Out) {
904   for (; B != E; ++B) {
905     const ListInit* edges = (*B)->getValueAsListInit("edges");
906
907     for (unsigned i = 0; i < edges->size(); ++i)
908       Out.push_back(edges->getElementAsRecord(i));
909   }
910 }
911
912 /// CalculatePriority - Calculate the priority of this plugin.
913 int CalculatePriority(RecordVector::const_iterator B,
914                       RecordVector::const_iterator E) {
915   int priority = 0;
916
917   if (B != E) {
918     priority  = static_cast<int>((*B)->getValueAsInt("priority"));
919
920     if (++B != E)
921       throw "More than one 'PluginPriority' instance found: "
922         "most probably an error!";
923   }
924
925   return priority;
926 }
927
928 /// NotInGraph - Helper function object for FilterNotInGraph.
929 struct NotInGraph {
930 private:
931   const llvm::StringSet<>& ToolsInGraph_;
932
933 public:
934   NotInGraph(const llvm::StringSet<>& ToolsInGraph)
935   : ToolsInGraph_(ToolsInGraph)
936   {}
937
938   bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
939     return (ToolsInGraph_.count(x->Name) == 0);
940   }
941 };
942
943 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
944 /// mentioned in the compilation graph definition.
945 void FilterNotInGraph (const RecordVector& EdgeVector,
946                        ToolDescriptions& ToolDescs) {
947
948   // List all tools mentioned in the graph.
949   llvm::StringSet<> ToolsInGraph;
950
951   for (RecordVector::const_iterator B = EdgeVector.begin(),
952          E = EdgeVector.end(); B != E; ++B) {
953
954     const Record* Edge = *B;
955     const std::string& NodeA = Edge->getValueAsString("a");
956     const std::string& NodeB = Edge->getValueAsString("b");
957
958     if (NodeA != "root")
959       ToolsInGraph.insert(NodeA);
960     ToolsInGraph.insert(NodeB);
961   }
962
963   // Filter ToolPropertiesList.
964   ToolDescriptions::iterator new_end =
965     std::remove_if(ToolDescs.begin(), ToolDescs.end(),
966                    NotInGraph(ToolsInGraph));
967   ToolDescs.erase(new_end, ToolDescs.end());
968 }
969
970 /// FillInToolToLang - Fills in two tables that map tool names to
971 /// (input, output) languages.  Helper function used by TypecheckGraph().
972 void FillInToolToLang (const ToolDescriptions& ToolDescs,
973                        StringMap<StringSet<> >& ToolToInLang,
974                        StringMap<std::string>& ToolToOutLang) {
975   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
976          E = ToolDescs.end(); B != E; ++B) {
977     const ToolDescription& D = *(*B);
978     for (StrVector::const_iterator B = D.InLanguage.begin(),
979            E = D.InLanguage.end(); B != E; ++B)
980       ToolToInLang[D.Name].insert(*B);
981     ToolToOutLang[D.Name] = D.OutLanguage;
982   }
983 }
984
985 /// TypecheckGraph - Check that names for output and input languages
986 /// on all edges do match. This doesn't do much when the information
987 /// about the whole graph is not available (i.e. when compiling most
988 /// plugins).
989 void TypecheckGraph (const RecordVector& EdgeVector,
990                      const ToolDescriptions& ToolDescs) {
991   StringMap<StringSet<> > ToolToInLang;
992   StringMap<std::string> ToolToOutLang;
993
994   FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
995   StringMap<std::string>::iterator IAE = ToolToOutLang.end();
996   StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
997
998   for (RecordVector::const_iterator B = EdgeVector.begin(),
999          E = EdgeVector.end(); B != E; ++B) {
1000     const Record* Edge = *B;
1001     const std::string& NodeA = Edge->getValueAsString("a");
1002     const std::string& NodeB = Edge->getValueAsString("b");
1003     StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
1004     StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
1005
1006     if (NodeA != "root") {
1007       if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
1008         throw "Edge " + NodeA + "->" + NodeB
1009           + ": output->input language mismatch";
1010     }
1011
1012     if (NodeB == "root")
1013       throw "Edges back to the root are not allowed!";
1014   }
1015 }
1016
1017 /// WalkCase - Walks the 'case' expression DAG and invokes
1018 /// TestCallback on every test, and StatementCallback on every
1019 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
1020 /// combinators (that is, they are passed directly to TestCallback).
1021 /// TestCallback must have type 'void TestCallback(const DagInit*, unsigned
1022 /// IndentLevel, bool FirstTest)'.
1023 /// StatementCallback must have type 'void StatementCallback(const Init*,
1024 /// unsigned IndentLevel)'.
1025 template <typename F1, typename F2>
1026 void WalkCase(const Init* Case, F1 TestCallback, F2 StatementCallback,
1027               unsigned IndentLevel = 0)
1028 {
1029   const DagInit& d = InitPtrToDag(Case);
1030
1031   // Error checks.
1032   if (GetOperatorName(d) != "case")
1033     throw "WalkCase should be invoked only on 'case' expressions!";
1034
1035   if (d.getNumArgs() < 2)
1036     throw "There should be at least one clause in the 'case' expression:\n"
1037       + d.getAsString();
1038
1039   // Main loop.
1040   bool even = false;
1041   const unsigned numArgs = d.getNumArgs();
1042   unsigned i = 1;
1043   for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1044        B != E; ++B) {
1045     Init* arg = *B;
1046
1047     if (!even)
1048     {
1049       // Handle test.
1050       const DagInit& Test = InitPtrToDag(arg);
1051
1052       if (GetOperatorName(Test) == "default" && (i+1 != numArgs))
1053         throw "The 'default' clause should be the last in the "
1054           "'case' construct!";
1055       if (i == numArgs)
1056         throw "Case construct handler: no corresponding action "
1057           "found for the test " + Test.getAsString() + '!';
1058
1059       TestCallback(Test, IndentLevel, (i == 1));
1060     }
1061     else
1062     {
1063       if (dynamic_cast<DagInit*>(arg)
1064           && GetOperatorName(static_cast<DagInit&>(*arg)) == "case") {
1065         // Nested 'case'.
1066         WalkCase(arg, TestCallback, StatementCallback, IndentLevel + Indent1);
1067       }
1068
1069       // Handle statement.
1070       StatementCallback(arg, IndentLevel);
1071     }
1072
1073     ++i;
1074     even = !even;
1075   }
1076 }
1077
1078 /// ExtractOptionNames - A helper function object used by
1079 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
1080 class ExtractOptionNames {
1081   llvm::StringSet<>& OptionNames_;
1082
1083   void processDag(const Init* Statement) {
1084     const DagInit& Stmt = InitPtrToDag(Statement);
1085     const std::string& ActionName = GetOperatorName(Stmt);
1086     if (ActionName == "forward" || ActionName == "forward_as" ||
1087         ActionName == "forward_value" ||
1088         ActionName == "forward_transformed_value" ||
1089         ActionName == "switch_on" || ActionName == "parameter_equals" ||
1090         ActionName == "element_in_list" || ActionName == "not_empty" ||
1091         ActionName == "empty") {
1092       CheckNumberOfArguments(Stmt, 1);
1093       const std::string& Name = InitPtrToString(Stmt.getArg(0));
1094       OptionNames_.insert(Name);
1095     }
1096     else if (ActionName == "and" || ActionName == "or") {
1097       for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
1098         this->processDag(Stmt.getArg(i));
1099       }
1100     }
1101   }
1102
1103 public:
1104   ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
1105   {}
1106
1107   void operator()(const Init* Statement) {
1108     if (typeid(*Statement) == typeid(ListInit)) {
1109       const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1110       for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1111            B != E; ++B)
1112         this->processDag(*B);
1113     }
1114     else {
1115       this->processDag(Statement);
1116     }
1117   }
1118
1119   void operator()(const DagInit& Test, unsigned, bool) {
1120     this->operator()(&Test);
1121   }
1122   void operator()(const Init* Statement, unsigned) {
1123     this->operator()(Statement);
1124   }
1125 };
1126
1127 /// CheckForSuperfluousOptions - Check that there are no side
1128 /// effect-free options (specified only in the OptionList). Otherwise,
1129 /// output a warning.
1130 void CheckForSuperfluousOptions (const RecordVector& Edges,
1131                                  const ToolDescriptions& ToolDescs,
1132                                  const OptionDescriptions& OptDescs) {
1133   llvm::StringSet<> nonSuperfluousOptions;
1134
1135   // Add all options mentioned in the ToolDesc.Actions to the set of
1136   // non-superfluous options.
1137   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1138          E = ToolDescs.end(); B != E; ++B) {
1139     const ToolDescription& TD = *(*B);
1140     ExtractOptionNames Callback(nonSuperfluousOptions);
1141     if (TD.Actions)
1142       WalkCase(TD.Actions, Callback, Callback);
1143   }
1144
1145   // Add all options mentioned in the 'case' clauses of the
1146   // OptionalEdges of the compilation graph to the set of
1147   // non-superfluous options.
1148   for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
1149        B != E; ++B) {
1150     const Record* Edge = *B;
1151     DagInit& Weight = *Edge->getValueAsDag("weight");
1152
1153     if (!IsDagEmpty(Weight))
1154       WalkCase(&Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
1155   }
1156
1157   // Check that all options in OptDescs belong to the set of
1158   // non-superfluous options.
1159   for (OptionDescriptions::const_iterator B = OptDescs.begin(),
1160          E = OptDescs.end(); B != E; ++B) {
1161     const OptionDescription& Val = B->second;
1162     if (!nonSuperfluousOptions.count(Val.Name)
1163         && Val.Type != OptionType::Alias)
1164       llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! "
1165         "Probable cause: this option is specified only in the OptionList.\n";
1166   }
1167 }
1168
1169 /// EmitCaseTest0Args - Helper function used by EmitCaseConstructHandler().
1170 bool EmitCaseTest0Args(const std::string& TestName, raw_ostream& O) {
1171   if (TestName == "single_input_file") {
1172     O << "InputFilenames.size() == 1";
1173     return true;
1174   }
1175   else if (TestName == "multiple_input_files") {
1176     O << "InputFilenames.size() > 1";
1177     return true;
1178   }
1179
1180   return false;
1181 }
1182
1183 /// EmitListTest - Helper function used by EmitCaseTest1ArgList().
1184 template <typename F>
1185 void EmitListTest(const ListInit& L, const char* LogicOp,
1186                   F Callback, raw_ostream& O)
1187 {
1188   // This is a lot like EmitLogicalOperationTest, but works on ListInits instead
1189   // of Dags...
1190   bool isFirst = true;
1191   for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B) {
1192     if (isFirst)
1193       isFirst = false;
1194     else
1195       O << " || ";
1196     Callback(InitPtrToString(*B), O);
1197   }
1198 }
1199
1200 // Callbacks for use with EmitListTest.
1201
1202 class EmitSwitchOn {
1203   const OptionDescriptions& OptDescs_;
1204 public:
1205   EmitSwitchOn(const OptionDescriptions& OptDescs) : OptDescs_(OptDescs)
1206   {}
1207
1208   void operator()(const std::string& OptName, raw_ostream& O) const {
1209     const OptionDescription& OptDesc = OptDescs_.FindSwitch(OptName);
1210     O << OptDesc.GenVariableName();
1211   }
1212 };
1213
1214 class EmitEmptyTest {
1215   bool EmitNegate_;
1216   const OptionDescriptions& OptDescs_;
1217 public:
1218   EmitEmptyTest(bool EmitNegate, const OptionDescriptions& OptDescs)
1219     : EmitNegate_(EmitNegate), OptDescs_(OptDescs)
1220   {}
1221
1222   void operator()(const std::string& OptName, raw_ostream& O) const {
1223     const char* Neg = (EmitNegate_ ? "!" : "");
1224     if (OptName == "o") {
1225       O << Neg << "OutputFilename.empty()";
1226     }
1227     else if (OptName == "save-temps") {
1228       O << Neg << "(SaveTemps == SaveTempsEnum::Unset)";
1229     }
1230     else {
1231       const OptionDescription& OptDesc = OptDescs_.FindListOrParameter(OptName);
1232       O << Neg << OptDesc.GenVariableName() << ".empty()";
1233     }
1234   }
1235 };
1236
1237
1238 /// EmitCaseTest1ArgList - Helper function used by EmitCaseTest1Arg();
1239 bool EmitCaseTest1ArgList(const std::string& TestName,
1240                           const DagInit& d,
1241                           const OptionDescriptions& OptDescs,
1242                           raw_ostream& O) {
1243   const ListInit& L = *static_cast<ListInit*>(d.getArg(0));
1244
1245   if (TestName == "any_switch_on") {
1246     EmitListTest(L, "||", EmitSwitchOn(OptDescs), O);
1247     return true;
1248   }
1249   else if (TestName == "switch_on") {
1250     EmitListTest(L, "&&", EmitSwitchOn(OptDescs), O);
1251     return true;
1252   }
1253   else if (TestName == "any_not_empty") {
1254     EmitListTest(L, "||", EmitEmptyTest(true, OptDescs), O);
1255     return true;
1256   }
1257   else if (TestName == "any_empty") {
1258     EmitListTest(L, "||", EmitEmptyTest(false, OptDescs), O);
1259     return true;
1260   }
1261   else if (TestName == "not_empty") {
1262     EmitListTest(L, "&&", EmitEmptyTest(true, OptDescs), O);
1263     return true;
1264   }
1265   else if (TestName == "empty") {
1266     EmitListTest(L, "&&", EmitEmptyTest(false, OptDescs), O);
1267     return true;
1268   }
1269
1270   return false;
1271 }
1272
1273 /// EmitCaseTest1ArgStr - Helper function used by EmitCaseTest1Arg();
1274 bool EmitCaseTest1ArgStr(const std::string& TestName,
1275                          const DagInit& d,
1276                          const OptionDescriptions& OptDescs,
1277                          raw_ostream& O) {
1278   const std::string& OptName = InitPtrToString(d.getArg(0));
1279
1280   if (TestName == "switch_on") {
1281     apply(EmitSwitchOn(OptDescs), OptName, O);
1282     return true;
1283   }
1284   else if (TestName == "input_languages_contain") {
1285     O << "InLangs.count(\"" << OptName << "\") != 0";
1286     return true;
1287   }
1288   else if (TestName == "in_language") {
1289     // This works only for single-argument Tool::GenerateAction. Join
1290     // tools can process several files in different languages simultaneously.
1291
1292     // TODO: make this work with Edge::Weight (if possible).
1293     O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
1294     return true;
1295   }
1296   else if (TestName == "not_empty" || TestName == "empty") {
1297     bool EmitNegate = (TestName == "not_empty");
1298     apply(EmitEmptyTest(EmitNegate, OptDescs), OptName, O);
1299     return true;
1300   }
1301
1302   return false;
1303 }
1304
1305 /// EmitCaseTest1Arg - Helper function used by EmitCaseConstructHandler();
1306 bool EmitCaseTest1Arg(const std::string& TestName,
1307                       const DagInit& d,
1308                       const OptionDescriptions& OptDescs,
1309                       raw_ostream& O) {
1310   CheckNumberOfArguments(d, 1);
1311   if (typeid(*d.getArg(0)) == typeid(ListInit))
1312     return EmitCaseTest1ArgList(TestName, d, OptDescs, O);
1313   else
1314     return EmitCaseTest1ArgStr(TestName, d, OptDescs, O);
1315 }
1316
1317 /// EmitCaseTest2Args - Helper function used by EmitCaseConstructHandler().
1318 bool EmitCaseTest2Args(const std::string& TestName,
1319                        const DagInit& d,
1320                        unsigned IndentLevel,
1321                        const OptionDescriptions& OptDescs,
1322                        raw_ostream& O) {
1323   CheckNumberOfArguments(d, 2);
1324   const std::string& OptName = InitPtrToString(d.getArg(0));
1325   const std::string& OptArg = InitPtrToString(d.getArg(1));
1326
1327   if (TestName == "parameter_equals") {
1328     const OptionDescription& OptDesc = OptDescs.FindParameter(OptName);
1329     O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
1330     return true;
1331   }
1332   else if (TestName == "element_in_list") {
1333     const OptionDescription& OptDesc = OptDescs.FindList(OptName);
1334     const std::string& VarName = OptDesc.GenVariableName();
1335     O << "std::find(" << VarName << ".begin(),\n";
1336     O.indent(IndentLevel + Indent1)
1337       << VarName << ".end(), \""
1338       << OptArg << "\") != " << VarName << ".end()";
1339     return true;
1340   }
1341
1342   return false;
1343 }
1344
1345 // Forward declaration.
1346 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
1347 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1348                   const OptionDescriptions& OptDescs,
1349                   raw_ostream& O);
1350
1351 /// EmitLogicalOperationTest - Helper function used by
1352 /// EmitCaseConstructHandler.
1353 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
1354                               unsigned IndentLevel,
1355                               const OptionDescriptions& OptDescs,
1356                               raw_ostream& O) {
1357   O << '(';
1358   for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
1359     const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
1360     EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1361     if (j != NumArgs - 1) {
1362       O << ")\n";
1363       O.indent(IndentLevel + Indent1) << ' ' << LogicOp << " (";
1364     }
1365     else {
1366       O << ')';
1367     }
1368   }
1369 }
1370
1371 void EmitLogicalNot(const DagInit& d, unsigned IndentLevel,
1372                     const OptionDescriptions& OptDescs, raw_ostream& O)
1373 {
1374   CheckNumberOfArguments(d, 1);
1375   const DagInit& InnerTest = InitPtrToDag(d.getArg(0));
1376   O << "! (";
1377   EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1378   O << ")";
1379 }
1380
1381 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
1382 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1383                   const OptionDescriptions& OptDescs,
1384                   raw_ostream& O) {
1385   const std::string& TestName = GetOperatorName(d);
1386
1387   if (TestName == "and")
1388     EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
1389   else if (TestName == "or")
1390     EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
1391   else if (TestName == "not")
1392     EmitLogicalNot(d, IndentLevel, OptDescs, O);
1393   else if (EmitCaseTest0Args(TestName, O))
1394     return;
1395   else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
1396     return;
1397   else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
1398     return;
1399   else
1400     throw "Unknown test '" + TestName + "' used in the 'case' construct!";
1401 }
1402
1403
1404 /// EmitCaseTestCallback - Callback used by EmitCaseConstructHandler.
1405 class EmitCaseTestCallback {
1406   bool EmitElseIf_;
1407   const OptionDescriptions& OptDescs_;
1408   raw_ostream& O_;
1409 public:
1410
1411   EmitCaseTestCallback(bool EmitElseIf,
1412                        const OptionDescriptions& OptDescs, raw_ostream& O)
1413     : EmitElseIf_(EmitElseIf), OptDescs_(OptDescs), O_(O)
1414   {}
1415
1416   void operator()(const DagInit& Test, unsigned IndentLevel, bool FirstTest)
1417   {
1418     if (GetOperatorName(Test) == "default") {
1419       O_.indent(IndentLevel) << "else {\n";
1420     }
1421     else {
1422       O_.indent(IndentLevel)
1423         << ((!FirstTest && EmitElseIf_) ? "else if (" : "if (");
1424       EmitCaseTest(Test, IndentLevel, OptDescs_, O_);
1425       O_ << ") {\n";
1426     }
1427   }
1428 };
1429
1430 /// EmitCaseStatementCallback - Callback used by EmitCaseConstructHandler.
1431 template <typename F>
1432 class EmitCaseStatementCallback {
1433   F Callback_;
1434   raw_ostream& O_;
1435 public:
1436
1437   EmitCaseStatementCallback(F Callback, raw_ostream& O)
1438     : Callback_(Callback), O_(O)
1439   {}
1440
1441   void operator() (const Init* Statement, unsigned IndentLevel) {
1442
1443     // Ignore nested 'case' DAG.
1444     if (!(dynamic_cast<const DagInit*>(Statement) &&
1445           GetOperatorName(static_cast<const DagInit&>(*Statement)) == "case")) {
1446       if (typeid(*Statement) == typeid(ListInit)) {
1447         const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1448         for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1449              B != E; ++B)
1450           Callback_(*B, (IndentLevel + Indent1), O_);
1451       }
1452       else {
1453         Callback_(Statement, (IndentLevel + Indent1), O_);
1454       }
1455     }
1456     O_.indent(IndentLevel) << "}\n";
1457   }
1458
1459 };
1460
1461 /// EmitCaseConstructHandler - Emit code that handles the 'case'
1462 /// construct. Takes a function object that should emit code for every case
1463 /// clause. Implemented on top of WalkCase.
1464 /// Callback's type is void F(Init* Statement, unsigned IndentLevel,
1465 /// raw_ostream& O).
1466 /// EmitElseIf parameter controls the type of condition that is emitted ('if
1467 /// (..) {..} else if (..) {} .. else {..}' vs. 'if (..) {..} if(..)  {..}
1468 /// .. else {..}').
1469 template <typename F>
1470 void EmitCaseConstructHandler(const Init* Case, unsigned IndentLevel,
1471                               F Callback, bool EmitElseIf,
1472                               const OptionDescriptions& OptDescs,
1473                               raw_ostream& O) {
1474   WalkCase(Case, EmitCaseTestCallback(EmitElseIf, OptDescs, O),
1475            EmitCaseStatementCallback<F>(Callback, O), IndentLevel);
1476 }
1477
1478 /// TokenizeCmdLine - converts from
1479 /// "$CALL(HookName, 'Arg1', 'Arg2')/path -arg1 -arg2" to
1480 /// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path", "-arg1", "-arg2"].
1481 void TokenizeCmdLine(const std::string& CmdLine, StrVector& Out) {
1482   const char* Delimiters = " \t\n\v\f\r";
1483   enum TokenizerState
1484   { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1485   cur_st  = Normal;
1486
1487   if (CmdLine.empty())
1488     return;
1489   Out.push_back("");
1490
1491   std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1492     E = CmdLine.size();
1493
1494   for (; B != E; ++B) {
1495     char cur_ch = CmdLine[B];
1496
1497     switch (cur_st) {
1498     case Normal:
1499       if (cur_ch == '$') {
1500         cur_st = SpecialCommand;
1501         break;
1502       }
1503       if (OneOf(Delimiters, cur_ch)) {
1504         // Skip whitespace
1505         B = CmdLine.find_first_not_of(Delimiters, B);
1506         if (B == std::string::npos) {
1507           B = E-1;
1508           continue;
1509         }
1510         --B;
1511         Out.push_back("");
1512         continue;
1513       }
1514       break;
1515
1516
1517     case SpecialCommand:
1518       if (OneOf(Delimiters, cur_ch)) {
1519         cur_st = Normal;
1520         Out.push_back("");
1521         continue;
1522       }
1523       if (cur_ch == '(') {
1524         Out.push_back("");
1525         cur_st = InsideSpecialCommand;
1526         continue;
1527       }
1528       break;
1529
1530     case InsideSpecialCommand:
1531       if (OneOf(Delimiters, cur_ch)) {
1532         continue;
1533       }
1534       if (cur_ch == '\'') {
1535         cur_st = InsideQuotationMarks;
1536         Out.push_back("");
1537         continue;
1538       }
1539       if (cur_ch == ')') {
1540         cur_st = Normal;
1541         Out.push_back("");
1542       }
1543       if (cur_ch == ',') {
1544         continue;
1545       }
1546
1547       break;
1548
1549     case InsideQuotationMarks:
1550       if (cur_ch == '\'') {
1551         cur_st = InsideSpecialCommand;
1552         continue;
1553       }
1554       break;
1555     }
1556
1557     Out.back().push_back(cur_ch);
1558   }
1559 }
1560
1561 /// SubstituteCall - Given "$CALL(HookName, [Arg1 [, Arg2 [...]]])", output
1562 /// "hooks::HookName([Arg1 [, Arg2 [, ...]]])". Helper function used by
1563 /// SubstituteSpecialCommands().
1564 StrVector::const_iterator
1565 SubstituteCall (StrVector::const_iterator Pos,
1566                 StrVector::const_iterator End,
1567                 bool IsJoin, raw_ostream& O)
1568 {
1569   const char* errorMessage = "Syntax error in $CALL invocation!";
1570   CheckedIncrement(Pos, End, errorMessage);
1571   const std::string& CmdName = *Pos;
1572
1573   if (CmdName == ")")
1574     throw "$CALL invocation: empty argument list!";
1575
1576   O << "hooks::";
1577   O << CmdName << "(";
1578
1579
1580   bool firstIteration = true;
1581   while (true) {
1582     CheckedIncrement(Pos, End, errorMessage);
1583     const std::string& Arg = *Pos;
1584     assert(Arg.size() != 0);
1585
1586     if (Arg[0] == ')')
1587       break;
1588
1589     if (firstIteration)
1590       firstIteration = false;
1591     else
1592       O << ", ";
1593
1594     if (Arg == "$INFILE") {
1595       if (IsJoin)
1596         throw "$CALL(Hook, $INFILE) can't be used with a Join tool!";
1597       else
1598         O << "inFile.c_str()";
1599     }
1600     else {
1601       O << '"' << Arg << '"';
1602     }
1603   }
1604
1605   O << ')';
1606
1607   return Pos;
1608 }
1609
1610 /// SubstituteEnv - Given '$ENV(VAR_NAME)', output 'getenv("VAR_NAME")'. Helper
1611 /// function used by SubstituteSpecialCommands().
1612 StrVector::const_iterator
1613 SubstituteEnv (StrVector::const_iterator Pos,
1614                StrVector::const_iterator End, raw_ostream& O)
1615 {
1616   const char* errorMessage = "Syntax error in $ENV invocation!";
1617   CheckedIncrement(Pos, End, errorMessage);
1618   const std::string& EnvName = *Pos;
1619
1620   if (EnvName == ")")
1621     throw "$ENV invocation: empty argument list!";
1622
1623   O << "checkCString(std::getenv(\"";
1624   O << EnvName;
1625   O << "\"))";
1626
1627   CheckedIncrement(Pos, End, errorMessage);
1628
1629   return Pos;
1630 }
1631
1632 /// SubstituteSpecialCommands - Given an invocation of $CALL or $ENV, output
1633 /// handler code. Helper function used by EmitCmdLineVecFill().
1634 StrVector::const_iterator
1635 SubstituteSpecialCommands (StrVector::const_iterator Pos,
1636                            StrVector::const_iterator End,
1637                            bool IsJoin, raw_ostream& O)
1638 {
1639
1640   const std::string& cmd = *Pos;
1641
1642   // Perform substitution.
1643   if (cmd == "$CALL") {
1644     Pos = SubstituteCall(Pos, End, IsJoin, O);
1645   }
1646   else if (cmd == "$ENV") {
1647     Pos = SubstituteEnv(Pos, End, O);
1648   }
1649   else {
1650     throw "Unknown special command: " + cmd;
1651   }
1652
1653   // Handle '$CMD(ARG)/additional/text'.
1654   const std::string& Leftover = *Pos;
1655   assert(Leftover.at(0) == ')');
1656   if (Leftover.size() != 1)
1657     O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1658
1659   return Pos;
1660 }
1661
1662 /// EmitCmdLineVecFill - Emit code that fills in the command line
1663 /// vector. Helper function used by EmitGenerateActionMethod().
1664 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1665                         bool IsJoin, unsigned IndentLevel,
1666                         raw_ostream& O) {
1667   StrVector StrVec;
1668   TokenizeCmdLine(InitPtrToString(CmdLine), StrVec);
1669
1670   if (StrVec.empty())
1671     throw "Tool '" + ToolName + "' has empty command line!";
1672
1673   StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1674
1675   // If there is a hook invocation on the place of the first command, skip it.
1676   assert(!StrVec[0].empty());
1677   if (StrVec[0][0] == '$') {
1678     while (I != E && (*I)[0] != ')' )
1679       ++I;
1680
1681     // Skip the ')' symbol.
1682     ++I;
1683   }
1684   else {
1685     ++I;
1686   }
1687
1688   bool hasINFILE = false;
1689
1690   for (; I != E; ++I) {
1691     const std::string& cmd = *I;
1692     assert(!cmd.empty());
1693     O.indent(IndentLevel);
1694     if (cmd.at(0) == '$') {
1695       if (cmd == "$INFILE") {
1696         hasINFILE = true;
1697         if (IsJoin) {
1698           O << "for (PathVector::const_iterator B = inFiles.begin()"
1699             << ", E = inFiles.end();\n";
1700           O.indent(IndentLevel) << "B != E; ++B)\n";
1701           O.indent(IndentLevel + Indent1) << "vec.push_back(B->str());\n";
1702         }
1703         else {
1704           O << "vec.push_back(inFile.str());\n";
1705         }
1706       }
1707       else if (cmd == "$OUTFILE") {
1708         O << "vec.push_back(\"\");\n";
1709         O.indent(IndentLevel) << "out_file_index = vec.size()-1;\n";
1710       }
1711       else {
1712         O << "vec.push_back(";
1713         I = SubstituteSpecialCommands(I, E, IsJoin, O);
1714         O << ");\n";
1715       }
1716     }
1717     else {
1718       O << "vec.push_back(\"" << cmd << "\");\n";
1719     }
1720   }
1721   if (!hasINFILE)
1722     throw "Tool '" + ToolName + "' doesn't take any input!";
1723
1724   O.indent(IndentLevel) << "cmd = ";
1725   if (StrVec[0][0] == '$')
1726     SubstituteSpecialCommands(StrVec.begin(), StrVec.end(), IsJoin, O);
1727   else
1728     O << '"' << StrVec[0] << '"';
1729   O << ";\n";
1730 }
1731
1732 /// EmitCmdLineVecFillCallback - A function object wrapper around
1733 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1734 /// argument to EmitCaseConstructHandler().
1735 class EmitCmdLineVecFillCallback {
1736   bool IsJoin;
1737   const std::string& ToolName;
1738  public:
1739   EmitCmdLineVecFillCallback(bool J, const std::string& TN)
1740     : IsJoin(J), ToolName(TN) {}
1741
1742   void operator()(const Init* Statement, unsigned IndentLevel,
1743                   raw_ostream& O) const
1744   {
1745     EmitCmdLineVecFill(Statement, ToolName, IsJoin, IndentLevel, O);
1746   }
1747 };
1748
1749 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1750 /// implement EmitActionHandler. Emits code for
1751 /// handling the (forward) and (forward_as) option properties.
1752 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1753                                             unsigned IndentLevel,
1754                                             const std::string& NewName,
1755                                             raw_ostream& O) {
1756   const std::string& Name = NewName.empty()
1757     ? ("-" + D.Name)
1758     : NewName;
1759   unsigned IndentLevel1 = IndentLevel + Indent1;
1760
1761   switch (D.Type) {
1762   case OptionType::Switch:
1763     O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1764     break;
1765   case OptionType::Parameter:
1766     O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1767     O.indent(IndentLevel) << "vec.push_back(" << D.GenVariableName() << ");\n";
1768     break;
1769   case OptionType::Prefix:
1770     O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\" + "
1771                           << D.GenVariableName() << ");\n";
1772     break;
1773   case OptionType::PrefixList:
1774     O.indent(IndentLevel)
1775       << "for (" << D.GenTypeDeclaration()
1776       << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1777     O.indent(IndentLevel)
1778       << "E = " << D.GenVariableName() << ".end(); B != E;) {\n";
1779     O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\" + " << "*B);\n";
1780     O.indent(IndentLevel1) << "++B;\n";
1781
1782     for (int i = 1, j = D.MultiVal; i < j; ++i) {
1783       O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1784       O.indent(IndentLevel1) << "++B;\n";
1785     }
1786
1787     O.indent(IndentLevel) << "}\n";
1788     break;
1789   case OptionType::ParameterList:
1790     O.indent(IndentLevel)
1791       << "for (" << D.GenTypeDeclaration() << "::iterator B = "
1792       << D.GenVariableName() << ".begin(),\n";
1793     O.indent(IndentLevel) << "E = " << D.GenVariableName()
1794                           << ".end() ; B != E;) {\n";
1795     O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\");\n";
1796
1797     for (int i = 0, j = D.MultiVal; i < j; ++i) {
1798       O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1799       O.indent(IndentLevel1) << "++B;\n";
1800     }
1801
1802     O.indent(IndentLevel) << "}\n";
1803     break;
1804   case OptionType::Alias:
1805   default:
1806     throw "Aliases are not allowed in tool option descriptions!";
1807   }
1808 }
1809
1810 /// ActionHandlingCallbackBase - Base class of EmitActionHandlersCallback and
1811 /// EmitPreprocessOptionsCallback.
1812 struct ActionHandlingCallbackBase
1813 {
1814
1815   void onErrorDag(const DagInit& d,
1816                   unsigned IndentLevel, raw_ostream& O) const
1817   {
1818     O.indent(IndentLevel)
1819       << "throw std::runtime_error(\"" <<
1820       (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0))
1821        : "Unknown error!")
1822       << "\");\n";
1823   }
1824
1825   void onWarningDag(const DagInit& d,
1826                     unsigned IndentLevel, raw_ostream& O) const
1827   {
1828     CheckNumberOfArguments(d, 1);
1829     O.indent(IndentLevel) << "llvm::errs() << \""
1830                           << InitPtrToString(d.getArg(0)) << "\";\n";
1831   }
1832
1833 };
1834
1835 /// EmitActionHandlersCallback - Emit code that handles actions. Used by
1836 /// EmitGenerateActionMethod() as an argument to EmitCaseConstructHandler().
1837
1838 class EmitActionHandlersCallback;
1839
1840 typedef void (EmitActionHandlersCallback::* EmitActionHandlersCallbackHandler)
1841 (const DagInit&, unsigned, raw_ostream&) const;
1842
1843 class EmitActionHandlersCallback :
1844   public ActionHandlingCallbackBase,
1845   public HandlerTable<EmitActionHandlersCallbackHandler>
1846 {
1847   typedef EmitActionHandlersCallbackHandler Handler;
1848
1849   const OptionDescriptions& OptDescs;
1850
1851   /// EmitHookInvocation - Common code for hook invocation from actions. Used by
1852   /// onAppendCmd and onOutputSuffix.
1853   void EmitHookInvocation(const std::string& Str,
1854                           const char* BlockOpen, const char* BlockClose,
1855                           unsigned IndentLevel, raw_ostream& O) const
1856   {
1857     StrVector Out;
1858     TokenizeCmdLine(Str, Out);
1859
1860     for (StrVector::const_iterator B = Out.begin(), E = Out.end();
1861          B != E; ++B) {
1862       const std::string& cmd = *B;
1863
1864       O.indent(IndentLevel) << BlockOpen;
1865
1866       if (cmd.at(0) == '$')
1867         B = SubstituteSpecialCommands(B, E,  /* IsJoin = */ true, O);
1868       else
1869         O << '"' << cmd << '"';
1870
1871       O << BlockClose;
1872     }
1873   }
1874
1875   void onAppendCmd (const DagInit& Dag,
1876                     unsigned IndentLevel, raw_ostream& O) const
1877   {
1878     CheckNumberOfArguments(Dag, 1);
1879     this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
1880                              "vec.push_back(", ");\n", IndentLevel, O);
1881   }
1882
1883   void onForward (const DagInit& Dag,
1884                   unsigned IndentLevel, raw_ostream& O) const
1885   {
1886     CheckNumberOfArguments(Dag, 1);
1887     const std::string& Name = InitPtrToString(Dag.getArg(0));
1888     EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1889                                           IndentLevel, "", O);
1890   }
1891
1892   void onForwardAs (const DagInit& Dag,
1893                     unsigned IndentLevel, raw_ostream& O) const
1894   {
1895     CheckNumberOfArguments(Dag, 2);
1896     const std::string& Name = InitPtrToString(Dag.getArg(0));
1897     const std::string& NewName = InitPtrToString(Dag.getArg(1));
1898     EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1899                                           IndentLevel, NewName, O);
1900   }
1901
1902   void onForwardValue (const DagInit& Dag,
1903                        unsigned IndentLevel, raw_ostream& O) const
1904   {
1905     CheckNumberOfArguments(Dag, 1);
1906     const std::string& Name = InitPtrToString(Dag.getArg(0));
1907     const OptionDescription& D = OptDescs.FindListOrParameter(Name);
1908
1909     if (D.isParameter()) {
1910       O.indent(IndentLevel) << "vec.push_back("
1911                             << D.GenVariableName() << ");\n";
1912     }
1913     else {
1914       O.indent(IndentLevel) << "std::copy(" << D.GenVariableName()
1915                             << ".begin(), " << D.GenVariableName()
1916                             << ".end(), std::back_inserter(vec));\n";
1917     }
1918   }
1919
1920   void onForwardTransformedValue (const DagInit& Dag,
1921                                   unsigned IndentLevel, raw_ostream& O) const
1922   {
1923     CheckNumberOfArguments(Dag, 2);
1924     const std::string& Name = InitPtrToString(Dag.getArg(0));
1925     const std::string& Hook = InitPtrToString(Dag.getArg(1));
1926     const OptionDescription& D = OptDescs.FindListOrParameter(Name);
1927
1928     O.indent(IndentLevel) << "vec.push_back(" << "hooks::"
1929                           << Hook << "(" << D.GenVariableName()
1930                           << (D.isParameter() ? ".c_str()" : "") << "));\n";
1931   }
1932
1933   void onOutputSuffix (const DagInit& Dag,
1934                        unsigned IndentLevel, raw_ostream& O) const
1935   {
1936     CheckNumberOfArguments(Dag, 1);
1937     this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
1938                              "output_suffix = ", ";\n", IndentLevel, O);
1939   }
1940
1941   void onStopCompilation (const DagInit& Dag,
1942                           unsigned IndentLevel, raw_ostream& O) const
1943   {
1944     O.indent(IndentLevel) << "stop_compilation = true;\n";
1945   }
1946
1947
1948   void onUnpackValues (const DagInit& Dag,
1949                        unsigned IndentLevel, raw_ostream& O) const
1950   {
1951     throw "'unpack_values' is deprecated. "
1952       "Use 'comma_separated' + 'forward_value' instead!";
1953   }
1954
1955  public:
1956
1957   explicit EmitActionHandlersCallback(const OptionDescriptions& OD)
1958     : OptDescs(OD)
1959   {
1960     if (!staticMembersInitialized_) {
1961       AddHandler("error", &EmitActionHandlersCallback::onErrorDag);
1962       AddHandler("warning", &EmitActionHandlersCallback::onWarningDag);
1963       AddHandler("append_cmd", &EmitActionHandlersCallback::onAppendCmd);
1964       AddHandler("forward", &EmitActionHandlersCallback::onForward);
1965       AddHandler("forward_as", &EmitActionHandlersCallback::onForwardAs);
1966       AddHandler("forward_value", &EmitActionHandlersCallback::onForwardValue);
1967       AddHandler("forward_transformed_value",
1968                  &EmitActionHandlersCallback::onForwardTransformedValue);
1969       AddHandler("output_suffix", &EmitActionHandlersCallback::onOutputSuffix);
1970       AddHandler("stop_compilation",
1971                  &EmitActionHandlersCallback::onStopCompilation);
1972       AddHandler("unpack_values",
1973                  &EmitActionHandlersCallback::onUnpackValues);
1974
1975       staticMembersInitialized_ = true;
1976     }
1977   }
1978
1979   void operator()(const Init* I,
1980                   unsigned IndentLevel, raw_ostream& O) const
1981   {
1982     InvokeDagInitHandler(this, I, IndentLevel, O);
1983   }
1984 };
1985
1986 bool IsOutFileIndexCheckRequiredStr (const Init* CmdLine) {
1987   StrVector StrVec;
1988   TokenizeCmdLine(InitPtrToString(CmdLine), StrVec);
1989
1990   for (StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1991        I != E; ++I) {
1992     if (*I == "$OUTFILE")
1993       return false;
1994   }
1995
1996   return true;
1997 }
1998
1999 class IsOutFileIndexCheckRequiredStrCallback {
2000   bool* ret_;
2001
2002 public:
2003   IsOutFileIndexCheckRequiredStrCallback(bool* ret) : ret_(ret)
2004   {}
2005
2006   void operator()(const Init* CmdLine) {
2007     // Ignore nested 'case' DAG.
2008     if (typeid(*CmdLine) == typeid(DagInit))
2009       return;
2010
2011     if (IsOutFileIndexCheckRequiredStr(CmdLine))
2012       *ret_ = true;
2013   }
2014
2015   void operator()(const DagInit* Test, unsigned, bool) {
2016     this->operator()(Test);
2017   }
2018   void operator()(const Init* Statement, unsigned) {
2019     this->operator()(Statement);
2020   }
2021 };
2022
2023 bool IsOutFileIndexCheckRequiredCase (Init* CmdLine) {
2024   bool ret = false;
2025   WalkCase(CmdLine, Id(), IsOutFileIndexCheckRequiredStrCallback(&ret));
2026   return ret;
2027 }
2028
2029 /// IsOutFileIndexCheckRequired - Should we emit an "out_file_index != -1" check
2030 /// in EmitGenerateActionMethod() ?
2031 bool IsOutFileIndexCheckRequired (Init* CmdLine) {
2032   if (typeid(*CmdLine) == typeid(StringInit))
2033     return IsOutFileIndexCheckRequiredStr(CmdLine);
2034   else
2035     return IsOutFileIndexCheckRequiredCase(CmdLine);
2036 }
2037
2038 void EmitGenerateActionMethodHeader(const ToolDescription& D,
2039                                     bool IsJoin, raw_ostream& O)
2040 {
2041   if (IsJoin)
2042     O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
2043   else
2044     O.indent(Indent1) << "Action GenerateAction(const sys::Path& inFile,\n";
2045
2046   O.indent(Indent2) << "bool HasChildren,\n";
2047   O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
2048   O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
2049   O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
2050   O.indent(Indent1) << "{\n";
2051   O.indent(Indent2) << "std::string cmd;\n";
2052   O.indent(Indent2) << "std::vector<std::string> vec;\n";
2053   O.indent(Indent2) << "bool stop_compilation = !HasChildren;\n";
2054   O.indent(Indent2) << "const char* output_suffix = \""
2055                     << D.OutputSuffix << "\";\n";
2056 }
2057
2058 // EmitGenerateActionMethod - Emit either a normal or a "join" version of the
2059 // Tool::GenerateAction() method.
2060 void EmitGenerateActionMethod (const ToolDescription& D,
2061                                const OptionDescriptions& OptDescs,
2062                                bool IsJoin, raw_ostream& O) {
2063
2064   EmitGenerateActionMethodHeader(D, IsJoin, O);
2065
2066   if (!D.CmdLine)
2067     throw "Tool " + D.Name + " has no cmd_line property!";
2068
2069   bool IndexCheckRequired = IsOutFileIndexCheckRequired(D.CmdLine);
2070   O.indent(Indent2) << "int out_file_index"
2071                     << (IndexCheckRequired ? " = -1" : "")
2072                     << ";\n\n";
2073
2074   // Process the cmd_line property.
2075   if (typeid(*D.CmdLine) == typeid(StringInit))
2076     EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
2077   else
2078     EmitCaseConstructHandler(D.CmdLine, Indent2,
2079                              EmitCmdLineVecFillCallback(IsJoin, D.Name),
2080                              true, OptDescs, O);
2081
2082   // For every understood option, emit handling code.
2083   if (D.Actions)
2084     EmitCaseConstructHandler(D.Actions, Indent2,
2085                              EmitActionHandlersCallback(OptDescs),
2086                              false, OptDescs, O);
2087
2088   O << '\n';
2089   O.indent(Indent2)
2090     << "std::string out_file = OutFilename("
2091     << (IsJoin ? "sys::Path(),\n" : "inFile,\n");
2092   O.indent(Indent3) << "TempDir, stop_compilation, output_suffix).str();\n\n";
2093
2094   if (IndexCheckRequired)
2095     O.indent(Indent2) << "if (out_file_index != -1)\n";
2096   O.indent(IndexCheckRequired ? Indent3 : Indent2)
2097     << "vec[out_file_index] = out_file;\n";
2098
2099   // Handle the Sink property.
2100   if (D.isSink()) {
2101     O.indent(Indent2) << "if (!" << SinkOptionName << ".empty()) {\n";
2102     O.indent(Indent3) << "vec.insert(vec.end(), "
2103                       << SinkOptionName << ".begin(), " << SinkOptionName
2104                       << ".end());\n";
2105     O.indent(Indent2) << "}\n";
2106   }
2107
2108   O.indent(Indent2) << "return Action(cmd, vec, stop_compilation, out_file);\n";
2109   O.indent(Indent1) << "}\n\n";
2110 }
2111
2112 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
2113 /// a given Tool class.
2114 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
2115                                 const OptionDescriptions& OptDescs,
2116                                 raw_ostream& O) {
2117   if (!ToolDesc.isJoin()) {
2118     O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
2119     O.indent(Indent2) << "bool HasChildren,\n";
2120     O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
2121     O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
2122     O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
2123     O.indent(Indent1) << "{\n";
2124     O.indent(Indent2) << "throw std::runtime_error(\"" << ToolDesc.Name
2125                       << " is not a Join tool!\");\n";
2126     O.indent(Indent1) << "}\n\n";
2127   }
2128   else {
2129     EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
2130   }
2131
2132   EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
2133 }
2134
2135 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
2136 /// methods for a given Tool class.
2137 void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
2138   O.indent(Indent1) << "const char** InputLanguages() const {\n";
2139   O.indent(Indent2) << "return InputLanguages_;\n";
2140   O.indent(Indent1) << "}\n\n";
2141
2142   if (D.OutLanguage.empty())
2143     throw "Tool " + D.Name + " has no 'out_language' property!";
2144
2145   O.indent(Indent1) << "const char* OutputLanguage() const {\n";
2146   O.indent(Indent2) << "return \"" << D.OutLanguage << "\";\n";
2147   O.indent(Indent1) << "}\n\n";
2148 }
2149
2150 /// EmitNameMethod - Emit the Name() method for a given Tool class.
2151 void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
2152   O.indent(Indent1) << "const char* Name() const {\n";
2153   O.indent(Indent2) << "return \"" << D.Name << "\";\n";
2154   O.indent(Indent1) << "}\n\n";
2155 }
2156
2157 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
2158 /// class.
2159 void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
2160   O.indent(Indent1) << "bool IsJoin() const {\n";
2161   if (D.isJoin())
2162     O.indent(Indent2) << "return true;\n";
2163   else
2164     O.indent(Indent2) << "return false;\n";
2165   O.indent(Indent1) << "}\n\n";
2166 }
2167
2168 /// EmitStaticMemberDefinitions - Emit static member definitions for a
2169 /// given Tool class.
2170 void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
2171   if (D.InLanguage.empty())
2172     throw "Tool " + D.Name + " has no 'in_language' property!";
2173
2174   O << "const char* " << D.Name << "::InputLanguages_[] = {";
2175   for (StrVector::const_iterator B = D.InLanguage.begin(),
2176          E = D.InLanguage.end(); B != E; ++B)
2177     O << '\"' << *B << "\", ";
2178   O << "0};\n\n";
2179 }
2180
2181 /// EmitToolClassDefinition - Emit a Tool class definition.
2182 void EmitToolClassDefinition (const ToolDescription& D,
2183                               const OptionDescriptions& OptDescs,
2184                               raw_ostream& O) {
2185   if (D.Name == "root")
2186     return;
2187
2188   // Header
2189   O << "class " << D.Name << " : public ";
2190   if (D.isJoin())
2191     O << "JoinTool";
2192   else
2193     O << "Tool";
2194
2195   O << " {\nprivate:\n";
2196   O.indent(Indent1) << "static const char* InputLanguages_[];\n\n";
2197
2198   O << "public:\n";
2199   EmitNameMethod(D, O);
2200   EmitInOutLanguageMethods(D, O);
2201   EmitIsJoinMethod(D, O);
2202   EmitGenerateActionMethods(D, OptDescs, O);
2203
2204   // Close class definition
2205   O << "};\n";
2206
2207   EmitStaticMemberDefinitions(D, O);
2208
2209 }
2210
2211 /// EmitOptionDefinitions - Iterate over a list of option descriptions
2212 /// and emit registration code.
2213 void EmitOptionDefinitions (const OptionDescriptions& descs,
2214                             bool HasSink, bool HasExterns,
2215                             raw_ostream& O)
2216 {
2217   std::vector<OptionDescription> Aliases;
2218
2219   // Emit static cl::Option variables.
2220   for (OptionDescriptions::const_iterator B = descs.begin(),
2221          E = descs.end(); B!=E; ++B) {
2222     const OptionDescription& val = B->second;
2223
2224     if (val.Type == OptionType::Alias) {
2225       Aliases.push_back(val);
2226       continue;
2227     }
2228
2229     if (val.isExtern())
2230       O << "extern ";
2231
2232     O << val.GenTypeDeclaration() << ' '
2233       << val.GenVariableName();
2234
2235     if (val.isExtern()) {
2236       O << ";\n";
2237       continue;
2238     }
2239
2240     O << "(\"" << val.Name << "\"\n";
2241
2242     if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
2243       O << ", cl::Prefix";
2244
2245     if (val.isRequired()) {
2246       if (val.isList() && !val.isMultiVal())
2247         O << ", cl::OneOrMore";
2248       else
2249         O << ", cl::Required";
2250     }
2251     else if (val.isOneOrMore() && val.isList()) {
2252         O << ", cl::OneOrMore";
2253     }
2254     else if (val.isOptional() && val.isList()) {
2255         O << ", cl::Optional";
2256     }
2257
2258     if (val.isReallyHidden())
2259       O << ", cl::ReallyHidden";
2260     else if (val.isHidden())
2261       O << ", cl::Hidden";
2262
2263     if (val.isCommaSeparated())
2264       O << ", cl::CommaSeparated";
2265
2266     if (val.MultiVal > 1)
2267       O << ", cl::multi_val(" << val.MultiVal << ')';
2268
2269     if (val.InitVal) {
2270       const std::string& str = val.InitVal->getAsString();
2271       O << ", cl::init(" << str << ')';
2272     }
2273
2274     if (!val.Help.empty())
2275       O << ", cl::desc(\"" << val.Help << "\")";
2276
2277     O << ");\n\n";
2278   }
2279
2280   // Emit the aliases (they should go after all the 'proper' options).
2281   for (std::vector<OptionDescription>::const_iterator
2282          B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
2283     const OptionDescription& val = *B;
2284
2285     O << val.GenTypeDeclaration() << ' '
2286       << val.GenVariableName()
2287       << "(\"" << val.Name << '\"';
2288
2289     const OptionDescription& D = descs.FindOption(val.Help);
2290     O << ", cl::aliasopt(" << D.GenVariableName() << ")";
2291
2292     O << ", cl::desc(\"" << "An alias for -" + val.Help  << "\"));\n";
2293   }
2294
2295   // Emit the sink option.
2296   if (HasSink)
2297     O << (HasExterns ? "extern cl" : "cl")
2298       << "::list<std::string> " << SinkOptionName
2299       << (HasExterns ? ";\n" : "(cl::Sink);\n");
2300
2301   O << '\n';
2302 }
2303
2304 /// EmitPreprocessOptionsCallback - Helper function passed to
2305 /// EmitCaseConstructHandler() by EmitPreprocessOptions().
2306
2307 class EmitPreprocessOptionsCallback;
2308
2309 typedef void
2310 (EmitPreprocessOptionsCallback::* EmitPreprocessOptionsCallbackHandler)
2311 (const DagInit&, unsigned, raw_ostream&) const;
2312
2313 class EmitPreprocessOptionsCallback :
2314   public ActionHandlingCallbackBase,
2315   public HandlerTable<EmitPreprocessOptionsCallbackHandler>
2316 {
2317   typedef EmitPreprocessOptionsCallbackHandler Handler;
2318   typedef void
2319   (EmitPreprocessOptionsCallback::* HandlerImpl)
2320   (const Init*, unsigned, raw_ostream&) const;
2321
2322   const OptionDescriptions& OptDescs_;
2323
2324   void onListOrDag(const DagInit& d, HandlerImpl h,
2325                    unsigned IndentLevel, raw_ostream& O) const
2326   {
2327     CheckNumberOfArguments(d, 1);
2328     const Init* I = d.getArg(0);
2329
2330     // If I is a list, apply h to each element.
2331     if (typeid(*I) == typeid(ListInit)) {
2332       const ListInit& L = *static_cast<const ListInit*>(I);
2333       for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B)
2334         ((this)->*(h))(*B, IndentLevel, O);
2335     }
2336     // Otherwise, apply h to I.
2337     else {
2338       ((this)->*(h))(I, IndentLevel, O);
2339     }
2340   }
2341
2342   void onUnsetOptionImpl(const Init* I,
2343                          unsigned IndentLevel, raw_ostream& O) const
2344   {
2345     const std::string& OptName = InitPtrToString(I);
2346     const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2347
2348     if (OptDesc.isSwitch()) {
2349       O.indent(IndentLevel) << OptDesc.GenVariableName() << " = false;\n";
2350     }
2351     else if (OptDesc.isParameter()) {
2352       O.indent(IndentLevel) << OptDesc.GenVariableName() << " = \"\";\n";
2353     }
2354     else if (OptDesc.isList()) {
2355       O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2356     }
2357     else {
2358       throw "Can't apply 'unset_option' to alias option '" + OptName + "'!";
2359     }
2360   }
2361
2362   void onUnsetOption(const DagInit& d,
2363                      unsigned IndentLevel, raw_ostream& O) const
2364   {
2365     this->onListOrDag(d, &EmitPreprocessOptionsCallback::onUnsetOptionImpl,
2366                       IndentLevel, O);
2367   }
2368
2369   void onSetOptionImpl(const DagInit& d,
2370                        unsigned IndentLevel, raw_ostream& O) const {
2371     CheckNumberOfArguments(d, 2);
2372     const std::string& OptName = InitPtrToString(d.getArg(0));
2373     const Init* Value = d.getArg(1);
2374     const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2375
2376     if (OptDesc.isList()) {
2377       const ListInit& List = InitPtrToList(Value);
2378
2379       O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2380       for (ListInit::const_iterator B = List.begin(), E = List.end();
2381            B != E; ++B) {
2382         O.indent(IndentLevel) << OptDesc.GenVariableName() << ".push_back(\""
2383                               << InitPtrToString(*B) << "\");\n";
2384       }
2385     }
2386     else if (OptDesc.isSwitch()) {
2387       CheckBooleanConstant(Value);
2388       O.indent(IndentLevel) << OptDesc.GenVariableName()
2389                             << " = " << Value->getAsString() << ";\n";
2390     }
2391     else if (OptDesc.isParameter()) {
2392       const std::string& Str = InitPtrToString(Value);
2393       O.indent(IndentLevel) << OptDesc.GenVariableName()
2394                             << " = \"" << Str << "\";\n";
2395     }
2396     else {
2397       throw "Can't apply 'set_option' to alias option -" + OptName + " !";
2398     }
2399   }
2400
2401   void onSetSwitch(const Init* I,
2402                    unsigned IndentLevel, raw_ostream& O) const {
2403     const std::string& OptName = InitPtrToString(I);
2404     const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2405
2406     if (OptDesc.isSwitch())
2407       O.indent(IndentLevel) << OptDesc.GenVariableName() << " = true;\n";
2408     else
2409       throw "set_option: -" + OptName + " is not a switch option!";
2410   }
2411
2412   void onSetOption(const DagInit& d,
2413                    unsigned IndentLevel, raw_ostream& O) const
2414   {
2415     CheckNumberOfArguments(d, 1);
2416
2417     // Two arguments: (set_option "parameter", VALUE), where VALUE can be a
2418     // boolean, a string or a string list.
2419     if (d.getNumArgs() > 1)
2420       this->onSetOptionImpl(d, IndentLevel, O);
2421     // One argument: (set_option "switch")
2422     // or (set_option ["switch1", "switch2", ...])
2423     else
2424       this->onListOrDag(d, &EmitPreprocessOptionsCallback::onSetSwitch,
2425                         IndentLevel, O);
2426   }
2427
2428 public:
2429
2430   EmitPreprocessOptionsCallback(const OptionDescriptions& OptDescs)
2431   : OptDescs_(OptDescs)
2432   {
2433     if (!staticMembersInitialized_) {
2434       AddHandler("error", &EmitPreprocessOptionsCallback::onErrorDag);
2435       AddHandler("warning", &EmitPreprocessOptionsCallback::onWarningDag);
2436       AddHandler("unset_option", &EmitPreprocessOptionsCallback::onUnsetOption);
2437       AddHandler("set_option", &EmitPreprocessOptionsCallback::onSetOption);
2438
2439       staticMembersInitialized_ = true;
2440     }
2441   }
2442
2443   void operator()(const Init* I,
2444                   unsigned IndentLevel, raw_ostream& O) const
2445   {
2446     InvokeDagInitHandler(this, I, IndentLevel, O);
2447   }
2448
2449 };
2450
2451 /// EmitPreprocessOptions - Emit the PreprocessOptionsLocal() function.
2452 void EmitPreprocessOptions (const RecordKeeper& Records,
2453                             const OptionDescriptions& OptDecs, raw_ostream& O)
2454 {
2455   O << "void PreprocessOptionsLocal() {\n";
2456
2457   const RecordVector& OptionPreprocessors =
2458     Records.getAllDerivedDefinitions("OptionPreprocessor");
2459
2460   for (RecordVector::const_iterator B = OptionPreprocessors.begin(),
2461          E = OptionPreprocessors.end(); B!=E; ++B) {
2462     DagInit* Case = (*B)->getValueAsDag("preprocessor");
2463     EmitCaseConstructHandler(Case, Indent1,
2464                              EmitPreprocessOptionsCallback(OptDecs),
2465                              false, OptDecs, O);
2466   }
2467
2468   O << "}\n\n";
2469 }
2470
2471 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMapLocal() function.
2472 void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
2473 {
2474   O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
2475
2476   // Get the relevant field out of RecordKeeper
2477   const Record* LangMapRecord = Records.getDef("LanguageMap");
2478
2479   // It is allowed for a plugin to have no language map.
2480   if (LangMapRecord) {
2481
2482     ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
2483     if (!LangsToSuffixesList)
2484       throw "Error in the language map definition!";
2485
2486     for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
2487       const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
2488
2489       const std::string& Lang = LangToSuffixes->getValueAsString("lang");
2490       const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
2491
2492       for (unsigned i = 0; i < Suffixes->size(); ++i)
2493         O.indent(Indent1) << "langMap[\""
2494                           << InitPtrToString(Suffixes->getElement(i))
2495                           << "\"] = \"" << Lang << "\";\n";
2496     }
2497   }
2498
2499   O << "}\n\n";
2500 }
2501
2502 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
2503 /// by EmitEdgeClass().
2504 void IncDecWeight (const Init* i, unsigned IndentLevel,
2505                    raw_ostream& O) {
2506   const DagInit& d = InitPtrToDag(i);
2507   const std::string& OpName = GetOperatorName(d);
2508
2509   if (OpName == "inc_weight") {
2510     O.indent(IndentLevel) << "ret += ";
2511   }
2512   else if (OpName == "dec_weight") {
2513     O.indent(IndentLevel) << "ret -= ";
2514   }
2515   else if (OpName == "error") {
2516     CheckNumberOfArguments(d, 1);
2517     O.indent(IndentLevel) << "throw std::runtime_error(\""
2518                           << InitPtrToString(d.getArg(0))
2519                           << "\");\n";
2520     return;
2521   }
2522   else {
2523     throw "Unknown operator in edge properties list: '" + OpName + "'!"
2524       "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
2525   }
2526
2527   if (d.getNumArgs() > 0)
2528     O << InitPtrToInt(d.getArg(0)) << ";\n";
2529   else
2530     O << "2;\n";
2531
2532 }
2533
2534 /// EmitEdgeClass - Emit a single Edge# class.
2535 void EmitEdgeClass (unsigned N, const std::string& Target,
2536                     DagInit* Case, const OptionDescriptions& OptDescs,
2537                     raw_ostream& O) {
2538
2539   // Class constructor.
2540   O << "class Edge" << N << ": public Edge {\n"
2541     << "public:\n";
2542   O.indent(Indent1) << "Edge" << N << "() : Edge(\"" << Target
2543                     << "\") {}\n\n";
2544
2545   // Function Weight().
2546   O.indent(Indent1)
2547     << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n";
2548   O.indent(Indent2) << "unsigned ret = 0;\n";
2549
2550   // Handle the 'case' construct.
2551   EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
2552
2553   O.indent(Indent2) << "return ret;\n";
2554   O.indent(Indent1) << "}\n\n};\n\n";
2555 }
2556
2557 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
2558 void EmitEdgeClasses (const RecordVector& EdgeVector,
2559                       const OptionDescriptions& OptDescs,
2560                       raw_ostream& O) {
2561   int i = 0;
2562   for (RecordVector::const_iterator B = EdgeVector.begin(),
2563          E = EdgeVector.end(); B != E; ++B) {
2564     const Record* Edge = *B;
2565     const std::string& NodeB = Edge->getValueAsString("b");
2566     DagInit& Weight = *Edge->getValueAsDag("weight");
2567
2568     if (!IsDagEmpty(Weight))
2569       EmitEdgeClass(i, NodeB, &Weight, OptDescs, O);
2570     ++i;
2571   }
2572 }
2573
2574 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraphLocal()
2575 /// function.
2576 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
2577                                    const ToolDescriptions& ToolDescs,
2578                                    raw_ostream& O)
2579 {
2580   O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
2581
2582   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2583          E = ToolDescs.end(); B != E; ++B)
2584     O.indent(Indent1) << "G.insertNode(new " << (*B)->Name << "());\n";
2585
2586   O << '\n';
2587
2588   // Insert edges.
2589
2590   int i = 0;
2591   for (RecordVector::const_iterator B = EdgeVector.begin(),
2592          E = EdgeVector.end(); B != E; ++B) {
2593     const Record* Edge = *B;
2594     const std::string& NodeA = Edge->getValueAsString("a");
2595     const std::string& NodeB = Edge->getValueAsString("b");
2596     DagInit& Weight = *Edge->getValueAsDag("weight");
2597
2598     O.indent(Indent1) << "G.insertEdge(\"" << NodeA << "\", ";
2599
2600     if (IsDagEmpty(Weight))
2601       O << "new SimpleEdge(\"" << NodeB << "\")";
2602     else
2603       O << "new Edge" << i << "()";
2604
2605     O << ");\n";
2606     ++i;
2607   }
2608
2609   O << "}\n\n";
2610 }
2611
2612 /// HookInfo - Information about the hook type and number of arguments.
2613 struct HookInfo {
2614
2615   // A hook can either have a single parameter of type std::vector<std::string>,
2616   // or NumArgs parameters of type const char*.
2617   enum HookType { ListHook, ArgHook };
2618
2619   HookType Type;
2620   unsigned NumArgs;
2621
2622   HookInfo() : Type(ArgHook), NumArgs(1)
2623   {}
2624
2625   HookInfo(HookType T) : Type(T), NumArgs(1)
2626   {}
2627
2628   HookInfo(unsigned N) : Type(ArgHook), NumArgs(N)
2629   {}
2630 };
2631
2632 typedef llvm::StringMap<HookInfo> HookInfoMap;
2633
2634 /// ExtractHookNames - Extract the hook names from all instances of
2635 /// $CALL(HookName) in the provided command line string/action. Helper
2636 /// function used by FillInHookNames().
2637 class ExtractHookNames {
2638   HookInfoMap& HookNames_;
2639   const OptionDescriptions& OptDescs_;
2640 public:
2641   ExtractHookNames(HookInfoMap& HookNames, const OptionDescriptions& OptDescs)
2642     : HookNames_(HookNames), OptDescs_(OptDescs)
2643   {}
2644
2645   void onAction (const DagInit& Dag) {
2646     const std::string& Name = GetOperatorName(Dag);
2647
2648     if (Name == "forward_transformed_value") {
2649       CheckNumberOfArguments(Dag, 2);
2650       const std::string& OptName = InitPtrToString(Dag.getArg(0));
2651       const std::string& HookName = InitPtrToString(Dag.getArg(1));
2652       const OptionDescription& D = OptDescs_.FindOption(OptName);
2653
2654       HookNames_[HookName] = HookInfo(D.isList() ? HookInfo::ListHook
2655                                       : HookInfo::ArgHook);
2656     }
2657     else if (Name == "append_cmd" || Name == "output_suffix") {
2658       CheckNumberOfArguments(Dag, 1);
2659       this->onCmdLine(InitPtrToString(Dag.getArg(0)));
2660     }
2661   }
2662
2663   void onCmdLine(const std::string& Cmd) {
2664     StrVector cmds;
2665     TokenizeCmdLine(Cmd, cmds);
2666
2667     for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
2668          B != E; ++B) {
2669       const std::string& cmd = *B;
2670
2671       if (cmd == "$CALL") {
2672         unsigned NumArgs = 0;
2673         CheckedIncrement(B, E, "Syntax error in $CALL invocation!");
2674         const std::string& HookName = *B;
2675
2676         if (HookName.at(0) == ')')
2677           throw "$CALL invoked with no arguments!";
2678
2679         while (++B != E && B->at(0) != ')') {
2680           ++NumArgs;
2681         }
2682
2683         HookInfoMap::const_iterator H = HookNames_.find(HookName);
2684
2685         if (H != HookNames_.end() && H->second.NumArgs != NumArgs &&
2686             H->second.Type != HookInfo::ArgHook)
2687           throw "Overloading of hooks is not allowed. Overloaded hook: "
2688             + HookName;
2689         else
2690           HookNames_[HookName] = HookInfo(NumArgs);
2691       }
2692     }
2693   }
2694
2695   void operator()(const Init* Arg) {
2696
2697     // We're invoked on an action (either a dag or a dag list).
2698     if (typeid(*Arg) == typeid(DagInit)) {
2699       const DagInit& Dag = InitPtrToDag(Arg);
2700       this->onAction(Dag);
2701       return;
2702     }
2703     else if (typeid(*Arg) == typeid(ListInit)) {
2704       const ListInit& List = InitPtrToList(Arg);
2705       for (ListInit::const_iterator B = List.begin(), E = List.end(); B != E;
2706            ++B) {
2707         const DagInit& Dag = InitPtrToDag(*B);
2708         this->onAction(Dag);
2709       }
2710       return;
2711     }
2712
2713     // We're invoked on a command line.
2714     this->onCmdLine(InitPtrToString(Arg));
2715   }
2716
2717   void operator()(const DagInit* Test, unsigned, bool) {
2718     this->operator()(Test);
2719   }
2720   void operator()(const Init* Statement, unsigned) {
2721     this->operator()(Statement);
2722   }
2723 };
2724
2725 /// FillInHookNames - Actually extract the hook names from all command
2726 /// line strings. Helper function used by EmitHookDeclarations().
2727 void FillInHookNames(const ToolDescriptions& ToolDescs,
2728                      const OptionDescriptions& OptDescs,
2729                      HookInfoMap& HookNames)
2730 {
2731   // For all tool descriptions:
2732   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2733          E = ToolDescs.end(); B != E; ++B) {
2734     const ToolDescription& D = *(*B);
2735
2736     // Look for 'forward_transformed_value' in 'actions'.
2737     if (D.Actions)
2738       WalkCase(D.Actions, Id(), ExtractHookNames(HookNames, OptDescs));
2739
2740     // Look for hook invocations in 'cmd_line'.
2741     if (!D.CmdLine)
2742       continue;
2743     if (dynamic_cast<StringInit*>(D.CmdLine))
2744       // This is a string.
2745       ExtractHookNames(HookNames, OptDescs).operator()(D.CmdLine);
2746     else
2747       // This is a 'case' construct.
2748       WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames, OptDescs));
2749   }
2750 }
2751
2752 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
2753 /// property records and emit hook function declaration for each
2754 /// instance of $CALL(HookName).
2755 void EmitHookDeclarations(const ToolDescriptions& ToolDescs,
2756                           const OptionDescriptions& OptDescs, raw_ostream& O) {
2757   HookInfoMap HookNames;
2758
2759   FillInHookNames(ToolDescs, OptDescs, HookNames);
2760   if (HookNames.empty())
2761     return;
2762
2763   O << "namespace hooks {\n";
2764   for (HookInfoMap::const_iterator B = HookNames.begin(),
2765          E = HookNames.end(); B != E; ++B) {
2766     const char* HookName = B->first();
2767     const HookInfo& Info = B->second;
2768
2769     O.indent(Indent1) << "std::string " << HookName << "(";
2770
2771     if (Info.Type == HookInfo::ArgHook) {
2772       for (unsigned i = 0, j = Info.NumArgs; i < j; ++i) {
2773         O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
2774       }
2775     }
2776     else {
2777       O << "const std::vector<std::string>& Arg";
2778     }
2779
2780     O <<");\n";
2781   }
2782   O << "}\n\n";
2783 }
2784
2785 /// EmitRegisterPlugin - Emit code to register this plugin.
2786 void EmitRegisterPlugin(int Priority, raw_ostream& O) {
2787   O << "struct Plugin : public llvmc::BasePlugin {\n\n";
2788   O.indent(Indent1) << "int Priority() const { return "
2789                     << Priority << "; }\n\n";
2790   O.indent(Indent1) << "void PreprocessOptions() const\n";
2791   O.indent(Indent1) << "{ PreprocessOptionsLocal(); }\n\n";
2792   O.indent(Indent1) << "void PopulateLanguageMap(LanguageMap& langMap) const\n";
2793   O.indent(Indent1) << "{ PopulateLanguageMapLocal(langMap); }\n\n";
2794   O.indent(Indent1)
2795     << "void PopulateCompilationGraph(CompilationGraph& graph) const\n";
2796   O.indent(Indent1) << "{ PopulateCompilationGraphLocal(graph); }\n"
2797                     << "};\n\n"
2798                     << "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
2799 }
2800
2801 /// EmitIncludes - Emit necessary #include directives and some
2802 /// additional declarations.
2803 void EmitIncludes(raw_ostream& O) {
2804   O << "#include \"llvm/CompilerDriver/BuiltinOptions.h\"\n"
2805     << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
2806     << "#include \"llvm/CompilerDriver/ForceLinkageMacros.h\"\n"
2807     << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
2808     << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
2809
2810     << "#include \"llvm/Support/CommandLine.h\"\n"
2811     << "#include \"llvm/Support/raw_ostream.h\"\n\n"
2812
2813     << "#include <algorithm>\n"
2814     << "#include <cstdlib>\n"
2815     << "#include <iterator>\n"
2816     << "#include <stdexcept>\n\n"
2817
2818     << "using namespace llvm;\n"
2819     << "using namespace llvmc;\n\n"
2820
2821     << "extern cl::opt<std::string> OutputFilename;\n\n"
2822
2823     << "inline const char* checkCString(const char* s)\n"
2824     << "{ return s == NULL ? \"\" : s; }\n\n";
2825 }
2826
2827
2828 /// PluginData - Holds all information about a plugin.
2829 struct PluginData {
2830   OptionDescriptions OptDescs;
2831   bool HasSink;
2832   bool HasExterns;
2833   ToolDescriptions ToolDescs;
2834   RecordVector Edges;
2835   int Priority;
2836 };
2837
2838 /// HasSink - Go through the list of tool descriptions and check if
2839 /// there are any with the 'sink' property set.
2840 bool HasSink(const ToolDescriptions& ToolDescs) {
2841   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2842          E = ToolDescs.end(); B != E; ++B)
2843     if ((*B)->isSink())
2844       return true;
2845
2846   return false;
2847 }
2848
2849 /// HasExterns - Go through the list of option descriptions and check
2850 /// if there are any external options.
2851 bool HasExterns(const OptionDescriptions& OptDescs) {
2852  for (OptionDescriptions::const_iterator B = OptDescs.begin(),
2853          E = OptDescs.end(); B != E; ++B)
2854     if (B->second.isExtern())
2855       return true;
2856
2857   return false;
2858 }
2859
2860 /// CollectPluginData - Collect tool and option properties,
2861 /// compilation graph edges and plugin priority from the parse tree.
2862 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
2863   // Collect option properties.
2864   const RecordVector& OptionLists =
2865     Records.getAllDerivedDefinitions("OptionList");
2866   CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
2867                             Data.OptDescs);
2868
2869   // Collect tool properties.
2870   const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
2871   CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
2872   Data.HasSink = HasSink(Data.ToolDescs);
2873   Data.HasExterns = HasExterns(Data.OptDescs);
2874
2875   // Collect compilation graph edges.
2876   const RecordVector& CompilationGraphs =
2877     Records.getAllDerivedDefinitions("CompilationGraph");
2878   FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
2879                    Data.Edges);
2880
2881   // Calculate the priority of this plugin.
2882   const RecordVector& Priorities =
2883     Records.getAllDerivedDefinitions("PluginPriority");
2884   Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
2885 }
2886
2887 /// CheckPluginData - Perform some sanity checks on the collected data.
2888 void CheckPluginData(PluginData& Data) {
2889   // Filter out all tools not mentioned in the compilation graph.
2890   FilterNotInGraph(Data.Edges, Data.ToolDescs);
2891
2892   // Typecheck the compilation graph.
2893   TypecheckGraph(Data.Edges, Data.ToolDescs);
2894
2895   // Check that there are no options without side effects (specified
2896   // only in the OptionList).
2897   CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
2898
2899 }
2900
2901 void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
2902   // Emit file header.
2903   EmitIncludes(O);
2904
2905   // Emit global option registration code.
2906   EmitOptionDefinitions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
2907
2908   // Emit hook declarations.
2909   EmitHookDeclarations(Data.ToolDescs, Data.OptDescs, O);
2910
2911   O << "namespace {\n\n";
2912
2913   // Emit PreprocessOptionsLocal() function.
2914   EmitPreprocessOptions(Records, Data.OptDescs, O);
2915
2916   // Emit PopulateLanguageMapLocal() function
2917   // (language map maps from file extensions to language names).
2918   EmitPopulateLanguageMap(Records, O);
2919
2920   // Emit Tool classes.
2921   for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
2922          E = Data.ToolDescs.end(); B!=E; ++B)
2923     EmitToolClassDefinition(*(*B), Data.OptDescs, O);
2924
2925   // Emit Edge# classes.
2926   EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
2927
2928   // Emit PopulateCompilationGraphLocal() function.
2929   EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
2930
2931   // Emit code for plugin registration.
2932   EmitRegisterPlugin(Data.Priority, O);
2933
2934   O << "} // End anonymous namespace.\n\n";
2935
2936   // Force linkage magic.
2937   O << "namespace llvmc {\n";
2938   O << "LLVMC_FORCE_LINKAGE_DECL(LLVMC_PLUGIN_NAME) {}\n";
2939   O << "}\n";
2940
2941   // EOF
2942 }
2943
2944
2945 // End of anonymous namespace
2946 }
2947
2948 /// run - The back-end entry point.
2949 void LLVMCConfigurationEmitter::run (raw_ostream &O) {
2950   try {
2951   PluginData Data;
2952
2953   CollectPluginData(Records, Data);
2954   CheckPluginData(Data);
2955
2956   EmitSourceFileHeader("LLVMC Configuration Library", O);
2957   EmitPluginCode(Data, O);
2958
2959   } catch (std::exception& Error) {
2960     throw Error.what() + std::string(" - usually this means a syntax error.");
2961   }
2962 }