blob: 3de4d37f25e8c9d3733c5fdad4ee4e109c006905 [file] [log] [blame]
Mikhail Glushenkovfb37f392008-05-30 06:20:54 +00001//===- LLVMCConfigurationEmitter.cpp - Generate LLVMC config ----*- C++ -*-===//
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00002//
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//
Mikhail Glushenkovbe9d9a12008-05-06 18:08:59 +000010// This tablegen backend is responsible for emitting LLVMC configuration code.
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +000011//
12//===----------------------------------------------------------------------===//
13
Mikhail Glushenkovecbdcf22008-05-06 18:09:29 +000014#include "LLVMCConfigurationEmitter.h"
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +000015#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"
Mikhail Glushenkovffcf3a12008-05-30 06:18:16 +000021#include "llvm/ADT/StringSet.h"
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +000022#include "llvm/Support/Streams.h"
Mikhail Glushenkovaa4774c2008-11-12 00:04:46 +000023
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +000024#include <algorithm>
25#include <cassert>
26#include <functional>
Mikhail Glushenkov4fb71ea2008-05-30 06:21:48 +000027#include <stdexcept>
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +000028#include <string>
Chris Lattner32a9e7a2008-06-04 04:46:14 +000029#include <typeinfo>
Mikhail Glushenkovaa4774c2008-11-12 00:04:46 +000030
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +000031using namespace llvm;
32
Mikhail Glushenkov895820d2008-05-06 18:12:03 +000033namespace {
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +000034
35//===----------------------------------------------------------------------===//
36/// Typedefs
37
38typedef std::vector<Record*> RecordVector;
39typedef std::vector<std::string> StrVector;
40
41//===----------------------------------------------------------------------===//
42/// Constants
43
Mikhail Glushenkov4561ab52008-05-07 21:50:19 +000044// Indentation strings.
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +000045const char * Indent1 = " ";
46const char * Indent2 = " ";
47const char * Indent3 = " ";
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +000048
Mikhail Glushenkov4561ab52008-05-07 21:50:19 +000049// Default help string.
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +000050const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
51
Mikhail Glushenkov4561ab52008-05-07 21:50:19 +000052// Name for the "sink" option.
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +000053const char * SinkOptionName = "AutoGeneratedSinkOption";
54
55//===----------------------------------------------------------------------===//
56/// Helper functions
57
Mikhail Glushenkovf9152532008-12-07 16:41:11 +000058/// Id - An 'identity' function object.
59struct Id {
60 template<typename T>
61 void operator()(const T&) const {
62 }
63};
64
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +000065int InitPtrToInt(const Init* ptr) {
66 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
Mikhail Glushenkov29063552008-05-06 18:18:20 +000067 return val.getValue();
68}
69
Mikhail Glushenkovffcf3a12008-05-30 06:18:16 +000070const std::string& InitPtrToString(const Init* ptr) {
71 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
72 return val.getValue();
73}
74
75const ListInit& InitPtrToList(const Init* ptr) {
76 const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
77 return val;
78}
79
80const DagInit& InitPtrToDag(const Init* ptr) {
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +000081 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
Mikhail Glushenkov29063552008-05-06 18:18:20 +000082 return val;
83}
84
Mikhail Glushenkov4561ab52008-05-07 21:50:19 +000085// checkNumberOfArguments - Ensure that the number of args in d is
Mikhail Glushenkove5557f42008-05-30 06:08:50 +000086// less than or equal to min_arguments, otherwise throw an exception.
Mikhail Glushenkov581936a2008-05-06 17:22:03 +000087void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
Mikhail Glushenkovb4ced5a2008-12-07 16:47:12 +000088 if (!d || d->getNumArgs() < min_arguments)
Mikhail Glushenkov581936a2008-05-06 17:22:03 +000089 throw "Property " + d->getOperator()->getAsString()
90 + " has too few arguments!";
91}
92
Mikhail Glushenkove5557f42008-05-30 06:08:50 +000093// isDagEmpty - is this DAG marked with an empty marker?
94bool isDagEmpty (const DagInit* d) {
95 return d->getOperator()->getAsString() == "empty";
96}
Mikhail Glushenkov581936a2008-05-06 17:22:03 +000097
Mikhail Glushenkovf9152532008-12-07 16:41:11 +000098// EscapeVariableName - Escape commas and other symbols not allowed
99// in the C++ variable names. Makes it possible to use options named
100// like "Wa," (useful for prefix options).
101std::string EscapeVariableName(const std::string& Var) {
102 std::string ret;
103 for (unsigned i = 0; i != Var.size(); ++i) {
104 char cur_char = Var[i];
105 if (cur_char == ',') {
106 ret += "_comma_";
107 }
108 else if (cur_char == '+') {
109 ret += "_plus_";
110 }
111 else if (cur_char == '-') {
112 ret += "_dash_";
113 }
114 else {
115 ret.push_back(cur_char);
116 }
117 }
118 return ret;
119}
120
Mikhail Glushenkova298bb72009-01-21 13:04:00 +0000121/// oneOf - Does the input string contain this character?
122bool oneOf(const char* lst, char c) {
123 while (*lst) {
124 if (*lst++ == c)
125 return true;
126 }
127 return false;
128}
129
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000130//===----------------------------------------------------------------------===//
131/// Back-end specific code
132
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000133
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000134/// OptionType - One of six different option types. See the
135/// documentation for detailed description of differences.
136/// Extern* options are those that are defined in some other plugin.
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000137namespace OptionType {
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000138 enum OptionType { Alias, Switch, Parameter, ParameterList,
Mikhail Glushenkovb4ced5a2008-12-07 16:47:12 +0000139 Prefix, PrefixList};
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000140
141bool IsList (OptionType t) {
Mikhail Glushenkovb4ced5a2008-12-07 16:47:12 +0000142 return (t == ParameterList || t == PrefixList);
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000143}
144
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000145bool IsSwitch (OptionType t) {
Mikhail Glushenkovb4ced5a2008-12-07 16:47:12 +0000146 return (t == Switch);
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000147}
148
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000149bool IsParameter (OptionType t) {
Mikhail Glushenkovb4ced5a2008-12-07 16:47:12 +0000150 return (t == Parameter || t == Prefix);
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000151}
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000152
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000153}
154
155OptionType::OptionType stringToOptionType(const std::string& T) {
156 if (T == "alias_option")
157 return OptionType::Alias;
158 else if (T == "switch_option")
159 return OptionType::Switch;
160 else if (T == "parameter_option")
161 return OptionType::Parameter;
162 else if (T == "parameter_list_option")
163 return OptionType::ParameterList;
164 else if (T == "prefix_option")
165 return OptionType::Prefix;
166 else if (T == "prefix_list_option")
167 return OptionType::PrefixList;
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000168 else
169 throw "Unknown option type: " + T + '!';
170}
171
172namespace OptionDescriptionFlags {
173 enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
Mikhail Glushenkovb4ced5a2008-12-07 16:47:12 +0000174 ReallyHidden = 0x4, Extern = 0x8 };
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000175}
176
177/// OptionDescription - Represents data contained in a single
178/// OptionList entry.
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000179struct OptionDescription {
180 OptionType::OptionType Type;
181 std::string Name;
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000182 unsigned Flags;
183 std::string Help;
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000184
185 OptionDescription(OptionType::OptionType t = OptionType::Switch,
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000186 const std::string& n = "",
187 const std::string& h = DefaultHelpString)
188 : Type(t), Name(n), Flags(0x0), Help(h)
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000189 {}
190
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000191 /// GenTypeDeclaration - Returns the C++ variable type of this
192 /// option.
193 const char* GenTypeDeclaration() const;
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000194
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000195 /// GenVariableName - Returns the variable name used in the
196 /// generated C++ code.
197 std::string GenVariableName() const;
Mikhail Glushenkov739c7202008-11-28 00:13:25 +0000198
Mikhail Glushenkov4561ab52008-05-07 21:50:19 +0000199 /// Merge - Merge two option descriptions.
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000200 void Merge (const OptionDescription& other);
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000201
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000202 // Misc convenient getters/setters.
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000203
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000204 bool isAlias() const;
Mikhail Glushenkovb4ced5a2008-12-07 16:47:12 +0000205
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000206 bool isExtern() const;
Mikhail Glushenkovb4ced5a2008-12-07 16:47:12 +0000207 void setExtern();
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000208
209 bool isRequired() const;
210 void setRequired();
211
212 bool isHidden() const;
213 void setHidden();
214
215 bool isReallyHidden() const;
216 void setReallyHidden();
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000217};
218
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000219void OptionDescription::Merge (const OptionDescription& other)
220{
221 if (other.Type != Type)
222 throw "Conflicting definitions for the option " + Name + "!";
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000223
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000224 if (Help == other.Help || Help == DefaultHelpString)
225 Help = other.Help;
226 else if (other.Help != DefaultHelpString) {
227 llvm::cerr << "Warning: several different help strings"
228 " defined for option " + Name + "\n";
229 }
230
231 Flags |= other.Flags;
232}
233
234bool OptionDescription::isAlias() const {
235 return Type == OptionType::Alias;
236}
237
238bool OptionDescription::isExtern() const {
Mikhail Glushenkovb4ced5a2008-12-07 16:47:12 +0000239 return Flags & OptionDescriptionFlags::Extern;
240}
241void OptionDescription::setExtern() {
242 Flags |= OptionDescriptionFlags::Extern;
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000243}
244
245bool OptionDescription::isRequired() const {
246 return Flags & OptionDescriptionFlags::Required;
247}
248void OptionDescription::setRequired() {
249 Flags |= OptionDescriptionFlags::Required;
250}
251
252bool OptionDescription::isHidden() const {
253 return Flags & OptionDescriptionFlags::Hidden;
254}
255void OptionDescription::setHidden() {
256 Flags |= OptionDescriptionFlags::Hidden;
257}
258
259bool OptionDescription::isReallyHidden() const {
260 return Flags & OptionDescriptionFlags::ReallyHidden;
261}
262void OptionDescription::setReallyHidden() {
263 Flags |= OptionDescriptionFlags::ReallyHidden;
264}
265
266const char* OptionDescription::GenTypeDeclaration() const {
267 switch (Type) {
268 case OptionType::Alias:
269 return "cl::alias";
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000270 case OptionType::PrefixList:
271 case OptionType::ParameterList:
272 return "cl::list<std::string>";
273 case OptionType::Switch:
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000274 return "cl::opt<bool>";
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000275 case OptionType::Parameter:
276 case OptionType::Prefix:
277 default:
278 return "cl::opt<std::string>";
279 }
280}
281
282std::string OptionDescription::GenVariableName() const {
283 const std::string& EscapedName = EscapeVariableName(Name);
284 switch (Type) {
285 case OptionType::Alias:
286 return "AutoGeneratedAlias_" + EscapedName;
287 case OptionType::PrefixList:
288 case OptionType::ParameterList:
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000289 return "AutoGeneratedList_" + EscapedName;
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000290 case OptionType::Switch:
291 return "AutoGeneratedSwitch_" + EscapedName;
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000292 case OptionType::Prefix:
293 case OptionType::Parameter:
294 default:
295 return "AutoGeneratedParameter_" + EscapedName;
296 }
297}
298
299/// OptionDescriptions - An OptionDescription array plus some helper
300/// functions.
301class OptionDescriptions {
302 typedef StringMap<OptionDescription> container_type;
303
304 /// Descriptions - A list of OptionDescriptions.
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000305 container_type Descriptions;
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000306
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000307public:
Mikhail Glushenkova7d0ae32008-05-30 06:28:37 +0000308 /// FindOption - exception-throwing wrapper for find().
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000309 const OptionDescription& FindOption(const std::string& OptName) const;
Mikhail Glushenkov581936a2008-05-06 17:22:03 +0000310
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000311 /// insertDescription - Insert new OptionDescription into
312 /// OptionDescriptions list
313 void InsertDescription (const OptionDescription& o);
Mikhail Glushenkov09b51c32008-05-30 06:27:02 +0000314
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000315 // Support for STL-style iteration
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000316 typedef container_type::const_iterator const_iterator;
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000317 const_iterator begin() const { return Descriptions.begin(); }
318 const_iterator end() const { return Descriptions.end(); }
319};
320
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000321const OptionDescription&
322OptionDescriptions::FindOption(const std::string& OptName) const
323{
324 const_iterator I = Descriptions.find(OptName);
325 if (I != Descriptions.end())
326 return I->second;
327 else
328 throw OptName + ": no such option!";
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000329}
330
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000331void OptionDescriptions::InsertDescription (const OptionDescription& o)
332{
333 container_type::iterator I = Descriptions.find(o.Name);
334 if (I != Descriptions.end()) {
335 OptionDescription& D = I->second;
336 D.Merge(o);
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000337 }
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000338 else {
339 Descriptions[o.Name] = o;
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000340 }
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000341}
342
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000343/// HandlerTable - A base class for function objects implemented as
344/// 'tables of handlers'.
345template <class T>
346class HandlerTable {
347protected:
Mikhail Glushenkov09b51c32008-05-30 06:27:02 +0000348 // Implementation details.
349
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000350 /// Handler -
351 typedef void (T::* Handler) (const DagInit*);
352 /// HandlerMap - A map from property names to property handlers
353 typedef StringMap<Handler> HandlerMap;
Mikhail Glushenkov09b51c32008-05-30 06:27:02 +0000354
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000355 static HandlerMap Handlers_;
Mikhail Glushenkov09b51c32008-05-30 06:27:02 +0000356 static bool staticMembersInitialized_;
357
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000358 T* childPtr;
359public:
Mikhail Glushenkov09b51c32008-05-30 06:27:02 +0000360
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000361 HandlerTable(T* cp) : childPtr(cp)
362 {}
363
364 /// operator() - Just forwards to the corresponding property
365 /// handler.
366 void operator() (Init* i) {
367 const DagInit& property = InitPtrToDag(i);
368 const std::string& property_name = property.getOperator()->getAsString();
369 typename HandlerMap::iterator method = Handlers_.find(property_name);
370
371 if (method != Handlers_.end()) {
372 Handler h = method->second;
373 (childPtr->*h)(&property);
374 }
375 else {
376 throw "No handler found for property " + property_name + "!";
377 }
378 }
379
380 void AddHandler(const char* Property, Handler Handl) {
381 Handlers_[Property] = Handl;
382 }
383};
384
385template <class T> typename HandlerTable<T>::HandlerMap
386HandlerTable<T>::Handlers_;
387template <class T> bool HandlerTable<T>::staticMembersInitialized_ = false;
388
389
390/// CollectOptionProperties - Function object for iterating over an
391/// option property list.
392class CollectOptionProperties : public HandlerTable<CollectOptionProperties> {
393private:
394
395 /// optDescs_ - OptionDescriptions table. This is where the
396 /// information is stored.
397 OptionDescription& optDesc_;
Mikhail Glushenkov09b51c32008-05-30 06:27:02 +0000398
399public:
400
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000401 explicit CollectOptionProperties(OptionDescription& OD)
402 : HandlerTable<CollectOptionProperties>(this), optDesc_(OD)
Mikhail Glushenkov09b51c32008-05-30 06:27:02 +0000403 {
404 if (!staticMembersInitialized_) {
Mikhail Glushenkovb4ced5a2008-12-07 16:47:12 +0000405 AddHandler("extern", &CollectOptionProperties::onExtern);
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000406 AddHandler("help", &CollectOptionProperties::onHelp);
407 AddHandler("hidden", &CollectOptionProperties::onHidden);
408 AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
409 AddHandler("required", &CollectOptionProperties::onRequired);
Mikhail Glushenkov09b51c32008-05-30 06:27:02 +0000410
411 staticMembersInitialized_ = true;
412 }
413 }
414
Mikhail Glushenkov09b51c32008-05-30 06:27:02 +0000415private:
416
417 /// Option property handlers --
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000418 /// Methods that handle option properties such as (help) or (hidden).
Mikhail Glushenkovfdee9542008-09-22 20:46:19 +0000419
Mikhail Glushenkovb4ced5a2008-12-07 16:47:12 +0000420 void onExtern (const DagInit* d) {
421 checkNumberOfArguments(d, 0);
422 optDesc_.setExtern();
423 }
424
Mikhail Glushenkov09b51c32008-05-30 06:27:02 +0000425 void onHelp (const DagInit* d) {
426 checkNumberOfArguments(d, 1);
Mikhail Glushenkovb4ced5a2008-12-07 16:47:12 +0000427 optDesc_.Help = InitPtrToString(d->getArg(0));
Mikhail Glushenkov09b51c32008-05-30 06:27:02 +0000428 }
429
Mikhail Glushenkov739c7202008-11-28 00:13:25 +0000430 void onHidden (const DagInit* d) {
431 checkNumberOfArguments(d, 0);
Mikhail Glushenkov739c7202008-11-28 00:13:25 +0000432 optDesc_.setHidden();
433 }
434
435 void onReallyHidden (const DagInit* d) {
436 checkNumberOfArguments(d, 0);
Mikhail Glushenkov739c7202008-11-28 00:13:25 +0000437 optDesc_.setReallyHidden();
438 }
439
Mikhail Glushenkov09b51c32008-05-30 06:27:02 +0000440 void onRequired (const DagInit* d) {
441 checkNumberOfArguments(d, 0);
Mikhail Glushenkov09b51c32008-05-30 06:27:02 +0000442 optDesc_.setRequired();
443 }
444
Mikhail Glushenkov09b51c32008-05-30 06:27:02 +0000445};
446
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000447/// AddOption - A function object that is applied to every option
448/// description. Used by CollectOptionDescriptions.
Mikhail Glushenkov2b7bcb42008-05-30 06:27:29 +0000449class AddOption {
450private:
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000451 OptionDescriptions& OptDescs_;
Mikhail Glushenkov2b7bcb42008-05-30 06:27:29 +0000452
453public:
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000454 explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
Mikhail Glushenkov2b7bcb42008-05-30 06:27:29 +0000455 {}
456
457 void operator()(const Init* i) {
458 const DagInit& d = InitPtrToDag(i);
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000459 checkNumberOfArguments(&d, 1);
Mikhail Glushenkov2b7bcb42008-05-30 06:27:29 +0000460
461 const OptionType::OptionType Type =
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000462 stringToOptionType(d.getOperator()->getAsString());
Mikhail Glushenkov2b7bcb42008-05-30 06:27:29 +0000463 const std::string& Name = InitPtrToString(d.getArg(0));
464
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000465 OptionDescription OD(Type, Name);
466
467 if (!OD.isExtern())
468 checkNumberOfArguments(&d, 2);
469
470 if (OD.isAlias()) {
471 // Aliases store the aliased option name in the 'Help' field.
Mikhail Glushenkov2b7bcb42008-05-30 06:27:29 +0000472 OD.Help = InitPtrToString(d.getArg(1));
473 }
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000474 else if (!OD.isExtern()) {
475 processOptionProperties(&d, OD);
476 }
477 OptDescs_.InsertDescription(OD);
Mikhail Glushenkov2b7bcb42008-05-30 06:27:29 +0000478 }
479
480private:
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000481 /// processOptionProperties - Go through the list of option
482 /// properties and call a corresponding handler for each.
483 static void processOptionProperties (const DagInit* d, OptionDescription& o) {
484 checkNumberOfArguments(d, 2);
485 DagInit::const_arg_iterator B = d->arg_begin();
486 // Skip the first argument: it's always the option name.
487 ++B;
488 std::for_each(B, d->arg_end(), CollectOptionProperties(o));
Mikhail Glushenkov2b7bcb42008-05-30 06:27:29 +0000489 }
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000490
Mikhail Glushenkov2b7bcb42008-05-30 06:27:29 +0000491};
492
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000493/// CollectOptionDescriptions - Collects option properties from all
494/// OptionLists.
495void CollectOptionDescriptions (RecordVector::const_iterator B,
496 RecordVector::const_iterator E,
497 OptionDescriptions& OptDescs)
498{
499 // For every OptionList:
500 for (; B!=E; ++B) {
501 RecordVector::value_type T = *B;
502 // Throws an exception if the value does not exist.
503 ListInit* PropList = T->getValueAsListInit("options");
Mikhail Glushenkov2b7bcb42008-05-30 06:27:29 +0000504
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000505 // For every option description in this list:
506 // collect the information and
507 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
508 }
509}
510
511// Tool information record
512
513namespace ToolFlags {
514 enum ToolFlags { Join = 0x1, Sink = 0x2 };
515}
516
517struct ToolDescription : public RefCountedBase<ToolDescription> {
518 std::string Name;
519 Init* CmdLine;
520 Init* Actions;
521 StrVector InLanguage;
522 std::string OutLanguage;
523 std::string OutputSuffix;
524 unsigned Flags;
525
526 // Various boolean properties
527 void setSink() { Flags |= ToolFlags::Sink; }
528 bool isSink() const { return Flags & ToolFlags::Sink; }
529 void setJoin() { Flags |= ToolFlags::Join; }
530 bool isJoin() const { return Flags & ToolFlags::Join; }
531
532 // Default ctor here is needed because StringMap can only store
533 // DefaultConstructible objects
534 ToolDescription() : CmdLine(0), Actions(0), Flags(0) {}
535 ToolDescription (const std::string& n)
536 : Name(n), CmdLine(0), Actions(0), Flags(0)
537 {}
538};
539
540/// ToolDescriptions - A list of Tool information records.
541typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
542
543
544/// CollectToolProperties - Function object for iterating over a list of
Mikhail Glushenkov8e7254c2008-05-09 08:27:26 +0000545/// tool property records.
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000546class CollectToolProperties : public HandlerTable<CollectToolProperties> {
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000547private:
548
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000549 /// toolDesc_ - Properties of the current Tool. This is where the
550 /// information is stored.
551 ToolDescription& toolDesc_;
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000552
553public:
554
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000555 explicit CollectToolProperties (ToolDescription& d)
556 : HandlerTable<CollectToolProperties>(this) , toolDesc_(d)
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000557 {
558 if (!staticMembersInitialized_) {
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000559
560 AddHandler("actions", &CollectToolProperties::onActions);
561 AddHandler("cmd_line", &CollectToolProperties::onCmdLine);
562 AddHandler("in_language", &CollectToolProperties::onInLanguage);
563 AddHandler("join", &CollectToolProperties::onJoin);
564 AddHandler("out_language", &CollectToolProperties::onOutLanguage);
565 AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
566 AddHandler("sink", &CollectToolProperties::onSink);
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000567
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000568 staticMembersInitialized_ = true;
569 }
570 }
571
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000572private:
573
574 /// Property handlers --
575 /// Functions that extract information about tool properties from
576 /// DAG representation.
577
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000578 void onActions (const DagInit* d) {
579 checkNumberOfArguments(d, 1);
Mikhail Glushenkovad889a72008-12-07 16:45:12 +0000580 Init* Case = d->getArg(0);
581 if (typeid(*Case) != typeid(DagInit) ||
582 static_cast<DagInit*>(Case)->getOperator()->getAsString() != "case")
583 throw
584 std::string("The argument to (actions) should be a 'case' construct!");
585 toolDesc_.Actions = Case;
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000586 }
587
Mikhail Glushenkov29063552008-05-06 18:18:20 +0000588 void onCmdLine (const DagInit* d) {
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000589 checkNumberOfArguments(d, 1);
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000590 toolDesc_.CmdLine = d->getArg(0);
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000591 }
592
Mikhail Glushenkov29063552008-05-06 18:18:20 +0000593 void onInLanguage (const DagInit* d) {
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000594 checkNumberOfArguments(d, 1);
Mikhail Glushenkovffcf3a12008-05-30 06:18:16 +0000595 Init* arg = d->getArg(0);
596
597 // Find out the argument's type.
598 if (typeid(*arg) == typeid(StringInit)) {
599 // It's a string.
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000600 toolDesc_.InLanguage.push_back(InitPtrToString(arg));
Mikhail Glushenkovffcf3a12008-05-30 06:18:16 +0000601 }
602 else {
603 // It's a list.
604 const ListInit& lst = InitPtrToList(arg);
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000605 StrVector& out = toolDesc_.InLanguage;
Mikhail Glushenkovffcf3a12008-05-30 06:18:16 +0000606
607 // Copy strings to the output vector.
608 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
609 B != E; ++B) {
610 out.push_back(InitPtrToString(*B));
611 }
612
613 // Remove duplicates.
614 std::sort(out.begin(), out.end());
615 StrVector::iterator newE = std::unique(out.begin(), out.end());
616 out.erase(newE, out.end());
617 }
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000618 }
619
Mikhail Glushenkov29063552008-05-06 18:18:20 +0000620 void onJoin (const DagInit* d) {
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000621 checkNumberOfArguments(d, 0);
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000622 toolDesc_.setJoin();
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000623 }
624
Mikhail Glushenkov29063552008-05-06 18:18:20 +0000625 void onOutLanguage (const DagInit* d) {
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000626 checkNumberOfArguments(d, 1);
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000627 toolDesc_.OutLanguage = InitPtrToString(d->getArg(0));
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000628 }
629
Mikhail Glushenkov29063552008-05-06 18:18:20 +0000630 void onOutputSuffix (const DagInit* d) {
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000631 checkNumberOfArguments(d, 1);
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000632 toolDesc_.OutputSuffix = InitPtrToString(d->getArg(0));
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000633 }
634
Mikhail Glushenkov29063552008-05-06 18:18:20 +0000635 void onSink (const DagInit* d) {
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000636 checkNumberOfArguments(d, 0);
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000637 toolDesc_.setSink();
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000638 }
639
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000640};
641
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000642
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000643/// CollectToolDescriptions - Gather information about tool properties
Mikhail Glushenkove43228952008-05-30 06:26:08 +0000644/// from the parsed TableGen data (basically a wrapper for the
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000645/// CollectToolProperties function object).
646void CollectToolDescriptions (RecordVector::const_iterator B,
647 RecordVector::const_iterator E,
648 ToolDescriptions& ToolDescs)
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000649{
650 // Iterate over a properties list of every Tool definition
651 for (;B!=E;++B) {
Mikhail Glushenkovfa270772008-11-17 17:29:42 +0000652 const Record* T = *B;
Mikhail Glushenkove43228952008-05-30 06:26:08 +0000653 // Throws an exception if the value does not exist.
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000654 ListInit* PropList = T->getValueAsListInit("properties");
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000655
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000656 IntrusiveRefCntPtr<ToolDescription>
657 ToolDesc(new ToolDescription(T->getName()));
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000658
659 std::for_each(PropList->begin(), PropList->end(),
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000660 CollectToolProperties(*ToolDesc));
661 ToolDescs.push_back(ToolDesc);
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +0000662 }
663}
664
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000665/// FillInEdgeVector - Merge all compilation graph definitions into
666/// one single edge list.
667void FillInEdgeVector(RecordVector::const_iterator B,
668 RecordVector::const_iterator E, RecordVector& Out) {
669 for (; B != E; ++B) {
670 const ListInit* edges = (*B)->getValueAsListInit("edges");
Mikhail Glushenkov09b51c32008-05-30 06:27:02 +0000671
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000672 for (unsigned i = 0; i < edges->size(); ++i)
673 Out.push_back(edges->getElementAsRecord(i));
674 }
675}
676
677/// CalculatePriority - Calculate the priority of this plugin.
678int CalculatePriority(RecordVector::const_iterator B,
679 RecordVector::const_iterator E) {
680 int total = 0;
Mikhail Glushenkov35fde152008-11-17 17:30:25 +0000681 for (; B!=E; ++B) {
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000682 total += static_cast<int>((*B)->getValueAsInt("priority"));
683 }
684 return total;
685}
Mikhail Glushenkove43228952008-05-30 06:26:08 +0000686
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000687/// NotInGraph - Helper function object for FilterNotInGraph.
688struct NotInGraph {
689private:
690 const llvm::StringSet<>& ToolsInGraph_;
691
692public:
693 NotInGraph(const llvm::StringSet<>& ToolsInGraph)
694 : ToolsInGraph_(ToolsInGraph)
695 {}
696
697 bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
698 return (ToolsInGraph_.count(x->Name) == 0);
699 }
700};
701
702/// FilterNotInGraph - Filter out from ToolDescs all Tools not
703/// mentioned in the compilation graph definition.
704void FilterNotInGraph (const RecordVector& EdgeVector,
705 ToolDescriptions& ToolDescs) {
706
707 // List all tools mentioned in the graph.
708 llvm::StringSet<> ToolsInGraph;
709
710 for (RecordVector::const_iterator B = EdgeVector.begin(),
711 E = EdgeVector.end(); B != E; ++B) {
712
713 const Record* Edge = *B;
Mikhail Glushenkov15b71ba2008-12-07 16:44:47 +0000714 const std::string& NodeA = Edge->getValueAsString("a");
715 const std::string& NodeB = Edge->getValueAsString("b");
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000716
Mikhail Glushenkov15b71ba2008-12-07 16:44:47 +0000717 if (NodeA != "root")
718 ToolsInGraph.insert(NodeA);
719 ToolsInGraph.insert(NodeB);
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000720 }
721
722 // Filter ToolPropertiesList.
723 ToolDescriptions::iterator new_end =
724 std::remove_if(ToolDescs.begin(), ToolDescs.end(),
725 NotInGraph(ToolsInGraph));
726 ToolDescs.erase(new_end, ToolDescs.end());
727}
728
729/// FillInToolToLang - Fills in two tables that map tool names to
730/// (input, output) languages. Helper function used by TypecheckGraph().
731void FillInToolToLang (const ToolDescriptions& ToolDescs,
732 StringMap<StringSet<> >& ToolToInLang,
733 StringMap<std::string>& ToolToOutLang) {
734 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
735 E = ToolDescs.end(); B != E; ++B) {
736 const ToolDescription& D = *(*B);
737 for (StrVector::const_iterator B = D.InLanguage.begin(),
738 E = D.InLanguage.end(); B != E; ++B)
739 ToolToInLang[D.Name].insert(*B);
740 ToolToOutLang[D.Name] = D.OutLanguage;
Mikhail Glushenkove43228952008-05-30 06:26:08 +0000741 }
742}
743
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000744/// TypecheckGraph - Check that names for output and input languages
745/// on all edges do match. This doesn't do much when the information
746/// about the whole graph is not available (i.e. when compiling most
747/// plugins).
748void TypecheckGraph (const RecordVector& EdgeVector,
749 const ToolDescriptions& ToolDescs) {
750 StringMap<StringSet<> > ToolToInLang;
751 StringMap<std::string> ToolToOutLang;
752
753 FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
754 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
755 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
756
757 for (RecordVector::const_iterator B = EdgeVector.begin(),
758 E = EdgeVector.end(); B != E; ++B) {
759 const Record* Edge = *B;
Mikhail Glushenkov15b71ba2008-12-07 16:44:47 +0000760 const std::string& NodeA = Edge->getValueAsString("a");
761 const std::string& NodeB = Edge->getValueAsString("b");
762 StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
763 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000764
Mikhail Glushenkov15b71ba2008-12-07 16:44:47 +0000765 if (NodeA != "root") {
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000766 if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
Mikhail Glushenkov15b71ba2008-12-07 16:44:47 +0000767 throw "Edge " + NodeA + "->" + NodeB
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000768 + ": output->input language mismatch";
769 }
770
Mikhail Glushenkov15b71ba2008-12-07 16:44:47 +0000771 if (NodeB == "root")
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000772 throw std::string("Edges back to the root are not allowed!");
773 }
774}
775
776/// WalkCase - Walks the 'case' expression DAG and invokes
777/// TestCallback on every test, and StatementCallback on every
778/// statement. Handles 'case' nesting, but not the 'and' and 'or'
779/// combinators.
780// TODO: Re-implement EmitCaseConstructHandler on top of this function?
781template <typename F1, typename F2>
782void WalkCase(Init* Case, F1 TestCallback, F2 StatementCallback) {
783 const DagInit& d = InitPtrToDag(Case);
784 bool even = false;
785 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
786 B != E; ++B) {
787 Init* arg = *B;
788 if (even && dynamic_cast<DagInit*>(arg)
789 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
790 WalkCase(arg, TestCallback, StatementCallback);
791 else if (!even)
792 TestCallback(arg);
793 else
794 StatementCallback(arg);
795 even = !even;
796 }
797}
798
799/// ExtractOptionNames - A helper function object used by
800/// CheckForSuperfluousOptions() to walk the 'case' DAG.
801class ExtractOptionNames {
802 llvm::StringSet<>& OptionNames_;
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000803
Mikhail Glushenkov08509492008-12-07 16:42:22 +0000804 void processDag(const Init* Statement) {
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000805 const DagInit& Stmt = InitPtrToDag(Statement);
806 const std::string& ActionName = Stmt.getOperator()->getAsString();
807 if (ActionName == "forward" || ActionName == "forward_as" ||
808 ActionName == "unpack_values" || ActionName == "switch_on" ||
809 ActionName == "parameter_equals" || ActionName == "element_in_list" ||
Mikhail Glushenkov5c2b6b22008-12-17 02:47:01 +0000810 ActionName == "not_empty" || ActionName == "empty") {
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000811 checkNumberOfArguments(&Stmt, 1);
812 const std::string& Name = InitPtrToString(Stmt.getArg(0));
813 OptionNames_.insert(Name);
814 }
815 else if (ActionName == "and" || ActionName == "or") {
816 for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
Mikhail Glushenkov08509492008-12-07 16:42:22 +0000817 this->processDag(Stmt.getArg(i));
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000818 }
819 }
820 }
Mikhail Glushenkov08509492008-12-07 16:42:22 +0000821
822public:
823 ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
824 {}
825
826 void operator()(const Init* Statement) {
827 if (typeid(*Statement) == typeid(ListInit)) {
828 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
829 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
830 B != E; ++B)
831 this->processDag(*B);
832 }
833 else {
834 this->processDag(Statement);
835 }
836 }
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000837};
838
Mikhail Glushenkova7d0ae32008-05-30 06:28:37 +0000839/// CheckForSuperfluousOptions - Check that there are no side
840/// effect-free options (specified only in the OptionList). Otherwise,
841/// output a warning.
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000842void CheckForSuperfluousOptions (const RecordVector& Edges,
843 const ToolDescriptions& ToolDescs,
844 const OptionDescriptions& OptDescs) {
Mikhail Glushenkova7d0ae32008-05-30 06:28:37 +0000845 llvm::StringSet<> nonSuperfluousOptions;
846
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000847 // Add all options mentioned in the ToolDesc.Actions to the set of
Mikhail Glushenkova7d0ae32008-05-30 06:28:37 +0000848 // non-superfluous options.
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000849 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
850 E = ToolDescs.end(); B != E; ++B) {
851 const ToolDescription& TD = *(*B);
852 ExtractOptionNames Callback(nonSuperfluousOptions);
853 if (TD.Actions)
854 WalkCase(TD.Actions, Callback, Callback);
855 }
856
857 // Add all options mentioned in the 'case' clauses of the
858 // OptionalEdges of the compilation graph to the set of
859 // non-superfluous options.
860 for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
861 B != E; ++B) {
862 const Record* Edge = *B;
863 DagInit* Weight = Edge->getValueAsDag("weight");
864
865 if (!isDagEmpty(Weight))
866 WalkCase(Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
Mikhail Glushenkova7d0ae32008-05-30 06:28:37 +0000867 }
868
869 // Check that all options in OptDescs belong to the set of
870 // non-superfluous options.
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000871 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
Mikhail Glushenkova7d0ae32008-05-30 06:28:37 +0000872 E = OptDescs.end(); B != E; ++B) {
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000873 const OptionDescription& Val = B->second;
Mikhail Glushenkova7d0ae32008-05-30 06:28:37 +0000874 if (!nonSuperfluousOptions.count(Val.Name)
875 && Val.Type != OptionType::Alias)
Mikhail Glushenkov01088772008-11-17 17:29:18 +0000876 llvm::cerr << "Warning: option '-" << Val.Name << "' has no effect! "
Mikhail Glushenkova7d0ae32008-05-30 06:28:37 +0000877 "Probable cause: this option is specified only in the OptionList.\n";
878 }
879}
880
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +0000881/// EmitCaseTest1Arg - Helper function used by
882/// EmitCaseConstructHandler.
883bool EmitCaseTest1Arg(const std::string& TestName,
884 const DagInit& d,
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000885 const OptionDescriptions& OptDescs,
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +0000886 std::ostream& O) {
887 checkNumberOfArguments(&d, 1);
888 const std::string& OptName = InitPtrToString(d.getArg(0));
Mikhail Glushenkov5c2b6b22008-12-17 02:47:01 +0000889
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +0000890 if (TestName == "switch_on") {
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000891 const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
892 if (!OptionType::IsSwitch(OptDesc.Type))
893 throw OptName + ": incorrect option type - should be a switch!";
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +0000894 O << OptDesc.GenVariableName();
895 return true;
896 } else if (TestName == "input_languages_contain") {
897 O << "InLangs.count(\"" << OptName << "\") != 0";
898 return true;
Mikhail Glushenkov2e73e852008-05-30 06:19:52 +0000899 } else if (TestName == "in_language") {
Mikhail Glushenkov07376512008-09-22 20:48:22 +0000900 // This works only for single-argument Tool::GenerateAction. Join
901 // tools can process several files in different languages simultaneously.
902
903 // TODO: make this work with Edge::Weight (if possible).
Mikhail Glushenkov11a353a2008-09-22 20:47:46 +0000904 O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
Mikhail Glushenkov2e73e852008-05-30 06:19:52 +0000905 return true;
Mikhail Glushenkov5c2b6b22008-12-17 02:47:01 +0000906 } else if (TestName == "not_empty" || TestName == "empty") {
907 const char* Test = (TestName == "empty") ? "" : "!";
908
Mikhail Glushenkov92b8da72008-05-30 06:24:07 +0000909 if (OptName == "o") {
Mikhail Glushenkov5c2b6b22008-12-17 02:47:01 +0000910 O << Test << "OutputFilename.empty()";
Mikhail Glushenkov92b8da72008-05-30 06:24:07 +0000911 return true;
912 }
913 else {
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000914 const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
915 if (OptionType::IsSwitch(OptDesc.Type))
916 throw OptName
917 + ": incorrect option type - should be a list or parameter!";
Mikhail Glushenkov5c2b6b22008-12-17 02:47:01 +0000918 O << Test << OptDesc.GenVariableName() << ".empty()";
Mikhail Glushenkov92b8da72008-05-30 06:24:07 +0000919 return true;
920 }
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +0000921 }
922
923 return false;
924}
925
926/// EmitCaseTest2Args - Helper function used by
927/// EmitCaseConstructHandler.
928bool EmitCaseTest2Args(const std::string& TestName,
929 const DagInit& d,
930 const char* IndentLevel,
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000931 const OptionDescriptions& OptDescs,
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +0000932 std::ostream& O) {
933 checkNumberOfArguments(&d, 2);
934 const std::string& OptName = InitPtrToString(d.getArg(0));
935 const std::string& OptArg = InitPtrToString(d.getArg(1));
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000936 const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +0000937
938 if (TestName == "parameter_equals") {
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000939 if (!OptionType::IsParameter(OptDesc.Type))
940 throw OptName + ": incorrect option type - should be a parameter!";
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +0000941 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
942 return true;
943 }
944 else if (TestName == "element_in_list") {
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000945 if (!OptionType::IsList(OptDesc.Type))
946 throw OptName + ": incorrect option type - should be a list!";
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +0000947 const std::string& VarName = OptDesc.GenVariableName();
948 O << "std::find(" << VarName << ".begin(),\n"
949 << IndentLevel << Indent1 << VarName << ".end(), \""
950 << OptArg << "\") != " << VarName << ".end()";
951 return true;
952 }
953
954 return false;
955}
956
957// Forward declaration.
958// EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
959void EmitCaseTest(const DagInit& d, const char* IndentLevel,
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000960 const OptionDescriptions& OptDescs,
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +0000961 std::ostream& O);
962
963/// EmitLogicalOperationTest - Helper function used by
964/// EmitCaseConstructHandler.
965void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
966 const char* IndentLevel,
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000967 const OptionDescriptions& OptDescs,
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +0000968 std::ostream& O) {
969 O << '(';
970 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
Mikhail Glushenkovffcf3a12008-05-30 06:18:16 +0000971 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +0000972 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
973 if (j != NumArgs - 1)
974 O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
975 else
976 O << ')';
977 }
978}
979
980/// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
981void EmitCaseTest(const DagInit& d, const char* IndentLevel,
Mikhail Glushenkovf9152532008-12-07 16:41:11 +0000982 const OptionDescriptions& OptDescs,
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +0000983 std::ostream& O) {
984 const std::string& TestName = d.getOperator()->getAsString();
985
986 if (TestName == "and")
987 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
988 else if (TestName == "or")
989 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
990 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
991 return;
992 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
993 return;
994 else
995 throw TestName + ": unknown edge property!";
996}
997
998// Emit code that handles the 'case' construct.
999// Takes a function object that should emit code for every case clause.
1000// Callback's type is
1001// void F(Init* Statement, const char* IndentLevel, std::ostream& O).
1002template <typename F>
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001003void EmitCaseConstructHandler(const Init* Dag, const char* IndentLevel,
Mikhail Glushenkov310d2eb2008-05-31 13:43:21 +00001004 F Callback, bool EmitElseIf,
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001005 const OptionDescriptions& OptDescs,
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +00001006 std::ostream& O) {
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001007 const DagInit* d = &InitPtrToDag(Dag);
1008 if (d->getOperator()->getAsString() != "case")
1009 throw std::string("EmitCaseConstructHandler should be invoked"
1010 " only on 'case' expressions!");
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +00001011
Mikhail Glushenkovcb64f4b2008-05-30 06:15:47 +00001012 unsigned numArgs = d->getNumArgs();
1013 if (d->getNumArgs() < 2)
1014 throw "There should be at least one clause in the 'case' expression:\n"
1015 + d->getAsString();
1016
1017 for (unsigned i = 0; i != numArgs; ++i) {
Mikhail Glushenkovffcf3a12008-05-30 06:18:16 +00001018 const DagInit& Test = InitPtrToDag(d->getArg(i));
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +00001019
Mikhail Glushenkovcb64f4b2008-05-30 06:15:47 +00001020 // Emit the test.
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +00001021 if (Test.getOperator()->getAsString() == "default") {
1022 if (i+2 != numArgs)
1023 throw std::string("The 'default' clause should be the last in the"
1024 "'case' construct!");
1025 O << IndentLevel << "else {\n";
1026 }
1027 else {
Mikhail Glushenkov2d0dc9a2008-05-30 06:22:15 +00001028 O << IndentLevel << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +00001029 EmitCaseTest(Test, IndentLevel, OptDescs, O);
1030 O << ") {\n";
1031 }
1032
Mikhail Glushenkovcb64f4b2008-05-30 06:15:47 +00001033 // Emit the corresponding statement.
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +00001034 ++i;
1035 if (i == numArgs)
1036 throw "Case construct handler: no corresponding action "
1037 "found for the test " + Test.getAsString() + '!';
1038
Mikhail Glushenkov2d0dc9a2008-05-30 06:22:15 +00001039 Init* arg = d->getArg(i);
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001040 const DagInit* nd = dynamic_cast<DagInit*>(arg);
1041 if (nd && (nd->getOperator()->getAsString() == "case")) {
1042 // Handle the nested 'case'.
1043 EmitCaseConstructHandler(nd, (std::string(IndentLevel) + Indent1).c_str(),
Mikhail Glushenkov2d0dc9a2008-05-30 06:22:15 +00001044 Callback, EmitElseIf, OptDescs, O);
1045 }
1046 else {
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001047 Callback(arg, (std::string(IndentLevel) + Indent1).c_str(), O);
Mikhail Glushenkov2d0dc9a2008-05-30 06:22:15 +00001048 }
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +00001049 O << IndentLevel << "}\n";
1050 }
1051}
1052
Mikhail Glushenkova298bb72009-01-21 13:04:00 +00001053/// TokenizeCmdline - converts from "$CALL(HookName, 'Arg1', 'Arg2')/path" to
1054/// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path"] .
1055/// Helper function used by EmitCmdLineVecFill and.
1056void TokenizeCmdline(const std::string& CmdLine, StrVector& Out) {
1057 const char* Delimiters = " \t\n\v\f\r";
1058 enum TokenizerState
1059 { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1060 cur_st = Normal;
1061 Out.push_back("");
1062
1063 std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1064 E = CmdLine.size();
1065 if (B == std::string::npos)
1066 throw "Empty command-line string!";
1067 for (; B != E; ++B) {
1068 char cur_ch = CmdLine[B];
1069
1070 switch (cur_st) {
1071 case Normal:
1072 if (cur_ch == '$') {
1073 cur_st = SpecialCommand;
1074 break;
1075 }
1076 if (oneOf(Delimiters, cur_ch)) {
1077 // Skip whitespace
1078 B = CmdLine.find_first_not_of(Delimiters, B);
1079 if (B == std::string::npos) {
1080 B = E-1;
1081 continue;
1082 }
1083 --B;
1084 Out.push_back("");
1085 continue;
1086 }
1087 break;
1088
1089
1090 case SpecialCommand:
1091 if (oneOf(Delimiters, cur_ch)) {
1092 cur_st = Normal;
1093 Out.push_back("");
1094 continue;
1095 }
1096 if (cur_ch == '(') {
1097 Out.push_back("");
1098 cur_st = InsideSpecialCommand;
1099 continue;
1100 }
1101 break;
1102
1103 case InsideSpecialCommand:
1104 if (oneOf(Delimiters, cur_ch)) {
1105 continue;
1106 }
1107 if (cur_ch == '\'') {
1108 cur_st = InsideQuotationMarks;
1109 Out.push_back("");
1110 continue;
1111 }
1112 if (cur_ch == ')') {
1113 cur_st = Normal;
1114 Out.push_back("");
1115 }
1116 if (cur_ch == ',') {
1117 continue;
1118 }
1119
1120 break;
1121
1122 case InsideQuotationMarks:
1123 if (cur_ch == '\'') {
1124 cur_st = InsideSpecialCommand;
1125 continue;
1126 }
1127 break;
1128 }
1129
1130 Out.back().push_back(cur_ch);
1131 }
1132}
1133
1134template <class I, class S>
1135void checkedIncrement(I& P, I E, S ErrorString) {
1136 ++P;
1137 if (P == E)
1138 throw ErrorString;
1139}
1140
Mikhail Glushenkov08bd2e72008-05-30 06:12:24 +00001141/// SubstituteSpecialCommands - Perform string substitution for $CALL
1142/// and $ENV. Helper function used by EmitCmdLineVecFill().
Mikhail Glushenkova298bb72009-01-21 13:04:00 +00001143StrVector::const_iterator SubstituteSpecialCommands
1144(StrVector::const_iterator Pos, StrVector::const_iterator End, std::ostream& O)
1145{
Mikhail Glushenkov22424562008-05-30 06:13:29 +00001146
Mikhail Glushenkova298bb72009-01-21 13:04:00 +00001147 const std::string& cmd = *Pos;
1148
1149 if (cmd == "$CALL") {
1150 checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1151 const std::string& CmdName = *Pos;
1152
1153 if (CmdName == ")")
Mikhail Glushenkov22424562008-05-30 06:13:29 +00001154 throw std::string("$CALL invocation: empty argument list!");
1155
Mikhail Glushenkova298bb72009-01-21 13:04:00 +00001156 O << "hooks::";
1157 O << CmdName << "(";
Mikhail Glushenkov22424562008-05-30 06:13:29 +00001158
Mikhail Glushenkova298bb72009-01-21 13:04:00 +00001159
1160 bool firstIteration = true;
1161 while (true) {
1162 checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1163 const std::string& Arg = *Pos;
1164 assert(Arg.size() != 0);
1165
1166 if (Arg[0] == ')')
1167 break;
1168
1169 if (firstIteration)
1170 firstIteration = false;
1171 else
1172 O << ", ";
1173
1174 O << '"' << Arg << '"';
1175 }
1176
1177 O << ')';
1178
1179 }
1180 else if (cmd == "$ENV") {
1181 checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1182 const std::string& EnvName = *Pos;
1183
1184 if (EnvName == ")")
1185 throw "$ENV invocation: empty argument list!";
1186
1187 O << "checkCString(std::getenv(\"";
1188 O << EnvName;
1189 O << "\"))";
1190
1191 checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
Mikhail Glushenkov22424562008-05-30 06:13:29 +00001192 }
1193 else {
1194 throw "Unknown special command: " + cmd;
1195 }
1196
Mikhail Glushenkova298bb72009-01-21 13:04:00 +00001197 const std::string& Leftover = *Pos;
1198 assert(Leftover.at(0) == ')');
1199 if (Leftover.size() != 1)
1200 O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1201 O << ')';
Mikhail Glushenkov22424562008-05-30 06:13:29 +00001202
Mikhail Glushenkova298bb72009-01-21 13:04:00 +00001203 return Pos;
Mikhail Glushenkov08bd2e72008-05-30 06:12:24 +00001204}
1205
1206/// EmitCmdLineVecFill - Emit code that fills in the command line
1207/// vector. Helper function used by EmitGenerateActionMethod().
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +00001208void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001209 bool IsJoin, const char* IndentLevel,
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +00001210 std::ostream& O) {
1211 StrVector StrVec;
Mikhail Glushenkova298bb72009-01-21 13:04:00 +00001212 TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1213
Mikhail Glushenkov08bd2e72008-05-30 06:12:24 +00001214 if (StrVec.empty())
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +00001215 throw "Tool " + ToolName + " has empty command line!";
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001216
Mikhail Glushenkova298bb72009-01-21 13:04:00 +00001217 StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1218
1219 // If there is a hook invocation on the place of the first command, skip it.
1220 if (StrVec[0][0] == '$') {
1221 while (I != E && (*I)[0] != ')' )
1222 ++I;
1223
1224 // Skip the ')' symbol.
1225 ++I;
1226 }
1227 else {
1228 ++I;
1229 }
1230
1231 for (; I != E; ++I) {
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001232 const std::string& cmd = *I;
Mikhail Glushenkova298bb72009-01-21 13:04:00 +00001233 // std::cerr << cmd;
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +00001234 O << IndentLevel;
Mikhail Glushenkov08bd2e72008-05-30 06:12:24 +00001235 if (cmd.at(0) == '$') {
1236 if (cmd == "$INFILE") {
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001237 if (IsJoin)
Mikhail Glushenkov08bd2e72008-05-30 06:12:24 +00001238 O << "for (PathVector::const_iterator B = inFiles.begin()"
1239 << ", E = inFiles.end();\n"
1240 << IndentLevel << "B != E; ++B)\n"
1241 << IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
1242 else
1243 O << "vec.push_back(inFile.toString());\n";
1244 }
1245 else if (cmd == "$OUTFILE") {
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001246 O << "vec.push_back(out_file);\n";
Mikhail Glushenkov08bd2e72008-05-30 06:12:24 +00001247 }
1248 else {
Mikhail Glushenkova298bb72009-01-21 13:04:00 +00001249 O << "vec.push_back(";
1250 I = SubstituteSpecialCommands(I, E, O);
Mikhail Glushenkov22424562008-05-30 06:13:29 +00001251 O << ");\n";
Mikhail Glushenkov08bd2e72008-05-30 06:12:24 +00001252 }
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001253 }
1254 else {
1255 O << "vec.push_back(\"" << cmd << "\");\n";
1256 }
1257 }
Mikhail Glushenkova298bb72009-01-21 13:04:00 +00001258 O << IndentLevel << "cmd = ";
1259
1260 if (StrVec[0][0] == '$')
1261 SubstituteSpecialCommands(StrVec.begin(), StrVec.end(), O);
1262 else
1263 O << '"' << StrVec[0] << '"';
1264 O << ";\n";
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +00001265}
1266
Mikhail Glushenkov08bd2e72008-05-30 06:12:24 +00001267/// EmitCmdLineVecFillCallback - A function object wrapper around
1268/// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1269/// argument to EmitCaseConstructHandler().
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +00001270class EmitCmdLineVecFillCallback {
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001271 bool IsJoin;
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +00001272 const std::string& ToolName;
1273 public:
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001274 EmitCmdLineVecFillCallback(bool J, const std::string& TN)
1275 : IsJoin(J), ToolName(TN) {}
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +00001276
1277 void operator()(const Init* Statement, const char* IndentLevel,
1278 std::ostream& O) const
1279 {
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001280 EmitCmdLineVecFill(Statement, ToolName, IsJoin,
1281 IndentLevel, O);
1282 }
1283};
1284
1285/// EmitForwardOptionPropertyHandlingCode - Helper function used to
1286/// implement EmitActionHandler. Emits code for
1287/// handling the (forward) and (forward_as) option properties.
1288void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1289 const char* Indent,
1290 const std::string& NewName,
1291 std::ostream& O) {
1292 const std::string& Name = NewName.empty()
1293 ? ("-" + D.Name)
1294 : NewName;
1295
1296 switch (D.Type) {
1297 case OptionType::Switch:
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001298 O << Indent << "vec.push_back(\"" << Name << "\");\n";
1299 break;
1300 case OptionType::Parameter:
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001301 O << Indent << "vec.push_back(\"" << Name << "\");\n";
1302 O << Indent << "vec.push_back(" << D.GenVariableName() << ");\n";
1303 break;
1304 case OptionType::Prefix:
1305 O << Indent << "vec.push_back(\"" << Name << "\" + "
1306 << D.GenVariableName() << ");\n";
1307 break;
1308 case OptionType::PrefixList:
1309 O << Indent << "for (" << D.GenTypeDeclaration()
1310 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1311 << Indent << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
1312 << Indent << Indent1 << "vec.push_back(\"" << Name << "\" + "
1313 << "*B);\n";
1314 break;
1315 case OptionType::ParameterList:
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001316 O << Indent << "for (" << D.GenTypeDeclaration()
1317 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1318 << Indent << "E = " << D.GenVariableName()
1319 << ".end() ; B != E; ++B) {\n"
1320 << Indent << Indent1 << "vec.push_back(\"" << Name << "\");\n"
1321 << Indent << Indent1 << "vec.push_back(*B);\n"
1322 << Indent << "}\n";
1323 break;
1324 case OptionType::Alias:
1325 default:
1326 throw std::string("Aliases are not allowed in tool option descriptions!");
1327 }
1328}
1329
1330/// EmitActionHandler - Emit code that handles actions. Used by
1331/// EmitGenerateActionMethod() as an argument to
1332/// EmitCaseConstructHandler().
1333class EmitActionHandler {
1334 const OptionDescriptions& OptDescs;
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001335
Mikhail Glushenkov08509492008-12-07 16:42:22 +00001336 void processActionDag(const Init* Statement, const char* IndentLevel,
1337 std::ostream& O) const
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001338 {
1339 const DagInit& Dag = InitPtrToDag(Statement);
1340 const std::string& ActionName = Dag.getOperator()->getAsString();
1341
1342 if (ActionName == "append_cmd") {
1343 checkNumberOfArguments(&Dag, 1);
1344 const std::string& Cmd = InitPtrToString(Dag.getArg(0));
1345 O << IndentLevel << "vec.push_back(\"" << Cmd << "\");\n";
1346 }
Mikhail Glushenkov5c2b6b22008-12-17 02:47:01 +00001347 else if (ActionName == "error") {
1348 O << IndentLevel << "throw std::runtime_error(\"" <<
1349 (Dag.getNumArgs() >= 1 ? InitPtrToString(Dag.getArg(0))
1350 : "Unknown error!")
1351 << "\");\n";
1352 }
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001353 else if (ActionName == "forward") {
1354 checkNumberOfArguments(&Dag, 1);
1355 const std::string& Name = InitPtrToString(Dag.getArg(0));
1356 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1357 IndentLevel, "", O);
1358 }
1359 else if (ActionName == "forward_as") {
1360 checkNumberOfArguments(&Dag, 2);
1361 const std::string& Name = InitPtrToString(Dag.getArg(0));
1362 const std::string& NewName = InitPtrToString(Dag.getArg(0));
1363 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1364 IndentLevel, NewName, O);
1365 }
1366 else if (ActionName == "output_suffix") {
1367 checkNumberOfArguments(&Dag, 1);
1368 const std::string& OutSuf = InitPtrToString(Dag.getArg(0));
1369 O << IndentLevel << "output_suffix = \"" << OutSuf << "\";\n";
1370 }
1371 else if (ActionName == "stop_compilation") {
1372 O << IndentLevel << "stop_compilation = true;\n";
1373 }
1374 else if (ActionName == "unpack_values") {
1375 checkNumberOfArguments(&Dag, 1);
1376 const std::string& Name = InitPtrToString(Dag.getArg(0));
1377 const OptionDescription& D = OptDescs.FindOption(Name);
1378
1379 if (OptionType::IsList(D.Type)) {
1380 O << IndentLevel << "for (" << D.GenTypeDeclaration()
1381 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1382 << IndentLevel << "E = " << D.GenVariableName()
1383 << ".end(); B != E; ++B)\n"
1384 << IndentLevel << Indent1 << "llvm::SplitString(*B, vec, \",\");\n";
1385 }
1386 else if (OptionType::IsParameter(D.Type)){
1387 O << Indent3 << "llvm::SplitString("
1388 << D.GenVariableName() << ", vec, \",\");\n";
1389 }
1390 else {
1391 throw "Option '" + D.Name +
1392 "': switches can't have the 'unpack_values' property!";
1393 }
1394 }
1395 else {
1396 throw "Unknown action name: " + ActionName + "!";
1397 }
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +00001398 }
Mikhail Glushenkov08509492008-12-07 16:42:22 +00001399 public:
1400 EmitActionHandler(const OptionDescriptions& OD)
1401 : OptDescs(OD) {}
1402
1403 void operator()(const Init* Statement, const char* IndentLevel,
1404 std::ostream& O) const
1405 {
1406 if (typeid(*Statement) == typeid(ListInit)) {
1407 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1408 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1409 B != E; ++B)
1410 this->processActionDag(*B, IndentLevel, O);
1411 }
1412 else {
1413 this->processActionDag(Statement, IndentLevel, O);
1414 }
1415 }
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +00001416};
1417
1418// EmitGenerateActionMethod - Emit one of two versions of the
1419// Tool::GenerateAction() method.
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001420void EmitGenerateActionMethod (const ToolDescription& D,
1421 const OptionDescriptions& OptDescs,
1422 bool IsJoin, std::ostream& O) {
1423 if (IsJoin)
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +00001424 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
1425 else
1426 O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
1427
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001428 O << Indent2 << "bool HasChildren,\n"
1429 << Indent2 << "const llvm::sys::Path& TempDir,\n"
Mikhail Glushenkov11a353a2008-09-22 20:47:46 +00001430 << Indent2 << "const InputLanguagesSet& InLangs,\n"
1431 << Indent2 << "const LanguageMap& LangMap) const\n"
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +00001432 << Indent1 << "{\n"
Mikhail Glushenkovc389e942008-11-08 19:43:32 +00001433 << Indent2 << "std::string cmd;\n"
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001434 << Indent2 << "std::vector<std::string> vec;\n"
1435 << Indent2 << "bool stop_compilation = !HasChildren;\n"
1436 << Indent2 << "const char* output_suffix = \"" << D.OutputSuffix << "\";\n"
1437 << Indent2 << "std::string out_file;\n\n";
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001438
Mikhail Glushenkov8e7254c2008-05-09 08:27:26 +00001439 // For every understood option, emit handling code.
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001440 if (D.Actions)
1441 EmitCaseConstructHandler(D.Actions, Indent2, EmitActionHandler(OptDescs),
1442 false, OptDescs, O);
1443
1444 O << '\n' << Indent2
1445 << "out_file = OutFilename(" << (IsJoin ? "sys::Path(),\n" : "inFile,\n")
1446 << Indent3 << "TempDir, stop_compilation, output_suffix).toString();\n\n";
1447
1448 // cmd_line is either a string or a 'case' construct.
1449 if (!D.CmdLine)
1450 throw "Tool " + D.Name + " has no cmd_line property!";
1451 else if (typeid(*D.CmdLine) == typeid(StringInit))
1452 EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
1453 else
1454 EmitCaseConstructHandler(D.CmdLine, Indent2,
1455 EmitCmdLineVecFillCallback(IsJoin, D.Name),
1456 true, OptDescs, O);
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001457
Mikhail Glushenkov8e7254c2008-05-09 08:27:26 +00001458 // Handle the Sink property.
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001459 if (D.isSink()) {
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001460 O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
1461 << Indent3 << "vec.insert(vec.end(), "
1462 << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
1463 << Indent2 << "}\n";
1464 }
1465
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001466 O << Indent2 << "return Action(cmd, vec, stop_compilation, out_file);\n"
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001467 << Indent1 << "}\n\n";
1468}
1469
Mikhail Glushenkov8e7254c2008-05-09 08:27:26 +00001470/// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1471/// a given Tool class.
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001472void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
1473 const OptionDescriptions& OptDescs,
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +00001474 std::ostream& O) {
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001475 if (!ToolDesc.isJoin())
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001476 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001477 << Indent2 << "bool HasChildren,\n"
1478 << Indent2 << "const llvm::sys::Path& TempDir,\n"
Mikhail Glushenkov11a353a2008-09-22 20:47:46 +00001479 << Indent2 << "const InputLanguagesSet& InLangs,\n"
1480 << Indent2 << "const LanguageMap& LangMap) const\n"
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001481 << Indent1 << "{\n"
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001482 << Indent2 << "throw std::runtime_error(\"" << ToolDesc.Name
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001483 << " is not a Join tool!\");\n"
1484 << Indent1 << "}\n\n";
1485 else
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001486 EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001487
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001488 EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001489}
1490
Mikhail Glushenkov4561ab52008-05-07 21:50:19 +00001491/// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1492/// methods for a given Tool class.
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001493void EmitInOutLanguageMethods (const ToolDescription& D, std::ostream& O) {
Mikhail Glushenkov5fe84752008-05-30 06:24:49 +00001494 O << Indent1 << "const char** InputLanguages() const {\n"
1495 << Indent2 << "return InputLanguages_;\n"
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001496 << Indent1 << "}\n\n";
1497
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001498 if (D.OutLanguage.empty())
1499 throw "Tool " + D.Name + " has no 'out_language' property!";
1500
Mikhail Glushenkovb96cb602008-05-06 17:24:26 +00001501 O << Indent1 << "const char* OutputLanguage() const {\n"
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001502 << Indent2 << "return \"" << D.OutLanguage << "\";\n"
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001503 << Indent1 << "}\n\n";
1504}
1505
Mikhail Glushenkov4561ab52008-05-07 21:50:19 +00001506/// EmitNameMethod - Emit the Name() method for a given Tool class.
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001507void EmitNameMethod (const ToolDescription& D, std::ostream& O) {
Mikhail Glushenkovb96cb602008-05-06 17:24:26 +00001508 O << Indent1 << "const char* Name() const {\n"
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001509 << Indent2 << "return \"" << D.Name << "\";\n"
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001510 << Indent1 << "}\n\n";
1511}
1512
Mikhail Glushenkov4561ab52008-05-07 21:50:19 +00001513/// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1514/// class.
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001515void EmitIsJoinMethod (const ToolDescription& D, std::ostream& O) {
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001516 O << Indent1 << "bool IsJoin() const {\n";
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001517 if (D.isJoin())
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001518 O << Indent2 << "return true;\n";
1519 else
1520 O << Indent2 << "return false;\n";
1521 O << Indent1 << "}\n\n";
1522}
1523
Mikhail Glushenkov5fe84752008-05-30 06:24:49 +00001524/// EmitStaticMemberDefinitions - Emit static member definitions for a
1525/// given Tool class.
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001526void EmitStaticMemberDefinitions(const ToolDescription& D, std::ostream& O) {
1527 if (D.InLanguage.empty())
1528 throw "Tool " + D.Name + " has no 'in_language' property!";
1529
1530 O << "const char* " << D.Name << "::InputLanguages_[] = {";
1531 for (StrVector::const_iterator B = D.InLanguage.begin(),
1532 E = D.InLanguage.end(); B != E; ++B)
Mikhail Glushenkov5fe84752008-05-30 06:24:49 +00001533 O << '\"' << *B << "\", ";
1534 O << "0};\n\n";
1535}
1536
Mikhail Glushenkov4561ab52008-05-07 21:50:19 +00001537/// EmitToolClassDefinition - Emit a Tool class definition.
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001538void EmitToolClassDefinition (const ToolDescription& D,
1539 const OptionDescriptions& OptDescs,
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +00001540 std::ostream& O) {
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001541 if (D.Name == "root")
Mikhail Glushenkov0d08db02008-05-06 16:35:25 +00001542 return;
1543
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001544 // Header
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001545 O << "class " << D.Name << " : public ";
1546 if (D.isJoin())
Mikhail Glushenkovc74bfc92008-05-06 17:26:53 +00001547 O << "JoinTool";
1548 else
1549 O << "Tool";
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001550
Mikhail Glushenkov5fe84752008-05-30 06:24:49 +00001551 O << "{\nprivate:\n"
1552 << Indent1 << "static const char* InputLanguages_[];\n\n";
1553
1554 O << "public:\n";
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001555 EmitNameMethod(D, O);
1556 EmitInOutLanguageMethods(D, O);
1557 EmitIsJoinMethod(D, O);
1558 EmitGenerateActionMethods(D, OptDescs, O);
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001559
1560 // Close class definition
Mikhail Glushenkov5fe84752008-05-30 06:24:49 +00001561 O << "};\n";
1562
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001563 EmitStaticMemberDefinitions(D, O);
Mikhail Glushenkov5fe84752008-05-30 06:24:49 +00001564
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001565}
1566
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001567/// EmitOptionDefintions - Iterate over a list of option descriptions
1568/// and emit registration code.
1569void EmitOptionDefintions (const OptionDescriptions& descs,
Mikhail Glushenkovb59dbad2008-12-07 16:42:47 +00001570 bool HasSink, bool HasExterns,
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001571 std::ostream& O)
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001572{
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001573 std::vector<OptionDescription> Aliases;
Mikhail Glushenkov6be4ffc2008-05-30 06:22:52 +00001574
Mikhail Glushenkov34f37622008-05-30 06:23:29 +00001575 // Emit static cl::Option variables.
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001576 for (OptionDescriptions::const_iterator B = descs.begin(),
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001577 E = descs.end(); B!=E; ++B) {
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001578 const OptionDescription& val = B->second;
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001579
Mikhail Glushenkov6be4ffc2008-05-30 06:22:52 +00001580 if (val.Type == OptionType::Alias) {
1581 Aliases.push_back(val);
1582 continue;
1583 }
1584
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001585 if (val.isExtern())
1586 O << "extern ";
1587
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001588 O << val.GenTypeDeclaration() << ' '
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001589 << val.GenVariableName();
1590
1591 if (val.isExtern()) {
1592 O << ";\n";
1593 continue;
1594 }
1595
1596 O << "(\"" << val.Name << '\"';
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001597
1598 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1599 O << ", cl::Prefix";
1600
1601 if (val.isRequired()) {
1602 switch (val.Type) {
1603 case OptionType::PrefixList:
1604 case OptionType::ParameterList:
1605 O << ", cl::OneOrMore";
1606 break;
1607 default:
1608 O << ", cl::Required";
1609 }
1610 }
1611
Mikhail Glushenkov739c7202008-11-28 00:13:25 +00001612 if (val.isReallyHidden() || val.isHidden()) {
1613 if (val.isRequired())
1614 O << " |";
1615 else
1616 O << ",";
1617 if (val.isReallyHidden())
1618 O << " cl::ReallyHidden";
1619 else
1620 O << " cl::Hidden";
1621 }
1622
Mikhail Glushenkov6be4ffc2008-05-30 06:22:52 +00001623 if (!val.Help.empty())
1624 O << ", cl::desc(\"" << val.Help << "\")";
1625
1626 O << ");\n";
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001627 }
1628
Mikhail Glushenkov6be4ffc2008-05-30 06:22:52 +00001629 // Emit the aliases (they should go after all the 'proper' options).
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001630 for (std::vector<OptionDescription>::const_iterator
Mikhail Glushenkov6be4ffc2008-05-30 06:22:52 +00001631 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001632 const OptionDescription& val = *B;
Mikhail Glushenkov6be4ffc2008-05-30 06:22:52 +00001633
1634 O << val.GenTypeDeclaration() << ' '
1635 << val.GenVariableName()
1636 << "(\"" << val.Name << '\"';
1637
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001638 const OptionDescription& D = descs.FindOption(val.Help);
1639 O << ", cl::aliasopt(" << D.GenVariableName() << ")";
Mikhail Glushenkov6be4ffc2008-05-30 06:22:52 +00001640
1641 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
1642 }
1643
1644 // Emit the sink option.
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001645 if (HasSink)
Mikhail Glushenkovb59dbad2008-12-07 16:42:47 +00001646 O << (HasExterns ? "extern cl" : "cl")
1647 << "::list<std::string> " << SinkOptionName
1648 << (HasExterns ? ";\n" : "(cl::Sink);\n");
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001649
1650 O << '\n';
1651}
1652
Mikhail Glushenkov4561ab52008-05-07 21:50:19 +00001653/// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001654void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
1655{
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001656 // Generate code
Mikhail Glushenkovc82ce4a2008-09-22 20:49:34 +00001657 O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001658
Mikhail Glushenkov01088772008-11-17 17:29:18 +00001659 // Get the relevant field out of RecordKeeper
Mikhail Glushenkovfa270772008-11-17 17:29:42 +00001660 const Record* LangMapRecord = Records.getDef("LanguageMap");
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001661
Mikhail Glushenkov01088772008-11-17 17:29:18 +00001662 // It is allowed for a plugin to have no language map.
1663 if (LangMapRecord) {
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001664
Mikhail Glushenkov01088772008-11-17 17:29:18 +00001665 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
1666 if (!LangsToSuffixesList)
1667 throw std::string("Error in the language map definition!");
1668
1669 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
Mikhail Glushenkovfa270772008-11-17 17:29:42 +00001670 const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
Mikhail Glushenkov01088772008-11-17 17:29:18 +00001671
1672 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
1673 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
1674
1675 for (unsigned i = 0; i < Suffixes->size(); ++i)
1676 O << Indent1 << "langMap[\""
1677 << InitPtrToString(Suffixes->getElement(i))
1678 << "\"] = \"" << Lang << "\";\n";
1679 }
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001680 }
1681
Mikhail Glushenkove1d44b52008-12-11 10:34:18 +00001682 O << "}\n\n";
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001683}
1684
Mikhail Glushenkov08bd2e72008-05-30 06:12:24 +00001685/// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
1686/// by EmitEdgeClass().
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +00001687void IncDecWeight (const Init* i, const char* IndentLevel,
1688 std::ostream& O) {
Mikhail Glushenkovffcf3a12008-05-30 06:18:16 +00001689 const DagInit& d = InitPtrToDag(i);
Mikhail Glushenkove5557f42008-05-30 06:08:50 +00001690 const std::string& OpName = d.getOperator()->getAsString();
1691
Mikhail Glushenkov5c2b6b22008-12-17 02:47:01 +00001692 if (OpName == "inc_weight") {
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001693 O << IndentLevel << "ret += ";
Mikhail Glushenkov5c2b6b22008-12-17 02:47:01 +00001694 }
1695 else if (OpName == "dec_weight") {
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001696 O << IndentLevel << "ret -= ";
Mikhail Glushenkov5c2b6b22008-12-17 02:47:01 +00001697 }
1698 else if (OpName == "error") {
1699 O << IndentLevel << "throw std::runtime_error(\"" <<
1700 (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0))
1701 : "Unknown error!")
1702 << "\");\n";
1703 return;
1704 }
1705
Mikhail Glushenkove5557f42008-05-30 06:08:50 +00001706 else
Mikhail Glushenkov5c2b6b22008-12-17 02:47:01 +00001707 throw "Unknown operator in edge properties list: " + OpName + '!' +
Mikhail Glushenkov65ee1e62008-12-18 04:06:58 +00001708 "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
Mikhail Glushenkove5557f42008-05-30 06:08:50 +00001709
1710 if (d.getNumArgs() > 0)
1711 O << InitPtrToInt(d.getArg(0)) << ";\n";
1712 else
1713 O << "2;\n";
1714
Mikhail Glushenkov29063552008-05-06 18:18:20 +00001715}
1716
Mikhail Glushenkov4561ab52008-05-07 21:50:19 +00001717/// EmitEdgeClass - Emit a single Edge# class.
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +00001718void EmitEdgeClass (unsigned N, const std::string& Target,
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001719 DagInit* Case, const OptionDescriptions& OptDescs,
Mikhail Glushenkovb5ccfbf2008-05-30 06:10:19 +00001720 std::ostream& O) {
Mikhail Glushenkov9ef501b2008-05-06 17:23:14 +00001721
1722 // Class constructor.
1723 O << "class Edge" << N << ": public Edge {\n"
1724 << "public:\n"
1725 << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1726 << "\") {}\n\n"
1727
Mikhail Glushenkovbb8b58d2008-05-06 18:14:24 +00001728 // Function Weight().
Mikhail Glushenkov76b1b242008-05-06 18:15:12 +00001729 << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
Mikhail Glushenkovbb8b58d2008-05-06 18:14:24 +00001730 << Indent2 << "unsigned ret = 0;\n";
Mikhail Glushenkov9ef501b2008-05-06 17:23:14 +00001731
Mikhail Glushenkove5557f42008-05-30 06:08:50 +00001732 // Handle the 'case' construct.
Mikhail Glushenkov2d0dc9a2008-05-30 06:22:15 +00001733 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
Mikhail Glushenkovbb8b58d2008-05-06 18:14:24 +00001734
1735 O << Indent2 << "return ret;\n"
1736 << Indent1 << "};\n\n};\n\n";
Mikhail Glushenkov9ef501b2008-05-06 17:23:14 +00001737}
1738
Mikhail Glushenkov08bd2e72008-05-30 06:12:24 +00001739/// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
Mikhail Glushenkovad746be2008-11-28 00:13:47 +00001740void EmitEdgeClasses (const RecordVector& EdgeVector,
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001741 const OptionDescriptions& OptDescs,
Mikhail Glushenkov0a174932008-05-06 16:36:06 +00001742 std::ostream& O) {
Mikhail Glushenkovad746be2008-11-28 00:13:47 +00001743 int i = 0;
Mikhail Glushenkov15b71ba2008-12-07 16:44:47 +00001744 for (RecordVector::const_iterator B = EdgeVector.begin(),
1745 E = EdgeVector.end(); B != E; ++B) {
1746 const Record* Edge = *B;
1747 const std::string& NodeB = Edge->getValueAsString("b");
Mikhail Glushenkove5557f42008-05-30 06:08:50 +00001748 DagInit* Weight = Edge->getValueAsDag("weight");
Mikhail Glushenkov0a174932008-05-06 16:36:06 +00001749
Mikhail Glushenkovad746be2008-11-28 00:13:47 +00001750 if (!isDagEmpty(Weight))
Mikhail Glushenkov15b71ba2008-12-07 16:44:47 +00001751 EmitEdgeClass(i, NodeB, Weight, OptDescs, O);
Mikhail Glushenkovad746be2008-11-28 00:13:47 +00001752 ++i;
Mikhail Glushenkov0a174932008-05-06 16:36:06 +00001753 }
1754}
1755
Mikhail Glushenkov4561ab52008-05-07 21:50:19 +00001756/// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1757/// function.
Mikhail Glushenkovad746be2008-11-28 00:13:47 +00001758void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001759 const ToolDescriptions& ToolDescs,
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001760 std::ostream& O)
1761{
Mikhail Glushenkovc82ce4a2008-09-22 20:49:34 +00001762 O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001763
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001764 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1765 E = ToolDescs.end(); B != E; ++B)
Mikhail Glushenkovfa270772008-11-17 17:29:42 +00001766 O << Indent1 << "G.insertNode(new " << (*B)->Name << "());\n";
Mikhail Glushenkov262d2482008-11-12 00:05:17 +00001767
Mikhail Glushenkov0d08db02008-05-06 16:35:25 +00001768 O << '\n';
1769
Mikhail Glushenkov262d2482008-11-12 00:05:17 +00001770 // Insert edges.
1771
Mikhail Glushenkovad746be2008-11-28 00:13:47 +00001772 int i = 0;
Mikhail Glushenkov15b71ba2008-12-07 16:44:47 +00001773 for (RecordVector::const_iterator B = EdgeVector.begin(),
1774 E = EdgeVector.end(); B != E; ++B) {
1775 const Record* Edge = *B;
1776 const std::string& NodeA = Edge->getValueAsString("a");
1777 const std::string& NodeB = Edge->getValueAsString("b");
Mikhail Glushenkove5557f42008-05-30 06:08:50 +00001778 DagInit* Weight = Edge->getValueAsDag("weight");
Mikhail Glushenkovd752c3f2008-05-06 16:36:50 +00001779
Mikhail Glushenkov15b71ba2008-12-07 16:44:47 +00001780 O << Indent1 << "G.insertEdge(\"" << NodeA << "\", ";
Mikhail Glushenkovd752c3f2008-05-06 16:36:50 +00001781
Mikhail Glushenkove5557f42008-05-30 06:08:50 +00001782 if (isDagEmpty(Weight))
Mikhail Glushenkov15b71ba2008-12-07 16:44:47 +00001783 O << "new SimpleEdge(\"" << NodeB << "\")";
Mikhail Glushenkovd752c3f2008-05-06 16:36:50 +00001784 else
1785 O << "new Edge" << i << "()";
1786
1787 O << ");\n";
Mikhail Glushenkovad746be2008-11-28 00:13:47 +00001788 ++i;
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001789 }
1790
Mikhail Glushenkove1d44b52008-12-11 10:34:18 +00001791 O << "}\n\n";
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001792}
1793
Mikhail Glushenkov08bd2e72008-05-30 06:12:24 +00001794/// ExtractHookNames - Extract the hook names from all instances of
1795/// $CALL(HookName) in the provided command line string. Helper
1796/// function used by FillInHookNames().
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001797class ExtractHookNames {
Mikhail Glushenkova298bb72009-01-21 13:04:00 +00001798 llvm::StringMap<unsigned>& HookNames_;
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001799public:
Mikhail Glushenkova298bb72009-01-21 13:04:00 +00001800 ExtractHookNames(llvm::StringMap<unsigned>& HookNames)
1801 : HookNames_(HookNames) {}
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001802
1803 void operator()(const Init* CmdLine) {
1804 StrVector cmds;
Mikhail Glushenkova298bb72009-01-21 13:04:00 +00001805 TokenizeCmdline(InitPtrToString(CmdLine), cmds);
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001806 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
1807 B != E; ++B) {
1808 const std::string& cmd = *B;
Mikhail Glushenkova298bb72009-01-21 13:04:00 +00001809
1810 if (cmd == "$CALL") {
1811 unsigned NumArgs = 0;
1812 checkedIncrement(B, E, "Syntax error in $CALL invocation!");
1813 const std::string& HookName = *B;
1814
1815
1816 if (HookName.at(0) == ')')
1817 throw "$CALL invoked with no arguments!";
1818
1819 while (++B != E && B->at(0) != ')') {
1820 ++NumArgs;
1821 }
1822
1823 StringMap<unsigned>::const_iterator H = HookNames_.find(HookName);
1824
1825 if (H != HookNames_.end() && H->second != NumArgs)
1826 throw "Overloading of hooks is not allowed. Overloaded hook: "
1827 + HookName;
1828 else
1829 HookNames_[HookName] = NumArgs;
1830
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001831 }
Mikhail Glushenkov08bd2e72008-05-30 06:12:24 +00001832 }
1833 }
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001834};
Mikhail Glushenkov2d0dc9a2008-05-30 06:22:15 +00001835
Mikhail Glushenkov08bd2e72008-05-30 06:12:24 +00001836/// FillInHookNames - Actually extract the hook names from all command
1837/// line strings. Helper function used by EmitHookDeclarations().
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001838void FillInHookNames(const ToolDescriptions& ToolDescs,
Mikhail Glushenkova298bb72009-01-21 13:04:00 +00001839 llvm::StringMap<unsigned>& HookNames)
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001840{
Mikhail Glushenkov2d0dc9a2008-05-30 06:22:15 +00001841 // For all command lines:
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001842 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1843 E = ToolDescs.end(); B != E; ++B) {
1844 const ToolDescription& D = *(*B);
1845 if (!D.CmdLine)
Mikhail Glushenkov08bd2e72008-05-30 06:12:24 +00001846 continue;
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001847 if (dynamic_cast<StringInit*>(D.CmdLine))
Mikhail Glushenkov08bd2e72008-05-30 06:12:24 +00001848 // This is a string.
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001849 ExtractHookNames(HookNames).operator()(D.CmdLine);
Mikhail Glushenkov2d0dc9a2008-05-30 06:22:15 +00001850 else
Mikhail Glushenkov08bd2e72008-05-30 06:12:24 +00001851 // This is a 'case' construct.
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001852 WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames));
Mikhail Glushenkov08bd2e72008-05-30 06:12:24 +00001853 }
1854}
1855
1856/// EmitHookDeclarations - Parse CmdLine fields of all the tool
1857/// property records and emit hook function declaration for each
1858/// instance of $CALL(HookName).
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001859void EmitHookDeclarations(const ToolDescriptions& ToolDescs, std::ostream& O) {
Mikhail Glushenkova298bb72009-01-21 13:04:00 +00001860 llvm::StringMap<unsigned> HookNames;
1861
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001862 FillInHookNames(ToolDescs, HookNames);
Mikhail Glushenkov08bd2e72008-05-30 06:12:24 +00001863 if (HookNames.empty())
1864 return;
Mikhail Glushenkov08bd2e72008-05-30 06:12:24 +00001865
1866 O << "namespace hooks {\n";
Mikhail Glushenkova298bb72009-01-21 13:04:00 +00001867 for (StringMap<unsigned>::const_iterator B = HookNames.begin(),
1868 E = HookNames.end(); B != E; ++B) {
1869 O << Indent1 << "const char* " << B->first() << "(";
Mikhail Glushenkov08bd2e72008-05-30 06:12:24 +00001870
Mikhail Glushenkova298bb72009-01-21 13:04:00 +00001871 for (unsigned i = 0, j = B->second; i < j; ++i) {
1872 O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
1873 }
1874
1875 O <<");\n";
1876 }
Mikhail Glushenkov08bd2e72008-05-30 06:12:24 +00001877 O << "}\n\n";
1878}
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00001879
Mikhail Glushenkovc82ce4a2008-09-22 20:49:34 +00001880/// EmitRegisterPlugin - Emit code to register this plugin.
Mikhail Glushenkov35fde152008-11-17 17:30:25 +00001881void EmitRegisterPlugin(int Priority, std::ostream& O) {
Mikhail Glushenkove1d44b52008-12-11 10:34:18 +00001882 O << "struct Plugin : public llvmc::BasePlugin {\n\n"
Mikhail Glushenkov35fde152008-11-17 17:30:25 +00001883 << Indent1 << "int Priority() const { return " << Priority << "; }\n\n"
Mikhail Glushenkovc82ce4a2008-09-22 20:49:34 +00001884 << Indent1 << "void PopulateLanguageMap(LanguageMap& langMap) const\n"
1885 << Indent1 << "{ PopulateLanguageMapLocal(langMap); }\n\n"
1886 << Indent1
1887 << "void PopulateCompilationGraph(CompilationGraph& graph) const\n"
1888 << Indent1 << "{ PopulateCompilationGraphLocal(graph); }\n"
1889 << "};\n\n"
1890
Mikhail Glushenkove1d44b52008-12-11 10:34:18 +00001891 << "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
Mikhail Glushenkovc82ce4a2008-09-22 20:49:34 +00001892}
1893
Mikhail Glushenkov67665722008-11-12 12:41:18 +00001894/// EmitIncludes - Emit necessary #include directives and some
1895/// additional declarations.
Mikhail Glushenkovc82ce4a2008-09-22 20:49:34 +00001896void EmitIncludes(std::ostream& O) {
Mikhail Glushenkov4a1a77c2008-09-22 20:50:40 +00001897 O << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
1898 << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
1899 << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
Mikhail Glushenkovc82ce4a2008-09-22 20:49:34 +00001900
1901 << "#include \"llvm/ADT/StringExtras.h\"\n"
1902 << "#include \"llvm/Support/CommandLine.h\"\n\n"
1903
1904 << "#include <cstdlib>\n"
1905 << "#include <stdexcept>\n\n"
1906
1907 << "using namespace llvm;\n"
1908 << "using namespace llvmc;\n\n"
1909
Mikhail Glushenkov67665722008-11-12 12:41:18 +00001910 << "extern cl::opt<std::string> OutputFilename;\n\n"
1911
1912 << "inline const char* checkCString(const char* s)\n"
1913 << "{ return s == NULL ? \"\" : s; }\n\n";
Mikhail Glushenkovc82ce4a2008-09-22 20:49:34 +00001914}
1915
Mikhail Glushenkovfa270772008-11-17 17:29:42 +00001916
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001917/// PluginData - Holds all information about a plugin.
1918struct PluginData {
1919 OptionDescriptions OptDescs;
1920 bool HasSink;
Mikhail Glushenkovb59dbad2008-12-07 16:42:47 +00001921 bool HasExterns;
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001922 ToolDescriptions ToolDescs;
1923 RecordVector Edges;
1924 int Priority;
Mikhail Glushenkovfa270772008-11-17 17:29:42 +00001925};
1926
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001927/// HasSink - Go through the list of tool descriptions and check if
Mikhail Glushenkovb59dbad2008-12-07 16:42:47 +00001928/// there are any with the 'sink' property set.
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001929bool HasSink(const ToolDescriptions& ToolDescs) {
1930 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1931 E = ToolDescs.end(); B != E; ++B)
1932 if ((*B)->isSink())
1933 return true;
Mikhail Glushenkovfa270772008-11-17 17:29:42 +00001934
Mikhail Glushenkovb59dbad2008-12-07 16:42:47 +00001935 return false;
1936}
1937
1938/// HasExterns - Go through the list of option descriptions and check
1939/// if there are any external options.
1940bool HasExterns(const OptionDescriptions& OptDescs) {
1941 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
1942 E = OptDescs.end(); B != E; ++B)
1943 if (B->second.isExtern())
1944 return true;
1945
1946 return false;
Mikhail Glushenkovfa270772008-11-17 17:29:42 +00001947}
1948
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001949/// CollectPluginData - Collect tool and option properties,
1950/// compilation graph edges and plugin priority from the parse tree.
1951void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
1952 // Collect option properties.
1953 const RecordVector& OptionLists =
1954 Records.getAllDerivedDefinitions("OptionList");
1955 CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
1956 Data.OptDescs);
1957
1958 // Collect tool properties.
1959 const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
1960 CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
1961 Data.HasSink = HasSink(Data.ToolDescs);
Mikhail Glushenkovb59dbad2008-12-07 16:42:47 +00001962 Data.HasExterns = HasExterns(Data.OptDescs);
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001963
1964 // Collect compilation graph edges.
1965 const RecordVector& CompilationGraphs =
1966 Records.getAllDerivedDefinitions("CompilationGraph");
1967 FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
1968 Data.Edges);
1969
1970 // Calculate the priority of this plugin.
1971 const RecordVector& Priorities =
1972 Records.getAllDerivedDefinitions("PluginPriority");
1973 Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
Mikhail Glushenkov35fde152008-11-17 17:30:25 +00001974}
1975
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001976/// CheckPluginData - Perform some sanity checks on the collected data.
1977void CheckPluginData(PluginData& Data) {
1978 // Filter out all tools not mentioned in the compilation graph.
1979 FilterNotInGraph(Data.Edges, Data.ToolDescs);
Mikhail Glushenkovad746be2008-11-28 00:13:47 +00001980
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001981 // Typecheck the compilation graph.
1982 TypecheckGraph(Data.Edges, Data.ToolDescs);
1983
1984 // Check that there are no options without side effects (specified
1985 // only in the OptionList).
1986 CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
1987
Mikhail Glushenkovad746be2008-11-28 00:13:47 +00001988}
1989
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001990void EmitPluginCode(const PluginData& Data, std::ostream& O) {
1991 // Emit file header.
1992 EmitIncludes(O);
1993
1994 // Emit global option registration code.
Mikhail Glushenkovb59dbad2008-12-07 16:42:47 +00001995 EmitOptionDefintions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00001996
1997 // Emit hook declarations.
1998 EmitHookDeclarations(Data.ToolDescs, O);
1999
Mikhail Glushenkove1d44b52008-12-11 10:34:18 +00002000 O << "namespace {\n\n";
2001
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00002002 // Emit PopulateLanguageMap() function
2003 // (a language map maps from file extensions to language names).
2004 EmitPopulateLanguageMap(Records, O);
2005
2006 // Emit Tool classes.
2007 for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
2008 E = Data.ToolDescs.end(); B!=E; ++B)
2009 EmitToolClassDefinition(*(*B), Data.OptDescs, O);
2010
2011 // Emit Edge# classes.
2012 EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
2013
2014 // Emit PopulateCompilationGraph() function.
2015 EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
2016
2017 // Emit code for plugin registration.
2018 EmitRegisterPlugin(Data.Priority, O);
2019
Mikhail Glushenkove1d44b52008-12-11 10:34:18 +00002020 O << "} // End anonymous namespace.\n";
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00002021 // EOF
2022}
2023
2024
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00002025// End of anonymous namespace
Mikhail Glushenkov895820d2008-05-06 18:12:03 +00002026}
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00002027
Mikhail Glushenkov4561ab52008-05-07 21:50:19 +00002028/// run - The back-end entry point.
Mikhail Glushenkov895820d2008-05-06 18:12:03 +00002029void LLVMCConfigurationEmitter::run (std::ostream &O) {
Mikhail Glushenkov4fb71ea2008-05-30 06:21:48 +00002030 try {
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00002031 PluginData Data;
Mikhail Glushenkov4561ab52008-05-07 21:50:19 +00002032
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00002033 CollectPluginData(Records, Data);
2034 CheckPluginData(Data);
2035
Mikhail Glushenkovbe9d9a12008-05-06 18:08:59 +00002036 EmitSourceFileHeader("LLVMC Configuration Library", O);
Mikhail Glushenkovf9152532008-12-07 16:41:11 +00002037 EmitPluginCode(Data, O);
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00002038
Mikhail Glushenkov4fb71ea2008-05-30 06:21:48 +00002039 } catch (std::exception& Error) {
2040 throw Error.what() + std::string(" - usually this means a syntax error.");
2041 }
Anton Korobeynikovac67b7e2008-03-23 08:57:20 +00002042}