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