Filter ToolPropertiesList to exclude all Tools not mentioned in the compilation graph.
[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 "llvm/Support/Streams.h"
23
24 #include <algorithm>
25 #include <cassert>
26 #include <functional>
27 #include <stdexcept>
28 #include <string>
29 #include <typeinfo>
30
31 using namespace llvm;
32
33 namespace {
34
35 //===----------------------------------------------------------------------===//
36 /// Typedefs
37
38 typedef std::vector<Record*> RecordVector;
39 typedef std::vector<std::string> StrVector;
40
41 //===----------------------------------------------------------------------===//
42 /// Constants
43
44 // Indentation strings.
45 const char * Indent1 = "    ";
46 const char * Indent2 = "        ";
47 const char * Indent3 = "            ";
48 const char * Indent4 = "                ";
49
50 // Default help string.
51 const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
52
53 // Name for the "sink" option.
54 const char * SinkOptionName = "AutoGeneratedSinkOption";
55
56 //===----------------------------------------------------------------------===//
57 /// Helper functions
58
59 int InitPtrToInt(const Init* ptr) {
60   const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
61   return val.getValue();
62 }
63
64 const std::string& InitPtrToString(const Init* ptr) {
65   const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
66   return val.getValue();
67 }
68
69 const ListInit& InitPtrToList(const Init* ptr) {
70   const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
71   return val;
72 }
73
74 const DagInit& InitPtrToDag(const Init* ptr) {
75   const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
76   return val;
77 }
78
79 // checkNumberOfArguments - Ensure that the number of args in d is
80 // less than or equal to min_arguments, otherwise throw an exception.
81 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
82   if (d->getNumArgs() < min_arguments)
83     throw "Property " + d->getOperator()->getAsString()
84       + " has too few arguments!";
85 }
86
87 // isDagEmpty - is this DAG marked with an empty marker?
88 bool isDagEmpty (const DagInit* d) {
89   return d->getOperator()->getAsString() == "empty";
90 }
91
92 //===----------------------------------------------------------------------===//
93 /// Back-end specific code
94
95 // A command-line option can have one of the following types:
96 //
97 // Alias - an alias for another option.
98 //
99 // Switch - a simple switch without arguments, e.g. -O2
100 //
101 // Parameter - an option that takes one(and only one) argument, e.g. -o file,
102 // --output=file
103 //
104 // ParameterList - same as Parameter, but more than one occurence
105 // of the option is allowed, e.g. -lm -lpthread
106 //
107 // Prefix - argument is everything after the prefix,
108 // e.g. -Wa,-foo,-bar, -DNAME=VALUE
109 //
110 // PrefixList - same as Prefix, but more than one option occurence is
111 // allowed.
112
113 namespace OptionType {
114   enum OptionType { Alias, Switch,
115                     Parameter, ParameterList, Prefix, PrefixList};
116 }
117
118 bool IsListOptionType (OptionType::OptionType t) {
119   return (t == OptionType::ParameterList || t == OptionType::PrefixList);
120 }
121
122 // Code duplication here is necessary because one option can affect
123 // several tools and those tools may have different actions associated
124 // with this option. GlobalOptionDescriptions are used to generate
125 // the option registration code, while ToolOptionDescriptions are used
126 // to generate tool-specific code.
127
128 /// OptionDescription - Base class for option descriptions.
129 struct OptionDescription {
130   OptionType::OptionType Type;
131   std::string Name;
132
133   OptionDescription(OptionType::OptionType t = OptionType::Switch,
134                     const std::string& n = "")
135   : Type(t), Name(n)
136   {}
137
138   const char* GenTypeDeclaration() const {
139     switch (Type) {
140     case OptionType::Alias:
141       return "cl::alias";
142     case OptionType::PrefixList:
143     case OptionType::ParameterList:
144       return "cl::list<std::string>";
145     case OptionType::Switch:
146       return "cl::opt<bool>";
147     case OptionType::Parameter:
148     case OptionType::Prefix:
149     default:
150       return "cl::opt<std::string>";
151     }
152   }
153
154   // Escape commas and other symbols not allowed in the C++ variable
155   // names. Makes it possible to use options with names like "Wa,"
156   // (useful for prefix options).
157   std::string EscapeVariableName(const std::string& Var) const {
158     std::string ret;
159     for (unsigned i = 0; i != Var.size(); ++i) {
160       char cur_char = Var[i];
161       if (cur_char == ',') {
162         ret += "_comma_";
163       }
164       else if (cur_char == '+') {
165         ret += "_plus_";
166       }
167       else if (cur_char == '-') {
168         ret += "_dash_";
169       }
170       else {
171         ret.push_back(cur_char);
172       }
173     }
174     return ret;
175   }
176
177   std::string GenVariableName() const {
178     const std::string& EscapedName = EscapeVariableName(Name);
179     switch (Type) {
180     case OptionType::Alias:
181      return "AutoGeneratedAlias" + EscapedName;
182     case OptionType::Switch:
183       return "AutoGeneratedSwitch" + EscapedName;
184     case OptionType::Prefix:
185       return "AutoGeneratedPrefix" + EscapedName;
186     case OptionType::PrefixList:
187       return "AutoGeneratedPrefixList" + EscapedName;
188     case OptionType::Parameter:
189       return "AutoGeneratedParameter" + EscapedName;
190     case OptionType::ParameterList:
191     default:
192       return "AutoGeneratedParameterList" + EscapedName;
193     }
194   }
195
196 };
197
198 // Global option description.
199
200 namespace GlobalOptionDescriptionFlags {
201   enum GlobalOptionDescriptionFlags { Required = 0x1 };
202 }
203
204 struct GlobalOptionDescription : public OptionDescription {
205   std::string Help;
206   unsigned Flags;
207
208   // We need to provide a default constructor because
209   // StringMap can only store DefaultConstructible objects.
210   GlobalOptionDescription() : OptionDescription(), Flags(0)
211   {}
212
213   GlobalOptionDescription (OptionType::OptionType t, const std::string& n,
214                            const std::string& h = DefaultHelpString)
215     : OptionDescription(t, n), Help(h), Flags(0)
216   {}
217
218   bool isRequired() const {
219     return Flags & GlobalOptionDescriptionFlags::Required;
220   }
221   void setRequired() {
222     Flags |= GlobalOptionDescriptionFlags::Required;
223   }
224
225   /// Merge - Merge two option descriptions.
226   void Merge (const GlobalOptionDescription& other)
227   {
228     if (other.Type != Type)
229       throw "Conflicting definitions for the option " + Name + "!";
230
231     if (Help == DefaultHelpString)
232       Help = other.Help;
233     else if (other.Help != DefaultHelpString) {
234       llvm::cerr << "Warning: more than one help string defined for option "
235         + Name + "\n";
236     }
237
238     Flags |= other.Flags;
239   }
240 };
241
242 /// GlobalOptionDescriptions - A GlobalOptionDescription array
243 /// together with some flags affecting generation of option
244 /// declarations.
245 struct GlobalOptionDescriptions {
246   typedef StringMap<GlobalOptionDescription> container_type;
247   typedef container_type::const_iterator const_iterator;
248
249   /// Descriptions - A list of GlobalOptionDescriptions.
250   container_type Descriptions;
251   /// HasSink - Should the emitter generate a "cl::sink" option?
252   bool HasSink;
253
254   /// FindOption - exception-throwing wrapper for find().
255   const GlobalOptionDescription& FindOption(const std::string& OptName) const {
256     const_iterator I = Descriptions.find(OptName);
257     if (I != Descriptions.end())
258       return I->second;
259     else
260       throw OptName + ": no such option!";
261   }
262
263   /// insertDescription - Insert new GlobalOptionDescription into
264   /// GlobalOptionDescriptions list
265   void insertDescription (const GlobalOptionDescription& o)
266   {
267     container_type::iterator I = Descriptions.find(o.Name);
268     if (I != Descriptions.end()) {
269       GlobalOptionDescription& D = I->second;
270       D.Merge(o);
271     }
272     else {
273       Descriptions[o.Name] = o;
274     }
275   }
276
277   // Support for STL-style iteration
278   const_iterator begin() const { return Descriptions.begin(); }
279   const_iterator end() const { return Descriptions.end(); }
280 };
281
282
283 // Tool-local option description.
284
285 // Properties without arguments are implemented as flags.
286 namespace ToolOptionDescriptionFlags {
287   enum ToolOptionDescriptionFlags { StopCompilation = 0x1,
288                                     Forward = 0x2, UnpackValues = 0x4};
289 }
290 namespace OptionPropertyType {
291   enum OptionPropertyType { AppendCmd, ForwardAs, OutputSuffix };
292 }
293
294 typedef std::pair<OptionPropertyType::OptionPropertyType, std::string>
295 OptionProperty;
296 typedef SmallVector<OptionProperty, 4> OptionPropertyList;
297
298 struct ToolOptionDescription : public OptionDescription {
299   unsigned Flags;
300   OptionPropertyList Props;
301
302   // StringMap can only store DefaultConstructible objects
303   ToolOptionDescription() : OptionDescription(), Flags(0) {}
304
305   ToolOptionDescription (OptionType::OptionType t, const std::string& n)
306     : OptionDescription(t, n)
307   {}
308
309   // Various boolean properties
310   bool isStopCompilation() const {
311     return Flags & ToolOptionDescriptionFlags::StopCompilation;
312   }
313   void setStopCompilation() {
314     Flags |= ToolOptionDescriptionFlags::StopCompilation;
315   }
316
317   bool isForward() const {
318     return Flags & ToolOptionDescriptionFlags::Forward;
319   }
320   void setForward() {
321     Flags |= ToolOptionDescriptionFlags::Forward;
322   }
323
324   bool isUnpackValues() const {
325     return Flags & ToolOptionDescriptionFlags::UnpackValues;
326   }
327   void setUnpackValues() {
328     Flags |= ToolOptionDescriptionFlags::UnpackValues;
329   }
330
331   void AddProperty (OptionPropertyType::OptionPropertyType t,
332                     const std::string& val)
333   {
334     Props.push_back(std::make_pair(t, val));
335   }
336 };
337
338 typedef StringMap<ToolOptionDescription> ToolOptionDescriptions;
339
340 // Tool information record
341
342 namespace ToolFlags {
343   enum ToolFlags { Join = 0x1, Sink = 0x2 };
344 }
345
346 struct ToolProperties : public RefCountedBase<ToolProperties> {
347   std::string Name;
348   Init* CmdLine;
349   StrVector InLanguage;
350   std::string OutLanguage;
351   std::string OutputSuffix;
352   unsigned Flags;
353   ToolOptionDescriptions OptDescs;
354
355   // Various boolean properties
356   void setSink()      { Flags |= ToolFlags::Sink; }
357   bool isSink() const { return Flags & ToolFlags::Sink; }
358   void setJoin()      { Flags |= ToolFlags::Join; }
359   bool isJoin() const { return Flags & ToolFlags::Join; }
360
361   // Default ctor here is needed because StringMap can only store
362   // DefaultConstructible objects
363   ToolProperties() : CmdLine(0), Flags(0) {}
364   ToolProperties (const std::string& n) : Name(n), CmdLine(0), Flags(0) {}
365 };
366
367
368 /// ToolPropertiesList - A list of Tool information records
369 /// IntrusiveRefCntPtrs are used here because StringMap has no copy
370 /// constructor (and we want to avoid copying ToolProperties anyway).
371 typedef std::vector<IntrusiveRefCntPtr<ToolProperties> > ToolPropertiesList;
372
373
374 /// CollectOptionProperties - Function object for iterating over a
375 /// list (usually, a DAG) of option property records.
376 class CollectOptionProperties {
377 private:
378   // Implementation details.
379
380   /// OptionPropertyHandler - a function that extracts information
381   /// about a given option property from its DAG representation.
382   typedef void (CollectOptionProperties::* OptionPropertyHandler)
383   (const DagInit*);
384
385   /// OptionPropertyHandlerMap - A map from option property names to
386   /// option property handlers
387   typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
388
389   static OptionPropertyHandlerMap optionPropertyHandlers_;
390   static bool staticMembersInitialized_;
391
392   /// This is where the information is stored
393
394   /// toolProps_ -  Properties of the current Tool.
395   ToolProperties* toolProps_;
396   /// optDescs_ - OptionDescriptions table (used to register options
397   /// globally).
398   GlobalOptionDescription& optDesc_;
399
400 public:
401
402   explicit CollectOptionProperties(ToolProperties* TP,
403                                    GlobalOptionDescription& OD)
404     : toolProps_(TP), optDesc_(OD)
405   {
406     if (!staticMembersInitialized_) {
407       optionPropertyHandlers_["append_cmd"] =
408         &CollectOptionProperties::onAppendCmd;
409       optionPropertyHandlers_["forward"] =
410         &CollectOptionProperties::onForward;
411       optionPropertyHandlers_["forward_as"] =
412         &CollectOptionProperties::onForwardAs;
413       optionPropertyHandlers_["help"] =
414         &CollectOptionProperties::onHelp;
415       optionPropertyHandlers_["output_suffix"] =
416         &CollectOptionProperties::onOutputSuffix;
417       optionPropertyHandlers_["required"] =
418         &CollectOptionProperties::onRequired;
419       optionPropertyHandlers_["stop_compilation"] =
420         &CollectOptionProperties::onStopCompilation;
421       optionPropertyHandlers_["unpack_values"] =
422         &CollectOptionProperties::onUnpackValues;
423
424       staticMembersInitialized_ = true;
425     }
426   }
427
428   /// operator() - Gets called for every option property; Just forwards
429   /// to the corresponding property handler.
430   void operator() (Init* i) {
431     const DagInit& option_property = InitPtrToDag(i);
432     const std::string& option_property_name
433       = option_property.getOperator()->getAsString();
434     OptionPropertyHandlerMap::iterator method
435       = optionPropertyHandlers_.find(option_property_name);
436
437     if (method != optionPropertyHandlers_.end()) {
438       OptionPropertyHandler h = method->second;
439       (this->*h)(&option_property);
440     }
441     else {
442       throw "Unknown option property: " + option_property_name + "!";
443     }
444   }
445
446 private:
447
448   /// Option property handlers --
449   /// Methods that handle properties that are common for all types of
450   /// options (like append_cmd, stop_compilation)
451
452   void onAppendCmd (const DagInit* d) {
453     checkNumberOfArguments(d, 1);
454     checkToolProps(d);
455     const std::string& cmd = InitPtrToString(d->getArg(0));
456
457     toolProps_->OptDescs[optDesc_.Name].
458       AddProperty(OptionPropertyType::AppendCmd, cmd);
459   }
460
461   void onOutputSuffix (const DagInit* d) {
462     checkNumberOfArguments(d, 1);
463     checkToolProps(d);
464     const std::string& suf = InitPtrToString(d->getArg(0));
465
466     if (toolProps_->OptDescs[optDesc_.Name].Type != OptionType::Switch)
467       throw "Option " + optDesc_.Name
468         + " can't have 'output_suffix' property since it isn't a switch!";
469
470     toolProps_->OptDescs[optDesc_.Name].AddProperty
471       (OptionPropertyType::OutputSuffix, suf);
472   }
473
474   void onForward (const DagInit* d) {
475     checkNumberOfArguments(d, 0);
476     checkToolProps(d);
477     toolProps_->OptDescs[optDesc_.Name].setForward();
478   }
479
480   void onForwardAs (const DagInit* d) {
481     checkNumberOfArguments(d, 1);
482     checkToolProps(d);
483     const std::string& cmd = InitPtrToString(d->getArg(0));
484
485     toolProps_->OptDescs[optDesc_.Name].
486       AddProperty(OptionPropertyType::ForwardAs, cmd);
487   }
488
489   void onHelp (const DagInit* d) {
490     checkNumberOfArguments(d, 1);
491     const std::string& help_message = InitPtrToString(d->getArg(0));
492
493     optDesc_.Help = help_message;
494   }
495
496   void onRequired (const DagInit* d) {
497     checkNumberOfArguments(d, 0);
498     checkToolProps(d);
499     optDesc_.setRequired();
500   }
501
502   void onStopCompilation (const DagInit* d) {
503     checkNumberOfArguments(d, 0);
504     checkToolProps(d);
505     if (optDesc_.Type != OptionType::Switch)
506       throw std::string("Only options of type Switch can stop compilation!");
507     toolProps_->OptDescs[optDesc_.Name].setStopCompilation();
508   }
509
510   void onUnpackValues (const DagInit* d) {
511     checkNumberOfArguments(d, 0);
512     checkToolProps(d);
513     toolProps_->OptDescs[optDesc_.Name].setUnpackValues();
514   }
515
516   // Helper functions
517
518   /// checkToolProps - Throw an error if toolProps_ == 0.
519   void checkToolProps(const DagInit* d) {
520     if (!d)
521       throw "Option property " + d->getOperator()->getAsString()
522         + " can't be used in this context";
523   }
524
525 };
526
527 CollectOptionProperties::OptionPropertyHandlerMap
528 CollectOptionProperties::optionPropertyHandlers_;
529
530 bool CollectOptionProperties::staticMembersInitialized_ = false;
531
532
533 /// processOptionProperties - Go through the list of option
534 /// properties and call a corresponding handler for each.
535 void processOptionProperties (const DagInit* d, ToolProperties* t,
536                               GlobalOptionDescription& o) {
537   checkNumberOfArguments(d, 2);
538   DagInit::const_arg_iterator B = d->arg_begin();
539   // Skip the first argument: it's always the option name.
540   ++B;
541   std::for_each(B, d->arg_end(), CollectOptionProperties(t, o));
542 }
543
544 /// AddOption - A function object wrapper for
545 /// processOptionProperties. Used by CollectProperties and
546 /// CollectPropertiesFromOptionList.
547 class AddOption {
548 private:
549   GlobalOptionDescriptions& OptDescs_;
550   ToolProperties* ToolProps_;
551
552 public:
553   explicit AddOption(GlobalOptionDescriptions& OD, ToolProperties* TP = 0)
554     : OptDescs_(OD), ToolProps_(TP)
555   {}
556
557   void operator()(const Init* i) {
558     const DagInit& d = InitPtrToDag(i);
559     checkNumberOfArguments(&d, 2);
560
561     const OptionType::OptionType Type =
562       getOptionType(d.getOperator()->getAsString());
563     const std::string& Name = InitPtrToString(d.getArg(0));
564
565     GlobalOptionDescription OD(Type, Name);
566     if (Type != OptionType::Alias) {
567       processOptionProperties(&d, ToolProps_, OD);
568       if (ToolProps_) {
569         ToolProps_->OptDescs[Name].Type = Type;
570         ToolProps_->OptDescs[Name].Name = Name;
571       }
572     }
573     else {
574       OD.Help = InitPtrToString(d.getArg(1));
575     }
576     OptDescs_.insertDescription(OD);
577   }
578
579 private:
580   OptionType::OptionType getOptionType(const std::string& T) const {
581     if (T == "alias_option")
582       return OptionType::Alias;
583     else if (T == "switch_option")
584       return OptionType::Switch;
585     else if (T == "parameter_option")
586       return OptionType::Parameter;
587     else if (T == "parameter_list_option")
588       return OptionType::ParameterList;
589     else if (T == "prefix_option")
590       return OptionType::Prefix;
591     else if (T == "prefix_list_option")
592       return OptionType::PrefixList;
593     else
594       throw "Unknown option type: " + T + '!';
595   }
596 };
597
598
599 /// CollectProperties - Function object for iterating over a list of
600 /// tool property records.
601 class CollectProperties {
602 private:
603
604   // Implementation details
605
606   /// PropertyHandler - a function that extracts information
607   /// about a given tool property from its DAG representation
608   typedef void (CollectProperties::*PropertyHandler)(const DagInit*);
609
610   /// PropertyHandlerMap - A map from property names to property
611   /// handlers.
612   typedef StringMap<PropertyHandler> PropertyHandlerMap;
613
614   // Static maps from strings to CollectProperties methods("handlers")
615   static PropertyHandlerMap propertyHandlers_;
616   static bool staticMembersInitialized_;
617
618
619   /// This is where the information is stored
620
621   /// toolProps_ -  Properties of the current Tool.
622   ToolProperties& toolProps_;
623   /// optDescs_ - OptionDescriptions table (used to register options
624   /// globally).
625   GlobalOptionDescriptions& optDescs_;
626
627 public:
628
629   explicit CollectProperties (ToolProperties& p, GlobalOptionDescriptions& d)
630     : toolProps_(p), optDescs_(d)
631   {
632     if (!staticMembersInitialized_) {
633       propertyHandlers_["cmd_line"] = &CollectProperties::onCmdLine;
634       propertyHandlers_["in_language"] = &CollectProperties::onInLanguage;
635       propertyHandlers_["join"] = &CollectProperties::onJoin;
636       propertyHandlers_["out_language"] = &CollectProperties::onOutLanguage;
637       propertyHandlers_["output_suffix"] = &CollectProperties::onOutputSuffix;
638       propertyHandlers_["parameter_option"]
639         = &CollectProperties::addOption;
640       propertyHandlers_["parameter_list_option"] =
641         &CollectProperties::addOption;
642       propertyHandlers_["prefix_option"] = &CollectProperties::addOption;
643       propertyHandlers_["prefix_list_option"] =
644         &CollectProperties::addOption;
645       propertyHandlers_["sink"] = &CollectProperties::onSink;
646       propertyHandlers_["switch_option"] = &CollectProperties::addOption;
647       propertyHandlers_["alias_option"] = &CollectProperties::addOption;
648
649       staticMembersInitialized_ = true;
650     }
651   }
652
653   /// operator() - Gets called for every tool property; Just forwards
654   /// to the corresponding property handler.
655   void operator() (Init* i) {
656     const DagInit& d = InitPtrToDag(i);
657     const std::string& property_name = d.getOperator()->getAsString();
658     PropertyHandlerMap::iterator method
659       = propertyHandlers_.find(property_name);
660
661     if (method != propertyHandlers_.end()) {
662       PropertyHandler h = method->second;
663       (this->*h)(&d);
664     }
665     else {
666       throw "Unknown tool property: " + property_name + "!";
667     }
668   }
669
670 private:
671
672   /// Property handlers --
673   /// Functions that extract information about tool properties from
674   /// DAG representation.
675
676   void onCmdLine (const DagInit* d) {
677     checkNumberOfArguments(d, 1);
678     toolProps_.CmdLine = d->getArg(0);
679   }
680
681   void onInLanguage (const DagInit* d) {
682     checkNumberOfArguments(d, 1);
683     Init* arg = d->getArg(0);
684
685     // Find out the argument's type.
686     if (typeid(*arg) == typeid(StringInit)) {
687       // It's a string.
688       toolProps_.InLanguage.push_back(InitPtrToString(arg));
689     }
690     else {
691       // It's a list.
692       const ListInit& lst = InitPtrToList(arg);
693       StrVector& out = toolProps_.InLanguage;
694
695       // Copy strings to the output vector.
696       for (ListInit::const_iterator B = lst.begin(), E = lst.end();
697            B != E; ++B) {
698         out.push_back(InitPtrToString(*B));
699       }
700
701       // Remove duplicates.
702       std::sort(out.begin(), out.end());
703       StrVector::iterator newE = std::unique(out.begin(), out.end());
704       out.erase(newE, out.end());
705     }
706   }
707
708   void onJoin (const DagInit* d) {
709     checkNumberOfArguments(d, 0);
710     toolProps_.setJoin();
711   }
712
713   void onOutLanguage (const DagInit* d) {
714     checkNumberOfArguments(d, 1);
715     toolProps_.OutLanguage = InitPtrToString(d->getArg(0));
716   }
717
718   void onOutputSuffix (const DagInit* d) {
719     checkNumberOfArguments(d, 1);
720     toolProps_.OutputSuffix = InitPtrToString(d->getArg(0));
721   }
722
723   void onSink (const DagInit* d) {
724     checkNumberOfArguments(d, 0);
725     optDescs_.HasSink = true;
726     toolProps_.setSink();
727   }
728
729   // Just forwards to the AddOption function object. Somewhat
730   // non-optimal, but avoids code duplication.
731   void addOption (const DagInit* d) {
732     checkNumberOfArguments(d, 2);
733     AddOption(optDescs_, &toolProps_)(d);
734   }
735
736 };
737
738 // Defintions of static members of CollectProperties.
739 CollectProperties::PropertyHandlerMap CollectProperties::propertyHandlers_;
740 bool CollectProperties::staticMembersInitialized_ = false;
741
742
743 /// CollectToolProperties - Gather information about tool properties
744 /// from the parsed TableGen data (basically a wrapper for the
745 /// CollectProperties function object).
746 void CollectToolProperties (RecordVector::const_iterator B,
747                             RecordVector::const_iterator E,
748                             ToolPropertiesList& TPList,
749                             GlobalOptionDescriptions& OptDescs)
750 {
751   // Iterate over a properties list of every Tool definition
752   for (;B!=E;++B) {
753     const Record* T = *B;
754     // Throws an exception if the value does not exist.
755     ListInit* PropList = T->getValueAsListInit("properties");
756
757     IntrusiveRefCntPtr<ToolProperties>
758       ToolProps(new ToolProperties(T->getName()));
759
760     std::for_each(PropList->begin(), PropList->end(),
761                   CollectProperties(*ToolProps, OptDescs));
762     TPList.push_back(ToolProps);
763   }
764 }
765
766
767 /// CollectPropertiesFromOptionLists - Gather information about
768 /// *global* option properties from all OptionLists.
769 void CollectPropertiesFromOptionLists (RecordVector::const_iterator B,
770                                        RecordVector::const_iterator E,
771                                        GlobalOptionDescriptions& OptDescs)
772 {
773   // Iterate over a properties list of every Tool definition
774   for (;B!=E;++B) {
775     RecordVector::value_type T = *B;
776     // Throws an exception if the value does not exist.
777     ListInit* PropList = T->getValueAsListInit("options");
778
779     std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
780   }
781 }
782
783 /// CheckForSuperfluousOptions - Check that there are no side
784 /// effect-free options (specified only in the OptionList). Otherwise,
785 /// output a warning.
786 void CheckForSuperfluousOptions (const ToolPropertiesList& TPList,
787                                  const GlobalOptionDescriptions& OptDescs) {
788   llvm::StringSet<> nonSuperfluousOptions;
789
790   // Add all options mentioned in the TPList to the set of
791   // non-superfluous options.
792   for (ToolPropertiesList::const_iterator B = TPList.begin(),
793          E = TPList.end(); B != E; ++B) {
794     const ToolProperties& TP = *(*B);
795     for (ToolOptionDescriptions::const_iterator B = TP.OptDescs.begin(),
796            E = TP.OptDescs.end(); B != E; ++B) {
797       nonSuperfluousOptions.insert(B->first());
798     }
799   }
800
801   // Check that all options in OptDescs belong to the set of
802   // non-superfluous options.
803   for (GlobalOptionDescriptions::const_iterator B = OptDescs.begin(),
804          E = OptDescs.end(); B != E; ++B) {
805     const GlobalOptionDescription& Val = B->second;
806     if (!nonSuperfluousOptions.count(Val.Name)
807         && Val.Type != OptionType::Alias)
808       llvm::cerr << "Warning: option '-" << Val.Name << "' has no effect! "
809         "Probable cause: this option is specified only in the OptionList.\n";
810   }
811 }
812
813 /// EmitCaseTest1Arg - Helper function used by
814 /// EmitCaseConstructHandler.
815 bool EmitCaseTest1Arg(const std::string& TestName,
816                       const DagInit& d,
817                       const GlobalOptionDescriptions& OptDescs,
818                       std::ostream& O) {
819   checkNumberOfArguments(&d, 1);
820   const std::string& OptName = InitPtrToString(d.getArg(0));
821   if (TestName == "switch_on") {
822     const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
823     if (OptDesc.Type != OptionType::Switch)
824       throw OptName + ": incorrect option type!";
825     O << OptDesc.GenVariableName();
826     return true;
827   } else if (TestName == "input_languages_contain") {
828     O << "InLangs.count(\"" << OptName << "\") != 0";
829     return true;
830   } else if (TestName == "in_language") {
831     // This works only for single-argument Tool::GenerateAction. Join
832     // tools can process several files in different languages simultaneously.
833
834     // TODO: make this work with Edge::Weight (if possible).
835     O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
836     return true;
837   } else if (TestName == "not_empty") {
838     if (OptName == "o") {
839       O << "!OutputFilename.empty()";
840       return true;
841     }
842     else {
843       const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
844       if (OptDesc.Type == OptionType::Switch)
845         throw OptName + ": incorrect option type!";
846       O << '!' << OptDesc.GenVariableName() << ".empty()";
847       return true;
848     }
849   }
850
851   return false;
852 }
853
854 /// EmitCaseTest2Args - Helper function used by
855 /// EmitCaseConstructHandler.
856 bool EmitCaseTest2Args(const std::string& TestName,
857                        const DagInit& d,
858                        const char* IndentLevel,
859                        const GlobalOptionDescriptions& OptDescs,
860                        std::ostream& O) {
861   checkNumberOfArguments(&d, 2);
862   const std::string& OptName = InitPtrToString(d.getArg(0));
863   const std::string& OptArg = InitPtrToString(d.getArg(1));
864   const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
865
866   if (TestName == "parameter_equals") {
867     if (OptDesc.Type != OptionType::Parameter
868         && OptDesc.Type != OptionType::Prefix)
869       throw OptName + ": incorrect option type!";
870     O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
871     return true;
872   }
873   else if (TestName == "element_in_list") {
874     if (OptDesc.Type != OptionType::ParameterList
875         && OptDesc.Type != OptionType::PrefixList)
876       throw OptName + ": incorrect option type!";
877     const std::string& VarName = OptDesc.GenVariableName();
878     O << "std::find(" << VarName << ".begin(),\n"
879       << IndentLevel << Indent1 << VarName << ".end(), \""
880       << OptArg << "\") != " << VarName << ".end()";
881     return true;
882   }
883
884   return false;
885 }
886
887 // Forward declaration.
888 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
889 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
890                   const GlobalOptionDescriptions& OptDescs,
891                   std::ostream& O);
892
893 /// EmitLogicalOperationTest - Helper function used by
894 /// EmitCaseConstructHandler.
895 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
896                               const char* IndentLevel,
897                               const GlobalOptionDescriptions& OptDescs,
898                               std::ostream& O) {
899   O << '(';
900   for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
901     const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
902     EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
903     if (j != NumArgs - 1)
904       O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
905     else
906       O << ')';
907   }
908 }
909
910 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
911 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
912                   const GlobalOptionDescriptions& OptDescs,
913                   std::ostream& O) {
914   const std::string& TestName = d.getOperator()->getAsString();
915
916   if (TestName == "and")
917     EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
918   else if (TestName == "or")
919     EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
920   else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
921     return;
922   else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
923     return;
924   else
925     throw TestName + ": unknown edge property!";
926 }
927
928 // Emit code that handles the 'case' construct.
929 // Takes a function object that should emit code for every case clause.
930 // Callback's type is
931 // void F(Init* Statement, const char* IndentLevel, std::ostream& O).
932 template <typename F>
933 void EmitCaseConstructHandler(const DagInit* d, const char* IndentLevel,
934                               F Callback, bool EmitElseIf,
935                               const GlobalOptionDescriptions& OptDescs,
936                               std::ostream& O) {
937   assert(d->getOperator()->getAsString() == "case");
938
939   unsigned numArgs = d->getNumArgs();
940   if (d->getNumArgs() < 2)
941     throw "There should be at least one clause in the 'case' expression:\n"
942       + d->getAsString();
943
944   for (unsigned i = 0; i != numArgs; ++i) {
945     const DagInit& Test = InitPtrToDag(d->getArg(i));
946
947     // Emit the test.
948     if (Test.getOperator()->getAsString() == "default") {
949       if (i+2 != numArgs)
950         throw std::string("The 'default' clause should be the last in the"
951                           "'case' construct!");
952       O << IndentLevel << "else {\n";
953     }
954     else {
955       O << IndentLevel << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
956       EmitCaseTest(Test, IndentLevel, OptDescs, O);
957       O << ") {\n";
958     }
959
960     // Emit the corresponding statement.
961     ++i;
962     if (i == numArgs)
963       throw "Case construct handler: no corresponding action "
964         "found for the test " + Test.getAsString() + '!';
965
966     Init* arg = d->getArg(i);
967     if (dynamic_cast<DagInit*>(arg)
968         && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case") {
969       EmitCaseConstructHandler(static_cast<DagInit*>(arg),
970                                (std::string(IndentLevel) + Indent1).c_str(),
971                                Callback, EmitElseIf, OptDescs, O);
972     }
973     else {
974       Callback(arg, IndentLevel, O);
975     }
976     O << IndentLevel << "}\n";
977   }
978 }
979
980 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
981 /// implement EmitOptionPropertyHandlingCode(). Emits code for
982 /// handling the (forward) and (forward_as) option properties.
983 void EmitForwardOptionPropertyHandlingCode (const ToolOptionDescription& D,
984                                             const std::string& NewName,
985                                             std::ostream& O) {
986   const std::string& Name = NewName.empty()
987     ? ("-" + D.Name)
988     : NewName;
989
990   switch (D.Type) {
991   case OptionType::Switch:
992     O << Indent3 << "vec.push_back(\"" << Name << "\");\n";
993     break;
994   case OptionType::Parameter:
995     O << Indent3 << "vec.push_back(\"" << Name << "\");\n";
996     O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
997     break;
998   case OptionType::Prefix:
999     O << Indent3 << "vec.push_back(\"" << Name << "\" + "
1000       << D.GenVariableName() << ");\n";
1001     break;
1002   case OptionType::PrefixList:
1003     O << Indent3 << "for (" << D.GenTypeDeclaration()
1004       << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1005       << Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
1006       << Indent4 << "vec.push_back(\"" << Name << "\" + "
1007       << "*B);\n";
1008     break;
1009   case OptionType::ParameterList:
1010     O << Indent3 << "for (" << D.GenTypeDeclaration()
1011       << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1012       << Indent3 << "E = " << D.GenVariableName()
1013       << ".end() ; B != E; ++B) {\n"
1014       << Indent4 << "vec.push_back(\"" << Name << "\");\n"
1015       << Indent4 << "vec.push_back(*B);\n"
1016       << Indent3 << "}\n";
1017     break;
1018   case OptionType::Alias:
1019   default:
1020     throw std::string("Aliases are not allowed in tool option descriptions!");
1021   }
1022 }
1023
1024 // ToolOptionHasInterestingProperties - A helper function used by
1025 // EmitOptionPropertyHandlingCode() that tells us whether we should
1026 // emit any property handling code at all.
1027 bool ToolOptionHasInterestingProperties(const ToolOptionDescription& D) {
1028   bool ret = false;
1029   for (OptionPropertyList::const_iterator B = D.Props.begin(),
1030          E = D.Props.end(); B != E; ++B) {
1031       const OptionProperty& OptProp = *B;
1032       if (OptProp.first == OptionPropertyType::AppendCmd
1033           || OptProp.first == OptionPropertyType::ForwardAs)
1034         ret = true;
1035     }
1036   if (D.isForward() || D.isUnpackValues())
1037     ret = true;
1038   return ret;
1039 }
1040
1041 /// EmitOptionPropertyHandlingCode - Helper function used by
1042 /// EmitGenerateActionMethod(). Emits code that handles option
1043 /// properties.
1044 void EmitOptionPropertyHandlingCode (const ToolOptionDescription& D,
1045                                      std::ostream& O)
1046 {
1047   if (!ToolOptionHasInterestingProperties(D))
1048     return;
1049   // Start of the if-clause.
1050   O << Indent2 << "if (";
1051   if (D.Type == OptionType::Switch)
1052     O << D.GenVariableName();
1053   else
1054     O << '!' << D.GenVariableName() << ".empty()";
1055
1056   O <<") {\n";
1057
1058   // Handle option properties that take an argument.
1059   for (OptionPropertyList::const_iterator B = D.Props.begin(),
1060         E = D.Props.end(); B!=E; ++B) {
1061     const OptionProperty& val = *B;
1062
1063     switch (val.first) {
1064       // (append_cmd cmd) property
1065     case OptionPropertyType::AppendCmd:
1066       O << Indent3 << "vec.push_back(\"" << val.second << "\");\n";
1067       break;
1068       // (forward_as) property
1069     case OptionPropertyType::ForwardAs:
1070       EmitForwardOptionPropertyHandlingCode(D, val.second, O);
1071       break;
1072       // Other properties with argument
1073     default:
1074       break;
1075     }
1076   }
1077
1078   // Handle flags
1079
1080   // (forward) property
1081   if (D.isForward())
1082     EmitForwardOptionPropertyHandlingCode(D, "", O);
1083
1084   // (unpack_values) property
1085   if (D.isUnpackValues()) {
1086     if (IsListOptionType(D.Type)) {
1087       O << Indent3 << "for (" << D.GenTypeDeclaration()
1088         << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1089         << Indent3 << "E = " << D.GenVariableName()
1090         << ".end(); B != E; ++B)\n"
1091         << Indent4 << "llvm::SplitString(*B, vec, \",\");\n";
1092     }
1093     else if (D.Type == OptionType::Prefix || D.Type == OptionType::Parameter){
1094       O << Indent3 << "llvm::SplitString("
1095         << D.GenVariableName() << ", vec, \",\");\n";
1096     }
1097     else {
1098       throw std::string("Switches can't have unpack_values property!");
1099     }
1100   }
1101
1102   // End of the if-clause.
1103   O << Indent2 << "}\n";
1104 }
1105
1106 /// SubstituteSpecialCommands - Perform string substitution for $CALL
1107 /// and $ENV. Helper function used by EmitCmdLineVecFill().
1108 std::string SubstituteSpecialCommands(const std::string& cmd) {
1109   size_t cparen = cmd.find(")");
1110   std::string ret;
1111
1112   if (cmd.find("$CALL(") == 0) {
1113     if (cmd.size() == 6)
1114       throw std::string("$CALL invocation: empty argument list!");
1115
1116     ret += "hooks::";
1117     ret += std::string(cmd.begin() + 6, cmd.begin() + cparen);
1118     ret += "()";
1119   }
1120   else if (cmd.find("$ENV(") == 0) {
1121     if (cmd.size() == 5)
1122       throw std::string("$ENV invocation: empty argument list!");
1123
1124     ret += "checkCString(std::getenv(\"";
1125     ret += std::string(cmd.begin() + 5, cmd.begin() + cparen);
1126     ret += "\"))";
1127   }
1128   else {
1129     throw "Unknown special command: " + cmd;
1130   }
1131
1132   if (cmd.begin() + cparen + 1 != cmd.end()) {
1133     ret += " + std::string(\"";
1134     ret += (cmd.c_str() + cparen + 1);
1135     ret += "\")";
1136   }
1137
1138   return ret;
1139 }
1140
1141 /// EmitCmdLineVecFill - Emit code that fills in the command line
1142 /// vector. Helper function used by EmitGenerateActionMethod().
1143 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1144                         bool Version, const char* IndentLevel,
1145                         std::ostream& O) {
1146   StrVector StrVec;
1147   SplitString(InitPtrToString(CmdLine), StrVec);
1148   if (StrVec.empty())
1149     throw "Tool " + ToolName + " has empty command line!";
1150
1151   StrVector::const_iterator I = StrVec.begin();
1152   ++I;
1153   for (StrVector::const_iterator E = StrVec.end(); I != E; ++I) {
1154     const std::string& cmd = *I;
1155     O << IndentLevel;
1156     if (cmd.at(0) == '$') {
1157       if (cmd == "$INFILE") {
1158         if (Version)
1159           O << "for (PathVector::const_iterator B = inFiles.begin()"
1160             << ", E = inFiles.end();\n"
1161             << IndentLevel << "B != E; ++B)\n"
1162             << IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
1163         else
1164           O << "vec.push_back(inFile.toString());\n";
1165       }
1166       else if (cmd == "$OUTFILE") {
1167         O << "vec.push_back(outFile.toString());\n";
1168       }
1169       else {
1170         O << "vec.push_back(" << SubstituteSpecialCommands(cmd);
1171         O << ");\n";
1172       }
1173     }
1174     else {
1175       O << "vec.push_back(\"" << cmd << "\");\n";
1176     }
1177   }
1178   O << IndentLevel << "cmd = "
1179     << ((StrVec[0][0] == '$') ? SubstituteSpecialCommands(StrVec[0])
1180         : "\"" + StrVec[0] + "\"")
1181     << ";\n";
1182 }
1183
1184 /// EmitCmdLineVecFillCallback - A function object wrapper around
1185 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1186 /// argument to EmitCaseConstructHandler().
1187 class EmitCmdLineVecFillCallback {
1188   bool Version;
1189   const std::string& ToolName;
1190  public:
1191   EmitCmdLineVecFillCallback(bool Ver, const std::string& TN)
1192     : Version(Ver), ToolName(TN) {}
1193
1194   void operator()(const Init* Statement, const char* IndentLevel,
1195                   std::ostream& O) const
1196   {
1197     EmitCmdLineVecFill(Statement, ToolName, Version,
1198                        (std::string(IndentLevel) + Indent1).c_str(), O);
1199   }
1200 };
1201
1202 // EmitGenerateActionMethod - Emit one of two versions of the
1203 // Tool::GenerateAction() method.
1204 void EmitGenerateActionMethod (const ToolProperties& P,
1205                                const GlobalOptionDescriptions& OptDescs,
1206                                bool Version, std::ostream& O) {
1207   if (Version)
1208     O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
1209   else
1210     O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
1211
1212   O << Indent2 << "const sys::Path& outFile,\n"
1213     << Indent2 << "const InputLanguagesSet& InLangs,\n"
1214     << Indent2 << "const LanguageMap& LangMap) const\n"
1215     << Indent1 << "{\n"
1216     << Indent2 << "std::string cmd;\n"
1217     << Indent2 << "std::vector<std::string> vec;\n";
1218
1219   // cmd_line is either a string or a 'case' construct.
1220   if (typeid(*P.CmdLine) == typeid(StringInit))
1221     EmitCmdLineVecFill(P.CmdLine, P.Name, Version, Indent2, O);
1222   else
1223     EmitCaseConstructHandler(&InitPtrToDag(P.CmdLine), Indent2,
1224                              EmitCmdLineVecFillCallback(Version, P.Name),
1225                              true, OptDescs, O);
1226
1227   // For every understood option, emit handling code.
1228   for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1229         E = P.OptDescs.end(); B != E; ++B) {
1230     const ToolOptionDescription& val = B->second;
1231     EmitOptionPropertyHandlingCode(val, O);
1232   }
1233
1234   // Handle the Sink property.
1235   if (P.isSink()) {
1236     O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
1237       << Indent3 << "vec.insert(vec.end(), "
1238       << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
1239       << Indent2 << "}\n";
1240   }
1241
1242   O << Indent2 << "return Action(cmd, vec);\n"
1243     << Indent1 << "}\n\n";
1244 }
1245
1246 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1247 /// a given Tool class.
1248 void EmitGenerateActionMethods (const ToolProperties& P,
1249                                 const GlobalOptionDescriptions& OptDescs,
1250                                 std::ostream& O) {
1251   if (!P.isJoin())
1252     O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
1253       << Indent2 << "const llvm::sys::Path& outFile,\n"
1254       << Indent2 << "const InputLanguagesSet& InLangs,\n"
1255       << Indent2 << "const LanguageMap& LangMap) const\n"
1256       << Indent1 << "{\n"
1257       << Indent2 << "throw std::runtime_error(\"" << P.Name
1258       << " is not a Join tool!\");\n"
1259       << Indent1 << "}\n\n";
1260   else
1261     EmitGenerateActionMethod(P, OptDescs, true, O);
1262
1263   EmitGenerateActionMethod(P, OptDescs, false, O);
1264 }
1265
1266 /// EmitIsLastMethod - Emit the IsLast() method for a given Tool
1267 /// class.
1268 void EmitIsLastMethod (const ToolProperties& P, std::ostream& O) {
1269   O << Indent1 << "bool IsLast() const {\n"
1270     << Indent2 << "bool last = false;\n";
1271
1272   for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1273         E = P.OptDescs.end(); B != E; ++B) {
1274     const ToolOptionDescription& val = B->second;
1275
1276     if (val.isStopCompilation())
1277       O << Indent2
1278         << "if (" << val.GenVariableName()
1279         << ")\n" << Indent3 << "last = true;\n";
1280   }
1281
1282   O << Indent2 << "return last;\n"
1283     << Indent1 <<  "}\n\n";
1284 }
1285
1286 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1287 /// methods for a given Tool class.
1288 void EmitInOutLanguageMethods (const ToolProperties& P, std::ostream& O) {
1289   O << Indent1 << "const char** InputLanguages() const {\n"
1290     << Indent2 << "return InputLanguages_;\n"
1291     << Indent1 << "}\n\n";
1292
1293   O << Indent1 << "const char* OutputLanguage() const {\n"
1294     << Indent2 << "return \"" << P.OutLanguage << "\";\n"
1295     << Indent1 << "}\n\n";
1296 }
1297
1298 /// EmitOutputSuffixMethod - Emit the OutputSuffix() method for a
1299 /// given Tool class.
1300 void EmitOutputSuffixMethod (const ToolProperties& P, std::ostream& O) {
1301   O << Indent1 << "const char* OutputSuffix() const {\n"
1302     << Indent2 << "const char* ret = \"" << P.OutputSuffix << "\";\n";
1303
1304   for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1305          E = P.OptDescs.end(); B != E; ++B) {
1306     const ToolOptionDescription& OptDesc = B->second;
1307     for (OptionPropertyList::const_iterator B = OptDesc.Props.begin(),
1308            E = OptDesc.Props.end(); B != E; ++B) {
1309       const OptionProperty& OptProp = *B;
1310       if (OptProp.first == OptionPropertyType::OutputSuffix) {
1311         O << Indent2 << "if (" << OptDesc.GenVariableName() << ")\n"
1312           << Indent3 << "ret = \"" << OptProp.second << "\";\n";
1313       }
1314     }
1315   }
1316
1317   O << Indent2 << "return ret;\n"
1318     << Indent1 << "}\n\n";
1319 }
1320
1321 /// EmitNameMethod - Emit the Name() method for a given Tool class.
1322 void EmitNameMethod (const ToolProperties& P, std::ostream& O) {
1323   O << Indent1 << "const char* Name() const {\n"
1324     << Indent2 << "return \"" << P.Name << "\";\n"
1325     << Indent1 << "}\n\n";
1326 }
1327
1328 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1329 /// class.
1330 void EmitIsJoinMethod (const ToolProperties& P, std::ostream& O) {
1331   O << Indent1 << "bool IsJoin() const {\n";
1332   if (P.isJoin())
1333     O << Indent2 << "return true;\n";
1334   else
1335     O << Indent2 << "return false;\n";
1336   O << Indent1 << "}\n\n";
1337 }
1338
1339 /// EmitStaticMemberDefinitions - Emit static member definitions for a
1340 /// given Tool class.
1341 void EmitStaticMemberDefinitions(const ToolProperties& P, std::ostream& O) {
1342   O << "const char* " << P.Name << "::InputLanguages_[] = {";
1343   for (StrVector::const_iterator B = P.InLanguage.begin(),
1344          E = P.InLanguage.end(); B != E; ++B)
1345     O << '\"' << *B << "\", ";
1346   O << "0};\n\n";
1347 }
1348
1349 /// EmitToolClassDefinition - Emit a Tool class definition.
1350 void EmitToolClassDefinition (const ToolProperties& P,
1351                               const GlobalOptionDescriptions& OptDescs,
1352                               std::ostream& O) {
1353   if (P.Name == "root")
1354     return;
1355
1356   // Header
1357   O << "class " << P.Name << " : public ";
1358   if (P.isJoin())
1359     O << "JoinTool";
1360   else
1361     O << "Tool";
1362
1363   O << "{\nprivate:\n"
1364     << Indent1 << "static const char* InputLanguages_[];\n\n";
1365
1366   O << "public:\n";
1367   EmitNameMethod(P, O);
1368   EmitInOutLanguageMethods(P, O);
1369   EmitOutputSuffixMethod(P, O);
1370   EmitIsJoinMethod(P, O);
1371   EmitGenerateActionMethods(P, OptDescs, O);
1372   EmitIsLastMethod(P, O);
1373
1374   // Close class definition
1375   O << "};\n";
1376
1377   EmitStaticMemberDefinitions(P, O);
1378
1379 }
1380
1381 /// EmitOptionDescriptions - Iterate over a list of option
1382 /// descriptions and emit registration code.
1383 void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
1384                              std::ostream& O)
1385 {
1386   std::vector<GlobalOptionDescription> Aliases;
1387
1388   // Emit static cl::Option variables.
1389   for (GlobalOptionDescriptions::const_iterator B = descs.begin(),
1390          E = descs.end(); B!=E; ++B) {
1391     const GlobalOptionDescription& val = B->second;
1392
1393     if (val.Type == OptionType::Alias) {
1394       Aliases.push_back(val);
1395       continue;
1396     }
1397
1398     O << val.GenTypeDeclaration() << ' '
1399       << val.GenVariableName()
1400       << "(\"" << val.Name << '\"';
1401
1402     if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1403       O << ", cl::Prefix";
1404
1405     if (val.isRequired()) {
1406       switch (val.Type) {
1407       case OptionType::PrefixList:
1408       case OptionType::ParameterList:
1409         O << ", cl::OneOrMore";
1410         break;
1411       default:
1412         O << ", cl::Required";
1413       }
1414     }
1415
1416     if (!val.Help.empty())
1417       O << ", cl::desc(\"" << val.Help << "\")";
1418
1419     O << ");\n";
1420   }
1421
1422   // Emit the aliases (they should go after all the 'proper' options).
1423   for (std::vector<GlobalOptionDescription>::const_iterator
1424          B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
1425     const GlobalOptionDescription& val = *B;
1426
1427     O << val.GenTypeDeclaration() << ' '
1428       << val.GenVariableName()
1429       << "(\"" << val.Name << '\"';
1430
1431     GlobalOptionDescriptions::container_type
1432       ::const_iterator F = descs.Descriptions.find(val.Help);
1433     if (F != descs.Descriptions.end())
1434       O << ", cl::aliasopt(" << F->second.GenVariableName() << ")";
1435     else
1436       throw val.Name + ": alias to an unknown option!";
1437
1438     O << ", cl::desc(\"" << "An alias for -" + val.Help  << "\"));\n";
1439   }
1440
1441   // Emit the sink option.
1442   if (descs.HasSink)
1443     O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
1444
1445   O << '\n';
1446 }
1447
1448 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
1449 void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
1450 {
1451   // Generate code
1452   O << "namespace {\n\n";
1453   O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
1454
1455   // Get the relevant field out of RecordKeeper
1456   const Record* LangMapRecord = Records.getDef("LanguageMap");
1457
1458   // It is allowed for a plugin to have no language map.
1459   if (LangMapRecord) {
1460
1461     ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
1462     if (!LangsToSuffixesList)
1463       throw std::string("Error in the language map definition!");
1464
1465     for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
1466       const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
1467
1468       const std::string& Lang = LangToSuffixes->getValueAsString("lang");
1469       const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
1470
1471       for (unsigned i = 0; i < Suffixes->size(); ++i)
1472         O << Indent1 << "langMap[\""
1473           << InitPtrToString(Suffixes->getElement(i))
1474           << "\"] = \"" << Lang << "\";\n";
1475     }
1476   }
1477
1478   O << "}\n\n}\n\n";
1479 }
1480
1481 /// FillInToolToLang - Fills in two tables that map tool names to
1482 /// (input, output) languages.  Used by the typechecker.
1483 void FillInToolToLang (const ToolPropertiesList& TPList,
1484                        StringMap<StringSet<> >& ToolToInLang,
1485                        StringMap<std::string>& ToolToOutLang) {
1486   for (ToolPropertiesList::const_iterator B = TPList.begin(), E = TPList.end();
1487        B != E; ++B) {
1488     const ToolProperties& P = *(*B);
1489     for (StrVector::const_iterator B = P.InLanguage.begin(),
1490            E = P.InLanguage.end(); B != E; ++B)
1491       ToolToInLang[P.Name].insert(*B);
1492     ToolToOutLang[P.Name] = P.OutLanguage;
1493   }
1494 }
1495
1496 /// TypecheckGraph - Check that names for output and input languages
1497 /// on all edges do match. This doesn't do much when the information
1498 /// about the whole graph is not available (i.e. when compiling most
1499 /// plugins).
1500 // TODO: add a --check-graph switch to llvmc2. It would also make it
1501 // possible to detect cycles and multiple default edges.
1502 void TypecheckGraph (const Record* CompilationGraph,
1503                      const ToolPropertiesList& TPList) {
1504   StringMap<StringSet<> > ToolToInLang;
1505   StringMap<std::string> ToolToOutLang;
1506
1507   FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
1508   ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1509   StringMap<std::string>::iterator IAE = ToolToOutLang.end();
1510   StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
1511
1512   for (unsigned i = 0; i < edges->size(); ++i) {
1513     const Record* Edge = edges->getElementAsRecord(i);
1514     const std::string& A = Edge->getValueAsString("a");
1515     const std::string& B = Edge->getValueAsString("b");
1516     StringMap<std::string>::iterator IA = ToolToOutLang.find(A);
1517     StringMap<StringSet<> >::iterator IB = ToolToInLang.find(B);
1518
1519     if (A != "root") {
1520       if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
1521         throw "Edge " + A + "->" + B
1522           + ": output->input language mismatch";
1523     }
1524
1525     if (B == "root")
1526       throw std::string("Edges back to the root are not allowed!");
1527   }
1528 }
1529
1530 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
1531 /// by EmitEdgeClass().
1532 void IncDecWeight (const Init* i, const char* IndentLevel,
1533                    std::ostream& O) {
1534   const DagInit& d = InitPtrToDag(i);
1535   const std::string& OpName = d.getOperator()->getAsString();
1536
1537   if (OpName == "inc_weight")
1538     O << IndentLevel << Indent1 << "ret += ";
1539   else if (OpName == "dec_weight")
1540     O << IndentLevel << Indent1 << "ret -= ";
1541   else
1542     throw "Unknown operator in edge properties list: " + OpName + '!';
1543
1544   if (d.getNumArgs() > 0)
1545     O << InitPtrToInt(d.getArg(0)) << ";\n";
1546   else
1547     O << "2;\n";
1548
1549 }
1550
1551 /// EmitEdgeClass - Emit a single Edge# class.
1552 void EmitEdgeClass (unsigned N, const std::string& Target,
1553                     DagInit* Case, const GlobalOptionDescriptions& OptDescs,
1554                     std::ostream& O) {
1555
1556   // Class constructor.
1557   O << "class Edge" << N << ": public Edge {\n"
1558     << "public:\n"
1559     << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1560     << "\") {}\n\n"
1561
1562   // Function Weight().
1563     << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
1564     << Indent2 << "unsigned ret = 0;\n";
1565
1566   // Handle the 'case' construct.
1567   EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
1568
1569   O << Indent2 << "return ret;\n"
1570     << Indent1 << "};\n\n};\n\n";
1571 }
1572
1573 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
1574 void EmitEdgeClasses (const Record* CompilationGraph,
1575                       const GlobalOptionDescriptions& OptDescs,
1576                       std::ostream& O) {
1577   ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1578
1579   for (unsigned i = 0; i < edges->size(); ++i) {
1580     const Record* Edge = edges->getElementAsRecord(i);
1581     const std::string& B = Edge->getValueAsString("b");
1582     DagInit* Weight = Edge->getValueAsDag("weight");
1583
1584     if (isDagEmpty(Weight))
1585       continue;
1586
1587     EmitEdgeClass(i, B, Weight, OptDescs, O);
1588   }
1589 }
1590
1591 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1592 /// function.
1593 void EmitPopulateCompilationGraph (const Record* CompilationGraph,
1594                                    const ToolPropertiesList& ToolProps,
1595                                    std::ostream& O)
1596 {
1597   ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1598
1599   O << "namespace {\n\n";
1600   O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
1601
1602   for (ToolPropertiesList::const_iterator B = ToolProps.begin(),
1603          E = ToolProps.end(); B != E; ++B)
1604     O << Indent1 << "G.insertNode(new " << (*B)->Name << "());\n";
1605
1606   O << '\n';
1607
1608   // Insert edges.
1609
1610   for (unsigned i = 0; i < edges->size(); ++i) {
1611     const Record* Edge = edges->getElementAsRecord(i);
1612     const std::string& A = Edge->getValueAsString("a");
1613     const std::string& B = Edge->getValueAsString("b");
1614     DagInit* Weight = Edge->getValueAsDag("weight");
1615
1616     O << Indent1 << "G.insertEdge(\"" << A << "\", ";
1617
1618     if (isDagEmpty(Weight))
1619       O << "new SimpleEdge(\"" << B << "\")";
1620     else
1621       O << "new Edge" << i << "()";
1622
1623     O << ");\n";
1624   }
1625
1626   O << "}\n\n}\n\n";
1627 }
1628
1629 /// ExtractHookNames - Extract the hook names from all instances of
1630 /// $CALL(HookName) in the provided command line string. Helper
1631 /// function used by FillInHookNames().
1632 void ExtractHookNames(const Init* CmdLine, StrVector& HookNames) {
1633   StrVector cmds;
1634   llvm::SplitString(InitPtrToString(CmdLine), cmds);
1635   for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
1636        B != E; ++B) {
1637     const std::string& cmd = *B;
1638     if (cmd.find("$CALL(") == 0) {
1639       if (cmd.size() == 6)
1640         throw std::string("$CALL invocation: empty argument list!");
1641       HookNames.push_back(std::string(cmd.begin() + 6,
1642                                       cmd.begin() + cmd.find(")")));
1643     }
1644   }
1645 }
1646
1647 /// ExtractHookNamesFromCaseConstruct - Extract hook names from the
1648 /// 'case' expression, handle nesting. Helper function used by
1649 /// FillInHookNames().
1650 void ExtractHookNamesFromCaseConstruct(Init* Case, StrVector& HookNames) {
1651   const DagInit& d = InitPtrToDag(Case);
1652   bool even = false;
1653   for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1654        B != E; ++B) {
1655     Init* arg = *B;
1656     if (even && dynamic_cast<DagInit*>(arg)
1657         && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
1658       ExtractHookNamesFromCaseConstruct(arg, HookNames);
1659     else if (even)
1660       ExtractHookNames(arg, HookNames);
1661     even = !even;
1662   }
1663 }
1664
1665 /// FillInHookNames - Actually extract the hook names from all command
1666 /// line strings. Helper function used by EmitHookDeclarations().
1667 void FillInHookNames(const ToolPropertiesList& TPList,
1668                      StrVector& HookNames) {
1669   // For all command lines:
1670   for (ToolPropertiesList::const_iterator B = TPList.begin(),
1671          E = TPList.end(); B != E; ++B) {
1672     const ToolProperties& P = *(*B);
1673     if (!P.CmdLine)
1674       continue;
1675     if (dynamic_cast<StringInit*>(P.CmdLine))
1676       // This is a string.
1677       ExtractHookNames(P.CmdLine, HookNames);
1678     else
1679       // This is a 'case' construct.
1680       ExtractHookNamesFromCaseConstruct(P.CmdLine, HookNames);
1681   }
1682 }
1683
1684 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
1685 /// property records and emit hook function declaration for each
1686 /// instance of $CALL(HookName).
1687 void EmitHookDeclarations(const ToolPropertiesList& ToolProps,
1688                           std::ostream& O) {
1689   StrVector HookNames;
1690   FillInHookNames(ToolProps, HookNames);
1691   if (HookNames.empty())
1692     return;
1693   std::sort(HookNames.begin(), HookNames.end());
1694   StrVector::const_iterator E = std::unique(HookNames.begin(), HookNames.end());
1695
1696   O << "namespace hooks {\n";
1697   for (StrVector::const_iterator B = HookNames.begin(); B != E; ++B)
1698     O << Indent1 << "std::string " << *B << "();\n";
1699
1700   O << "}\n\n";
1701 }
1702
1703 /// EmitRegisterPlugin - Emit code to register this plugin.
1704 void EmitRegisterPlugin(std::ostream& O) {
1705   O << "namespace {\n\n"
1706     << "struct Plugin : public llvmc::BasePlugin {\n"
1707     << Indent1 << "void PopulateLanguageMap(LanguageMap& langMap) const\n"
1708     << Indent1 << "{ PopulateLanguageMapLocal(langMap); }\n\n"
1709     << Indent1
1710     << "void PopulateCompilationGraph(CompilationGraph& graph) const\n"
1711     << Indent1 << "{ PopulateCompilationGraphLocal(graph); }\n"
1712     << "};\n\n"
1713
1714     << "static llvmc::RegisterPlugin<Plugin> RP;\n\n}\n\n";
1715 }
1716
1717 /// EmitIncludes - Emit necessary #include directives and some
1718 /// additional declarations.
1719 void EmitIncludes(std::ostream& O) {
1720   O << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
1721     << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
1722     << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
1723
1724     << "#include \"llvm/ADT/StringExtras.h\"\n"
1725     << "#include \"llvm/Support/CommandLine.h\"\n\n"
1726
1727     << "#include <cstdlib>\n"
1728     << "#include <stdexcept>\n\n"
1729
1730     << "using namespace llvm;\n"
1731     << "using namespace llvmc;\n\n"
1732
1733     << "extern cl::opt<std::string> OutputFilename;\n\n"
1734
1735     << "inline const char* checkCString(const char* s)\n"
1736     << "{ return s == NULL ? \"\" : s; }\n\n";
1737 }
1738
1739 /// NotInGraph - Helper function object for FilterNotInGraph.
1740 struct NotInGraph {
1741 private:
1742   const llvm::StringSet<>& ToolsInGraph_;
1743
1744 public:
1745   NotInGraph(const llvm::StringSet<>& ToolsInGraph)
1746   : ToolsInGraph_(ToolsInGraph)
1747   {}
1748
1749   bool operator()(const IntrusiveRefCntPtr<ToolProperties>& x) {
1750     return (ToolsInGraph_.count(x->Name) == 0);
1751   }
1752 };
1753
1754 /// FilterNotInGraph - Filter out from ToolProps all Tools not
1755 /// mentioned in the compilation graph definition.
1756 void FilterNotInGraph (const Record* CompilationGraph,
1757                        ToolPropertiesList& ToolProps) {
1758
1759   // List all tools mentioned in the graph.
1760   llvm::StringSet<> ToolsInGraph;
1761   ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1762
1763   for (unsigned i = 0; i < edges->size(); ++i) {
1764     const Record* Edge = edges->getElementAsRecord(i);
1765     const std::string& A = Edge->getValueAsString("a");
1766     const std::string& B = Edge->getValueAsString("b");
1767
1768     if (A != "root")
1769       ToolsInGraph.insert(A);
1770     ToolsInGraph.insert(B);
1771   }
1772
1773   // Filter ToolPropertiesList.
1774   ToolPropertiesList::iterator new_end =
1775     std::remove_if(ToolProps.begin(), ToolProps.end(),
1776                    NotInGraph(ToolsInGraph));
1777   ToolProps.erase(new_end, ToolProps.end());
1778 }
1779
1780 // End of anonymous namespace
1781 }
1782
1783 /// run - The back-end entry point.
1784 void LLVMCConfigurationEmitter::run (std::ostream &O) {
1785   try {
1786
1787   // Emit file header.
1788   EmitSourceFileHeader("LLVMC Configuration Library", O);
1789   EmitIncludes(O);
1790
1791   // Get a list of all defined Tools.
1792
1793   RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1794   if (Tools.empty())
1795     throw std::string("No tool definitions found!");
1796
1797   // Gather information from the Tool description dags.
1798   ToolPropertiesList ToolProps;
1799   GlobalOptionDescriptions OptDescs;
1800   CollectToolProperties(Tools.begin(), Tools.end(), ToolProps, OptDescs);
1801
1802   RecordVector OptionLists = Records.getAllDerivedDefinitions("OptionList");
1803   CollectPropertiesFromOptionLists(OptionLists.begin(), OptionLists.end(),
1804                                    OptDescs);
1805
1806   // TOTHINK: Nothing actually prevents us from having multiple
1807   // compilation graphs in a single plugin; OTOH, I do not see how
1808   // that could be useful.
1809   const Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
1810   if (!CompilationGraphRecord)
1811     throw std::string("Compilation graph description not found!");
1812
1813   FilterNotInGraph(CompilationGraphRecord, ToolProps);
1814
1815   // Typecheck the compilation graph.
1816   TypecheckGraph(CompilationGraphRecord, ToolProps);
1817
1818   // Check that there are no options without side effects (specified
1819   // only in the OptionList).
1820   CheckForSuperfluousOptions(ToolProps, OptDescs);
1821
1822   // Emit global option registration code.
1823   EmitOptionDescriptions(OptDescs, O);
1824
1825   // Emit hook declarations.
1826   EmitHookDeclarations(ToolProps, O);
1827
1828   // Emit PopulateLanguageMap() function
1829   // (a language map maps from file extensions to language names).
1830   EmitPopulateLanguageMap(Records, O);
1831
1832   // Emit Tool classes.
1833   for (ToolPropertiesList::const_iterator B = ToolProps.begin(),
1834          E = ToolProps.end(); B!=E; ++B)
1835     EmitToolClassDefinition(*(*B), OptDescs, O);
1836
1837   // Emit Edge# classes.
1838   EmitEdgeClasses(CompilationGraphRecord, OptDescs, O);
1839
1840   // Emit PopulateCompilationGraph() function.
1841   EmitPopulateCompilationGraph(CompilationGraphRecord, ToolProps, O);
1842
1843   // Emit code for plugin registration.
1844   EmitRegisterPlugin(O);
1845
1846   // EOF
1847   } catch (std::exception& Error) {
1848     throw Error.what() + std::string(" - usually this means a syntax error.");
1849   }
1850 }