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