blob: f336d452031fc4addb22f9f995a02b9c00e46658 [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"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000023#include <algorithm>
24#include <cassert>
25#include <functional>
Mikhail Glushenkovffe736e2008-05-30 06:21:48 +000026#include <stdexcept>
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000027#include <string>
Chris Lattner52aa6862008-06-04 04:46:14 +000028#include <typeinfo>
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000029using namespace llvm;
30
Mikhail Glushenkovc1f738d2008-05-06 18:12:03 +000031namespace {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000032
33//===----------------------------------------------------------------------===//
34/// Typedefs
35
36typedef std::vector<Record*> RecordVector;
37typedef std::vector<std::string> StrVector;
38
39//===----------------------------------------------------------------------===//
40/// Constants
41
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +000042// Indentation strings.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000043const char * Indent1 = " ";
44const char * Indent2 = " ";
45const char * Indent3 = " ";
46const char * Indent4 = " ";
47
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +000048// Default help string.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000049const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
50
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +000051// Name for the "sink" option.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000052const char * SinkOptionName = "AutoGeneratedSinkOption";
53
54//===----------------------------------------------------------------------===//
55/// Helper functions
56
Mikhail Glushenkov35576b02008-05-30 06:10:19 +000057int InitPtrToInt(const Init* ptr) {
58 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +000059 return val.getValue();
60}
61
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +000062const std::string& InitPtrToString(const Init* ptr) {
63 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
64 return val.getValue();
65}
66
67const ListInit& InitPtrToList(const Init* ptr) {
68 const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
69 return val;
70}
71
72const DagInit& InitPtrToDag(const Init* ptr) {
Mikhail Glushenkov35576b02008-05-30 06:10:19 +000073 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +000074 return val;
75}
76
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +000077// checkNumberOfArguments - Ensure that the number of args in d is
Mikhail Glushenkovdedba642008-05-30 06:08:50 +000078// less than or equal to min_arguments, otherwise throw an exception.
Mikhail Glushenkova5922cc2008-05-06 17:22:03 +000079void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
80 if (d->getNumArgs() < min_arguments)
81 throw "Property " + d->getOperator()->getAsString()
82 + " has too few arguments!";
83}
84
Mikhail Glushenkovdedba642008-05-30 06:08:50 +000085// isDagEmpty - is this DAG marked with an empty marker?
86bool isDagEmpty (const DagInit* d) {
87 return d->getOperator()->getAsString() == "empty";
88}
Mikhail Glushenkova5922cc2008-05-06 17:22:03 +000089
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000090//===----------------------------------------------------------------------===//
91/// Back-end specific code
92
93// A command-line option can have one of the following types:
94//
Mikhail Glushenkovb623c322008-05-30 06:22:52 +000095// Alias - an alias for another option.
96//
97// Switch - a simple switch without arguments, e.g. -O2
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000098//
99// Parameter - an option that takes one(and only one) argument, e.g. -o file,
100// --output=file
101//
102// ParameterList - same as Parameter, but more than one occurence
103// of the option is allowed, e.g. -lm -lpthread
104//
105// Prefix - argument is everything after the prefix,
106// e.g. -Wa,-foo,-bar, -DNAME=VALUE
107//
108// PrefixList - same as Prefix, but more than one option occurence is
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000109// allowed.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000110
111namespace OptionType {
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000112 enum OptionType { Alias, Switch,
113 Parameter, ParameterList, Prefix, PrefixList};
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000114}
115
116bool IsListOptionType (OptionType::OptionType t) {
117 return (t == OptionType::ParameterList || t == OptionType::PrefixList);
118}
119
120// Code duplication here is necessary because one option can affect
121// several tools and those tools may have different actions associated
122// with this option. GlobalOptionDescriptions are used to generate
123// the option registration code, while ToolOptionDescriptions are used
124// to generate tool-specific code.
125
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000126/// OptionDescription - Base class for option descriptions.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000127struct OptionDescription {
128 OptionType::OptionType Type;
129 std::string Name;
130
131 OptionDescription(OptionType::OptionType t = OptionType::Switch,
132 const std::string& n = "")
133 : Type(t), Name(n)
134 {}
135
136 const char* GenTypeDeclaration() const {
137 switch (Type) {
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000138 case OptionType::Alias:
139 return "cl::alias";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000140 case OptionType::PrefixList:
141 case OptionType::ParameterList:
142 return "cl::list<std::string>";
143 case OptionType::Switch:
144 return "cl::opt<bool>";
145 case OptionType::Parameter:
146 case OptionType::Prefix:
147 default:
148 return "cl::opt<std::string>";
149 }
150 }
151
Mikhail Glushenkov4019e952008-05-12 16:33:06 +0000152 // Escape commas and other symbols not allowed in the C++ variable
153 // names. Makes it possible to use options with names like "Wa,"
154 // (useful for prefix options).
155 std::string EscapeVariableName(const std::string& Var) const {
156 std::string ret;
157 for (unsigned i = 0; i != Var.size(); ++i) {
158 if (Var[i] == ',') {
159 ret += "_comma_";
160 }
161 else {
162 ret.push_back(Var[i]);
163 }
164 }
165 return ret;
166 }
167
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000168 std::string GenVariableName() const {
Mikhail Glushenkov4019e952008-05-12 16:33:06 +0000169 const std::string& EscapedName = EscapeVariableName(Name);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000170 switch (Type) {
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000171 case OptionType::Alias:
172 return "AutoGeneratedAlias" + EscapedName;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000173 case OptionType::Switch:
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000174 return "AutoGeneratedSwitch" + EscapedName;
175 case OptionType::Prefix:
176 return "AutoGeneratedPrefix" + EscapedName;
177 case OptionType::PrefixList:
178 return "AutoGeneratedPrefixList" + EscapedName;
179 case OptionType::Parameter:
180 return "AutoGeneratedParameter" + EscapedName;
181 case OptionType::ParameterList:
182 default:
183 return "AutoGeneratedParameterList" + EscapedName;
184 }
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000185 }
186
187};
188
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000189// Global option description.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000190
191namespace GlobalOptionDescriptionFlags {
192 enum GlobalOptionDescriptionFlags { Required = 0x1 };
193}
194
195struct GlobalOptionDescription : public OptionDescription {
196 std::string Help;
197 unsigned Flags;
198
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000199 // We need to provide a default constructor because
200 // StringMap can only store DefaultConstructible objects.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000201 GlobalOptionDescription() : OptionDescription(), Flags(0)
202 {}
203
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000204 GlobalOptionDescription (OptionType::OptionType t, const std::string& n,
205 const std::string& h = DefaultHelpString)
206 : OptionDescription(t, n), Help(h), Flags(0)
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000207 {}
208
209 bool isRequired() const {
210 return Flags & GlobalOptionDescriptionFlags::Required;
211 }
212 void setRequired() {
213 Flags |= GlobalOptionDescriptionFlags::Required;
214 }
215
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000216 /// Merge - Merge two option descriptions.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000217 void Merge (const GlobalOptionDescription& other)
218 {
219 if (other.Type != Type)
220 throw "Conflicting definitions for the option " + Name + "!";
221
Mikhail Glushenkov434816d2008-05-06 18:13:00 +0000222 if (Help == DefaultHelpString)
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000223 Help = other.Help;
Mikhail Glushenkov434816d2008-05-06 18:13:00 +0000224 else if (other.Help != DefaultHelpString) {
225 llvm::cerr << "Warning: more than one help string defined for option "
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000226 + Name + "\n";
Mikhail Glushenkov434816d2008-05-06 18:13:00 +0000227 }
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000228
229 Flags |= other.Flags;
230 }
231};
232
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000233/// GlobalOptionDescriptions - A GlobalOptionDescription array
234/// together with some flags affecting generation of option
235/// declarations.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000236struct GlobalOptionDescriptions {
237 typedef StringMap<GlobalOptionDescription> container_type;
238 typedef container_type::const_iterator const_iterator;
239
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000240 /// Descriptions - A list of GlobalOptionDescriptions.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000241 container_type Descriptions;
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000242 /// HasSink - Should the emitter generate a "cl::sink" option?
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000243 bool HasSink;
244
Mikhail Glushenkove5fcb552008-05-30 06:28:37 +0000245 /// FindOption - exception-throwing wrapper for find().
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 Glushenkove5fcb552008-05-30 06:28:37 +0000254 /// insertDescription - Insert new GlobalOptionDescription into
255 /// GlobalOptionDescriptions list
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000256 void insertDescription (const GlobalOptionDescription& o)
257 {
258 container_type::iterator I = Descriptions.find(o.Name);
259 if (I != Descriptions.end()) {
260 GlobalOptionDescription& D = I->second;
261 D.Merge(o);
262 }
263 else {
264 Descriptions[o.Name] = o;
265 }
266 }
267
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000268 // Support for STL-style iteration
269 const_iterator begin() const { return Descriptions.begin(); }
270 const_iterator end() const { return Descriptions.end(); }
271};
272
273
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000274// Tool-local option description.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000275
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000276// Properties without arguments are implemented as flags.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000277namespace ToolOptionDescriptionFlags {
278 enum ToolOptionDescriptionFlags { StopCompilation = 0x1,
279 Forward = 0x2, UnpackValues = 0x4};
280}
281namespace OptionPropertyType {
Mikhail Glushenkovabab33b2008-05-30 06:13:02 +0000282 enum OptionPropertyType { AppendCmd, OutputSuffix };
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000283}
284
285typedef std::pair<OptionPropertyType::OptionPropertyType, std::string>
286OptionProperty;
287typedef SmallVector<OptionProperty, 4> OptionPropertyList;
288
289struct ToolOptionDescription : public OptionDescription {
290 unsigned Flags;
291 OptionPropertyList Props;
292
293 // StringMap can only store DefaultConstructible objects
Mikhail Glushenkov18cbe892008-03-27 09:53:47 +0000294 ToolOptionDescription() : OptionDescription(), Flags(0) {}
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000295
296 ToolOptionDescription (OptionType::OptionType t, const std::string& n)
297 : OptionDescription(t, n)
298 {}
299
300 // Various boolean properties
301 bool isStopCompilation() const {
302 return Flags & ToolOptionDescriptionFlags::StopCompilation;
303 }
304 void setStopCompilation() {
305 Flags |= ToolOptionDescriptionFlags::StopCompilation;
306 }
307
308 bool isForward() const {
309 return Flags & ToolOptionDescriptionFlags::Forward;
310 }
311 void setForward() {
312 Flags |= ToolOptionDescriptionFlags::Forward;
313 }
314
315 bool isUnpackValues() const {
316 return Flags & ToolOptionDescriptionFlags::UnpackValues;
317 }
318 void setUnpackValues() {
319 Flags |= ToolOptionDescriptionFlags::UnpackValues;
320 }
321
322 void AddProperty (OptionPropertyType::OptionPropertyType t,
323 const std::string& val)
324 {
325 Props.push_back(std::make_pair(t, val));
326 }
327};
328
329typedef StringMap<ToolOptionDescription> ToolOptionDescriptions;
330
331// Tool information record
332
333namespace ToolFlags {
334 enum ToolFlags { Join = 0x1, Sink = 0x2 };
335}
336
337struct ToolProperties : public RefCountedBase<ToolProperties> {
338 std::string Name;
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000339 Init* CmdLine;
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +0000340 StrVector InLanguage;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000341 std::string OutLanguage;
342 std::string OutputSuffix;
343 unsigned Flags;
344 ToolOptionDescriptions OptDescs;
345
346 // Various boolean properties
347 void setSink() { Flags |= ToolFlags::Sink; }
348 bool isSink() const { return Flags & ToolFlags::Sink; }
349 void setJoin() { Flags |= ToolFlags::Join; }
350 bool isJoin() const { return Flags & ToolFlags::Join; }
351
352 // Default ctor here is needed because StringMap can only store
353 // DefaultConstructible objects
Anton Korobeynikov246fced2008-06-01 16:22:49 +0000354 ToolProperties() : CmdLine(0), Flags(0) {}
355 ToolProperties (const std::string& n) : Name(n), CmdLine(0), Flags(0) {}
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000356};
357
358
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000359/// ToolPropertiesList - A list of Tool information records
360/// IntrusiveRefCntPtrs are used here because StringMap has no copy
361/// constructor (and we want to avoid copying ToolProperties anyway).
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000362typedef std::vector<IntrusiveRefCntPtr<ToolProperties> > ToolPropertiesList;
363
364
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000365/// CollectOptionProperties - Function object for iterating over a
366/// list (usually, a DAG) of option property records.
367class CollectOptionProperties {
368private:
369 // Implementation details.
370
371 /// OptionPropertyHandler - a function that extracts information
372 /// about a given option property from its DAG representation.
373 typedef void (CollectOptionProperties::* OptionPropertyHandler)
374 (const DagInit*);
375
376 /// OptionPropertyHandlerMap - A map from option property names to
377 /// option property handlers
378 typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
379
380 static OptionPropertyHandlerMap optionPropertyHandlers_;
381 static bool staticMembersInitialized_;
382
383 /// This is where the information is stored
384
385 /// toolProps_ - Properties of the current Tool.
386 ToolProperties* toolProps_;
387 /// optDescs_ - OptionDescriptions table (used to register options
388 /// globally).
389 GlobalOptionDescription& optDesc_;
390
391public:
392
393 explicit CollectOptionProperties(ToolProperties* TP,
394 GlobalOptionDescription& OD)
395 : toolProps_(TP), optDesc_(OD)
396 {
397 if (!staticMembersInitialized_) {
398 optionPropertyHandlers_["append_cmd"] =
399 &CollectOptionProperties::onAppendCmd;
400 optionPropertyHandlers_["forward"] =
401 &CollectOptionProperties::onForward;
402 optionPropertyHandlers_["help"] =
403 &CollectOptionProperties::onHelp;
404 optionPropertyHandlers_["output_suffix"] =
405 &CollectOptionProperties::onOutputSuffix;
406 optionPropertyHandlers_["required"] =
407 &CollectOptionProperties::onRequired;
408 optionPropertyHandlers_["stop_compilation"] =
409 &CollectOptionProperties::onStopCompilation;
410 optionPropertyHandlers_["unpack_values"] =
411 &CollectOptionProperties::onUnpackValues;
412
413 staticMembersInitialized_ = true;
414 }
415 }
416
417 /// operator() - Gets called for every option property; Just forwards
418 /// to the corresponding property handler.
419 void operator() (Init* i) {
420 const DagInit& option_property = InitPtrToDag(i);
421 const std::string& option_property_name
422 = option_property.getOperator()->getAsString();
423 OptionPropertyHandlerMap::iterator method
424 = optionPropertyHandlers_.find(option_property_name);
425
426 if (method != optionPropertyHandlers_.end()) {
427 OptionPropertyHandler h = method->second;
428 (this->*h)(&option_property);
429 }
430 else {
431 throw "Unknown option property: " + option_property_name + "!";
432 }
433 }
434
435private:
436
437 /// Option property handlers --
438 /// Methods that handle properties that are common for all types of
439 /// options (like append_cmd, stop_compilation)
440
441 void onAppendCmd (const DagInit* d) {
442 checkNumberOfArguments(d, 1);
443 checkToolProps(d);
444 const std::string& cmd = InitPtrToString(d->getArg(0));
445
446 toolProps_->OptDescs[optDesc_.Name].
447 AddProperty(OptionPropertyType::AppendCmd, cmd);
448 }
449
450 void onOutputSuffix (const DagInit* d) {
451 checkNumberOfArguments(d, 1);
452 checkToolProps(d);
453 const std::string& suf = InitPtrToString(d->getArg(0));
454
455 if (toolProps_->OptDescs[optDesc_.Name].Type != OptionType::Switch)
456 throw "Option " + optDesc_.Name
457 + " can't have 'output_suffix' property since it isn't a switch!";
458
459 toolProps_->OptDescs[optDesc_.Name].AddProperty
460 (OptionPropertyType::OutputSuffix, suf);
461 }
462
463 void onForward (const DagInit* d) {
464 checkNumberOfArguments(d, 0);
465 checkToolProps(d);
466 toolProps_->OptDescs[optDesc_.Name].setForward();
467 }
468
469 void onHelp (const DagInit* d) {
470 checkNumberOfArguments(d, 1);
471 const std::string& help_message = InitPtrToString(d->getArg(0));
472
473 optDesc_.Help = help_message;
474 }
475
476 void onRequired (const DagInit* d) {
477 checkNumberOfArguments(d, 0);
478 checkToolProps(d);
479 optDesc_.setRequired();
480 }
481
482 void onStopCompilation (const DagInit* d) {
483 checkNumberOfArguments(d, 0);
484 checkToolProps(d);
485 if (optDesc_.Type != OptionType::Switch)
486 throw std::string("Only options of type Switch can stop compilation!");
487 toolProps_->OptDescs[optDesc_.Name].setStopCompilation();
488 }
489
490 void onUnpackValues (const DagInit* d) {
491 checkNumberOfArguments(d, 0);
492 checkToolProps(d);
493 toolProps_->OptDescs[optDesc_.Name].setUnpackValues();
494 }
495
496 // Helper functions
497
498 /// checkToolProps - Throw an error if toolProps_ == 0.
499 void checkToolProps(const DagInit* d) {
500 if (!d)
501 throw "Option property " + d->getOperator()->getAsString()
502 + " can't be used in this context";
503 }
504
505};
506
507CollectOptionProperties::OptionPropertyHandlerMap
508CollectOptionProperties::optionPropertyHandlers_;
509
510bool CollectOptionProperties::staticMembersInitialized_ = false;
511
512
513/// processOptionProperties - Go through the list of option
514/// properties and call a corresponding handler for each.
515void processOptionProperties (const DagInit* d, ToolProperties* t,
516 GlobalOptionDescription& o) {
517 checkNumberOfArguments(d, 2);
518 DagInit::const_arg_iterator B = d->arg_begin();
519 // Skip the first argument: it's always the option name.
520 ++B;
521 std::for_each(B, d->arg_end(), CollectOptionProperties(t, o));
522}
523
Mikhail Glushenkove62df252008-05-30 06:27:29 +0000524/// AddOption - A function object wrapper for
525/// processOptionProperties. Used by CollectProperties and
526/// CollectPropertiesFromOptionList.
527class AddOption {
528private:
529 GlobalOptionDescriptions& OptDescs_;
530 ToolProperties* ToolProps_;
531
532public:
533 explicit AddOption(GlobalOptionDescriptions& OD, ToolProperties* TP = 0)
534 : OptDescs_(OD), ToolProps_(TP)
535 {}
536
537 void operator()(const Init* i) {
538 const DagInit& d = InitPtrToDag(i);
539 checkNumberOfArguments(&d, 2);
540
541 const OptionType::OptionType Type =
542 getOptionType(d.getOperator()->getAsString());
543 const std::string& Name = InitPtrToString(d.getArg(0));
544
545 GlobalOptionDescription OD(Type, Name);
546 if (Type != OptionType::Alias) {
547 processOptionProperties(&d, ToolProps_, OD);
548 if (ToolProps_) {
549 ToolProps_->OptDescs[Name].Type = Type;
550 ToolProps_->OptDescs[Name].Name = Name;
551 }
552 }
553 else {
554 OD.Help = InitPtrToString(d.getArg(1));
555 }
556 OptDescs_.insertDescription(OD);
557 }
558
559private:
560 OptionType::OptionType getOptionType(const std::string& T) const {
561 if (T == "alias_option")
562 return OptionType::Alias;
563 else if (T == "switch_option")
564 return OptionType::Switch;
565 else if (T == "parameter_option")
566 return OptionType::Parameter;
567 else if (T == "parameter_list_option")
568 return OptionType::ParameterList;
569 else if (T == "prefix_option")
570 return OptionType::Prefix;
571 else if (T == "prefix_list_option")
572 return OptionType::PrefixList;
573 else
574 throw "Unknown option type: " + T + '!';
575 }
576};
577
578
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000579/// CollectProperties - Function object for iterating over a list of
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000580/// tool property records.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000581class CollectProperties {
582private:
583
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000584 // Implementation details
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000585
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000586 /// PropertyHandler - a function that extracts information
587 /// about a given tool property from its DAG representation
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000588 typedef void (CollectProperties::*PropertyHandler)(const DagInit*);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000589
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000590 /// PropertyHandlerMap - A map from property names to property
591 /// handlers.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000592 typedef StringMap<PropertyHandler> PropertyHandlerMap;
593
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000594 // Static maps from strings to CollectProperties methods("handlers")
595 static PropertyHandlerMap propertyHandlers_;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000596 static bool staticMembersInitialized_;
597
598
599 /// This is where the information is stored
600
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000601 /// toolProps_ - Properties of the current Tool.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000602 ToolProperties& toolProps_;
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000603 /// optDescs_ - OptionDescriptions table (used to register options
604 /// globally).
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000605 GlobalOptionDescriptions& optDescs_;
606
607public:
608
609 explicit CollectProperties (ToolProperties& p, GlobalOptionDescriptions& d)
610 : toolProps_(p), optDescs_(d)
611 {
612 if (!staticMembersInitialized_) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000613 propertyHandlers_["cmd_line"] = &CollectProperties::onCmdLine;
614 propertyHandlers_["in_language"] = &CollectProperties::onInLanguage;
615 propertyHandlers_["join"] = &CollectProperties::onJoin;
616 propertyHandlers_["out_language"] = &CollectProperties::onOutLanguage;
617 propertyHandlers_["output_suffix"] = &CollectProperties::onOutputSuffix;
618 propertyHandlers_["parameter_option"]
Mikhail Glushenkove62df252008-05-30 06:27:29 +0000619 = &CollectProperties::addOption;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000620 propertyHandlers_["parameter_list_option"] =
Mikhail Glushenkove62df252008-05-30 06:27:29 +0000621 &CollectProperties::addOption;
622 propertyHandlers_["prefix_option"] = &CollectProperties::addOption;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000623 propertyHandlers_["prefix_list_option"] =
Mikhail Glushenkove62df252008-05-30 06:27:29 +0000624 &CollectProperties::addOption;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000625 propertyHandlers_["sink"] = &CollectProperties::onSink;
Mikhail Glushenkove62df252008-05-30 06:27:29 +0000626 propertyHandlers_["switch_option"] = &CollectProperties::addOption;
627 propertyHandlers_["alias_option"] = &CollectProperties::addOption;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000628
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000629 staticMembersInitialized_ = true;
630 }
631 }
632
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000633 /// operator() - Gets called for every tool property; Just forwards
634 /// to the corresponding property handler.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000635 void operator() (Init* i) {
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +0000636 const DagInit& d = InitPtrToDag(i);
Mikhail Glushenkova5922cc2008-05-06 17:22:03 +0000637 const std::string& property_name = d.getOperator()->getAsString();
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000638 PropertyHandlerMap::iterator method
639 = propertyHandlers_.find(property_name);
640
641 if (method != propertyHandlers_.end()) {
642 PropertyHandler h = method->second;
643 (this->*h)(&d);
644 }
645 else {
646 throw "Unknown tool property: " + property_name + "!";
647 }
648 }
649
650private:
651
652 /// Property handlers --
653 /// Functions that extract information about tool properties from
654 /// DAG representation.
655
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000656 void onCmdLine (const DagInit* d) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000657 checkNumberOfArguments(d, 1);
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000658 toolProps_.CmdLine = d->getArg(0);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000659 }
660
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000661 void onInLanguage (const DagInit* d) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000662 checkNumberOfArguments(d, 1);
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +0000663 Init* arg = d->getArg(0);
664
665 // Find out the argument's type.
666 if (typeid(*arg) == typeid(StringInit)) {
667 // It's a string.
668 toolProps_.InLanguage.push_back(InitPtrToString(arg));
669 }
670 else {
671 // It's a list.
672 const ListInit& lst = InitPtrToList(arg);
673 StrVector& out = toolProps_.InLanguage;
674
675 // Copy strings to the output vector.
676 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
677 B != E; ++B) {
678 out.push_back(InitPtrToString(*B));
679 }
680
681 // Remove duplicates.
682 std::sort(out.begin(), out.end());
683 StrVector::iterator newE = std::unique(out.begin(), out.end());
684 out.erase(newE, out.end());
685 }
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000686 }
687
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000688 void onJoin (const DagInit* d) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000689 checkNumberOfArguments(d, 0);
690 toolProps_.setJoin();
691 }
692
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000693 void onOutLanguage (const DagInit* d) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000694 checkNumberOfArguments(d, 1);
695 toolProps_.OutLanguage = InitPtrToString(d->getArg(0));
696 }
697
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000698 void onOutputSuffix (const DagInit* d) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000699 checkNumberOfArguments(d, 1);
700 toolProps_.OutputSuffix = InitPtrToString(d->getArg(0));
701 }
702
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000703 void onSink (const DagInit* d) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000704 checkNumberOfArguments(d, 0);
705 optDescs_.HasSink = true;
706 toolProps_.setSink();
707 }
708
Mikhail Glushenkove62df252008-05-30 06:27:29 +0000709 // Just forwards to the AddOption function object. Somewhat
710 // non-optimal, but avoids code duplication.
711 void addOption (const DagInit* d) {
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000712 checkNumberOfArguments(d, 2);
Mikhail Glushenkove62df252008-05-30 06:27:29 +0000713 AddOption(optDescs_, &toolProps_)(d);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000714 }
715
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000716};
717
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000718// Defintions of static members of CollectProperties.
719CollectProperties::PropertyHandlerMap CollectProperties::propertyHandlers_;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000720bool CollectProperties::staticMembersInitialized_ = false;
721
722
Mikhail Glushenkovd638e852008-05-30 06:26:08 +0000723/// CollectToolProperties - Gather information about tool properties
724/// from the parsed TableGen data (basically a wrapper for the
725/// CollectProperties function object).
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000726void CollectToolProperties (RecordVector::const_iterator B,
727 RecordVector::const_iterator E,
728 ToolPropertiesList& TPList,
729 GlobalOptionDescriptions& OptDescs)
730{
731 // Iterate over a properties list of every Tool definition
732 for (;B!=E;++B) {
Mikhail Glushenkovd638e852008-05-30 06:26:08 +0000733 Record* T = *B;
734 // Throws an exception if the value does not exist.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000735 ListInit* PropList = T->getValueAsListInit("properties");
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000736
737 IntrusiveRefCntPtr<ToolProperties>
738 ToolProps(new ToolProperties(T->getName()));
739
740 std::for_each(PropList->begin(), PropList->end(),
741 CollectProperties(*ToolProps, OptDescs));
742 TPList.push_back(ToolProps);
743 }
744}
745
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000746
747/// CollectPropertiesFromOptionList - Gather information about
Mikhail Glushenkovd638e852008-05-30 06:26:08 +0000748/// *global* option properties from the OptionList.
Mikhail Glushenkovd638e852008-05-30 06:26:08 +0000749void CollectPropertiesFromOptionList (RecordVector::const_iterator B,
750 RecordVector::const_iterator E,
751 GlobalOptionDescriptions& OptDescs)
752{
753 // Iterate over a properties list of every Tool definition
Mikhail Glushenkovd638e852008-05-30 06:26:08 +0000754 for (;B!=E;++B) {
755 RecordVector::value_type T = *B;
756 // Throws an exception if the value does not exist.
757 ListInit* PropList = T->getValueAsListInit("options");
758
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000759 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
Mikhail Glushenkovd638e852008-05-30 06:26:08 +0000760 }
761}
762
Mikhail Glushenkove5fcb552008-05-30 06:28:37 +0000763/// CheckForSuperfluousOptions - Check that there are no side
764/// effect-free options (specified only in the OptionList). Otherwise,
765/// output a warning.
766void CheckForSuperfluousOptions (const ToolPropertiesList& TPList,
767 const GlobalOptionDescriptions& OptDescs) {
768 llvm::StringSet<> nonSuperfluousOptions;
769
770 // Add all options mentioned in the TPList to the set of
771 // non-superfluous options.
772 for (ToolPropertiesList::const_iterator B = TPList.begin(),
773 E = TPList.end(); B != E; ++B) {
774 const ToolProperties& TP = *(*B);
775 for (ToolOptionDescriptions::const_iterator B = TP.OptDescs.begin(),
776 E = TP.OptDescs.end(); B != E; ++B) {
777 nonSuperfluousOptions.insert(B->first());
778 }
779 }
780
781 // Check that all options in OptDescs belong to the set of
782 // non-superfluous options.
783 for (GlobalOptionDescriptions::const_iterator B = OptDescs.begin(),
784 E = OptDescs.end(); B != E; ++B) {
785 const GlobalOptionDescription& Val = B->second;
786 if (!nonSuperfluousOptions.count(Val.Name)
787 && Val.Type != OptionType::Alias)
788 cerr << "Warning: option '-" << Val.Name << "' has no effect! "
789 "Probable cause: this option is specified only in the OptionList.\n";
790 }
791}
792
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000793/// EmitCaseTest1Arg - Helper function used by
794/// EmitCaseConstructHandler.
795bool EmitCaseTest1Arg(const std::string& TestName,
796 const DagInit& d,
797 const GlobalOptionDescriptions& OptDescs,
798 std::ostream& O) {
799 checkNumberOfArguments(&d, 1);
800 const std::string& OptName = InitPtrToString(d.getArg(0));
801 if (TestName == "switch_on") {
802 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
803 if (OptDesc.Type != OptionType::Switch)
804 throw OptName + ": incorrect option type!";
805 O << OptDesc.GenVariableName();
806 return true;
807 } else if (TestName == "input_languages_contain") {
808 O << "InLangs.count(\"" << OptName << "\") != 0";
809 return true;
Mikhail Glushenkov242d0e62008-05-30 06:19:52 +0000810 } else if (TestName == "in_language") {
811 // Works only for cmd_line!
812 O << "GetLanguage(inFile) == \"" << OptName << '\"';
813 return true;
814 } else if (TestName == "not_empty") {
Mikhail Glushenkovb4833872008-05-30 06:24:07 +0000815 if (OptName == "o") {
816 O << "!OutputFilename.empty()";
817 return true;
818 }
819 else {
820 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
821 if (OptDesc.Type == OptionType::Switch)
822 throw OptName + ": incorrect option type!";
823 O << '!' << OptDesc.GenVariableName() << ".empty()";
824 return true;
825 }
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000826 }
827
828 return false;
829}
830
831/// EmitCaseTest2Args - Helper function used by
832/// EmitCaseConstructHandler.
833bool EmitCaseTest2Args(const std::string& TestName,
834 const DagInit& d,
835 const char* IndentLevel,
836 const GlobalOptionDescriptions& OptDescs,
837 std::ostream& O) {
838 checkNumberOfArguments(&d, 2);
839 const std::string& OptName = InitPtrToString(d.getArg(0));
840 const std::string& OptArg = InitPtrToString(d.getArg(1));
841 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
842
843 if (TestName == "parameter_equals") {
844 if (OptDesc.Type != OptionType::Parameter
845 && OptDesc.Type != OptionType::Prefix)
846 throw OptName + ": incorrect option type!";
847 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
848 return true;
849 }
850 else if (TestName == "element_in_list") {
851 if (OptDesc.Type != OptionType::ParameterList
852 && OptDesc.Type != OptionType::PrefixList)
853 throw OptName + ": incorrect option type!";
854 const std::string& VarName = OptDesc.GenVariableName();
855 O << "std::find(" << VarName << ".begin(),\n"
856 << IndentLevel << Indent1 << VarName << ".end(), \""
857 << OptArg << "\") != " << VarName << ".end()";
858 return true;
859 }
860
861 return false;
862}
863
864// Forward declaration.
865// EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
866void EmitCaseTest(const DagInit& d, const char* IndentLevel,
867 const GlobalOptionDescriptions& OptDescs,
868 std::ostream& O);
869
870/// EmitLogicalOperationTest - Helper function used by
871/// EmitCaseConstructHandler.
872void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
873 const char* IndentLevel,
874 const GlobalOptionDescriptions& OptDescs,
875 std::ostream& O) {
876 O << '(';
877 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +0000878 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000879 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
880 if (j != NumArgs - 1)
881 O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
882 else
883 O << ')';
884 }
885}
886
887/// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
888void EmitCaseTest(const DagInit& d, const char* IndentLevel,
889 const GlobalOptionDescriptions& OptDescs,
890 std::ostream& O) {
891 const std::string& TestName = d.getOperator()->getAsString();
892
893 if (TestName == "and")
894 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
895 else if (TestName == "or")
896 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
897 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
898 return;
899 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
900 return;
901 else
902 throw TestName + ": unknown edge property!";
903}
904
905// Emit code that handles the 'case' construct.
906// Takes a function object that should emit code for every case clause.
907// Callback's type is
908// void F(Init* Statement, const char* IndentLevel, std::ostream& O).
909template <typename F>
910void EmitCaseConstructHandler(const DagInit* d, const char* IndentLevel,
Mikhail Glushenkov1d95e9f2008-05-31 13:43:21 +0000911 F Callback, bool EmitElseIf,
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000912 const GlobalOptionDescriptions& OptDescs,
913 std::ostream& O) {
914 assert(d->getOperator()->getAsString() == "case");
915
Mikhail Glushenkov31681512008-05-30 06:15:47 +0000916 unsigned numArgs = d->getNumArgs();
917 if (d->getNumArgs() < 2)
918 throw "There should be at least one clause in the 'case' expression:\n"
919 + d->getAsString();
920
921 for (unsigned i = 0; i != numArgs; ++i) {
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +0000922 const DagInit& Test = InitPtrToDag(d->getArg(i));
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000923
Mikhail Glushenkov31681512008-05-30 06:15:47 +0000924 // Emit the test.
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000925 if (Test.getOperator()->getAsString() == "default") {
926 if (i+2 != numArgs)
927 throw std::string("The 'default' clause should be the last in the"
928 "'case' construct!");
929 O << IndentLevel << "else {\n";
930 }
931 else {
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +0000932 O << IndentLevel << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000933 EmitCaseTest(Test, IndentLevel, OptDescs, O);
934 O << ") {\n";
935 }
936
Mikhail Glushenkov31681512008-05-30 06:15:47 +0000937 // Emit the corresponding statement.
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000938 ++i;
939 if (i == numArgs)
940 throw "Case construct handler: no corresponding action "
941 "found for the test " + Test.getAsString() + '!';
942
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +0000943 Init* arg = d->getArg(i);
944 if (dynamic_cast<DagInit*>(arg)
945 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case") {
946 EmitCaseConstructHandler(static_cast<DagInit*>(arg),
947 (std::string(IndentLevel) + Indent1).c_str(),
948 Callback, EmitElseIf, OptDescs, O);
949 }
950 else {
951 Callback(arg, IndentLevel, O);
952 }
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000953 O << IndentLevel << "}\n";
954 }
955}
956
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000957/// EmitForwardOptionPropertyHandlingCode - Helper function used to
958/// implement EmitOptionPropertyHandlingCode(). Emits code for
959/// handling the (forward) option property.
960void EmitForwardOptionPropertyHandlingCode (const ToolOptionDescription& D,
961 std::ostream& O) {
962 switch (D.Type) {
963 case OptionType::Switch:
964 O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
965 break;
966 case OptionType::Parameter:
967 O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
968 O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
969 break;
970 case OptionType::Prefix:
971 O << Indent3 << "vec.push_back(\"-" << D.Name << "\" + "
972 << D.GenVariableName() << ");\n";
973 break;
974 case OptionType::PrefixList:
975 O << Indent3 << "for (" << D.GenTypeDeclaration()
976 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
977 << Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
978 << Indent4 << "vec.push_back(\"-" << D.Name << "\" + "
979 << "*B);\n";
980 break;
981 case OptionType::ParameterList:
982 O << Indent3 << "for (" << D.GenTypeDeclaration()
983 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
984 << Indent3 << "E = " << D.GenVariableName()
985 << ".end() ; B != E; ++B) {\n"
986 << Indent4 << "vec.push_back(\"-" << D.Name << "\");\n"
987 << Indent4 << "vec.push_back(*B);\n"
988 << Indent3 << "}\n";
989 break;
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000990 case OptionType::Alias:
991 default:
992 throw std::string("Aliases are not allowed in tool option descriptions!");
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000993 }
994}
995
Mikhail Glushenkovea6ce492008-05-30 06:15:20 +0000996// ToolOptionHasInterestingProperties - A helper function used by
997// EmitOptionPropertyHandlingCode() that tells us whether we should
998// emit any property handling code at all.
Mikhail Glushenkov31f52152008-05-30 06:10:47 +0000999bool ToolOptionHasInterestingProperties(const ToolOptionDescription& D) {
Mikhail Glushenkovea6ce492008-05-30 06:15:20 +00001000 bool ret = false;
1001 for (OptionPropertyList::const_iterator B = D.Props.begin(),
1002 E = D.Props.end(); B != E; ++B) {
1003 const OptionProperty& OptProp = *B;
1004 if (OptProp.first == OptionPropertyType::AppendCmd)
1005 ret = true;
1006 }
1007 if (D.isForward() || D.isUnpackValues())
1008 ret = true;
1009 return ret;
Mikhail Glushenkov31f52152008-05-30 06:10:47 +00001010}
1011
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001012/// EmitOptionPropertyHandlingCode - Helper function used by
1013/// EmitGenerateActionMethod(). Emits code that handles option
1014/// properties.
Mikhail Glushenkov31f52152008-05-30 06:10:47 +00001015void EmitOptionPropertyHandlingCode (const ToolOptionDescription& D,
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001016 std::ostream& O)
1017{
Mikhail Glushenkov31f52152008-05-30 06:10:47 +00001018 if (!ToolOptionHasInterestingProperties(D))
1019 return;
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001020 // Start of the if-clause.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001021 O << Indent2 << "if (";
1022 if (D.Type == OptionType::Switch)
1023 O << D.GenVariableName();
1024 else
1025 O << '!' << D.GenVariableName() << ".empty()";
1026
1027 O <<") {\n";
1028
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001029 // Handle option properties that take an argument.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001030 for (OptionPropertyList::const_iterator B = D.Props.begin(),
1031 E = D.Props.end(); B!=E; ++B) {
1032 const OptionProperty& val = *B;
1033
1034 switch (val.first) {
1035 // (append_cmd cmd) property
1036 case OptionPropertyType::AppendCmd:
1037 O << Indent3 << "vec.push_back(\"" << val.second << "\");\n";
1038 break;
1039 // Other properties with argument
1040 default:
1041 break;
1042 }
1043 }
1044
1045 // Handle flags
1046
1047 // (forward) property
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001048 if (D.isForward())
1049 EmitForwardOptionPropertyHandlingCode(D, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001050
1051 // (unpack_values) property
1052 if (D.isUnpackValues()) {
1053 if (IsListOptionType(D.Type)) {
1054 O << Indent3 << "for (" << D.GenTypeDeclaration()
1055 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1056 << Indent3 << "E = " << D.GenVariableName()
1057 << ".end(); B != E; ++B)\n"
Mikhail Glushenkov028f18e2008-05-06 18:13:45 +00001058 << Indent4 << "llvm::SplitString(*B, vec, \",\");\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001059 }
1060 else if (D.Type == OptionType::Prefix || D.Type == OptionType::Parameter){
Mikhail Glushenkov028f18e2008-05-06 18:13:45 +00001061 O << Indent3 << "llvm::SplitString("
1062 << D.GenVariableName() << ", vec, \",\");\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001063 }
1064 else {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001065 throw std::string("Switches can't have unpack_values property!");
1066 }
1067 }
1068
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001069 // End of the if-clause.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001070 O << Indent2 << "}\n";
1071}
1072
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001073/// SubstituteSpecialCommands - Perform string substitution for $CALL
1074/// and $ENV. Helper function used by EmitCmdLineVecFill().
1075std::string SubstituteSpecialCommands(const std::string& cmd) {
Mikhail Glushenkov1e453b02008-05-30 06:13:29 +00001076 size_t cparen = cmd.find(")");
1077 std::string ret;
1078
1079 if (cmd.find("$CALL(") == 0) {
1080 if (cmd.size() == 6)
1081 throw std::string("$CALL invocation: empty argument list!");
1082
1083 ret += "hooks::";
1084 ret += std::string(cmd.begin() + 6, cmd.begin() + cparen);
1085 ret += "()";
1086 }
1087 else if (cmd.find("$ENV(") == 0) {
1088 if (cmd.size() == 5)
1089 throw std::string("$ENV invocation: empty argument list!");
1090
1091 ret += "std::getenv(\"";
1092 ret += std::string(cmd.begin() + 5, cmd.begin() + cparen);
1093 ret += "\")";
1094 }
1095 else {
1096 throw "Unknown special command: " + cmd;
1097 }
1098
1099 if (cmd.begin() + cparen + 1 != cmd.end()) {
1100 ret += " + std::string(\"";
1101 ret += (cmd.c_str() + cparen + 1);
1102 ret += "\")";
1103 }
1104
1105 return ret;
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001106}
1107
1108/// EmitCmdLineVecFill - Emit code that fills in the command line
1109/// vector. Helper function used by EmitGenerateActionMethod().
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001110void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1111 bool Version, const char* IndentLevel,
1112 std::ostream& O) {
1113 StrVector StrVec;
Mikhail Glushenkov1e453b02008-05-30 06:13:29 +00001114 SplitString(InitPtrToString(CmdLine), StrVec);
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001115 if (StrVec.empty())
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001116 throw "Tool " + ToolName + " has empty command line!";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001117
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001118 StrVector::const_iterator I = StrVec.begin();
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001119 ++I;
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001120 for (StrVector::const_iterator E = StrVec.end(); I != E; ++I) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001121 const std::string& cmd = *I;
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001122 O << IndentLevel;
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001123 if (cmd.at(0) == '$') {
1124 if (cmd == "$INFILE") {
1125 if (Version)
1126 O << "for (PathVector::const_iterator B = inFiles.begin()"
1127 << ", E = inFiles.end();\n"
1128 << IndentLevel << "B != E; ++B)\n"
1129 << IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
1130 else
1131 O << "vec.push_back(inFile.toString());\n";
1132 }
1133 else if (cmd == "$OUTFILE") {
1134 O << "vec.push_back(outFile.toString());\n";
1135 }
1136 else {
Mikhail Glushenkov1e453b02008-05-30 06:13:29 +00001137 O << "vec.push_back(" << SubstituteSpecialCommands(cmd);
1138 O << ");\n";
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001139 }
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001140 }
1141 else {
1142 O << "vec.push_back(\"" << cmd << "\");\n";
1143 }
1144 }
Mikhail Glushenkov52a54132008-05-30 06:23:29 +00001145 O << IndentLevel << "cmd = "
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001146 << ((StrVec[0][0] == '$') ? SubstituteSpecialCommands(StrVec[0])
1147 : "\"" + StrVec[0] + "\"")
Mikhail Glushenkov52a54132008-05-30 06:23:29 +00001148 << ";\n";
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001149}
1150
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001151/// EmitCmdLineVecFillCallback - A function object wrapper around
1152/// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1153/// argument to EmitCaseConstructHandler().
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001154class EmitCmdLineVecFillCallback {
1155 bool Version;
1156 const std::string& ToolName;
1157 public:
1158 EmitCmdLineVecFillCallback(bool Ver, const std::string& TN)
1159 : Version(Ver), ToolName(TN) {}
1160
1161 void operator()(const Init* Statement, const char* IndentLevel,
1162 std::ostream& O) const
1163 {
Mikhail Glushenkov31f52152008-05-30 06:10:47 +00001164 EmitCmdLineVecFill(Statement, ToolName, Version,
1165 (std::string(IndentLevel) + Indent1).c_str(), O);
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001166 }
1167};
1168
1169// EmitGenerateActionMethod - Emit one of two versions of the
1170// Tool::GenerateAction() method.
1171void EmitGenerateActionMethod (const ToolProperties& P,
1172 const GlobalOptionDescriptions& OptDescs,
1173 bool Version, std::ostream& O) {
1174 if (Version)
1175 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
1176 else
1177 O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
1178
1179 O << Indent2 << "const sys::Path& outFile,\n"
1180 << Indent2 << "const InputLanguagesSet& InLangs) const\n"
1181 << Indent1 << "{\n"
Mikhail Glushenkov61923cb2008-05-30 06:24:49 +00001182 << Indent2 << "const char* cmd;\n"
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001183 << Indent2 << "std::vector<std::string> vec;\n";
1184
1185 // cmd_line is either a string or a 'case' construct.
1186 if (typeid(*P.CmdLine) == typeid(StringInit))
1187 EmitCmdLineVecFill(P.CmdLine, P.Name, Version, Indent2, O);
1188 else
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001189 EmitCaseConstructHandler(&InitPtrToDag(P.CmdLine), Indent2,
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001190 EmitCmdLineVecFillCallback(Version, P.Name),
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001191 true, OptDescs, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001192
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001193 // For every understood option, emit handling code.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001194 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1195 E = P.OptDescs.end(); B != E; ++B) {
1196 const ToolOptionDescription& val = B->second;
Mikhail Glushenkov31f52152008-05-30 06:10:47 +00001197 EmitOptionPropertyHandlingCode(val, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001198 }
1199
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001200 // Handle the Sink property.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001201 if (P.isSink()) {
1202 O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
1203 << Indent3 << "vec.insert(vec.end(), "
1204 << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
1205 << Indent2 << "}\n";
1206 }
1207
Mikhail Glushenkov52a54132008-05-30 06:23:29 +00001208 O << Indent2 << "return Action(cmd, vec);\n"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001209 << Indent1 << "}\n\n";
1210}
1211
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001212/// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1213/// a given Tool class.
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001214void EmitGenerateActionMethods (const ToolProperties& P,
1215 const GlobalOptionDescriptions& OptDescs,
1216 std::ostream& O) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001217 if (!P.isJoin())
1218 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001219 << Indent2 << "const llvm::sys::Path& outFile,\n"
1220 << Indent2 << "const InputLanguagesSet& InLangs) const\n"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001221 << Indent1 << "{\n"
1222 << Indent2 << "throw std::runtime_error(\"" << P.Name
1223 << " is not a Join tool!\");\n"
1224 << Indent1 << "}\n\n";
1225 else
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001226 EmitGenerateActionMethod(P, OptDescs, true, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001227
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001228 EmitGenerateActionMethod(P, OptDescs, false, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001229}
1230
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001231/// EmitIsLastMethod - Emit the IsLast() method for a given Tool
1232/// class.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001233void EmitIsLastMethod (const ToolProperties& P, std::ostream& O) {
1234 O << Indent1 << "bool IsLast() const {\n"
1235 << Indent2 << "bool last = false;\n";
1236
1237 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1238 E = P.OptDescs.end(); B != E; ++B) {
1239 const ToolOptionDescription& val = B->second;
1240
1241 if (val.isStopCompilation())
1242 O << Indent2
1243 << "if (" << val.GenVariableName()
1244 << ")\n" << Indent3 << "last = true;\n";
1245 }
1246
1247 O << Indent2 << "return last;\n"
1248 << Indent1 << "}\n\n";
1249}
1250
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001251/// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1252/// methods for a given Tool class.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001253void EmitInOutLanguageMethods (const ToolProperties& P, std::ostream& O) {
Mikhail Glushenkov61923cb2008-05-30 06:24:49 +00001254 O << Indent1 << "const char** InputLanguages() const {\n"
1255 << Indent2 << "return InputLanguages_;\n"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001256 << Indent1 << "}\n\n";
1257
Mikhail Glushenkovd379d162008-05-06 17:24:26 +00001258 O << Indent1 << "const char* OutputLanguage() const {\n"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001259 << Indent2 << "return \"" << P.OutLanguage << "\";\n"
1260 << Indent1 << "}\n\n";
1261}
1262
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001263/// EmitOutputSuffixMethod - Emit the OutputSuffix() method for a
1264/// given Tool class.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001265void EmitOutputSuffixMethod (const ToolProperties& P, std::ostream& O) {
Mikhail Glushenkovd379d162008-05-06 17:24:26 +00001266 O << Indent1 << "const char* OutputSuffix() const {\n"
Mikhail Glushenkovabab33b2008-05-30 06:13:02 +00001267 << Indent2 << "const char* ret = \"" << P.OutputSuffix << "\";\n";
1268
1269 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1270 E = P.OptDescs.end(); B != E; ++B) {
1271 const ToolOptionDescription& OptDesc = B->second;
1272 for (OptionPropertyList::const_iterator B = OptDesc.Props.begin(),
1273 E = OptDesc.Props.end(); B != E; ++B) {
1274 const OptionProperty& OptProp = *B;
1275 if (OptProp.first == OptionPropertyType::OutputSuffix) {
1276 O << Indent2 << "if (" << OptDesc.GenVariableName() << ")\n"
1277 << Indent3 << "ret = \"" << OptProp.second << "\";\n";
1278 }
1279 }
1280 }
1281
1282 O << Indent2 << "return ret;\n"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001283 << Indent1 << "}\n\n";
1284}
1285
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001286/// EmitNameMethod - Emit the Name() method for a given Tool class.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001287void EmitNameMethod (const ToolProperties& P, std::ostream& O) {
Mikhail Glushenkovd379d162008-05-06 17:24:26 +00001288 O << Indent1 << "const char* Name() const {\n"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001289 << Indent2 << "return \"" << P.Name << "\";\n"
1290 << Indent1 << "}\n\n";
1291}
1292
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001293/// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1294/// class.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001295void EmitIsJoinMethod (const ToolProperties& P, std::ostream& O) {
1296 O << Indent1 << "bool IsJoin() const {\n";
1297 if (P.isJoin())
1298 O << Indent2 << "return true;\n";
1299 else
1300 O << Indent2 << "return false;\n";
1301 O << Indent1 << "}\n\n";
1302}
1303
Mikhail Glushenkov61923cb2008-05-30 06:24:49 +00001304/// EmitStaticMemberDefinitions - Emit static member definitions for a
1305/// given Tool class.
1306void EmitStaticMemberDefinitions(const ToolProperties& P, std::ostream& O) {
1307 O << "const char* " << P.Name << "::InputLanguages_[] = {";
1308 for (StrVector::const_iterator B = P.InLanguage.begin(),
1309 E = P.InLanguage.end(); B != E; ++B)
1310 O << '\"' << *B << "\", ";
1311 O << "0};\n\n";
1312}
1313
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001314/// EmitToolClassDefinition - Emit a Tool class definition.
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001315void EmitToolClassDefinition (const ToolProperties& P,
1316 const GlobalOptionDescriptions& OptDescs,
1317 std::ostream& O) {
1318 if (P.Name == "root")
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001319 return;
1320
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001321 // Header
Mikhail Glushenkov121889c2008-05-06 17:26:53 +00001322 O << "class " << P.Name << " : public ";
1323 if (P.isJoin())
1324 O << "JoinTool";
1325 else
1326 O << "Tool";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001327
Mikhail Glushenkov61923cb2008-05-30 06:24:49 +00001328 O << "{\nprivate:\n"
1329 << Indent1 << "static const char* InputLanguages_[];\n\n";
1330
1331 O << "public:\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001332 EmitNameMethod(P, O);
1333 EmitInOutLanguageMethods(P, O);
1334 EmitOutputSuffixMethod(P, O);
1335 EmitIsJoinMethod(P, O);
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001336 EmitGenerateActionMethods(P, OptDescs, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001337 EmitIsLastMethod(P, O);
1338
1339 // Close class definition
Mikhail Glushenkov61923cb2008-05-30 06:24:49 +00001340 O << "};\n";
1341
1342 EmitStaticMemberDefinitions(P, O);
1343
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001344}
1345
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001346/// EmitOptionDescriptions - Iterate over a list of option
1347/// descriptions and emit registration code.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001348void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
1349 std::ostream& O)
1350{
Mikhail Glushenkovb623c322008-05-30 06:22:52 +00001351 std::vector<GlobalOptionDescription> Aliases;
1352
Mikhail Glushenkov52a54132008-05-30 06:23:29 +00001353 // Emit static cl::Option variables.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001354 for (GlobalOptionDescriptions::const_iterator B = descs.begin(),
1355 E = descs.end(); B!=E; ++B) {
1356 const GlobalOptionDescription& val = B->second;
1357
Mikhail Glushenkovb623c322008-05-30 06:22:52 +00001358 if (val.Type == OptionType::Alias) {
1359 Aliases.push_back(val);
1360 continue;
1361 }
1362
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001363 O << val.GenTypeDeclaration() << ' '
1364 << val.GenVariableName()
1365 << "(\"" << val.Name << '\"';
1366
1367 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1368 O << ", cl::Prefix";
1369
1370 if (val.isRequired()) {
1371 switch (val.Type) {
1372 case OptionType::PrefixList:
1373 case OptionType::ParameterList:
1374 O << ", cl::OneOrMore";
1375 break;
1376 default:
1377 O << ", cl::Required";
1378 }
1379 }
1380
Mikhail Glushenkovb623c322008-05-30 06:22:52 +00001381 if (!val.Help.empty())
1382 O << ", cl::desc(\"" << val.Help << "\")";
1383
1384 O << ");\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001385 }
1386
Mikhail Glushenkovb623c322008-05-30 06:22:52 +00001387 // Emit the aliases (they should go after all the 'proper' options).
1388 for (std::vector<GlobalOptionDescription>::const_iterator
1389 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
1390 const GlobalOptionDescription& val = *B;
1391
1392 O << val.GenTypeDeclaration() << ' '
1393 << val.GenVariableName()
1394 << "(\"" << val.Name << '\"';
1395
1396 GlobalOptionDescriptions::container_type
1397 ::const_iterator F = descs.Descriptions.find(val.Help);
1398 if (F != descs.Descriptions.end())
1399 O << ", cl::aliasopt(" << F->second.GenVariableName() << ")";
1400 else
1401 throw val.Name + ": alias to an unknown option!";
1402
1403 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
1404 }
1405
1406 // Emit the sink option.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001407 if (descs.HasSink)
1408 O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
1409
1410 O << '\n';
1411}
1412
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001413/// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001414void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
1415{
1416 // Get the relevant field out of RecordKeeper
1417 Record* LangMapRecord = Records.getDef("LanguageMap");
1418 if (!LangMapRecord)
1419 throw std::string("Language map definition not found!");
1420
1421 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
1422 if (!LangsToSuffixesList)
1423 throw std::string("Error in the language map definition!");
1424
1425 // Generate code
Mikhail Glushenkov242d0e62008-05-30 06:19:52 +00001426 O << "void llvmc::PopulateLanguageMap() {\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001427
1428 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
1429 Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
1430
1431 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
1432 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
1433
1434 for (unsigned i = 0; i < Suffixes->size(); ++i)
Mikhail Glushenkov242d0e62008-05-30 06:19:52 +00001435 O << Indent1 << "GlobalLanguageMap[\""
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001436 << InitPtrToString(Suffixes->getElement(i))
1437 << "\"] = \"" << Lang << "\";\n";
1438 }
1439
1440 O << "}\n\n";
1441}
1442
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001443/// FillInToolToLang - Fills in two tables that map tool names to
1444/// (input, output) languages. Used by the typechecker.
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001445void FillInToolToLang (const ToolPropertiesList& TPList,
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001446 StringMap<StringSet<> >& ToolToInLang,
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001447 StringMap<std::string>& ToolToOutLang) {
1448 for (ToolPropertiesList::const_iterator B = TPList.begin(), E = TPList.end();
1449 B != E; ++B) {
1450 const ToolProperties& P = *(*B);
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001451 for (StrVector::const_iterator B = P.InLanguage.begin(),
1452 E = P.InLanguage.end(); B != E; ++B)
1453 ToolToInLang[P.Name].insert(*B);
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001454 ToolToOutLang[P.Name] = P.OutLanguage;
1455 }
1456}
1457
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001458/// TypecheckGraph - Check that names for output and input languages
1459/// on all edges do match.
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001460// TOFIX: It would be nice if this function also checked for cycles
1461// and multiple default edges in the graph (better error
1462// reporting). Unfortunately, it is awkward to do right now because
1463// our intermediate representation is not sufficiently
Mikhail Glushenkovc178ead2008-09-22 20:45:17 +00001464// sophisticated. Algorithms like these require a real graph instead of
1465// an AST.
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001466void TypecheckGraph (Record* CompilationGraph,
1467 const ToolPropertiesList& TPList) {
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001468 StringMap<StringSet<> > ToolToInLang;
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001469 StringMap<std::string> ToolToOutLang;
1470
1471 FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
1472 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001473 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
1474 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001475
1476 for (unsigned i = 0; i < edges->size(); ++i) {
1477 Record* Edge = edges->getElementAsRecord(i);
1478 Record* A = Edge->getValueAsDef("a");
1479 Record* B = Edge->getValueAsDef("b");
1480 StringMap<std::string>::iterator IA = ToolToOutLang.find(A->getName());
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001481 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(B->getName());
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001482 if (IA == IAE)
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001483 throw A->getName() + ": no such tool!";
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001484 if (IB == IBE)
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001485 throw B->getName() + ": no such tool!";
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001486 if (A->getName() != "root" && IB->second.count(IA->second) == 0)
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001487 throw "Edge " + A->getName() + "->" + B->getName()
1488 + ": output->input language mismatch";
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001489 if (B->getName() == "root")
Mikhail Glushenkov761958d2008-05-06 16:36:50 +00001490 throw std::string("Edges back to the root are not allowed!");
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001491 }
1492}
1493
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001494/// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
1495/// by EmitEdgeClass().
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001496void IncDecWeight (const Init* i, const char* IndentLevel,
1497 std::ostream& O) {
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001498 const DagInit& d = InitPtrToDag(i);
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001499 const std::string& OpName = d.getOperator()->getAsString();
1500
1501 if (OpName == "inc_weight")
1502 O << IndentLevel << Indent1 << "ret += ";
1503 else if (OpName == "dec_weight")
1504 O << IndentLevel << Indent1 << "ret -= ";
1505 else
1506 throw "Unknown operator in edge properties list: " + OpName + '!';
1507
1508 if (d.getNumArgs() > 0)
1509 O << InitPtrToInt(d.getArg(0)) << ";\n";
1510 else
1511 O << "2;\n";
1512
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +00001513}
1514
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001515/// EmitEdgeClass - Emit a single Edge# class.
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001516void EmitEdgeClass (unsigned N, const std::string& Target,
1517 DagInit* Case, const GlobalOptionDescriptions& OptDescs,
1518 std::ostream& O) {
Mikhail Glushenkov8d0d5d22008-05-06 17:23:14 +00001519
1520 // Class constructor.
1521 O << "class Edge" << N << ": public Edge {\n"
1522 << "public:\n"
1523 << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1524 << "\") {}\n\n"
1525
Mikhail Glushenkov7dbc0ab2008-05-06 18:14:24 +00001526 // Function Weight().
Mikhail Glushenkovd6228882008-05-06 18:15:12 +00001527 << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
Mikhail Glushenkov7dbc0ab2008-05-06 18:14:24 +00001528 << Indent2 << "unsigned ret = 0;\n";
Mikhail Glushenkov8d0d5d22008-05-06 17:23:14 +00001529
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001530 // Handle the 'case' construct.
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001531 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
Mikhail Glushenkov7dbc0ab2008-05-06 18:14:24 +00001532
1533 O << Indent2 << "return ret;\n"
1534 << Indent1 << "};\n\n};\n\n";
Mikhail Glushenkov8d0d5d22008-05-06 17:23:14 +00001535}
1536
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001537/// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001538void EmitEdgeClasses (Record* CompilationGraph,
1539 const GlobalOptionDescriptions& OptDescs,
1540 std::ostream& O) {
1541 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1542
1543 for (unsigned i = 0; i < edges->size(); ++i) {
Mikhail Glushenkov761958d2008-05-06 16:36:50 +00001544 Record* Edge = edges->getElementAsRecord(i);
1545 Record* B = Edge->getValueAsDef("b");
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001546 DagInit* Weight = Edge->getValueAsDag("weight");
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001547
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001548 if (isDagEmpty(Weight))
Mikhail Glushenkov761958d2008-05-06 16:36:50 +00001549 continue;
1550
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001551 EmitEdgeClass(i, B->getName(), Weight, OptDescs, O);
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001552 }
1553}
1554
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001555/// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1556/// function.
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001557void EmitPopulateCompilationGraph (Record* CompilationGraph,
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001558 std::ostream& O)
1559{
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001560 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001561
1562 // Generate code
Mikhail Glushenkov34307a92008-05-06 18:08:59 +00001563 O << "void llvmc::PopulateCompilationGraph(CompilationGraph& G) {\n"
Mikhail Glushenkov242d0e62008-05-30 06:19:52 +00001564 << Indent1 << "PopulateLanguageMap();\n\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001565
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001566 // Insert vertices
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001567
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001568 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1569 if (Tools.empty())
1570 throw std::string("No tool definitions found!");
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001571
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001572 for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
1573 const std::string& Name = (*B)->getName();
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001574 if (Name != "root")
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001575 O << Indent1 << "G.insertNode(new "
1576 << Name << "());\n";
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001577 }
1578
1579 O << '\n';
1580
1581 // Insert edges
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001582 for (unsigned i = 0; i < edges->size(); ++i) {
1583 Record* Edge = edges->getElementAsRecord(i);
1584 Record* A = Edge->getValueAsDef("a");
1585 Record* B = Edge->getValueAsDef("b");
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001586 DagInit* Weight = Edge->getValueAsDag("weight");
Mikhail Glushenkov761958d2008-05-06 16:36:50 +00001587
1588 O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
1589
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001590 if (isDagEmpty(Weight))
Mikhail Glushenkov761958d2008-05-06 16:36:50 +00001591 O << "new SimpleEdge(\"" << B->getName() << "\")";
1592 else
1593 O << "new Edge" << i << "()";
1594
1595 O << ");\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001596 }
1597
1598 O << "}\n\n";
1599}
1600
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001601/// ExtractHookNames - Extract the hook names from all instances of
1602/// $CALL(HookName) in the provided command line string. Helper
1603/// function used by FillInHookNames().
1604void ExtractHookNames(const Init* CmdLine, StrVector& HookNames) {
1605 StrVector cmds;
Mikhail Glushenkov1e453b02008-05-30 06:13:29 +00001606 llvm::SplitString(InitPtrToString(CmdLine), cmds);
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001607 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
1608 B != E; ++B) {
1609 const std::string& cmd = *B;
1610 if (cmd.find("$CALL(") == 0) {
1611 if (cmd.size() == 6)
1612 throw std::string("$CALL invocation: empty argument list!");
Mikhail Glushenkov1e453b02008-05-30 06:13:29 +00001613 HookNames.push_back(std::string(cmd.begin() + 6,
1614 cmd.begin() + cmd.find(")")));
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001615 }
1616 }
1617}
1618
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001619/// ExtractHookNamesFromCaseConstruct - Extract hook names from the
1620/// 'case' expression, handle nesting. Helper function used by
1621/// FillInHookNames().
1622void ExtractHookNamesFromCaseConstruct(Init* Case, StrVector& HookNames) {
1623 const DagInit& d = InitPtrToDag(Case);
1624 bool even = false;
1625 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1626 B != E; ++B) {
1627 Init* arg = *B;
1628 if (even && dynamic_cast<DagInit*>(arg)
1629 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
1630 ExtractHookNamesFromCaseConstruct(arg, HookNames);
1631 else if (even)
1632 ExtractHookNames(arg, HookNames);
1633 even = !even;
1634 }
1635}
1636
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001637/// FillInHookNames - Actually extract the hook names from all command
1638/// line strings. Helper function used by EmitHookDeclarations().
1639void FillInHookNames(const ToolPropertiesList& TPList,
1640 StrVector& HookNames) {
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001641 // For all command lines:
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001642 for (ToolPropertiesList::const_iterator B = TPList.begin(),
1643 E = TPList.end(); B != E; ++B) {
1644 const ToolProperties& P = *(*B);
1645 if (!P.CmdLine)
1646 continue;
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001647 if (dynamic_cast<StringInit*>(P.CmdLine))
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001648 // This is a string.
1649 ExtractHookNames(P.CmdLine, HookNames);
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001650 else
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001651 // This is a 'case' construct.
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001652 ExtractHookNamesFromCaseConstruct(P.CmdLine, HookNames);
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001653 }
1654}
1655
1656/// EmitHookDeclarations - Parse CmdLine fields of all the tool
1657/// property records and emit hook function declaration for each
1658/// instance of $CALL(HookName).
1659void EmitHookDeclarations(const ToolPropertiesList& ToolProps,
1660 std::ostream& O) {
1661 StrVector HookNames;
1662 FillInHookNames(ToolProps, HookNames);
1663 if (HookNames.empty())
1664 return;
1665 std::sort(HookNames.begin(), HookNames.end());
1666 StrVector::const_iterator E = std::unique(HookNames.begin(), HookNames.end());
1667
1668 O << "namespace hooks {\n";
1669 for (StrVector::const_iterator B = HookNames.begin(); B != E; ++B)
1670 O << Indent1 << "std::string " << *B << "();\n";
1671
1672 O << "}\n\n";
1673}
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001674
1675// End of anonymous namespace
Mikhail Glushenkovc1f738d2008-05-06 18:12:03 +00001676}
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001677
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001678/// run - The back-end entry point.
Mikhail Glushenkovc1f738d2008-05-06 18:12:03 +00001679void LLVMCConfigurationEmitter::run (std::ostream &O) {
Mikhail Glushenkovffe736e2008-05-30 06:21:48 +00001680 try {
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001681
1682 // Emit file header.
Mikhail Glushenkov34307a92008-05-06 18:08:59 +00001683 EmitSourceFileHeader("LLVMC Configuration Library", O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001684
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001685 // Get a list of all defined Tools.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001686 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1687 if (Tools.empty())
1688 throw std::string("No tool definitions found!");
1689
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001690 // Gather information from the Tool description dags.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001691 ToolPropertiesList tool_props;
1692 GlobalOptionDescriptions opt_descs;
1693 CollectToolProperties(Tools.begin(), Tools.end(), tool_props, opt_descs);
1694
Mikhail Glushenkovd638e852008-05-30 06:26:08 +00001695 RecordVector OptionLists = Records.getAllDerivedDefinitions("OptionList");
1696 CollectPropertiesFromOptionList(OptionLists.begin(), OptionLists.end(),
1697 opt_descs);
1698
Mikhail Glushenkove5fcb552008-05-30 06:28:37 +00001699 // Check that there are no options without side effects (specified
1700 // only in the OptionList).
1701 CheckForSuperfluousOptions(tool_props, opt_descs);
1702
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001703 // Emit global option registration code.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001704 EmitOptionDescriptions(opt_descs, O);
1705
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001706 // Emit hook declarations.
1707 EmitHookDeclarations(tool_props, O);
1708
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001709 // Emit PopulateLanguageMap() function
1710 // (a language map maps from file extensions to language names).
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001711 EmitPopulateLanguageMap(Records, O);
1712
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001713 // Emit Tool classes.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001714 for (ToolPropertiesList::const_iterator B = tool_props.begin(),
1715 E = tool_props.end(); B!=E; ++B)
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001716 EmitToolClassDefinition(*(*B), opt_descs, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001717
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001718 Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
1719 if (!CompilationGraphRecord)
1720 throw std::string("Compilation graph description not found!");
1721
1722 // Typecheck the compilation graph.
1723 TypecheckGraph(CompilationGraphRecord, tool_props);
1724
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001725 // Emit Edge# classes.
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001726 EmitEdgeClasses(CompilationGraphRecord, opt_descs, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001727
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001728 // Emit PopulateCompilationGraph() function.
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001729 EmitPopulateCompilationGraph(CompilationGraphRecord, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001730
1731 // EOF
Mikhail Glushenkovffe736e2008-05-30 06:21:48 +00001732 } catch (std::exception& Error) {
1733 throw Error.what() + std::string(" - usually this means a syntax error.");
1734 }
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001735}