llvmc: remove dynamic plugins.
[oota-llvm.git] / utils / TableGen / LLVMCConfigurationEmitter.cpp
index b6858404fa3c9be633c01a4baa46e278e957103a..2d4455078216d9c97098b4113d6aa59ca855beff 100644 (file)
@@ -43,6 +43,7 @@ const unsigned TabWidth = 4;
 const unsigned Indent1  = TabWidth*1;
 const unsigned Indent2  = TabWidth*2;
 const unsigned Indent3  = TabWidth*3;
+const unsigned Indent4  = TabWidth*4;
 
 // Default help string.
 const char * const DefaultHelpString = "NO HELP MESSAGE PROVIDED";
@@ -116,7 +117,7 @@ bool IsDagEmpty (const DagInit& d) {
 // 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 EscapeVariableName (const std::string& Var) {
   std::string ret;
   for (unsigned i = 0; i != Var.size(); ++i) {
     char cur_char = Var[i];
@@ -136,6 +137,21 @@ std::string EscapeVariableName(const std::string& Var) {
   return ret;
 }
 
+/// EscapeQuotes - Replace '"' with '\"'.
+std::string EscapeQuotes (const std::string& Var) {
+  std::string ret;
+  for (unsigned i = 0; i != Var.size(); ++i) {
+    char cur_char = Var[i];
+    if (cur_char == '"') {
+      ret += "\\\"";
+    }
+    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) {
@@ -172,21 +188,25 @@ void apply(F Fun, T0& Arg0, T1& Arg1) {
 /// documentation for detailed description of differences.
 namespace OptionType {
 
-  enum OptionType { Alias, Switch, Parameter, ParameterList,
-                    Prefix, PrefixList};
+  enum OptionType { Alias, Switch, SwitchList,
+                    Parameter, ParameterList, Prefix, PrefixList };
 
   bool IsAlias(OptionType t) {
     return (t == Alias);
   }
 
   bool IsList (OptionType t) {
-    return (t == ParameterList || t == PrefixList);
+    return (t == SwitchList || t == ParameterList || t == PrefixList);
   }
 
   bool IsSwitch (OptionType t) {
     return (t == Switch);
   }
 
+  bool IsSwitchList (OptionType t) {
+    return (t == SwitchList);
+  }
+
   bool IsParameter (OptionType t) {
     return (t == Parameter || t == Prefix);
   }
@@ -198,6 +218,8 @@ OptionType::OptionType stringToOptionType(const std::string& T) {
     return OptionType::Alias;
   else if (T == "switch_option")
     return OptionType::Switch;
+  else if (T == "switch_list_option")
+    return OptionType::SwitchList;
   else if (T == "parameter_option")
     return OptionType::Parameter;
   else if (T == "parameter_list_option")
@@ -212,9 +234,9 @@ OptionType::OptionType stringToOptionType(const std::string& T) {
 
 namespace OptionDescriptionFlags {
   enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
-                                ReallyHidden = 0x4, Extern = 0x8,
-                                OneOrMore = 0x10, Optional = 0x20,
-                                CommaSeparated = 0x40 };
+                                ReallyHidden = 0x4, OneOrMore = 0x8,
+                                Optional = 0x10, CommaSeparated = 0x20,
+                                ForwardNotSplit = 0x40, ZeroOrMore = 0x80 };
 }
 
 /// OptionDescription - Represents data contained in a single
@@ -244,6 +266,9 @@ struct OptionDescription {
   /// Merge - Merge two option descriptions.
   void Merge (const OptionDescription& other);
 
+  /// CheckConsistency - Check that the flags are consistent.
+  void CheckConsistency() const;
+
   // Misc convenient getters/setters.
 
   bool isAlias() const;
@@ -253,8 +278,8 @@ struct OptionDescription {
   bool isCommaSeparated() const;
   void setCommaSeparated();
 
-  bool isExtern() const;
-  void setExtern();
+  bool isForwardNotSplit() const;
+  void setForwardNotSplit();
 
   bool isRequired() const;
   void setRequired();
@@ -262,6 +287,9 @@ struct OptionDescription {
   bool isOneOrMore() const;
   void setOneOrMore();
 
+  bool isZeroOrMore() const;
+  void setZeroOrMore();
+
   bool isOptional() const;
   void setOptional();
 
@@ -274,14 +302,35 @@ struct OptionDescription {
   bool isSwitch() const
   { return OptionType::IsSwitch(this->Type); }
 
+  bool isSwitchList() const
+  { return OptionType::IsSwitchList(this->Type); }
+
   bool isParameter() const
   { return OptionType::IsParameter(this->Type); }
 
   bool isList() const
   { return OptionType::IsList(this->Type); }
 
+  bool isParameterList() const
+  { return (OptionType::IsList(this->Type)
+            && !OptionType::IsSwitchList(this->Type)); }
+
 };
 
+void OptionDescription::CheckConsistency() const {
+  unsigned i = 0;
+
+  i += this->isRequired();
+  i += this->isOptional();
+  i += this->isOneOrMore();
+  i += this->isZeroOrMore();
+
+  if (i > 1) {
+    throw "Only one of (required), (optional), (one_or_more) or "
+      "(zero_or_more) properties is allowed!";
+  }
+}
+
 void OptionDescription::Merge (const OptionDescription& other)
 {
   if (other.Type != Type)
@@ -312,11 +361,11 @@ void OptionDescription::setCommaSeparated() {
   Flags |= OptionDescriptionFlags::CommaSeparated;
 }
 
-bool OptionDescription::isExtern() const {
-  return Flags & OptionDescriptionFlags::Extern;
+bool OptionDescription::isForwardNotSplit() const {
+  return Flags & OptionDescriptionFlags::ForwardNotSplit;
 }
-void OptionDescription::setExtern() {
-  Flags |= OptionDescriptionFlags::Extern;
+void OptionDescription::setForwardNotSplit() {
+  Flags |= OptionDescriptionFlags::ForwardNotSplit;
 }
 
 bool OptionDescription::isRequired() const {
@@ -333,6 +382,13 @@ void OptionDescription::setOneOrMore() {
   Flags |= OptionDescriptionFlags::OneOrMore;
 }
 
+bool OptionDescription::isZeroOrMore() const {
+  return Flags & OptionDescriptionFlags::ZeroOrMore;
+}
+void OptionDescription::setZeroOrMore() {
+  Flags |= OptionDescriptionFlags::ZeroOrMore;
+}
+
 bool OptionDescription::isOptional() const {
   return Flags & OptionDescriptionFlags::Optional;
 }
@@ -363,6 +419,8 @@ const char* OptionDescription::GenTypeDeclaration() const {
     return "cl::list<std::string>";
   case OptionType::Switch:
     return "cl::opt<bool>";
+  case OptionType::SwitchList:
+    return "cl::list<bool>";
   case OptionType::Parameter:
   case OptionType::Prefix:
   default:
@@ -380,6 +438,8 @@ std::string OptionDescription::GenVariableName() const {
     return "AutoGeneratedList_" + EscapedName;
   case OptionType::Switch:
     return "AutoGeneratedSwitch_" + EscapedName;
+  case OptionType::SwitchList:
+    return "AutoGeneratedSwitchList_" + EscapedName;
   case OptionType::Prefix:
   case OptionType::Parameter:
   default:
@@ -404,8 +464,11 @@ public:
   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& FindParameterList(const std::string& OptName) const;
   const OptionDescription&
   FindListOrParameter(const std::string& OptName) const;
+  const OptionDescription&
+  FindParameterListOrParameter(const std::string& OptName) const;
 
   /// insertDescription - Insert new OptionDescription into
   /// OptionDescriptions list
@@ -442,6 +505,14 @@ OptionDescriptions::FindList(const std::string& OptName) const {
   return OptDesc;
 }
 
+const OptionDescription&
+OptionDescriptions::FindParameterList(const std::string& OptName) const {
+  const OptionDescription& OptDesc = this->FindOption(OptName);
+  if (!OptDesc.isList() || OptDesc.isSwitchList())
+    throw OptName + ": incorrect option type - should be a parameter list!";
+  return OptDesc;
+}
+
 const OptionDescription&
 OptionDescriptions::FindParameter(const std::string& OptName) const {
   const OptionDescription& OptDesc = this->FindOption(OptName);
@@ -459,6 +530,16 @@ OptionDescriptions::FindListOrParameter(const std::string& OptName) const {
   return OptDesc;
 }
 
+const OptionDescription&
+OptionDescriptions::FindParameterListOrParameter
+(const std::string& OptName) const {
+  const OptionDescription& OptDesc = this->FindOption(OptName);
+  if ((!OptDesc.isList() && !OptDesc.isParameter()) || OptDesc.isSwitchList())
+    throw OptName
+      + ": incorrect option type - should be a parameter list or parameter!";
+  return OptDesc;
+}
+
 void OptionDescriptions::InsertDescription (const OptionDescription& o) {
   container_type::iterator I = Descriptions.find(o.Name);
   if (I != Descriptions.end()) {
@@ -561,16 +642,18 @@ public:
     : optDesc_(OD)
   {
     if (!staticMembersInitialized_) {
-      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("zero_or_more", &CollectOptionProperties::onZeroOrMore);
       AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
       AddHandler("required", &CollectOptionProperties::onRequired);
       AddHandler("optional", &CollectOptionProperties::onOptional);
       AddHandler("comma_separated", &CollectOptionProperties::onCommaSeparated);
+      AddHandler("forward_not_split",
+                 &CollectOptionProperties::onForwardNotSplit);
 
       staticMembersInitialized_ = true;
     }
@@ -587,14 +670,9 @@ private:
   /// Option property handlers --
   /// Methods that handle option properties such as (help) or (hidden).
 
-  void onExtern (const DagInit& d) {
-    CheckNumberOfArguments(d, 0);
-    optDesc_.setExtern();
-  }
-
   void onHelp (const DagInit& d) {
     CheckNumberOfArguments(d, 1);
-    optDesc_.Help = InitPtrToString(d.getArg(0));
+    optDesc_.Help = EscapeQuotes(InitPtrToString(d.getArg(0)));
   }
 
   void onHidden (const DagInit& d) {
@@ -609,17 +687,23 @@ private:
 
   void onCommaSeparated (const DagInit& d) {
     CheckNumberOfArguments(d, 0);
-    if (!optDesc_.isList())
-      throw "'comma_separated' is valid only on list options!";
+    if (!optDesc_.isParameterList())
+      throw "'comma_separated' is valid only on parameter list options!";
     optDesc_.setCommaSeparated();
   }
 
+  void onForwardNotSplit (const DagInit& d) {
+    CheckNumberOfArguments(d, 0);
+    if (!optDesc_.isParameter())
+      throw "'forward_not_split' is valid only for parameter options!";
+    optDesc_.setForwardNotSplit();
+  }
+
   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();
+    optDesc_.CheckConsistency();
   }
 
   void onInit (const DagInit& d) {
@@ -638,24 +722,31 @@ private:
 
   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();
+    optDesc_.CheckConsistency();
+  }
+
+  void onZeroOrMore (const DagInit& d) {
+    CheckNumberOfArguments(d, 0);
+
+    if (optDesc_.isList())
+      llvm::errs() << "Warning: specifying the 'zero_or_more' property "
+        "on a list option has no effect.\n";
+
+    optDesc_.setZeroOrMore();
+    optDesc_.CheckConsistency();
   }
 
   void onOptional (const DagInit& d) {
     CheckNumberOfArguments(d, 0);
-    if (optDesc_.isRequired() || optDesc_.isOneOrMore())
-      throw "Only one of (required), (optional) or "
-        "(one_or_more) properties is allowed!";
-    if (!OptionType::IsList(optDesc_.Type))
+
+    if (!optDesc_.isList())
       llvm::errs() << "Warning: specifying the 'optional' property"
-        "on a non-list option will have no effect.\n";
+        "on a non-list option has no effect.\n";
+
     optDesc_.setOptional();
+    optDesc_.CheckConsistency();
   }
 
   void onMultiVal (const DagInit& d) {
@@ -664,7 +755,7 @@ private:
     if (val < 2)
       throw "Error in the 'multi_val' property: "
         "the value must be greater than 1!";
-    if (!OptionType::IsList(optDesc_.Type))
+    if (!optDesc_.isParameterList())
       throw "The multi_val property is valid only on list options!";
     optDesc_.MultiVal = val;
   }
@@ -691,16 +782,17 @@ public:
 
     OptionDescription OD(Type, Name);
 
-    if (!OD.isExtern())
-      CheckNumberOfArguments(d, 2);
+
+    CheckNumberOfArguments(d, 2);
 
     if (OD.isAlias()) {
       // Aliases store the aliased option name in the 'Help' field.
       OD.Help = InitPtrToString(d.getArg(1));
     }
-    else if (!OD.isExtern()) {
+    else {
       processOptionProperties(d, OD);
     }
+
     OptDescs_.InsertDescription(OD);
   }
 
@@ -746,9 +838,12 @@ struct ToolDescription : public RefCountedBase<ToolDescription> {
   Init* CmdLine;
   Init* Actions;
   StrVector InLanguage;
+  std::string InFileOption;
+  std::string OutFileOption;
   std::string OutLanguage;
   std::string OutputSuffix;
   unsigned Flags;
+  const Init* OnEmpty;
 
   // Various boolean properties
   void setSink()      { Flags |= ToolFlags::Sink; }
@@ -758,9 +853,13 @@ struct ToolDescription : public RefCountedBase<ToolDescription> {
 
   // Default ctor here is needed because StringMap can only store
   // DefaultConstructible objects
-  ToolDescription() : CmdLine(0), Actions(0), Flags(0) {}
+  ToolDescription ()
+    : CmdLine(0), Actions(0), OutFileOption("-o"),
+      Flags(0), OnEmpty(0)
+  {}
   ToolDescription (const std::string& n)
-  : Name(n), CmdLine(0), Actions(0), Flags(0)
+    : Name(n), CmdLine(0), Actions(0), OutFileOption("-o"),
+      Flags(0), OnEmpty(0)
   {}
 };
 
@@ -791,12 +890,17 @@ public:
     if (!staticMembersInitialized_) {
 
       AddHandler("actions", &CollectToolProperties::onActions);
-      AddHandler("cmd_line", &CollectToolProperties::onCmdLine);
+      AddHandler("command", &CollectToolProperties::onCommand);
       AddHandler("in_language", &CollectToolProperties::onInLanguage);
       AddHandler("join", &CollectToolProperties::onJoin);
       AddHandler("out_language", &CollectToolProperties::onOutLanguage);
+
+      AddHandler("out_file_option", &CollectToolProperties::onOutFileOption);
+      AddHandler("in_file_option", &CollectToolProperties::onInFileOption);
+
       AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
       AddHandler("sink", &CollectToolProperties::onSink);
+      AddHandler("works_on_empty", &CollectToolProperties::onWorksOnEmpty);
 
       staticMembersInitialized_ = true;
     }
@@ -821,7 +925,7 @@ private:
     toolDesc_.Actions = Case;
   }
 
-  void onCmdLine (const DagInit& d) {
+  void onCommand (const DagInit& d) {
     CheckNumberOfArguments(d, 1);
     toolDesc_.CmdLine = d.getArg(0);
   }
@@ -863,6 +967,16 @@ private:
     toolDesc_.OutLanguage = InitPtrToString(d.getArg(0));
   }
 
+  void onOutFileOption (const DagInit& d) {
+    CheckNumberOfArguments(d, 1);
+    toolDesc_.OutFileOption = InitPtrToString(d.getArg(0));
+  }
+
+  void onInFileOption (const DagInit& d) {
+    CheckNumberOfArguments(d, 1);
+    toolDesc_.InFileOption = InitPtrToString(d.getArg(0));
+  }
+
   void onOutputSuffix (const DagInit& d) {
     CheckNumberOfArguments(d, 1);
     toolDesc_.OutputSuffix = InitPtrToString(d.getArg(0));
@@ -873,6 +987,10 @@ private:
     toolDesc_.setSink();
   }
 
+  void onWorksOnEmpty (const DagInit& d) {
+    toolDesc_.OnEmpty = d.getArg(0);
+  }
+
 };
 
 /// CollectToolDescriptions - Gather information about tool properties
@@ -909,22 +1027,6 @@ void FillInEdgeVector(RecordVector::const_iterator B,
   }
 }
 
-/// 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:
@@ -1086,14 +1188,28 @@ class ExtractOptionNames {
     if (ActionName == "forward" || ActionName == "forward_as" ||
         ActionName == "forward_value" ||
         ActionName == "forward_transformed_value" ||
-        ActionName == "switch_on" || ActionName == "parameter_equals" ||
+        ActionName == "switch_on" || ActionName == "any_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);
+
+      Init* Arg = Stmt.getArg(0);
+      if (typeid(*Arg) == typeid(StringInit)) {
+        const std::string& Name = InitPtrToString(Arg);
+        OptionNames_.insert(Name);
+      }
+      else {
+        // It's a list.
+        const ListInit& List = InitPtrToList(Arg);
+        for (ListInit::const_iterator B = List.begin(), E = List.end();
+             B != E; ++B) {
+          const std::string& Name = InitPtrToString(*B);
+          OptionNames_.insert(Name);
+        }
+      }
     }
-    else if (ActionName == "and" || ActionName == "or") {
+    else if (ActionName == "and" || ActionName == "or" || ActionName == "not") {
       for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
         this->processDag(Stmt.getArg(i));
       }
@@ -1192,7 +1308,7 @@ void EmitListTest(const ListInit& L, const char* LogicOp,
     if (isFirst)
       isFirst = false;
     else
-      O << " || ";
+      O << ' ' << LogicOp << ' ';
     Callback(InitPtrToString(*B), O);
   }
 }
@@ -1240,7 +1356,7 @@ bool EmitCaseTest1ArgList(const std::string& TestName,
                           const DagInit& d,
                           const OptionDescriptions& OptDescs,
                           raw_ostream& O) {
-  const ListInit& L = *static_cast<ListInit*>(d.getArg(0));
+  const ListInit& L = InitPtrToList(d.getArg(0));
 
   if (TestName == "any_switch_on") {
     EmitListTest(L, "||", EmitSwitchOn(OptDescs), O);
@@ -1330,7 +1446,7 @@ bool EmitCaseTest2Args(const std::string& TestName,
     return true;
   }
   else if (TestName == "element_in_list") {
-    const OptionDescription& OptDesc = OptDescs.FindList(OptName);
+    const OptionDescription& OptDesc = OptDescs.FindParameterList(OptName);
     const std::string& VarName = OptDesc.GenVariableName();
     O << "std::find(" << VarName << ".begin(),\n";
     O.indent(IndentLevel + Indent1)
@@ -1397,7 +1513,7 @@ void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
   else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
     return;
   else
-    throw TestName + ": unknown edge property!";
+    throw "Unknown test '" + TestName + "' used in the 'case' construct!";
 }
 
 
@@ -1461,7 +1577,7 @@ public:
 /// 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,
+/// Callback's type is void F(const Init* Statement, unsigned IndentLevel,
 /// raw_ostream& O).
 /// EmitElseIf parameter controls the type of condition that is emitted ('if
 /// (..) {..} else if (..) {} .. else {..}' vs. 'if (..) {..} if(..)  {..}
@@ -1670,81 +1786,58 @@ void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
   if (StrVec.empty())
     throw "Tool '" + ToolName + "' has empty command line!";
 
-  StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
+  StrVector::const_iterator B = StrVec.begin(), E = StrVec.end();
 
-  // If there is a hook invocation on the place of the first command, skip it.
+  // Emit the command itself.
   assert(!StrVec[0].empty());
+  O.indent(IndentLevel) << "cmd = ";
   if (StrVec[0][0] == '$') {
-    while (I != E && (*I)[0] != ')' )
-      ++I;
-
-    // Skip the ')' symbol.
-    ++I;
+    B = SubstituteSpecialCommands(B, E, IsJoin, O);
+    ++B;
   }
   else {
-    ++I;
+    O << '"' << StrVec[0] << '"';
+    ++B;
   }
+  O << ";\n";
 
-  bool hasINFILE = false;
+  // Go through the command arguments.
+  assert(B <= E);
+  for (; B != E; ++B) {
+    const std::string& cmd = *B;
 
-  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";
-      }
+      O << "vec.push_back(std::make_pair(0, ";
+      B = SubstituteSpecialCommands(B, E, IsJoin, O);
+      O << "));\n";
     }
     else {
-      O << "vec.push_back(\"" << cmd << "\");\n";
+      O << "vec.push_back(std::make_pair(0, \"" << 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) {}
+/// EmitForEachListElementCycleHeader - Emit common code for iterating through
+/// all elements of a list. Helper function used by
+/// EmitForwardOptionPropertyHandlingCode.
+void EmitForEachListElementCycleHeader (const OptionDescription& D,
+                                        unsigned IndentLevel,
+                                        raw_ostream& O) {
+  unsigned IndentLevel1 = IndentLevel + Indent1;
 
-  void operator()(const Init* Statement, unsigned IndentLevel,
-                  raw_ostream& O) const
-  {
-    EmitCmdLineVecFill(Statement, ToolName, IsJoin, IndentLevel, O);
-  }
-};
+  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) << "unsigned pos = " << D.GenVariableName()
+                         << ".getPosition(B - " << D.GenVariableName()
+                         << ".begin());\n";
+}
 
 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
 /// implement EmitActionHandler. Emits code for
@@ -1760,45 +1853,61 @@ void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
 
   switch (D.Type) {
   case OptionType::Switch:
-    O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
+    O.indent(IndentLevel)
+      << "vec.push_back(std::make_pair(" << D.GenVariableName()
+      << ".getPosition(), \"" << Name << "\"));\n";
     break;
   case OptionType::Parameter:
-    O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
-    O.indent(IndentLevel) << "vec.push_back(" << D.GenVariableName() << ");\n";
+    O.indent(IndentLevel) << "vec.push_back(std::make_pair("
+                          << D.GenVariableName()
+                          <<".getPosition(), \"" << Name;
+
+    if (!D.isForwardNotSplit()) {
+      O << "\"));\n";
+      O.indent(IndentLevel) << "vec.push_back(std::make_pair("
+                            << D.GenVariableName() << ".getPosition(), "
+                            << D.GenVariableName() << "));\n";
+    }
+    else {
+      O << "=\" + " << D.GenVariableName() << "));\n";
+    }
     break;
   case OptionType::Prefix:
-    O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\" + "
-                          << D.GenVariableName() << ");\n";
+    O.indent(IndentLevel) << "vec.push_back(std::make_pair("
+                          << D.GenVariableName() << ".getPosition(), \""
+                          << Name << "\" + "
+                          << D.GenVariableName() << "));\n";
     break;
   case OptionType::PrefixList:
-    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";
+    EmitForEachListElementCycleHeader(D, IndentLevel, O);
+    O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, \""
+                           << 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) << "vec.push_back(std::make_pair(pos, *B));\n";
       O.indent(IndentLevel1) << "++B;\n";
     }
 
     O.indent(IndentLevel) << "}\n";
     break;
   case OptionType::ParameterList:
-    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";
+    EmitForEachListElementCycleHeader(D, IndentLevel, O);
+    O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, \""
+                           << Name << "\"));\n";
 
     for (int i = 0, j = D.MultiVal; i < j; ++i) {
-      O.indent(IndentLevel1) << "vec.push_back(*B);\n";
+      O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, *B));\n";
       O.indent(IndentLevel1) << "++B;\n";
     }
 
+    O.indent(IndentLevel) << "}\n";
+    break;
+  case OptionType::SwitchList:
+    EmitForEachListElementCycleHeader(D, IndentLevel, O);
+    O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, \""
+                           << Name << "\"));\n";
+    O.indent(IndentLevel1) << "++B;\n";
     O.indent(IndentLevel) << "}\n";
     break;
   case OptionType::Alias:
@@ -1816,10 +1925,10 @@ struct ActionHandlingCallbackBase
                   unsigned IndentLevel, raw_ostream& O) const
   {
     O.indent(IndentLevel)
-      << "throw std::runtime_error(\"" <<
-      (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0))
-       : "Unknown error!")
+      << "PrintError(\""
+      << (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0)) : "Unknown error!")
       << "\");\n";
+    O.indent(IndentLevel) << "return 1;\n";
   }
 
   void onWarningDag(const DagInit& d,
@@ -1877,7 +1986,8 @@ class EmitActionHandlersCallback :
   {
     CheckNumberOfArguments(Dag, 1);
     this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
-                             "vec.push_back(", ");\n", IndentLevel, O);
+                             "vec.push_back(std::make_pair(65536, ", "));\n",
+                             IndentLevel, O);
   }
 
   void onForward (const DagInit& Dag,
@@ -1904,16 +2014,32 @@ class EmitActionHandlersCallback :
   {
     CheckNumberOfArguments(Dag, 1);
     const std::string& Name = InitPtrToString(Dag.getArg(0));
-    const OptionDescription& D = OptDescs.FindListOrParameter(Name);
+    const OptionDescription& D = OptDescs.FindParameterListOrParameter(Name);
+
+    if (D.isSwitchList()) {
+      throw std::runtime_error
+        ("forward_value is not allowed with switch_list");
+    }
 
     if (D.isParameter()) {
-      O.indent(IndentLevel) << "vec.push_back("
-                            << D.GenVariableName() << ");\n";
+      O.indent(IndentLevel) << "vec.push_back(std::make_pair("
+                            << D.GenVariableName() << ".getPosition(), "
+                            << D.GenVariableName() << "));\n";
     }
     else {
-      O.indent(IndentLevel) << "std::copy(" << D.GenVariableName()
-                            << ".begin(), " << D.GenVariableName()
-                            << ".end(), std::back_inserter(vec));\n";
+      O.indent(IndentLevel) << "for (" << D.GenTypeDeclaration()
+                            << "::iterator B = " << D.GenVariableName()
+                            << ".begin(), \n";
+      O.indent(IndentLevel + Indent1) << " E = " << D.GenVariableName()
+                                      << ".end(); B != E; ++B)\n";
+      O.indent(IndentLevel) << "{\n";
+      O.indent(IndentLevel + Indent1)
+        << "unsigned pos = " << D.GenVariableName()
+        << ".getPosition(B - " << D.GenVariableName()
+        << ".begin());\n";
+      O.indent(IndentLevel + Indent1)
+        << "vec.push_back(std::make_pair(pos, *B));\n";
+      O.indent(IndentLevel) << "}\n";
     }
   }
 
@@ -1923,11 +2049,20 @@ class EmitActionHandlersCallback :
     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);
+    const OptionDescription& D = OptDescs.FindParameterListOrParameter(Name);
 
-    O.indent(IndentLevel) << "vec.push_back(" << "hooks::"
-                          << Hook << "(" << D.GenVariableName()
-                          << (D.isParameter() ? ".c_str()" : "") << "));\n";
+    O.indent(IndentLevel) << "vec.push_back(std::make_pair("
+                          << D.GenVariableName() << ".getPosition("
+                          << (D.isList() ? "0" : "") << "), "
+                          << "hooks::" << Hook << "(" << D.GenVariableName()
+                          << (D.isParameter() ? ".c_str()" : "") << ")));\n";
+  }
+
+  void onNoOutFile (const DagInit& Dag,
+                    unsigned IndentLevel, raw_ostream& O) const
+  {
+    CheckNumberOfArguments(Dag, 0);
+    O.indent(IndentLevel) << "no_out_file = true;\n";
   }
 
   void onOutputSuffix (const DagInit& Dag,
@@ -1966,12 +2101,15 @@ class EmitActionHandlersCallback :
       AddHandler("forward_value", &EmitActionHandlersCallback::onForwardValue);
       AddHandler("forward_transformed_value",
                  &EmitActionHandlersCallback::onForwardTransformedValue);
+      AddHandler("no_out_file",
+                 &EmitActionHandlersCallback::onNoOutFile);
       AddHandler("output_suffix", &EmitActionHandlersCallback::onOutputSuffix);
       AddHandler("stop_compilation",
                  &EmitActionHandlersCallback::onStopCompilation);
       AddHandler("unpack_values",
                  &EmitActionHandlersCallback::onUnpackValues);
 
+
       staticMembersInitialized_ = true;
     }
   }
@@ -1983,76 +2121,33 @@ class EmitActionHandlersCallback :
   }
 };
 
-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;
-}
-
-/// 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);
-}
-
 void EmitGenerateActionMethodHeader(const ToolDescription& D,
-                                    bool IsJoin, raw_ostream& O)
+                                    bool IsJoin, bool Naked,
+                                    raw_ostream& O)
 {
+  O.indent(Indent1) << "int GenerateAction(Action& Out,\n";
+
   if (IsJoin)
-    O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
+    O.indent(Indent2) << "const PathVector& inFiles,\n";
   else
-    O.indent(Indent1) << "Action GenerateAction(const sys::Path& inFile,\n";
+    O.indent(Indent2) << "const sys::Path& inFile,\n";
 
-  O.indent(Indent2) << "bool HasChildren,\n";
+  O.indent(Indent2) << "const 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";
+
+  if (!Naked) {
+    O.indent(Indent2) << "std::string cmd;\n";
+    O.indent(Indent2) << "std::string out_file;\n";
+    O.indent(Indent2)
+      << "std::vector<std::pair<unsigned, std::string> > vec;\n";
+    O.indent(Indent2) << "bool stop_compilation = !HasChildren;\n";
+    O.indent(Indent2) << "bool no_out_file = false;\n";
+    O.indent(Indent2) << "std::string output_suffix(\""
+                      << D.OutputSuffix << "\");\n";
+  }
 }
 
 // EmitGenerateActionMethod - Emit either a normal or a "join" version of the
@@ -2061,51 +2156,74 @@ void EmitGenerateActionMethod (const ToolDescription& D,
                                const OptionDescriptions& OptDescs,
                                bool IsJoin, raw_ostream& O) {
 
-  EmitGenerateActionMethodHeader(D, IsJoin, O);
+  EmitGenerateActionMethodHeader(D, IsJoin, /* Naked = */ false, O);
 
   if (!D.CmdLine)
     throw "Tool " + D.Name + " has no cmd_line property!";
 
-  bool IndexCheckRequired = IsOutFileIndexCheckRequired(D.CmdLine);
-  O.indent(Indent2) << "int out_file_index"
-                    << (IndexCheckRequired ? " = -1" : "")
-                    << ";\n\n";
-
-  // Process the cmd_line property.
-  if (typeid(*D.CmdLine) == typeid(StringInit))
-    EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
-  else
-    EmitCaseConstructHandler(D.CmdLine, Indent2,
-                             EmitCmdLineVecFillCallback(IsJoin, D.Name),
-                             true, OptDescs, O);
+  // Process the 'command' property.
+  O << '\n';
+  EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
+  O << '\n';
 
-  // For every understood option, emit handling code.
+  // Process the 'actions' list of this tool.
   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";
+  // Input file (s)
+  if (!D.InFileOption.empty()) {
+    O.indent(Indent2)
+      << "vec.push_back(std::make_pair(InputFilenames.getPosition(0), \""
+      << D.InFileOption << "\");\n";
+  }
+
+  if (IsJoin) {
+    O.indent(Indent2)
+      << "for (PathVector::const_iterator B = inFiles.begin(),\n";
+    O.indent(Indent3) << "E = inFiles.end(); B != E; ++B)\n";
+    O.indent(Indent2) << "{\n";
+    O.indent(Indent3) << "vec.push_back(std::make_pair("
+                      << "InputFilenames.getPosition(B - inFiles.begin()), "
+                      << "B->str()));\n";
+    O.indent(Indent2) << "}\n";
+  }
+  else {
+    O.indent(Indent2) << "vec.push_back(std::make_pair("
+                      << "InputFilenames.getPosition(0), inFile.str()));\n";
+  }
+
+  // Output file
+  O.indent(Indent2) << "if (!no_out_file) {\n";
+  if (!D.OutFileOption.empty())
+    O.indent(Indent3) << "vec.push_back(std::make_pair(65536, \""
+                      << D.OutFileOption << "\"));\n";
+
+  O.indent(Indent3) << "out_file = this->OutFilename("
+                    << (IsJoin ? "sys::Path(),\n" : "inFile,\n");
+  O.indent(Indent4) <<
+    "TempDir, stop_compilation, output_suffix.c_str()).str();\n\n";
+  O.indent(Indent3) << "vec.push_back(std::make_pair(65536, out_file));\n";
+
+  O.indent(Indent2) << "}\n\n";
 
   // Handle the Sink property.
   if (D.isSink()) {
     O.indent(Indent2) << "if (!" << SinkOptionName << ".empty()) {\n";
-    O.indent(Indent3) << "vec.insert(vec.end(), "
-                      << SinkOptionName << ".begin(), " << SinkOptionName
-                      << ".end());\n";
+    O.indent(Indent3) << "for (cl::list<std::string>::iterator B = "
+                      << SinkOptionName << ".begin(), E = " << SinkOptionName
+                      << ".end(); B != E; ++B)\n";
+    O.indent(Indent4) << "vec.push_back(std::make_pair(" << SinkOptionName
+                      << ".getPosition(B - " << SinkOptionName
+                      <<  ".begin()), *B));\n";
     O.indent(Indent2) << "}\n";
   }
 
-  O.indent(Indent2) << "return Action(cmd, vec, stop_compilation, out_file);\n";
+  O.indent(Indent2) << "Out.Construct(cmd, this->SortArgs(vec), "
+                    << "stop_compilation, out_file);\n";
+  O.indent(Indent2) << "return 0;\n";
   O.indent(Indent1) << "}\n\n";
 }
 
@@ -2115,14 +2233,11 @@ 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
+    EmitGenerateActionMethodHeader(ToolDesc, /* IsJoin = */ true,
+                                   /* Naked = */ true, O);
+    O.indent(Indent2) << "PrintError(\"" << ToolDesc.Name
                       << " is not a Join tool!\");\n";
+    O.indent(Indent2) << "return -1;\n";
     O.indent(Indent1) << "}\n\n";
   }
   else {
@@ -2165,6 +2280,29 @@ void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
   O.indent(Indent1) << "}\n\n";
 }
 
