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