Add support for user-provided hooks and environment variable reads to the cmd_line...
[oota-llvm.git] / utils / TableGen / LLVMCConfigurationEmitter.cpp
index 1947aa5bef55001a51bb7a83a84e1decf600b93c..d160412cfaa718e916a351e1a74c7fd771c46ae4 100644 (file)
@@ -53,30 +53,33 @@ const char * SinkOptionName = "AutoGeneratedSinkOption";
 //===----------------------------------------------------------------------===//
 /// Helper functions
 
-std::string InitPtrToString(Init* ptr) {
-  StringInit& val = dynamic_cast<StringInit&>(*ptr);
+const std::string& InitPtrToString(const Init* ptr) {
+  const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
   return val.getValue();
 }
 
-int InitPtrToInt(Init* ptr) {
-  IntInit& val = dynamic_cast<IntInit&>(*ptr);
+int InitPtrToInt(const Init* ptr) {
+  const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
   return val.getValue();
 }
 
-const DagInit& InitPtrToDagInitRef(Init* ptr) {
-  DagInit& val = dynamic_cast<DagInit&>(*ptr);
+const DagInit& InitPtrToDagInitRef(const Init* ptr) {
+  const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
   return val;
 }
 
-
 // checkNumberOfArguments - Ensure that the number of args in d is
-// less than or equal to min_arguments, otherwise throw an exception .
+// less than or equal to min_arguments, otherwise throw an exception.
 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
   if (d->getNumArgs() < min_arguments)
     throw "Property " + d->getOperator()->getAsString()
       + " has too few arguments!";
 }
 
+// isDagEmpty - is this DAG marked with an empty marker?
+bool isDagEmpty (const DagInit* d) {
+  return d->getOperator()->getAsString() == "empty";
+}
 
 //===----------------------------------------------------------------------===//
 /// Back-end specific code
@@ -135,19 +138,36 @@ struct OptionDescription {
     }
   }
 
+  // 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" + Name;
+     return "AutoGeneratedSwitch" + EscapedName;
    case OptionType::Prefix:
-     return "AutoGeneratedPrefix" + Name;
+     return "AutoGeneratedPrefix" + EscapedName;
    case OptionType::PrefixList:
-     return "AutoGeneratedPrefixList" + Name;
+     return "AutoGeneratedPrefixList" + EscapedName;
    case OptionType::Parameter:
-     return "AutoGeneratedParameter" + Name;
+     return "AutoGeneratedParameter" + EscapedName;
    case OptionType::ParameterList:
    default:
-     return "AutoGeneratedParameterList" + Name;
+     return "AutoGeneratedParameterList" + EscapedName;
    }
   }
 
