Refactoring, no functionality change.
[oota-llvm.git] / utils / TableGen / LLVMCConfigurationEmitter.cpp
index 2bac7036e29fc7852e6a3fcbb48dd8c2f1d76544..be3382c29d5cbd27aba7acd4323fb221b7336cf5 100644 (file)
@@ -1,4 +1,4 @@
-//===- LLVMCConfigurationEmitter.cpp - Generate LLVMC config --------------===//
+//===- LLVMCConfigurationEmitter.cpp - Generate LLVMC config ----*- C++ -*-===//
 //
 //                     The LLVM Compiler Infrastructure
 //
 #include "Record.h"
 
 #include "llvm/ADT/IntrusiveRefCntPtr.h"
-#include "llvm/ADT/SmallVector.h"
-#include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringMap.h"
-#include "llvm/Support/Streams.h"
-
+#include "llvm/ADT/StringSet.h"
 #include <algorithm>
 #include <cassert>
 #include <functional>
+#include <stdexcept>
 #include <string>
+#include <typeinfo>
 
 using namespace llvm;
 
@@ -38,624 +37,1292 @@ typedef std::vector<std::string> StrVector;
 //===----------------------------------------------------------------------===//
 /// Constants
 
-// Indentation strings.
-const char * Indent1 = "    ";
-const char * Indent2 = "        ";
-const char * Indent3 = "            ";
-const char * Indent4 = "                ";
+// Indentation.
+const unsigned TabWidth = 4;
+const unsigned Indent1  = TabWidth*1;
+const unsigned Indent2  = TabWidth*2;
+const unsigned Indent3  = TabWidth*3;
 
 // Default help string.
-const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
+const char * const DefaultHelpString = "NO HELP MESSAGE PROVIDED";
 
 // Name for the "sink" option.
-const char * SinkOptionName = "AutoGeneratedSinkOption";
+const char * const SinkOptionName = "AutoGeneratedSinkOption";
 
 //===----------------------------------------------------------------------===//
 /// Helper functions
 
+/// Id - An 'identity' function object.
+struct Id {
+  template<typename T0>
+  void operator()(const T0&) const {
+  }
+  template<typename T0, typename T1>
+  void operator()(const T0&, const T1&) const {
+  }
+  template<typename T0, typename T1, typename T2>
+  void operator()(const T0&, const T1&, const T2&) const {
+  }
+};
+
+int InitPtrToInt(const Init* ptr) {
+  const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
+  return val.getValue();
+}
+
 const std::string& InitPtrToString(const Init* ptr) {
   const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
   return val.getValue();
 }
 
-int InitPtrToInt(const Init* ptr) {
-  const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
-  return val.getValue();
+const ListInit& InitPtrToList(const Init* ptr) {
+  const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
+  return val;
 }
 
-const DagInit& InitPtrToDagInitRef(const Init* ptr) {
+const DagInit& InitPtrToDag(const Init* ptr) {
   const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
   return val;
 }
 
+const std::string GetOperatorName(const DagInit& D) {
+  return D.getOperator()->getAsString();
+}
+
 // 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!";
+// greater than or equal to min_arguments, otherwise throw an exception.
+void checkNumberOfArguments (const DagInit& d, unsigned minArgs) {
+  if (d.getNumArgs() < minArgs)
+    throw GetOperatorName(d) + ": too few arguments!";
 }
 
 // isDagEmpty - is this DAG marked with an empty marker?
-bool isDagEmpty (const DagInit* d) {
-  return d->getOperator()->getAsString() == "empty";
+bool isDagEmpty (const DagInit& d) {
+  return GetOperatorName(d) == "empty_dag_marker";
+}
+
+// EscapeVariableName - Escape commas and other symbols not allowed
+// in the C++ variable names. Makes it possible to use options named
+// like "Wa," (useful for prefix options).
+std::string EscapeVariableName(const std::string& Var) {
+  std::string ret;
+  for (unsigned i = 0; i != Var.size(); ++i) {
+    char cur_char = Var[i];
+    if (cur_char == ',') {
+      ret += "_comma_";
+    }
+    else if (cur_char == '+') {
+      ret += "_plus_";
+    }
+    else if (cur_char == '-') {
+      ret += "_dash_";
+    }
+    else {
+      ret.push_back(cur_char);
+    }
+  }
+  return ret;
+}
+
+/// oneOf - Does the input string contain this character?
+bool oneOf(const char* lst, char c) {
+  while (*lst) {
+    if (*lst++ == c)
+      return true;
+  }
+  return false;
+}
+
+template <class I, class S>
+void checkedIncrement(I& P, I E, S ErrorString) {
+  ++P;
+  if (P == E)
+    throw ErrorString;
+}
+
+// apply is needed because C++'s syntax doesn't let us construct a function
+// object and call it in the same statement.
+template<typename F, typename T0>
+void apply(F Fun, T0& Arg0) {
+  return Fun(Arg0);
+}
+
+template<typename F, typename T0, typename T1>
+void apply(F Fun, T0& Arg0, T1& Arg1) {
+  return Fun(Arg0, Arg1);
 }
 
 //===----------------------------------------------------------------------===//
 /// 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
-//
-// Parameter - an option that takes one(and only one) argument, e.g. -o file,
-// --output=file
-//
-// ParameterList - same as Parameter, but more than one occurence
-// of the option is allowed, e.g. -lm -lpthread
-//
-// Prefix - argument is everything after the prefix,
-// e.g. -Wa,-foo,-bar, -DNAME=VALUE
-//
-// PrefixList - same as Prefix, but more than one option occurence is
-// allowed
 
+/// OptionType - One of six different option types. See the
+/// documentation for detailed description of differences.
 namespace OptionType {
-  enum OptionType { Switch, Parameter, ParameterList, Prefix, PrefixList};
+
+  enum OptionType { Alias, Switch, Parameter, ParameterList,
+                    Prefix, PrefixList};
+
+  bool IsAlias(OptionType t) {
+    return (t == Alias);
+  }
+
+  bool IsList (OptionType t) {
+    return (t == ParameterList || t == PrefixList);
+  }
+
+  bool IsSwitch (OptionType t) {
+    return (t == Switch);
+  }
+
+  bool IsParameter (OptionType t) {
+    return (t == Parameter || t == Prefix);
+  }
+
 }
 
-bool IsListOptionType (OptionType::OptionType t) {
-  return (t == OptionType::ParameterList || t == OptionType::PrefixList);
+OptionType::OptionType stringToOptionType(const std::string& T) {
+  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 + '!';
 }
 
-// Code duplication here is necessary because one option can affect
-// several tools and those tools may have different actions associated
-// with this option. GlobalOptionDescriptions are used to generate
-// the option registration code, while ToolOptionDescriptions are used
-// to generate tool-specific code.
+namespace OptionDescriptionFlags {
+  enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
+                                ReallyHidden = 0x4, Extern = 0x8,
+                                OneOrMore = 0x10, Optional = 0x20,
+                                CommaSeparated = 0x40 };
+}
 
-/// OptionDescription - Base class for option descriptions.
+/// OptionDescription - Represents data contained in a single
+/// OptionList entry.
 struct OptionDescription {
   OptionType::OptionType Type;
   std::string Name;
+  unsigned Flags;
+  std::string Help;
+  unsigned MultiVal;
+  Init* InitVal;
 
   OptionDescription(OptionType::OptionType t = OptionType::Switch,
-                    const std::string& n = "")
-  : Type(t), Name(n)
+                    const std::string& n = "",
+                    const std::string& h = DefaultHelpString)
+    : Type(t), Name(n), Flags(0x0), Help(h), MultiVal(1), InitVal(0)
   {}
 
-  const char* GenTypeDeclaration() const {
-    switch (Type) {
-    case OptionType::PrefixList:
-    case OptionType::ParameterList:
-      return "cl::list<std::string>";
-    case OptionType::Switch:
-      return "cl::opt<bool>";
-    case OptionType::Parameter:
-    case OptionType::Prefix:
-    default:
-      return "cl::opt<std::string>";
-    }
-  }
+  /// GenTypeDeclaration - Returns the C++ variable type of this
+  /// option.
+  const char* GenTypeDeclaration() const;
 
-  // 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::Switch:
-     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;
-   }
-  }
+  /// GenVariableName - Returns the variable name used in the
+  /// generated C++ code.
+  std::string GenVariableName() const;
+
+  /// Merge - Merge two option descriptions.
+  void Merge (const OptionDescription& other);
+
+  // Misc convenient getters/setters.
+
+  bool isAlias() const;
+
+  bool isMultiVal() const;
+
+  bool isCommaSeparated() const;
+  void setCommaSeparated();
+
+  bool isExtern() const;
+  void setExtern();
+
+  bool isRequired() const;
+  void setRequired();
+
+  bool isOneOrMore() const;
+  void setOneOrMore();
+
+  bool isOptional() const;
+  void setOptional();
+
+  bool isHidden() const;
+  void setHidden();
+
+  bool isReallyHidden() const;
+  void setReallyHidden();
+
+  bool isSwitch() const
+  { return OptionType::IsSwitch(this->Type); }
+
+  bool isParameter() const
+  { return OptionType::IsParameter(this->Type); }
+
+  bool isList() const
+  { return OptionType::IsList(this->Type); }
 
 };
 
