-//===- LLVMCConfigurationEmitter.cpp - Generate LLVMC config --------------===//
+//===- LLVMCConfigurationEmitter.cpp - Generate LLVMC config ----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringMap.h"
+#include "llvm/ADT/StringSet.h"
#include "llvm/Support/Streams.h"
-
#include <algorithm>
#include <cassert>
#include <functional>
+#include <stdexcept>
#include <string>
-
+#include <typeinfo>
using namespace llvm;
namespace {
//===----------------------------------------------------------------------===//
/// Constants
-// Indentation strings
+// Indentation strings.
const char * Indent1 = " ";
const char * Indent2 = " ";
const char * Indent3 = " ";
const char * Indent4 = " ";
-// Default help string
+// Default help string.
const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
-// Name for the "sink" option
+// Name for the "sink" option.
const char * SinkOptionName = "AutoGeneratedSinkOption";
//===----------------------------------------------------------------------===//
/// Helper functions
-std::string InitPtrToString(Init* ptr) {
- StringInit& val = dynamic_cast<StringInit&>(*ptr);
+int InitPtrToInt(const Init* ptr) {
+ const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
return val.getValue();
}
-// Ensure that the number of args in d is <= min_arguments,
-// throw exception otherwise
+const std::string& InitPtrToString(const Init* ptr) {
+ const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
+ return val.getValue();
+}
+
+const ListInit& InitPtrToList(const Init* ptr) {
+ const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
+ return val;
+}
+
+const DagInit& InitPtrToDag(const Init* ptr) {
+ const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
+ return val;
+}
+
+// checkNumberOfArguments - Ensure that the number of args in d is
+// less than or equal to min_arguments, otherwise throw an exception.
void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
if (d->getNumArgs() < min_arguments)
throw "Property " + d->getOperator()->getAsString()
+ " has too few arguments!";
}
+// isDagEmpty - is this DAG marked with an empty marker?
+bool isDagEmpty (const DagInit* d) {
+ return d->getOperator()->getAsString() == "empty";
+}
//===----------------------------------------------------------------------===//
/// Back-end specific code
// A command-line option can have one of the following types:
//
-// Switch - a simple switch w/o arguments, e.g. -O2
+// Alias - an alias for another option.
+//
+// Switch - a simple switch without arguments, e.g. -O2
//
// Parameter - an option that takes one(and only one) argument, e.g. -o file,
// --output=file
// e.g. -Wa,-foo,-bar, -DNAME=VALUE
//
// PrefixList - same as Prefix, but more than one option occurence is
-// allowed
+// allowed.
namespace OptionType {
- enum OptionType { Switch, Parameter, ParameterList, Prefix, PrefixList};
+ enum OptionType { Alias, Switch,
+ Parameter, ParameterList, Prefix, PrefixList};
}
bool IsListOptionType (OptionType::OptionType t) {
// the option registration code, while ToolOptionDescriptions are used
// to generate tool-specific code.
-// Base class for option descriptions
-
+/// OptionDescription - Base class for option descriptions.
struct OptionDescription {
OptionType::OptionType Type;
std::string Name;
const char* GenTypeDeclaration() const {
switch (Type) {
+ case OptionType::Alias:
+ return "cl::alias";
case OptionType::PrefixList:
case OptionType::ParameterList:
return "cl::list<std::string>";
}
}
+ // Escape commas and other symbols not allowed in the C++ variable
+ // names. Makes it possible to use options with names like "Wa,"
+ // (useful for prefix options).
+ std::string EscapeVariableName(const std::string& Var) const {
+ std::string ret;
+ for (unsigned i = 0; i != Var.size(); ++i) {
+ if (Var[i] == ',') {
+ ret += "_comma_";
+ }
+ else {
+ ret.push_back(Var[i]);
+ }
+ }
+ return ret;
+ }
+
std::string GenVariableName() const {
+ const std::string& EscapedName = EscapeVariableName(Name);
switch (Type) {
+ case OptionType::Alias:
+ return "AutoGeneratedAlias" + EscapedName;
case OptionType::Switch:
- return "AutoGeneratedSwitch" + Name;
- case OptionType::Prefix:
- return "AutoGeneratedPrefix" + Name;
- case OptionType::PrefixList:
- return "AutoGeneratedPrefixList" + Name;
- case OptionType::Parameter:
- return "AutoGeneratedParameter" + Name;
- case OptionType::ParameterList:
- default:
- return "AutoGeneratedParameterList" + Name;
- }
+ return "AutoGeneratedSwitch" + EscapedName;
+ case OptionType::Prefix:
+ return "AutoGeneratedPrefix" + EscapedName;
+ case OptionType::PrefixList:
+ return "AutoGeneratedPrefixList" + EscapedName;
+ case OptionType::Parameter:
+ return "AutoGeneratedParameter" + EscapedName;
+ case OptionType::ParameterList:
+ default:
+ return "AutoGeneratedParameterList" + EscapedName;
+ }
}
};
-// Global option description
+// Global option description.
namespace GlobalOptionDescriptionFlags {
enum GlobalOptionDescriptionFlags { Required = 0x1 };
std::string Help;
unsigned Flags;
- // We need t provide a default constructor since
- // StringMap can only store DefaultConstructible objects
+ // We need to provide a default constructor because
+ // StringMap can only store DefaultConstructible objects.
GlobalOptionDescription() : OptionDescription(), Flags(0)
{}
- GlobalOptionDescription (OptionType::OptionType t, const std::string& n)
- : OptionDescription(t, n), Help(DefaultHelpString), Flags(0)
+ GlobalOptionDescription (OptionType::OptionType t, const std::string& n,
+ const std::string& h = DefaultHelpString)
+ : OptionDescription(t, n), Help(h), Flags(0)
{}
bool isRequired() const {
Flags |= GlobalOptionDescriptionFlags::Required;
}
- // Merge two option descriptions
+ /// Merge - Merge two option descriptions.
void Merge (const GlobalOptionDescription& other)
{
if (other.Type != Type)
}
};
-// A GlobalOptionDescription array
-// + some flags affecting generation of option declarations
+/// GlobalOptionDescriptions - A GlobalOptionDescription array
+/// together with some flags affecting generation of option
+/// declarations.
struct GlobalOptionDescriptions {
typedef StringMap<GlobalOptionDescription> container_type;
typedef container_type::const_iterator const_iterator;
- // A list of GlobalOptionDescriptions
+ /// Descriptions - A list of GlobalOptionDescriptions.
container_type Descriptions;
- // Should the emitter generate a "cl::sink" option?
+ /// HasSink - Should the emitter generate a "cl::sink" option?
bool HasSink;
+ /// FindOption - exception-throwing wrapper for find().
const GlobalOptionDescription& FindOption(const std::string& OptName) const {
const_iterator I = Descriptions.find(OptName);
if (I != Descriptions.end())
throw OptName + ": no such option!";
}
+ /// insertDescription - Insert new GlobalOptionDescription into
+ /// GlobalOptionDescriptions list
+ void insertDescription (const GlobalOptionDescription& o)
+ {
+ container_type::iterator I = Descriptions.find(o.Name);
+ if (I != Descriptions.end()) {
+ GlobalOptionDescription& D = I->second;
+ D.Merge(o);
+ }
+ else {
+ Descriptions[o.Name] = o;
+ }
+ }
+
// Support for STL-style iteration
const_iterator begin() const { return Descriptions.begin(); }
const_iterator end() const { return Descriptions.end(); }
};
-// Tool-local option description
+// Tool-local option description.
-// Properties without arguments are implemented as flags
+// Properties without arguments are implemented as flags.
namespace ToolOptionDescriptionFlags {
enum ToolOptionDescriptionFlags { StopCompilation = 0x1,
Forward = 0x2, UnpackValues = 0x4};
}
namespace OptionPropertyType {
- enum OptionPropertyType { AppendCmd };
+ enum OptionPropertyType { AppendCmd, OutputSuffix };
}
typedef std::pair<OptionPropertyType::OptionPropertyType, std::string>
struct ToolProperties : public RefCountedBase<ToolProperties> {
std::string Name;
- StrVector CmdLine;
- std::string InLanguage;
+ Init* CmdLine;
+ StrVector InLanguage;
std::string OutLanguage;
std::string OutputSuffix;
unsigned Flags;
// Default ctor here is needed because StringMap can only store
// DefaultConstructible objects
- ToolProperties() : Flags(0) {}
- ToolProperties (const std::string& n) : Name(n), Flags(0) {}
+ ToolProperties() : CmdLine(0), Flags(0) {}
+ ToolProperties (const std::string& n) : Name(n), CmdLine(0), Flags(0) {}
};
-// A list of Tool information records
-// IntrusiveRefCntPtrs are used because StringMap has no copy constructor
-// (and we want to avoid copying ToolProperties anyway)
+/// ToolPropertiesList - A list of Tool information records
+/// IntrusiveRefCntPtrs are used here because StringMap has no copy
+/// constructor (and we want to avoid copying ToolProperties anyway).
typedef std::vector<IntrusiveRefCntPtr<ToolProperties> > ToolPropertiesList;
-// Function object for iterating over a list of tool property records
-class CollectProperties {
+/// CollectOptionProperties - Function object for iterating over a
+/// list (usually, a DAG) of option property records.
+class CollectOptionProperties {
private:
+ // Implementation details.
- /// Implementation details
+ /// OptionPropertyHandler - a function that extracts information
+ /// about a given option property from its DAG representation.
+ typedef void (CollectOptionProperties::* OptionPropertyHandler)
+ (const DagInit*);
- // "Property handler" - a function that extracts information
- // about a given tool property from its DAG representation
- typedef void (CollectProperties::*PropertyHandler)(DagInit*);
+ /// OptionPropertyHandlerMap - A map from option property names to
+ /// option property handlers
+ typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
- // Map from property names -> property handlers
- typedef StringMap<PropertyHandler> PropertyHandlerMap;
+ static OptionPropertyHandlerMap optionPropertyHandlers_;
+ static bool staticMembersInitialized_;
- // "Option property handler" - a function that extracts information
- // about a given option property from its DAG representation
- typedef void (CollectProperties::*
- OptionPropertyHandler)(DagInit*, GlobalOptionDescription &);
+ /// This is where the information is stored
- // Map from option property names -> option property handlers
- typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
+ /// toolProps_ - Properties of the current Tool.
+ ToolProperties* toolProps_;
+ /// optDescs_ - OptionDescriptions table (used to register options
+ /// globally).
+ GlobalOptionDescription& optDesc_;
+
+public:
+
+ explicit CollectOptionProperties(ToolProperties* TP,
+ GlobalOptionDescription& OD)
+ : toolProps_(TP), optDesc_(OD)
+ {
+ if (!staticMembersInitialized_) {
+ optionPropertyHandlers_["append_cmd"] =
+ &CollectOptionProperties::onAppendCmd;
+ optionPropertyHandlers_["forward"] =
+ &CollectOptionProperties::onForward;
+ optionPropertyHandlers_["help"] =
+ &CollectOptionProperties::onHelp;
+ optionPropertyHandlers_["output_suffix"] =
+ &CollectOptionProperties::onOutputSuffix;
+ optionPropertyHandlers_["required"] =
+ &CollectOptionProperties::onRequired;
+ optionPropertyHandlers_["stop_compilation"] =
+ &CollectOptionProperties::onStopCompilation;
+ optionPropertyHandlers_["unpack_values"] =
+ &CollectOptionProperties::onUnpackValues;
+
+ staticMembersInitialized_ = true;
+ }
+ }
+
+ /// operator() - Gets called for every option property; Just forwards
+ /// to the corresponding property handler.
+ void operator() (Init* i) {
+ const DagInit& option_property = InitPtrToDag(i);
+ const std::string& option_property_name
+ = option_property.getOperator()->getAsString();
+ OptionPropertyHandlerMap::iterator method
+ = optionPropertyHandlers_.find(option_property_name);
+
+ if (method != optionPropertyHandlers_.end()) {
+ OptionPropertyHandler h = method->second;
+ (this->*h)(&option_property);
+ }
+ else {
+ throw "Unknown option property: " + option_property_name + "!";
+ }
+ }
+
+private:
+
+ /// Option property handlers --
+ /// Methods that handle properties that are common for all types of
+ /// options (like append_cmd, stop_compilation)
+
+ void onAppendCmd (const DagInit* d) {
+ checkNumberOfArguments(d, 1);
+ checkToolProps(d);
+ const std::string& cmd = InitPtrToString(d->getArg(0));
+
+ toolProps_->OptDescs[optDesc_.Name].
+ AddProperty(OptionPropertyType::AppendCmd, cmd);
+ }
+
+ void onOutputSuffix (const DagInit* d) {
+ checkNumberOfArguments(d, 1);
+ checkToolProps(d);
+ const std::string& suf = InitPtrToString(d->getArg(0));
+
+ if (toolProps_->OptDescs[optDesc_.Name].Type != OptionType::Switch)
+ throw "Option " + optDesc_.Name
+ + " can't have 'output_suffix' property since it isn't a switch!";
+
+ toolProps_->OptDescs[optDesc_.Name].AddProperty
+ (OptionPropertyType::OutputSuffix, suf);
+ }
+
+ void onForward (const DagInit* d) {
+ checkNumberOfArguments(d, 0);
+ checkToolProps(d);
+ toolProps_->OptDescs[optDesc_.Name].setForward();
+ }
+
+ void onHelp (const DagInit* d) {
+ checkNumberOfArguments(d, 1);
+ const std::string& help_message = InitPtrToString(d->getArg(0));
+
+ optDesc_.Help = help_message;
+ }
+
+ void onRequired (const DagInit* d) {
+ checkNumberOfArguments(d, 0);
+ checkToolProps(d);
+ optDesc_.setRequired();
+ }
+
+ void onStopCompilation (const DagInit* d) {
+ checkNumberOfArguments(d, 0);
+ checkToolProps(d);
+ if (optDesc_.Type != OptionType::Switch)
+ throw std::string("Only options of type Switch can stop compilation!");
+ toolProps_->OptDescs[optDesc_.Name].setStopCompilation();
+ }
+
+ void onUnpackValues (const DagInit* d) {
+ checkNumberOfArguments(d, 0);
+ checkToolProps(d);
+ toolProps_->OptDescs[optDesc_.Name].setUnpackValues();
+ }
+
+ // Helper functions
+
+ /// checkToolProps - Throw an error if toolProps_ == 0.
+ void checkToolProps(const DagInit* d) {
+ if (!d)
+ throw "Option property " + d->getOperator()->getAsString()
+ + " can't be used in this context";
+ }
+
+};
+
+CollectOptionProperties::OptionPropertyHandlerMap
+CollectOptionProperties::optionPropertyHandlers_;
+
+bool CollectOptionProperties::staticMembersInitialized_ = false;
+
+
+/// processOptionProperties - Go through the list of option
+/// properties and call a corresponding handler for each.
+void processOptionProperties (const DagInit* d, ToolProperties* t,
+ GlobalOptionDescription& o) {
+ checkNumberOfArguments(d, 2);
+ DagInit::const_arg_iterator B = d->arg_begin();
+ // Skip the first argument: it's always the option name.
+ ++B;
+ std::for_each(B, d->arg_end(), CollectOptionProperties(t, o));
+}
+
+/// AddOption - A function object wrapper for
+/// processOptionProperties. Used by CollectProperties and
+/// CollectPropertiesFromOptionList.
+class AddOption {
+private:
+ GlobalOptionDescriptions& OptDescs_;
+ ToolProperties* ToolProps_;
+
+public:
+ explicit AddOption(GlobalOptionDescriptions& OD, ToolProperties* TP = 0)
+ : OptDescs_(OD), ToolProps_(TP)
+ {}
+
+ void operator()(const Init* i) {
+ const DagInit& d = InitPtrToDag(i);
+ checkNumberOfArguments(&d, 2);
+
+ const OptionType::OptionType Type =
+ getOptionType(d.getOperator()->getAsString());
+ const std::string& Name = InitPtrToString(d.getArg(0));
+
+ GlobalOptionDescription OD(Type, Name);
+ if (Type != OptionType::Alias) {
+ processOptionProperties(&d, ToolProps_, OD);
+ if (ToolProps_) {
+ ToolProps_->OptDescs[Name].Type = Type;
+ ToolProps_->OptDescs[Name].Name = Name;
+ }
+ }
+ else {
+ OD.Help = InitPtrToString(d.getArg(1));
+ }
+ OptDescs_.insertDescription(OD);
+ }
+
+private:
+ OptionType::OptionType getOptionType(const std::string& T) const {
+ if (T == "alias_option")
+ return OptionType::Alias;
+ else if (T == "switch_option")
+ return OptionType::Switch;
+ else if (T == "parameter_option")
+ return OptionType::Parameter;
+ else if (T == "parameter_list_option")
+ return OptionType::ParameterList;
+ else if (T == "prefix_option")
+ return OptionType::Prefix;
+ else if (T == "prefix_list_option")
+ return OptionType::PrefixList;
+ else
+ throw "Unknown option type: " + T + '!';
+ }
+};
+
+
+/// CollectProperties - Function object for iterating over a list of
+/// tool property records.
+class CollectProperties {
+private:
+
+ // Implementation details
+
+ /// PropertyHandler - a function that extracts information
+ /// about a given tool property from its DAG representation
+ typedef void (CollectProperties::*PropertyHandler)(const DagInit*);
+
+ /// PropertyHandlerMap - A map from property names to property
+ /// handlers.
+ typedef StringMap<PropertyHandler> PropertyHandlerMap;
// Static maps from strings to CollectProperties methods("handlers")
static PropertyHandlerMap propertyHandlers_;
- static OptionPropertyHandlerMap optionPropertyHandlers_;
static bool staticMembersInitialized_;
/// This is where the information is stored
- // Current Tool properties
+ /// toolProps_ - Properties of the current Tool.
ToolProperties& toolProps_;
- // OptionDescriptions table(used to register options globally)
+ /// optDescs_ - OptionDescriptions table (used to register options
+ /// globally).
GlobalOptionDescriptions& optDescs_;
public:
: toolProps_(p), optDescs_(d)
{
if (!staticMembersInitialized_) {
- // Init tool property handlers
propertyHandlers_["cmd_line"] = &CollectProperties::onCmdLine;
propertyHandlers_["in_language"] = &CollectProperties::onInLanguage;
propertyHandlers_["join"] = &CollectProperties::onJoin;
propertyHandlers_["out_language"] = &CollectProperties::onOutLanguage;
propertyHandlers_["output_suffix"] = &CollectProperties::onOutputSuffix;
propertyHandlers_["parameter_option"]
- = &CollectProperties::onParameter;
+ = &CollectProperties::addOption;
propertyHandlers_["parameter_list_option"] =
- &CollectProperties::onParameterList;
- propertyHandlers_["prefix_option"] = &CollectProperties::onPrefix;
+ &CollectProperties::addOption;
+ propertyHandlers_["prefix_option"] = &CollectProperties::addOption;
propertyHandlers_["prefix_list_option"] =
- &CollectProperties::onPrefixList;
+ &CollectProperties::addOption;
propertyHandlers_["sink"] = &CollectProperties::onSink;
- propertyHandlers_["switch_option"] = &CollectProperties::onSwitch;
-
- // Init option property handlers
- optionPropertyHandlers_["append_cmd"] = &CollectProperties::onAppendCmd;
- optionPropertyHandlers_["forward"] = &CollectProperties::onForward;
- optionPropertyHandlers_["help"] = &CollectProperties::onHelp;
- optionPropertyHandlers_["required"] = &CollectProperties::onRequired;
- optionPropertyHandlers_["stop_compilation"] =
- &CollectProperties::onStopCompilation;
- optionPropertyHandlers_["unpack_values"] =
- &CollectProperties::onUnpackValues;
+ propertyHandlers_["switch_option"] = &CollectProperties::addOption;
+ propertyHandlers_["alias_option"] = &CollectProperties::addOption;
staticMembersInitialized_ = true;
}
}
- // Gets called for every tool property;
- // Just forwards to the corresponding property handler.
+ /// operator() - Gets called for every tool property; Just forwards
+ /// to the corresponding property handler.
void operator() (Init* i) {
- DagInit& d = dynamic_cast<DagInit&>(*i);
+ const DagInit& d = InitPtrToDag(i);
const std::string& property_name = d.getOperator()->getAsString();
PropertyHandlerMap::iterator method
= propertyHandlers_.find(property_name);
/// Functions that extract information about tool properties from
/// DAG representation.
- void onCmdLine (DagInit* d) {
+ void onCmdLine (const DagInit* d) {
checkNumberOfArguments(d, 1);
- SplitString(InitPtrToString(d->getArg(0)), toolProps_.CmdLine);
- if (toolProps_.CmdLine.empty())
- throw "Tool " + toolProps_.Name + " has empty command line!";
+ toolProps_.CmdLine = d->getArg(0);
}
- void onInLanguage (DagInit* d) {
+ void onInLanguage (const DagInit* d) {
checkNumberOfArguments(d, 1);
- toolProps_.InLanguage = InitPtrToString(d->getArg(0));
+ Init* arg = d->getArg(0);
+
+ // Find out the argument's type.
+ if (typeid(*arg) == typeid(StringInit)) {
+ // It's a string.
+ toolProps_.InLanguage.push_back(InitPtrToString(arg));
+ }
+ else {
+ // It's a list.
+ const ListInit& lst = InitPtrToList(arg);
+ StrVector& out = toolProps_.InLanguage;
+
+ // Copy strings to the output vector.
+ for (ListInit::const_iterator B = lst.begin(), E = lst.end();
+ B != E; ++B) {
+ out.push_back(InitPtrToString(*B));
+ }
+
+ // Remove duplicates.
+ std::sort(out.begin(), out.end());
+ StrVector::iterator newE = std::unique(out.begin(), out.end());
+ out.erase(newE, out.end());
+ }
}
- void onJoin (DagInit* d) {
+ void onJoin (const DagInit* d) {
checkNumberOfArguments(d, 0);
toolProps_.setJoin();
}
- void onOutLanguage (DagInit* d) {
+ void onOutLanguage (const DagInit* d) {
checkNumberOfArguments(d, 1);
toolProps_.OutLanguage = InitPtrToString(d->getArg(0));
}
- void onOutputSuffix (DagInit* d) {
+ void onOutputSuffix (const DagInit* d) {
checkNumberOfArguments(d, 1);
toolProps_.OutputSuffix = InitPtrToString(d->getArg(0));
}
- void onSink (DagInit* d) {
+ void onSink (const DagInit* d) {
checkNumberOfArguments(d, 0);
optDescs_.HasSink = true;
toolProps_.setSink();
}
- void onSwitch (DagInit* d) { addOption(d, OptionType::Switch); }
- void onParameter (DagInit* d) { addOption(d, OptionType::Parameter); }
- void onParameterList (DagInit* d) { addOption(d, OptionType::ParameterList); }
- void onPrefix (DagInit* d) { addOption(d, OptionType::Prefix); }
- void onPrefixList (DagInit* d) { addOption(d, OptionType::PrefixList); }
+ // Just forwards to the AddOption function object. Somewhat
+ // non-optimal, but avoids code duplication.
+ void addOption (const DagInit* d) {
+ checkNumberOfArguments(d, 2);
+ AddOption(optDescs_, &toolProps_)(d);
+ }
- /// Option property handlers --
- /// Methods that handle properties that are common for all types of
- /// options (like append_cmd, stop_compilation)
+};
- void onAppendCmd (DagInit* d, GlobalOptionDescription& o) {
- checkNumberOfArguments(d, 1);
- std::string const& cmd = InitPtrToString(d->getArg(0));
+// Defintions of static members of CollectProperties.
+CollectProperties::PropertyHandlerMap CollectProperties::propertyHandlers_;
+bool CollectProperties::staticMembersInitialized_ = false;
- toolProps_.OptDescs[o.Name].AddProperty(OptionPropertyType::AppendCmd, cmd);
- }
- void onForward (DagInit* d, GlobalOptionDescription& o) {
- checkNumberOfArguments(d, 0);
- toolProps_.OptDescs[o.Name].setForward();
- }
+/// CollectToolProperties - Gather information about tool properties
+/// from the parsed TableGen data (basically a wrapper for the
+/// CollectProperties function object).
+void CollectToolProperties (RecordVector::const_iterator B,
+ RecordVector::const_iterator E,
+ ToolPropertiesList& TPList,
+ GlobalOptionDescriptions& OptDescs)
+{
+ // Iterate over a properties list of every Tool definition
+ for (;B!=E;++B) {
+ Record* T = *B;
+ // Throws an exception if the value does not exist.
+ ListInit* PropList = T->getValueAsListInit("properties");
- void onHelp (DagInit* d, GlobalOptionDescription& o) {
- checkNumberOfArguments(d, 1);
- const std::string& help_message = InitPtrToString(d->getArg(0));
+ IntrusiveRefCntPtr<ToolProperties>
+ ToolProps(new ToolProperties(T->getName()));
- o.Help = help_message;
+ std::for_each(PropList->begin(), PropList->end(),
+ CollectProperties(*ToolProps, OptDescs));
+ TPList.push_back(ToolProps);
}
+}
- void onRequired (DagInit* d, GlobalOptionDescription& o) {
- checkNumberOfArguments(d, 0);
- o.setRequired();
- }
- void onStopCompilation (DagInit* d, GlobalOptionDescription& o) {
- checkNumberOfArguments(d, 0);
- if (o.Type != OptionType::Switch)
- throw std::string("Only options of type Switch can stop compilation!");
- toolProps_.OptDescs[o.Name].setStopCompilation();
- }
+/// CollectPropertiesFromOptionList - Gather information about
+/// *global* option properties from the OptionList.
+void CollectPropertiesFromOptionList (RecordVector::const_iterator B,
+ RecordVector::const_iterator E,
+ GlobalOptionDescriptions& OptDescs)
+{
+ // Iterate over a properties list of every Tool definition
+ for (;B!=E;++B) {
+ RecordVector::value_type T = *B;
+ // Throws an exception if the value does not exist.
+ ListInit* PropList = T->getValueAsListInit("options");
- void onUnpackValues (DagInit* d, GlobalOptionDescription& o) {
- checkNumberOfArguments(d, 0);
- toolProps_.OptDescs[o.Name].setUnpackValues();
+ std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
}
+}
- /// Helper functions
-
- // Add an option of type t
- void addOption (DagInit* d, OptionType::OptionType t) {
- checkNumberOfArguments(d, 2);
- const std::string& name = InitPtrToString(d->getArg(0));
+/// CheckForSuperfluousOptions - Check that there are no side
+/// effect-free options (specified only in the OptionList). Otherwise,
+/// output a warning.
+void CheckForSuperfluousOptions (const ToolPropertiesList& TPList,
+ const GlobalOptionDescriptions& OptDescs) {
+ llvm::StringSet<> nonSuperfluousOptions;
+
+ // Add all options mentioned in the TPList to the set of
+ // non-superfluous options.
+ for (ToolPropertiesList::const_iterator B = TPList.begin(),
+ E = TPList.end(); B != E; ++B) {
+ const ToolProperties& TP = *(*B);
+ for (ToolOptionDescriptions::const_iterator B = TP.OptDescs.begin(),
+ E = TP.OptDescs.end(); B != E; ++B) {
+ nonSuperfluousOptions.insert(B->first());
+ }
+ }
- GlobalOptionDescription o(t, name);
- toolProps_.OptDescs[name].Type = t;
- toolProps_.OptDescs[name].Name = name;
- processOptionProperties(d, o);
- insertDescription(o);
+ // Check that all options in OptDescs belong to the set of
+ // non-superfluous options.
+ for (GlobalOptionDescriptions::const_iterator B = OptDescs.begin(),
+ E = OptDescs.end(); B != E; ++B) {
+ const GlobalOptionDescription& Val = B->second;
+ if (!nonSuperfluousOptions.count(Val.Name)
+ && Val.Type != OptionType::Alias)
+ cerr << "Warning: option '-" << Val.Name << "' has no effect! "
+ "Probable cause: this option is specified only in the OptionList.\n";
}
+}
- // Insert new GlobalOptionDescription into GlobalOptionDescriptions list
- void insertDescription (const GlobalOptionDescription& o)
- {
- if (optDescs_.Descriptions.count(o.Name)) {
- GlobalOptionDescription& D = optDescs_.Descriptions[o.Name];
- D.Merge(o);
+/// EmitCaseTest1Arg - Helper function used by
+/// EmitCaseConstructHandler.
+bool EmitCaseTest1Arg(const std::string& TestName,
+ const DagInit& d,
+ const GlobalOptionDescriptions& OptDescs,
+ std::ostream& O) {
+ checkNumberOfArguments(&d, 1);
+ const std::string& OptName = InitPtrToString(d.getArg(0));
+ if (TestName == "switch_on") {
+ const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
+ if (OptDesc.Type != OptionType::Switch)
+ throw OptName + ": incorrect option type!";
+ O << OptDesc.GenVariableName();
+ return true;
+ } else if (TestName == "input_languages_contain") {
+ O << "InLangs.count(\"" << OptName << "\") != 0";
+ return true;
+ } else if (TestName == "in_language") {
+ // Works only for cmd_line!
+ O << "GetLanguage(inFile) == \"" << OptName << '\"';
+ return true;
+ } else if (TestName == "not_empty") {
+ if (OptName == "o") {
+ O << "!OutputFilename.empty()";
+ return true;
}
else {
- optDescs_.Descriptions[o.Name] = o;
+ const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
+ if (OptDesc.Type == OptionType::Switch)
+ throw OptName + ": incorrect option type!";
+ O << '!' << OptDesc.GenVariableName() << ".empty()";
+ return true;
}
}
- // Go through the list of option properties and call a corresponding
- // handler for each.
- //
- // Parameters:
- // name - option name
- // d - option property list
- void processOptionProperties (DagInit* d, GlobalOptionDescription& o) {
- // First argument is option name
- checkNumberOfArguments(d, 2);
+ return false;
+}
- for (unsigned B = 1, E = d->getNumArgs(); B!=E; ++B) {
- DagInit& option_property
- = dynamic_cast<DagInit&>(*d->getArg(B));
- const std::string& option_property_name
- = option_property.getOperator()->getAsString();
- OptionPropertyHandlerMap::iterator method
- = optionPropertyHandlers_.find(option_property_name);
-
- if (method != optionPropertyHandlers_.end()) {
- OptionPropertyHandler h = method->second;
- (this->*h)(&option_property, o);
- }
- else {
- throw "Unknown option property: " + option_property_name + "!";
- }
- }
+/// EmitCaseTest2Args - Helper function used by
+/// EmitCaseConstructHandler.
+bool EmitCaseTest2Args(const std::string& TestName,
+ const DagInit& d,
+ const char* IndentLevel,
+ const GlobalOptionDescriptions& OptDescs,
+ std::ostream& O) {
+ checkNumberOfArguments(&d, 2);
+ const std::string& OptName = InitPtrToString(d.getArg(0));
+ const std::string& OptArg = InitPtrToString(d.getArg(1));
+ const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
+
+ if (TestName == "parameter_equals") {
+ if (OptDesc.Type != OptionType::Parameter
+ && OptDesc.Type != OptionType::Prefix)
+ throw OptName + ": incorrect option type!";
+ O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
+ return true;
+ }
+ else if (TestName == "element_in_list") {
+ if (OptDesc.Type != OptionType::ParameterList
+ && OptDesc.Type != OptionType::PrefixList)
+ throw OptName + ": incorrect option type!";
+ const std::string& VarName = OptDesc.GenVariableName();
+ O << "std::find(" << VarName << ".begin(),\n"
+ << IndentLevel << Indent1 << VarName << ".end(), \""
+ << OptArg << "\") != " << VarName << ".end()";
+ return true;
}
-};
-// Static members of CollectProperties
-CollectProperties::PropertyHandlerMap
-CollectProperties::propertyHandlers_;
+ return false;
+}
-CollectProperties::OptionPropertyHandlerMap
-CollectProperties::optionPropertyHandlers_;
+// Forward declaration.
+// EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
+void EmitCaseTest(const DagInit& d, const char* IndentLevel,
+ const GlobalOptionDescriptions& OptDescs,
+ std::ostream& O);
-bool CollectProperties::staticMembersInitialized_ = false;
+/// EmitLogicalOperationTest - Helper function used by
+/// EmitCaseConstructHandler.
+void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
+ const char* IndentLevel,
+ const GlobalOptionDescriptions& OptDescs,
+ std::ostream& O) {
+ O << '(';
+ for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
+ const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
+ EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
+ if (j != NumArgs - 1)
+ O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
+ else
+ O << ')';
+ }
+}
+/// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
+void EmitCaseTest(const DagInit& d, const char* IndentLevel,
+ const GlobalOptionDescriptions& OptDescs,
+ std::ostream& O) {
+ const std::string& TestName = d.getOperator()->getAsString();
+
+ if (TestName == "and")
+ EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
+ else if (TestName == "or")
+ EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
+ else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
+ return;
+ else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
+ return;
+ else
+ throw TestName + ": unknown edge property!";
+}
-// Gather information from the parsed TableGen data
-// (Basically a wrapper for CollectProperties)
-void CollectToolProperties (RecordVector::const_iterator B,
- RecordVector::const_iterator E,
- ToolPropertiesList& TPList,
- GlobalOptionDescriptions& OptDescs)
-{
- // Iterate over a properties list of every Tool definition
- for (;B!=E;++B) {
- RecordVector::value_type T = *B;
- ListInit* PropList = T->getValueAsListInit("properties");
+// Emit code that handles the 'case' construct.
+// Takes a function object that should emit code for every case clause.
+// Callback's type is
+// void F(Init* Statement, const char* IndentLevel, std::ostream& O).
+template <typename F>
+void EmitCaseConstructHandler(const DagInit* d, const char* IndentLevel,
+ F Callback, bool EmitElseIf,
+ const GlobalOptionDescriptions& OptDescs,
+ std::ostream& O) {
+ assert(d->getOperator()->getAsString() == "case");
+
+ unsigned numArgs = d->getNumArgs();
+ if (d->getNumArgs() < 2)
+ throw "There should be at least one clause in the 'case' expression:\n"
+ + d->getAsString();
+
+ for (unsigned i = 0; i != numArgs; ++i) {
+ const DagInit& Test = InitPtrToDag(d->getArg(i));
+
+ // Emit the test.
+ if (Test.getOperator()->getAsString() == "default") {
+ if (i+2 != numArgs)
+ throw std::string("The 'default' clause should be the last in the"
+ "'case' construct!");
+ O << IndentLevel << "else {\n";
+ }
+ else {
+ O << IndentLevel << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
+ EmitCaseTest(Test, IndentLevel, OptDescs, O);
+ O << ") {\n";
+ }
- IntrusiveRefCntPtr<ToolProperties>
- ToolProps(new ToolProperties(T->getName()));
+ // Emit the corresponding statement.
+ ++i;
+ if (i == numArgs)
+ throw "Case construct handler: no corresponding action "
+ "found for the test " + Test.getAsString() + '!';
+
+ Init* arg = d->getArg(i);
+ if (dynamic_cast<DagInit*>(arg)
+ && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case") {
+ EmitCaseConstructHandler(static_cast<DagInit*>(arg),
+ (std::string(IndentLevel) + Indent1).c_str(),
+ Callback, EmitElseIf, OptDescs, O);
+ }
+ else {
+ Callback(arg, IndentLevel, O);
+ }
+ O << IndentLevel << "}\n";
+ }
+}
- std::for_each(PropList->begin(), PropList->end(),
- CollectProperties(*ToolProps, OptDescs));
- TPList.push_back(ToolProps);
+/// EmitForwardOptionPropertyHandlingCode - Helper function used to
+/// implement EmitOptionPropertyHandlingCode(). Emits code for
+/// handling the (forward) option property.
+void EmitForwardOptionPropertyHandlingCode (const ToolOptionDescription& D,
+ std::ostream& O) {
+ switch (D.Type) {
+ case OptionType::Switch:
+ O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
+ break;
+ case OptionType::Parameter:
+ O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
+ O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
+ break;
+ case OptionType::Prefix:
+ O << Indent3 << "vec.push_back(\"-" << D.Name << "\" + "
+ << D.GenVariableName() << ");\n";
+ break;
+ case OptionType::PrefixList:
+ O << Indent3 << "for (" << D.GenTypeDeclaration()
+ << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
+ << Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
+ << Indent4 << "vec.push_back(\"-" << D.Name << "\" + "
+ << "*B);\n";
+ break;
+ case OptionType::ParameterList:
+ O << Indent3 << "for (" << D.GenTypeDeclaration()
+ << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
+ << Indent3 << "E = " << D.GenVariableName()
+ << ".end() ; B != E; ++B) {\n"
+ << Indent4 << "vec.push_back(\"-" << D.Name << "\");\n"
+ << Indent4 << "vec.push_back(*B);\n"
+ << Indent3 << "}\n";
+ break;
+ case OptionType::Alias:
+ default:
+ throw std::string("Aliases are not allowed in tool option descriptions!");
}
}
-// Used by EmitGenerateActionMethod
-void EmitOptionPropertyHandlingCode (const ToolProperties& P,
- const ToolOptionDescription& D,
+// ToolOptionHasInterestingProperties - A helper function used by
+// EmitOptionPropertyHandlingCode() that tells us whether we should
+// emit any property handling code at all.
+bool ToolOptionHasInterestingProperties(const ToolOptionDescription& D) {
+ bool ret = false;
+ for (OptionPropertyList::const_iterator B = D.Props.begin(),
+ E = D.Props.end(); B != E; ++B) {
+ const OptionProperty& OptProp = *B;
+ if (OptProp.first == OptionPropertyType::AppendCmd)
+ ret = true;
+ }
+ if (D.isForward() || D.isUnpackValues())
+ ret = true;
+ return ret;
+}
+
+/// EmitOptionPropertyHandlingCode - Helper function used by
+/// EmitGenerateActionMethod(). Emits code that handles option
+/// properties.
+void EmitOptionPropertyHandlingCode (const ToolOptionDescription& D,
std::ostream& O)
{
- // if clause
+ if (!ToolOptionHasInterestingProperties(D))
+ return;
+ // Start of the if-clause.
O << Indent2 << "if (";
if (D.Type == OptionType::Switch)
O << D.GenVariableName();
O <<") {\n";
- // Handle option properties that take an argument
+ // Handle option properties that take an argument.
for (OptionPropertyList::const_iterator B = D.Props.begin(),
E = D.Props.end(); B!=E; ++B) {
const OptionProperty& val = *B;
// Handle flags
// (forward) property
- if (D.isForward()) {
- switch (D.Type) {
- case OptionType::Switch:
- O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
- break;
- case OptionType::Parameter:
- O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
- O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
- break;
- case OptionType::Prefix:
- O << Indent3 << "vec.push_back(\"-" << D.Name << "\" + "
- << D.GenVariableName() << ");\n";
- break;
- case OptionType::PrefixList:
- O << Indent3 << "for (" << D.GenTypeDeclaration()
- << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
- << Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
- << Indent4 << "vec.push_back(\"-" << D.Name << "\" + "
- << "*B);\n";
- break;
- case OptionType::ParameterList:
- O << Indent3 << "for (" << D.GenTypeDeclaration()
- << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
- << Indent3 << "E = " << D.GenVariableName()
- << ".end() ; B != E; ++B) {\n"
- << Indent4 << "vec.push_back(\"-" << D.Name << "\");\n"
- << Indent4 << "vec.push_back(*B);\n"
- << Indent3 << "}\n";
- break;
- }
- }
+ if (D.isForward())
+ EmitForwardOptionPropertyHandlingCode(D, O);
// (unpack_values) property
if (D.isUnpackValues()) {
<< D.GenVariableName() << ", vec, \",\");\n";
}
else {
- // TOFIX: move this to the type-checking phase
throw std::string("Switches can't have unpack_values property!");
}
}
- // close if clause
+ // End of the if-clause.
O << Indent2 << "}\n";
}
-// Emite one of two versions of GenerateAction method
-void EmitGenerateActionMethod (const ToolProperties& P, int V, std::ostream& O)
-{
- assert(V==1 || V==2);
- if (V==1)
- O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
- else
- O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
+/// SubstituteSpecialCommands - Perform string substitution for $CALL
+/// and $ENV. Helper function used by EmitCmdLineVecFill().
+std::string SubstituteSpecialCommands(const std::string& cmd) {
+ size_t cparen = cmd.find(")");
+ std::string ret;
- O << Indent2 << "const sys::Path& outFile) const\n"
- << Indent1 << "{\n"
- << Indent2 << "std::vector<std::string> vec;\n";
+ if (cmd.find("$CALL(") == 0) {
+ if (cmd.size() == 6)
+ throw std::string("$CALL invocation: empty argument list!");
+
+ ret += "hooks::";
+ ret += std::string(cmd.begin() + 6, cmd.begin() + cparen);
+ ret += "()";
+ }
+ else if (cmd.find("$ENV(") == 0) {
+ if (cmd.size() == 5)
+ throw std::string("$ENV invocation: empty argument list!");
+
+ ret += "std::getenv(\"";
+ ret += std::string(cmd.begin() + 5, cmd.begin() + cparen);
+ ret += "\")";
+ }
+ else {
+ throw "Unknown special command: " + cmd;
+ }
+
+ if (cmd.begin() + cparen + 1 != cmd.end()) {
+ ret += " + std::string(\"";
+ ret += (cmd.c_str() + cparen + 1);
+ ret += "\")";
+ }
- // Parse CmdLine tool property
- if(P.CmdLine.empty())
- throw "Tool " + P.Name + " has empty command line!";
+ return ret;
+}
- StrVector::const_iterator I = P.CmdLine.begin();
+/// EmitCmdLineVecFill - Emit code that fills in the command line
+/// vector. Helper function used by EmitGenerateActionMethod().
+void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
+ bool Version, const char* IndentLevel,
+ std::ostream& O) {
+ StrVector StrVec;
+ SplitString(InitPtrToString(CmdLine), StrVec);
+ if (StrVec.empty())
+ throw "Tool " + ToolName + " has empty command line!";
+
+ StrVector::const_iterator I = StrVec.begin();
++I;
- for (StrVector::const_iterator E = P.CmdLine.end(); I != E; ++I) {
+ for (StrVector::const_iterator E = StrVec.end(); I != E; ++I) {
const std::string& cmd = *I;
- O << Indent2;
- if (cmd == "$INFILE") {
- if (V==1)
- O << "for (PathVector::const_iterator B = inFiles.begin()"
- << ", E = inFiles.end();\n"
- << Indent2 << "B != E; ++B)\n"
- << Indent3 << "vec.push_back(B->toString());\n";
- else
- O << "vec.push_back(inFile.toString());\n";
- }
- else if (cmd == "$OUTFILE") {
- O << "vec.push_back(outFile.toString());\n";
+ O << IndentLevel;
+ if (cmd.at(0) == '$') {
+ if (cmd == "$INFILE") {
+ if (Version)
+ O << "for (PathVector::const_iterator B = inFiles.begin()"
+ << ", E = inFiles.end();\n"
+ << IndentLevel << "B != E; ++B)\n"
+ << IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
+ else
+ O << "vec.push_back(inFile.toString());\n";
+ }
+ else if (cmd == "$OUTFILE") {
+ O << "vec.push_back(outFile.toString());\n";
+ }
+ else {
+ O << "vec.push_back(" << SubstituteSpecialCommands(cmd);
+ O << ");\n";
+ }
}
else {
O << "vec.push_back(\"" << cmd << "\");\n";
}
}
+ O << IndentLevel << "cmd = "
+ << ((StrVec[0][0] == '$') ? SubstituteSpecialCommands(StrVec[0])
+ : "\"" + StrVec[0] + "\"")
+ << ";\n";
+}
+
+/// EmitCmdLineVecFillCallback - A function object wrapper around
+/// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
+/// argument to EmitCaseConstructHandler().
+class EmitCmdLineVecFillCallback {
+ bool Version;
+ const std::string& ToolName;
+ public:
+ EmitCmdLineVecFillCallback(bool Ver, const std::string& TN)
+ : Version(Ver), ToolName(TN) {}
+
+ void operator()(const Init* Statement, const char* IndentLevel,
+ std::ostream& O) const
+ {
+ EmitCmdLineVecFill(Statement, ToolName, Version,
+ (std::string(IndentLevel) + Indent1).c_str(), O);
+ }
+};
+
+// EmitGenerateActionMethod - Emit one of two versions of the
+// Tool::GenerateAction() method.
+void EmitGenerateActionMethod (const ToolProperties& P,
+ const GlobalOptionDescriptions& OptDescs,
+ bool Version, std::ostream& O) {
+ if (Version)
+ O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
+ else
+ O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
+
+ O << Indent2 << "const sys::Path& outFile,\n"
+ << Indent2 << "const InputLanguagesSet& InLangs) const\n"
+ << Indent1 << "{\n"
+ << Indent2 << "const char* cmd;\n"
+ << Indent2 << "std::vector<std::string> vec;\n";
- // For every understood option, emit handling code
+ // cmd_line is either a string or a 'case' construct.
+ if (typeid(*P.CmdLine) == typeid(StringInit))
+ EmitCmdLineVecFill(P.CmdLine, P.Name, Version, Indent2, O);
+ else
+ EmitCaseConstructHandler(&InitPtrToDag(P.CmdLine), Indent2,
+ EmitCmdLineVecFillCallback(Version, P.Name),
+ true, OptDescs, O);
+
+ // For every understood option, emit handling code.
for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
E = P.OptDescs.end(); B != E; ++B) {
const ToolOptionDescription& val = B->second;
- EmitOptionPropertyHandlingCode(P, val, O);
+ EmitOptionPropertyHandlingCode(val, O);
}
- // Handle Sink property
+ // Handle the Sink property.
if (P.isSink()) {
O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
<< Indent3 << "vec.insert(vec.end(), "
<< Indent2 << "}\n";
}
- O << Indent2 << "return Action(\"" << P.CmdLine.at(0) << "\", vec);\n"
+ O << Indent2 << "return Action(cmd, vec);\n"
<< Indent1 << "}\n\n";
}
-// Emit GenerateAction methods for Tool classes
-void EmitGenerateActionMethods (const ToolProperties& P, std::ostream& O) {
-
+/// EmitGenerateActionMethods - Emit two GenerateAction() methods for
+/// a given Tool class.
+void EmitGenerateActionMethods (const ToolProperties& P,
+ const GlobalOptionDescriptions& OptDescs,
+ std::ostream& O) {
if (!P.isJoin())
O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
- << Indent2 << "const llvm::sys::Path& outFile) const\n"
+ << Indent2 << "const llvm::sys::Path& outFile,\n"
+ << Indent2 << "const InputLanguagesSet& InLangs) const\n"
<< Indent1 << "{\n"
<< Indent2 << "throw std::runtime_error(\"" << P.Name
<< " is not a Join tool!\");\n"
<< Indent1 << "}\n\n";
else
- EmitGenerateActionMethod(P, 1, O);
+ EmitGenerateActionMethod(P, OptDescs, true, O);
- EmitGenerateActionMethod(P, 2, O);
+ EmitGenerateActionMethod(P, OptDescs, false, O);
}
-// Emit IsLast() method for Tool classes
+/// EmitIsLastMethod - Emit the IsLast() method for a given Tool
+/// class.
void EmitIsLastMethod (const ToolProperties& P, std::ostream& O) {
O << Indent1 << "bool IsLast() const {\n"
<< Indent2 << "bool last = false;\n";
<< Indent1 << "}\n\n";
}
-// Emit static [Input,Output]Language() methods for Tool classes
+/// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
+/// methods for a given Tool class.
void EmitInOutLanguageMethods (const ToolProperties& P, std::ostream& O) {
- O << Indent1 << "const char* InputLanguage() const {\n"
- << Indent2 << "return \"" << P.InLanguage << "\";\n"
+ O << Indent1 << "const char** InputLanguages() const {\n"
+ << Indent2 << "return InputLanguages_;\n"
<< Indent1 << "}\n\n";
O << Indent1 << "const char* OutputLanguage() const {\n"
<< Indent1 << "}\n\n";
}
-// Emit static [Input,Output]Language() methods for Tool classes
+/// EmitOutputSuffixMethod - Emit the OutputSuffix() method for a
+/// given Tool class.
void EmitOutputSuffixMethod (const ToolProperties& P, std::ostream& O) {
O << Indent1 << "const char* OutputSuffix() const {\n"
- << Indent2 << "return \"" << P.OutputSuffix << "\";\n"
+ << Indent2 << "const char* ret = \"" << P.OutputSuffix << "\";\n";
+
+ for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
+ E = P.OptDescs.end(); B != E; ++B) {
+ const ToolOptionDescription& OptDesc = B->second;
+ for (OptionPropertyList::const_iterator B = OptDesc.Props.begin(),
+ E = OptDesc.Props.end(); B != E; ++B) {
+ const OptionProperty& OptProp = *B;
+ if (OptProp.first == OptionPropertyType::OutputSuffix) {
+ O << Indent2 << "if (" << OptDesc.GenVariableName() << ")\n"
+ << Indent3 << "ret = \"" << OptProp.second << "\";\n";
+ }
+ }
+ }
+
+ O << Indent2 << "return ret;\n"
<< Indent1 << "}\n\n";
}
-// Emit static Name() method for Tool classes
+/// EmitNameMethod - Emit the Name() method for a given Tool class.
void EmitNameMethod (const ToolProperties& P, std::ostream& O) {
O << Indent1 << "const char* Name() const {\n"
<< Indent2 << "return \"" << P.Name << "\";\n"
<< Indent1 << "}\n\n";
}
-// Emit static Name() method for Tool classes
+/// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
+/// class.
void EmitIsJoinMethod (const ToolProperties& P, std::ostream& O) {
O << Indent1 << "bool IsJoin() const {\n";
if (P.isJoin())
O << Indent1 << "}\n\n";
}
-// Emit a Tool class definition
-void EmitToolClassDefinition (const ToolProperties& P, std::ostream& O) {
+/// EmitStaticMemberDefinitions - Emit static member definitions for a
+/// given Tool class.
+void EmitStaticMemberDefinitions(const ToolProperties& P, std::ostream& O) {
+ O << "const char* " << P.Name << "::InputLanguages_[] = {";
+ for (StrVector::const_iterator B = P.InLanguage.begin(),
+ E = P.InLanguage.end(); B != E; ++B)
+ O << '\"' << *B << "\", ";
+ O << "0};\n\n";
+}
- if(P.Name == "root")
+/// EmitToolClassDefinition - Emit a Tool class definition.
+void EmitToolClassDefinition (const ToolProperties& P,
+ const GlobalOptionDescriptions& OptDescs,
+ std::ostream& O) {
+ if (P.Name == "root")
return;
// Header
O << "JoinTool";
else
O << "Tool";
- O << " {\npublic:\n";
+ O << "{\nprivate:\n"
+ << Indent1 << "static const char* InputLanguages_[];\n\n";
+
+ O << "public:\n";
EmitNameMethod(P, O);
EmitInOutLanguageMethods(P, O);
EmitOutputSuffixMethod(P, O);
EmitIsJoinMethod(P, O);
- EmitGenerateActionMethods(P, O);
+ EmitGenerateActionMethods(P, OptDescs, O);
EmitIsLastMethod(P, O);
// Close class definition
- O << "};\n\n";
+ O << "};\n";
+
+ EmitStaticMemberDefinitions(P, O);
+
}
-// Iterate over a list of option descriptions and emit registration code
+/// EmitOptionDescriptions - Iterate over a list of option
+/// descriptions and emit registration code.
void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
std::ostream& O)
{
- // Emit static cl::Option variables
+ std::vector<GlobalOptionDescription> Aliases;
+
+ // Emit static cl::Option variables.
for (GlobalOptionDescriptions::const_iterator B = descs.begin(),
E = descs.end(); B!=E; ++B) {
const GlobalOptionDescription& val = B->second;
+ if (val.Type == OptionType::Alias) {
+ Aliases.push_back(val);
+ continue;
+ }
+
O << val.GenTypeDeclaration() << ' '
<< val.GenVariableName()
<< "(\"" << val.Name << '\"';
}
}
- O << ", cl::desc(\"" << val.Help << "\"));\n";
+ if (!val.Help.empty())
+ O << ", cl::desc(\"" << val.Help << "\")";
+
+ O << ");\n";
+ }
+
+ // Emit the aliases (they should go after all the 'proper' options).
+ for (std::vector<GlobalOptionDescription>::const_iterator
+ B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
+ const GlobalOptionDescription& val = *B;
+
+ O << val.GenTypeDeclaration() << ' '
+ << val.GenVariableName()
+ << "(\"" << val.Name << '\"';
+
+ GlobalOptionDescriptions::container_type
+ ::const_iterator F = descs.Descriptions.find(val.Help);
+ if (F != descs.Descriptions.end())
+ O << ", cl::aliasopt(" << F->second.GenVariableName() << ")";
+ else
+ throw val.Name + ": alias to an unknown option!";
+
+ O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
}
+ // Emit the sink option.
if (descs.HasSink)
O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
O << '\n';
}
+/// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
{
// Get the relevant field out of RecordKeeper
throw std::string("Error in the language map definition!");
// Generate code
- O << "void llvmc::PopulateLanguageMap(LanguageMap& language_map) {\n";
+ O << "void llvmc::PopulateLanguageMap() {\n";
for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
for (unsigned i = 0; i < Suffixes->size(); ++i)
- O << Indent1 << "language_map[\""
+ O << Indent1 << "GlobalLanguageMap[\""
<< InitPtrToString(Suffixes->getElement(i))
<< "\"] = \"" << Lang << "\";\n";
}
O << "}\n\n";
}
-// Fills in two tables that map tool names to (input, output) languages.
-// Used by the typechecker.
+/// FillInToolToLang - Fills in two tables that map tool names to
+/// (input, output) languages. Used by the typechecker.
void FillInToolToLang (const ToolPropertiesList& TPList,
- StringMap<std::string>& ToolToInLang,
+ StringMap<StringSet<> >& ToolToInLang,
StringMap<std::string>& ToolToOutLang) {
for (ToolPropertiesList::const_iterator B = TPList.begin(), E = TPList.end();
B != E; ++B) {
const ToolProperties& P = *(*B);
- ToolToInLang[P.Name] = P.InLanguage;
+ for (StrVector::const_iterator B = P.InLanguage.begin(),
+ E = P.InLanguage.end(); B != E; ++B)
+ ToolToInLang[P.Name].insert(*B);
ToolToOutLang[P.Name] = P.OutLanguage;
}
}
-// Check that all output and input language names match.
-// TOFIX: check for cycles.
-// TOFIX: check for multiple default edges.
+/// TypecheckGraph - Check that names for output and input languages
+/// on all edges do match.
+// TOFIX: It would be nice if this function also checked for cycles
+// and multiple default edges in the graph (better error
+// reporting). Unfortunately, it is awkward to do right now because
+// our intermediate representation is not sufficiently
+// sophisticated. Algorithms like these require a real graph instead of
+// an AST.
void TypecheckGraph (Record* CompilationGraph,
const ToolPropertiesList& TPList) {
- StringMap<std::string> ToolToInLang;
+ StringMap<StringSet<> > ToolToInLang;
StringMap<std::string> ToolToOutLang;
FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
ListInit* edges = CompilationGraph->getValueAsListInit("edges");
- StringMap<std::string>::iterator IAE = ToolToInLang.end();
- StringMap<std::string>::iterator IBE = ToolToOutLang.end();
+ StringMap<std::string>::iterator IAE = ToolToOutLang.end();
+ StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
for (unsigned i = 0; i < edges->size(); ++i) {
Record* Edge = edges->getElementAsRecord(i);
Record* A = Edge->getValueAsDef("a");
Record* B = Edge->getValueAsDef("b");
StringMap<std::string>::iterator IA = ToolToOutLang.find(A->getName());
- StringMap<std::string>::iterator IB = ToolToInLang.find(B->getName());
- if(IA == IAE)
+ StringMap<StringSet<> >::iterator IB = ToolToInLang.find(B->getName());
+ if (IA == IAE)
throw A->getName() + ": no such tool!";
- if(IB == IBE)
+ if (IB == IBE)
throw B->getName() + ": no such tool!";
- if(A->getName() != "root" && IA->second != IB->second)
+ if (A->getName() != "root" && IB->second.count(IA->second) == 0)
throw "Edge " + A->getName() + "->" + B->getName()
+ ": output->input language mismatch";
- if(B->getName() == "root")
+ if (B->getName() == "root")
throw std::string("Edges back to the root are not allowed!");
}
}
-// Helper function used by EmitEdgePropertyTest.
-void EmitEdgePropertyTest1Arg(const DagInit& Prop,
- const GlobalOptionDescriptions& OptDescs,
- std::ostream& O) {
- checkNumberOfArguments(&Prop, 1);
- const std::string& OptName = InitPtrToString(Prop.getArg(0));
- const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
- if (OptDesc.Type != OptionType::Switch)
- throw OptName + ": incorrect option type!";
- O << OptDesc.GenVariableName();
-}
-
-// Helper function used by EmitEdgePropertyTest.
-void EmitEdgePropertyTest2Args(const std::string& PropName,
- const DagInit& Prop,
- const GlobalOptionDescriptions& OptDescs,
- std::ostream& O) {
- checkNumberOfArguments(&Prop, 2);
- const std::string& OptName = InitPtrToString(Prop.getArg(0));
- const std::string& OptArg = InitPtrToString(Prop.getArg(1));
- const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
+/// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
+/// by EmitEdgeClass().
+void IncDecWeight (const Init* i, const char* IndentLevel,
+ std::ostream& O) {
+ const DagInit& d = InitPtrToDag(i);
+ const std::string& OpName = d.getOperator()->getAsString();
- if (PropName == "parameter_equals") {
- if (OptDesc.Type != OptionType::Parameter
- && OptDesc.Type != OptionType::Prefix)
- throw OptName + ": incorrect option type!";
- O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
- }
- else if (PropName == "element_in_list") {
- if (OptDesc.Type != OptionType::ParameterList
- && OptDesc.Type != OptionType::PrefixList)
- throw OptName + ": incorrect option type!";
- const std::string& VarName = OptDesc.GenVariableName();
- O << "std::find(" << VarName << ".begin(),\n"
- << Indent3 << VarName << ".end(), \""
- << OptArg << "\") != " << VarName << ".end()";
- }
+ if (OpName == "inc_weight")
+ O << IndentLevel << Indent1 << "ret += ";
+ else if (OpName == "dec_weight")
+ O << IndentLevel << Indent1 << "ret -= ";
else
- throw PropName + ": unknown edge property!";
-}
+ throw "Unknown operator in edge properties list: " + OpName + '!';
-// Helper function used by EmitEdgeClass.
-void EmitEdgePropertyTest(const std::string& PropName,
- const DagInit& Prop,
- const GlobalOptionDescriptions& OptDescs,
- std::ostream& O) {
- if (PropName == "switch_on")
- EmitEdgePropertyTest1Arg(Prop, OptDescs, O);
+ if (d.getNumArgs() > 0)
+ O << InitPtrToInt(d.getArg(0)) << ";\n";
else
- EmitEdgePropertyTest2Args(PropName, Prop, OptDescs, O);
+ O << "2;\n";
+
}
-// Emit a single Edge* class.
-void EmitEdgeClass(unsigned N, const std::string& Target,
- ListInit* Props, const GlobalOptionDescriptions& OptDescs,
- std::ostream& O) {
- bool IsDefault = false;
+/// EmitEdgeClass - Emit a single Edge# class.
+void EmitEdgeClass (unsigned N, const std::string& Target,
+ DagInit* Case, const GlobalOptionDescriptions& OptDescs,
+ std::ostream& O) {
// Class constructor.
O << "class Edge" << N << ": public Edge {\n"
<< Indent1 << "Edge" << N << "() : Edge(\"" << Target
<< "\") {}\n\n"
- // Function isEnabled().
- << Indent1 << "bool isEnabled() const {\n"
- << Indent2 << "bool ret = false;\n";
-
- for (size_t i = 0, PropsSize = Props->size(); i < PropsSize; ++i) {
- const DagInit& Prop = dynamic_cast<DagInit&>(*Props->getElement(i));
- const std::string& PropName = Prop.getOperator()->getAsString();
-
- if (PropName == "default")
- IsDefault = true;
-
- O << Indent2 << "if (ret || (";
- if (PropName == "and") {
- O << '(';
- for (unsigned j = 0, NumArgs = Prop.getNumArgs(); j < NumArgs; ++j) {
- const DagInit& InnerProp = dynamic_cast<DagInit&>(*Prop.getArg(j));
- const std::string& InnerPropName =
- InnerProp.getOperator()->getAsString();
- EmitEdgePropertyTest(InnerPropName, InnerProp, OptDescs, O);
- if (j != NumArgs - 1)
- O << ")\n" << Indent3 << " && (";
- else
- O << ')';
- }
- }
- else {
- EmitEdgePropertyTest(PropName, Prop, OptDescs, O);
- }
- O << "))\n" << Indent3 << "ret = true;\n";
- }
+ // Function Weight().
+ << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
+ << Indent2 << "unsigned ret = 0;\n";
- O << Indent2 << "return ret;\n"
- << Indent1 << "};\n\n"
+ // Handle the 'case' construct.
+ EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
- // Function isDefault().
- << Indent1 << "bool isDefault() const { return ";
- if (IsDefault)
- O << "true";
- else
- O << "false";
- O <<"; }\n};\n\n";
+ O << Indent2 << "return ret;\n"
+ << Indent1 << "};\n\n};\n\n";
}
-// Emit Edge* classes that represent graph edges.
+/// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
void EmitEdgeClasses (Record* CompilationGraph,
const GlobalOptionDescriptions& OptDescs,
std::ostream& O) {
for (unsigned i = 0; i < edges->size(); ++i) {
Record* Edge = edges->getElementAsRecord(i);
Record* B = Edge->getValueAsDef("b");
- ListInit* Props = Edge->getValueAsListInit("props");
+ DagInit* Weight = Edge->getValueAsDag("weight");
- if (Props->empty())
+ if (isDagEmpty(Weight))
continue;
- EmitEdgeClass(i, B->getName(), Props, OptDescs, O);
+ EmitEdgeClass(i, B->getName(), Weight, OptDescs, O);
}
}
+/// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
+/// function.
void EmitPopulateCompilationGraph (Record* CompilationGraph,
std::ostream& O)
{
// Generate code
O << "void llvmc::PopulateCompilationGraph(CompilationGraph& G) {\n"
- << Indent1 << "PopulateLanguageMap(G.ExtsToLangs);\n\n";
+ << Indent1 << "PopulateLanguageMap();\n\n";
// Insert vertices
for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
const std::string& Name = (*B)->getName();
- if(Name != "root")
+ if (Name != "root")
O << Indent1 << "G.insertNode(new "
<< Name << "());\n";
}
Record* Edge = edges->getElementAsRecord(i);
Record* A = Edge->getValueAsDef("a");
Record* B = Edge->getValueAsDef("b");
- ListInit* Props = Edge->getValueAsListInit("props");
+ DagInit* Weight = Edge->getValueAsDag("weight");
O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
- if (Props->empty())
+ if (isDagEmpty(Weight))
O << "new SimpleEdge(\"" << B->getName() << "\")";
else
O << "new Edge" << i << "()";
O << "}\n\n";
}
+/// ExtractHookNames - Extract the hook names from all instances of
+/// $CALL(HookName) in the provided command line string. Helper
+/// function used by FillInHookNames().
+void ExtractHookNames(const Init* CmdLine, StrVector& HookNames) {
+ StrVector cmds;
+ llvm::SplitString(InitPtrToString(CmdLine), cmds);
+ for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
+ B != E; ++B) {
+ const std::string& cmd = *B;
+ if (cmd.find("$CALL(") == 0) {
+ if (cmd.size() == 6)
+ throw std::string("$CALL invocation: empty argument list!");
+ HookNames.push_back(std::string(cmd.begin() + 6,
+ cmd.begin() + cmd.find(")")));
+ }
+ }
+}
+
+/// ExtractHookNamesFromCaseConstruct - Extract hook names from the
+/// 'case' expression, handle nesting. Helper function used by
+/// FillInHookNames().
+void ExtractHookNamesFromCaseConstruct(Init* Case, StrVector& HookNames) {
+ const DagInit& d = InitPtrToDag(Case);
+ bool even = false;
+ for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
+ B != E; ++B) {
+ Init* arg = *B;
+ if (even && dynamic_cast<DagInit*>(arg)
+ && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
+ ExtractHookNamesFromCaseConstruct(arg, HookNames);
+ else if (even)
+ ExtractHookNames(arg, HookNames);
+ even = !even;
+ }
+}
+
+/// FillInHookNames - Actually extract the hook names from all command
+/// line strings. Helper function used by EmitHookDeclarations().
+void FillInHookNames(const ToolPropertiesList& TPList,
+ StrVector& HookNames) {
+ // For all command lines:
+ for (ToolPropertiesList::const_iterator B = TPList.begin(),
+ E = TPList.end(); B != E; ++B) {
+ const ToolProperties& P = *(*B);
+ if (!P.CmdLine)
+ continue;
+ if (dynamic_cast<StringInit*>(P.CmdLine))
+ // This is a string.
+ ExtractHookNames(P.CmdLine, HookNames);
+ else
+ // This is a 'case' construct.
+ ExtractHookNamesFromCaseConstruct(P.CmdLine, HookNames);
+ }
+}
+
+/// EmitHookDeclarations - Parse CmdLine fields of all the tool
+/// property records and emit hook function declaration for each
+/// instance of $CALL(HookName).
+void EmitHookDeclarations(const ToolPropertiesList& ToolProps,
+ std::ostream& O) {
+ StrVector HookNames;
+ FillInHookNames(ToolProps, HookNames);
+ if (HookNames.empty())
+ return;
+ std::sort(HookNames.begin(), HookNames.end());
+ StrVector::const_iterator E = std::unique(HookNames.begin(), HookNames.end());
+
+ O << "namespace hooks {\n";
+ for (StrVector::const_iterator B = HookNames.begin(); B != E; ++B)
+ O << Indent1 << "std::string " << *B << "();\n";
+
+ O << "}\n\n";
+}
// End of anonymous namespace
}
-// Back-end entry point
+/// run - The back-end entry point.
void LLVMCConfigurationEmitter::run (std::ostream &O) {
- // Emit file header
+ try {
+
+ // Emit file header.
EmitSourceFileHeader("LLVMC Configuration Library", O);
- // Get a list of all defined Tools
+ // Get a list of all defined Tools.
RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
if (Tools.empty())
throw std::string("No tool definitions found!");
- // Gather information from the Tool descriptions
+ // Gather information from the Tool description dags.
ToolPropertiesList tool_props;
GlobalOptionDescriptions opt_descs;
CollectToolProperties(Tools.begin(), Tools.end(), tool_props, opt_descs);
- // Emit global option registration code
+ RecordVector OptionLists = Records.getAllDerivedDefinitions("OptionList");
+ CollectPropertiesFromOptionList(OptionLists.begin(), OptionLists.end(),
+ opt_descs);
+
+ // Check that there are no options without side effects (specified
+ // only in the OptionList).
+ CheckForSuperfluousOptions(tool_props, opt_descs);
+
+ // Emit global option registration code.
EmitOptionDescriptions(opt_descs, O);
- // Emit PopulateLanguageMap function
- // (a language map maps from file extensions to language names)
+ // Emit hook declarations.
+ EmitHookDeclarations(tool_props, O);
+
+ // Emit PopulateLanguageMap() function
+ // (a language map maps from file extensions to language names).
EmitPopulateLanguageMap(Records, O);
- // Emit Tool classes
+ // Emit Tool classes.
for (ToolPropertiesList::const_iterator B = tool_props.begin(),
E = tool_props.end(); B!=E; ++B)
- EmitToolClassDefinition(*(*B), O);
+ EmitToolClassDefinition(*(*B), opt_descs, O);
Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
if (!CompilationGraphRecord)
// Typecheck the compilation graph.
TypecheckGraph(CompilationGraphRecord, tool_props);
- // Emit Edge* classes.
+ // Emit Edge# classes.
EmitEdgeClasses(CompilationGraphRecord, opt_descs, O);
- // Emit PopulateCompilationGraph function
+ // Emit PopulateCompilationGraph() function.
EmitPopulateCompilationGraph(CompilationGraphRecord, O);
// EOF
+ } catch (std::exception& Error) {
+ throw Error.what() + std::string(" - usually this means a syntax error.");
+ }
}