@@ -287,7 +307,7 @@ namespace ToolFlags {
 
 struct ToolProperties : public RefCountedBase<ToolProperties> {
   std::string Name;
-  StrVector CmdLine;
+  Init* CmdLine;
   std::string InLanguage;
   std::string OutLanguage;
   std::string OutputSuffix;
@@ -412,9 +432,7 @@ private:
 
   void onCmdLine (const DagInit* d) {
     checkNumberOfArguments(d, 1);
-    SplitString(InitPtrToString(d->getArg(0)), toolProps_.CmdLine);
-    if (toolProps_.CmdLine.empty())
-      throw "Tool " + toolProps_.Name + " has empty command line!";
+    toolProps_.CmdLine = d->getArg(0);
   }
 
   void onInLanguage (const DagInit* d) {
@@ -590,6 +608,138 @@ void CollectToolProperties (RecordVector::const_iterator B,
   }
 }
 
+/// 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;
+  }
+
+  return false;
+}
+
+/// EmitCaseTest2Args - Helper function used by
+/// EmitCaseConstructHandler.
+bool EmitCaseTest2Args(const std::string& TestName,
+                       const DagInit& d,
+                       const char* IndentLevel,
+                       const GlobalOptionDescriptions& OptDescs,
+                       std::ostream& O) {
+  checkNumberOfArguments(&d, 2);
+  const std::string& OptName = InitPtrToString(d.getArg(0));
+  const std::string& OptArg = InitPtrToString(d.getArg(1));
+  const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
+
+  if (TestName == "parameter_equals") {
+    if (OptDesc.Type != OptionType::Parameter
+        && OptDesc.Type != OptionType::Prefix)
+      throw OptName + ": incorrect option type!";
+    O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
+    return true;
+  }
+  else if (TestName == "element_in_list") {
+    if (OptDesc.Type != OptionType::ParameterList
+        && OptDesc.Type != OptionType::PrefixList)
+      throw OptName + ": incorrect option type!";
+    const std::string& VarName = OptDesc.GenVariableName();
+    O << "std::find(" << VarName << ".begin(),\n"
+      << IndentLevel << Indent1 << VarName << ".end(), \""
+      << OptArg << "\") != " << VarName << ".end()";
+    return true;
+  }
+
+  return false;
+}
+
+// Forward declaration.
+// EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
+void EmitCaseTest(const DagInit& d, const char* IndentLevel,
+                  const GlobalOptionDescriptions& OptDescs,
+                  std::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) {
+  O << '(';
+  for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
+    const DagInit& InnerTest = InitPtrToDagInitRef(d.getArg(j));
+    EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
+    if (j != NumArgs - 1)
+      O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
+    else
+      O << ')';
+  }
+}
+
+/// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
+void EmitCaseTest(const DagInit& d, const char* IndentLevel,
+                  const GlobalOptionDescriptions& OptDescs,
+                  std::ostream& O) {
+  const std::string& TestName = d.getOperator()->getAsString();
+
+  if (TestName == "and")
+    EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
+  else if (TestName == "or")
+    EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
+  else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
+    return;
+  else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
+    return;
+  else
+    throw TestName + ": unknown edge property!";
+}
+
+// Emit code that handles the 'case' construct.
+// Takes a function object that should emit code for every case clause.
+// Callback's type is
+// void F(Init* Statement, const char* IndentLevel, std::ostream& O).
+template <typename F>
+void EmitCaseConstructHandler(const DagInit* d, const char* IndentLevel,
+                              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";
+    }
+    else {
+      O << IndentLevel << "if (";
+      EmitCaseTest(Test, IndentLevel, OptDescs, O);
+      O << ") {\n";
+    }
+
+    ++i;
+    if (i == numArgs)
+      throw "Case construct handler: no corresponding action "
+        "found for the test " + Test.getAsString() + '!';
+
+    Callback(d->getArg(i), IndentLevel, O);
+    O << IndentLevel << "}\n";
+  }
+}
+
 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
 /// implement EmitOptionPropertyHandlingCode(). Emits code for
 /// handling the (forward) option property.
@@ -626,13 +776,22 @@ void EmitForwardOptionPropertyHandlingCode (const ToolOptionDescription& D,
   }
 }
 
+// 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;
+}
+
 /// EmitOptionPropertyHandlingCode - Helper function used by
 /// EmitGenerateActionMethod(). Emits code that handles option
 /// properties.
