f8a964044fe8625b3d3d6dd23fe9c7624c05f5b7
[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
800         std::string("The argument to (actions) should be a 'case' construct!");
801     toolDesc_.Actions = Case;
802   }
803
804   void onCmdLine (const DagInit* d) {
805     checkNumberOfArguments(d, 1);
806     toolDesc_.CmdLine = d->getArg(0);
807   }
808
809   void onInLanguage (const DagInit* d) {
810     checkNumberOfArguments(d, 1);
811     Init* arg = d->getArg(0);
812
813     // Find out the argument's type.
814     if (typeid(*arg) == typeid(StringInit)) {
815       // It's a string.
816       toolDesc_.InLanguage.push_back(InitPtrToString(arg));
817     }
818     else {
819       // It's a list.
820       const ListInit& lst = InitPtrToList(arg);
821       StrVector& out = toolDesc_.InLanguage;
822
823       // Copy strings to the output vector.
824       for (ListInit::const_iterator B = lst.begin(), E = lst.end();
825            B != E; ++B) {
826         out.push_back(InitPtrToString(*B));
827       }
828
829       // Remove duplicates.
830       std::sort(out.begin(), out.end());
831       StrVector::iterator newE = std::unique(out.begin(), out.end());
832       out.erase(newE, out.end());
833     }
834   }
835
836   void onJoin (const DagInit* d) {
837     checkNumberOfArguments(d, 0);
838     toolDesc_.setJoin();
839   }
840
841   void onOutLanguage (const DagInit* d) {
842     checkNumberOfArguments(d, 1);
843     toolDesc_.OutLanguage = InitPtrToString(d->getArg(0));
844   }
845
846   void onOutputSuffix (const DagInit* d) {
847     checkNumberOfArguments(d, 1);
848     toolDesc_.OutputSuffix = InitPtrToString(d->getArg(0));
849   }
850
851   void onSink (const DagInit* d) {
852     checkNumberOfArguments(d, 0);
853     toolDesc_.setSink();
854   }
855
856 };
857
858 /// CollectToolDescriptions - Gather information about tool properties
859 /// from the parsed TableGen data (basically a wrapper for the
860 /// CollectToolProperties function object).
861 void CollectToolDescriptions (RecordVector::const_iterator B,
862                               RecordVector::const_iterator E,
863                               ToolDescriptions& ToolDescs)
864 {
865   // Iterate over a properties list of every Tool definition
866   for (;B!=E;++B) {
867     const Record* T = *B;
868     // Throws an exception if the value does not exist.
869     ListInit* PropList = T->getValueAsListInit("properties");
870
871     IntrusiveRefCntPtr<ToolDescription>
872       ToolDesc(new ToolDescription(T->getName()));
873
874     std::for_each(PropList->begin(), PropList->end(),
875                   CollectToolProperties(*ToolDesc));
876     ToolDescs.push_back(ToolDesc);
877   }
878 }
879
880 /// FillInEdgeVector - Merge all compilation graph definitions into
881 /// one single edge list.
882 void FillInEdgeVector(RecordVector::const_iterator B,
883                       RecordVector::const_iterator E, RecordVector& Out) {
884   for (; B != E; ++B) {
885     const ListInit* edges = (*B)->getValueAsListInit("edges");
886
887     for (unsigned i = 0; i < edges->size(); ++i)
888       Out.push_back(edges->getElementAsRecord(i));
889   }
890 }
891
892 /// CalculatePriority - Calculate the priority of this plugin.
893 int CalculatePriority(RecordVector::const_iterator B,
894                       RecordVector::const_iterator E) {
895   int priority = 0;
896
897   if (B != E) {
898     priority  = static_cast<int>((*B)->getValueAsInt("priority"));
899
900     if (++B != E)
901       throw std::string("More than one 'PluginPriority' instance found: "
902                         "most probably an error!");
903   }
904
905   return priority;
906 }
907
908 /// NotInGraph - Helper function object for FilterNotInGraph.
909 struct NotInGraph {
910 private:
911   const llvm::StringSet<>& ToolsInGraph_;
912
913 public:
914   NotInGraph(const llvm::StringSet<>& ToolsInGraph)
915   : ToolsInGraph_(ToolsInGraph)
916   {}
917
918   bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
919     return (ToolsInGraph_.count(x->Name) == 0);
920   }
921 };
922
923 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
924 /// mentioned in the compilation graph definition.
925 void FilterNotInGraph (const RecordVector& EdgeVector,
926                        ToolDescriptions& ToolDescs) {
927
928   // List all tools mentioned in the graph.
929   llvm::StringSet<> ToolsInGraph;
930
931   for (RecordVector::const_iterator B = EdgeVector.begin(),
932          E = EdgeVector.end(); B != E; ++B) {
933
934     const Record* Edge = *B;
935     const std::string& NodeA = Edge->getValueAsString("a");
936     const std::string& NodeB = Edge->getValueAsString("b");
937
938     if (NodeA != "root")
939       ToolsInGraph.insert(NodeA);
940     ToolsInGraph.insert(NodeB);
941   }
942
943   // Filter ToolPropertiesList.
944   ToolDescriptions::iterator new_end =
945     std::remove_if(ToolDescs.begin(), ToolDescs.end(),
946                    NotInGraph(ToolsInGraph));
947   ToolDescs.erase(new_end, ToolDescs.end());
948 }
949
950 /// FillInToolToLang - Fills in two tables that map tool names to
951 /// (input, output) languages.  Helper function used by TypecheckGraph().
952 void FillInToolToLang (const ToolDescriptions& ToolDescs,
953                        StringMap<StringSet<> >& ToolToInLang,
954                        StringMap<std::string>& ToolToOutLang) {
955   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
956          E = ToolDescs.end(); B != E; ++B) {
957     const ToolDescription& D = *(*B);
958     for (StrVector::const_iterator B = D.InLanguage.begin(),
959            E = D.InLanguage.end(); B != E; ++B)
960       ToolToInLang[D.Name].insert(*B);
961     ToolToOutLang[D.Name] = D.OutLanguage;
962   }
963 }
964
965 /// TypecheckGraph - Check that names for output and input languages
966 /// on all edges do match. This doesn't do much when the information
967 /// about the whole graph is not available (i.e. when compiling most
968 /// plugins).
969 void TypecheckGraph (const RecordVector& EdgeVector,
970                      const ToolDescriptions& ToolDescs) {
971   StringMap<StringSet<> > ToolToInLang;
972   StringMap<std::string> ToolToOutLang;
973
974   FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
975   StringMap<std::string>::iterator IAE = ToolToOutLang.end();
976   StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
977
978   for (RecordVector::const_iterator B = EdgeVector.begin(),
979          E = EdgeVector.end(); B != E; ++B) {
980     const Record* Edge = *B;
981     const std::string& NodeA = Edge->getValueAsString("a");
982     const std::string& NodeB = Edge->getValueAsString("b");
983     StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
984     StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
985
986     if (NodeA != "root") {
987       if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
988         throw "Edge " + NodeA + "->" + NodeB
989           + ": output->input language mismatch";
990     }
991
992     if (NodeB == "root")
993       throw std::string("Edges back to the root are not allowed!");
994   }
995 }
996
997 /// WalkCase - Walks the 'case' expression DAG and invokes
998 /// TestCallback on every test, and StatementCallback on every
999 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
1000 /// combinators (that is, they are passed directly to TestCallback).
1001 /// TestCallback must have type 'void TestCallback(const DagInit*, unsigned
1002 /// IndentLevel, bool FirstTest)'.
1003 /// StatementCallback must have type 'void StatementCallback(const Init*,
1004 /// unsigned IndentLevel)'.
1005 template <typename F1, typename F2>
1006 void WalkCase(const Init* Case, F1 TestCallback, F2 StatementCallback,
1007               unsigned IndentLevel = 0)
1008 {
1009   const DagInit& d = InitPtrToDag(Case);
1010
1011   // Error checks.
1012   if (GetOperatorName(d) != "case")
1013     throw std::string("WalkCase should be invoked only on 'case' expressions!");
1014
1015   if (d.getNumArgs() < 2)
1016     throw "There should be at least one clause in the 'case' expression:\n"
1017       + d.getAsString();
1018
1019   // Main loop.
1020   bool even = false;
1021   const unsigned numArgs = d.getNumArgs();
1022   unsigned i = 1;
1023   for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1024        B != E; ++B) {
1025     Init* arg = *B;
1026
1027     if (!even)
1028     {
1029       // Handle test.
1030       const DagInit& Test = InitPtrToDag(arg);
1031
1032       if (GetOperatorName(Test) == "default" && (i+1 != numArgs))
1033         throw std::string("The 'default' clause should be the last in the"
1034                           "'case' construct!");
1035       if (i == numArgs)
1036         throw "Case construct handler: no corresponding action "
1037           "found for the test " + Test.getAsString() + '!';
1038
1039       TestCallback(&Test, IndentLevel, (i == 1));
1040     }
1041     else
1042     {
1043       if (dynamic_cast<DagInit*>(arg)
1044           && GetOperatorName(static_cast<DagInit*>(arg)) == "case") {
1045         // Nested 'case'.
1046         WalkCase(arg, TestCallback, StatementCallback, IndentLevel + Indent1);
1047       }
1048
1049       // Handle statement.
1050       StatementCallback(arg, IndentLevel);
1051     }
1052
1053     ++i;
1054     even = !even;
1055   }
1056 }
1057
1058 /// ExtractOptionNames - A helper function object used by
1059 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
1060 class ExtractOptionNames {
1061   llvm::StringSet<>& OptionNames_;
1062
1063   void processDag(const Init* Statement) {
1064     const DagInit& Stmt = InitPtrToDag(Statement);
1065     const std::string& ActionName = GetOperatorName(Stmt);
1066     if (ActionName == "forward" || ActionName == "forward_as" ||
1067         ActionName == "forward_value" ||
1068         ActionName == "forward_transformed_value" ||
1069         ActionName == "switch_on" || ActionName == "parameter_equals" ||
1070         ActionName == "element_in_list" || ActionName == "not_empty" ||
1071         ActionName == "empty") {
1072       checkNumberOfArguments(&Stmt, 1);
1073       const std::string& Name = InitPtrToString(Stmt.getArg(0));
1074       OptionNames_.insert(Name);
1075     }
1076     else if (ActionName == "and" || ActionName == "or") {
1077       for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
1078         this->processDag(Stmt.getArg(i));
1079       }
1080     }
1081   }
1082
1083 public:
1084   ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
1085   {}
1086
1087   void operator()(const Init* Statement) {
1088     if (typeid(*Statement) == typeid(ListInit)) {
1089       const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1090       for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1091            B != E; ++B)
1092         this->processDag(*B);
1093     }
1094     else {
1095       this->processDag(Statement);
1096     }
1097   }
1098
1099   void operator()(const DagInit* Test, unsigned, bool) {
1100     this->operator()(Test);
1101   }
1102   void operator()(const Init* Statement, unsigned) {
1103     this->operator()(Statement);
1104   }
1105 };
1106
1107 /// CheckForSuperfluousOptions - Check that there are no side
1108 /// effect-free options (specified only in the OptionList). Otherwise,
1109 /// output a warning.
1110 void CheckForSuperfluousOptions (const RecordVector& Edges,
1111                                  const ToolDescriptions& ToolDescs,
1112                                  const OptionDescriptions& OptDescs) {
1113   llvm::StringSet<> nonSuperfluousOptions;
1114
1115   // Add all options mentioned in the ToolDesc.Actions to the set of
1116   // non-superfluous options.
1117   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1118          E = ToolDescs.end(); B != E; ++B) {
1119     const ToolDescription& TD = *(*B);
1120     ExtractOptionNames Callback(nonSuperfluousOptions);
1121     if (TD.Actions)
1122       WalkCase(TD.Actions, Callback, Callback);
1123   }
1124
1125   // Add all options mentioned in the 'case' clauses of the
1126   // OptionalEdges of the compilation graph to the set of
1127   // non-superfluous options.
1128   for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
1129        B != E; ++B) {
1130     const Record* Edge = *B;
1131     DagInit* Weight = Edge->getValueAsDag("weight");
1132
1133     if (!isDagEmpty(Weight))
1134       WalkCase(Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
1135   }
1136
1137   // Check that all options in OptDescs belong to the set of
1138   // non-superfluous options.
1139   for (OptionDescriptions::const_iterator B = OptDescs.begin(),
1140          E = OptDescs.end(); B != E; ++B) {
1141     const OptionDescription& Val = B->second;
1142     if (!nonSuperfluousOptions.count(Val.Name)
1143         && Val.Type != OptionType::Alias)
1144       llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! "
1145         "Probable cause: this option is specified only in the OptionList.\n";
1146   }
1147 }
1148
1149 /// EmitCaseTest0Args - Helper function used by EmitCaseConstructHandler().
1150 bool EmitCaseTest0Args(const std::string& TestName, raw_ostream& O) {
1151   if (TestName == "single_input_file") {
1152     O << "InputFilenames.size() == 1";
1153     return true;
1154   }
1155   else if (TestName == "multiple_input_files") {
1156     O << "InputFilenames.size() > 1";
1157     return true;
1158   }
1159
1160   return false;
1161 }
1162
1163 /// EmitListTest - Helper function used by EmitCaseTest1ArgList().
1164 template <typename F>
1165 void EmitListTest(const ListInit& L, const char* LogicOp,
1166                   F Callback, raw_ostream& O)
1167 {
1168   // This is a lot like EmitLogicalOperationTest, but works on ListInits instead
1169   // of Dags...
1170   bool isFirst = true;
1171   for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B) {
1172     if (isFirst)
1173       isFirst = false;
1174     else
1175       O << " || ";
1176     Callback(InitPtrToString(*B), O);
1177   }
1178 }
1179
1180 // Callbacks for use with EmitListTest.
1181
1182 class EmitSwitchOn {
1183   const OptionDescriptions& OptDescs_;
1184 public:
1185   EmitSwitchOn(const OptionDescriptions& OptDescs) : OptDescs_(OptDescs)
1186   {}
1187
1188   void operator()(const std::string& OptName, raw_ostream& O) const {
1189     const OptionDescription& OptDesc = OptDescs_.FindSwitch(OptName);
1190     O << OptDesc.GenVariableName();
1191   }
1192 };
1193
1194 class EmitEmptyTest {
1195   bool EmitNegate_;
1196   const OptionDescriptions& OptDescs_;
1197 public:
1198   EmitEmptyTest(bool EmitNegate, const OptionDescriptions& OptDescs)
1199     : EmitNegate_(EmitNegate), OptDescs_(OptDescs)
1200   {}
1201
1202   void operator()(const std::string& OptName, raw_ostream& O) const {
1203     const char* Neg = (EmitNegate_ ? "!" : "");
1204     if (OptName == "o") {
1205       O << Neg << "OutputFilename.empty()";
1206     }
1207     else if (OptName == "save-temps") {
1208       O << Neg << "(SaveTemps == SaveTempsEnum::Unset)";
1209     }
1210     else {
1211       const OptionDescription& OptDesc = OptDescs_.FindListOrParameter(OptName);
1212       O << Neg << OptDesc.GenVariableName() << ".empty()";
1213     }
1214   }
1215 };
1216
1217
1218 /// EmitCaseTest1ArgList - Helper function used by EmitCaseTest1Arg();
1219 bool EmitCaseTest1ArgList(const std::string& TestName,
1220                           const DagInit& d,
1221                           const OptionDescriptions& OptDescs,
1222                           raw_ostream& O) {
1223   const ListInit& L = *static_cast<ListInit*>(d.getArg(0));
1224
1225   if (TestName == "any_switch_on") {
1226     EmitListTest(L, "||", EmitSwitchOn(OptDescs), O);
1227     return true;
1228   }
1229   else if (TestName == "switch_on") {
1230     EmitListTest(L, "&&", EmitSwitchOn(OptDescs), O);
1231     return true;
1232   }
1233   else if (TestName == "any_not_empty") {
1234     EmitListTest(L, "||", EmitEmptyTest(true, OptDescs), O);
1235     return true;
1236   }
1237   else if (TestName == "any_empty") {
1238     EmitListTest(L, "||", EmitEmptyTest(false, OptDescs), O);
1239     return true;
1240   }
1241   else if (TestName == "not_empty") {
1242     EmitListTest(L, "&&", EmitEmptyTest(true, OptDescs), O);
1243     return true;
1244   }
1245   else if (TestName == "empty") {
1246     EmitListTest(L, "&&", EmitEmptyTest(false, OptDescs), O);
1247     return true;
1248   }
1249
1250   return false;
1251 }
1252
1253 /// EmitCaseTest1ArgStr - Helper function used by EmitCaseTest1Arg();
1254 bool EmitCaseTest1ArgStr(const std::string& TestName,
1255                          const DagInit& d,
1256                          const OptionDescriptions& OptDescs,
1257                          raw_ostream& O) {
1258   const std::string& OptName = InitPtrToString(d.getArg(0));
1259
1260   if (TestName == "switch_on") {
1261     apply(EmitSwitchOn(OptDescs), OptName, O);
1262     return true;
1263   }
1264   else if (TestName == "input_languages_contain") {
1265     O << "InLangs.count(\"" << OptName << "\") != 0";
1266     return true;
1267   }
1268   else if (TestName == "in_language") {
1269     // This works only for single-argument Tool::GenerateAction. Join
1270     // tools can process several files in different languages simultaneously.
1271
1272     // TODO: make this work with Edge::Weight (if possible).
1273     O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
1274     return true;
1275   }
1276   else if (TestName == "not_empty" || TestName == "empty") {
1277     bool EmitNegate = (TestName == "not_empty");
1278     apply(EmitEmptyTest(EmitNegate, OptDescs), OptName, O);
1279     return true;
1280   }
1281
1282   return false;
1283 }
1284
1285 /// EmitCaseTest1Arg - Helper function used by EmitCaseConstructHandler();
1286 bool EmitCaseTest1Arg(const std::string& TestName,
1287                       const DagInit& d,
1288                       const OptionDescriptions& OptDescs,
1289                       raw_ostream& O) {
1290   checkNumberOfArguments(&d, 1);
1291   if (typeid(*d.getArg(0)) == typeid(ListInit))
1292     return EmitCaseTest1ArgList(TestName, d, OptDescs, O);
1293   else
1294     return EmitCaseTest1ArgStr(TestName, d, OptDescs, O);
1295 }
1296
1297 /// EmitCaseTest2Args - Helper function used by EmitCaseConstructHandler().
1298 bool EmitCaseTest2Args(const std::string& TestName,
1299                        const DagInit& d,
1300                        unsigned IndentLevel,
1301                        const OptionDescriptions& OptDescs,
1302                        raw_ostream& O) {
1303   checkNumberOfArguments(&d, 2);
1304   const std::string& OptName = InitPtrToString(d.getArg(0));
1305   const std::string& OptArg = InitPtrToString(d.getArg(1));
1306
1307   if (TestName == "parameter_equals") {
1308     const OptionDescription& OptDesc = OptDescs.FindParameter(OptName);
1309     O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
1310     return true;
1311   }
1312   else if (TestName == "element_in_list") {
1313     const OptionDescription& OptDesc = OptDescs.FindList(OptName);
1314     const std::string& VarName = OptDesc.GenVariableName();
1315     O << "std::find(" << VarName << ".begin(),\n";
1316     O.indent(IndentLevel + Indent1)
1317       << VarName << ".end(), \""
1318       << OptArg << "\") != " << VarName << ".end()";
1319     return true;
1320   }
1321
1322   return false;
1323 }
1324
1325 // Forward declaration.
1326 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
1327 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1328                   const OptionDescriptions& OptDescs,
1329                   raw_ostream& O);
1330
1331 /// EmitLogicalOperationTest - Helper function used by
1332 /// EmitCaseConstructHandler.
1333 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
1334                               unsigned IndentLevel,
1335                               const OptionDescriptions& OptDescs,
1336                               raw_ostream& O) {
1337   O << '(';
1338   for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
1339     const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
1340     EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1341     if (j != NumArgs - 1) {
1342       O << ")\n";
1343       O.indent(IndentLevel + Indent1) << ' ' << LogicOp << " (";
1344     }
1345     else {
1346       O << ')';
1347     }
1348   }
1349 }
1350
1351 void EmitLogicalNot(const DagInit& d, unsigned IndentLevel,
1352                     const OptionDescriptions& OptDescs, raw_ostream& O)
1353 {
1354   checkNumberOfArguments(&d, 1);
1355   const DagInit& InnerTest = InitPtrToDag(d.getArg(0));
1356   O << "! (";
1357   EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1358   O << ")";
1359 }
1360
1361 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
1362 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1363                   const OptionDescriptions& OptDescs,
1364                   raw_ostream& O) {
1365   const std::string& TestName = GetOperatorName(d);
1366
1367   if (TestName == "and")
1368     EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
1369   else if (TestName == "or")
1370     EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
1371   else if (TestName == "not")
1372     EmitLogicalNot(d, IndentLevel, OptDescs, O);
1373   else if (EmitCaseTest0Args(TestName, O))
1374     return;
1375   else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
1376     return;
1377   else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
1378     return;
1379   else
1380     throw TestName + ": unknown edge property!";
1381 }
1382
1383
1384 /// EmitCaseTestCallback - Callback used by EmitCaseConstructHandler.
1385 class EmitCaseTestCallback {
1386   bool EmitElseIf_;
1387   const OptionDescriptions& OptDescs_;
1388   raw_ostream& O_;
1389 public:
1390
1391   EmitCaseTestCallback(bool EmitElseIf,
1392                        const OptionDescriptions& OptDescs, raw_ostream& O)
1393     : EmitElseIf_(EmitElseIf), OptDescs_(OptDescs), O_(O)
1394   {}
1395
1396   void operator()(const DagInit* Test, unsigned IndentLevel, bool FirstTest)
1397   {
1398     if (GetOperatorName(Test) == "default") {
1399       O_.indent(IndentLevel) << "else {\n";
1400     }
1401     else {
1402       O_.indent(IndentLevel)
1403         << ((!FirstTest && EmitElseIf_) ? "else if (" : "if (");
1404       EmitCaseTest(*Test, IndentLevel, OptDescs_, O_);
1405       O_ << ") {\n";
1406     }
1407   }
1408 };
1409
1410 /// EmitCaseStatementCallback - Callback used by EmitCaseConstructHandler.
1411 template <typename F>
1412 class EmitCaseStatementCallback {
1413   F Callback_;
1414   raw_ostream& O_;
1415 public:
1416
1417   EmitCaseStatementCallback(F Callback, raw_ostream& O)
1418     : Callback_(Callback), O_(O)
1419   {}
1420
1421   void operator() (const Init* Statement, unsigned IndentLevel) {
1422
1423     // Ignore nested 'case' DAG.
1424     if (!(dynamic_cast<const DagInit*>(Statement) &&
1425           GetOperatorName(static_cast<const DagInit*>(Statement)) == "case")) {
1426       if (typeid(*Statement) == typeid(ListInit)) {
1427         const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1428         for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1429              B != E; ++B)
1430           Callback_(*B, (IndentLevel + Indent1), O_);
1431       }
1432       else {
1433         Callback_(Statement, (IndentLevel + Indent1), O_);
1434       }
1435     }
1436     O_.indent(IndentLevel) << "}\n";
1437   }
1438
1439 };
1440
1441 /// EmitCaseConstructHandler - Emit code that handles the 'case'
1442 /// construct. Takes a function object that should emit code for every case
1443 /// clause. Implemented on top of WalkCase.
1444 /// Callback's type is void F(Init* Statement, unsigned IndentLevel,
1445 /// raw_ostream& O).
1446 /// EmitElseIf parameter controls the type of condition that is emitted ('if
1447 /// (..) {..} else if (..) {} .. else {..}' vs. 'if (..) {..} if(..)  {..}
1448 /// .. else {..}').
1449 template <typename F>
1450 void EmitCaseConstructHandler(const Init* Case, unsigned IndentLevel,
1451                               F Callback, bool EmitElseIf,
1452                               const OptionDescriptions& OptDescs,
1453                               raw_ostream& O) {
1454   WalkCase(Case, EmitCaseTestCallback(EmitElseIf, OptDescs, O),
1455            EmitCaseStatementCallback<F>(Callback, O), IndentLevel);
1456 }
1457
1458 /// TokenizeCmdline - converts from "$CALL(HookName, 'Arg1', 'Arg2')/path" to
1459 /// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path"] .
1460 /// Helper function used by EmitCmdLineVecFill and.
1461 void TokenizeCmdline(const std::string& CmdLine, StrVector& Out) {
1462   const char* Delimiters = " \t\n\v\f\r";
1463   enum TokenizerState
1464   { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1465   cur_st  = Normal;
1466
1467   if (CmdLine.empty())
1468     return;
1469   Out.push_back("");
1470
1471   std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1472     E = CmdLine.size();
1473
1474   for (; B != E; ++B) {
1475     char cur_ch = CmdLine[B];
1476
1477     switch (cur_st) {
1478     case Normal:
1479       if (cur_ch == '$') {
1480         cur_st = SpecialCommand;
1481         break;
1482       }
1483       if (oneOf(Delimiters, cur_ch)) {
1484         // Skip whitespace
1485         B = CmdLine.find_first_not_of(Delimiters, B);
1486         if (B == std::string::npos) {
1487           B = E-1;
1488           continue;
1489         }
1490         --B;
1491         Out.push_back("");
1492         continue;
1493       }
1494       break;
1495
1496
1497     case SpecialCommand:
1498       if (oneOf(Delimiters, cur_ch)) {
1499         cur_st = Normal;
1500         Out.push_back("");
1501         continue;
1502       }
1503       if (cur_ch == '(') {
1504         Out.push_back("");
1505         cur_st = InsideSpecialCommand;
1506         continue;
1507       }
1508       break;
1509
1510     case InsideSpecialCommand:
1511       if (oneOf(Delimiters, cur_ch)) {
1512         continue;
1513       }
1514       if (cur_ch == '\'') {
1515         cur_st = InsideQuotationMarks;
1516         Out.push_back("");
1517         continue;
1518       }
1519       if (cur_ch == ')') {
1520         cur_st = Normal;
1521         Out.push_back("");
1522       }
1523       if (cur_ch == ',') {
1524         continue;
1525       }
1526
1527       break;
1528
1529     case InsideQuotationMarks:
1530       if (cur_ch == '\'') {
1531         cur_st = InsideSpecialCommand;
1532         continue;
1533       }
1534       break;
1535     }
1536
1537     Out.back().push_back(cur_ch);
1538   }
1539 }
1540
1541 /// SubstituteSpecialCommands - Perform string substitution for $CALL
1542 /// and $ENV. Helper function used by EmitCmdLineVecFill().
1543 StrVector::const_iterator SubstituteSpecialCommands
1544 (StrVector::const_iterator Pos, StrVector::const_iterator End, raw_ostream& O)
1545 {
1546
1547   const std::string& cmd = *Pos;
1548
1549   if (cmd == "$CALL") {
1550     checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1551     const std::string& CmdName = *Pos;
1552
1553     if (CmdName == ")")
1554       throw std::string("$CALL invocation: empty argument list!");
1555
1556     O << "hooks::";
1557     O << CmdName << "(";
1558
1559
1560     bool firstIteration = true;
1561     while (true) {
1562       checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1563       const std::string& Arg = *Pos;
1564       assert(Arg.size() != 0);
1565
1566       if (Arg[0] == ')')
1567         break;
1568
1569       if (firstIteration)
1570         firstIteration = false;
1571       else
1572         O << ", ";
1573
1574       O << '"' << Arg << '"';
1575     }
1576
1577     O << ')';
1578
1579   }
1580   else if (cmd == "$ENV") {
1581     checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1582     const std::string& EnvName = *Pos;
1583
1584     if (EnvName == ")")
1585       throw "$ENV invocation: empty argument list!";
1586
1587     O << "checkCString(std::getenv(\"";
1588     O << EnvName;
1589     O << "\"))";
1590
1591     checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1592   }
1593   else {
1594     throw "Unknown special command: " + cmd;
1595   }
1596
1597   const std::string& Leftover = *Pos;
1598   assert(Leftover.at(0) == ')');
1599   if (Leftover.size() != 1)
1600     O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1601
1602   return Pos;
1603 }
1604
1605 /// EmitCmdLineVecFill - Emit code that fills in the command line
1606 /// vector. Helper function used by EmitGenerateActionMethod().
1607 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1608                         bool IsJoin, unsigned IndentLevel,
1609                         raw_ostream& O) {
1610   StrVector StrVec;
1611   TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1612
1613   if (StrVec.empty())
1614     throw "Tool '" + ToolName + "' has empty command line!";
1615
1616   StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1617
1618   // If there is a hook invocation on the place of the first command, skip it.
1619   assert(!StrVec[0].empty());
1620   if (StrVec[0][0] == '$') {
1621     while (I != E && (*I)[0] != ')' )
1622       ++I;
1623
1624     // Skip the ')' symbol.
1625     ++I;
1626   }
1627   else {
1628     ++I;
1629   }
1630
1631   bool hasINFILE = false;
1632
1633   for (; I != E; ++I) {
1634     const std::string& cmd = *I;
1635     assert(!cmd.empty());
1636     O.indent(IndentLevel);
1637     if (cmd.at(0) == '$') {
1638       if (cmd == "$INFILE") {
1639         hasINFILE = true;
1640         if (IsJoin) {
1641           O << "for (PathVector::const_iterator B = inFiles.begin()"
1642             << ", E = inFiles.end();\n";
1643           O.indent(IndentLevel) << "B != E; ++B)\n";
1644           O.indent(IndentLevel + Indent1) << "vec.push_back(B->str());\n";
1645         }
1646         else {
1647           O << "vec.push_back(inFile.str());\n";
1648         }
1649       }
1650       else if (cmd == "$OUTFILE") {
1651         O << "vec.push_back(\"\");\n";
1652         O.indent(IndentLevel) << "out_file_index = vec.size()-1;\n";
1653       }
1654       else {
1655         O << "vec.push_back(";
1656         I = SubstituteSpecialCommands(I, E, O);
1657         O << ");\n";
1658       }
1659     }
1660     else {
1661       O << "vec.push_back(\"" << cmd << "\");\n";
1662     }
1663   }
1664   if (!hasINFILE)
1665     throw "Tool '" + ToolName + "' doesn't take any input!";
1666
1667   O.indent(IndentLevel) << "cmd = ";
1668   if (StrVec[0][0] == '$')
1669     SubstituteSpecialCommands(StrVec.begin(), StrVec.end(), O);
1670   else
1671     O << '"' << StrVec[0] << '"';
1672   O << ";\n";
1673 }
1674
1675 /// EmitCmdLineVecFillCallback - A function object wrapper around
1676 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1677 /// argument to EmitCaseConstructHandler().
1678 class EmitCmdLineVecFillCallback {
1679   bool IsJoin;
1680   const std::string& ToolName;
1681  public:
1682   EmitCmdLineVecFillCallback(bool J, const std::string& TN)
1683     : IsJoin(J), ToolName(TN) {}
1684
1685   void operator()(const Init* Statement, unsigned IndentLevel,
1686                   raw_ostream& O) const
1687   {
1688     EmitCmdLineVecFill(Statement, ToolName, IsJoin, IndentLevel, O);
1689   }
1690 };
1691
1692 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1693 /// implement EmitActionHandler. Emits code for
1694 /// handling the (forward) and (forward_as) option properties.
1695 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1696                                             unsigned IndentLevel,
1697                                             const std::string& NewName,
1698                                             raw_ostream& O) {
1699   const std::string& Name = NewName.empty()
1700     ? ("-" + D.Name)
1701     : NewName;
1702   unsigned IndentLevel1 = IndentLevel + Indent1;
1703
1704   switch (D.Type) {
1705   case OptionType::Switch:
1706     O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1707     break;
1708   case OptionType::Parameter:
1709     O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1710     O.indent(IndentLevel) << "vec.push_back(" << D.GenVariableName() << ");\n";
1711     break;
1712   case OptionType::Prefix:
1713     O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\" + "
1714                           << D.GenVariableName() << ");\n";
1715     break;
1716   case OptionType::PrefixList:
1717     O.indent(IndentLevel)
1718       << "for (" << D.GenTypeDeclaration()
1719       << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1720     O.indent(IndentLevel)
1721       << "E = " << D.GenVariableName() << ".end(); B != E;) {\n";
1722     O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\" + " << "*B);\n";
1723     O.indent(IndentLevel1) << "++B;\n";
1724
1725     for (int i = 1, j = D.MultiVal; i < j; ++i) {
1726       O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1727       O.indent(IndentLevel1) << "++B;\n";
1728     }
1729
1730     O.indent(IndentLevel) << "}\n";
1731     break;
1732   case OptionType::ParameterList:
1733     O.indent(IndentLevel)
1734       << "for (" << D.GenTypeDeclaration() << "::iterator B = "
1735       << D.GenVariableName() << ".begin(),\n";
1736     O.indent(IndentLevel) << "E = " << D.GenVariableName()
1737                           << ".end() ; B != E;) {\n";
1738     O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\");\n";
1739
1740     for (int i = 0, j = D.MultiVal; i < j; ++i) {
1741       O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1742       O.indent(IndentLevel1) << "++B;\n";
1743     }
1744
1745     O.indent(IndentLevel) << "}\n";
1746     break;
1747   case OptionType::Alias:
1748   default:
1749     throw std::string("Aliases are not allowed in tool option descriptions!");
1750   }
1751 }
1752
1753 /// ActionHandlingCallbackBase - Base class of EmitActionHandlersCallback and
1754 /// EmitPreprocessOptionsCallback.
1755 struct ActionHandlingCallbackBase {
1756
1757   void onErrorDag(const DagInit& d,
1758                   unsigned IndentLevel, raw_ostream& O) const
1759   {
1760     O.indent(IndentLevel)
1761       << "throw std::runtime_error(\"" <<
1762       (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0))
1763        : "Unknown error!")
1764       << "\");\n";
1765   }
1766
1767   void onWarningDag(const DagInit& d,
1768                     unsigned IndentLevel, raw_ostream& O) const
1769   {
1770     checkNumberOfArguments(&d, 1);
1771     O.indent(IndentLevel) << "llvm::errs() << \""
1772                           << InitPtrToString(d.getArg(0)) << "\";\n";
1773   }
1774
1775 };
1776
1777 /// EmitActionHandlersCallback - Emit code that handles actions. Used by
1778 /// EmitGenerateActionMethod() as an argument to EmitCaseConstructHandler().
1779 class EmitActionHandlersCallback;
1780 typedef void (EmitActionHandlersCallback::* EmitActionHandlersCallbackHandler)
1781 (const DagInit&, unsigned, raw_ostream&) const;
1782
1783 class EmitActionHandlersCallback
1784 : public ActionHandlingCallbackBase,
1785   public HandlerTable<EmitActionHandlersCallbackHandler>
1786 {
1787   const OptionDescriptions& OptDescs;
1788   typedef EmitActionHandlersCallbackHandler Handler;
1789
1790   void onAppendCmd (const DagInit& Dag,
1791                     unsigned IndentLevel, raw_ostream& O) const
1792   {
1793     checkNumberOfArguments(&Dag, 1);
1794     const std::string& Cmd = InitPtrToString(Dag.getArg(0));
1795     StrVector Out;
1796     llvm::SplitString(Cmd, Out);
1797
1798     for (StrVector::const_iterator B = Out.begin(), E = Out.end();
1799          B != E; ++B)
1800       O.indent(IndentLevel) << "vec.push_back(\"" << *B << "\");\n";
1801   }
1802
1803   void onForward (const DagInit& Dag,
1804                   unsigned IndentLevel, raw_ostream& O) const
1805   {
1806     checkNumberOfArguments(&Dag, 1);
1807     const std::string& Name = InitPtrToString(Dag.getArg(0));
1808     EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1809                                           IndentLevel, "", O);
1810   }
1811
1812   void onForwardAs (const DagInit& Dag,
1813                     unsigned IndentLevel, raw_ostream& O) const
1814   {
1815     checkNumberOfArguments(&Dag, 2);
1816     const std::string& Name = InitPtrToString(Dag.getArg(0));
1817     const std::string& NewName = InitPtrToString(Dag.getArg(1));
1818     EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1819                                           IndentLevel, NewName, O);
1820   }
1821
1822   void onForwardValue (const DagInit& Dag,
1823                        unsigned IndentLevel, raw_ostream& O) const
1824   {
1825     checkNumberOfArguments(&Dag, 1);
1826     const std::string& Name = InitPtrToString(Dag.getArg(0));
1827     const OptionDescription& D = OptDescs.FindOption(Name);
1828
1829     if (D.isParameter()) {
1830       O.indent(IndentLevel) << "vec.push_back("
1831                             << D.GenVariableName() << ");\n";
1832     }
1833     else if (D.isList()) {
1834       O.indent(IndentLevel) << "std::copy(" << D.GenVariableName()
1835                             << ".begin(), " << D.GenVariableName()
1836                             << ".end(), std::back_inserter(vec));\n";
1837     }
1838     else {
1839       throw "'forward_value' used with a switch or an alias!";
1840     }
1841   }
1842
1843   void onForwardTransformedValue (const DagInit& Dag,
1844                                   unsigned IndentLevel, raw_ostream& O) const
1845   {
1846     checkNumberOfArguments(&Dag, 2);
1847     const std::string& Name = InitPtrToString(Dag.getArg(0));
1848     const std::string& Hook = InitPtrToString(Dag.getArg(1));
1849     const OptionDescription& D = OptDescs.FindOption(Name);
1850
1851     if (D.isParameter() || D.isList()) {
1852       O.indent(IndentLevel) << "vec.push_back(" << "hooks::"
1853                             << Hook << "(" << D.GenVariableName() << "));\n";
1854     }
1855     else {
1856       throw "'forward_transformed_value' used with a switch or an alias!";
1857     }
1858   }
1859
1860
1861   void onOutputSuffix (const DagInit& Dag,
1862                        unsigned IndentLevel, raw_ostream& O) const
1863   {
1864     checkNumberOfArguments(&Dag, 1);
1865     const std::string& OutSuf = InitPtrToString(Dag.getArg(0));
1866     O.indent(IndentLevel) << "output_suffix = \"" << OutSuf << "\";\n";
1867   }
1868
1869   void onStopCompilation (const DagInit& Dag,
1870                           unsigned IndentLevel, raw_ostream& O) const
1871   {
1872     O.indent(IndentLevel) << "stop_compilation = true;\n";
1873   }
1874
1875
1876   void onUnpackValues (const DagInit& Dag,
1877                        unsigned IndentLevel, raw_ostream& O) const
1878   {
1879     throw "'unpack_values' is deprecated. "
1880       "Use 'comma_separated' + 'forward_value' instead!";
1881   }
1882
1883  public:
1884
1885   explicit EmitActionHandlersCallback(const OptionDescriptions& OD)
1886     : OptDescs(OD)
1887   {
1888     if (!staticMembersInitialized_) {
1889       AddHandler("error", &EmitActionHandlersCallback::onErrorDag);
1890       AddHandler("warning", &EmitActionHandlersCallback::onWarningDag);
1891       AddHandler("append_cmd", &EmitActionHandlersCallback::onAppendCmd);
1892       AddHandler("forward", &EmitActionHandlersCallback::onForward);
1893       AddHandler("forward_as", &EmitActionHandlersCallback::onForwardAs);
1894       AddHandler("forward_value", &EmitActionHandlersCallback::onForwardValue);
1895       AddHandler("forward_transformed_value",
1896                  &EmitActionHandlersCallback::onForwardTransformedValue);
1897       AddHandler("output_suffix", &EmitActionHandlersCallback::onOutputSuffix);
1898       AddHandler("stop_compilation",
1899                  &EmitActionHandlersCallback::onStopCompilation);
1900       AddHandler("unpack_values",
1901                  &EmitActionHandlersCallback::onUnpackValues);
1902
1903       staticMembersInitialized_ = true;
1904     }
1905   }
1906
1907   void operator()(const Init* Statement,
1908                   unsigned IndentLevel, raw_ostream& O) const
1909   {
1910     const DagInit& Dag = InitPtrToDag(Statement);
1911     const std::string& ActionName = GetOperatorName(Dag);
1912     Handler h = GetHandler(ActionName);
1913
1914     ((this)->*(h))(Dag, IndentLevel, O);
1915   }
1916 };
1917
1918 bool IsOutFileIndexCheckRequiredStr (const Init* CmdLine) {
1919   StrVector StrVec;
1920   TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1921
1922   for (StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1923        I != E; ++I) {
1924     if (*I == "$OUTFILE")
1925       return false;
1926   }
1927
1928   return true;
1929 }
1930
1931 class IsOutFileIndexCheckRequiredStrCallback {
1932   bool* ret_;
1933
1934 public:
1935   IsOutFileIndexCheckRequiredStrCallback(bool* ret) : ret_(ret)
1936   {}
1937
1938   void operator()(const Init* CmdLine) {
1939     // Ignore nested 'case' DAG.
1940     if (typeid(*CmdLine) == typeid(DagInit))
1941       return;
1942
1943     if (IsOutFileIndexCheckRequiredStr(CmdLine))
1944       *ret_ = true;
1945   }
1946
1947   void operator()(const DagInit* Test, unsigned, bool) {
1948     this->operator()(Test);
1949   }
1950   void operator()(const Init* Statement, unsigned) {
1951     this->operator()(Statement);
1952   }
1953 };
1954
1955 bool IsOutFileIndexCheckRequiredCase (Init* CmdLine) {
1956   bool ret = false;
1957   WalkCase(CmdLine, Id(), IsOutFileIndexCheckRequiredStrCallback(&ret));
1958   return ret;
1959 }
1960
1961 /// IsOutFileIndexCheckRequired - Should we emit an "out_file_index != -1" check
1962 /// in EmitGenerateActionMethod() ?
1963 bool IsOutFileIndexCheckRequired (Init* CmdLine) {
1964   if (typeid(*CmdLine) == typeid(StringInit))
1965     return IsOutFileIndexCheckRequiredStr(CmdLine);
1966   else
1967     return IsOutFileIndexCheckRequiredCase(CmdLine);
1968 }
1969
1970 void EmitGenerateActionMethodHeader(const ToolDescription& D,
1971                                     bool IsJoin, raw_ostream& O)
1972 {
1973   if (IsJoin)
1974     O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
1975   else
1976     O.indent(Indent1) << "Action GenerateAction(const sys::Path& inFile,\n";
1977
1978   O.indent(Indent2) << "bool HasChildren,\n";
1979   O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
1980   O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
1981   O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
1982   O.indent(Indent1) << "{\n";
1983   O.indent(Indent2) << "std::string cmd;\n";
1984   O.indent(Indent2) << "std::vector<std::string> vec;\n";
1985   O.indent(Indent2) << "bool stop_compilation = !HasChildren;\n";
1986   O.indent(Indent2) << "const char* output_suffix = \""
1987                     << D.OutputSuffix << "\";\n";
1988 }
1989
1990 // EmitGenerateActionMethod - Emit either a normal or a "join" version of the
1991 // Tool::GenerateAction() method.
1992 void EmitGenerateActionMethod (const ToolDescription& D,
1993                                const OptionDescriptions& OptDescs,
1994                                bool IsJoin, raw_ostream& O) {
1995
1996   EmitGenerateActionMethodHeader(D, IsJoin, O);
1997
1998   if (!D.CmdLine)
1999     throw "Tool " + D.Name + " has no cmd_line property!";
2000
2001   bool IndexCheckRequired = IsOutFileIndexCheckRequired(D.CmdLine);
2002   O.indent(Indent2) << "int out_file_index"
2003                     << (IndexCheckRequired ? " = -1" : "")
2004                     << ";\n\n";
2005
2006   // Process the cmd_line property.
2007   if (typeid(*D.CmdLine) == typeid(StringInit))
2008     EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
2009   else
2010     EmitCaseConstructHandler(D.CmdLine, Indent2,
2011                              EmitCmdLineVecFillCallback(IsJoin, D.Name),
2012                              true, OptDescs, O);
2013
2014   // For every understood option, emit handling code.
2015   if (D.Actions)
2016     EmitCaseConstructHandler(D.Actions, Indent2,
2017                              EmitActionHandlersCallback(OptDescs),
2018                              false, OptDescs, O);
2019
2020   O << '\n';
2021   O.indent(Indent2)
2022     << "std::string out_file = OutFilename("
2023     << (IsJoin ? "sys::Path(),\n" : "inFile,\n");
2024   O.indent(Indent3) << "TempDir, stop_compilation, output_suffix).str();\n\n";
2025
2026   if (IndexCheckRequired)
2027     O.indent(Indent2) << "if (out_file_index != -1)\n";
2028   O.indent(IndexCheckRequired ? Indent3 : Indent2)
2029     << "vec[out_file_index] = out_file;\n";
2030
2031   // Handle the Sink property.
2032   if (D.isSink()) {
2033     O.indent(Indent2) << "if (!" << SinkOptionName << ".empty()) {\n";
2034     O.indent(Indent3) << "vec.insert(vec.end(), "
2035                       << SinkOptionName << ".begin(), " << SinkOptionName
2036                       << ".end());\n";
2037     O.indent(Indent2) << "}\n";
2038   }
2039
2040   O.indent(Indent2) << "return Action(cmd, vec, stop_compilation, out_file);\n";
2041   O.indent(Indent1) << "}\n\n";
2042 }
2043
2044 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
2045 /// a given Tool class.
2046 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
2047                                 const OptionDescriptions& OptDescs,
2048                                 raw_ostream& O) {
2049   if (!ToolDesc.isJoin()) {
2050     O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
2051     O.indent(Indent2) << "bool HasChildren,\n";
2052     O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
2053     O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
2054     O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
2055     O.indent(Indent1) << "{\n";
2056     O.indent(Indent2) << "throw std::runtime_error(\"" << ToolDesc.Name
2057                       << " is not a Join tool!\");\n";
2058     O.indent(Indent1) << "}\n\n";
2059   }
2060   else {
2061     EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
2062   }
2063
2064   EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
2065 }
2066
2067 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
2068 /// methods for a given Tool class.
2069 void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
2070   O.indent(Indent1) << "const char** InputLanguages() const {\n";
2071   O.indent(Indent2) << "return InputLanguages_;\n";
2072   O.indent(Indent1) << "}\n\n";
2073
2074   if (D.OutLanguage.empty())
2075     throw "Tool " + D.Name + " has no 'out_language' property!";
2076
2077   O.indent(Indent1) << "const char* OutputLanguage() const {\n";
2078   O.indent(Indent2) << "return \"" << D.OutLanguage << "\";\n";
2079   O.indent(Indent1) << "}\n\n";
2080 }
2081
2082 /// EmitNameMethod - Emit the Name() method for a given Tool class.
2083 void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
2084   O.indent(Indent1) << "const char* Name() const {\n";
2085   O.indent(Indent2) << "return \"" << D.Name << "\";\n";
2086   O.indent(Indent1) << "}\n\n";
2087 }
2088
2089 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
2090 /// class.
2091 void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
2092   O.indent(Indent1) << "bool IsJoin() const {\n";
2093   if (D.isJoin())
2094     O.indent(Indent2) << "return true;\n";
2095   else
2096     O.indent(Indent2) << "return false;\n";
2097   O.indent(Indent1) << "}\n\n";
2098 }
2099
2100 /// EmitStaticMemberDefinitions - Emit static member definitions for a
2101 /// given Tool class.
2102 void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
2103   if (D.InLanguage.empty())
2104     throw "Tool " + D.Name + " has no 'in_language' property!";
2105
2106   O << "const char* " << D.Name << "::InputLanguages_[] = {";
2107   for (StrVector::const_iterator B = D.InLanguage.begin(),
2108          E = D.InLanguage.end(); B != E; ++B)
2109     O << '\"' << *B << "\", ";
2110   O << "0};\n\n";
2111 }
2112
2113 /// EmitToolClassDefinition - Emit a Tool class definition.
2114 void EmitToolClassDefinition (const ToolDescription& D,
2115                               const OptionDescriptions& OptDescs,
2116                               raw_ostream& O) {
2117   if (D.Name == "root")
2118     return;
2119
2120   // Header
2121   O << "class " << D.Name << " : public ";
2122   if (D.isJoin())
2123     O << "JoinTool";
2124   else
2125     O << "Tool";
2126
2127   O << "{\nprivate:\n";
2128   O.indent(Indent1) << "static const char* InputLanguages_[];\n\n";
2129
2130   O << "public:\n";
2131   EmitNameMethod(D, O);
2132   EmitInOutLanguageMethods(D, O);
2133   EmitIsJoinMethod(D, O);
2134   EmitGenerateActionMethods(D, OptDescs, O);
2135
2136   // Close class definition
2137   O << "};\n";
2138
2139   EmitStaticMemberDefinitions(D, O);
2140
2141 }
2142
2143 /// EmitOptionDefinitions - Iterate over a list of option descriptions
2144 /// and emit registration code.
2145 void EmitOptionDefinitions (const OptionDescriptions& descs,
2146                             bool HasSink, bool HasExterns,
2147                             raw_ostream& O)
2148 {
2149   std::vector<OptionDescription> Aliases;
2150
2151   // Emit static cl::Option variables.
2152   for (OptionDescriptions::const_iterator B = descs.begin(),
2153          E = descs.end(); B!=E; ++B) {
2154     const OptionDescription& val = B->second;
2155
2156     if (val.Type == OptionType::Alias) {
2157       Aliases.push_back(val);
2158       continue;
2159     }
2160
2161     if (val.isExtern())
2162       O << "extern ";
2163
2164     O << val.GenTypeDeclaration() << ' '
2165       << val.GenVariableName();
2166
2167     if (val.isExtern()) {
2168       O << ";\n";
2169       continue;
2170     }
2171
2172     O << "(\"" << val.Name << "\"\n";
2173
2174     if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
2175       O << ", cl::Prefix";
2176
2177     if (val.isRequired()) {
2178       if (val.isList() && !val.isMultiVal())
2179         O << ", cl::OneOrMore";
2180       else
2181         O << ", cl::Required";
2182     }
2183     else if (val.isOneOrMore() && val.isList()) {
2184         O << ", cl::OneOrMore";
2185     }
2186     else if (val.isZeroOrOne() && val.isList()) {
2187         O << ", cl::ZeroOrOne";
2188     }
2189
2190     if (val.isReallyHidden())
2191       O << ", cl::ReallyHidden";
2192     else if (val.isHidden())
2193       O << ", cl::Hidden";
2194
2195     if (val.isCommaSeparated())
2196       O << ", cl::CommaSeparated";
2197
2198     if (val.MultiVal > 1)
2199       O << ", cl::multi_val(" << val.MultiVal << ')';
2200
2201     if (val.InitVal) {
2202       const std::string& str = val.InitVal->getAsString();
2203       O << ", cl::init(" << str << ')';
2204     }
2205
2206     if (!val.Help.empty())
2207       O << ", cl::desc(\"" << val.Help << "\")";
2208
2209     O << ");\n\n";
2210   }
2211
2212   // Emit the aliases (they should go after all the 'proper' options).
2213   for (std::vector<OptionDescription>::const_iterator
2214          B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
2215     const OptionDescription& val = *B;
2216
2217     O << val.GenTypeDeclaration() << ' '
2218       << val.GenVariableName()
2219       << "(\"" << val.Name << '\"';
2220
2221     const OptionDescription& D = descs.FindOption(val.Help);
2222     O << ", cl::aliasopt(" << D.GenVariableName() << ")";
2223
2224     O << ", cl::desc(\"" << "An alias for -" + val.Help  << "\"));\n";
2225   }
2226
2227   // Emit the sink option.
2228   if (HasSink)
2229     O << (HasExterns ? "extern cl" : "cl")
2230       << "::list<std::string> " << SinkOptionName
2231       << (HasExterns ? ";\n" : "(cl::Sink);\n");
2232
2233   O << '\n';
2234 }
2235
2236 /// EmitPreprocessOptionsCallback - Helper function passed to
2237 /// EmitCaseConstructHandler() by EmitPreprocessOptions().
2238 class EmitPreprocessOptionsCallback : ActionHandlingCallbackBase {
2239   const OptionDescriptions& OptDescs_;
2240
2241   void onUnsetOption(Init* i, unsigned IndentLevel, raw_ostream& O) {
2242     const std::string& OptName = InitPtrToString(i);
2243     const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2244
2245     if (OptDesc.isSwitch()) {
2246       O.indent(IndentLevel) << OptDesc.GenVariableName() << " = false;\n";
2247     }
2248     else if (OptDesc.isParameter()) {
2249       O.indent(IndentLevel) << OptDesc.GenVariableName() << " = \"\";\n";
2250     }
2251     else if (OptDesc.isList()) {
2252       O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2253     }
2254     else {
2255       throw "Can't apply 'unset_option' to alias option '" + OptName + "'!";
2256     }
2257   }
2258
2259   void processDag(const Init* I, unsigned IndentLevel, raw_ostream& O)
2260   {
2261     const DagInit& d = InitPtrToDag(I);
2262     const std::string& OpName = GetOperatorName(d);
2263
2264     if (OpName == "warning") {
2265       this->onWarningDag(d, IndentLevel, O);
2266     }
2267     else if (OpName == "error") {
2268       this->onWarningDag(d, IndentLevel, O);
2269     }
2270     else if (OpName == "unset_option") {
2271       checkNumberOfArguments(&d, 1);
2272       Init* I = d.getArg(0);
2273       if (typeid(*I) == typeid(ListInit)) {
2274         const ListInit& DagList = *static_cast<const ListInit*>(I);
2275         for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
2276              B != E; ++B)
2277           this->onUnsetOption(*B, IndentLevel, O);
2278       }
2279       else {
2280         this->onUnsetOption(I, IndentLevel, O);
2281       }
2282     }
2283     else {
2284       throw "Unknown operator in the option preprocessor: '" + OpName + "'!"
2285         "\nOnly 'warning', 'error' and 'unset_option' are allowed.";
2286     }
2287   }
2288
2289 public:
2290
2291   void operator()(const Init* I, unsigned IndentLevel, raw_ostream& O) {
2292       this->processDag(I, IndentLevel, O);
2293   }
2294
2295   EmitPreprocessOptionsCallback(const OptionDescriptions& OptDescs)
2296   : OptDescs_(OptDescs)
2297   {}
2298 };
2299
2300 /// EmitPreprocessOptions - Emit the PreprocessOptionsLocal() function.
2301 void EmitPreprocessOptions (const RecordKeeper& Records,
2302                             const OptionDescriptions& OptDecs, raw_ostream& O)
2303 {
2304   O << "void PreprocessOptionsLocal() {\n";
2305
2306   const RecordVector& OptionPreprocessors =
2307     Records.getAllDerivedDefinitions("OptionPreprocessor");
2308
2309   for (RecordVector::const_iterator B = OptionPreprocessors.begin(),
2310          E = OptionPreprocessors.end(); B!=E; ++B) {
2311     DagInit* Case = (*B)->getValueAsDag("preprocessor");
2312     EmitCaseConstructHandler(Case, Indent1,
2313                              EmitPreprocessOptionsCallback(OptDecs),
2314                              false, OptDecs, O);
2315   }
2316
2317   O << "}\n\n";
2318 }
2319
2320 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMapLocal() function.
2321 void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
2322 {
2323   O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
2324
2325   // Get the relevant field out of RecordKeeper
2326   const Record* LangMapRecord = Records.getDef("LanguageMap");
2327
2328   // It is allowed for a plugin to have no language map.
2329   if (LangMapRecord) {
2330
2331     ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
2332     if (!LangsToSuffixesList)
2333       throw std::string("Error in the language map definition!");
2334
2335     for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
2336       const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
2337
2338       const std::string& Lang = LangToSuffixes->getValueAsString("lang");
2339       const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
2340
2341       for (unsigned i = 0; i < Suffixes->size(); ++i)
2342         O.indent(Indent1) << "langMap[\""
2343                           << InitPtrToString(Suffixes->getElement(i))
2344                           << "\"] = \"" << Lang << "\";\n";
2345     }
2346   }
2347
2348   O << "}\n\n";
2349 }
2350
2351 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
2352 /// by EmitEdgeClass().
2353 void IncDecWeight (const Init* i, unsigned IndentLevel,
2354                    raw_ostream& O) {
2355   const DagInit& d = InitPtrToDag(i);
2356   const std::string& OpName = GetOperatorName(d);
2357
2358   if (OpName == "inc_weight") {
2359     O.indent(IndentLevel) << "ret += ";
2360   }
2361   else if (OpName == "dec_weight") {
2362     O.indent(IndentLevel) << "ret -= ";
2363   }
2364   else if (OpName == "error") {
2365     checkNumberOfArguments(&d, 1);
2366     O.indent(IndentLevel) << "throw std::runtime_error(\""
2367                           << InitPtrToString(d.getArg(0))
2368                           << "\");\n";
2369     return;
2370   }
2371   else {
2372     throw "Unknown operator in edge properties list: '" + OpName + "'!"
2373       "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
2374   }
2375
2376   if (d.getNumArgs() > 0)
2377     O << InitPtrToInt(d.getArg(0)) << ";\n";
2378   else
2379     O << "2;\n";
2380
2381 }
2382
2383 /// EmitEdgeClass - Emit a single Edge# class.
2384 void EmitEdgeClass (unsigned N, const std::string& Target,
2385                     DagInit* Case, const OptionDescriptions& OptDescs,
2386                     raw_ostream& O) {
2387
2388   // Class constructor.
2389   O << "class Edge" << N << ": public Edge {\n"
2390     << "public:\n";
2391   O.indent(Indent1) << "Edge" << N << "() : Edge(\"" << Target
2392                     << "\") {}\n\n";
2393
2394   // Function Weight().
2395   O.indent(Indent1)
2396     << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n";
2397   O.indent(Indent2) << "unsigned ret = 0;\n";
2398
2399   // Handle the 'case' construct.
2400   EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
2401
2402   O.indent(Indent2) << "return ret;\n";
2403   O.indent(Indent1) << "};\n\n};\n\n";
2404 }
2405
2406 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
2407 void EmitEdgeClasses (const RecordVector& EdgeVector,
2408                       const OptionDescriptions& OptDescs,
2409                       raw_ostream& O) {
2410   int i = 0;
2411   for (RecordVector::const_iterator B = EdgeVector.begin(),
2412          E = EdgeVector.end(); B != E; ++B) {
2413     const Record* Edge = *B;
2414     const std::string& NodeB = Edge->getValueAsString("b");
2415     DagInit* Weight = Edge->getValueAsDag("weight");
2416
2417     if (!isDagEmpty(Weight))
2418       EmitEdgeClass(i, NodeB, Weight, OptDescs, O);
2419     ++i;
2420   }
2421 }
2422
2423 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraphLocal()
2424 /// function.
2425 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
2426                                    const ToolDescriptions& ToolDescs,
2427                                    raw_ostream& O)
2428 {
2429   O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
2430
2431   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2432          E = ToolDescs.end(); B != E; ++B)
2433     O.indent(Indent1) << "G.insertNode(new " << (*B)->Name << "());\n";
2434
2435   O << '\n';
2436
2437   // Insert edges.
2438
2439   int i = 0;
2440   for (RecordVector::const_iterator B = EdgeVector.begin(),
2441          E = EdgeVector.end(); B != E; ++B) {
2442     const Record* Edge = *B;
2443     const std::string& NodeA = Edge->getValueAsString("a");
2444     const std::string& NodeB = Edge->getValueAsString("b");
2445     DagInit* Weight = Edge->getValueAsDag("weight");
2446
2447     O.indent(Indent1) << "G.insertEdge(\"" << NodeA << "\", ";
2448
2449     if (isDagEmpty(Weight))
2450       O << "new SimpleEdge(\"" << NodeB << "\")";
2451     else
2452       O << "new Edge" << i << "()";
2453
2454     O << ");\n";
2455     ++i;
2456   }
2457
2458   O << "}\n\n";
2459 }
2460
2461 /// HookInfo - Information about the hook type and number of arguments.
2462 struct HookInfo {
2463
2464   // A hook can either have a single parameter of type std::vector<std::string>,
2465   // or NumArgs parameters of type const char*.
2466   enum HookType { ListHook, ArgHook };
2467
2468   HookType Type;
2469   unsigned NumArgs;
2470
2471   HookInfo() : Type(ArgHook), NumArgs(1)
2472   {}
2473
2474   HookInfo(HookType T) : Type(T), NumArgs(1)
2475   {}
2476
2477   HookInfo(unsigned N) : Type(ArgHook), NumArgs(N)
2478   {}
2479 };
2480
2481 typedef llvm::StringMap<HookInfo> HookInfoMap;
2482
2483 /// ExtractHookNames - Extract the hook names from all instances of
2484 /// $CALL(HookName) in the provided command line string/action. Helper
2485 /// function used by FillInHookNames().
2486 class ExtractHookNames {
2487   HookInfoMap& HookNames_;
2488   const OptionDescriptions& OptDescs_;
2489 public:
2490   ExtractHookNames(HookInfoMap& HookNames, const OptionDescriptions& OptDescs)
2491     : HookNames_(HookNames), OptDescs_(OptDescs)
2492   {}
2493
2494   void onAction (const DagInit& Dag) {
2495     if (GetOperatorName(Dag) == "forward_transformed_value") {
2496       checkNumberOfArguments(Dag, 2);
2497       const std::string& OptName = InitPtrToString(Dag.getArg(0));
2498       const std::string& HookName = InitPtrToString(Dag.getArg(1));
2499       const OptionDescription& D = OptDescs_.FindOption(OptName);
2500
2501       HookNames_[HookName] = HookInfo(D.isList() ? HookInfo::ListHook
2502                                       : HookInfo::ArgHook);
2503     }
2504   }
2505
2506   void operator()(const Init* Arg) {
2507
2508     // We're invoked on an action (either a dag or a dag list).
2509     if (typeid(*Arg) == typeid(DagInit)) {
2510       const DagInit& Dag = InitPtrToDag(Arg);
2511       this->onAction(Dag);
2512       return;
2513     }
2514     else if (typeid(*Arg) == typeid(ListInit)) {
2515       const ListInit& List = InitPtrToList(Arg);
2516       for (ListInit::const_iterator B = List.begin(), E = List.end(); B != E;
2517            ++B) {
2518         const DagInit& Dag = InitPtrToDag(*B);
2519         this->onAction(Dag);
2520       }
2521       return;
2522     }
2523
2524     // We're invoked on a command line.
2525     StrVector cmds;
2526     TokenizeCmdline(InitPtrToString(Arg), cmds);
2527     for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
2528          B != E; ++B) {
2529       const std::string& cmd = *B;
2530
2531       if (cmd == "$CALL") {
2532         unsigned NumArgs = 0;
2533         checkedIncrement(B, E, "Syntax error in $CALL invocation!");
2534         const std::string& HookName = *B;
2535
2536
2537         if (HookName.at(0) == ')')
2538           throw "$CALL invoked with no arguments!";
2539
2540         while (++B != E && B->at(0) != ')') {
2541           ++NumArgs;
2542         }
2543
2544         HookInfoMap::const_iterator H = HookNames_.find(HookName);
2545
2546         if (H != HookNames_.end() && H->second.NumArgs != NumArgs &&
2547             H->second.Type != HookInfo::ArgHook)
2548           throw "Overloading of hooks is not allowed. Overloaded hook: "
2549             + HookName;
2550         else
2551           HookNames_[HookName] = HookInfo(NumArgs);
2552
2553       }
2554     }
2555   }
2556
2557   void operator()(const DagInit* Test, unsigned, bool) {
2558     this->operator()(Test);
2559   }
2560   void operator()(const Init* Statement, unsigned) {
2561     this->operator()(Statement);
2562   }
2563 };
2564
2565 /// FillInHookNames - Actually extract the hook names from all command
2566 /// line strings. Helper function used by EmitHookDeclarations().
2567 void FillInHookNames(const ToolDescriptions& ToolDescs,
2568                      const OptionDescriptions& OptDescs,
2569                      HookInfoMap& HookNames)
2570 {
2571   // For all tool descriptions:
2572   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2573          E = ToolDescs.end(); B != E; ++B) {
2574     const ToolDescription& D = *(*B);
2575
2576     // Look for 'forward_transformed_value' in 'actions'.
2577     if (D.Actions)
2578       WalkCase(D.Actions, Id(), ExtractHookNames(HookNames, OptDescs));
2579
2580     // Look for hook invocations in 'cmd_line'.
2581     if (!D.CmdLine)
2582       continue;
2583     if (dynamic_cast<StringInit*>(D.CmdLine))
2584       // This is a string.
2585       ExtractHookNames(HookNames, OptDescs).operator()(D.CmdLine);
2586     else
2587       // This is a 'case' construct.
2588       WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames, OptDescs));
2589   }
2590 }
2591
2592 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
2593 /// property records and emit hook function declaration for each
2594 /// instance of $CALL(HookName).
2595 void EmitHookDeclarations(const ToolDescriptions& ToolDescs,
2596                           const OptionDescriptions& OptDescs, raw_ostream& O) {
2597   HookInfoMap HookNames;
2598
2599   FillInHookNames(ToolDescs, OptDescs, HookNames);
2600   if (HookNames.empty())
2601     return;
2602
2603   O << "namespace hooks {\n";
2604   for (HookInfoMap::const_iterator B = HookNames.begin(),
2605          E = HookNames.end(); B != E; ++B) {
2606     const char* HookName = B->first();
2607     const HookInfo& Info = B->second;
2608
2609     O.indent(Indent1) << "std::string " << HookName << "(";
2610
2611     if (Info.Type == HookInfo::ArgHook) {
2612       for (unsigned i = 0, j = Info.NumArgs; i < j; ++i) {
2613         O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
2614       }
2615     }
2616     else {
2617       O << "const std::vector<std::string>& Arg";
2618     }
2619
2620     O <<");\n";
2621   }
2622   O << "}\n\n";
2623 }
2624
2625 /// EmitRegisterPlugin - Emit code to register this plugin.
2626 void EmitRegisterPlugin(int Priority, raw_ostream& O) {
2627   O << "struct Plugin : public llvmc::BasePlugin {\n\n";
2628   O.indent(Indent1) << "int Priority() const { return "
2629                     << Priority << "; }\n\n";
2630   O.indent(Indent1) << "void PreprocessOptions() const\n";
2631   O.indent(Indent1) << "{ PreprocessOptionsLocal(); }\n\n";
2632   O.indent(Indent1) << "void PopulateLanguageMap(LanguageMap& langMap) const\n";
2633   O.indent(Indent1) << "{ PopulateLanguageMapLocal(langMap); }\n\n";
2634   O.indent(Indent1)
2635     << "void PopulateCompilationGraph(CompilationGraph& graph) const\n";
2636   O.indent(Indent1) << "{ PopulateCompilationGraphLocal(graph); }\n"
2637                     << "};\n\n"
2638                     << "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
2639 }
2640
2641 /// EmitIncludes - Emit necessary #include directives and some
2642 /// additional declarations.
2643 void EmitIncludes(raw_ostream& O) {
2644   O << "#include \"llvm/CompilerDriver/BuiltinOptions.h\"\n"
2645     << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
2646     << "#include \"llvm/CompilerDriver/ForceLinkageMacros.h\"\n"
2647     << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
2648     << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
2649
2650     << "#include \"llvm/Support/CommandLine.h\"\n"
2651     << "#include \"llvm/Support/raw_ostream.h\"\n\n"
2652
2653     << "#include <algorithm>\n"
2654     << "#include <cstdlib>\n"
2655     << "#include <iterator>\n"
2656     << "#include <stdexcept>\n\n"
2657
2658     << "using namespace llvm;\n"
2659     << "using namespace llvmc;\n\n"
2660
2661     << "extern cl::opt<std::string> OutputFilename;\n\n"
2662
2663     << "inline const char* checkCString(const char* s)\n"
2664     << "{ return s == NULL ? \"\" : s; }\n\n";
2665 }
2666
2667
2668 /// PluginData - Holds all information about a plugin.
2669 struct PluginData {
2670   OptionDescriptions OptDescs;
2671   bool HasSink;
2672   bool HasExterns;
2673   ToolDescriptions ToolDescs;
2674   RecordVector Edges;
2675   int Priority;
2676 };
2677
2678 /// HasSink - Go through the list of tool descriptions and check if
2679 /// there are any with the 'sink' property set.
2680 bool HasSink(const ToolDescriptions& ToolDescs) {
2681   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2682          E = ToolDescs.end(); B != E; ++B)
2683     if ((*B)->isSink())
2684       return true;
2685
2686   return false;
2687 }
2688
2689 /// HasExterns - Go through the list of option descriptions and check
2690 /// if there are any external options.
2691 bool HasExterns(const OptionDescriptions& OptDescs) {
2692  for (OptionDescriptions::const_iterator B = OptDescs.begin(),
2693          E = OptDescs.end(); B != E; ++B)
2694     if (B->second.isExtern())
2695       return true;
2696
2697   return false;
2698 }
2699
2700 /// CollectPluginData - Collect tool and option properties,
2701 /// compilation graph edges and plugin priority from the parse tree.
2702 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
2703   // Collect option properties.
2704   const RecordVector& OptionLists =
2705     Records.getAllDerivedDefinitions("OptionList");
2706   CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
2707                             Data.OptDescs);
2708
2709   // Collect tool properties.
2710   const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
2711   CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
2712   Data.HasSink = HasSink(Data.ToolDescs);
2713   Data.HasExterns = HasExterns(Data.OptDescs);
2714
2715   // Collect compilation graph edges.
2716   const RecordVector& CompilationGraphs =
2717     Records.getAllDerivedDefinitions("CompilationGraph");
2718   FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
2719                    Data.Edges);
2720
2721   // Calculate the priority of this plugin.
2722   const RecordVector& Priorities =
2723     Records.getAllDerivedDefinitions("PluginPriority");
2724   Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
2725 }
2726
2727 /// CheckPluginData - Perform some sanity checks on the collected data.
2728 void CheckPluginData(PluginData& Data) {
2729   // Filter out all tools not mentioned in the compilation graph.
2730   FilterNotInGraph(Data.Edges, Data.ToolDescs);
2731
2732   // Typecheck the compilation graph.
2733   TypecheckGraph(Data.Edges, Data.ToolDescs);
2734
2735   // Check that there are no options without side effects (specified
2736   // only in the OptionList).
2737   CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
2738
2739 }
2740
2741 void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
2742   // Emit file header.
2743   EmitIncludes(O);
2744
2745   // Emit global option registration code.
2746   EmitOptionDefinitions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
2747
2748   // Emit hook declarations.
2749   EmitHookDeclarations(Data.ToolDescs, Data.OptDescs, O);
2750
2751   O << "namespace {\n\n";
2752
2753   // Emit PreprocessOptionsLocal() function.
2754   EmitPreprocessOptions(Records, Data.OptDescs, O);
2755
2756   // Emit PopulateLanguageMapLocal() function
2757   // (language map maps from file extensions to language names).
2758   EmitPopulateLanguageMap(Records, O);
2759
2760   // Emit Tool classes.
2761   for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
2762          E = Data.ToolDescs.end(); B!=E; ++B)
2763     EmitToolClassDefinition(*(*B), Data.OptDescs, O);
2764
2765   // Emit Edge# classes.
2766   EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
2767
2768   // Emit PopulateCompilationGraphLocal() function.
2769   EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
2770
2771   // Emit code for plugin registration.
2772   EmitRegisterPlugin(Data.Priority, O);
2773
2774   O << "} // End anonymous namespace.\n\n";
2775
2776   // Force linkage magic.
2777   O << "namespace llvmc {\n";
2778   O << "LLVMC_FORCE_LINKAGE_DECL(LLVMC_PLUGIN_NAME) {}\n";
2779   O << "}\n";
2780
2781   // EOF
2782 }
2783
2784
2785 // End of anonymous namespace
2786 }
2787
2788 /// run - The back-end entry point.
2789 void LLVMCConfigurationEmitter::run (raw_ostream &O) {
2790   try {
2791   PluginData Data;
2792
2793   CollectPluginData(Records, Data);
2794   CheckPluginData(Data);
2795
2796   EmitSourceFileHeader("LLVMC Configuration Library", O);
2797   EmitPluginCode(Data, O);
2798
2799   } catch (std::exception& Error) {
2800     throw Error.what() + std::string(" - usually this means a syntax error.");
2801   }
2802 }