-// Global option description.
+void OptionDescription::Merge (const OptionDescription& other)
+{
+  if (other.Type != Type)
+    throw "Conflicting definitions for the option " + Name + "!";
+
+  if (Help == other.Help || Help == DefaultHelpString)
+    Help = other.Help;
+  else if (other.Help != DefaultHelpString) {
+    llvm::errs() << "Warning: several different help strings"
+      " defined for option " + Name + "\n";
+  }
 
-namespace GlobalOptionDescriptionFlags {
-  enum GlobalOptionDescriptionFlags { Required = 0x1 };
+  Flags |= other.Flags;
 }
 
-struct GlobalOptionDescription : public OptionDescription {
-  std::string Help;
-  unsigned Flags;
+bool OptionDescription::isAlias() const {
+  return OptionType::IsAlias(this->Type);
+}
 
-  // We need to provide a default constructor because
-  // StringMap can only store DefaultConstructible objects.
-  GlobalOptionDescription() : OptionDescription(), Flags(0)
-  {}
+bool OptionDescription::isMultiVal() const {
+  return MultiVal > 1;
+}
 
-  GlobalOptionDescription (OptionType::OptionType t, const std::string& n)
-    : OptionDescription(t, n), Help(DefaultHelpString), Flags(0)
-  {}
+bool OptionDescription::isCommaSeparated() const {
+  return Flags & OptionDescriptionFlags::CommaSeparated;
+}
+void OptionDescription::setCommaSeparated() {
+  Flags |= OptionDescriptionFlags::CommaSeparated;
+}
 
-  bool isRequired() const {
-    return Flags & GlobalOptionDescriptionFlags::Required;
-  }
-  void setRequired() {
-    Flags |= GlobalOptionDescriptionFlags::Required;
-  }
+bool OptionDescription::isExtern() const {
+  return Flags & OptionDescriptionFlags::Extern;
+}
+void OptionDescription::setExtern() {
+  Flags |= OptionDescriptionFlags::Extern;
+}
 
-  /// Merge - Merge two option descriptions.
-  void Merge (const GlobalOptionDescription& other)
-  {
-    if (other.Type != Type)
-      throw "Conflicting definitions for the option " + Name + "!";
-
-    if (Help == DefaultHelpString)
-      Help = other.Help;
-    else if (other.Help != DefaultHelpString) {
-      llvm::cerr << "Warning: more than one help string defined for option "
-        + Name + "\n";
-    }
+bool OptionDescription::isRequired() const {
+  return Flags & OptionDescriptionFlags::Required;
+}
+void OptionDescription::setRequired() {
+  Flags |= OptionDescriptionFlags::Required;
+}
+
+bool OptionDescription::isOneOrMore() const {
+  return Flags & OptionDescriptionFlags::OneOrMore;
+}
+void OptionDescription::setOneOrMore() {
+  Flags |= OptionDescriptionFlags::OneOrMore;
+}
+
+bool OptionDescription::isOptional() const {
+  return Flags & OptionDescriptionFlags::Optional;
+}
+void OptionDescription::setOptional() {
+  Flags |= OptionDescriptionFlags::Optional;
+}
+
+bool OptionDescription::isHidden() const {
+  return Flags & OptionDescriptionFlags::Hidden;
+}
+void OptionDescription::setHidden() {
+  Flags |= OptionDescriptionFlags::Hidden;
+}
+
+bool OptionDescription::isReallyHidden() const {
+  return Flags & OptionDescriptionFlags::ReallyHidden;
+}
+void OptionDescription::setReallyHidden() {
+  Flags |= OptionDescriptionFlags::ReallyHidden;
+}
+
+const char* OptionDescription::GenTypeDeclaration() const {
+  switch (Type) {
+  case OptionType::Alias:
+    return "cl::alias";
+  case OptionType::PrefixList:
+  case OptionType::ParameterList:
+    return "cl::list<std::string>";
+  case OptionType::Switch:
+    return "cl::opt<bool>";
+  case OptionType::Parameter:
+  case OptionType::Prefix:
+  default:
+    return "cl::opt<std::string>";
+  }
+}
 
-    Flags |= other.Flags;
+std::string OptionDescription::GenVariableName() const {
+  const std::string& EscapedName = EscapeVariableName(Name);
+  switch (Type) {
+  case OptionType::Alias:
+    return "AutoGeneratedAlias_" + EscapedName;
+  case OptionType::PrefixList:
+  case OptionType::ParameterList:
+    return "AutoGeneratedList_" + EscapedName;
+  case OptionType::Switch:
+    return "AutoGeneratedSwitch_" + EscapedName;
+  case OptionType::Prefix:
+  case OptionType::Parameter:
+  default:
+    return "AutoGeneratedParameter_" + EscapedName;
   }
-};
+}
 
-/// 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;
+/// OptionDescriptions - An OptionDescription array plus some helper
+/// functions.
+class OptionDescriptions {
+  typedef StringMap<OptionDescription> container_type;
 
-  /// Descriptions - A list of GlobalOptionDescriptions.
+  /// Descriptions - A list of OptionDescriptions.
   container_type Descriptions;
-  /// HasSink - Should the emitter generate a "cl::sink" option?
-  bool HasSink;
 
-  const GlobalOptionDescription& FindOption(const std::string& OptName) const {
-    const_iterator I = Descriptions.find(OptName);
-    if (I != Descriptions.end())
-      return I->second;
-    else
-      throw OptName + ": no such option!";
-  }
+public:
+  /// FindOption - exception-throwing wrapper for find().
+  const OptionDescription& FindOption(const std::string& OptName) const;
+
+  // Wrappers for FindOption that throw an exception in case the option has a
+  // wrong type.
+  const OptionDescription& FindSwitch(const std::string& OptName) const;
+  const OptionDescription& FindParameter(const std::string& OptName) const;
+  const OptionDescription& FindList(const std::string& OptName) const;
+  const OptionDescription&
+  FindListOrParameter(const std::string& OptName) const;
+
+  /// insertDescription - Insert new OptionDescription into
+  /// OptionDescriptions list
+  void InsertDescription (const OptionDescription& o);
 
   // Support for STL-style iteration
+  typedef container_type::const_iterator const_iterator;
   const_iterator begin() const { return Descriptions.begin(); }
   const_iterator end() const { return Descriptions.end(); }
 };
 
-
-// Tool-local option description.
-
-// Properties without arguments are implemented as flags.
-namespace ToolOptionDescriptionFlags {
-  enum ToolOptionDescriptionFlags { StopCompilation = 0x1,
-                                    Forward = 0x2, UnpackValues = 0x4};
-}
-namespace OptionPropertyType {
-  enum OptionPropertyType { AppendCmd };
+const OptionDescription&
+OptionDescriptions::FindOption(const std::string& OptName) const {
+  const_iterator I = Descriptions.find(OptName);
+  if (I != Descriptions.end())
+    return I->second;
+  else
+    throw OptName + ": no such option!";
 }
 
-typedef std::pair<OptionPropertyType::OptionPropertyType, std::string>
-OptionProperty;
-typedef SmallVector<OptionProperty, 4> OptionPropertyList;
-
-struct ToolOptionDescription : public OptionDescription {
-  unsigned Flags;
-  OptionPropertyList Props;
+const OptionDescription&
+OptionDescriptions::FindSwitch(const std::string& OptName) const {
+  const OptionDescription& OptDesc = this->FindOption(OptName);
+  if (!OptDesc.isSwitch())
+    throw OptName + ": incorrect option type - should be a switch!";
+  return OptDesc;
+}
 
-  // StringMap can only store DefaultConstructible objects
-  ToolOptionDescription() : OptionDescription(), Flags(0) {}
+const OptionDescription&
+OptionDescriptions::FindList(const std::string& OptName) const {
+  const OptionDescription& OptDesc = this->FindOption(OptName);
+  if (!OptDesc.isList())
+    throw OptName + ": incorrect option type - should be a list!";
+  return OptDesc;
+}
 
-  ToolOptionDescription (OptionType::OptionType t, const std::string& n)
-    : OptionDescription(t, n)
-  {}
+const OptionDescription&
+OptionDescriptions::FindParameter(const std::string& OptName) const {
+  const OptionDescription& OptDesc = this->FindOption(OptName);
+  if (!OptDesc.isParameter())
+    throw OptName + ": incorrect option type - should be a parameter!";
+  return OptDesc;
+}
 
-  // Various boolean properties
-  bool isStopCompilation() const {
-    return Flags & ToolOptionDescriptionFlags::StopCompilation;
-  }
-  void setStopCompilation() {
-    Flags |= ToolOptionDescriptionFlags::StopCompilation;
-  }
+const OptionDescription&
+OptionDescriptions::FindListOrParameter(const std::string& OptName) const {
+  const OptionDescription& OptDesc = this->FindOption(OptName);
+  if (!OptDesc.isList() && !OptDesc.isParameter())
+    throw OptName
+      + ": incorrect option type - should be a list or parameter!";
+  return OptDesc;
+}
 
-  bool isForward() const {
-    return Flags & ToolOptionDescriptionFlags::Forward;
+void OptionDescriptions::InsertDescription (const OptionDescription& o) {
+  container_type::iterator I = Descriptions.find(o.Name);
+  if (I != Descriptions.end()) {
+    OptionDescription& D = I->second;
+    D.Merge(o);
   }
-  void setForward() {
-    Flags |= ToolOptionDescriptionFlags::Forward;
+  else {
+    Descriptions[o.Name] = o;
   }
+}
 
-  bool isUnpackValues() const {
-    return Flags & ToolOptionDescriptionFlags::UnpackValues;
-  }
-  void setUnpackValues() {
-    Flags |= ToolOptionDescriptionFlags::UnpackValues;
-  }
+/// HandlerTable - A base class for function objects implemented as
+/// 'tables of handlers'.
+template <typename Handler>
+class HandlerTable {
+protected:
+  // Implementation details.
 
-  void AddProperty (OptionPropertyType::OptionPropertyType t,
-                    const std::string& val)
-  {
-    Props.push_back(std::make_pair(t, val));
-  }
-};
+  /// HandlerMap - A map from property names to property handlers
+  typedef StringMap<Handler> HandlerMap;
 
-typedef StringMap<ToolOptionDescription> ToolOptionDescriptions;
+  static HandlerMap Handlers_;
+  static bool staticMembersInitialized_;
 
-// Tool information record
+public:
 
-namespace ToolFlags {
-  enum ToolFlags { Join = 0x1, Sink = 0x2 };
-}
+  Handler GetHandler (const std::string& HandlerName) const {
+    typename HandlerMap::iterator method = Handlers_.find(HandlerName);
 
-struct ToolProperties : public RefCountedBase<ToolProperties> {
-  std::string Name;
-  Init* CmdLine;
-  std::string InLanguage;
-  std::string OutLanguage;
-  std::string OutputSuffix;
-  unsigned Flags;
-  ToolOptionDescriptions OptDescs;
+    if (method != Handlers_.end()) {
+      Handler h = method->second;
+      return h;
+    }
+    else {
+      throw "No handler found for property " + HandlerName + "!";
+    }
+  }
 
-  // Various boolean properties
-  void setSink()      { Flags |= ToolFlags::Sink; }
-  bool isSink() const { return Flags & ToolFlags::Sink; }
-  void setJoin()      { Flags |= ToolFlags::Join; }
-  bool isJoin() const { return Flags & ToolFlags::Join; }
+  void AddHandler(const char* Property, Handler H) {
+    Handlers_[Property] = H;
+  }
 
-  // Default ctor here is needed because StringMap can only store
-  // DefaultConstructible objects
-  ToolProperties() : Flags(0) {}
-  ToolProperties (const std::string& n) : Name(n), Flags(0) {}
 };
 
+template <class Handler, class FunctionObject>
+Handler GetHandler(FunctionObject* Obj, const DagInit& Dag) {
+  const std::string& HandlerName = GetOperatorName(Dag);
+  return Obj->GetHandler(HandlerName);
+}
 
-/// 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;
+template <class FunctionObject>
+void InvokeDagInitHandler(FunctionObject* Obj, Init* I) {
+  typedef void (FunctionObject::*Handler) (const DagInit&);
 
+  const DagInit& Dag = InitPtrToDag(I);
+  Handler h = GetHandler<Handler>(Obj, Dag);
 
-/// CollectProperties - Function object for iterating over a list of
-/// tool property records.
-class CollectProperties {
-private:
+  ((Obj)->*(h))(Dag);
+}
 
-  /// Implementation details
+template <class FunctionObject>
+void InvokeDagInitHandler(const FunctionObject* const Obj,
+                          const Init* I, unsigned IndentLevel, raw_ostream& O)
+{
+  typedef void (FunctionObject::*Handler)
+    (const DagInit&, unsigned IndentLevel, raw_ostream& O) const;
 
-  /// PropertyHandler - a function that extracts information
-  /// about a given tool property from its DAG representation
-  typedef void (CollectProperties::*PropertyHandler)(const DagInit*);
+  const DagInit& Dag = InitPtrToDag(I);
+  Handler h = GetHandler<Handler>(Obj, Dag);
 
-  /// PropertyHandlerMap - A map from property names to property
-  /// handlers.
-  typedef StringMap<PropertyHandler> PropertyHandlerMap;
+  ((Obj)->*(h))(Dag, IndentLevel, O);
+}
 
-  /// OptionPropertyHandler - a function that extracts information
-  /// about a given option property from its DAG representation.
-  typedef void (CollectProperties::* OptionPropertyHandler)
-  (const DagInit*, GlobalOptionDescription &);
 
-  /// OptionPropertyHandlerMap - A map from option property names to
-  /// option property handlers
-  typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
+template <typename H>
+typename HandlerTable<H>::HandlerMap HandlerTable<H>::Handlers_;
 
-  // Static maps from strings to CollectProperties methods("handlers")
-  static PropertyHandlerMap propertyHandlers_;
-  static OptionPropertyHandlerMap optionPropertyHandlers_;
-  static bool staticMembersInitialized_;
+template <typename H>
+bool HandlerTable<H>::staticMembersInitialized_ = false;
 
 
-  /// This is where the information is stored
+/// CollectOptionProperties - Function object for iterating over an
+/// option property list.
+class CollectOptionProperties;
+typedef void (CollectOptionProperties::* CollectOptionPropertiesHandler)
+(const DagInit&);
 
-  /// toolProps_ -  Properties of the current Tool.
-  ToolProperties& toolProps_;
-  /// optDescs_ - OptionDescriptions table (used to register options
-  /// globally).
-  GlobalOptionDescriptions& optDescs_;
+class CollectOptionProperties
+: public HandlerTable<CollectOptionPropertiesHandler>
+{
+private:
+
+  /// optDescs_ - OptionDescriptions table. This is where the
+  /// information is stored.
+  OptionDescription& optDesc_;
 
 public:
 
-  explicit CollectProperties (ToolProperties& p, GlobalOptionDescriptions& d)
-    : toolProps_(p), optDescs_(d)
+  explicit CollectOptionProperties(OptionDescription& OD)
+    : optDesc_(OD)
   {
     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;
-      propertyHandlers_["parameter_list_option"] =
-        &CollectProperties::onParameterList;
-      propertyHandlers_["prefix_option"] = &CollectProperties::onPrefix;
-      propertyHandlers_["prefix_list_option"] =
-        &CollectProperties::onPrefixList;
-      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;
+      AddHandler("extern", &CollectOptionProperties::onExtern);
+      AddHandler("help", &CollectOptionProperties::onHelp);
+      AddHandler("hidden", &CollectOptionProperties::onHidden);
+      AddHandler("init", &CollectOptionProperties::onInit);
+      AddHandler("multi_val", &CollectOptionProperties::onMultiVal);
+      AddHandler("one_or_more", &CollectOptionProperties::onOneOrMore);
+      AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
+      AddHandler("required", &CollectOptionProperties::onRequired);
+      AddHandler("optional", &CollectOptionProperties::onOptional);
+      AddHandler("comma_separated", &CollectOptionProperties::onCommaSeparated);
 
       staticMembersInitialized_ = true;
     }
   }
 
-  /// operator() - Gets called for every tool property; Just forwards
-  /// to the corresponding property handler.
-  void operator() (Init* i) {
-    const DagInit& d = InitPtrToDagInitRef(i);
-    const std::string& property_name = d.getOperator()->getAsString();
-    PropertyHandlerMap::iterator method
-      = propertyHandlers_.find(property_name);
-
-    if (method != propertyHandlers_.end()) {
-      PropertyHandler h = method->second;
-      (this->*h)(&d);
-    }
-    else {
-      throw "Unknown tool property: " + property_name + "!";
-    }
+  /// operator() - Just forwards to the corresponding property
+  /// handler.
+  void operator() (Init* I) {
+    InvokeDagInitHandler(this, I);
   }
 
 private:
 
-  /// Property handlers --
-  /// Functions that extract information about tool properties from
-  /// DAG representation.
+  /// Option property handlers --
+  /// Methods that handle option properties such as (help) or (hidden).
 
-  void onCmdLine (const DagInit* d) {
-    checkNumberOfArguments(d, 1);
-    toolProps_.CmdLine = d->getArg(0);
+  void onExtern (const DagInit& d) {
+    checkNumberOfArguments(d, 0);
+    optDesc_.setExtern();
   }
 
-  void onInLanguage (const DagInit* d) {
+  void onHelp (const DagInit& d) {
     checkNumberOfArguments(d, 1);
-    toolProps_.InLanguage = InitPtrToString(d->getArg(0));
+    optDesc_.Help = InitPtrToString(d.getArg(0));
   }
 
-  void onJoin (const DagInit* d) {
+  void onHidden (const DagInit& d) {
     checkNumberOfArguments(d, 0);
-    toolProps_.setJoin();
-  }
-
-  void onOutLanguage (const DagInit* d) {
-    checkNumberOfArguments(d, 1);
-    toolProps_.OutLanguage = InitPtrToString(d->getArg(0));
+    optDesc_.setHidden();
   }
 
-  void onOutputSuffix (const DagInit* d) {
-    checkNumberOfArguments(d, 1);
-    toolProps_.OutputSuffix = InitPtrToString(d->getArg(0));
+  void onReallyHidden (const DagInit& d) {
+    checkNumberOfArguments(d, 0);
+    optDesc_.setReallyHidden();
   }
 
-  void onSink (const DagInit* d) {
+  void onCommaSeparated (const DagInit& d) {
     checkNumberOfArguments(d, 0);
-    optDescs_.HasSink = true;
-    toolProps_.setSink();
+    if (!optDesc_.isList())
+      throw "'comma_separated' is valid only on list options!";
+    optDesc_.setCommaSeparated();
   }
 
-  void onSwitch (const DagInit* d) {
-    addOption(d, OptionType::Switch);
+  void onRequired (const DagInit& d) {
+    checkNumberOfArguments(d, 0);
+    if (optDesc_.isOneOrMore() || optDesc_.isOptional())
+      throw "Only one of (required), (optional) or "
+        "(one_or_more) properties is allowed!";
+    optDesc_.setRequired();
   }
 
-  void onParameter (const DagInit* d) {
-    addOption(d, OptionType::Parameter);
-  }
+  void onInit (const DagInit& d) {
+    checkNumberOfArguments(d, 1);
+    Init* i = d.getArg(0);
+    const std::string& str = i->getAsString();
 
-  void onParameterList (const DagInit* d) {
-    addOption(d, OptionType::ParameterList);
-  }
+    bool correct = optDesc_.isParameter() && dynamic_cast<StringInit*>(i);
+    correct |= (optDesc_.isSwitch() && (str == "true" || str == "false"));
 
-  void onPrefix (const DagInit* d) {
-    addOption(d, OptionType::Prefix);
-  }
+    if (!correct)
+      throw "Incorrect usage of the 'init' option property!";
 
-  void onPrefixList (const DagInit* d) {
-    addOption(d, OptionType::PrefixList);
+    optDesc_.InitVal = i;
   }
 
-  /// 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, GlobalOptionDescription& o) {
-    checkNumberOfArguments(d, 1);
-    std::string const& cmd = InitPtrToString(d->getArg(0));
-
-    toolProps_.OptDescs[o.Name].AddProperty(OptionPropertyType::AppendCmd, cmd);
+  void onOneOrMore (const DagInit& d) {
+    checkNumberOfArguments(d, 0);
+    if (optDesc_.isRequired() || optDesc_.isOptional())
+      throw "Only one of (required), (optional) or "
+        "(one_or_more) properties is allowed!";
+    if (!OptionType::IsList(optDesc_.Type))
+      llvm::errs() << "Warning: specifying the 'one_or_more' property "
+        "on a non-list option will have no effect.\n";
+    optDesc_.setOneOrMore();
   }
 
-  void onForward (const DagInit* d, GlobalOptionDescription& o) {
+  void onOptional (const DagInit& d) {
     checkNumberOfArguments(d, 0);
-    toolProps_.OptDescs[o.Name].setForward();
+    if (optDesc_.isRequired() || optDesc_.isOneOrMore())
+      throw "Only one of (required), (optional) or "
+        "(one_or_more) properties is allowed!";
+    if (!OptionType::IsList(optDesc_.Type))
+      llvm::errs() << "Warning: specifying the 'optional' property"
+        "on a non-list option will have no effect.\n";
+    optDesc_.setOptional();
   }
 
-  void onHelp (const DagInit* d, GlobalOptionDescription& o) {
+  void onMultiVal (const DagInit& d) {
     checkNumberOfArguments(d, 1);
-    const std::string& help_message = InitPtrToString(d->getArg(0));
-
-    o.Help = help_message;
+    int val = InitPtrToInt(d.getArg(0));
+    if (val < 2)
+      throw "Error in the 'multi_val' property: "
+        "the value must be greater than 1!";
+    if (!OptionType::IsList(optDesc_.Type))
+      throw "The multi_val property is valid only on list options!";
+    optDesc_.MultiVal = val;
   }
 
-  void onRequired (const DagInit* d, GlobalOptionDescription& o) {
-    checkNumberOfArguments(d, 0);
-    o.setRequired();
-  }
+};
 
-  void onStopCompilation (const 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();
-  }
+/// AddOption - A function object that is applied to every option
+/// description. Used by CollectOptionDescriptions.
+class AddOption {
+private:
+  OptionDescriptions& OptDescs_;
 
-  void onUnpackValues (const DagInit* d, GlobalOptionDescription& o) {
-    checkNumberOfArguments(d, 0);
-    toolProps_.OptDescs[o.Name].setUnpackValues();
-  }
+public:
+  explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
+  {}
+
+  void operator()(const Init* i) {
+    const DagInit& d = InitPtrToDag(i);
+    checkNumberOfArguments(d, 1);
 
-  /// Helper functions
+    const OptionType::OptionType Type =
+      stringToOptionType(GetOperatorName(d));
+    const std::string& Name = InitPtrToString(d.getArg(0));
 
-  // Add an option of type t
-  void addOption (const DagInit* d, OptionType::OptionType t) {
-    checkNumberOfArguments(d, 2);
-    const std::string& name = InitPtrToString(d->getArg(0));
+    OptionDescription OD(Type, Name);
 
-    GlobalOptionDescription o(t, name);
-    toolProps_.OptDescs[name].Type = t;
-    toolProps_.OptDescs[name].Name = name;
-    processOptionProperties(d, o);
-    insertDescription(o);
-  }
+    if (!OD.isExtern())
+      checkNumberOfArguments(d, 2);
 
-  // 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);
+    if (OD.isAlias()) {
+      // Aliases store the aliased option name in the 'Help' field.
+      OD.Help = InitPtrToString(d.getArg(1));
     }
-    else {
-      optDescs_.Descriptions[o.Name] = o;
+    else if (!OD.isExtern()) {
+      processOptionProperties(d, OD);
     }
+    OptDescs_.InsertDescription(OD);
   }
 
+private:
   /// processOptionProperties - Go through the list of option
   /// properties and call a corresponding handler for each.
-  ///
-  /// Parameters:
-  /// name - option name
-  /// d - option property list
-  void processOptionProperties (const DagInit* d, GlobalOptionDescription& o) {
-    // First argument is option name
+  static void processOptionProperties (const DagInit& d, OptionDescription& o) {
     checkNumberOfArguments(d, 2);
-
-    for (unsigned B = 1, E = d->getNumArgs(); B!=E; ++B) {
-      const DagInit& option_property
-        = InitPtrToDagInitRef(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 + "!";
-      }
-    }
+    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(o));
   }
-};
-
-// Static members of CollectProperties
-CollectProperties::PropertyHandlerMap
-CollectProperties::propertyHandlers_;
-
-CollectProperties::OptionPropertyHandlerMap
-CollectProperties::optionPropertyHandlers_;
-
-bool CollectProperties::staticMembersInitialized_ = false;
 
+};
 
-/// CollectToolProperties - Gather information 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)
+/// CollectOptionDescriptions - Collects option properties from all
+/// OptionLists.
+void CollectOptionDescriptions (RecordVector::const_iterator B,
+                                RecordVector::const_iterator E,
+                                OptionDescriptions& OptDescs)
 {
-  // Iterate over a properties list of every Tool definition
-  for (;B!=E;++B) {
+  // For every OptionList:
+  for (; B!=E; ++B) {
     RecordVector::value_type T = *B;
-    ListInit* PropList = T->getValueAsListInit("properties");
-
-    IntrusiveRefCntPtr<ToolProperties>
-      ToolProps(new ToolProperties(T->getName()));
+    // Throws an exception if the value does not exist.
+    ListInit* PropList = T->getValueAsListInit("options");
 
-    std::for_each(PropList->begin(), PropList->end(),
-                  CollectProperties(*ToolProps, OptDescs));
-    TPList.push_back(ToolProps);
+    // For every option description in this list:
+    // collect the information and
+    std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
   }
 }
 
-/// 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;
-  }
+// Tool information record
 
-  return false;
+namespace ToolFlags {
+  enum ToolFlags { Join = 0x1, Sink = 0x2 };
 }
 
-/// EmitCaseTest2Args - Helper function used by
-/// EmitCaseConstructHandler.
+struct ToolDescription : public RefCountedBase<ToolDescription> {
+  std::string Name;
+  Init* CmdLine;
+  Init* Actions;
+  StrVector InLanguage;
+  std::string OutLanguage;
+  std::string OutputSuffix;
+  unsigned Flags;
+
+  // Various boolean properties
+  void setSink()      { Flags |= ToolFlags::Sink; }
+  bool isSink() const { return Flags & ToolFlags::Sink; }
+  void setJoin()      { Flags |= ToolFlags::Join; }
+  bool isJoin() const { return Flags & ToolFlags::Join; }
+
+  // Default ctor here is needed because StringMap can only store
+  // DefaultConstructible objects
+  ToolDescription() : CmdLine(0), Actions(0), Flags(0) {}
+  ToolDescription (const std::string& n)
+  : Name(n), CmdLine(0), Actions(0), Flags(0)
+  {}
+};
+
+/// ToolDescriptions - A list of Tool information records.
+typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
+
+
+/// CollectToolProperties - Function object for iterating over a list of
+/// tool property records.
+
+class CollectToolProperties;
+typedef void (CollectToolProperties::* CollectToolPropertiesHandler)
+(const DagInit&);
+
+class CollectToolProperties : public HandlerTable<CollectToolPropertiesHandler>
+{
+private:
+
+  /// toolDesc_ - Properties of the current Tool. This is where the
+  /// information is stored.
+  ToolDescription& toolDesc_;
+
+public:
+
+  explicit CollectToolProperties (ToolDescription& d)
+    : toolDesc_(d)
+  {
+    if (!staticMembersInitialized_) {
+
+      AddHandler("actions", &CollectToolProperties::onActions);
+      AddHandler("cmd_line", &CollectToolProperties::onCmdLine);
+      AddHandler("in_language", &CollectToolProperties::onInLanguage);
+      AddHandler("join", &CollectToolProperties::onJoin);
+      AddHandler("out_language", &CollectToolProperties::onOutLanguage);
+      AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
+      AddHandler("sink", &CollectToolProperties::onSink);
+
+      staticMembersInitialized_ = true;
+    }
+  }
+
+  void operator() (Init* I) {
+    InvokeDagInitHandler(this, I);
+  }
+
+private:
+
+  /// Property handlers --
+  /// Functions that extract information about tool properties from
+  /// DAG representation.
+
+  void onActions (const DagInit& d) {
+    checkNumberOfArguments(d, 1);
+    Init* Case = d.getArg(0);
+    if (typeid(*Case) != typeid(DagInit) ||
+        GetOperatorName(static_cast<DagInit&>(*Case)) != "case")
+      throw "The argument to (actions) should be a 'case' construct!";
+    toolDesc_.Actions = Case;
+  }
+
+  void onCmdLine (const DagInit& d) {
+    checkNumberOfArguments(d, 1);
+    toolDesc_.CmdLine = d.getArg(0);
+  }
+
+  void onInLanguage (const DagInit& d) {
+    checkNumberOfArguments(d, 1);
+    Init* arg = d.getArg(0);
+
+    // Find out the argument's type.
+    if (typeid(*arg) == typeid(StringInit)) {
+      // It's a string.
+      toolDesc_.InLanguage.push_back(InitPtrToString(arg));
+    }
+    else {
+      // It's a list.
+      const ListInit& lst = InitPtrToList(arg);
+      StrVector& out = toolDesc_.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 (const DagInit& d) {
+    checkNumberOfArguments(d, 0);
+    toolDesc_.setJoin();
+  }
+
+  void onOutLanguage (const DagInit& d) {
+    checkNumberOfArguments(d, 1);
+    toolDesc_.OutLanguage = InitPtrToString(d.getArg(0));
+  }
+
+  void onOutputSuffix (const DagInit& d) {
+    checkNumberOfArguments(d, 1);
+    toolDesc_.OutputSuffix = InitPtrToString(d.getArg(0));
+  }
+
+  void onSink (const DagInit& d) {
+    checkNumberOfArguments(d, 0);
+    toolDesc_.setSink();
+  }
+
+};
+
+/// CollectToolDescriptions - Gather information about tool properties
+/// from the parsed TableGen data (basically a wrapper for the
+/// CollectToolProperties function object).
+void CollectToolDescriptions (RecordVector::const_iterator B,
+                              RecordVector::const_iterator E,
+                              ToolDescriptions& ToolDescs)
+{
+  // Iterate over a properties list of every Tool definition
+  for (;B!=E;++B) {
+    const Record* T = *B;
+    // Throws an exception if the value does not exist.
+    ListInit* PropList = T->getValueAsListInit("properties");
+
+    IntrusiveRefCntPtr<ToolDescription>
+      ToolDesc(new ToolDescription(T->getName()));
+
+    std::for_each(PropList->begin(), PropList->end(),
+                  CollectToolProperties(*ToolDesc));
+    ToolDescs.push_back(ToolDesc);
+  }
+}
+
+/// FillInEdgeVector - Merge all compilation graph definitions into
+/// one single edge list.
+void FillInEdgeVector(RecordVector::const_iterator B,
+                      RecordVector::const_iterator E, RecordVector& Out) {
+  for (; B != E; ++B) {
+    const ListInit* edges = (*B)->getValueAsListInit("edges");
+
+    for (unsigned i = 0; i < edges->size(); ++i)
+      Out.push_back(edges->getElementAsRecord(i));
+  }
+}
+
+/// CalculatePriority - Calculate the priority of this plugin.
+int CalculatePriority(RecordVector::const_iterator B,
+                      RecordVector::const_iterator E) {
+  int priority = 0;
+
+  if (B != E) {
+    priority  = static_cast<int>((*B)->getValueAsInt("priority"));
+
+    if (++B != E)
+      throw "More than one 'PluginPriority' instance found: "
+        "most probably an error!";
+  }
+
+  return priority;
+}
+
+/// NotInGraph - Helper function object for FilterNotInGraph.
+struct NotInGraph {
+private:
+  const llvm::StringSet<>& ToolsInGraph_;
+
+public:
+  NotInGraph(const llvm::StringSet<>& ToolsInGraph)
+  : ToolsInGraph_(ToolsInGraph)
+  {}
+
+  bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
+    return (ToolsInGraph_.count(x->Name) == 0);
+  }
+};
+
+/// FilterNotInGraph - Filter out from ToolDescs all Tools not
+/// mentioned in the compilation graph definition.
+void FilterNotInGraph (const RecordVector& EdgeVector,
+                       ToolDescriptions& ToolDescs) {
+
+  // List all tools mentioned in the graph.
+  llvm::StringSet<> ToolsInGraph;
+
+  for (RecordVector::const_iterator B = EdgeVector.begin(),
+         E = EdgeVector.end(); B != E; ++B) {
+
+    const Record* Edge = *B;
+    const std::string& NodeA = Edge->getValueAsString("a");
+    const std::string& NodeB = Edge->getValueAsString("b");
+
+    if (NodeA != "root")
+      ToolsInGraph.insert(NodeA);
+    ToolsInGraph.insert(NodeB);
+  }
+
+  // Filter ToolPropertiesList.
+  ToolDescriptions::iterator new_end =
+    std::remove_if(ToolDescs.begin(), ToolDescs.end(),
+                   NotInGraph(ToolsInGraph));
+  ToolDescs.erase(new_end, ToolDescs.end());
+}
+
+/// FillInToolToLang - Fills in two tables that map tool names to
+/// (input, output) languages.  Helper function used by TypecheckGraph().
+void FillInToolToLang (const ToolDescriptions& ToolDescs,
+                       StringMap<StringSet<> >& ToolToInLang,
+                       StringMap<std::string>& ToolToOutLang) {
+  for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
+         E = ToolDescs.end(); B != E; ++B) {
+    const ToolDescription& D = *(*B);
+    for (StrVector::const_iterator B = D.InLanguage.begin(),
+           E = D.InLanguage.end(); B != E; ++B)
+      ToolToInLang[D.Name].insert(*B);
+    ToolToOutLang[D.Name] = D.OutLanguage;
+  }
+}
+
+/// TypecheckGraph - Check that names for output and input languages
+/// on all edges do match. This doesn't do much when the information
+/// about the whole graph is not available (i.e. when compiling most
+/// plugins).
+void TypecheckGraph (const RecordVector& EdgeVector,
+                     const ToolDescriptions& ToolDescs) {
+  StringMap<StringSet<> > ToolToInLang;
+  StringMap<std::string> ToolToOutLang;
+
+  FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
+  StringMap<std::string>::iterator IAE = ToolToOutLang.end();
+  StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
+
+  for (RecordVector::const_iterator B = EdgeVector.begin(),
+         E = EdgeVector.end(); B != E; ++B) {
+    const Record* Edge = *B;
+    const std::string& NodeA = Edge->getValueAsString("a");
+    const std::string& NodeB = Edge->getValueAsString("b");
+    StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
+    StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
+
+    if (NodeA != "root") {
+      if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
+        throw "Edge " + NodeA + "->" + NodeB
+          + ": output->input language mismatch";
+    }
+
+    if (NodeB == "root")
+      throw "Edges back to the root are not allowed!";
+  }
+}
+
+/// WalkCase - Walks the 'case' expression DAG and invokes
+/// TestCallback on every test, and StatementCallback on every
+/// statement. Handles 'case' nesting, but not the 'and' and 'or'
+/// combinators (that is, they are passed directly to TestCallback).
+/// TestCallback must have type 'void TestCallback(const DagInit*, unsigned
+/// IndentLevel, bool FirstTest)'.
+/// StatementCallback must have type 'void StatementCallback(const Init*,
+/// unsigned IndentLevel)'.
+template <typename F1, typename F2>
+void WalkCase(const Init* Case, F1 TestCallback, F2 StatementCallback,
+              unsigned IndentLevel = 0)
+{
+  const DagInit& d = InitPtrToDag(Case);
+
+  // Error checks.
+  if (GetOperatorName(d) != "case")
+    throw "WalkCase should be invoked only on 'case' expressions!";
+
+  if (d.getNumArgs() < 2)
+    throw "There should be at least one clause in the 'case' expression:\n"
+      + d.getAsString();
+
+  // Main loop.
+  bool even = false;
+  const unsigned numArgs = d.getNumArgs();
+  unsigned i = 1;
+  for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
+       B != E; ++B) {
+    Init* arg = *B;
+
+    if (!even)
+    {
+      // Handle test.
+      const DagInit& Test = InitPtrToDag(arg);
+
+      if (GetOperatorName(Test) == "default" && (i+1 != numArgs))
+        throw "The 'default' clause should be the last in the "
+          "'case' construct!";
+      if (i == numArgs)
+        throw "Case construct handler: no corresponding action "
+          "found for the test " + Test.getAsString() + '!';
+
+      TestCallback(Test, IndentLevel, (i == 1));
+    }
+    else
+    {
+      if (dynamic_cast<DagInit*>(arg)
+          && GetOperatorName(static_cast<DagInit&>(*arg)) == "case") {
+        // Nested 'case'.
+        WalkCase(arg, TestCallback, StatementCallback, IndentLevel + Indent1);
+      }
+
+      // Handle statement.
+      StatementCallback(arg, IndentLevel);
+    }
+
+    ++i;
+    even = !even;
+  }
+}
+
+/// ExtractOptionNames - A helper function object used by
+/// CheckForSuperfluousOptions() to walk the 'case' DAG.
+class ExtractOptionNames {
+  llvm::StringSet<>& OptionNames_;
+
+  void processDag(const Init* Statement) {
+    const DagInit& Stmt = InitPtrToDag(Statement);
+    const std::string& ActionName = GetOperatorName(Stmt);
+    if (ActionName == "forward" || ActionName == "forward_as" ||
+        ActionName == "forward_value" ||
+        ActionName == "forward_transformed_value" ||
+        ActionName == "switch_on" || ActionName == "parameter_equals" ||
+        ActionName == "element_in_list" || ActionName == "not_empty" ||
+        ActionName == "empty") {
+      checkNumberOfArguments(Stmt, 1);
+      const std::string& Name = InitPtrToString(Stmt.getArg(0));
+      OptionNames_.insert(Name);
+    }
+    else if (ActionName == "and" || ActionName == "or") {
+      for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
+        this->processDag(Stmt.getArg(i));
+      }
+    }
+  }
+
+public:
+  ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
+  {}
+
+  void operator()(const Init* Statement) {
+    if (typeid(*Statement) == typeid(ListInit)) {
+      const ListInit& DagList = *static_cast<const ListInit*>(Statement);
+      for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
+           B != E; ++B)
+        this->processDag(*B);
+    }
+    else {
+      this->processDag(Statement);
+    }
+  }
+
+  void operator()(const DagInit& Test, unsigned, bool) {
+    this->operator()(&Test);
+  }
+  void operator()(const Init* Statement, unsigned) {
+    this->operator()(Statement);
+  }
+};
+
+/// CheckForSuperfluousOptions - Check that there are no side
+/// effect-free options (specified only in the OptionList). Otherwise,
+/// output a warning.
+void CheckForSuperfluousOptions (const RecordVector& Edges,
+                                 const ToolDescriptions& ToolDescs,
+                                 const OptionDescriptions& OptDescs) {
+  llvm::StringSet<> nonSuperfluousOptions;
+
+  // Add all options mentioned in the ToolDesc.Actions to the set of
+  // non-superfluous options.
+  for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
+         E = ToolDescs.end(); B != E; ++B) {
+    const ToolDescription& TD = *(*B);
+    ExtractOptionNames Callback(nonSuperfluousOptions);
+    if (TD.Actions)
+      WalkCase(TD.Actions, Callback, Callback);
+  }
+
+  // Add all options mentioned in the 'case' clauses of the
+  // OptionalEdges of the compilation graph to the set of
+  // non-superfluous options.
+  for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
+       B != E; ++B) {
+    const Record* Edge = *B;
+    DagInit& Weight = *Edge->getValueAsDag("weight");
+
+    if (!isDagEmpty(Weight))
+      WalkCase(&Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
+  }
+
+  // Check that all options in OptDescs belong to the set of
+  // non-superfluous options.
+  for (OptionDescriptions::const_iterator B = OptDescs.begin(),
+         E = OptDescs.end(); B != E; ++B) {
+    const OptionDescription& Val = B->second;
+    if (!nonSuperfluousOptions.count(Val.Name)
+        && Val.Type != OptionType::Alias)
+      llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! "
+        "Probable cause: this option is specified only in the OptionList.\n";
+  }
+}
+
+/// EmitCaseTest0Args - Helper function used by EmitCaseConstructHandler().
+bool EmitCaseTest0Args(const std::string& TestName, raw_ostream& O) {
+  if (TestName == "single_input_file") {
+    O << "InputFilenames.size() == 1";
+    return true;
+  }
+  else if (TestName == "multiple_input_files") {
+    O << "InputFilenames.size() > 1";
+    return true;
+  }
+
+  return false;
+}
+
+/// EmitListTest - Helper function used by EmitCaseTest1ArgList().
+template <typename F>
+void EmitListTest(const ListInit& L, const char* LogicOp,
+                  F Callback, raw_ostream& O)
+{
+  // This is a lot like EmitLogicalOperationTest, but works on ListInits instead
+  // of Dags...
+  bool isFirst = true;
+  for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B) {
+    if (isFirst)
+      isFirst = false;
+    else
+      O << " || ";
+    Callback(InitPtrToString(*B), O);
+  }
+}
+
+// Callbacks for use with EmitListTest.
+
+class EmitSwitchOn {
+  const OptionDescriptions& OptDescs_;
+public:
+  EmitSwitchOn(const OptionDescriptions& OptDescs) : OptDescs_(OptDescs)
+  {}
+
+  void operator()(const std::string& OptName, raw_ostream& O) const {
+    const OptionDescription& OptDesc = OptDescs_.FindSwitch(OptName);
+    O << OptDesc.GenVariableName();
+  }
+};
+
+class EmitEmptyTest {
+  bool EmitNegate_;
+  const OptionDescriptions& OptDescs_;
+public:
+  EmitEmptyTest(bool EmitNegate, const OptionDescriptions& OptDescs)
+    : EmitNegate_(EmitNegate), OptDescs_(OptDescs)
+  {}
+
+  void operator()(const std::string& OptName, raw_ostream& O) const {
+    const char* Neg = (EmitNegate_ ? "!" : "");
+    if (OptName == "o") {
+      O << Neg << "OutputFilename.empty()";
+    }
+    else if (OptName == "save-temps") {
+      O << Neg << "(SaveTemps == SaveTempsEnum::Unset)";
+    }
+    else {
+      const OptionDescription& OptDesc = OptDescs_.FindListOrParameter(OptName);
+      O << Neg << OptDesc.GenVariableName() << ".empty()";
+    }
+  }
+};
+
+
+/// EmitCaseTest1ArgList - Helper function used by EmitCaseTest1Arg();
+bool EmitCaseTest1ArgList(const std::string& TestName,
+                          const DagInit& d,
+                          const OptionDescriptions& OptDescs,
+                          raw_ostream& O) {
+  const ListInit& L = *static_cast<ListInit*>(d.getArg(0));
+
+  if (TestName == "any_switch_on") {
+    EmitListTest(L, "||", EmitSwitchOn(OptDescs), O);
+    return true;
+  }
+  else if (TestName == "switch_on") {
+    EmitListTest(L, "&&", EmitSwitchOn(OptDescs), O);
+    return true;
+  }
+  else if (TestName == "any_not_empty") {
+    EmitListTest(L, "||", EmitEmptyTest(true, OptDescs), O);
+    return true;
+  }
+  else if (TestName == "any_empty") {
+    EmitListTest(L, "||", EmitEmptyTest(false, OptDescs), O);
+    return true;
+  }
+  else if (TestName == "not_empty") {
+    EmitListTest(L, "&&", EmitEmptyTest(true, OptDescs), O);
+    return true;
+  }
+  else if (TestName == "empty") {
+    EmitListTest(L, "&&", EmitEmptyTest(false, OptDescs), O);
+    return true;
+  }
+
+  return false;
+}
+
+/// EmitCaseTest1ArgStr - Helper function used by EmitCaseTest1Arg();
+bool EmitCaseTest1ArgStr(const std::string& TestName,
+                         const DagInit& d,
+                         const OptionDescriptions& OptDescs,
+                         raw_ostream& O) {
+  const std::string& OptName = InitPtrToString(d.getArg(0));
+
+  if (TestName == "switch_on") {
+    apply(EmitSwitchOn(OptDescs), OptName, O);
+    return true;
+  }
+  else if (TestName == "input_languages_contain") {
+    O << "InLangs.count(\"" << OptName << "\") != 0";
+    return true;
+  }
+  else if (TestName == "in_language") {
+    // This works only for single-argument Tool::GenerateAction. Join
+    // tools can process several files in different languages simultaneously.
+
+    // TODO: make this work with Edge::Weight (if possible).
+    O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
+    return true;
+  }
+  else if (TestName == "not_empty" || TestName == "empty") {
+    bool EmitNegate = (TestName == "not_empty");
+    apply(EmitEmptyTest(EmitNegate, OptDescs), OptName, O);
+    return true;
+  }
+
+  return false;
+}
+
+/// EmitCaseTest1Arg - Helper function used by EmitCaseConstructHandler();
+bool EmitCaseTest1Arg(const std::string& TestName,
+                      const DagInit& d,
+                      const OptionDescriptions& OptDescs,
+                      raw_ostream& O) {
+  checkNumberOfArguments(d, 1);
+  if (typeid(*d.getArg(0)) == typeid(ListInit))
+    return EmitCaseTest1ArgList(TestName, d, OptDescs, O);
+  else
+    return EmitCaseTest1ArgStr(TestName, d, OptDescs, O);
+}
+
+/// 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);
+                       unsigned IndentLevel,
+                       const OptionDescriptions& OptDescs,
+                       raw_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!";
+    const OptionDescription& OptDesc = OptDescs.FindParameter(OptName);
     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 OptionDescription& OptDesc = OptDescs.FindList(OptName);
     const std::string& VarName = OptDesc.GenVariableName();
-    O << "std::find(" << VarName << ".begin(),\n"
-      << IndentLevel << Indent1 << VarName << ".end(), \""
+    O << "std::find(" << VarName << ".begin(),\n";
+    O.indent(IndentLevel + Indent1)
+      << VarName << ".end(), \""
       << OptArg << "\") != " << VarName << ".end()";
     return true;
   }
@@ -665,37 +1332,54 @@ bool EmitCaseTest2Args(const std::string& TestName,
 
 // Forward declaration.
 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
-void EmitCaseTest(const DagInit& d, const char* IndentLevel,
-                  const GlobalOptionDescriptions& OptDescs,
-                  std::ostream& O);
+void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
+                  const OptionDescriptions& OptDescs,
+                  raw_ostream& O);
 
 /// EmitLogicalOperationTest - Helper function used by
 /// EmitCaseConstructHandler.
 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
-                              const char* IndentLevel,
-                              const GlobalOptionDescriptions& OptDescs,
-                              std::ostream& O) {
+                              unsigned IndentLevel,
+                              const OptionDescriptions& OptDescs,
+                              raw_ostream& O) {
   O << '(';
   for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
-    const DagInit& InnerTest = InitPtrToDagInitRef(d.getArg(j));
+    const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
     EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
-    if (j != NumArgs - 1)
-      O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
-    else
+    if (j != NumArgs - 1) {
+      O << ")\n";
+      O.indent(IndentLevel + Indent1) << ' ' << LogicOp << " (";
+    }
+    else {
       O << ')';
+    }
   }
 }
 
+void EmitLogicalNot(const DagInit& d, unsigned IndentLevel,
+                    const OptionDescriptions& OptDescs, raw_ostream& O)
+{
+  checkNumberOfArguments(d, 1);
+  const DagInit& InnerTest = InitPtrToDag(d.getArg(0));
+  O << "! (";
+  EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
+  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();
+void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
+                  const OptionDescriptions& OptDescs,
+                  raw_ostream& O) {
+  const std::string& TestName = GetOperatorName(d);
 
   if (TestName == "and")
     EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
   else if (TestName == "or")
     EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
+  else if (TestName == "not")
+    EmitLogicalNot(d, IndentLevel, OptDescs, O);
+  else if (EmitCaseTest0Args(TestName, O))
+    return;
   else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
     return;
   else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
@@ -704,464 +1388,1063 @@ void EmitCaseTest(const DagInit& d, const char* IndentLevel,
     throw TestName + ": unknown edge property!";
 }
 
-// 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).
+
+/// EmitCaseTestCallback - Callback used by EmitCaseConstructHandler.
+class EmitCaseTestCallback {
+  bool EmitElseIf_;
+  const OptionDescriptions& OptDescs_;
+  raw_ostream& O_;
+public:
+
+  EmitCaseTestCallback(bool EmitElseIf,
+                       const OptionDescriptions& OptDescs, raw_ostream& O)
+    : EmitElseIf_(EmitElseIf), OptDescs_(OptDescs), O_(O)
+  {}
+
+  void operator()(const DagInit& Test, unsigned IndentLevel, bool FirstTest)
+  {
+    if (GetOperatorName(Test) == "default") {
+      O_.indent(IndentLevel) << "else {\n";
+    }
+    else {
+      O_.indent(IndentLevel)
+        << ((!FirstTest && EmitElseIf_) ? "else if (" : "if (");
+      EmitCaseTest(Test, IndentLevel, OptDescs_, O_);
+      O_ << ") {\n";
+    }
+  }
+};
+
+/// EmitCaseStatementCallback - Callback used by EmitCaseConstructHandler.
+template <typename F>
+class EmitCaseStatementCallback {
+  F Callback_;
+  raw_ostream& O_;
+public:
+
+  EmitCaseStatementCallback(F Callback, raw_ostream& O)
+    : Callback_(Callback), O_(O)
+  {}
+
+  void operator() (const Init* Statement, unsigned IndentLevel) {
+
+    // Ignore nested 'case' DAG.
+    if (!(dynamic_cast<const DagInit*>(Statement) &&
+          GetOperatorName(static_cast<const DagInit&>(*Statement)) == "case")) {
+      if (typeid(*Statement) == typeid(ListInit)) {
+        const ListInit& DagList = *static_cast<const ListInit*>(Statement);
+        for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
+             B != E; ++B)
+          Callback_(*B, (IndentLevel + Indent1), O_);
+      }
+      else {
+        Callback_(Statement, (IndentLevel + Indent1), O_);
+      }
+    }
+    O_.indent(IndentLevel) << "}\n";
+  }
+
+};
+
+/// EmitCaseConstructHandler - Emit code that handles the 'case'
+/// construct. Takes a function object that should emit code for every case
+/// clause. Implemented on top of WalkCase.
+/// Callback's type is void F(Init* Statement, unsigned IndentLevel,
+/// raw_ostream& O).
+/// EmitElseIf parameter controls the type of condition that is emitted ('if
+/// (..) {..} else if (..) {} .. else {..}' vs. 'if (..) {..} if(..)  {..}
+/// .. else {..}').
 template <typename F>
-void EmitCaseConstructHandler(const DagInit* d, const char* IndentLevel,
-                              const F& Callback,
-                              const GlobalOptionDescriptions& OptDescs,
-                              std::ostream& O) {
-  assert(d->getOperator()->getAsString() == "case");
-
-  for (unsigned i = 0, numArgs = d->getNumArgs(); i != numArgs; ++i) {
-    const DagInit& Test = InitPtrToDagInitRef(d->getArg(i));
-
-    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";
+void EmitCaseConstructHandler(const Init* Case, unsigned IndentLevel,
+                              F Callback, bool EmitElseIf,
+                              const OptionDescriptions& OptDescs,
+                              raw_ostream& O) {
+  WalkCase(Case, EmitCaseTestCallback(EmitElseIf, OptDescs, O),
+           EmitCaseStatementCallback<F>(Callback, O), IndentLevel);
+}
+
+/// TokenizeCmdLine - converts from
+/// "$CALL(HookName, 'Arg1', 'Arg2')/path -arg1 -arg2" to
+/// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path", "-arg1", "-arg2"].
+void TokenizeCmdLine(const std::string& CmdLine, StrVector& Out) {
+  const char* Delimiters = " \t\n\v\f\r";
+  enum TokenizerState
+  { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
+  cur_st  = Normal;
+
+  if (CmdLine.empty())
+    return;
+  Out.push_back("");
+
+  std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
+    E = CmdLine.size();
+
+  for (; B != E; ++B) {
+    char cur_ch = CmdLine[B];
+
+    switch (cur_st) {
+    case Normal:
+      if (cur_ch == '$') {
+        cur_st = SpecialCommand;
+        break;
+      }
+      if (oneOf(Delimiters, cur_ch)) {
+        // Skip whitespace
+        B = CmdLine.find_first_not_of(Delimiters, B);
+        if (B == std::string::npos) {
+          B = E-1;
+          continue;
+        }
+        --B;
+        Out.push_back("");
+        continue;
+      }
+      break;
+
+
+    case SpecialCommand:
+      if (oneOf(Delimiters, cur_ch)) {
+        cur_st = Normal;
+        Out.push_back("");
+        continue;
+      }
+      if (cur_ch == '(') {
+        Out.push_back("");
+        cur_st = InsideSpecialCommand;
+        continue;
+      }
+      break;
+
+    case InsideSpecialCommand:
+      if (oneOf(Delimiters, cur_ch)) {
+        continue;
+      }
+      if (cur_ch == '\'') {
+        cur_st = InsideQuotationMarks;
+        Out.push_back("");
+        continue;
+      }
+      if (cur_ch == ')') {
+        cur_st = Normal;
+        Out.push_back("");
+      }
+      if (cur_ch == ',') {
+        continue;
+      }
+
+      break;
+
+    case InsideQuotationMarks:
+      if (cur_ch == '\'') {
+        cur_st = InsideSpecialCommand;
+        continue;
+      }
+      break;
+    }
+
+    Out.back().push_back(cur_ch);
+  }
+}
+
+/// SubstituteCall - Given "$CALL(HookName, [Arg1 [, Arg2 [...]]])", output
+/// "hooks::HookName([Arg1 [, Arg2 [, ...]]])". Helper function used by
+/// SubstituteSpecialCommands().
+StrVector::const_iterator
+SubstituteCall (StrVector::const_iterator Pos,
+                StrVector::const_iterator End,
+                bool IsJoin, raw_ostream& O)
+{
+  const char* errorMessage = "Syntax error in $CALL invocation!";
+  checkedIncrement(Pos, End, errorMessage);
+  const std::string& CmdName = *Pos;
+
+  if (CmdName == ")")
+    throw "$CALL invocation: empty argument list!";
+
+  O << "hooks::";
+  O << CmdName << "(";
+
+
+  bool firstIteration = true;
+  while (true) {
+    checkedIncrement(Pos, End, errorMessage);
+    const std::string& Arg = *Pos;
+    assert(Arg.size() != 0);
+
+    if (Arg[0] == ')')
+      break;
+
+    if (firstIteration)
+      firstIteration = false;
+    else
+      O << ", ";
+
+    if (Arg == "$INFILE") {
+      if (IsJoin)
+        throw "$CALL(Hook, $INFILE) can't be used with a Join tool!";
+      else
+        O << "inFile.c_str()";
     }
     else {
-      O << IndentLevel << "if (";
-      EmitCaseTest(Test, IndentLevel, OptDescs, O);
-      O << ") {\n";
+      O << '"' << Arg << '"';
     }
+  }
 
-    ++i;
-    if (i == numArgs)
-      throw "Case construct handler: no corresponding action "
-        "found for the test " + Test.getAsString() + '!';
+  O << ')';
+
+  return Pos;
+}
+
+/// SubstituteEnv - Given '$ENV(VAR_NAME)', output 'getenv("VAR_NAME")'. Helper
+/// function used by SubstituteSpecialCommands().
+StrVector::const_iterator
+SubstituteEnv (StrVector::const_iterator Pos,
+               StrVector::const_iterator End, raw_ostream& O)
+{
+  const char* errorMessage = "Syntax error in $ENV invocation!";
+  checkedIncrement(Pos, End, errorMessage);
+  const std::string& EnvName = *Pos;
+
+  if (EnvName == ")")
+    throw "$ENV invocation: empty argument list!";
 
-    Callback(d->getArg(i), IndentLevel, O);
-    O << IndentLevel << "}\n";
+  O << "checkCString(std::getenv(\"";
+  O << EnvName;
+  O << "\"))";
+
+  checkedIncrement(Pos, End, errorMessage);
+
+  return Pos;
+}
+
+/// SubstituteSpecialCommands - Given an invocation of $CALL or $ENV, output
+/// handler code. Helper function used by EmitCmdLineVecFill().
+StrVector::const_iterator
+SubstituteSpecialCommands (StrVector::const_iterator Pos,
+                           StrVector::const_iterator End,
+                           bool IsJoin, raw_ostream& O)
+{
+
+  const std::string& cmd = *Pos;
+
+  // Perform substitution.
+  if (cmd == "$CALL") {
+    Pos = SubstituteCall(Pos, End, IsJoin, O);
   }
+  else if (cmd == "$ENV") {
+    Pos = SubstituteEnv(Pos, End, O);
+  }
+  else {
+    throw "Unknown special command: " + cmd;
+  }
+
+  // Handle '$CMD(ARG)/additional/text'.
+  const std::string& Leftover = *Pos;
+  assert(Leftover.at(0) == ')');
+  if (Leftover.size() != 1)
+    O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
+
+  return Pos;
 }
 
+/// 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 IsJoin, unsigned IndentLevel,
+                        raw_ostream& O) {
+  StrVector StrVec;
+  TokenizeCmdLine(InitPtrToString(CmdLine), StrVec);
+
+  if (StrVec.empty())
+    throw "Tool '" + ToolName + "' has empty command line!";
+
+  StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
+
+  // If there is a hook invocation on the place of the first command, skip it.
+  assert(!StrVec[0].empty());
+  if (StrVec[0][0] == '$') {
+    while (I != E && (*I)[0] != ')' )
+      ++I;
+
+    // Skip the ')' symbol.
+    ++I;
+  }
+  else {
+    ++I;
+  }
+
+  bool hasINFILE = false;
+
+  for (; I != E; ++I) {
+    const std::string& cmd = *I;
+    assert(!cmd.empty());
+    O.indent(IndentLevel);
+    if (cmd.at(0) == '$') {
+      if (cmd == "$INFILE") {
+        hasINFILE = true;
+        if (IsJoin) {
+          O << "for (PathVector::const_iterator B = inFiles.begin()"
+            << ", E = inFiles.end();\n";
+          O.indent(IndentLevel) << "B != E; ++B)\n";
+          O.indent(IndentLevel + Indent1) << "vec.push_back(B->str());\n";
+        }
+        else {
+          O << "vec.push_back(inFile.str());\n";
+        }
+      }
+      else if (cmd == "$OUTFILE") {
+        O << "vec.push_back(\"\");\n";
+        O.indent(IndentLevel) << "out_file_index = vec.size()-1;\n";
+      }
+      else {
+        O << "vec.push_back(";
+        I = SubstituteSpecialCommands(I, E, IsJoin, O);
+        O << ");\n";
+      }
+    }
+    else {
+      O << "vec.push_back(\"" << cmd << "\");\n";
+    }
+  }
+  if (!hasINFILE)
+    throw "Tool '" + ToolName + "' doesn't take any input!";
+
+  O.indent(IndentLevel) << "cmd = ";
+  if (StrVec[0][0] == '$')
+    SubstituteSpecialCommands(StrVec.begin(), StrVec.end(), IsJoin, O);
+  else
+    O << '"' << StrVec[0] << '"';
+  O << ";\n";
+}
+
+/// EmitCmdLineVecFillCallback - A function object wrapper around
+/// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
+/// argument to EmitCaseConstructHandler().
+class EmitCmdLineVecFillCallback {
+  bool IsJoin;
+  const std::string& ToolName;
+ public:
+  EmitCmdLineVecFillCallback(bool J, const std::string& TN)
+    : IsJoin(J), ToolName(TN) {}
+
+  void operator()(const Init* Statement, unsigned IndentLevel,
+                  raw_ostream& O) const
+  {
+    EmitCmdLineVecFill(Statement, ToolName, IsJoin, IndentLevel, O);
+  }
+};
+
 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
-/// implement EmitOptionPropertyHandlingCode(). Emits code for
-/// handling the (forward) option property.
-void EmitForwardOptionPropertyHandlingCode (const ToolOptionDescription& D,
-                                            std::ostream& O) {
+/// implement EmitActionHandler. Emits code for
+/// handling the (forward) and (forward_as) option properties.
+void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
+                                            unsigned IndentLevel,
+                                            const std::string& NewName,
+                                            raw_ostream& O) {
+  const std::string& Name = NewName.empty()
+    ? ("-" + D.Name)
+    : NewName;
+  unsigned IndentLevel1 = IndentLevel + Indent1;
+
   switch (D.Type) {
   case OptionType::Switch:
-    O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
+    O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
     break;
   case OptionType::Parameter:
-    O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
-    O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
+    O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
+    O.indent(IndentLevel) << "vec.push_back(" << D.GenVariableName() << ");\n";
     break;
   case OptionType::Prefix:
-    O << Indent3 << "vec.push_back(\"-" << D.Name << "\" + "
-      << D.GenVariableName() << ");\n";
+    O.indent(IndentLevel) << "vec.push_back(\"" << 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";
+    O.indent(IndentLevel)
+      << "for (" << D.GenTypeDeclaration()
+      << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
+    O.indent(IndentLevel)
+      << "E = " << D.GenVariableName() << ".end(); B != E;) {\n";
+    O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\" + " << "*B);\n";
+    O.indent(IndentLevel1) << "++B;\n";
+
+    for (int i = 1, j = D.MultiVal; i < j; ++i) {
+      O.indent(IndentLevel1) << "vec.push_back(*B);\n";
+      O.indent(IndentLevel1) << "++B;\n";
+    }
+
+    O.indent(IndentLevel) << "}\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";
+    O.indent(IndentLevel)
+      << "for (" << D.GenTypeDeclaration() << "::iterator B = "
+      << D.GenVariableName() << ".begin(),\n";
+    O.indent(IndentLevel) << "E = " << D.GenVariableName()
+                          << ".end() ; B != E;) {\n";
+    O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\");\n";
+
+    for (int i = 0, j = D.MultiVal; i < j; ++i) {
+      O.indent(IndentLevel1) << "vec.push_back(*B);\n";
+      O.indent(IndentLevel1) << "++B;\n";
+    }
+
+    O.indent(IndentLevel) << "}\n";
     break;
+  case OptionType::Alias:
+  default:
+    throw "Aliases are not allowed in tool option descriptions!";
   }
 }
 
-// A helper function used by EmitOptionPropertyHandlingCode() that
-// tells us whether we should emit any code at all.
-bool ToolOptionHasInterestingProperties(const ToolOptionDescription& D) {
-  if (!D.isForward() && !D.isUnpackValues() && D.Props.empty())
-    return false;
-  return true;
-}
+/// ActionHandlingCallbackBase - Base class of EmitActionHandlersCallback and
+/// EmitPreprocessOptionsCallback.
+struct ActionHandlingCallbackBase
+{
+
+  void onErrorDag(const DagInit& d,
+                  unsigned IndentLevel, raw_ostream& O) const
+  {
+    O.indent(IndentLevel)
+      << "throw std::runtime_error(\"" <<
+      (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0))
+       : "Unknown error!")
+      << "\");\n";
+  }
+
+  void onWarningDag(const DagInit& d,
+                    unsigned IndentLevel, raw_ostream& O) const
+  {
+    checkNumberOfArguments(d, 1);
+    O.indent(IndentLevel) << "llvm::errs() << \""
+                          << InitPtrToString(d.getArg(0)) << "\";\n";
+  }
+
+};
+
+/// EmitActionHandlersCallback - Emit code that handles actions. Used by
+/// EmitGenerateActionMethod() as an argument to EmitCaseConstructHandler().
+
+class EmitActionHandlersCallback;
+
+typedef void (EmitActionHandlersCallback::* EmitActionHandlersCallbackHandler)
+(const DagInit&, unsigned, raw_ostream&) const;
 
-/// EmitOptionPropertyHandlingCode - Helper function used by
-/// EmitGenerateActionMethod(). Emits code that handles option
-/// properties.
-void EmitOptionPropertyHandlingCode (const ToolOptionDescription& D,
-                                     std::ostream& O)
+class EmitActionHandlersCallback :
+  public ActionHandlingCallbackBase,
+  public HandlerTable<EmitActionHandlersCallbackHandler>
 {
-  if (!ToolOptionHasInterestingProperties(D))
-    return;
-  // Start of the if-clause.
-  O << Indent2 << "if (";
-  if (D.Type == OptionType::Switch)
-    O << D.GenVariableName();
-  else
-    O << '!' << D.GenVariableName() << ".empty()";
+  typedef EmitActionHandlersCallbackHandler Handler;
 
-  O <<") {\n";
+  const OptionDescriptions& OptDescs;
 
-  // 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;
+  /// EmitHookInvocation - Common code for hook invocation from actions. Used by
+  /// onAppendCmd and onOutputSuffix.
+  void EmitHookInvocation(const std::string& Str,
+                          const char* BlockOpen, const char* BlockClose,
+                          unsigned IndentLevel, raw_ostream& O) const
+  {
+    StrVector Out;
+    TokenizeCmdLine(Str, Out);
 
-    switch (val.first) {
-      // (append_cmd cmd) property
-    case OptionPropertyType::AppendCmd:
-      O << Indent3 << "vec.push_back(\"" << val.second << "\");\n";
-      break;
-      // Other properties with argument
-    default:
-      break;
+    for (StrVector::const_iterator B = Out.begin(), E = Out.end();
+         B != E; ++B) {
+      const std::string& cmd = *B;
+
+      O.indent(IndentLevel) << BlockOpen;
+
+      if (cmd.at(0) == '$')
+        B = SubstituteSpecialCommands(B, E,  /* IsJoin = */ true, O);
+      else
+        O << '"' << cmd << '"';
+
+      O << BlockClose;
     }
   }
 
-  // Handle flags
+  void onAppendCmd (const DagInit& Dag,
+                    unsigned IndentLevel, raw_ostream& O) const
+  {
+    checkNumberOfArguments(Dag, 1);
+    this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
+                             "vec.push_back(", ");\n", IndentLevel, O);
+  }
 
-  // (forward) property
-  if (D.isForward())
-    EmitForwardOptionPropertyHandlingCode(D, O);
+  void onForward (const DagInit& Dag,
+                  unsigned IndentLevel, raw_ostream& O) const
+  {
+    checkNumberOfArguments(Dag, 1);
+    const std::string& Name = InitPtrToString(Dag.getArg(0));
+    EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
+                                          IndentLevel, "", O);
+  }
 
-  // (unpack_values) property
-  if (D.isUnpackValues()) {
-    if (IsListOptionType(D.Type)) {
-      O << Indent3 << "for (" << D.GenTypeDeclaration()
-        << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
-        << Indent3 << "E = " << D.GenVariableName()
-        << ".end(); B != E; ++B)\n"
-        << Indent4 << "llvm::SplitString(*B, vec, \",\");\n";
-    }
-    else if (D.Type == OptionType::Prefix || D.Type == OptionType::Parameter){
-      O << Indent3 << "llvm::SplitString("
-        << D.GenVariableName() << ", vec, \",\");\n";
+  void onForwardAs (const DagInit& Dag,
+                    unsigned IndentLevel, raw_ostream& O) const
+  {
+    checkNumberOfArguments(Dag, 2);
+    const std::string& Name = InitPtrToString(Dag.getArg(0));
+    const std::string& NewName = InitPtrToString(Dag.getArg(1));
+    EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
+                                          IndentLevel, NewName, O);
+  }
+
+  void onForwardValue (const DagInit& Dag,
+                       unsigned IndentLevel, raw_ostream& O) const
+  {
+    checkNumberOfArguments(Dag, 1);
+    const std::string& Name = InitPtrToString(Dag.getArg(0));
+    const OptionDescription& D = OptDescs.FindListOrParameter(Name);
+
+    if (D.isParameter()) {
+      O.indent(IndentLevel) << "vec.push_back("
+                            << D.GenVariableName() << ");\n";
     }
     else {
-      throw std::string("Switches can't have unpack_values property!");
+      O.indent(IndentLevel) << "std::copy(" << D.GenVariableName()
+                            << ".begin(), " << D.GenVariableName()
+                            << ".end(), std::back_inserter(vec));\n";
     }
   }
 
-  // End of the if-clause.
-  O << Indent2 << "}\n";
+  void onForwardTransformedValue (const DagInit& Dag,
+                                  unsigned IndentLevel, raw_ostream& O) const
+  {
+    checkNumberOfArguments(Dag, 2);
+    const std::string& Name = InitPtrToString(Dag.getArg(0));
+    const std::string& Hook = InitPtrToString(Dag.getArg(1));
+    const OptionDescription& D = OptDescs.FindListOrParameter(Name);
+
+    O.indent(IndentLevel) << "vec.push_back(" << "hooks::"
+                          << Hook << "(" << D.GenVariableName()
+                          << (D.isParameter() ? ".c_str()" : "") << "));\n";
+  }
+
+  void onOutputSuffix (const DagInit& Dag,
+                       unsigned IndentLevel, raw_ostream& O) const
+  {
+    checkNumberOfArguments(Dag, 1);
+    this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
+                             "output_suffix = ", ";\n", IndentLevel, O);
+  }
+
+  void onStopCompilation (const DagInit& Dag,
+                          unsigned IndentLevel, raw_ostream& O) const
+  {
+    O.indent(IndentLevel) << "stop_compilation = true;\n";
+  }
+
+
+  void onUnpackValues (const DagInit& Dag,
+                       unsigned IndentLevel, raw_ostream& O) const
+  {
+    throw "'unpack_values' is deprecated. "
+      "Use 'comma_separated' + 'forward_value' instead!";
+  }
+
+ public:
+
+  explicit EmitActionHandlersCallback(const OptionDescriptions& OD)
+    : OptDescs(OD)
+  {
+    if (!staticMembersInitialized_) {
+      AddHandler("error", &EmitActionHandlersCallback::onErrorDag);
+      AddHandler("warning", &EmitActionHandlersCallback::onWarningDag);
+      AddHandler("append_cmd", &EmitActionHandlersCallback::onAppendCmd);
+      AddHandler("forward", &EmitActionHandlersCallback::onForward);
+      AddHandler("forward_as", &EmitActionHandlersCallback::onForwardAs);
+      AddHandler("forward_value", &EmitActionHandlersCallback::onForwardValue);
+      AddHandler("forward_transformed_value",
+                 &EmitActionHandlersCallback::onForwardTransformedValue);
+      AddHandler("output_suffix", &EmitActionHandlersCallback::onOutputSuffix);
+      AddHandler("stop_compilation",
+                 &EmitActionHandlersCallback::onStopCompilation);
+      AddHandler("unpack_values",
+                 &EmitActionHandlersCallback::onUnpackValues);
+
+      staticMembersInitialized_ = true;
+    }
+  }
+
+  void operator()(const Init* I,
+                  unsigned IndentLevel, raw_ostream& O) const
+  {
+    InvokeDagInitHandler(this, I, IndentLevel, O);
+  }
+};
+
+bool IsOutFileIndexCheckRequiredStr (const Init* CmdLine) {
+  StrVector StrVec;
+  TokenizeCmdLine(InitPtrToString(CmdLine), StrVec);
+
+  for (StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
+       I != E; ++I) {
+    if (*I == "$OUTFILE")
+      return false;
+  }
+
+  return true;
+}
+
+class IsOutFileIndexCheckRequiredStrCallback {
+  bool* ret_;
+
+public:
+  IsOutFileIndexCheckRequiredStrCallback(bool* ret) : ret_(ret)
+  {}
+
+  void operator()(const Init* CmdLine) {
+    // Ignore nested 'case' DAG.
+    if (typeid(*CmdLine) == typeid(DagInit))
+      return;
+
+    if (IsOutFileIndexCheckRequiredStr(CmdLine))
+      *ret_ = true;
+  }
+
+  void operator()(const DagInit* Test, unsigned, bool) {
+    this->operator()(Test);
+  }
+  void operator()(const Init* Statement, unsigned) {
+    this->operator()(Statement);
+  }
+};
+
+bool IsOutFileIndexCheckRequiredCase (Init* CmdLine) {
+  bool ret = false;
+  WalkCase(CmdLine, Id(), IsOutFileIndexCheckRequiredStrCallback(&ret));
+  return ret;
 }
 
-void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
-                        bool Version, const char* IndentLevel,
-                        std::ostream& O) {
-  StrVector StrVec;
-  SplitString(InitPtrToString(CmdLine), StrVec);
-  if (InitPtrToString(CmdLine).empty())
-    throw "Tool " + ToolName + " has empty command line!";
+/// IsOutFileIndexCheckRequired - Should we emit an "out_file_index != -1" check
+/// in EmitGenerateActionMethod() ?
+bool IsOutFileIndexCheckRequired (Init* CmdLine) {
+  if (typeid(*CmdLine) == typeid(StringInit))
+    return IsOutFileIndexCheckRequiredStr(CmdLine);
+  else
+    return IsOutFileIndexCheckRequiredCase(CmdLine);
+}
 
-  StrVector::const_iterator I = StrVec.begin();
-  ++I;
-  for (StrVector::const_iterator E = StrVec.end(); I != E; ++I) {
-    const std::string& cmd = *I;
-    O << IndentLevel;
-    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(\"" << cmd << "\");\n";
-    }
-  }
-  O << IndentLevel << "ret = Action(\"" << StrVec.at(0) << "\", vec);\n";
+void EmitGenerateActionMethodHeader(const ToolDescription& D,
+                                    bool IsJoin, raw_ostream& O)
+{
+  if (IsJoin)
+    O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
+  else
+    O.indent(Indent1) << "Action GenerateAction(const sys::Path& inFile,\n";
+
+  O.indent(Indent2) << "bool HasChildren,\n";
+  O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
+  O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
+  O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
+  O.indent(Indent1) << "{\n";
+  O.indent(Indent2) << "std::string cmd;\n";
+  O.indent(Indent2) << "std::vector<std::string> vec;\n";
+  O.indent(Indent2) << "bool stop_compilation = !HasChildren;\n";
+  O.indent(Indent2) << "const char* output_suffix = \""
+                    << D.OutputSuffix << "\";\n";
 }
 
-class EmitCmdLineVecFillCallback {
-  bool Version;
-  const std::string& ToolName;
- public:
-  EmitCmdLineVecFillCallback(bool Ver, const std::string& TN)
-    : Version(Ver), ToolName(TN) {}
+// EmitGenerateActionMethod - Emit either a normal or a "join" version of the
+// Tool::GenerateAction() method.
+void EmitGenerateActionMethod (const ToolDescription& D,
+                               const OptionDescriptions& OptDescs,
+                               bool IsJoin, raw_ostream& O) {
 
-  void operator()(const Init* Statement, const char* IndentLevel,
-                  std::ostream& O) const
-  {
-    EmitCmdLineVecFill(Statement, ToolName, Version,
-                       (std::string(IndentLevel) + Indent1).c_str(), O);
-  }
-};
+  EmitGenerateActionMethodHeader(D, IsJoin, 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";
+  if (!D.CmdLine)
+    throw "Tool " + D.Name + " has no cmd_line property!";
 
-  O << Indent2 << "const sys::Path& outFile,\n"
-    << Indent2 << "const InputLanguagesSet& InLangs) const\n"
-    << Indent1 << "{\n"
-    << Indent2 << "Action ret;\n"
-    << Indent2 << "std::vector<std::string> vec;\n";
+  bool IndexCheckRequired = IsOutFileIndexCheckRequired(D.CmdLine);
+  O.indent(Indent2) << "int out_file_index"
+                    << (IndexCheckRequired ? " = -1" : "")
+                    << ";\n\n";
 
-  // cmd_line is either a string or a 'case' construct.
-  if (typeid(*P.CmdLine) == typeid(StringInit))
-    EmitCmdLineVecFill(P.CmdLine, P.Name, Version, Indent2, O);
+  // Process the cmd_line property.
+  if (typeid(*D.CmdLine) == typeid(StringInit))
+    EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
   else
-    EmitCaseConstructHandler(&InitPtrToDagInitRef(P.CmdLine), Indent2,
-                             EmitCmdLineVecFillCallback(Version, P.Name),
-                             OptDescs, O);
+    EmitCaseConstructHandler(D.CmdLine, Indent2,
+                             EmitCmdLineVecFillCallback(IsJoin, D.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(val, O);
-  }
+  if (D.Actions)
+    EmitCaseConstructHandler(D.Actions, Indent2,
+                             EmitActionHandlersCallback(OptDescs),
+                             false, OptDescs, O);
+
+  O << '\n';
+  O.indent(Indent2)
+    << "std::string out_file = OutFilename("
+    << (IsJoin ? "sys::Path(),\n" : "inFile,\n");
+  O.indent(Indent3) << "TempDir, stop_compilation, output_suffix).str();\n\n";
+
+  if (IndexCheckRequired)
+    O.indent(Indent2) << "if (out_file_index != -1)\n";
+  O.indent(IndexCheckRequired ? Indent3 : Indent2)
+    << "vec[out_file_index] = out_file;\n";
 
   // Handle the Sink property.
-  if (P.isSink()) {
-    O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
-      << Indent3 << "vec.insert(vec.end(), "
-      << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
-      << Indent2 << "}\n";
+  if (D.isSink()) {
+    O.indent(Indent2) << "if (!" << SinkOptionName << ".empty()) {\n";
+    O.indent(Indent3) << "vec.insert(vec.end(), "
+                      << SinkOptionName << ".begin(), " << SinkOptionName
+                      << ".end());\n";
+    O.indent(Indent2) << "}\n";
   }
 
-  O << Indent2 << "return ret;\n"
-    << Indent1 << "}\n\n";
+  O.indent(Indent2) << "return Action(cmd, vec, stop_compilation, out_file);\n";
+  O.indent(Indent1) << "}\n\n";
 }
 
 /// 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,\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, OptDescs, true, O);
-
-  EmitGenerateActionMethod(P, OptDescs, false, O);
-}
-
-/// 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";
-
-  for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
-        E = P.OptDescs.end(); B != E; ++B) {
-    const ToolOptionDescription& val = B->second;
-
-    if (val.isStopCompilation())
-      O << Indent2
-        << "if (" << val.GenVariableName()
-        << ")\n" << Indent3 << "last = true;\n";
+void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
+                                const OptionDescriptions& OptDescs,
+                                raw_ostream& O) {
+  if (!ToolDesc.isJoin()) {
+    O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
+    O.indent(Indent2) << "bool HasChildren,\n";
+    O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
+    O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
+    O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
+    O.indent(Indent1) << "{\n";
+    O.indent(Indent2) << "throw std::runtime_error(\"" << ToolDesc.Name
+                      << " is not a Join tool!\");\n";
+    O.indent(Indent1) << "}\n\n";
+  }
+  else {
+    EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
   }
 
-  O << Indent2 << "return last;\n"
-    << Indent1 <<  "}\n\n";
+  EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
 }
 
 /// 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"
-    << Indent1 << "}\n\n";
+void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
+  O.indent(Indent1) << "const char** InputLanguages() const {\n";
+  O.indent(Indent2) << "return InputLanguages_;\n";
+  O.indent(Indent1) << "}\n\n";
 
-  O << Indent1 << "const char* OutputLanguage() const {\n"
-    << Indent2 << "return \"" << P.OutLanguage << "\";\n"
-    << Indent1 << "}\n\n";
-}
+  if (D.OutLanguage.empty())
+    throw "Tool " + D.Name + " has no 'out_language' property!";
 
-/// 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"
-    << Indent1 << "}\n\n";
+  O.indent(Indent1) << "const char* OutputLanguage() const {\n";
+  O.indent(Indent2) << "return \"" << D.OutLanguage << "\";\n";
+  O.indent(Indent1) << "}\n\n";
 }
 
 /// 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";
+void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
+  O.indent(Indent1) << "const char* Name() const {\n";
+  O.indent(Indent2) << "return \"" << D.Name << "\";\n";
+  O.indent(Indent1) << "}\n\n";
 }
 
 /// 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 << Indent2 << "return true;\n";
+void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
+  O.indent(Indent1) << "bool IsJoin() const {\n";
+  if (D.isJoin())
+    O.indent(Indent2) << "return true;\n";
   else
-    O << Indent2 << "return false;\n";
-  O << Indent1 << "}\n\n";
+    O.indent(Indent2) << "return false;\n";
+  O.indent(Indent1) << "}\n\n";
+}
+
+/// EmitStaticMemberDefinitions - Emit static member definitions for a
+/// given Tool class.
+void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
+  if (D.InLanguage.empty())
+    throw "Tool " + D.Name + " has no 'in_language' property!";
+
+  O << "const char* " << D.Name << "::InputLanguages_[] = {";
+  for (StrVector::const_iterator B = D.InLanguage.begin(),
+         E = D.InLanguage.end(); B != E; ++B)
+    O << '\"' << *B << "\", ";
+  O << "0};\n\n";
 }
 
 /// EmitToolClassDefinition - Emit a Tool class definition.
-void EmitToolClassDefinition (const ToolProperties& P,
-                              const GlobalOptionDescriptions& OptDescs,
-                              std::ostream& O) {
-  if (P.Name == "root")
+void EmitToolClassDefinition (const ToolDescription& D,
+                              const OptionDescriptions& OptDescs,
+                              raw_ostream& O) {
+  if (D.Name == "root")
     return;
 
   // Header
-  O << "class " << P.Name << " : public ";
-  if (P.isJoin())
+  O << "class " << D.Name << " : public ";
+  if (D.isJoin())
     O << "JoinTool";
   else
     O << "Tool";
-  O << " {\npublic:\n";
 
-  EmitNameMethod(P, O);
-  EmitInOutLanguageMethods(P, O);
-  EmitOutputSuffixMethod(P, O);
-  EmitIsJoinMethod(P, O);
-  EmitGenerateActionMethods(P, OptDescs, O);
-  EmitIsLastMethod(P, O);
+  O << " {\nprivate:\n";
+  O.indent(Indent1) << "static const char* InputLanguages_[];\n\n";
+
+  O << "public:\n";
+  EmitNameMethod(D, O);
+  EmitInOutLanguageMethods(D, O);
+  EmitIsJoinMethod(D, O);
+  EmitGenerateActionMethods(D, OptDescs, O);
 
   // Close class definition
-  O << "};\n\n";
+  O << "};\n";
+
+  EmitStaticMemberDefinitions(D, O);
+
 }
 
-/// EmitOptionDescriptions - Iterate over a list of option
-/// descriptions and emit registration code.
-void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
-                             std::ostream& O)
+/// EmitOptionDefinitions - Iterate over a list of option descriptions
+/// and emit registration code.
+void EmitOptionDefinitions (const OptionDescriptions& descs,
+                            bool HasSink, bool HasExterns,
+                            raw_ostream& O)
 {
-  // Emit static cl::Option variables
-  for (GlobalOptionDescriptions::const_iterator B = descs.begin(),
+  std::vector<OptionDescription> Aliases;
+
+  // Emit static cl::Option variables.
+  for (OptionDescriptions::const_iterator B = descs.begin(),
          E = descs.end(); B!=E; ++B) {
-    const GlobalOptionDescription& val = B->second;
+    const OptionDescription& val = B->second;
+
+    if (val.Type == OptionType::Alias) {
+      Aliases.push_back(val);
+      continue;
+    }
+
+    if (val.isExtern())
+      O << "extern ";
 
     O << val.GenTypeDeclaration() << ' '
-      << val.GenVariableName()
-      << "(\"" << val.Name << '\"';
+      << val.GenVariableName();
+
+    if (val.isExtern()) {
+      O << ";\n";
+      continue;
+    }
+
+    O << "(\"" << val.Name << "\"\n";
 
     if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
       O << ", cl::Prefix";
 
     if (val.isRequired()) {
-      switch (val.Type) {
-      case OptionType::PrefixList:
-      case OptionType::ParameterList:
+      if (val.isList() && !val.isMultiVal())
         O << ", cl::OneOrMore";
-        break;
-      default:
+      else
         O << ", cl::Required";
-      }
     }
+    else if (val.isOneOrMore() && val.isList()) {
+        O << ", cl::OneOrMore";
+    }
+    else if (val.isOptional() && val.isList()) {
+        O << ", cl::Optional";
+    }
+
+    if (val.isReallyHidden())
+      O << ", cl::ReallyHidden";
+    else if (val.isHidden())
+      O << ", cl::Hidden";
+
+    if (val.isCommaSeparated())
+      O << ", cl::CommaSeparated";
+
+    if (val.MultiVal > 1)
+      O << ", cl::multi_val(" << val.MultiVal << ')';
+
+    if (val.InitVal) {
+      const std::string& str = val.InitVal->getAsString();
+      O << ", cl::init(" << str << ')';
+    }
+
+    if (!val.Help.empty())
+      O << ", cl::desc(\"" << val.Help << "\")";
+
+    O << ");\n\n";
+  }
+
+  // Emit the aliases (they should go after all the 'proper' options).
+  for (std::vector<OptionDescription>::const_iterator
+         B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
+    const OptionDescription& val = *B;
+
+    O << val.GenTypeDeclaration() << ' '
+      << val.GenVariableName()
+      << "(\"" << val.Name << '\"';
 
-    O << ", cl::desc(\"" << val.Help << "\"));\n";
+    const OptionDescription& D = descs.FindOption(val.Help);
+    O << ", cl::aliasopt(" << D.GenVariableName() << ")";
+
+    O << ", cl::desc(\"" << "An alias for -" + val.Help  << "\"));\n";
   }
 
-  if (descs.HasSink)
-    O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
+  // Emit the sink option.
+  if (HasSink)
+    O << (HasExterns ? "extern cl" : "cl")
+      << "::list<std::string> " << SinkOptionName
+      << (HasExterns ? ";\n" : "(cl::Sink);\n");
 
   O << '\n';
 }
 
-/// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
-void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
+/// EmitPreprocessOptionsCallback - Helper function passed to
+/// EmitCaseConstructHandler() by EmitPreprocessOptions().
+
+class EmitPreprocessOptionsCallback;
+
+typedef void
+(EmitPreprocessOptionsCallback::* EmitPreprocessOptionsCallbackHandler)
+(const DagInit&, unsigned, raw_ostream&) const;
+
+class EmitPreprocessOptionsCallback :
+  public ActionHandlingCallbackBase,
+  public HandlerTable<EmitPreprocessOptionsCallbackHandler>
 {
-  // Get the relevant field out of RecordKeeper
-  Record* LangMapRecord = Records.getDef("LanguageMap");
-  if (!LangMapRecord)
-    throw std::string("Language map definition not found!");
+  typedef EmitPreprocessOptionsCallbackHandler Handler;
+
+  const OptionDescriptions& OptDescs_;
+
+  void onUnsetOptionStr(const Init* I,
+                        unsigned IndentLevel, raw_ostream& O) const
+  {
+    const std::string& OptName = InitPtrToString(I);
+    const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
+
+    if (OptDesc.isSwitch()) {
+      O.indent(IndentLevel) << OptDesc.GenVariableName() << " = false;\n";
+    }
+    else if (OptDesc.isParameter()) {
+      O.indent(IndentLevel) << OptDesc.GenVariableName() << " = \"\";\n";
+    }
+    else if (OptDesc.isList()) {
+      O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
+    }
+    else {
+      throw "Can't apply 'unset_option' to alias option '" + OptName + "'!";
+    }
+  }
+
+  void onUnsetOptionList(const ListInit& L,
+                         unsigned IndentLevel, raw_ostream& O) const
+  {
+    for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B)
+      this->onUnsetOptionStr(*B, IndentLevel, O);
+  }
+
+  void onUnsetOption(const DagInit& d,
+                     unsigned IndentLevel, raw_ostream& O) const
+  {
+    checkNumberOfArguments(d, 1);
+    Init* I = d.getArg(0);
+
+    if (typeid(*I) == typeid(ListInit)) {
+      const ListInit& L = *static_cast<const ListInit*>(I);
+      this->onUnsetOptionList(L, IndentLevel, O);
+    }
+    else {
+      this->onUnsetOptionStr(I, IndentLevel, O);
+    }
+  }
+
+public:
+
+  EmitPreprocessOptionsCallback(const OptionDescriptions& OptDescs)
+  : OptDescs_(OptDescs)
+  {
+    if (!staticMembersInitialized_) {
+      AddHandler("error", &EmitPreprocessOptionsCallback::onErrorDag);
+      AddHandler("warning", &EmitPreprocessOptionsCallback::onWarningDag);
+      AddHandler("unset_option", &EmitPreprocessOptionsCallback::onUnsetOption);
+
+      staticMembersInitialized_ = true;
+    }
+  }
 
-  ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
-  if (!LangsToSuffixesList)
-    throw std::string("Error in the language map definition!");
+  void operator()(const Init* I,
+                  unsigned IndentLevel, raw_ostream& O) const
+  {
+    InvokeDagInitHandler(this, I, IndentLevel, O);
+  }
 
-  // Generate code
-  O << "void llvmc::PopulateLanguageMap(LanguageMap& language_map) {\n";
+};
 
-  for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
-    Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
+/// EmitPreprocessOptions - Emit the PreprocessOptionsLocal() function.
+void EmitPreprocessOptions (const RecordKeeper& Records,
+                            const OptionDescriptions& OptDecs, raw_ostream& O)
+{
+  O << "void PreprocessOptionsLocal() {\n";
 
-    const std::string& Lang = LangToSuffixes->getValueAsString("lang");
-    const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
+  const RecordVector& OptionPreprocessors =
+    Records.getAllDerivedDefinitions("OptionPreprocessor");
 
-    for (unsigned i = 0; i < Suffixes->size(); ++i)
-      O << Indent1 << "language_map[\""
-        << InitPtrToString(Suffixes->getElement(i))
-        << "\"] = \"" << Lang << "\";\n";
+  for (RecordVector::const_iterator B = OptionPreprocessors.begin(),
+         E = OptionPreprocessors.end(); B!=E; ++B) {
+    DagInit* Case = (*B)->getValueAsDag("preprocessor");
+    EmitCaseConstructHandler(Case, Indent1,
+                             EmitPreprocessOptionsCallback(OptDecs),
+                             false, OptDecs, O);
   }
 
   O << "}\n\n";
 }
 
-/// 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<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;
-    ToolToOutLang[P.Name] = P.OutLanguage;
+/// EmitPopulateLanguageMap - Emit the PopulateLanguageMapLocal() function.
+void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
+{
+  O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
+
+  // Get the relevant field out of RecordKeeper
+  const Record* LangMapRecord = Records.getDef("LanguageMap");
+
+  // It is allowed for a plugin to have no language map.
+  if (LangMapRecord) {
+
+    ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
+    if (!LangsToSuffixesList)
+      throw "Error in the language map definition!";
+
+    for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
+      const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
+
+      const std::string& Lang = LangToSuffixes->getValueAsString("lang");
+      const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
+
+      for (unsigned i = 0; i < Suffixes->size(); ++i)
+        O.indent(Indent1) << "langMap[\""
+                          << InitPtrToString(Suffixes->getElement(i))
+                          << "\"] = \"" << Lang << "\";\n";
+    }
   }
+
+  O << "}\n\n";
 }
 
-/// TypecheckGraph - Check that names for output and input languages
-/// on all edges do match.
-// TOFIX: check for cycles.
-// TOFIX: check for multiple default edges.
-void TypecheckGraph (Record* CompilationGraph,
-                     const ToolPropertiesList& TPList) {
-  StringMap<std::string> ToolToInLang;
-  StringMap<std::string> ToolToOutLang;
+/// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
+/// by EmitEdgeClass().
+void IncDecWeight (const Init* i, unsigned IndentLevel,
+                   raw_ostream& O) {
+  const DagInit& d = InitPtrToDag(i);
+  const std::string& OpName = GetOperatorName(d);
 
-  FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
-  ListInit* edges = CompilationGraph->getValueAsListInit("edges");
-  StringMap<std::string>::iterator IAE = ToolToInLang.end();
-  StringMap<std::string>::iterator IBE = ToolToOutLang.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)
-      throw A->getName() + ": no such tool!";
-    if (IB == IBE)
-      throw B->getName() + ": no such tool!";
-    if (A->getName() != "root" && IA->second != IB->second)
-      throw "Edge " + A->getName() + "->" + B->getName()
-        + ": output->input language mismatch";
-    if (B->getName() == "root")
-      throw std::string("Edges back to the root are not allowed!");
-  }
-}
-
-// Helper function passed to EmitCaseConstructHandler by EmitEdgeClass.
-void IncDecWeight (const Init* i, const char* IndentLevel,
-                   std::ostream& O) {
-  const DagInit& d = InitPtrToDagInitRef(i);
-  const std::string& OpName = d.getOperator()->getAsString();
-
-  if (OpName == "inc_weight")
-    O << IndentLevel << Indent1 << "ret += ";
-  else if (OpName == "dec_weight")
-    O << IndentLevel << Indent1 << "ret -= ";
-  else
-    throw "Unknown operator in edge properties list: " + OpName + '!';
+  if (OpName == "inc_weight") {
+    O.indent(IndentLevel) << "ret += ";
+  }
+  else if (OpName == "dec_weight") {
+    O.indent(IndentLevel) << "ret -= ";
+  }
+  else if (OpName == "error") {
+    checkNumberOfArguments(d, 1);
+    O.indent(IndentLevel) << "throw std::runtime_error(\""
+                          << InitPtrToString(d.getArg(0))
+                          << "\");\n";
+    return;
+  }
+  else {
+    throw "Unknown operator in edge properties list: '" + OpName + "'!"
+      "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
+  }
 
   if (d.getNumArgs() > 0)
     O << InitPtrToInt(d.getArg(0)) << ";\n";
@@ -1172,134 +2455,430 @@ void IncDecWeight (const Init* i, const char* IndentLevel,
 
 /// EmitEdgeClass - Emit a single Edge# class.
 void EmitEdgeClass (unsigned N, const std::string& Target,
-                    DagInit* Case, const GlobalOptionDescriptions& OptDescs,
-                    std::ostream& O) {
+                    DagInit* Case, const OptionDescriptions& OptDescs,
+                    raw_ostream& O) {
 
   // Class constructor.
   O << "class Edge" << N << ": public Edge {\n"
-    << "public:\n"
-    << Indent1 << "Edge" << N << "() : Edge(\"" << Target
-    << "\") {}\n\n"
+    << "public:\n";
+  O.indent(Indent1) << "Edge" << N << "() : Edge(\"" << Target
+                    << "\") {}\n\n";
 
   // Function Weight().
-    << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
-    << Indent2 << "unsigned ret = 0;\n";
+  O.indent(Indent1)
+    << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n";
+  O.indent(Indent2) << "unsigned ret = 0;\n";
 
   // Handle the 'case' construct.
-  EmitCaseConstructHandler(Case, Indent2, IncDecWeight, OptDescs, O);
+  EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
 
-  O << Indent2 << "return ret;\n"
-    << Indent1 << "};\n\n};\n\n";
+  O.indent(Indent2) << "return ret;\n";
+  O.indent(Indent1) << "};\n\n};\n\n";
 }
 
-// Emit Edge* classes that represent graph edges.
-void EmitEdgeClasses (Record* CompilationGraph,
-                      const GlobalOptionDescriptions& OptDescs,
-                      std::ostream& O) {
-  ListInit* edges = CompilationGraph->getValueAsListInit("edges");
+/// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
+void EmitEdgeClasses (const RecordVector& EdgeVector,
+                      const OptionDescriptions& OptDescs,
+                      raw_ostream& O) {
+  int i = 0;
+  for (RecordVector::const_iterator B = EdgeVector.begin(),
+         E = EdgeVector.end(); B != E; ++B) {
+    const Record* Edge = *B;
+    const std::string& NodeB = Edge->getValueAsString("b");
+    DagInit& Weight = *Edge->getValueAsDag("weight");
+
+    if (!isDagEmpty(Weight))
+      EmitEdgeClass(i, NodeB, &Weight, OptDescs, O);
+    ++i;
+  }
+}
+
+/// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraphLocal()
+/// function.
+void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
+                                   const ToolDescriptions& ToolDescs,
+                                   raw_ostream& O)
+{
+  O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
+
+  for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
+         E = ToolDescs.end(); B != E; ++B)
+    O.indent(Indent1) << "G.insertNode(new " << (*B)->Name << "());\n";
+
+  O << '\n';
+
+  // Insert edges.
 
-  for (unsigned i = 0; i < edges->size(); ++i) {
-    Record* Edge = edges->getElementAsRecord(i);
-    Record* B = Edge->getValueAsDef("b");
-    DagInit* Weight = Edge->getValueAsDag("weight");
+  int i = 0;
+  for (RecordVector::const_iterator B = EdgeVector.begin(),
+         E = EdgeVector.end(); B != E; ++B) {
+    const Record* Edge = *B;
+    const std::string& NodeA = Edge->getValueAsString("a");
+    const std::string& NodeB = Edge->getValueAsString("b");
+    DagInit& Weight = *Edge->getValueAsDag("weight");
+
+    O.indent(Indent1) << "G.insertEdge(\"" << NodeA << "\", ";
 
     if (isDagEmpty(Weight))
-      continue;
+      O << "new SimpleEdge(\"" << NodeB << "\")";
+    else
+      O << "new Edge" << i << "()";
 
-    EmitEdgeClass(i, B->getName(), Weight, OptDescs, O);
+    O << ");\n";
+    ++i;
   }
+
+  O << "}\n\n";
 }
 
-/// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
-/// function.
-void EmitPopulateCompilationGraph (Record* CompilationGraph,
-                                   std::ostream& O)
-{
-  ListInit* edges = CompilationGraph->getValueAsListInit("edges");
+/// HookInfo - Information about the hook type and number of arguments.
+struct HookInfo {
+
+  // A hook can either have a single parameter of type std::vector<std::string>,
+  // or NumArgs parameters of type const char*.
+  enum HookType { ListHook, ArgHook };
+
+  HookType Type;
+  unsigned NumArgs;
+
+  HookInfo() : Type(ArgHook), NumArgs(1)
+  {}
 
-  // Generate code
-  O << "void llvmc::PopulateCompilationGraph(CompilationGraph& G) {\n"
-    << Indent1 << "PopulateLanguageMap(G.ExtsToLangs);\n\n";
+  HookInfo(HookType T) : Type(T), NumArgs(1)
+  {}
+
+  HookInfo(unsigned N) : Type(ArgHook), NumArgs(N)
+  {}
+};
+
+typedef llvm::StringMap<HookInfo> HookInfoMap;
+
+/// ExtractHookNames - Extract the hook names from all instances of
+/// $CALL(HookName) in the provided command line string/action. Helper
+/// function used by FillInHookNames().
+class ExtractHookNames {
+  HookInfoMap& HookNames_;
+  const OptionDescriptions& OptDescs_;
+public:
+  ExtractHookNames(HookInfoMap& HookNames, const OptionDescriptions& OptDescs)
+    : HookNames_(HookNames), OptDescs_(OptDescs)
+  {}
 
-  // Insert vertices
+  void onAction (const DagInit& Dag) {
+    const std::string& Name = GetOperatorName(Dag);
 
-  RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
-  if (Tools.empty())
-    throw std::string("No tool definitions found!");
+    if (Name == "forward_transformed_value") {
+      checkNumberOfArguments(Dag, 2);
+      const std::string& OptName = InitPtrToString(Dag.getArg(0));
+      const std::string& HookName = InitPtrToString(Dag.getArg(1));
+      const OptionDescription& D = OptDescs_.FindOption(OptName);
 
-  for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
-    const std::string& Name = (*B)->getName();
-    if (Name != "root")
-      O << Indent1 << "G.insertNode(new "
-        << Name << "());\n";
+      HookNames_[HookName] = HookInfo(D.isList() ? HookInfo::ListHook
+                                      : HookInfo::ArgHook);
+    }
+    else if (Name == "append_cmd" || Name == "output_suffix") {
+      checkNumberOfArguments(Dag, 1);
+      this->onCmdLine(InitPtrToString(Dag.getArg(0)));
+    }
   }
 
-  O << '\n';
+  void onCmdLine(const std::string& Cmd) {
+    StrVector cmds;
+    TokenizeCmdLine(Cmd, cmds);
 
-  // Insert edges
-  for (unsigned i = 0; i < edges->size(); ++i) {
-    Record* Edge = edges->getElementAsRecord(i);
-    Record* A = Edge->getValueAsDef("a");
-    Record* B = Edge->getValueAsDef("b");
-    DagInit* Weight = Edge->getValueAsDag("weight");
+    for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
+         B != E; ++B) {
+      const std::string& cmd = *B;
 
-    O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
+      if (cmd == "$CALL") {
+        unsigned NumArgs = 0;
+        checkedIncrement(B, E, "Syntax error in $CALL invocation!");
+        const std::string& HookName = *B;
 
-    if (isDagEmpty(Weight))
-      O << "new SimpleEdge(\"" << B->getName() << "\")";
-    else
-      O << "new Edge" << i << "()";
+        if (HookName.at(0) == ')')
+          throw "$CALL invoked with no arguments!";
 
-    O << ");\n";
+        while (++B != E && B->at(0) != ')') {
+          ++NumArgs;
+        }
+
+        HookInfoMap::const_iterator H = HookNames_.find(HookName);
+
+        if (H != HookNames_.end() && H->second.NumArgs != NumArgs &&
+            H->second.Type != HookInfo::ArgHook)
+          throw "Overloading of hooks is not allowed. Overloaded hook: "
+            + HookName;
+        else
+          HookNames_[HookName] = HookInfo(NumArgs);
+      }
+    }
+  }
+
+  void operator()(const Init* Arg) {
+
+    // We're invoked on an action (either a dag or a dag list).
+    if (typeid(*Arg) == typeid(DagInit)) {
+      const DagInit& Dag = InitPtrToDag(Arg);
+      this->onAction(Dag);
+      return;
+    }
+    else if (typeid(*Arg) == typeid(ListInit)) {
+      const ListInit& List = InitPtrToList(Arg);
+      for (ListInit::const_iterator B = List.begin(), E = List.end(); B != E;
+           ++B) {
+        const DagInit& Dag = InitPtrToDag(*B);
+        this->onAction(Dag);
+      }
+      return;
+    }
+
+    // We're invoked on a command line.
+    this->onCmdLine(InitPtrToString(Arg));
+  }
+
+  void operator()(const DagInit* Test, unsigned, bool) {
+    this->operator()(Test);
+  }
+  void operator()(const Init* Statement, unsigned) {
+    this->operator()(Statement);
+  }
+};
+
+/// FillInHookNames - Actually extract the hook names from all command
+/// line strings. Helper function used by EmitHookDeclarations().
+void FillInHookNames(const ToolDescriptions& ToolDescs,
+                     const OptionDescriptions& OptDescs,
+                     HookInfoMap& HookNames)
+{
+  // For all tool descriptions:
+  for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
+         E = ToolDescs.end(); B != E; ++B) {
+    const ToolDescription& D = *(*B);
+
+    // Look for 'forward_transformed_value' in 'actions'.
+    if (D.Actions)
+      WalkCase(D.Actions, Id(), ExtractHookNames(HookNames, OptDescs));
+
+    // Look for hook invocations in 'cmd_line'.
+    if (!D.CmdLine)
+      continue;
+    if (dynamic_cast<StringInit*>(D.CmdLine))
+      // This is a string.
+      ExtractHookNames(HookNames, OptDescs).operator()(D.CmdLine);
+    else
+      // This is a 'case' construct.
+      WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames, OptDescs));
   }
+}
+
+/// EmitHookDeclarations - Parse CmdLine fields of all the tool
+/// property records and emit hook function declaration for each
+/// instance of $CALL(HookName).
+void EmitHookDeclarations(const ToolDescriptions& ToolDescs,
+                          const OptionDescriptions& OptDescs, raw_ostream& O) {
+  HookInfoMap HookNames;
+
+  FillInHookNames(ToolDescs, OptDescs, HookNames);
+  if (HookNames.empty())
+    return;
+
+  O << "namespace hooks {\n";
+  for (HookInfoMap::const_iterator B = HookNames.begin(),
+         E = HookNames.end(); B != E; ++B) {
+    const char* HookName = B->first();
+    const HookInfo& Info = B->second;
+
+    O.indent(Indent1) << "std::string " << HookName << "(";
+
+    if (Info.Type == HookInfo::ArgHook) {
+      for (unsigned i = 0, j = Info.NumArgs; i < j; ++i) {
+        O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
+      }
+    }
+    else {
+      O << "const std::vector<std::string>& Arg";
+    }
 
+    O <<");\n";
+  }
   O << "}\n\n";
 }
 
+/// EmitRegisterPlugin - Emit code to register this plugin.
+void EmitRegisterPlugin(int Priority, raw_ostream& O) {
+  O << "struct Plugin : public llvmc::BasePlugin {\n\n";
+  O.indent(Indent1) << "int Priority() const { return "
+                    << Priority << "; }\n\n";
+  O.indent(Indent1) << "void PreprocessOptions() const\n";
+  O.indent(Indent1) << "{ PreprocessOptionsLocal(); }\n\n";
+  O.indent(Indent1) << "void PopulateLanguageMap(LanguageMap& langMap) const\n";
+  O.indent(Indent1) << "{ PopulateLanguageMapLocal(langMap); }\n\n";
+  O.indent(Indent1)
+    << "void PopulateCompilationGraph(CompilationGraph& graph) const\n";
+  O.indent(Indent1) << "{ PopulateCompilationGraphLocal(graph); }\n"
+                    << "};\n\n"
+                    << "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
+}
+
+/// EmitIncludes - Emit necessary #include directives and some
+/// additional declarations.
+void EmitIncludes(raw_ostream& O) {
+  O << "#include \"llvm/CompilerDriver/BuiltinOptions.h\"\n"
+    << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
+    << "#include \"llvm/CompilerDriver/ForceLinkageMacros.h\"\n"
+    << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
+    << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
 
-// End of anonymous namespace
+    << "#include \"llvm/Support/CommandLine.h\"\n"
+    << "#include \"llvm/Support/raw_ostream.h\"\n\n"
+
+    << "#include <algorithm>\n"
+    << "#include <cstdlib>\n"
+    << "#include <iterator>\n"
+    << "#include <stdexcept>\n\n"
+
+    << "using namespace llvm;\n"
+    << "using namespace llvmc;\n\n"
+
+    << "extern cl::opt<std::string> OutputFilename;\n\n"
+
+    << "inline const char* checkCString(const char* s)\n"
+    << "{ return s == NULL ? \"\" : s; }\n\n";
 }
 
-/// run - The back-end entry point.
-void LLVMCConfigurationEmitter::run (std::ostream &O) {
 
-  // Emit file header.
-  EmitSourceFileHeader("LLVMC Configuration Library", O);
+/// PluginData - Holds all information about a plugin.
+struct PluginData {
+  OptionDescriptions OptDescs;
+  bool HasSink;
+  bool HasExterns;
+  ToolDescriptions ToolDescs;
+  RecordVector Edges;
+  int Priority;
+};
+
+/// HasSink - Go through the list of tool descriptions and check if
+/// there are any with the 'sink' property set.
+bool HasSink(const ToolDescriptions& ToolDescs) {
+  for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
+         E = ToolDescs.end(); B != E; ++B)
+    if ((*B)->isSink())
+      return true;
+
+  return false;
+}
+
+/// HasExterns - Go through the list of option descriptions and check
+/// if there are any external options.
+bool HasExterns(const OptionDescriptions& OptDescs) {
+ for (OptionDescriptions::const_iterator B = OptDescs.begin(),
+         E = OptDescs.end(); B != E; ++B)
+    if (B->second.isExtern())
+      return true;
+
+  return false;
+}
+
+/// CollectPluginData - Collect tool and option properties,
+/// compilation graph edges and plugin priority from the parse tree.
+void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
+  // Collect option properties.
+  const RecordVector& OptionLists =
+    Records.getAllDerivedDefinitions("OptionList");
+  CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
+                            Data.OptDescs);
+
+  // Collect tool properties.
+  const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
+  CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
+  Data.HasSink = HasSink(Data.ToolDescs);
+  Data.HasExterns = HasExterns(Data.OptDescs);
+
+  // Collect compilation graph edges.
+  const RecordVector& CompilationGraphs =
+    Records.getAllDerivedDefinitions("CompilationGraph");
+  FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
+                   Data.Edges);
+
+  // Calculate the priority of this plugin.
+  const RecordVector& Priorities =
+    Records.getAllDerivedDefinitions("PluginPriority");
+  Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
+}
+
+/// CheckPluginData - Perform some sanity checks on the collected data.
+void CheckPluginData(PluginData& Data) {
+  // Filter out all tools not mentioned in the compilation graph.
+  FilterNotInGraph(Data.Edges, Data.ToolDescs);
 
-  // Get a list of all defined Tools.
-  RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
-  if (Tools.empty())
-    throw std::string("No tool definitions found!");
+  // Typecheck the compilation graph.
+  TypecheckGraph(Data.Edges, Data.ToolDescs);
+
+  // Check that there are no options without side effects (specified
+  // only in the OptionList).
+  CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
+
+}
 
