blob: b16d841f1a36899d24715372a297572eca982859 [file] [log] [blame]
Mikhail Glushenkov2d3327f2008-05-30 06:20:54 +00001//===- LLVMCConfigurationEmitter.cpp - Generate LLVMC config ----*- C++ -*-===//
Anton Korobeynikove9ffb5b2008-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 Glushenkov34307a92008-05-06 18:08:59 +000010// This tablegen backend is responsible for emitting LLVMC configuration code.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000011//
12//===----------------------------------------------------------------------===//
13
Mikhail Glushenkov41405722008-05-06 18:09:29 +000014#include "LLVMCConfigurationEmitter.h"
Anton Korobeynikove9ffb5b2008-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 Glushenkov0e92d2f2008-05-30 06:18:16 +000021#include "llvm/ADT/StringSet.h"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000022#include "llvm/Support/Streams.h"
23
24#include <algorithm>
25#include <cassert>
26#include <functional>
Mikhail Glushenkovffe736e2008-05-30 06:21:48 +000027#include <stdexcept>
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000028#include <string>
29
30using namespace llvm;
31
Mikhail Glushenkovc1f738d2008-05-06 18:12:03 +000032namespace {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000033
34//===----------------------------------------------------------------------===//
35/// Typedefs
36
37typedef std::vector<Record*> RecordVector;
38typedef std::vector<std::string> StrVector;
39
40//===----------------------------------------------------------------------===//
41/// Constants
42
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +000043// Indentation strings.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000044const char * Indent1 = " ";
45const char * Indent2 = " ";
46const char * Indent3 = " ";
47const char * Indent4 = " ";
48
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +000049// Default help string.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000050const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
51
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +000052// Name for the "sink" option.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000053const char * SinkOptionName = "AutoGeneratedSinkOption";
54
55//===----------------------------------------------------------------------===//
56/// Helper functions
57
Mikhail Glushenkov35576b02008-05-30 06:10:19 +000058int InitPtrToInt(const Init* ptr) {
59 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +000060 return val.getValue();
61}
62
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +000063const std::string& InitPtrToString(const Init* ptr) {
64 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
65 return val.getValue();
66}
67
68const ListInit& InitPtrToList(const Init* ptr) {
69 const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
70 return val;
71}
72
73const DagInit& InitPtrToDag(const Init* ptr) {
Mikhail Glushenkov35576b02008-05-30 06:10:19 +000074 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +000075 return val;
76}
77
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +000078// checkNumberOfArguments - Ensure that the number of args in d is
Mikhail Glushenkovdedba642008-05-30 06:08:50 +000079// less than or equal to min_arguments, otherwise throw an exception.
Mikhail Glushenkova5922cc2008-05-06 17:22:03 +000080void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
81 if (d->getNumArgs() < min_arguments)
82 throw "Property " + d->getOperator()->getAsString()
83 + " has too few arguments!";
84}
85
Mikhail Glushenkovdedba642008-05-30 06:08:50 +000086// isDagEmpty - is this DAG marked with an empty marker?
87bool isDagEmpty (const DagInit* d) {
88 return d->getOperator()->getAsString() == "empty";
89}
Mikhail Glushenkova5922cc2008-05-06 17:22:03 +000090
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000091//===----------------------------------------------------------------------===//
92/// Back-end specific code
93
94// A command-line option can have one of the following types:
95//
Mikhail Glushenkovb623c322008-05-30 06:22:52 +000096// Alias - an alias for another option.
97//
98// Switch - a simple switch without arguments, e.g. -O2
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000099//
100// Parameter - an option that takes one(and only one) argument, e.g. -o file,
101// --output=file
102//
103// ParameterList - same as Parameter, but more than one occurence
104// of the option is allowed, e.g. -lm -lpthread
105//
106// Prefix - argument is everything after the prefix,
107// e.g. -Wa,-foo,-bar, -DNAME=VALUE
108//
109// PrefixList - same as Prefix, but more than one option occurence is
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000110// allowed.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000111
112namespace OptionType {
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000113 enum OptionType { Alias, Switch,
114 Parameter, ParameterList, Prefix, PrefixList};
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000115}
116
117bool IsListOptionType (OptionType::OptionType t) {
118 return (t == OptionType::ParameterList || t == OptionType::PrefixList);
119}
120
121// Code duplication here is necessary because one option can affect
122// several tools and those tools may have different actions associated
123// with this option. GlobalOptionDescriptions are used to generate
124// the option registration code, while ToolOptionDescriptions are used
125// to generate tool-specific code.
126
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000127/// OptionDescription - Base class for option descriptions.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000128struct OptionDescription {
129 OptionType::OptionType Type;
130 std::string Name;
131
132 OptionDescription(OptionType::OptionType t = OptionType::Switch,
133 const std::string& n = "")
134 : Type(t), Name(n)
135 {}
136
137 const char* GenTypeDeclaration() const {
138 switch (Type) {
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000139 case OptionType::Alias:
140 return "cl::alias";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000141 case OptionType::PrefixList:
142 case OptionType::ParameterList:
143 return "cl::list<std::string>";
144 case OptionType::Switch:
145 return "cl::opt<bool>";
146 case OptionType::Parameter:
147 case OptionType::Prefix:
148 default:
149 return "cl::opt<std::string>";
150 }
151 }
152
Mikhail Glushenkov4019e952008-05-12 16:33:06 +0000153 // Escape commas and other symbols not allowed in the C++ variable
154 // names. Makes it possible to use options with names like "Wa,"
155 // (useful for prefix options).
156 std::string EscapeVariableName(const std::string& Var) const {
157 std::string ret;
158 for (unsigned i = 0; i != Var.size(); ++i) {
159 if (Var[i] == ',') {
160 ret += "_comma_";
161 }
162 else {
163 ret.push_back(Var[i]);
164 }
165 }
166 return ret;
167 }
168
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000169 std::string GenVariableName() const {
Mikhail Glushenkov4019e952008-05-12 16:33:06 +0000170 const std::string& EscapedName = EscapeVariableName(Name);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000171 switch (Type) {
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000172 case OptionType::Alias:
173 return "AutoGeneratedAlias" + EscapedName;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000174 case OptionType::Switch:
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000175 return "AutoGeneratedSwitch" + EscapedName;
176 case OptionType::Prefix:
177 return "AutoGeneratedPrefix" + EscapedName;
178 case OptionType::PrefixList:
179 return "AutoGeneratedPrefixList" + EscapedName;
180 case OptionType::Parameter:
181 return "AutoGeneratedParameter" + EscapedName;
182 case OptionType::ParameterList:
183 default:
184 return "AutoGeneratedParameterList" + EscapedName;
185 }
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000186 }
187
188};
189
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000190// Global option description.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000191
192namespace GlobalOptionDescriptionFlags {
193 enum GlobalOptionDescriptionFlags { Required = 0x1 };
194}
195
196struct GlobalOptionDescription : public OptionDescription {
197 std::string Help;
198 unsigned Flags;
199
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000200 // We need to provide a default constructor because
201 // StringMap can only store DefaultConstructible objects.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000202 GlobalOptionDescription() : OptionDescription(), Flags(0)
203 {}
204
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000205 GlobalOptionDescription (OptionType::OptionType t, const std::string& n,
206 const std::string& h = DefaultHelpString)
207 : OptionDescription(t, n), Help(h), Flags(0)
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000208 {}
209
210 bool isRequired() const {
211 return Flags & GlobalOptionDescriptionFlags::Required;
212 }
213 void setRequired() {
214 Flags |= GlobalOptionDescriptionFlags::Required;
215 }
216
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000217 /// Merge - Merge two option descriptions.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000218 void Merge (const GlobalOptionDescription& other)
219 {
220 if (other.Type != Type)
221 throw "Conflicting definitions for the option " + Name + "!";
222
Mikhail Glushenkov434816d2008-05-06 18:13:00 +0000223 if (Help == DefaultHelpString)
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000224 Help = other.Help;
Mikhail Glushenkov434816d2008-05-06 18:13:00 +0000225 else if (other.Help != DefaultHelpString) {
226 llvm::cerr << "Warning: more than one help string defined for option "
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000227 + Name + "\n";
Mikhail Glushenkov434816d2008-05-06 18:13:00 +0000228 }
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000229
230 Flags |= other.Flags;
231 }
232};
233
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000234/// GlobalOptionDescriptions - A GlobalOptionDescription array
235/// together with some flags affecting generation of option
236/// declarations.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000237struct GlobalOptionDescriptions {
238 typedef StringMap<GlobalOptionDescription> container_type;
239 typedef container_type::const_iterator const_iterator;
240
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000241 /// Descriptions - A list of GlobalOptionDescriptions.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000242 container_type Descriptions;
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000243 /// HasSink - Should the emitter generate a "cl::sink" option?
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000244 bool HasSink;
245
Mikhail Glushenkova5922cc2008-05-06 17:22:03 +0000246 const GlobalOptionDescription& FindOption(const std::string& OptName) const {
247 const_iterator I = Descriptions.find(OptName);
248 if (I != Descriptions.end())
249 return I->second;
250 else
251 throw OptName + ": no such option!";
252 }
253
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000254 // Insert new GlobalOptionDescription into GlobalOptionDescriptions list
255 void insertDescription (const GlobalOptionDescription& o)
256 {
257 container_type::iterator I = Descriptions.find(o.Name);
258 if (I != Descriptions.end()) {
259 GlobalOptionDescription& D = I->second;
260 D.Merge(o);
261 }
262 else {
263 Descriptions[o.Name] = o;
264 }
265 }
266
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000267 // Support for STL-style iteration
268 const_iterator begin() const { return Descriptions.begin(); }
269 const_iterator end() const { return Descriptions.end(); }
270};
271
272
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000273// Tool-local option description.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000274
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000275// Properties without arguments are implemented as flags.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000276namespace ToolOptionDescriptionFlags {
277 enum ToolOptionDescriptionFlags { StopCompilation = 0x1,
278 Forward = 0x2, UnpackValues = 0x4};
279}
280namespace OptionPropertyType {
Mikhail Glushenkovabab33b2008-05-30 06:13:02 +0000281 enum OptionPropertyType { AppendCmd, OutputSuffix };
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000282}
283
284typedef std::pair<OptionPropertyType::OptionPropertyType, std::string>
285OptionProperty;
286typedef SmallVector<OptionProperty, 4> OptionPropertyList;
287
288struct ToolOptionDescription : public OptionDescription {
289 unsigned Flags;
290 OptionPropertyList Props;
291
292 // StringMap can only store DefaultConstructible objects
Mikhail Glushenkov18cbe892008-03-27 09:53:47 +0000293 ToolOptionDescription() : OptionDescription(), Flags(0) {}
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000294
295 ToolOptionDescription (OptionType::OptionType t, const std::string& n)
296 : OptionDescription(t, n)
297 {}
298
299 // Various boolean properties
300 bool isStopCompilation() const {
301 return Flags & ToolOptionDescriptionFlags::StopCompilation;
302 }
303 void setStopCompilation() {
304 Flags |= ToolOptionDescriptionFlags::StopCompilation;
305 }
306
307 bool isForward() const {
308 return Flags & ToolOptionDescriptionFlags::Forward;
309 }
310 void setForward() {
311 Flags |= ToolOptionDescriptionFlags::Forward;
312 }
313
314 bool isUnpackValues() const {
315 return Flags & ToolOptionDescriptionFlags::UnpackValues;
316 }
317 void setUnpackValues() {
318 Flags |= ToolOptionDescriptionFlags::UnpackValues;
319 }
320
321 void AddProperty (OptionPropertyType::OptionPropertyType t,
322 const std::string& val)
323 {
324 Props.push_back(std::make_pair(t, val));
325 }
326};
327
328typedef StringMap<ToolOptionDescription> ToolOptionDescriptions;
329
330// Tool information record
331
332namespace ToolFlags {
333 enum ToolFlags { Join = 0x1, Sink = 0x2 };
334}
335
336struct ToolProperties : public RefCountedBase<ToolProperties> {
337 std::string Name;
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000338 Init* CmdLine;
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +0000339 StrVector InLanguage;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000340 std::string OutLanguage;
341 std::string OutputSuffix;
342 unsigned Flags;
343 ToolOptionDescriptions OptDescs;
344
345 // Various boolean properties
346 void setSink() { Flags |= ToolFlags::Sink; }
347 bool isSink() const { return Flags & ToolFlags::Sink; }
348 void setJoin() { Flags |= ToolFlags::Join; }
349 bool isJoin() const { return Flags & ToolFlags::Join; }
350
351 // Default ctor here is needed because StringMap can only store
352 // DefaultConstructible objects
Mikhail Glushenkov434816d2008-05-06 18:13:00 +0000353 ToolProperties() : Flags(0) {}
354 ToolProperties (const std::string& n) : Name(n), Flags(0) {}
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000355};
356
357
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000358/// ToolPropertiesList - A list of Tool information records
359/// IntrusiveRefCntPtrs are used here because StringMap has no copy
360/// constructor (and we want to avoid copying ToolProperties anyway).
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000361typedef std::vector<IntrusiveRefCntPtr<ToolProperties> > ToolPropertiesList;
362
363
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000364/// CollectOptionProperties - Function object for iterating over a
365/// list (usually, a DAG) of option property records.
366class CollectOptionProperties {
367private:
368 // Implementation details.
369
370 /// OptionPropertyHandler - a function that extracts information
371 /// about a given option property from its DAG representation.
372 typedef void (CollectOptionProperties::* OptionPropertyHandler)
373 (const DagInit*);
374
375 /// OptionPropertyHandlerMap - A map from option property names to
376 /// option property handlers
377 typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
378
379 static OptionPropertyHandlerMap optionPropertyHandlers_;
380 static bool staticMembersInitialized_;
381
382 /// This is where the information is stored
383
384 /// toolProps_ - Properties of the current Tool.
385 ToolProperties* toolProps_;
386 /// optDescs_ - OptionDescriptions table (used to register options
387 /// globally).
388 GlobalOptionDescription& optDesc_;
389
390public:
391
392 explicit CollectOptionProperties(ToolProperties* TP,
393 GlobalOptionDescription& OD)
394 : toolProps_(TP), optDesc_(OD)
395 {
396 if (!staticMembersInitialized_) {
397 optionPropertyHandlers_["append_cmd"] =
398 &CollectOptionProperties::onAppendCmd;
399 optionPropertyHandlers_["forward"] =
400 &CollectOptionProperties::onForward;
401 optionPropertyHandlers_["help"] =
402 &CollectOptionProperties::onHelp;
403 optionPropertyHandlers_["output_suffix"] =
404 &CollectOptionProperties::onOutputSuffix;
405 optionPropertyHandlers_["required"] =
406 &CollectOptionProperties::onRequired;
407 optionPropertyHandlers_["stop_compilation"] =
408 &CollectOptionProperties::onStopCompilation;
409 optionPropertyHandlers_["unpack_values"] =
410 &CollectOptionProperties::onUnpackValues;
411
412 staticMembersInitialized_ = true;
413 }
414 }
415
416 /// operator() - Gets called for every option property; Just forwards
417 /// to the corresponding property handler.
418 void operator() (Init* i) {
419 const DagInit& option_property = InitPtrToDag(i);
420 const std::string& option_property_name
421 = option_property.getOperator()->getAsString();
422 OptionPropertyHandlerMap::iterator method
423 = optionPropertyHandlers_.find(option_property_name);
424
425 if (method != optionPropertyHandlers_.end()) {
426 OptionPropertyHandler h = method->second;
427 (this->*h)(&option_property);
428 }
429 else {
430 throw "Unknown option property: " + option_property_name + "!";
431 }
432 }
433
434private:
435
436 /// Option property handlers --
437 /// Methods that handle properties that are common for all types of
438 /// options (like append_cmd, stop_compilation)
439
440 void onAppendCmd (const DagInit* d) {
441 checkNumberOfArguments(d, 1);
442 checkToolProps(d);
443 const std::string& cmd = InitPtrToString(d->getArg(0));
444
445 toolProps_->OptDescs[optDesc_.Name].
446 AddProperty(OptionPropertyType::AppendCmd, cmd);
447 }
448
449 void onOutputSuffix (const DagInit* d) {
450 checkNumberOfArguments(d, 1);
451 checkToolProps(d);
452 const std::string& suf = InitPtrToString(d->getArg(0));
453
454 if (toolProps_->OptDescs[optDesc_.Name].Type != OptionType::Switch)
455 throw "Option " + optDesc_.Name
456 + " can't have 'output_suffix' property since it isn't a switch!";
457
458 toolProps_->OptDescs[optDesc_.Name].AddProperty
459 (OptionPropertyType::OutputSuffix, suf);
460 }
461
462 void onForward (const DagInit* d) {
463 checkNumberOfArguments(d, 0);
464 checkToolProps(d);
465 toolProps_->OptDescs[optDesc_.Name].setForward();
466 }
467
468 void onHelp (const DagInit* d) {
469 checkNumberOfArguments(d, 1);
470 const std::string& help_message = InitPtrToString(d->getArg(0));
471
472 optDesc_.Help = help_message;
473 }
474
475 void onRequired (const DagInit* d) {
476 checkNumberOfArguments(d, 0);
477 checkToolProps(d);
478 optDesc_.setRequired();
479 }
480
481 void onStopCompilation (const DagInit* d) {
482 checkNumberOfArguments(d, 0);
483 checkToolProps(d);
484 if (optDesc_.Type != OptionType::Switch)
485 throw std::string("Only options of type Switch can stop compilation!");
486 toolProps_->OptDescs[optDesc_.Name].setStopCompilation();
487 }
488
489 void onUnpackValues (const DagInit* d) {
490 checkNumberOfArguments(d, 0);
491 checkToolProps(d);
492 toolProps_->OptDescs[optDesc_.Name].setUnpackValues();
493 }
494
495 // Helper functions
496
497 /// checkToolProps - Throw an error if toolProps_ == 0.
498 void checkToolProps(const DagInit* d) {
499 if (!d)
500 throw "Option property " + d->getOperator()->getAsString()
501 + " can't be used in this context";
502 }
503
504};
505
506CollectOptionProperties::OptionPropertyHandlerMap
507CollectOptionProperties::optionPropertyHandlers_;
508
509bool CollectOptionProperties::staticMembersInitialized_ = false;
510
511
512/// processOptionProperties - Go through the list of option
513/// properties and call a corresponding handler for each.
514void processOptionProperties (const DagInit* d, ToolProperties* t,
515 GlobalOptionDescription& o) {
516 checkNumberOfArguments(d, 2);
517 DagInit::const_arg_iterator B = d->arg_begin();
518 // Skip the first argument: it's always the option name.
519 ++B;
520 std::for_each(B, d->arg_end(), CollectOptionProperties(t, o));
521}
522
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000523/// CollectProperties - Function object for iterating over a list of
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000524/// tool property records.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000525class CollectProperties {
526private:
527
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000528 // Implementation details
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000529
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000530 /// PropertyHandler - a function that extracts information
531 /// about a given tool property from its DAG representation
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000532 typedef void (CollectProperties::*PropertyHandler)(const DagInit*);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000533
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000534 /// PropertyHandlerMap - A map from property names to property
535 /// handlers.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000536 typedef StringMap<PropertyHandler> PropertyHandlerMap;
537
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000538 // Static maps from strings to CollectProperties methods("handlers")
539 static PropertyHandlerMap propertyHandlers_;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000540 static bool staticMembersInitialized_;
541
542
543 /// This is where the information is stored
544
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000545 /// toolProps_ - Properties of the current Tool.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000546 ToolProperties& toolProps_;
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000547 /// optDescs_ - OptionDescriptions table (used to register options
548 /// globally).
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000549 GlobalOptionDescriptions& optDescs_;
550
551public:
552
553 explicit CollectProperties (ToolProperties& p, GlobalOptionDescriptions& d)
554 : toolProps_(p), optDescs_(d)
555 {
556 if (!staticMembersInitialized_) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000557 propertyHandlers_["cmd_line"] = &CollectProperties::onCmdLine;
558 propertyHandlers_["in_language"] = &CollectProperties::onInLanguage;
559 propertyHandlers_["join"] = &CollectProperties::onJoin;
560 propertyHandlers_["out_language"] = &CollectProperties::onOutLanguage;
561 propertyHandlers_["output_suffix"] = &CollectProperties::onOutputSuffix;
562 propertyHandlers_["parameter_option"]
563 = &CollectProperties::onParameter;
564 propertyHandlers_["parameter_list_option"] =
565 &CollectProperties::onParameterList;
566 propertyHandlers_["prefix_option"] = &CollectProperties::onPrefix;
567 propertyHandlers_["prefix_list_option"] =
568 &CollectProperties::onPrefixList;
569 propertyHandlers_["sink"] = &CollectProperties::onSink;
570 propertyHandlers_["switch_option"] = &CollectProperties::onSwitch;
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000571 propertyHandlers_["alias_option"] = &CollectProperties::onAlias;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000572
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000573 staticMembersInitialized_ = true;
574 }
575 }
576
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000577 /// operator() - Gets called for every tool property; Just forwards
578 /// to the corresponding property handler.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000579 void operator() (Init* i) {
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +0000580 const DagInit& d = InitPtrToDag(i);
Mikhail Glushenkova5922cc2008-05-06 17:22:03 +0000581 const std::string& property_name = d.getOperator()->getAsString();
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000582 PropertyHandlerMap::iterator method
583 = propertyHandlers_.find(property_name);
584
585 if (method != propertyHandlers_.end()) {
586 PropertyHandler h = method->second;
587 (this->*h)(&d);
588 }
589 else {
590 throw "Unknown tool property: " + property_name + "!";
591 }
592 }
593
594private:
595
596 /// Property handlers --
597 /// Functions that extract information about tool properties from
598 /// DAG representation.
599
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000600 void onCmdLine (const DagInit* d) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000601 checkNumberOfArguments(d, 1);
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000602 toolProps_.CmdLine = d->getArg(0);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000603 }
604
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000605 void onInLanguage (const DagInit* d) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000606 checkNumberOfArguments(d, 1);
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +0000607 Init* arg = d->getArg(0);
608
609 // Find out the argument's type.
610 if (typeid(*arg) == typeid(StringInit)) {
611 // It's a string.
612 toolProps_.InLanguage.push_back(InitPtrToString(arg));
613 }
614 else {
615 // It's a list.
616 const ListInit& lst = InitPtrToList(arg);
617 StrVector& out = toolProps_.InLanguage;
618
619 // Copy strings to the output vector.
620 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
621 B != E; ++B) {
622 out.push_back(InitPtrToString(*B));
623 }
624
625 // Remove duplicates.
626 std::sort(out.begin(), out.end());
627 StrVector::iterator newE = std::unique(out.begin(), out.end());
628 out.erase(newE, out.end());
629 }
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000630 }
631
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000632 void onJoin (const DagInit* d) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000633 checkNumberOfArguments(d, 0);
634 toolProps_.setJoin();
635 }
636
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000637 void onOutLanguage (const DagInit* d) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000638 checkNumberOfArguments(d, 1);
639 toolProps_.OutLanguage = InitPtrToString(d->getArg(0));
640 }
641
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000642 void onOutputSuffix (const DagInit* d) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000643 checkNumberOfArguments(d, 1);
644 toolProps_.OutputSuffix = InitPtrToString(d->getArg(0));
645 }
646
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000647 void onSink (const DagInit* d) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000648 checkNumberOfArguments(d, 0);
649 optDescs_.HasSink = true;
650 toolProps_.setSink();
651 }
652
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000653 void onAlias (const DagInit* d) {
654 checkNumberOfArguments(d, 2);
655 // We just need a GlobalOptionDescription for the aliases.
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000656 optDescs_.insertDescription
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000657 (GlobalOptionDescription(OptionType::Alias,
658 InitPtrToString(d->getArg(0)),
659 InitPtrToString(d->getArg(1))));
660 }
661
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000662 void onSwitch (const DagInit* d) {
663 addOption(d, OptionType::Switch);
664 }
665
666 void onParameter (const DagInit* d) {
667 addOption(d, OptionType::Parameter);
668 }
669
670 void onParameterList (const DagInit* d) {
671 addOption(d, OptionType::ParameterList);
672 }
673
674 void onPrefix (const DagInit* d) {
675 addOption(d, OptionType::Prefix);
676 }
677
678 void onPrefixList (const DagInit* d) {
679 addOption(d, OptionType::PrefixList);
680 }
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000681
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000682 /// Helper functions
683
684 // Add an option of type t
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000685 void addOption (const DagInit* d, OptionType::OptionType t) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000686 checkNumberOfArguments(d, 2);
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000687 const std::string& Name = InitPtrToString(d->getArg(0));
688 GlobalOptionDescription OD(t, Name);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000689
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000690 toolProps_.OptDescs[Name].Type = t;
691 toolProps_.OptDescs[Name].Name = Name;
692 processOptionProperties(d, &toolProps_, OD);
693 optDescs_.insertDescription(OD);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000694 }
695
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000696};
697
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000698// Defintions of static members of CollectProperties.
699CollectProperties::PropertyHandlerMap CollectProperties::propertyHandlers_;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000700bool CollectProperties::staticMembersInitialized_ = false;
701
702
Mikhail Glushenkovd638e852008-05-30 06:26:08 +0000703/// CollectToolProperties - Gather information about tool properties
704/// from the parsed TableGen data (basically a wrapper for the
705/// CollectProperties function object).
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000706void CollectToolProperties (RecordVector::const_iterator B,
707 RecordVector::const_iterator E,
708 ToolPropertiesList& TPList,
709 GlobalOptionDescriptions& OptDescs)
710{
711 // Iterate over a properties list of every Tool definition
712 for (;B!=E;++B) {
Mikhail Glushenkovd638e852008-05-30 06:26:08 +0000713 Record* T = *B;
714 // Throws an exception if the value does not exist.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000715 ListInit* PropList = T->getValueAsListInit("properties");
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000716
717 IntrusiveRefCntPtr<ToolProperties>
718 ToolProps(new ToolProperties(T->getName()));
719
720 std::for_each(PropList->begin(), PropList->end(),
721 CollectProperties(*ToolProps, OptDescs));
722 TPList.push_back(ToolProps);
723 }
724}
725
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000726/// AddOption - A helper function object used by
727/// CollectPropertiesFromOptionList.
728// TOFIX: this largely duplicates CollectProperties::addOption, find a
729// way to merge them.
730class AddOption {
731private:
732 GlobalOptionDescriptions& OptDescs_;
733
734public:
735 explicit AddOption(GlobalOptionDescriptions& OD) : OptDescs_(OD)
736 {}
737
738 void operator()(Init* i) {
739 const DagInit& d = InitPtrToDag(i);
740 checkNumberOfArguments(&d, 2);
741 const std::string& Type = d.getOperator()->getAsString();
742 const std::string& Name = InitPtrToString(d.getArg(0));
743 GlobalOptionDescription OD(AddOption::getType(Type), Name);
744 if (OD.Type != OptionType::Alias)
745 processOptionProperties(&d, 0, OD);
746 OptDescs_.insertDescription(OD);
747 }
748
749 OptionType::OptionType getType(const std::string& T) const {
750 if (T == "alias_option")
751 return OptionType::Alias;
752 else if (T == "switch_option")
753 return OptionType::Switch;
754 else if (T == "parameter_option")
755 return OptionType::Parameter;
756 else if (T == "parameter_list_option")
757 return OptionType::ParameterList;
758 else if (T == "prefix_option")
759 return OptionType::Prefix;
760 else if (T == "prefix_list_option")
761 return OptionType::PrefixList;
762 else
763 throw "Unknown option type: " + T + '!';
764 }
765};
766
767/// CollectPropertiesFromOptionList - Gather information about
Mikhail Glushenkovd638e852008-05-30 06:26:08 +0000768/// *global* option properties from the OptionList.
Mikhail Glushenkovd638e852008-05-30 06:26:08 +0000769void CollectPropertiesFromOptionList (RecordVector::const_iterator B,
770 RecordVector::const_iterator E,
771 GlobalOptionDescriptions& OptDescs)
772{
773 // Iterate over a properties list of every Tool definition
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000774
Mikhail Glushenkovd638e852008-05-30 06:26:08 +0000775 for (;B!=E;++B) {
776 RecordVector::value_type T = *B;
777 // Throws an exception if the value does not exist.
778 ListInit* PropList = T->getValueAsListInit("options");
779
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000780 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
Mikhail Glushenkovd638e852008-05-30 06:26:08 +0000781 }
782}
783
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000784/// EmitCaseTest1Arg - Helper function used by
785/// EmitCaseConstructHandler.
786bool EmitCaseTest1Arg(const std::string& TestName,
787 const DagInit& d,
788 const GlobalOptionDescriptions& OptDescs,
789 std::ostream& O) {
790 checkNumberOfArguments(&d, 1);
791 const std::string& OptName = InitPtrToString(d.getArg(0));
792 if (TestName == "switch_on") {
793 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
794 if (OptDesc.Type != OptionType::Switch)
795 throw OptName + ": incorrect option type!";
796 O << OptDesc.GenVariableName();
797 return true;
798 } else if (TestName == "input_languages_contain") {
799 O << "InLangs.count(\"" << OptName << "\") != 0";
800 return true;
Mikhail Glushenkov242d0e62008-05-30 06:19:52 +0000801 } else if (TestName == "in_language") {
802 // Works only for cmd_line!
803 O << "GetLanguage(inFile) == \"" << OptName << '\"';
804 return true;
805 } else if (TestName == "not_empty") {
Mikhail Glushenkovb4833872008-05-30 06:24:07 +0000806 if (OptName == "o") {
807 O << "!OutputFilename.empty()";
808 return true;
809 }
810 else {
811 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
812 if (OptDesc.Type == OptionType::Switch)
813 throw OptName + ": incorrect option type!";
814 O << '!' << OptDesc.GenVariableName() << ".empty()";
815 return true;
816 }
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000817 }
818
819 return false;
820}
821
822/// EmitCaseTest2Args - Helper function used by
823/// EmitCaseConstructHandler.
824bool EmitCaseTest2Args(const std::string& TestName,
825 const DagInit& d,
826 const char* IndentLevel,
827 const GlobalOptionDescriptions& OptDescs,
828 std::ostream& O) {
829 checkNumberOfArguments(&d, 2);
830 const std::string& OptName = InitPtrToString(d.getArg(0));
831 const std::string& OptArg = InitPtrToString(d.getArg(1));
832 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
833
834 if (TestName == "parameter_equals") {
835 if (OptDesc.Type != OptionType::Parameter
836 && OptDesc.Type != OptionType::Prefix)
837 throw OptName + ": incorrect option type!";
838 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
839 return true;
840 }
841 else if (TestName == "element_in_list") {
842 if (OptDesc.Type != OptionType::ParameterList
843 && OptDesc.Type != OptionType::PrefixList)
844 throw OptName + ": incorrect option type!";
845 const std::string& VarName = OptDesc.GenVariableName();
846 O << "std::find(" << VarName << ".begin(),\n"
847 << IndentLevel << Indent1 << VarName << ".end(), \""
848 << OptArg << "\") != " << VarName << ".end()";
849 return true;
850 }
851
852 return false;
853}
854
855// Forward declaration.
856// EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
857void EmitCaseTest(const DagInit& d, const char* IndentLevel,
858 const GlobalOptionDescriptions& OptDescs,
859 std::ostream& O);
860
861/// EmitLogicalOperationTest - Helper function used by
862/// EmitCaseConstructHandler.
863void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
864 const char* IndentLevel,
865 const GlobalOptionDescriptions& OptDescs,
866 std::ostream& O) {
867 O << '(';
868 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +0000869 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000870 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
871 if (j != NumArgs - 1)
872 O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
873 else
874 O << ')';
875 }
876}
877
878/// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
879void EmitCaseTest(const DagInit& d, const char* IndentLevel,
880 const GlobalOptionDescriptions& OptDescs,
881 std::ostream& O) {
882 const std::string& TestName = d.getOperator()->getAsString();
883
884 if (TestName == "and")
885 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
886 else if (TestName == "or")
887 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
888 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
889 return;
890 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
891 return;
892 else
893 throw TestName + ": unknown edge property!";
894}
895
896// Emit code that handles the 'case' construct.
897// Takes a function object that should emit code for every case clause.
898// Callback's type is
899// void F(Init* Statement, const char* IndentLevel, std::ostream& O).
900template <typename F>
901void EmitCaseConstructHandler(const DagInit* d, const char* IndentLevel,
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +0000902 const F& Callback, bool EmitElseIf,
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000903 const GlobalOptionDescriptions& OptDescs,
904 std::ostream& O) {
905 assert(d->getOperator()->getAsString() == "case");
906
Mikhail Glushenkov31681512008-05-30 06:15:47 +0000907 unsigned numArgs = d->getNumArgs();
908 if (d->getNumArgs() < 2)
909 throw "There should be at least one clause in the 'case' expression:\n"
910 + d->getAsString();
911
912 for (unsigned i = 0; i != numArgs; ++i) {
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +0000913 const DagInit& Test = InitPtrToDag(d->getArg(i));
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000914
Mikhail Glushenkov31681512008-05-30 06:15:47 +0000915 // Emit the test.
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000916 if (Test.getOperator()->getAsString() == "default") {
917 if (i+2 != numArgs)
918 throw std::string("The 'default' clause should be the last in the"
919 "'case' construct!");
920 O << IndentLevel << "else {\n";
921 }
922 else {
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +0000923 O << IndentLevel << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000924 EmitCaseTest(Test, IndentLevel, OptDescs, O);
925 O << ") {\n";
926 }
927
Mikhail Glushenkov31681512008-05-30 06:15:47 +0000928 // Emit the corresponding statement.
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000929 ++i;
930 if (i == numArgs)
931 throw "Case construct handler: no corresponding action "
932 "found for the test " + Test.getAsString() + '!';
933
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +0000934 Init* arg = d->getArg(i);
935 if (dynamic_cast<DagInit*>(arg)
936 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case") {
937 EmitCaseConstructHandler(static_cast<DagInit*>(arg),
938 (std::string(IndentLevel) + Indent1).c_str(),
939 Callback, EmitElseIf, OptDescs, O);
940 }
941 else {
942 Callback(arg, IndentLevel, O);
943 }
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000944 O << IndentLevel << "}\n";
945 }
946}
947
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000948/// EmitForwardOptionPropertyHandlingCode - Helper function used to
949/// implement EmitOptionPropertyHandlingCode(). Emits code for
950/// handling the (forward) option property.
951void EmitForwardOptionPropertyHandlingCode (const ToolOptionDescription& D,
952 std::ostream& O) {
953 switch (D.Type) {
954 case OptionType::Switch:
955 O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
956 break;
957 case OptionType::Parameter:
958 O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
959 O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
960 break;
961 case OptionType::Prefix:
962 O << Indent3 << "vec.push_back(\"-" << D.Name << "\" + "
963 << D.GenVariableName() << ");\n";
964 break;
965 case OptionType::PrefixList:
966 O << Indent3 << "for (" << D.GenTypeDeclaration()
967 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
968 << Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
969 << Indent4 << "vec.push_back(\"-" << D.Name << "\" + "
970 << "*B);\n";
971 break;
972 case OptionType::ParameterList:
973 O << Indent3 << "for (" << D.GenTypeDeclaration()
974 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
975 << Indent3 << "E = " << D.GenVariableName()
976 << ".end() ; B != E; ++B) {\n"
977 << Indent4 << "vec.push_back(\"-" << D.Name << "\");\n"
978 << Indent4 << "vec.push_back(*B);\n"
979 << Indent3 << "}\n";
980 break;
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000981 case OptionType::Alias:
982 default:
983 throw std::string("Aliases are not allowed in tool option descriptions!");
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000984 }
985}
986
Mikhail Glushenkovea6ce492008-05-30 06:15:20 +0000987// ToolOptionHasInterestingProperties - A helper function used by
988// EmitOptionPropertyHandlingCode() that tells us whether we should
989// emit any property handling code at all.
Mikhail Glushenkov31f52152008-05-30 06:10:47 +0000990bool ToolOptionHasInterestingProperties(const ToolOptionDescription& D) {
Mikhail Glushenkovea6ce492008-05-30 06:15:20 +0000991 bool ret = false;
992 for (OptionPropertyList::const_iterator B = D.Props.begin(),
993 E = D.Props.end(); B != E; ++B) {
994 const OptionProperty& OptProp = *B;
995 if (OptProp.first == OptionPropertyType::AppendCmd)
996 ret = true;
997 }
998 if (D.isForward() || D.isUnpackValues())
999 ret = true;
1000 return ret;
Mikhail Glushenkov31f52152008-05-30 06:10:47 +00001001}
1002
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001003/// EmitOptionPropertyHandlingCode - Helper function used by
1004/// EmitGenerateActionMethod(). Emits code that handles option
1005/// properties.
Mikhail Glushenkov31f52152008-05-30 06:10:47 +00001006void EmitOptionPropertyHandlingCode (const ToolOptionDescription& D,
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001007 std::ostream& O)
1008{
Mikhail Glushenkov31f52152008-05-30 06:10:47 +00001009 if (!ToolOptionHasInterestingProperties(D))
1010 return;
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001011 // Start of the if-clause.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001012 O << Indent2 << "if (";
1013 if (D.Type == OptionType::Switch)
1014 O << D.GenVariableName();
1015 else
1016 O << '!' << D.GenVariableName() << ".empty()";
1017
1018 O <<") {\n";
1019
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001020 // Handle option properties that take an argument.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001021 for (OptionPropertyList::const_iterator B = D.Props.begin(),
1022 E = D.Props.end(); B!=E; ++B) {
1023 const OptionProperty& val = *B;
1024
1025 switch (val.first) {
1026 // (append_cmd cmd) property
1027 case OptionPropertyType::AppendCmd:
1028 O << Indent3 << "vec.push_back(\"" << val.second << "\");\n";
1029 break;
1030 // Other properties with argument
1031 default:
1032 break;
1033 }
1034 }
1035
1036 // Handle flags
1037
1038 // (forward) property
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001039 if (D.isForward())
1040 EmitForwardOptionPropertyHandlingCode(D, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001041
1042 // (unpack_values) property
1043 if (D.isUnpackValues()) {
1044 if (IsListOptionType(D.Type)) {
1045 O << Indent3 << "for (" << D.GenTypeDeclaration()
1046 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1047 << Indent3 << "E = " << D.GenVariableName()
1048 << ".end(); B != E; ++B)\n"
Mikhail Glushenkov028f18e2008-05-06 18:13:45 +00001049 << Indent4 << "llvm::SplitString(*B, vec, \",\");\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001050 }
1051 else if (D.Type == OptionType::Prefix || D.Type == OptionType::Parameter){
Mikhail Glushenkov028f18e2008-05-06 18:13:45 +00001052 O << Indent3 << "llvm::SplitString("
1053 << D.GenVariableName() << ", vec, \",\");\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001054 }
1055 else {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001056 throw std::string("Switches can't have unpack_values property!");
1057 }
1058 }
1059
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001060 // End of the if-clause.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001061 O << Indent2 << "}\n";
1062}
1063
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001064/// SubstituteSpecialCommands - Perform string substitution for $CALL
1065/// and $ENV. Helper function used by EmitCmdLineVecFill().
1066std::string SubstituteSpecialCommands(const std::string& cmd) {
Mikhail Glushenkov1e453b02008-05-30 06:13:29 +00001067 size_t cparen = cmd.find(")");
1068 std::string ret;
1069
1070 if (cmd.find("$CALL(") == 0) {
1071 if (cmd.size() == 6)
1072 throw std::string("$CALL invocation: empty argument list!");
1073
1074 ret += "hooks::";
1075 ret += std::string(cmd.begin() + 6, cmd.begin() + cparen);
1076 ret += "()";
1077 }
1078 else if (cmd.find("$ENV(") == 0) {
1079 if (cmd.size() == 5)
1080 throw std::string("$ENV invocation: empty argument list!");
1081
1082 ret += "std::getenv(\"";
1083 ret += std::string(cmd.begin() + 5, cmd.begin() + cparen);
1084 ret += "\")";
1085 }
1086 else {
1087 throw "Unknown special command: " + cmd;
1088 }
1089
1090 if (cmd.begin() + cparen + 1 != cmd.end()) {
1091 ret += " + std::string(\"";
1092 ret += (cmd.c_str() + cparen + 1);
1093 ret += "\")";
1094 }
1095
1096 return ret;
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001097}
1098
1099/// EmitCmdLineVecFill - Emit code that fills in the command line
1100/// vector. Helper function used by EmitGenerateActionMethod().
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001101void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1102 bool Version, const char* IndentLevel,
1103 std::ostream& O) {
1104 StrVector StrVec;
Mikhail Glushenkov1e453b02008-05-30 06:13:29 +00001105 SplitString(InitPtrToString(CmdLine), StrVec);
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001106 if (StrVec.empty())
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001107 throw "Tool " + ToolName + " has empty command line!";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001108
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001109 StrVector::const_iterator I = StrVec.begin();
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001110 ++I;
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001111 for (StrVector::const_iterator E = StrVec.end(); I != E; ++I) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001112 const std::string& cmd = *I;
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001113 O << IndentLevel;
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001114 if (cmd.at(0) == '$') {
1115 if (cmd == "$INFILE") {
1116 if (Version)
1117 O << "for (PathVector::const_iterator B = inFiles.begin()"
1118 << ", E = inFiles.end();\n"
1119 << IndentLevel << "B != E; ++B)\n"
1120 << IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
1121 else
1122 O << "vec.push_back(inFile.toString());\n";
1123 }
1124 else if (cmd == "$OUTFILE") {
1125 O << "vec.push_back(outFile.toString());\n";
1126 }
1127 else {
Mikhail Glushenkov1e453b02008-05-30 06:13:29 +00001128 O << "vec.push_back(" << SubstituteSpecialCommands(cmd);
1129 O << ");\n";
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001130 }
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001131 }
1132 else {
1133 O << "vec.push_back(\"" << cmd << "\");\n";
1134 }
1135 }
Mikhail Glushenkov52a54132008-05-30 06:23:29 +00001136 O << IndentLevel << "cmd = "
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001137 << ((StrVec[0][0] == '$') ? SubstituteSpecialCommands(StrVec[0])
1138 : "\"" + StrVec[0] + "\"")
Mikhail Glushenkov52a54132008-05-30 06:23:29 +00001139 << ";\n";
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001140}
1141
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001142/// EmitCmdLineVecFillCallback - A function object wrapper around
1143/// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1144/// argument to EmitCaseConstructHandler().
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001145class EmitCmdLineVecFillCallback {
1146 bool Version;
1147 const std::string& ToolName;
1148 public:
1149 EmitCmdLineVecFillCallback(bool Ver, const std::string& TN)
1150 : Version(Ver), ToolName(TN) {}
1151
1152 void operator()(const Init* Statement, const char* IndentLevel,
1153 std::ostream& O) const
1154 {
Mikhail Glushenkov31f52152008-05-30 06:10:47 +00001155 EmitCmdLineVecFill(Statement, ToolName, Version,
1156 (std::string(IndentLevel) + Indent1).c_str(), O);
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001157 }
1158};
1159
1160// EmitGenerateActionMethod - Emit one of two versions of the
1161// Tool::GenerateAction() method.
1162void EmitGenerateActionMethod (const ToolProperties& P,
1163 const GlobalOptionDescriptions& OptDescs,
1164 bool Version, std::ostream& O) {
1165 if (Version)
1166 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
1167 else
1168 O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
1169
1170 O << Indent2 << "const sys::Path& outFile,\n"
1171 << Indent2 << "const InputLanguagesSet& InLangs) const\n"
1172 << Indent1 << "{\n"
Mikhail Glushenkov61923cb2008-05-30 06:24:49 +00001173 << Indent2 << "const char* cmd;\n"
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001174 << Indent2 << "std::vector<std::string> vec;\n";
1175
1176 // cmd_line is either a string or a 'case' construct.
1177 if (typeid(*P.CmdLine) == typeid(StringInit))
1178 EmitCmdLineVecFill(P.CmdLine, P.Name, Version, Indent2, O);
1179 else
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001180 EmitCaseConstructHandler(&InitPtrToDag(P.CmdLine), Indent2,
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001181 EmitCmdLineVecFillCallback(Version, P.Name),
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001182 true, OptDescs, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001183
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001184 // For every understood option, emit handling code.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001185 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1186 E = P.OptDescs.end(); B != E; ++B) {
1187 const ToolOptionDescription& val = B->second;
Mikhail Glushenkov31f52152008-05-30 06:10:47 +00001188 EmitOptionPropertyHandlingCode(val, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001189 }
1190
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001191 // Handle the Sink property.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001192 if (P.isSink()) {
1193 O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
1194 << Indent3 << "vec.insert(vec.end(), "
1195 << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
1196 << Indent2 << "}\n";
1197 }
1198
Mikhail Glushenkov52a54132008-05-30 06:23:29 +00001199 O << Indent2 << "return Action(cmd, vec);\n"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001200 << Indent1 << "}\n\n";
1201}
1202
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001203/// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1204/// a given Tool class.
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001205void EmitGenerateActionMethods (const ToolProperties& P,
1206 const GlobalOptionDescriptions& OptDescs,
1207 std::ostream& O) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001208 if (!P.isJoin())
1209 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001210 << Indent2 << "const llvm::sys::Path& outFile,\n"
1211 << Indent2 << "const InputLanguagesSet& InLangs) const\n"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001212 << Indent1 << "{\n"
1213 << Indent2 << "throw std::runtime_error(\"" << P.Name
1214 << " is not a Join tool!\");\n"
1215 << Indent1 << "}\n\n";
1216 else
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001217 EmitGenerateActionMethod(P, OptDescs, true, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001218
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001219 EmitGenerateActionMethod(P, OptDescs, false, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001220}
1221
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001222/// EmitIsLastMethod - Emit the IsLast() method for a given Tool
1223/// class.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001224void EmitIsLastMethod (const ToolProperties& P, std::ostream& O) {
1225 O << Indent1 << "bool IsLast() const {\n"
1226 << Indent2 << "bool last = false;\n";
1227
1228 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1229 E = P.OptDescs.end(); B != E; ++B) {
1230 const ToolOptionDescription& val = B->second;
1231
1232 if (val.isStopCompilation())
1233 O << Indent2
1234 << "if (" << val.GenVariableName()
1235 << ")\n" << Indent3 << "last = true;\n";
1236 }
1237
1238 O << Indent2 << "return last;\n"
1239 << Indent1 << "}\n\n";
1240}
1241
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001242/// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1243/// methods for a given Tool class.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001244void EmitInOutLanguageMethods (const ToolProperties& P, std::ostream& O) {
Mikhail Glushenkov61923cb2008-05-30 06:24:49 +00001245 O << Indent1 << "const char** InputLanguages() const {\n"
1246 << Indent2 << "return InputLanguages_;\n"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001247 << Indent1 << "}\n\n";
1248
Mikhail Glushenkovd379d162008-05-06 17:24:26 +00001249 O << Indent1 << "const char* OutputLanguage() const {\n"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001250 << Indent2 << "return \"" << P.OutLanguage << "\";\n"
1251 << Indent1 << "}\n\n";
1252}
1253
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001254/// EmitOutputSuffixMethod - Emit the OutputSuffix() method for a
1255/// given Tool class.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001256void EmitOutputSuffixMethod (const ToolProperties& P, std::ostream& O) {
Mikhail Glushenkovd379d162008-05-06 17:24:26 +00001257 O << Indent1 << "const char* OutputSuffix() const {\n"
Mikhail Glushenkovabab33b2008-05-30 06:13:02 +00001258 << Indent2 << "const char* ret = \"" << P.OutputSuffix << "\";\n";
1259
1260 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1261 E = P.OptDescs.end(); B != E; ++B) {
1262 const ToolOptionDescription& OptDesc = B->second;
1263 for (OptionPropertyList::const_iterator B = OptDesc.Props.begin(),
1264 E = OptDesc.Props.end(); B != E; ++B) {
1265 const OptionProperty& OptProp = *B;
1266 if (OptProp.first == OptionPropertyType::OutputSuffix) {
1267 O << Indent2 << "if (" << OptDesc.GenVariableName() << ")\n"
1268 << Indent3 << "ret = \"" << OptProp.second << "\";\n";
1269 }
1270 }
1271 }
1272
1273 O << Indent2 << "return ret;\n"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001274 << Indent1 << "}\n\n";
1275}
1276
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001277/// EmitNameMethod - Emit the Name() method for a given Tool class.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001278void EmitNameMethod (const ToolProperties& P, std::ostream& O) {
Mikhail Glushenkovd379d162008-05-06 17:24:26 +00001279 O << Indent1 << "const char* Name() const {\n"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001280 << Indent2 << "return \"" << P.Name << "\";\n"
1281 << Indent1 << "}\n\n";
1282}
1283
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001284/// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1285/// class.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001286void EmitIsJoinMethod (const ToolProperties& P, std::ostream& O) {
1287 O << Indent1 << "bool IsJoin() const {\n";
1288 if (P.isJoin())
1289 O << Indent2 << "return true;\n";
1290 else
1291 O << Indent2 << "return false;\n";
1292 O << Indent1 << "}\n\n";
1293}
1294
Mikhail Glushenkov61923cb2008-05-30 06:24:49 +00001295/// EmitStaticMemberDefinitions - Emit static member definitions for a
1296/// given Tool class.
1297void EmitStaticMemberDefinitions(const ToolProperties& P, std::ostream& O) {
1298 O << "const char* " << P.Name << "::InputLanguages_[] = {";
1299 for (StrVector::const_iterator B = P.InLanguage.begin(),
1300 E = P.InLanguage.end(); B != E; ++B)
1301 O << '\"' << *B << "\", ";
1302 O << "0};\n\n";
1303}
1304
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001305/// EmitToolClassDefinition - Emit a Tool class definition.
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001306void EmitToolClassDefinition (const ToolProperties& P,
1307 const GlobalOptionDescriptions& OptDescs,
1308 std::ostream& O) {
1309 if (P.Name == "root")
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001310 return;
1311
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001312 // Header
Mikhail Glushenkov121889c2008-05-06 17:26:53 +00001313 O << "class " << P.Name << " : public ";
1314 if (P.isJoin())
1315 O << "JoinTool";
1316 else
1317 O << "Tool";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001318
Mikhail Glushenkov61923cb2008-05-30 06:24:49 +00001319 O << "{\nprivate:\n"
1320 << Indent1 << "static const char* InputLanguages_[];\n\n";
1321
1322 O << "public:\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001323 EmitNameMethod(P, O);
1324 EmitInOutLanguageMethods(P, O);
1325 EmitOutputSuffixMethod(P, O);
1326 EmitIsJoinMethod(P, O);
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001327 EmitGenerateActionMethods(P, OptDescs, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001328 EmitIsLastMethod(P, O);
1329
1330 // Close class definition
Mikhail Glushenkov61923cb2008-05-30 06:24:49 +00001331 O << "};\n";
1332
1333 EmitStaticMemberDefinitions(P, O);
1334
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001335}
1336
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001337/// EmitOptionDescriptions - Iterate over a list of option
1338/// descriptions and emit registration code.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001339void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
1340 std::ostream& O)
1341{
Mikhail Glushenkovb623c322008-05-30 06:22:52 +00001342 std::vector<GlobalOptionDescription> Aliases;
1343
Mikhail Glushenkov52a54132008-05-30 06:23:29 +00001344 // Emit static cl::Option variables.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001345 for (GlobalOptionDescriptions::const_iterator B = descs.begin(),
1346 E = descs.end(); B!=E; ++B) {
1347 const GlobalOptionDescription& val = B->second;
1348
Mikhail Glushenkovb623c322008-05-30 06:22:52 +00001349 if (val.Type == OptionType::Alias) {
1350 Aliases.push_back(val);
1351 continue;
1352 }
1353
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001354 O << val.GenTypeDeclaration() << ' '
1355 << val.GenVariableName()
1356 << "(\"" << val.Name << '\"';
1357
1358 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1359 O << ", cl::Prefix";
1360
1361 if (val.isRequired()) {
1362 switch (val.Type) {
1363 case OptionType::PrefixList:
1364 case OptionType::ParameterList:
1365 O << ", cl::OneOrMore";
1366 break;
1367 default:
1368 O << ", cl::Required";
1369 }
1370 }
1371
Mikhail Glushenkovb623c322008-05-30 06:22:52 +00001372 if (!val.Help.empty())
1373 O << ", cl::desc(\"" << val.Help << "\")";
1374
1375 O << ");\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001376 }
1377
Mikhail Glushenkovb623c322008-05-30 06:22:52 +00001378 // Emit the aliases (they should go after all the 'proper' options).
1379 for (std::vector<GlobalOptionDescription>::const_iterator
1380 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
1381 const GlobalOptionDescription& val = *B;
1382
1383 O << val.GenTypeDeclaration() << ' '
1384 << val.GenVariableName()
1385 << "(\"" << val.Name << '\"';
1386
1387 GlobalOptionDescriptions::container_type
1388 ::const_iterator F = descs.Descriptions.find(val.Help);
1389 if (F != descs.Descriptions.end())
1390 O << ", cl::aliasopt(" << F->second.GenVariableName() << ")";
1391 else
1392 throw val.Name + ": alias to an unknown option!";
1393
1394 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
1395 }
1396
1397 // Emit the sink option.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001398 if (descs.HasSink)
1399 O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
1400
1401 O << '\n';
1402}
1403
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001404/// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001405void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
1406{
1407 // Get the relevant field out of RecordKeeper
1408 Record* LangMapRecord = Records.getDef("LanguageMap");
1409 if (!LangMapRecord)
1410 throw std::string("Language map definition not found!");
1411
1412 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
1413 if (!LangsToSuffixesList)
1414 throw std::string("Error in the language map definition!");
1415
1416 // Generate code
Mikhail Glushenkov242d0e62008-05-30 06:19:52 +00001417 O << "void llvmc::PopulateLanguageMap() {\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001418
1419 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
1420 Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
1421
1422 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
1423 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
1424
1425 for (unsigned i = 0; i < Suffixes->size(); ++i)
Mikhail Glushenkov242d0e62008-05-30 06:19:52 +00001426 O << Indent1 << "GlobalLanguageMap[\""
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001427 << InitPtrToString(Suffixes->getElement(i))
1428 << "\"] = \"" << Lang << "\";\n";
1429 }
1430
1431 O << "}\n\n";
1432}
1433
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001434/// FillInToolToLang - Fills in two tables that map tool names to
1435/// (input, output) languages. Used by the typechecker.
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001436void FillInToolToLang (const ToolPropertiesList& TPList,
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001437 StringMap<StringSet<> >& ToolToInLang,
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001438 StringMap<std::string>& ToolToOutLang) {
1439 for (ToolPropertiesList::const_iterator B = TPList.begin(), E = TPList.end();
1440 B != E; ++B) {
1441 const ToolProperties& P = *(*B);
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001442 for (StrVector::const_iterator B = P.InLanguage.begin(),
1443 E = P.InLanguage.end(); B != E; ++B)
1444 ToolToInLang[P.Name].insert(*B);
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001445 ToolToOutLang[P.Name] = P.OutLanguage;
1446 }
1447}
1448
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001449/// TypecheckGraph - Check that names for output and input languages
1450/// on all edges do match.
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001451// TOFIX: It would be nice if this function also checked for cycles
1452// and multiple default edges in the graph (better error
1453// reporting). Unfortunately, it is awkward to do right now because
1454// our intermediate representation is not sufficiently
1455// sofisticated. Algorithms like these should be run on a real graph
1456// instead of AST.
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001457void TypecheckGraph (Record* CompilationGraph,
1458 const ToolPropertiesList& TPList) {
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001459 StringMap<StringSet<> > ToolToInLang;
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001460 StringMap<std::string> ToolToOutLang;
1461
1462 FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
1463 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001464 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
1465 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001466
1467 for (unsigned i = 0; i < edges->size(); ++i) {
1468 Record* Edge = edges->getElementAsRecord(i);
1469 Record* A = Edge->getValueAsDef("a");
1470 Record* B = Edge->getValueAsDef("b");
1471 StringMap<std::string>::iterator IA = ToolToOutLang.find(A->getName());
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001472 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(B->getName());
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001473 if (IA == IAE)
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001474 throw A->getName() + ": no such tool!";
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001475 if (IB == IBE)
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001476 throw B->getName() + ": no such tool!";
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001477 if (A->getName() != "root" && IB->second.count(IA->second) == 0)
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001478 throw "Edge " + A->getName() + "->" + B->getName()
1479 + ": output->input language mismatch";
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001480 if (B->getName() == "root")
Mikhail Glushenkov761958d2008-05-06 16:36:50 +00001481 throw std::string("Edges back to the root are not allowed!");
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001482 }
1483}
1484
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001485/// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
1486/// by EmitEdgeClass().
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001487void IncDecWeight (const Init* i, const char* IndentLevel,
1488 std::ostream& O) {
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001489 const DagInit& d = InitPtrToDag(i);
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001490 const std::string& OpName = d.getOperator()->getAsString();
1491
1492 if (OpName == "inc_weight")
1493 O << IndentLevel << Indent1 << "ret += ";
1494 else if (OpName == "dec_weight")
1495 O << IndentLevel << Indent1 << "ret -= ";
1496 else
1497 throw "Unknown operator in edge properties list: " + OpName + '!';
1498
1499 if (d.getNumArgs() > 0)
1500 O << InitPtrToInt(d.getArg(0)) << ";\n";
1501 else
1502 O << "2;\n";
1503
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +00001504}
1505
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001506/// EmitEdgeClass - Emit a single Edge# class.
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001507void EmitEdgeClass (unsigned N, const std::string& Target,
1508 DagInit* Case, const GlobalOptionDescriptions& OptDescs,
1509 std::ostream& O) {
Mikhail Glushenkov8d0d5d22008-05-06 17:23:14 +00001510
1511 // Class constructor.
1512 O << "class Edge" << N << ": public Edge {\n"
1513 << "public:\n"
1514 << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1515 << "\") {}\n\n"
1516
Mikhail Glushenkov7dbc0ab2008-05-06 18:14:24 +00001517 // Function Weight().
Mikhail Glushenkovd6228882008-05-06 18:15:12 +00001518 << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
Mikhail Glushenkov7dbc0ab2008-05-06 18:14:24 +00001519 << Indent2 << "unsigned ret = 0;\n";
Mikhail Glushenkov8d0d5d22008-05-06 17:23:14 +00001520
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001521 // Handle the 'case' construct.
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001522 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
Mikhail Glushenkov7dbc0ab2008-05-06 18:14:24 +00001523
1524 O << Indent2 << "return ret;\n"
1525 << Indent1 << "};\n\n};\n\n";
Mikhail Glushenkov8d0d5d22008-05-06 17:23:14 +00001526}
1527
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001528/// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001529void EmitEdgeClasses (Record* CompilationGraph,
1530 const GlobalOptionDescriptions& OptDescs,
1531 std::ostream& O) {
1532 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1533
1534 for (unsigned i = 0; i < edges->size(); ++i) {
Mikhail Glushenkov761958d2008-05-06 16:36:50 +00001535 Record* Edge = edges->getElementAsRecord(i);
1536 Record* B = Edge->getValueAsDef("b");
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001537 DagInit* Weight = Edge->getValueAsDag("weight");
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001538
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001539 if (isDagEmpty(Weight))
Mikhail Glushenkov761958d2008-05-06 16:36:50 +00001540 continue;
1541
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001542 EmitEdgeClass(i, B->getName(), Weight, OptDescs, O);
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001543 }
1544}
1545
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001546/// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1547/// function.
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001548void EmitPopulateCompilationGraph (Record* CompilationGraph,
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001549 std::ostream& O)
1550{
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001551 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001552
1553 // Generate code
Mikhail Glushenkov34307a92008-05-06 18:08:59 +00001554 O << "void llvmc::PopulateCompilationGraph(CompilationGraph& G) {\n"
Mikhail Glushenkov242d0e62008-05-30 06:19:52 +00001555 << Indent1 << "PopulateLanguageMap();\n\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001556
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001557 // Insert vertices
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001558
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001559 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1560 if (Tools.empty())
1561 throw std::string("No tool definitions found!");
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001562
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001563 for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
1564 const std::string& Name = (*B)->getName();
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001565 if (Name != "root")
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001566 O << Indent1 << "G.insertNode(new "
1567 << Name << "());\n";
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001568 }
1569
1570 O << '\n';
1571
1572 // Insert edges
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001573 for (unsigned i = 0; i < edges->size(); ++i) {
1574 Record* Edge = edges->getElementAsRecord(i);
1575 Record* A = Edge->getValueAsDef("a");
1576 Record* B = Edge->getValueAsDef("b");
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001577 DagInit* Weight = Edge->getValueAsDag("weight");
Mikhail Glushenkov761958d2008-05-06 16:36:50 +00001578
1579 O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
1580
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001581 if (isDagEmpty(Weight))
Mikhail Glushenkov761958d2008-05-06 16:36:50 +00001582 O << "new SimpleEdge(\"" << B->getName() << "\")";
1583 else
1584 O << "new Edge" << i << "()";
1585
1586 O << ");\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001587 }
1588
1589 O << "}\n\n";
1590}
1591
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001592/// ExtractHookNames - Extract the hook names from all instances of
1593/// $CALL(HookName) in the provided command line string. Helper
1594/// function used by FillInHookNames().
1595void ExtractHookNames(const Init* CmdLine, StrVector& HookNames) {
1596 StrVector cmds;
Mikhail Glushenkov1e453b02008-05-30 06:13:29 +00001597 llvm::SplitString(InitPtrToString(CmdLine), cmds);
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001598 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
1599 B != E; ++B) {
1600 const std::string& cmd = *B;
1601 if (cmd.find("$CALL(") == 0) {
1602 if (cmd.size() == 6)
1603 throw std::string("$CALL invocation: empty argument list!");
Mikhail Glushenkov1e453b02008-05-30 06:13:29 +00001604 HookNames.push_back(std::string(cmd.begin() + 6,
1605 cmd.begin() + cmd.find(")")));
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001606 }
1607 }
1608}
1609
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001610/// ExtractHookNamesFromCaseConstruct - Extract hook names from the
1611/// 'case' expression, handle nesting. Helper function used by
1612/// FillInHookNames().
1613void ExtractHookNamesFromCaseConstruct(Init* Case, StrVector& HookNames) {
1614 const DagInit& d = InitPtrToDag(Case);
1615 bool even = false;
1616 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1617 B != E; ++B) {
1618 Init* arg = *B;
1619 if (even && dynamic_cast<DagInit*>(arg)
1620 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
1621 ExtractHookNamesFromCaseConstruct(arg, HookNames);
1622 else if (even)
1623 ExtractHookNames(arg, HookNames);
1624 even = !even;
1625 }
1626}
1627
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001628/// FillInHookNames - Actually extract the hook names from all command
1629/// line strings. Helper function used by EmitHookDeclarations().
1630void FillInHookNames(const ToolPropertiesList& TPList,
1631 StrVector& HookNames) {
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001632 // For all command lines:
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001633 for (ToolPropertiesList::const_iterator B = TPList.begin(),
1634 E = TPList.end(); B != E; ++B) {
1635 const ToolProperties& P = *(*B);
1636 if (!P.CmdLine)
1637 continue;
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001638 if (dynamic_cast<StringInit*>(P.CmdLine))
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001639 // This is a string.
1640 ExtractHookNames(P.CmdLine, HookNames);
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001641 else
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001642 // This is a 'case' construct.
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001643 ExtractHookNamesFromCaseConstruct(P.CmdLine, HookNames);
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001644 }
1645}
1646
1647/// EmitHookDeclarations - Parse CmdLine fields of all the tool
1648/// property records and emit hook function declaration for each
1649/// instance of $CALL(HookName).
1650void EmitHookDeclarations(const ToolPropertiesList& ToolProps,
1651 std::ostream& O) {
1652 StrVector HookNames;
1653 FillInHookNames(ToolProps, HookNames);
1654 if (HookNames.empty())
1655 return;
1656 std::sort(HookNames.begin(), HookNames.end());
1657 StrVector::const_iterator E = std::unique(HookNames.begin(), HookNames.end());
1658
1659 O << "namespace hooks {\n";
1660 for (StrVector::const_iterator B = HookNames.begin(); B != E; ++B)
1661 O << Indent1 << "std::string " << *B << "();\n";
1662
1663 O << "}\n\n";
1664}
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001665
1666// End of anonymous namespace
Mikhail Glushenkovc1f738d2008-05-06 18:12:03 +00001667}
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001668
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001669/// run - The back-end entry point.
Mikhail Glushenkovc1f738d2008-05-06 18:12:03 +00001670void LLVMCConfigurationEmitter::run (std::ostream &O) {
Mikhail Glushenkovffe736e2008-05-30 06:21:48 +00001671 try {
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001672
1673 // Emit file header.
Mikhail Glushenkov34307a92008-05-06 18:08:59 +00001674 EmitSourceFileHeader("LLVMC Configuration Library", O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001675
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001676 // Get a list of all defined Tools.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001677 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1678 if (Tools.empty())
1679 throw std::string("No tool definitions found!");
1680
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001681 // Gather information from the Tool description dags.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001682 ToolPropertiesList tool_props;
1683 GlobalOptionDescriptions opt_descs;
1684 CollectToolProperties(Tools.begin(), Tools.end(), tool_props, opt_descs);
1685
Mikhail Glushenkovd638e852008-05-30 06:26:08 +00001686 RecordVector OptionLists = Records.getAllDerivedDefinitions("OptionList");
1687 CollectPropertiesFromOptionList(OptionLists.begin(), OptionLists.end(),
1688 opt_descs);
1689
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001690 // Emit global option registration code.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001691 EmitOptionDescriptions(opt_descs, O);
1692
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001693 // Emit hook declarations.
1694 EmitHookDeclarations(tool_props, O);
1695
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001696 // Emit PopulateLanguageMap() function
1697 // (a language map maps from file extensions to language names).
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001698 EmitPopulateLanguageMap(Records, O);
1699
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001700 // Emit Tool classes.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001701 for (ToolPropertiesList::const_iterator B = tool_props.begin(),
1702 E = tool_props.end(); B!=E; ++B)
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001703 EmitToolClassDefinition(*(*B), opt_descs, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001704
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001705 Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
1706 if (!CompilationGraphRecord)
1707 throw std::string("Compilation graph description not found!");
1708
1709 // Typecheck the compilation graph.
1710 TypecheckGraph(CompilationGraphRecord, tool_props);
1711
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001712 // Emit Edge# classes.
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001713 EmitEdgeClasses(CompilationGraphRecord, opt_descs, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001714
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001715 // Emit PopulateCompilationGraph() function.
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001716 EmitPopulateCompilationGraph(CompilationGraphRecord, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001717
1718 // EOF
Mikhail Glushenkovffe736e2008-05-30 06:21:48 +00001719 } catch (std::exception& Error) {
1720 throw Error.what() + std::string(" - usually this means a syntax error.");
1721 }
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001722}