+/// EmitWorksOnEmptyCallback - Callback used by EmitWorksOnEmptyMethod in
+/// conjunction with EmitCaseConstructHandler.
+void EmitWorksOnEmptyCallback (const Init* Value,
+                               unsigned IndentLevel, raw_ostream& O) {
+  CheckBooleanConstant(Value);
+  O.indent(IndentLevel) << "return " << Value->getAsString() << ";\n";
+}
+
+/// EmitWorksOnEmptyMethod - Emit the WorksOnEmpty() method for a given Tool
+/// class.
+void EmitWorksOnEmptyMethod (const ToolDescription& D,
+                             const OptionDescriptions& OptDescs,
+                             raw_ostream& O)
+{
+  O.indent(Indent1) << "bool WorksOnEmpty() const {\n";
+  if (D.OnEmpty == 0)
+    O.indent(Indent2) << "return false;\n";
+  else
+    EmitCaseConstructHandler(D.OnEmpty, Indent2, EmitWorksOnEmptyCallback,
+                             /*EmitElseIf = */ true, OptDescs, O);
+  O.indent(Indent1) << "}\n\n";
+}
+
 /// EmitStaticMemberDefinitions - Emit static member definitions for a
 /// given Tool class.
 void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
@@ -2199,6 +2337,7 @@ void EmitToolClassDefinition (const ToolDescription& D,
   EmitNameMethod(D, O);
   EmitInOutLanguageMethods(D, O);
   EmitIsJoinMethod(D, O);
+  EmitWorksOnEmptyMethod(D, OptDescs, O);
   EmitGenerateActionMethods(D, OptDescs, O);
 
   // Close class definition
@@ -2211,8 +2350,7 @@ void EmitToolClassDefinition (const ToolDescription& D,
 /// EmitOptionDefinitions - Iterate over a list of option descriptions
 /// and emit registration code.
 void EmitOptionDefinitions (const OptionDescriptions& descs,
-                            bool HasSink, bool HasExterns,
-                            raw_ostream& O)
+                            bool HasSink, raw_ostream& O)
 {
   std::vector<OptionDescription> Aliases;
 
@@ -2226,17 +2364,9 @@ void EmitOptionDefinitions (const OptionDescriptions& descs,
       continue;
     }
 
-    if (val.isExtern())
-      O << "extern ";
-
     O << val.GenTypeDeclaration() << ' '
       << val.GenVariableName();
 
-    if (val.isExtern()) {
-      O << ";\n";
-      continue;
-    }
-
     O << "(\"" << val.Name << "\"\n";
 
     if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
@@ -2248,12 +2378,15 @@ void EmitOptionDefinitions (const OptionDescriptions& descs,
       else
         O << ", cl::Required";
     }
-    else if (val.isOneOrMore() && val.isList()) {
-        O << ", cl::OneOrMore";
-    }
-    else if (val.isOptional() && val.isList()) {
+
+    if (val.isOptional())
         O << ", cl::Optional";
-    }
+
+    if (val.isOneOrMore())
+        O << ", cl::OneOrMore";
+
+    if (val.isZeroOrMore())
+        O << ", cl::ZeroOrMore";
 
     if (val.isReallyHidden())
       O << ", cl::ReallyHidden";
@@ -2294,9 +2427,7 @@ void EmitOptionDefinitions (const OptionDescriptions& descs,
 
   // Emit the sink option.
   if (HasSink)
-    O << (HasExterns ? "extern cl" : "cl")
-      << "::list<std::string> " << SinkOptionName
-      << (HasExterns ? ";\n" : "(cl::Sink);\n");
+    O << "cl" << "::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
 
   O << '\n';
 }
@@ -2379,8 +2510,15 @@ class EmitPreprocessOptionsCallback :
       O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
       for (ListInit::const_iterator B = List.begin(), E = List.end();
            B != E; ++B) {
-        O.indent(IndentLevel) << OptDesc.GenVariableName() << ".push_back(\""
-                              << InitPtrToString(*B) << "\");\n";
+        const Init* CurElem = *B;
+        if (OptDesc.isSwitchList())
+          CheckBooleanConstant(CurElem);
+
+        O.indent(IndentLevel)
+          << OptDesc.GenVariableName() << ".push_back(\""
+          << (OptDesc.isSwitchList() ? CurElem->getAsString()
+              : InitPtrToString(CurElem))
+          << "\");\n";
       }
     }
     else if (OptDesc.isSwitch()) {
@@ -2448,11 +2586,11 @@ public:
 
 };
 
-/// EmitPreprocessOptions - Emit the PreprocessOptionsLocal() function.
+/// EmitPreprocessOptions - Emit the PreprocessOptions() function.
 void EmitPreprocessOptions (const RecordKeeper& Records,
                             const OptionDescriptions& OptDecs, raw_ostream& O)
 {
-  O << "void PreprocessOptionsLocal() {\n";
+  O << "int PreprocessOptions () {\n";
 
   const RecordVector& OptionPreprocessors =
     Records.getAllDerivedDefinitions("OptionPreprocessor");
@@ -2465,15 +2603,18 @@ void EmitPreprocessOptions (const RecordKeeper& Records,
                              false, OptDecs, O);
   }
 
+  O << '\n';
+  O.indent(Indent1) << "return 0;\n";
   O << "}\n\n";
 }
 
