remove parallel support.
[oota-llvm.git] / utils / TableGen / AsmMatcherEmitter.cpp
index 4dbd24c70db5c1ac30577663d7334f6f070e33a7..e5c068bcdf63589c27a56dade7a37de2310415ca 100644 (file)
@@ -140,7 +140,7 @@ static std::string FlattenVariants(const std::string &AsmString,
 }
 
 /// TokenizeAsmString - Tokenize a simplified assembly string.
-static void TokenizeAsmString(const StringRef &AsmString, 
+static void TokenizeAsmString(StringRef AsmString, 
                               SmallVectorImpl<StringRef> &Tokens) {
   unsigned Prev = 0;
   bool InTok = true;
@@ -207,21 +207,20 @@ static void TokenizeAsmString(const StringRef &AsmString,
     Tokens.push_back(AsmString.substr(Prev));
 }
 
-static bool IsAssemblerInstruction(const StringRef &Name,
+static bool IsAssemblerInstruction(StringRef Name,
                                    const CodeGenInstruction &CGI, 
                                    const SmallVectorImpl<StringRef> &Tokens) {
-  // Ignore psuedo ops.
+  // Ignore "codegen only" instructions.
+  if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
+    return false;
+
+  // Ignore pseudo ops.
   //
-  // FIXME: This is a hack.
+  // FIXME: This is a hack; can we convert these instructions to set the
+  // "codegen only" bit instead?
   if (const RecordVal *Form = CGI.TheDef->getValue("Form"))
     if (Form->getValue()->getAsString() == "Pseudo")
       return false;
-  
-  // Ignore "PHI" node.
-  //
-  // FIXME: This is also a hack.
-  if (Name == "PHI")
-    return false;
 
   // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
   //
@@ -245,11 +244,8 @@ static bool IsAssemblerInstruction(const StringRef &Name,
   //
   // FIXME: Is this true?
   //
-  // Also, we ignore instructions which reference the operand multiple times;
-  // this implies a constraint we would not currently honor. These are
-  // currently always fake instructions for simplifying codegen.
-  //
-  // FIXME: Encode this assumption in the .td, so we can error out here.
+  // Also, check for instructions which reference the operand multiple times;
+  // this implies a constraint we would not honor.
   std::set<std::string> OperandNames;
   for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
     if (Tokens[i][0] == '$' && 
@@ -258,18 +254,15 @@ static bool IsAssemblerInstruction(const StringRef &Name,
       DEBUG({
           errs() << "warning: '" << Name << "': "
                  << "ignoring instruction; operand with attribute '" 
-                 << Tokens[i] << "'\n";
+                 << Tokens[i] << "'\n";
         });
       return false;
     }
 
     if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
-      DEBUG({
-          errs() << "warning: '" << Name << "': "
-                 << "ignoring instruction; tied operand '" 
-                 << Tokens[i] << "'\n";
-        });
-      return false;
+      std::string Err = "'" + Name.str() + "': " +
+        "invalid assembler instruction; tied operand '" + Tokens[i].str() + "'";
+      throw TGError(CGI.TheDef->getLoc(), Err);
     }
   }
 
@@ -472,6 +465,10 @@ struct InstructionInfo {
     if (Operands.size() != RHS.Operands.size())
       return false;
 
+    // Otherwise, make sure the ordering of the two instructions is unambiguous
+    // by checking that either (a) a token or operand kind discriminates them,
+    // or (b) the ordering among equivalent kinds is consistent.
+
     // Tokens and operand kinds are unambiguous (assuming a correct target
     // specific parser).
     for (unsigned i = 0, e = Operands.size(); i != e; ++i)
@@ -531,15 +528,16 @@ private:
 
 private:
   /// getTokenClass - Lookup or create the class for the given token.
-  ClassInfo *getTokenClass(const StringRef &Token);
+  ClassInfo *getTokenClass(StringRef Token);
 
   /// getOperandClass - Lookup or create the class for the given operand.
-  ClassInfo *getOperandClass(const StringRef &Token,
+  ClassInfo *getOperandClass(StringRef Token,
                              const CodeGenInstruction::OperandInfo &OI);
 
   /// BuildRegisterClasses - Build the ClassInfo* instances for register
   /// classes.
-  void BuildRegisterClasses(CodeGenTarget &Target);
+  void BuildRegisterClasses(CodeGenTarget &Target, 
+                            std::set<std::string> &SingletonRegisterNames);
 
   /// BuildOperandClasses - Build the ClassInfo* instances for user defined
   /// operand classes.
@@ -572,13 +570,18 @@ void InstructionInfo::dump() {
       continue;
     }
 
+    if (!Op.OperandInfo) {
+      errs() << "(singleton register)\n";
+      continue;
+    }
+
     const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
     errs() << OI.Name << " " << OI.Rec->getName()
            << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
   }
 }
 
-static std::string getEnumNameForToken(const StringRef &Str) {
+static std::string getEnumNameForToken(StringRef Str) {
   std::string Res;
   
   for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
@@ -599,7 +602,18 @@ static std::string getEnumNameForToken(const StringRef &Str) {
   return Res;
 }
 
-ClassInfo *AsmMatcherInfo::getTokenClass(const StringRef &Token) {
+/// getRegisterRecord - Get the register record for \arg name, or 0.
+static Record *getRegisterRecord(CodeGenTarget &Target, StringRef Name) {
+  for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
+    const CodeGenRegister &Reg = Target.getRegisters()[i];
+    if (Name == Reg.TheDef->getValueAsString("AsmName"))
+      return Reg.TheDef;
+  }
+
+  return 0;
+}
+
+ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
   ClassInfo *&Entry = TokenClasses[Token];
   
   if (!Entry) {
@@ -617,7 +631,7 @@ ClassInfo *AsmMatcherInfo::getTokenClass(const StringRef &Token) {
 }
 
 ClassInfo *
-AsmMatcherInfo::getOperandClass(const StringRef &Token,
+AsmMatcherInfo::getOperandClass(StringRef Token,
                                 const CodeGenInstruction::OperandInfo &OI) {
   if (OI.Rec->isSubClassOf("RegisterClass")) {
     ClassInfo *CI = RegisterClassClasses[OI.Rec];
@@ -642,7 +656,9 @@ AsmMatcherInfo::getOperandClass(const StringRef &Token,
   return CI;
 }
 
-void AsmMatcherInfo::BuildRegisterClasses(CodeGenTarget &Target) {
+void AsmMatcherInfo::BuildRegisterClasses(CodeGenTarget &Target,
+                                          std::set<std::string>
+                                            &SingletonRegisterNames) {
   std::vector<CodeGenRegisterClass> RegisterClasses;
   std::vector<CodeGenRegister> Registers;
 
@@ -657,7 +673,13 @@ void AsmMatcherInfo::BuildRegisterClasses(CodeGenTarget &Target) {
          ie = RegisterClasses.end(); it != ie; ++it)
     RegisterSets.insert(std::set<Record*>(it->Elements.begin(),
                                           it->Elements.end()));
-  
+
+  // Add any required singleton sets.
+  for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
+         ie = SingletonRegisterNames.end(); it != ie; ++it)
+    if (Record *Rec = getRegisterRecord(Target, *it))
+      RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
+         
   // Introduce derived sets where necessary (when a register does not determine
   // a unique register set class), and build the mapping of registers to the set
   // they should classify to.
@@ -739,15 +761,37 @@ void AsmMatcherInfo::BuildRegisterClasses(CodeGenTarget &Target) {
   for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
          ie = RegisterMap.end(); it != ie; ++it)
     this->RegisterClasses[it->first] = RegisterSetClasses[it->second];
+
+  // Name the register classes which correspond to singleton registers.
+  for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
+         ie = SingletonRegisterNames.end(); it != ie; ++it) {
+    if (Record *Rec = getRegisterRecord(Target, *it)) {
+      ClassInfo *CI = this->RegisterClasses[Rec];
+      assert(CI && "Missing singleton register class info!");
+
+      if (CI->ValueName.empty()) {
+        CI->ClassName = Rec->getName();
+        CI->Name = "MCK_" + Rec->getName();
+        CI->ValueName = Rec->getName();
+      } else
+        CI->ValueName = CI->ValueName + "," + Rec->getName();
+    }
+  }
 }
 
 void AsmMatcherInfo::BuildOperandClasses(CodeGenTarget &Target) {
   std::vector<Record*> AsmOperands;
   AsmOperands = Records.getAllDerivedDefinitions("AsmOperandClass");
+
+  // Pre-populate AsmOperandClasses map.
+  for (std::vector<Record*>::iterator it = AsmOperands.begin(), 
+         ie = AsmOperands.end(); it != ie; ++it)
+    AsmOperandClasses[*it] = new ClassInfo();
+
   unsigned Index = 0;
   for (std::vector<Record*>::iterator it = AsmOperands.begin(), 
          ie = AsmOperands.end(); it != ie; ++it, ++Index) {
-    ClassInfo *CI = new ClassInfo();
+    ClassInfo *CI = AsmOperandClasses[*it];
     CI->Kind = ClassInfo::UserClass0 + Index;
 
     Init *Super = (*it)->getValueInit("SuperClass");
@@ -797,26 +841,23 @@ AsmMatcherInfo::AsmMatcherInfo(Record *_AsmParser)
 }
 
 void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
-  // Build info for the register classes.
-  BuildRegisterClasses(Target);
-
-  // Build info for the user defined assembly operand classes.
-  BuildOperandClasses(Target);
-
-  // Build the instruction information.
-  for (std::map<std::string, CodeGenInstruction>::const_iterator 
-         it = Target.getInstructions().begin(), 
-         ie = Target.getInstructions().end(); 
-       it != ie; ++it) {
-    const CodeGenInstruction &CGI = it->second;
+  // Parse the instructions; we need to do this first so that we can gather the
+  // singleton register classes.
+  std::set<std::string> SingletonRegisterNames;
+  
+  const std::vector<const CodeGenInstruction*> &InstrList =
+    Target.getInstructionsByEnumValue();
+  
+  for (unsigned i = 0, e = InstrList.size(); i != e; ++i) {
+    const CodeGenInstruction &CGI = *InstrList[i];
 
-    if (!StringRef(it->first).startswith(MatchPrefix))
+    if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
       continue;
 
-    OwningPtr<InstructionInfo> II(new InstructionInfo);
+    OwningPtr<InstructionInfo> II(new InstructionInfo());
     
-    II->InstrName = it->first;
-    II->Instr = &it->second;
+    II->InstrName = CGI.TheDef->getName();
+    II->Instr = &CGI;
     II->AsmString = FlattenVariants(CGI.AsmString, 0);
 
     // Remove comments from the asm string.
@@ -829,12 +870,56 @@ void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
     TokenizeAsmString(II->AsmString, II->Tokens);
 
     // Ignore instructions which shouldn't be matched.
-    if (!IsAssemblerInstruction(it->first, CGI, II->Tokens))
+    if (!IsAssemblerInstruction(CGI.TheDef->getName(), CGI, II->Tokens))
       continue;
 
+    // Collect singleton registers, if used.
+    if (!RegisterPrefix.empty()) {
+      for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
+        if (II->Tokens[i].startswith(RegisterPrefix)) {
+          StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
+          Record *Rec = getRegisterRecord(Target, RegName);
+          
+          if (!Rec) {
+            std::string Err = "unable to find register for '" + RegName.str() + 
+              "' (which matches register prefix)";
+            throw TGError(CGI.TheDef->getLoc(), Err);
+          }
+
+          SingletonRegisterNames.insert(RegName);
+        }
+      }
+    }
+    
+    Instructions.push_back(II.take());
+  }
+
+  // Build info for the register classes.
+  BuildRegisterClasses(Target, SingletonRegisterNames);
+
+  // Build info for the user defined assembly operand classes.
+  BuildOperandClasses(Target);
+
+  // Build the instruction information.
+  for (std::vector<InstructionInfo*>::iterator it = Instructions.begin(),
+         ie = Instructions.end(); it != ie; ++it) {
+    InstructionInfo *II = *it;
+
     for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
       StringRef Token = II->Tokens[i];
 
+      // Check for singleton registers.
+      if (!RegisterPrefix.empty() && Token.startswith(RegisterPrefix)) {
+        StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
+        InstructionInfo::Operand Op;
+        Op.Class = RegisterClasses[getRegisterRecord(Target, RegName)];
+        Op.OperandInfo = 0;
+        assert(Op.Class && Op.Class->Registers.size() == 1 &&
+               "Unexpected class for singleton register");
+        II->Operands.push_back(Op);
+        continue;
+      }
+
       // Check for simple tokens.
       if (Token[0] != '$') {
         InstructionInfo::Operand Op;
@@ -854,30 +939,53 @@ void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
       // Map this token to an operand. FIXME: Move elsewhere.
       unsigned Idx;
       try {
-        Idx = CGI.getOperandNamed(OperandName);
+        Idx = II->Instr->getOperandNamed(OperandName);
       } catch(...) {
-        errs() << "error: unable to find operand: '" << OperandName << "'!\n";
-        break;
+        throw std::string("error: unable to find operand: '" + 
+                          OperandName.str() + "'");
+      }
+
+      // FIXME: This is annoying, the named operand may be tied (e.g.,
+      // XCHG8rm). What we want is the untied operand, which we now have to
+      // grovel for. Only worry about this for single entry operands, we have to
+      // clean this up anyway.
+      const CodeGenInstruction::OperandInfo *OI = &II->Instr->OperandList[Idx];
+      if (OI->Constraints[0].isTied()) {
+        unsigned TiedOp = OI->Constraints[0].getTiedOperand();
+
+        // The tied operand index is an MIOperand index, find the operand that
+        // contains it.
+        for (unsigned i = 0, e = II->Instr->OperandList.size(); i != e; ++i) {
+          if (II->Instr->OperandList[i].MIOperandNo == TiedOp) {
+            OI = &II->Instr->OperandList[i];
+            break;
+          }
+        }
+
+        assert(OI && "Unable to find tied operand target!");
       }
 
-      const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[Idx];      
       InstructionInfo::Operand Op;
-      Op.Class = getOperandClass(Token, OI);
-      Op.OperandInfo = &OI;
+      Op.Class = getOperandClass(Token, *OI);
+      Op.OperandInfo = OI;
       II->Operands.push_back(Op);
     }
-
-    // If we broke out, ignore the instruction.
-    if (II->Operands.size() != II->Tokens.size())
-      continue;
-
-    Instructions.push_back(II.take());
   }
 
   // Reorder classes so that classes preceed super classes.
   std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
 }
 
+static std::pair<unsigned, unsigned> *
+GetTiedOperandAtIndex(SmallVectorImpl<std::pair<unsigned, unsigned> > &List,
+                      unsigned Index) {
+  for (unsigned i = 0, e = List.size(); i != e; ++i)
+    if (Index == List[i].first)
+      return &List[i];
+
+  return 0;
+}
+
 static void EmitConvertToMCInst(CodeGenTarget &Target,
                                 std::vector<InstructionInfo*> &Infos,
                                 raw_ostream &OS) {
@@ -891,10 +999,10 @@ static void EmitConvertToMCInst(CodeGenTarget &Target,
 
   // Start the unified conversion function.
 
-  CvtOS << "static bool ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
+  CvtOS << "static void ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
         << "unsigned Opcode,\n"
-        << "                            SmallVectorImpl<"
-        << Target.getName() << "Operand> &Operands) {\n";
+        << "                      const SmallVectorImpl<MCParsedAsmOperand*"
+        << "> &Operands) {\n";
   CvtOS << "  Inst.setOpcode(Opcode);\n";
   CvtOS << "  switch (Kind) {\n";
   CvtOS << "  default:\n";
@@ -904,6 +1012,9 @@ static void EmitConvertToMCInst(CodeGenTarget &Target,
   OS << "// Unified function for converting operants to MCInst instances.\n\n";
   OS << "enum ConversionKind {\n";
   
+  // TargetOperandClass - This is the target's operand class, like X86Operand.
+  std::string TargetOperandClass = Target.getName() + "Operand";
+  
   for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
          ie = Infos.end(); it != ie; ++it) {
     InstructionInfo &II = **it;
@@ -915,6 +1026,19 @@ static void EmitConvertToMCInst(CodeGenTarget &Target,
       if (Op.OperandInfo)
         MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
     }
+
+    // Find any tied operands.
+    SmallVector<std::pair<unsigned, unsigned>, 4> TiedOperands;
+    for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
+      const CodeGenInstruction::OperandInfo &OpInfo = II.Instr->OperandList[i];
+      for (unsigned j = 0, e = OpInfo.Constraints.size(); j != e; ++j) {
+        const CodeGenInstruction::ConstraintInfo &CI = OpInfo.Constraints[j];
+        if (CI.isTied())
+          TiedOperands.push_back(std::make_pair(OpInfo.MIOperandNo + j,
+                                                CI.getTiedOperand()));
+      }
+    }
+
     std::sort(MIOperandList.begin(), MIOperandList.end());
 
     // Compute the total number of operands.
@@ -933,14 +1057,20 @@ static void EmitConvertToMCInst(CodeGenTarget &Target,
       assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
              "Duplicate match for instruction operand!");
       
-      Signature += "_";
-
       // Skip operands which weren't matched by anything, this occurs when the
       // .td file encodes "implicit" operands as explicit ones.
       //
       // FIXME: This should be removed from the MCInst structure.
-      for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
-        Signature += "Imp";
+      for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
+        std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
+                                                                   CurIndex);
+        if (!Tie)
+          Signature += "__Imp";
+        else
+          Signature += "__Tie" + utostr(Tie->second);
+      }
+
+      Signature += "__";
 
       // Registers are always converted the same, don't duplicate the conversion
       // function based on them.
@@ -958,8 +1088,14 @@ static void EmitConvertToMCInst(CodeGenTarget &Target,
     }
 
     // Add any trailing implicit operands.
-    for (; CurIndex != NumMIOperands; ++CurIndex)
-      Signature += "Imp";
+    for (; CurIndex != NumMIOperands; ++CurIndex) {
+      std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
+                                                                 CurIndex);
+      if (!Tie)
+        Signature += "__Imp";
+      else
+        Signature += "__Tie" + utostr(Tie->second);
+    }
 
     II.ConversionFnKind = Signature;
 
@@ -979,25 +1115,53 @@ static void EmitConvertToMCInst(CodeGenTarget &Target,
       InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
 
       // Add the implicit operands.
-      for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
-        CvtOS << "    Inst.addOperand(MCOperand::CreateReg(0));\n";
+      for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
+        // See if this is a tied operand.
+        std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
+                                                                   CurIndex);
+
+        if (!Tie) {
+          // If not, this is some implicit operand. Just assume it is a register
+          // for now.
+          CvtOS << "    Inst.addOperand(MCOperand::CreateReg(0));\n";
+        } else {
+          // Copy the tied operand.
+          assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
+          CvtOS << "    Inst.addOperand(Inst.getOperand("
+                << Tie->second << "));\n";
+        }
+      }
 
-      CvtOS << "    Operands[" << MIOperandList[i].second 
-         << "]." << Op.Class->RenderMethod 
+      CvtOS << "    ((" << TargetOperandClass << "*)Operands["
+         << MIOperandList[i].second 
+         << "])->" << Op.Class->RenderMethod 
          << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
       CurIndex += Op.OperandInfo->MINumOperands;
     }
     
     // And add trailing implicit operands.
-    for (; CurIndex != NumMIOperands; ++CurIndex)
-      CvtOS << "    Inst.addOperand(MCOperand::CreateReg(0));\n";
-    CvtOS << "    break;\n";
+    for (; CurIndex != NumMIOperands; ++CurIndex) {
+      std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
+                                                                 CurIndex);
+
+      if (!Tie) {
+        // If not, this is some implicit operand. Just assume it is a register
+        // for now.
+        CvtOS << "    Inst.addOperand(MCOperand::CreateReg(0));\n";
+      } else {
+        // Copy the tied operand.
+        assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
+        CvtOS << "    Inst.addOperand(Inst.getOperand("
+              << Tie->second << "));\n";
+      }
+    }
+
+    CvtOS << "    return;\n";
   }
 
   // Finish the convert function.
 
   CvtOS << "  }\n";
-  CvtOS << "  return false;\n";
   CvtOS << "}\n\n";
 
   // Finish the enum, and drop the convert function after it.
@@ -1043,8 +1207,9 @@ static void EmitMatchClassEnumeration(CodeGenTarget &Target,
 static void EmitClassifyOperand(CodeGenTarget &Target,
                                 AsmMatcherInfo &Info,
                                 raw_ostream &OS) {
-  OS << "static MatchClassKind ClassifyOperand("
-     << Target.getName() << "Operand &Operand) {\n";
+  OS << "static MatchClassKind ClassifyOperand(MCParsedAsmOperand *GOp) {\n"
+     << "  " << Target.getName() << "Operand &Operand = *("
+     << Target.getName() << "Operand*)GOp;\n";
 
   // Classify tokens.
   OS << "  if (Operand.isToken())\n";
@@ -1290,7 +1455,7 @@ static void EmitMatchTokenString(CodeGenTarget &Target,
       Matches.push_back(StringPair(CI.ValueName, "return " + CI.Name + ";"));
   }
 
-  OS << "static MatchClassKind MatchTokenString(const StringRef &Name) {\n";
+  OS << "static MatchClassKind MatchTokenString(StringRef Name) {\n";
 
   EmitStringMatcher("Name", Matches, OS);
 
@@ -1313,9 +1478,7 @@ static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
                                  "return " + utostr(i + 1) + ";"));
   }
   
-  OS << "unsigned " << Target.getName() 
-     << AsmParser->getValueAsString("AsmParserClassName")
-     << "::MatchRegisterName(const StringRef &Name) {\n";
+  OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
 
   EmitStringMatcher("Name", Matches, OS);
   
@@ -1328,18 +1491,15 @@ void AsmMatcherEmitter::run(raw_ostream &OS) {
   Record *AsmParser = Target.getAsmParser();
   std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
 
-  EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
-
-  // Emit the function to match a register name to number.
-  EmitMatchRegisterName(Target, AsmParser, OS);
-
   // Compute the information on the instructions to match.
   AsmMatcherInfo Info(AsmParser);
   Info.BuildInfo(Target);
 
-  // Sort the instruction table using the partial order on classes.
-  std::sort(Info.Instructions.begin(), Info.Instructions.end(),
-            less_ptr<InstructionInfo>());
+  // Sort the instruction table using the partial order on classes. We use
+  // stable_sort to ensure that ambiguous instructions are still
+  // deterministically ordered.
+  std::stable_sort(Info.Instructions.begin(), Info.Instructions.end(),
+                   less_ptr<InstructionInfo>());
   
   DEBUG_WITH_TYPE("instruction_info", {
       for (std::vector<InstructionInfo*>::iterator 
@@ -1373,6 +1533,15 @@ void AsmMatcherEmitter::run(raw_ostream &OS) {
                << " ambiguous instructions!\n";
       });
 
+  // Write the output.
+
+  EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
+
+  // Emit the function to match a register name to number.
+  EmitMatchRegisterName(Target, AsmParser, OS);
+  
+  OS << "#ifndef REGISTERS_ONLY\n\n";
+
   // Generate the unified function to convert operands into an MCInst.
   EmitConvertToMCInst(Target, Info.Instructions, OS);
 
@@ -1397,9 +1566,8 @@ void AsmMatcherEmitter::run(raw_ostream &OS) {
     MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
   
   OS << "bool " << Target.getName() << ClassName
-     << "::MatchInstruction(" 
-     << "SmallVectorImpl<" << Target.getName() << "Operand> &Operands, "
-     << "MCInst &Inst) {\n";
+     << "::\nMatchInstruction(const SmallVectorImpl<MCParsedAsmOperand*> "
+        "&Operands,\n                 MCInst &Inst) {\n";
 
   // Emit the static match table; unused classes get initalized to 0 which is
   // guaranteed to be InvalidMatchClass.
@@ -1466,10 +1634,19 @@ void AsmMatcherEmitter::run(raw_ostream &OS) {
     OS << "      continue;\n";
   }
   OS << "\n";
-  OS << "    return ConvertToMCInst(it->ConvertFn, Inst, "
-     << "it->Opcode, Operands);\n";
+  OS << "    ConvertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
+
+  // Call the post-processing function, if used.
+  std::string InsnCleanupFn =
+    AsmParser->getValueAsString("AsmParserInstCleanup");
+  if (!InsnCleanupFn.empty())
+    OS << "    " << InsnCleanupFn << "(Inst);\n";
+
+  OS << "    return false;\n";
   OS << "  }\n\n";
 
   OS << "  return true;\n";
   OS << "}\n\n";
+  
+  OS << "#endif // REGISTERS_ONLY\n";
 }