-  // Gather information from the Tool description dags.
-  ToolPropertiesList tool_props;
-  GlobalOptionDescriptions opt_descs;
-  CollectToolProperties(Tools.begin(), Tools.end(), tool_props, opt_descs);
+void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
+  // Emit file header.
+  EmitIncludes(O);
 
   // Emit global option registration code.
-  EmitOptionDescriptions(opt_descs, O);
+  EmitOptionDefinitions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
+
+  // Emit hook declarations.
+  EmitHookDeclarations(Data.ToolDescs, Data.OptDescs, O);
+
+  O << "namespace {\n\n";
+
+  // Emit PreprocessOptionsLocal() function.
+  EmitPreprocessOptions(Records, Data.OptDescs, O);
 
-  // Emit PopulateLanguageMap() function
-  // (language map maps from file extensions to language names).
+  // Emit PopulateLanguageMapLocal() function
+  // (language map maps from file extensions to language names).
   EmitPopulateLanguageMap(Records, O);
 
   // Emit Tool classes.
-  for (ToolPropertiesList::const_iterator B = tool_props.begin(),
-         E = tool_props.end(); B!=E; ++B)
-    EmitToolClassDefinition(*(*B), opt_descs, O);
+  for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
+         E = Data.ToolDescs.end(); B!=E; ++B)
+    EmitToolClassDefinition(*(*B), Data.OptDescs, O);
 
