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