-void EmitOptionPropertyHandlingCode (const ToolProperties& P,
-                                     const ToolOptionDescription& D,
+void EmitOptionPropertyHandlingCode (const ToolOptionDescription& D,
                                      std::ostream& O)
 {
+  if (!ToolOptionHasInterestingProperties(D))
+    return;
   // Start of the if-clause.
   O << Indent2 << "if (";
   if (D.Type == OptionType::Switch)
@@ -678,7 +837,6 @@ void EmitOptionPropertyHandlingCode (const ToolProperties& P,
         << D.GenVariableName() << ", vec, \",\");\n";
     }
     else {
-      // TOFIX: move this to the type-checking phase
       throw std::string("Switches can't have unpack_values property!");
     }
   }
@@ -687,50 +845,113 @@ void EmitOptionPropertyHandlingCode (const ToolProperties& P,
   O << Indent2 << "}\n";
 }
 
+/// SubstituteSpecialCommands - Perform string substitution for $CALL
+/// and $ENV. Helper function used by EmitCmdLineVecFill().
+std::string SubstituteSpecialCommands(const std::string& cmd) {
+ if (cmd.find("$CALL(") == 0) {
+   if (cmd.size() == 6)
+     throw std::string("$CALL invocation: empty argument list!");
+   return std::string("hooks::") + (cmd.c_str() + 6) + "()";
+ }
+ else if (cmd.find("$ENV(") == 0) {
+   if (cmd.size() == 5)
+     throw std::string("$ENV invocation: empty argument list!");
+   return std::string("std::getenv(\"") + (cmd.c_str() + 5) + "\")";
+ }
+ else {
+   throw "Unknown special command: " + cmd;
+ }
+}
+
+/// EmitCmdLineVecFill - Emit code that fills in the command line
+/// vector. Helper function used by EmitGenerateActionMethod().
+void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
+                        bool Version, const char* IndentLevel,
+                        std::ostream& O) {
+  StrVector StrVec;
+  SplitString(InitPtrToString(CmdLine), StrVec, ") ");
+  if (StrVec.empty())
+    throw "Tool " + ToolName + " has empty command line!";
+
+  StrVector::const_iterator I = StrVec.begin();
+  ++I;
+  for (StrVector::const_iterator E = StrVec.end(); I != E; ++I) {
+    const std::string& cmd = *I;
+    O << IndentLevel;
+    if (cmd.at(0) == '$') {
+      if (cmd == "$INFILE") {
+        if (Version)
+          O << "for (PathVector::const_iterator B = inFiles.begin()"
+            << ", E = inFiles.end();\n"
+            << IndentLevel << "B != E; ++B)\n"
+            << IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
+        else
+          O << "vec.push_back(inFile.toString());\n";
+      }
+      else if (cmd == "$OUTFILE") {
+        O << "vec.push_back(outFile.toString());\n";
+      }
+      else {
+        O << "vec.push_back(" << SubstituteSpecialCommands(cmd) << ");\n";
+      }
+    }
+    else {
+      O << "vec.push_back(\"" << cmd << "\");\n";
+    }
+  }
+  O << IndentLevel << "ret = Action("
+    << ((StrVec[0][0] == '$') ? SubstituteSpecialCommands(StrVec[0])
+        : "\"" + StrVec[0] + "\"")
+    << ", vec);\n";
+}
+
+/// EmitCmdLineVecFillCallback - A function object wrapper around
+/// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
+/// argument to EmitCaseConstructHandler().
+class EmitCmdLineVecFillCallback {
+  bool Version;
+  const std::string& ToolName;
+ public:
+  EmitCmdLineVecFillCallback(bool Ver, const std::string& TN)
+    : Version(Ver), ToolName(TN) {}
+
+  void operator()(const Init* Statement, const char* IndentLevel,
+                  std::ostream& O) const
+  {
+    EmitCmdLineVecFill(Statement, ToolName, Version,
+                       (std::string(IndentLevel) + Indent1).c_str(), O);
+  }
+};
+
 // EmitGenerateActionMethod - Emit one of two versions of the
 // Tool::GenerateAction() method.