-  Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
-  if (!CompilationGraphRecord)
-    throw std::string("Compilation graph description not found!");
+  // Emit Edge# classes.
+  EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
 
-  // Typecheck the compilation graph.
-  TypecheckGraph(CompilationGraphRecord, tool_props);
+  // Emit PopulateCompilationGraphLocal() function.
+  EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
 
-  // Emit Edge# classes.
-  EmitEdgeClasses(CompilationGraphRecord, opt_descs, O);
+  // Emit code for plugin registration.
+  EmitRegisterPlugin(Data.Priority, O);
+
+  O << "} // End anonymous namespace.\n\n";
 
-  // Emit PopulateCompilationGraph() function.
-  EmitPopulateCompilationGraph(CompilationGraphRecord, O);
+  // Force linkage magic.
+  O << "namespace llvmc {\n";
+  O << "LLVMC_FORCE_LINKAGE_DECL(LLVMC_PLUGIN_NAME) {}\n";
+  O << "}\n";
 
   // EOF
 }
+
+
+// End of anonymous namespace
+}
+
+/// run - The back-end entry point.
+void LLVMCConfigurationEmitter::run (raw_ostream &O) {
+  try {
+  PluginData Data;
+
+  CollectPluginData(Records, Data);
+  CheckPluginData(Data);
+
+  EmitSourceFileHeader("LLVMC Configuration Library", O);
+  EmitPluginCode(Data, O);
+
+  } catch (std::exception& Error) {
+    throw Error.what() + std::string(" - usually this means a syntax error.");
+  }
+}