-/// EmitPopulateLanguageMap - Emit the PopulateLanguageMapLocal() function.
+/// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
 void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
 {
-  O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
+  O << "int PopulateLanguageMap (LanguageMap& langMap) {\n";
 
   // Get the relevant field out of RecordKeeper
+  // TODO: change this to getAllDerivedDefinitions.
   const Record* LangMapRecord = Records.getDef("LanguageMap");
 
   // It is allowed for a plugin to have no language map.
@@ -2496,6 +2637,8 @@ void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
     }
   }
 
+  O << '\n';
+  O.indent(Indent1) << "return 0;\n";
   O << "}\n\n";
 }
 
@@ -2513,10 +2656,12 @@ void IncDecWeight (const Init* i, unsigned IndentLevel,
     O.indent(IndentLevel) << "ret -= ";
   }
   else if (OpName == "error") {
+    // TODO: fix this
     CheckNumberOfArguments(d, 1);
-    O.indent(IndentLevel) << "throw std::runtime_error(\""
+    O.indent(IndentLevel) << "PrintError(\""
                           << InitPtrToString(d.getArg(0))
                           << "\");\n";
+    O.indent(IndentLevel) << "return -1;\n";
     return;
   }
   else {
@@ -2571,13 +2716,12 @@ void EmitEdgeClasses (const RecordVector& EdgeVector,
   }
 }
 
