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