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