-/// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraphLocal()
-/// function.
+/// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph() function.
 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
                                    const ToolDescriptions& ToolDescs,
                                    raw_ostream& O)
 {
-  O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
+  O << "int PopulateCompilationGraph (CompilationGraph& G) {\n";
 
   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
          E = ToolDescs.end(); B != E; ++B)
@@ -2595,17 +2739,21 @@ void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
     const std::string& NodeB = Edge->getValueAsString("b");
     DagInit& Weight = *Edge->getValueAsDag("weight");
 
-    O.indent(Indent1) << "G.insertEdge(\"" << NodeA << "\", ";
+    O.indent(Indent1) << "if (int ret = G.insertEdge(\"" << NodeA << "\", ";
 
     if (IsDagEmpty(Weight))
       O << "new SimpleEdge(\"" << NodeB << "\")";
     else
       O << "new Edge" << i << "()";
 
-    O << ");\n";
+    O << "))\n";
+    O.indent(Indent2) << "return ret;\n";
+
     ++i;
   }
 
+  O << '\n';
+  O.indent(Indent1) << "return 0;\n";
   O << "}\n\n";
 }
 
@@ -2649,7 +2797,8 @@ public:
       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);
+      const OptionDescription& D =
+        OptDescs_.FindParameterListOrParameter(OptName);
 
       HookNames_[HookName] = HookInfo(D.isList() ? HookInfo::ListHook
                                       : HookInfo::ArgHook);