-void EmitGenerateActionMethod (const ToolProperties& P, bool V, std::ostream& O)
-{
-  if (V)
+void EmitGenerateActionMethod (const ToolProperties& P,
+                               const GlobalOptionDescriptions& OptDescs,
+                               bool Version, std::ostream& O) {
+  if (Version)
     O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
   else
     O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
 
-  O << Indent2 << "const sys::Path& outFile) const\n"
+  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";
 
-  // Parse CmdLine tool property
-  if(P.CmdLine.empty())
-    throw "Tool " + P.Name + " has empty command line!";
-
-  StrVector::const_iterator I = P.CmdLine.begin();
-  ++I;
-  for (StrVector::const_iterator E = P.CmdLine.end(); I != E; ++I) {
-    const std::string& cmd = *I;
-    O << Indent2;
-    if (cmd == "$INFILE") {
-      if (V)
-        O << "for (PathVector::const_iterator B = inFiles.begin()"
-          << ", E = inFiles.end();\n"
-          << Indent2 << "B != E; ++B)\n"
-          << Indent3 << "vec.push_back(B->toString());\n";
-      else
-        O << "vec.push_back(inFile.toString());\n";
-    }
-    else if (cmd == "$OUTFILE") {
-      O << "vec.push_back(outFile.toString());\n";
-    }
-    else {
-      O << "vec.push_back(\"" << cmd << "\");\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);
+  else
+    EmitCaseConstructHandler(&InitPtrToDagInitRef(P.CmdLine), Indent2,
+                             EmitCmdLineVecFillCallback(Version, P.Name),
+                             OptDescs, O);
 
   // For every understood option, emit handling code.
   for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
         E = P.OptDescs.end(); B != E; ++B) {
     const ToolOptionDescription& val = B->second;
-    EmitOptionPropertyHandlingCode(P, val, O);
+    EmitOptionPropertyHandlingCode(val, O);
   }
 
   // Handle the Sink property.
@@ -741,25 +962,27 @@ void EmitGenerateActionMethod (const ToolProperties& P, bool V, std::ostream& O)
       << Indent2 << "}\n";
   }
 
-  O << Indent2 << "return Action(\"" << P.CmdLine.at(0) << "\", vec);\n"
+  O << Indent2 << "return ret;\n"
     << Indent1 << "}\n\n";
 }
 
 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
 /// a given Tool class.
-void EmitGenerateActionMethods (const ToolProperties& P, std::ostream& O) {
-
+void EmitGenerateActionMethods (const ToolProperties& P,
+                                const GlobalOptionDescriptions& OptDescs,
+                                std::ostream& O) {
   if (!P.isJoin())
     O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
-      << Indent2 << "const llvm::sys::Path& outFile) const\n"
+      << Indent2 << "const llvm::sys::Path& outFile,\n"
+      << Indent2 << "const InputLanguagesSet& InLangs) const\n"
       << Indent1 << "{\n"
       << Indent2 << "throw std::runtime_error(\"" << P.Name
       << " is not a Join tool!\");\n"
       << Indent1 << "}\n\n";
   else
-    EmitGenerateActionMethod(P, true, O);
+    EmitGenerateActionMethod(P, OptDescs, true, O);
 
-  EmitGenerateActionMethod(P, false, O);
+  EmitGenerateActionMethod(P, OptDescs, false, O);
 }
 
 /// EmitIsLastMethod - Emit the IsLast() method for a given Tool
@@ -821,9 +1044,10 @@ void EmitIsJoinMethod (const ToolProperties& P, std::ostream& O) {
 }
 
 /// EmitToolClassDefinition - Emit a Tool class definition.
-void EmitToolClassDefinition (const ToolProperties& P, std::ostream& O) {
-
-  if(P.Name == "root")
+void EmitToolClassDefinition (const ToolProperties& P,
+                              const GlobalOptionDescriptions& OptDescs,
+                              std::ostream& O) {
+  if (P.Name == "root")
     return;
 
   // Header
@@ -838,7 +1062,7 @@ void EmitToolClassDefinition (const ToolProperties& P, std::ostream& O) {
   EmitInOutLanguageMethods(P, O);
   EmitOutputSuffixMethod(P, O);
   EmitIsJoinMethod(P, O);
-  EmitGenerateActionMethods(P, O);
+  EmitGenerateActionMethods(P, OptDescs, O);
   EmitIsLastMethod(P, O);
 
   // Close class definition
@@ -945,115 +1169,43 @@ void TypecheckGraph (Record* CompilationGraph,
     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)
+    if (IA == IAE)
       throw A->getName() + ": no such tool!";
-    if(IB == IBE)
+    if (IB == IBE)
       throw B->getName() + ": no such tool!";
-    if(A->getName() != "root" && IA->second != IB->second)
+    if (A->getName() != "root" && IA->second != IB->second)
       throw "Edge " + A->getName() + "->" + B->getName()
         + ": output->input language mismatch";
-    if(B->getName() == "root")
+    if (B->getName() == "root")
       throw std::string("Edges back to the root are not allowed!");
   }
 }
 
-/// EmitEdgePropertyTest1Arg - Helper function used by
-/// EmitEdgePropertyTest.
-bool EmitEdgePropertyTest1Arg(const std::string& PropName,
-                              const DagInit& Prop,
-                              const GlobalOptionDescriptions& OptDescs,
-                              std::ostream& O) {
-  checkNumberOfArguments(&Prop, 1);
-  const std::string& OptName = InitPtrToString(Prop.getArg(0));
-  if (PropName == "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 (PropName == "if_input_languages_contain") {
-    O << "InLangs.count(\"" << OptName << "\") != 0";
-    return true;
-  }
-
-  return false;
-}
-
-/// EmitEdgePropertyTest2Args - Helper function used by
-/// EmitEdgePropertyTest.
-bool EmitEdgePropertyTest2Args(const std::string& PropName,
-                               const DagInit& Prop,
-                               const GlobalOptionDescriptions& OptDescs,
-                               std::ostream& O) {
-  checkNumberOfArguments(&Prop, 2);
-  const std::string& OptName = InitPtrToString(Prop.getArg(0));
-  const std::string& OptArg = InitPtrToString(Prop.getArg(1));
-  const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
-
-  if (PropName == "parameter_equals") {
-    if (OptDesc.Type != OptionType::Parameter
-        && OptDesc.Type != OptionType::Prefix)
-      throw OptName + ": incorrect option type!";
-    O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
-    return true;
-  }
-  else if (PropName == "element_in_list") {
-    if (OptDesc.Type != OptionType::ParameterList
-        && OptDesc.Type != OptionType::PrefixList)
-      throw OptName + ": incorrect option type!";
-    const std::string& VarName = OptDesc.GenVariableName();
-    O << "std::find(" << VarName << ".begin(),\n"
-      << Indent3 << VarName << ".end(), \""
-      << OptArg << "\") != " << VarName << ".end()";
-    return true;
-  }
-
-  return false;
-}
-
-// Forward declaration.
-void EmitEdgePropertyTest(const DagInit& Prop,
-                          const GlobalOptionDescriptions& OptDescs,
-                          std::ostream& O);
-
-/// EmitLogicalOperationTest - Helper function used by
-/// EmitEdgePropertyTest.
-void EmitLogicalOperationTest(const DagInit& Prop, const char* LogicOp,
-                              const GlobalOptionDescriptions& OptDescs,
-                              std::ostream& O) {
-  O << '(';
-  for (unsigned j = 0, NumArgs = Prop.getNumArgs(); j < NumArgs; ++j) {
-    const DagInit& InnerProp = InitPtrToDagInitRef(Prop.getArg(j));
-    EmitEdgePropertyTest(InnerProp, OptDescs, O);
-    if (j != NumArgs - 1)
-      O << ")\n" << Indent3 << ' ' << LogicOp << " (";
-    else
-      O << ')';
-  }
-}
+/// IncDecWeight - 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();
 
-/// EmitEdgePropertyTest - Helper function used by EmitEdgeClass.
-void EmitEdgePropertyTest(const DagInit& Prop,
-                          const GlobalOptionDescriptions& OptDescs,
-                          std::ostream& O) {
-  const std::string& PropName = Prop.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 (PropName == "and")
-    EmitLogicalOperationTest(Prop, "&&", OptDescs, O);
-  else if (PropName == "or")
-    EmitLogicalOperationTest(Prop, "||", OptDescs, O);
-  else if (EmitEdgePropertyTest1Arg(PropName, Prop, OptDescs, O))
-    return;
-  else if (EmitEdgePropertyTest2Args(PropName, Prop, OptDescs, O))
-    return;
+  if (d.getNumArgs() > 0)
+    O << InitPtrToInt(d.getArg(0)) << ";\n";
   else
-    throw PropName + ": unknown edge property!";
+    O << "2;\n";
+
 }
 
 /// EmitEdgeClass - Emit a single Edge# class.
-void EmitEdgeClass(unsigned N, const std::string& Target,
-                   ListInit* Props, const GlobalOptionDescriptions& OptDescs,
-                   std::ostream& O) {
+void EmitEdgeClass (unsigned N, const std::string& Target,
+                    DagInit* Case, const GlobalOptionDescriptions& OptDescs,
+                    std::ostream& O) {
 
   // Class constructor.
   O << "class Edge" << N << ": public Edge {\n"
@@ -1065,32 +1217,14 @@ void EmitEdgeClass(unsigned N, const std::string& Target,
     << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
     << Indent2 << "unsigned ret = 0;\n";
 
-  // Emit tests for every edge property.
-  for (size_t i = 0, PropsSize = Props->size(); i < PropsSize; ++i) {
-    const DagInit& Prop = InitPtrToDagInitRef(Props->getElement(i));
-    const std::string& PropName = Prop.getOperator()->getAsString();
-    unsigned N = 2;
-
-    O << Indent2 << "if (";
-
-    if (PropName == "weight") {
-      checkNumberOfArguments(&Prop, 2);
-      N = InitPtrToInt(Prop.getArg(0));
-      const DagInit& InnerProp = InitPtrToDagInitRef(Prop.getArg(1));
-      EmitEdgePropertyTest(InnerProp, OptDescs, O);
-    }
-    else {
-      EmitEdgePropertyTest(Prop, OptDescs, O);
-    }
-
-    O << ")\n" << Indent3 << "ret += " << N << ";\n";
-  }
+  // Handle the 'case' construct.
+  EmitCaseConstructHandler(Case, Indent2, IncDecWeight, OptDescs, O);
 
   O << Indent2 << "return ret;\n"
     << Indent1 << "};\n\n};\n\n";
 }
 
-// Emit Edge* classes that represent graph edges.
+/// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
 void EmitEdgeClasses (Record* CompilationGraph,
                       const GlobalOptionDescriptions& OptDescs,
                       std::ostream& O) {
@@ -1099,12 +1233,12 @@ void EmitEdgeClasses (Record* CompilationGraph,
   for (unsigned i = 0; i < edges->size(); ++i) {
     Record* Edge = edges->getElementAsRecord(i);
     Record* B = Edge->getValueAsDef("b");
-    ListInit* Props = Edge->getValueAsListInit("props");
+    DagInit* Weight = Edge->getValueAsDag("weight");
 
-    if (Props->empty())
+    if (isDagEmpty(Weight))
       continue;
 
-    EmitEdgeClass(i, B->getName(), Props, OptDescs, O);
+    EmitEdgeClass(i, B->getName(), Weight, OptDescs, O);
   }
 }
 
@@ -1127,7 +1261,7 @@ void EmitPopulateCompilationGraph (Record* CompilationGraph,
 
   for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
     const std::string& Name = (*B)->getName();
-    if(Name != "root")
+    if (Name != "root")
       O << Indent1 << "G.insertNode(new "
         << Name << "());\n";
   }
@@ -1139,11 +1273,11 @@ void EmitPopulateCompilationGraph (Record* CompilationGraph,
     Record* Edge = edges->getElementAsRecord(i);
     Record* A = Edge->getValueAsDef("a");
     Record* B = Edge->getValueAsDef("b");
-    ListInit* Props = Edge->getValueAsListInit("props");
+    DagInit* Weight = Edge->getValueAsDag("weight");
 
     O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
 
-    if (Props->empty())
+    if (isDagEmpty(Weight))
       O << "new SimpleEdge(\"" << B->getName() << "\")";
     else
       O << "new Edge" << i << "()";
@@ -1154,6 +1288,68 @@ void EmitPopulateCompilationGraph (Record* CompilationGraph,
   O << "}\n\n";
 }
 
+/// ExtractHookNames - Extract the hook names from all instances of
+/// $CALL(HookName) in the provided command line string. Helper
+/// function used by FillInHookNames().
+void ExtractHookNames(const Init* CmdLine, StrVector& HookNames) {
+  StrVector cmds;
+  llvm::SplitString(InitPtrToString(CmdLine), cmds, ") ");
+  for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
+       B != E; ++B) {
+    const std::string& cmd = *B;
+    if (cmd.find("$CALL(") == 0) {
+      if (cmd.size() == 6)
+        throw std::string("$CALL invocation: empty argument list!");
+      HookNames.push_back(std::string(cmd.c_str() + 6));
+    }
+  }
+}
+
+/// FillInHookNames - Actually extract the hook names from all command
+/// line strings. Helper function used by EmitHookDeclarations().
+void FillInHookNames(const ToolPropertiesList& TPList,
+                     StrVector& HookNames) {
+  for (ToolPropertiesList::const_iterator B = TPList.begin(),
+         E = TPList.end(); B != E; ++B) {
+    const ToolProperties& P = *(*B);
+    if (!P.CmdLine)
+      continue;
+    if (typeid(*P.CmdLine) == typeid(StringInit)) {
+      // This is a string.
+      ExtractHookNames(P.CmdLine, HookNames);
+    }
+    else {
+      // This is a 'case' construct.
+      const DagInit& d = InitPtrToDagInitRef(P.CmdLine);
+      bool even = false;
+      for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
+           B != E; ++B) {
+        if (even)
+          ExtractHookNames(*B, HookNames);
+        even = !even;
+      }
+    }
+  }
+}
+
+/// EmitHookDeclarations - Parse CmdLine fields of all the tool
+/// property records and emit hook function declaration for each
+/// instance of $CALL(HookName).
+void EmitHookDeclarations(const ToolPropertiesList& ToolProps,
+                          std::ostream& O) {
+  StrVector HookNames;
+  FillInHookNames(ToolProps, HookNames);
+  if (HookNames.empty())
+    return;
+  std::sort(HookNames.begin(), HookNames.end());
+  StrVector::const_iterator E = std::unique(HookNames.begin(), HookNames.end());
+
+  O << "namespace hooks {\n";
+  for (StrVector::const_iterator B = HookNames.begin(); B != E; ++B)
+    O << Indent1 << "std::string " << *B << "();\n";
+
+  O << "}\n\n";
+}
 
 // End of anonymous namespace
 }
@@ -1177,6 +1373,9 @@ void LLVMCConfigurationEmitter::run (std::ostream &O) {
   // Emit global option registration code.
   EmitOptionDescriptions(opt_descs, O);
 
+  // Emit hook declarations.
+  EmitHookDeclarations(tool_props, O);
+
   // Emit PopulateLanguageMap() function
   // (a language map maps from file extensions to language names).
   EmitPopulateLanguageMap(Records, O);
@@ -1184,7 +1383,7 @@ void LLVMCConfigurationEmitter::run (std::ostream &O) {
   // Emit Tool classes.
   for (ToolPropertiesList::const_iterator B = tool_props.begin(),
          E = tool_props.end(); B!=E; ++B)
-    EmitToolClassDefinition(*(*B), O);
+    EmitToolClassDefinition(*(*B), opt_descs, O);
 
   Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
   if (!CompilationGraphRecord)