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