@@ -2782,29 +2931,12 @@ void EmitHookDeclarations(const ToolDescriptions& ToolDescs,
   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/Error.h\"\n"
     << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
 
     << "#include \"llvm/Support/CommandLine.h\"\n"
@@ -2829,10 +2961,8 @@ void EmitIncludes(raw_ostream& O) {
 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
@@ -2846,19 +2976,8 @@ bool HasSink(const ToolDescriptions& ToolDescs) {
   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.
+/// CollectPluginData - Collect compilation graph edges, tool properties and
+/// option properties from the parse tree.
 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
   // Collect option properties.
   const RecordVector& OptionLists =
@@ -2870,18 +2989,12 @@ void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
   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.
@@ -2895,7 +3008,6 @@ void CheckPluginData(PluginData& Data) {
   // Check that there are no options without side effects (specified
   // only in the OptionList).
   CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
-
 }
 
 void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
@@ -2903,20 +3015,13 @@ void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
   EmitIncludes(O);
 
   // Emit global option registration code.
-  EmitOptionDefinitions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
+  EmitOptionDefinitions(Data.OptDescs, Data.HasSink, O);
 
   // Emit hook declarations.
   EmitHookDeclarations(Data.ToolDescs, Data.OptDescs, O);
 
   O << "namespace {\n\n";
 
-  // Emit PreprocessOptionsLocal() function.
-  EmitPreprocessOptions(Records, Data.OptDescs, O);
-
-  // Emit PopulateLanguageMapLocal() function
-  // (language map maps from file extensions to language names).
-  EmitPopulateLanguageMap(Records, O);
-
   // Emit Tool classes.
   for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
          E = Data.ToolDescs.end(); B!=E; ++B)
@@ -2925,18 +3030,23 @@ void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
   // Emit Edge# classes.
   EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
 
-  // Emit PopulateCompilationGraphLocal() function.
-  EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
-
-  // Emit code for plugin registration.
-  EmitRegisterPlugin(Data.Priority, O);
-
   O << "} // End anonymous namespace.\n\n";
 
-  // Force linkage magic.
   O << "namespace llvmc {\n";
-  O << "LLVMC_FORCE_LINKAGE_DECL(LLVMC_PLUGIN_NAME) {}\n";
-  O << "}\n";
+  O << "namespace autogenerated {\n\n";
+
+  // Emit PreprocessOptions() function.
+  EmitPreprocessOptions(Records, Data.OptDescs, O);
+
+  // Emit PopulateLanguageMap() function
+  // (language map maps from file extensions to language names).
+  EmitPopulateLanguageMap(Records, O);
+
+  // Emit PopulateCompilationGraph() function.
+  EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
+
+  O << "} // End namespace autogenerated.\n";
+  O << "} // End namespace llvmc.\n\n";
 
   // EOF
 }
@@ -2953,7 +3063,7 @@ void LLVMCConfigurationEmitter::run (raw_ostream &O) {
   CollectPluginData(Records, Data);
   CheckPluginData(Data);
 
-  EmitSourceFileHeader("LLVMC Configuration Library", O);
+  this->EmitSourceFileHeader("LLVMC Configuration Library", O);
   EmitPluginCode(Data, O);
 
   } catch (std::exception& Error) {