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