Fix PR1975: dag isel emitter produces patterns that isel wrong flag result.
[oota-llvm.git] / utils / TableGen / DAGISelEmitter.cpp
index 830d0efc37f32b50edfae8ad6d7ec4fd7173f1d0..7a1920ceac7b2e11bbcdf4fbbe51075ec3481ed7 100644 (file)
 using namespace llvm;
 
 //===----------------------------------------------------------------------===//
-// DAGISelEmitter implementation
+// DAGISelEmitter Helper methods
 //
 
-
 /// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
 /// ComplexPattern.
 static bool NodeIsComplexPattern(TreePatternNode *N) {
@@ -37,7 +36,7 @@ static bool NodeIsComplexPattern(TreePatternNode *N) {
 /// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
 /// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
-                                                   CodegenDAGPatterns &CGP) {
+                                                   CodeGenDAGPatterns &CGP) {
   if (N->isLeaf() &&
       dynamic_cast<DefInit*>(N->getLeafValue()) &&
       static_cast<DefInit*>(N->getLeafValue())->getDef()->
@@ -51,7 +50,7 @@ static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
 /// getPatternSize - Return the 'size' of this pattern.  We want to match large
 /// patterns before small ones.  This is used to determine the size of a
 /// pattern.
-static unsigned getPatternSize(TreePatternNode *P, CodegenDAGPatterns &CGP) {
+static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
   assert((MVT::isExtIntegerInVTs(P->getExtTypes()) || 
           MVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
           P->getExtTypeNum(0) == MVT::isVoid ||
@@ -100,7 +99,7 @@ static unsigned getPatternSize(TreePatternNode *P, CodegenDAGPatterns &CGP) {
 /// This is a temporary hack.  We should really include the instruction
 /// latencies in this calculation.
 static unsigned getResultPatternCost(TreePatternNode *P,
-                                     CodegenDAGPatterns &CGP) {
+                                     CodeGenDAGPatterns &CGP) {
   if (P->isLeaf()) return 0;
   
   unsigned Cost = 0;
@@ -119,7 +118,7 @@ static unsigned getResultPatternCost(TreePatternNode *P,
 /// getResultPatternCodeSize - Compute the code size of instructions for this
 /// pattern.
 static unsigned getResultPatternSize(TreePatternNode *P, 
-                                     CodegenDAGPatterns &CGP) {
+                                     CodeGenDAGPatterns &CGP) {
   if (P->isLeaf()) return 0;
 
   unsigned Cost = 0;
@@ -136,11 +135,11 @@ static unsigned getResultPatternSize(TreePatternNode *P,
 // In particular, we want to match maximal patterns first and lowest cost within
 // a particular complexity first.
 struct PatternSortingPredicate {
-  PatternSortingPredicate(CodegenDAGPatterns &cgp) : CGP(cgp) {}
-  CodegenDAGPatterns &CGP;
+  PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
+  CodeGenDAGPatterns &CGP;
 
-  bool operator()(PatternToMatch *LHS,
-                  PatternToMatch *RHS) {
+  bool operator()(const PatternToMatch *LHS,
+                  const PatternToMatch *RHS) {
     unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
     unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
     LHSSize += LHS->getAddedComplexity();
@@ -180,7 +179,7 @@ static void RemoveAllTypes(TreePatternNode *N) {
 /// NodeHasProperty - return true if TreePatternNode has the specified
 /// property.
 static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
-                            CodegenDAGPatterns &CGP) {
+                            CodeGenDAGPatterns &CGP) {
   if (N->isLeaf()) {
     const ComplexPattern *CP = NodeGetComplexPattern(N, CGP);
     if (CP)
@@ -194,7 +193,7 @@ static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
 }
 
 static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
-                               CodegenDAGPatterns &CGP) {
+                               CodeGenDAGPatterns &CGP) {
   if (NodeHasProperty(N, Property, CGP))
     return true;
 
@@ -207,9 +206,91 @@ static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
   return false;
 }
 
+//===----------------------------------------------------------------------===//
+// Node Transformation emitter implementation.
+//
+void DAGISelEmitter::EmitNodeTransforms(std::ostream &OS) {
+  // Walk the pattern fragments, adding them to a map, which sorts them by
+  // name.
+  typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
+  NXsByNameTy NXsByName;
+
+  for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
+       I != E; ++I)
+    NXsByName.insert(std::make_pair(I->first->getName(), I->second));
+  
+  OS << "\n// Node transformations.\n";
+  
+  for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
+       I != E; ++I) {
+    Record *SDNode = I->second.first;
+    std::string Code = I->second.second;
+    
+    if (Code.empty()) continue;  // Empty code?  Skip it.
+    
+    std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
+    const char *C2 = ClassName == "SDNode" ? "N" : "inN";
+    
+    OS << "inline SDOperand Transform_" << I->first << "(SDNode *" << C2
+       << ") {\n";
+    if (ClassName != "SDNode")
+      OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
+    OS << Code << "\n}\n";
+  }
+}
+
+//===----------------------------------------------------------------------===//
+// Predicate emitter implementation.
+//
+
+void DAGISelEmitter::EmitPredicateFunctions(std::ostream &OS) {
+  OS << "\n// Predicate functions.\n";
+
+  // Walk the pattern fragments, adding them to a map, which sorts them by
+  // name.
+  typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
+  PFsByNameTy PFsByName;
+
+  for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
+       I != E; ++I)
+    PFsByName.insert(std::make_pair(I->first->getName(), *I));
+
+  
+  for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
+       I != E; ++I) {
+    Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
+    TreePattern *P = I->second.second;
+    
+    // If there is a code init for this fragment, emit the predicate code.
+    std::string Code = PatFragRecord->getValueAsCode("Predicate");
+    if (Code.empty()) continue;
+    
+    if (P->getOnlyTree()->isLeaf())
+      OS << "inline bool Predicate_" << PatFragRecord->getName()
+      << "(SDNode *N) {\n";
+    else {
+      std::string ClassName =
+        CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
+      const char *C2 = ClassName == "SDNode" ? "N" : "inN";
+      
+      OS << "inline bool Predicate_" << PatFragRecord->getName()
+         << "(SDNode *" << C2 << ") {\n";
+      if (ClassName != "SDNode")
+        OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
+    }
+    OS << Code << "\n}\n";
+  }
+  
+  OS << "\n\n";
+}
+
+
+//===----------------------------------------------------------------------===//
+// PatternCodeEmitter implementation.
+//
 class PatternCodeEmitter {
 private:
-  CodegenDAGPatterns &CGP;
+  CodeGenDAGPatterns &CGP;
 
   // Predicates.
   ListInit *Predicates;
@@ -224,6 +305,8 @@ private:
   std::map<std::string, std::string> VariableMap;
   // Node to operator mapping
   std::map<std::string, Record*> OperatorMap;
+  // Name of the folded node which produces a flag.
+  std::pair<std::string, unsigned> FoldedFlag;
   // Names of all the folded nodes which produce chains.
   std::vector<std::pair<std::string, unsigned> > FoldedChains;
   // Original input chain(s).
@@ -273,7 +356,7 @@ private:
     VTNo++;
   }
 public:
-  PatternCodeEmitter(CodegenDAGPatterns &cgp, ListInit *preds,
+  PatternCodeEmitter(CodeGenDAGPatterns &cgp, ListInit *preds,
                      TreePatternNode *pattern, TreePatternNode *instr,
                      std::vector<std::pair<unsigned, std::string> > &gc,
                      std::set<std::string> &gd,
@@ -454,7 +537,7 @@ public:
           emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
                     RootName + "1), " + itostr(II->getValue()) + ")");
           
-          EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
+          EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0), RootName,
                              ChainSuffix + utostr(0), FoundChain);
           return;
         }
@@ -465,7 +548,7 @@ public:
       emitInit("SDOperand " + RootName + utostr(OpNo) + " = " +
                RootName + ".getOperand(" +utostr(OpNo) + ");");
 
-      EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
+      EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo), RootName,
                          ChainSuffix + utostr(OpNo), FoundChain);
     }
 
@@ -497,7 +580,8 @@ public:
   }
 
   void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
-                          const std::string &RootName,
+                          const std::string &RootName, 
+                          const std::string &ParentRootName,
                           const std::string &ChainSuffix, bool &FoundChain) {
     if (!Child->isLeaf()) {
       // If it's not a leaf, recursively match.
@@ -505,8 +589,17 @@ public:
       emitCheck(RootName + ".getOpcode() == " +
                 CInfo.getEnumName());
       EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
-      if (NodeHasProperty(Child, SDNPHasChain, CGP))
+      bool HasChain = false;
+      if (NodeHasProperty(Child, SDNPHasChain, CGP)) {
+        HasChain = true;
         FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
+      }
+      if (NodeHasProperty(Child, SDNPOutFlag, CGP)) {
+        assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
+               "Pattern folded multiple nodes which produce flags?");
+        FoldedFlag = std::make_pair(RootName,
+                                    CInfo.getNumResults() + (unsigned)HasChain);
+      }
     } else {
       // If this child has a name associated with it, capture it in VarMap. If
       // we already saw this in the pattern, emit code to verify dagness.
@@ -553,7 +646,12 @@ public:
             emitCode("SDOperand " + ChainName + ";");
           }
           
-          std::string Code = Fn + "(N, ";
+          std::string Code = Fn + "(";
+          if (CP->hasAttribute(CPAttrParentAsRoot)) {
+            Code += ParentRootName + ", ";
+          } else {
+            Code += "N, ";
+          }
           if (CP->hasProperty(SDNPHasChain)) {
             std::string ParentName(RootName.begin(), RootName.end()-1);
             Code += ParentName + ", ";
@@ -613,7 +711,9 @@ public:
     std::vector<std::string> NodeOps;
     // This is something selected from the pattern we matched.
     if (!N->getName().empty()) {
-      std::string &Val = VariableMap[N->getName()];
+      const std::string &VarName = N->getName();
+      std::string Val = VariableMap[VarName];
+      bool ModifiedVal = false;
       assert(!Val.empty() &&
              "Variable referenced but not defined and not caught earlier!");
       if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
@@ -627,6 +727,7 @@ public:
       if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
         assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
         std::string CastType;
+        std::string TmpVar =  "Tmp" + utostr(ResNo);
         switch (N->getTypeNum(0)) {
         default:
           cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
@@ -638,56 +739,53 @@ public:
         case MVT::i32: CastType = "unsigned"; break;
         case MVT::i64: CastType = "uint64_t"; break;
         }
-        emitCode("SDOperand Tmp" + utostr(ResNo) + 
+        emitCode("SDOperand " + TmpVar + 
                  " = CurDAG->getTargetConstant(((" + CastType +
                  ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
                  getEnumName(N->getTypeNum(0)) + ");");
-        NodeOps.push_back("Tmp" + utostr(ResNo));
         // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
         // value if used multiple times by this pattern result.
-        Val = "Tmp"+utostr(ResNo);
+        Val = TmpVar;
+        ModifiedVal = true;
+        NodeOps.push_back(Val);
       } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
         Record *Op = OperatorMap[N->getName()];
         // Transform ExternalSymbol to TargetExternalSymbol
         if (Op && Op->getName() == "externalsym") {
-          emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
+          std::string TmpVar = "Tmp"+utostr(ResNo);
+          emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
                    "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
                    Val + ")->getSymbol(), " +
                    getEnumName(N->getTypeNum(0)) + ");");
-          NodeOps.push_back("Tmp" + utostr(ResNo));
           // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
           // this value if used multiple times by this pattern result.
-          Val = "Tmp"+utostr(ResNo);
-        } else {
-          NodeOps.push_back(Val);
+          Val = TmpVar;
+          ModifiedVal = true;
         }
+        NodeOps.push_back(Val);
       } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
                  || N->getOperator()->getName() == "tglobaltlsaddr")) {
         Record *Op = OperatorMap[N->getName()];
         // Transform GlobalAddress to TargetGlobalAddress
         if (Op && (Op->getName() == "globaladdr" ||
                    Op->getName() == "globaltlsaddr")) {
-          emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
+          std::string TmpVar = "Tmp" + utostr(ResNo);
+          emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
                    "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
                    ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
                    ");");
-          NodeOps.push_back("Tmp" + utostr(ResNo));
           // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
           // this value if used multiple times by this pattern result.
-          Val = "Tmp"+utostr(ResNo);
-        } else {
-          NodeOps.push_back(Val);
+          Val = TmpVar;
+          ModifiedVal = true;
         }
-      } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
         NodeOps.push_back(Val);
-        // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
-        // value if used multiple times by this pattern result.
-        Val = "Tmp"+utostr(ResNo);
-      } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
+      } else if (!N->isLeaf()
+                 && (N->getOperator()->getName() == "texternalsym"
+                      || N->getOperator()->getName() == "tconstpool")) {
+        // Do not rewrite the variable name, since we don't generate a new
+        // temporary.
         NodeOps.push_back(Val);
-        // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
-        // value if used multiple times by this pattern result.
-        Val = "Tmp"+utostr(ResNo);
       } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
         for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
           emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
@@ -705,6 +803,10 @@ public:
         }
         NodeOps.push_back(Val);
       }
+
+      if (ModifiedVal) {
+        VariableMap[VarName] = Val;
+      }
       return NodeOps;
     }
     if (N->isLeaf()) {
@@ -746,7 +848,7 @@ public:
       const CodeGenTarget &CGT = CGP.getTargetInfo();
       CodeGenInstruction &II = CGT.getInstruction(Op->getName());
       const DAGInstruction &Inst = CGP.getInstruction(Op);
-      TreePattern *InstPat = Inst.getPattern();
+      const TreePattern *InstPat = Inst.getPattern();
       // FIXME: Assume actual pattern comes before "implicit".
       TreePatternNode *InstPatNode =
         isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
@@ -754,7 +856,7 @@ public:
       if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
         InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
       }
-      bool HasVarOps     = isRoot && II.hasVariableNumberOfOperands;
+      bool HasVarOps     = isRoot && II.isVariadic;
       // FIXME: fix how we deal with physical register operands.
       bool HasImpInputs  = isRoot && Inst.getNumImpOperands() > 0;
       bool HasImpResults = isRoot && DstRegs.size() > 0;
@@ -1014,9 +1116,15 @@ public:
         }
 
         if (NodeHasOutFlag) {
-          emitCode("ReplaceUses(SDOperand(N.Val, " +
-                   utostr(NumPatResults + (unsigned)InputHasChain)
-                   +"), InFlag);");
+          if (FoldedFlag.first != "") {
+            emitCode("ReplaceUses(SDOperand(" + FoldedFlag.first + ".Val, " +
+                     utostr(FoldedFlag.second) + "), InFlag);");
+          } else {
+            assert(NodeHasProperty(Pattern, SDNPOutFlag, CGP));
+            emitCode("ReplaceUses(SDOperand(N.Val, " +
+                     utostr(NumPatResults + (unsigned)InputHasChain)
+                     +"), InFlag);");
+          }
           NeedReplace = true;
         }
 
@@ -1194,12 +1302,12 @@ private:
 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
 /// stream to match the pattern, and generate the code for the match if it
 /// succeeds.  Returns true if the pattern is not guaranteed to match.
-void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
+void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
                   std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
                                            std::set<std::string> &GeneratedDecl,
                                         std::vector<std::string> &TargetOpcodes,
                                           std::vector<std::string> &TargetVTs) {
-  PatternCodeEmitter Emitter(*CGP, Pattern.getPredicates(),
+  PatternCodeEmitter Emitter(CGP, Pattern.getPredicates(),
                              Pattern.getSrcPattern(), Pattern.getDstPattern(),
                              GeneratedCode, GeneratedDecl,
                              TargetOpcodes, TargetVTs);
@@ -1209,7 +1317,7 @@ void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
   Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
 
   // TP - Get *SOME* tree pattern, we don't care which.
-  TreePattern &TP = *CGP->pf_begin()->second;
+  TreePattern &TP = *CGP.pf_begin()->second;
   
   // At this point, we know that we structurally match the pattern, but the
   // types of the nodes may not match.  Figure out the fewest number of type 
@@ -1252,7 +1360,7 @@ void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
 /// EraseCodeLine - Erase one code line from all of the patterns.  If removing
 /// a line causes any of them to be empty, remove them and return true when
 /// done.
-static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*, 
+static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*, 
                           std::vector<std::pair<unsigned, std::string> > > >
                           &Patterns) {
   bool ErasedPatterns = false;
@@ -1269,13 +1377,13 @@ static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*,
 
 /// EmitPatterns - Emit code for at least one pattern, but try to group common
 /// code together between the patterns.
-void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*, 
+void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*, 
                               std::vector<std::pair<unsigned, std::string> > > >
                                   &Patterns, unsigned Indent,
                                   std::ostream &OS) {
   typedef std::pair<unsigned, std::string> CodeLine;
   typedef std::vector<CodeLine> CodeList;
-  typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
+  typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
   
   if (Patterns.empty()) return;
   
@@ -1295,7 +1403,7 @@ void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
     
     // FIXME: Emit braces?
     if (Shared.size() == 1) {
-      PatternToMatch &Pattern = *Shared.back().first;
+      const PatternToMatch &Pattern = *Shared.back().first;
       OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
       Pattern.getSrcPattern()->print(OS);
       OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
@@ -1303,11 +1411,11 @@ void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
       OS << "\n";
       unsigned AddedComplexity = Pattern.getAddedComplexity();
       OS << std::string(Indent, ' ') << "// Pattern complexity = "
-         << getPatternSize(Pattern.getSrcPattern(), *CGP) + AddedComplexity
+         << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
          << "  cost = "
-         << getResultPatternCost(Pattern.getDstPattern(), *CGP)
+         << getResultPatternCost(Pattern.getDstPattern(), CGP)
          << "  size = "
-         << getResultPatternSize(Pattern.getDstPattern(), *CGP) << "\n";
+         << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
     }
     if (FirstCodeLine.first != 1) {
       OS << std::string(Indent, ' ') << "{\n";
@@ -1320,7 +1428,7 @@ void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
     }
     
     if (Other.size() == 1) {
-      PatternToMatch &Pattern = *Other.back().first;
+      const PatternToMatch &Pattern = *Other.back().first;
       OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
       Pattern.getSrcPattern()->print(OS);
       OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
@@ -1328,11 +1436,11 @@ void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
       OS << "\n";
       unsigned AddedComplexity = Pattern.getAddedComplexity();
       OS << std::string(Indent, ' ') << "// Pattern complexity = "
-         << getPatternSize(Pattern.getSrcPattern(), *CGP) + AddedComplexity
+         << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
          << "  cost = "
-         << getResultPatternCost(Pattern.getDstPattern(), *CGP)
+         << getResultPatternCost(Pattern.getDstPattern(), CGP)
          << "  size = "
-         << getResultPatternSize(Pattern.getDstPattern(), *CGP) << "\n";
+         << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
     }
     EmitPatterns(Other, Indent, OS);
     return;
@@ -1380,7 +1488,7 @@ void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
     OS << std::string(Indent-2, ' ') << "}\n";
 }
 
-static std::string getOpcodeName(Record *Op, CodegenDAGPatterns &CGP) {
+static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
   return CGP.getSDNodeInfo(Op).getEnumName();
 }
 
@@ -1392,7 +1500,7 @@ static std::string getLegalCName(std::string OpName) {
 }
 
 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
-  const CodeGenTarget &Target = CGP->getTargetInfo();
+  const CodeGenTarget &Target = CGP.getTargetInfo();
   
   // Get the namespace to insert instructions into.  Make sure not to pick up
   // "TargetInstrInfo" by accidentally getting the namespace off the PHI
@@ -1408,27 +1516,27 @@ void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
   if (!InstNS.empty()) InstNS += "::";
   
   // Group the patterns by their top-level opcodes.
-  std::map<std::string, std::vector<PatternToMatch*> > PatternsByOpcode;
+  std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
   // All unique target node emission functions.
   std::map<std::string, unsigned> EmitFunctions;
-  for (CodegenDAGPatterns::ptm_iterator I = CGP->ptm_begin(),
-       E = CGP->ptm_end(); I != E; ++I) {
-    PatternToMatch &Pattern = *I;
+  for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
+       E = CGP.ptm_end(); I != E; ++I) {
+    const PatternToMatch &Pattern = *I;
 
     TreePatternNode *Node = Pattern.getSrcPattern();
     if (!Node->isLeaf()) {
-      PatternsByOpcode[getOpcodeName(Node->getOperator(), *CGP)].
+      PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
         push_back(&Pattern);
     } else {
       const ComplexPattern *CP;
       if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
-        PatternsByOpcode[getOpcodeName(CGP->getSDNodeNamed("imm"), *CGP)].
+        PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
           push_back(&Pattern);
-      } else if ((CP = NodeGetComplexPattern(Node, *CGP))) {
+      } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
         std::vector<Record*> OpNodes = CP->getRootNodes();
         for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
-          PatternsByOpcode[getOpcodeName(OpNodes[j], *CGP)]
-            .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], *CGP)].begin(),
+          PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
+            .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
                     &Pattern);
         }
       } else {
@@ -1449,45 +1557,46 @@ void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
   // Emit one Select_* method for each top-level opcode.  We do this instead of
   // emitting one giant switch statement to support compilers where this will
   // result in the recursive functions taking less stack space.
-  for (std::map<std::string, std::vector<PatternToMatch*> >::iterator
+  for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
          PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
        PBOI != E; ++PBOI) {
     const std::string &OpName = PBOI->first;
-    std::vector<PatternToMatch*> &PatternsOfOp = PBOI->second;
+    std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
     assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
 
     // We want to emit all of the matching code now.  However, we want to emit
     // the matches in order of minimal cost.  Sort the patterns so the least
     // cost one is at the start.
     std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
-                     PatternSortingPredicate(*CGP));
+                     PatternSortingPredicate(CGP));
 
     // Split them into groups by type.
-    std::map<MVT::ValueType, std::vector<PatternToMatch*> > PatternsByType;
+    std::map<MVT::ValueType, std::vector<const PatternToMatch*> >PatternsByType;
     for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
-      PatternToMatch *Pat = PatternsOfOp[i];
+      const PatternToMatch *Pat = PatternsOfOp[i];
       TreePatternNode *SrcPat = Pat->getSrcPattern();
       MVT::ValueType VT = SrcPat->getTypeNum(0);
-      std::map<MVT::ValueType, std::vector<PatternToMatch*> >::iterator TI = 
+      std::map<MVT::ValueType, 
+               std::vector<const PatternToMatch*> >::iterator TI = 
         PatternsByType.find(VT);
       if (TI != PatternsByType.end())
         TI->second.push_back(Pat);
       else {
-        std::vector<PatternToMatch*> PVec;
+        std::vector<const PatternToMatch*> PVec;
         PVec.push_back(Pat);
         PatternsByType.insert(std::make_pair(VT, PVec));
       }
     }
 
-    for (std::map<MVT::ValueType, std::vector<PatternToMatch*> >::iterator
+    for (std::map<MVT::ValueType, std::vector<const PatternToMatch*> >::iterator
            II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
          ++II) {
       MVT::ValueType OpVT = II->first;
-      std::vector<PatternToMatch*> &Patterns = II->second;
+      std::vector<const PatternToMatch*> &Patterns = II->second;
       typedef std::vector<std::pair<unsigned,std::string> > CodeList;
       typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
     
-      std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
+      std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
       std::vector<std::vector<std::string> > PatternOpcodes;
       std::vector<std::vector<std::string> > PatternVTs;
       std::vector<std::set<std::string> > PatternDecls;
@@ -1676,12 +1785,36 @@ void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
   OS << "SDNode *Select_LABEL(const SDOperand &N) {\n"
      << "  SDOperand Chain = N.getOperand(0);\n"
      << "  SDOperand N1 = N.getOperand(1);\n"
-     << "  unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
-     << "  SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
+     << "  SDOperand N2 = N.getOperand(2);\n"
+     << "  unsigned C1 = cast<ConstantSDNode>(N1)->getValue();\n"
+     << "  unsigned C2 = cast<ConstantSDNode>(N2)->getValue();\n"
+     << "  SDOperand Tmp1 = CurDAG->getTargetConstant(C1, MVT::i32);\n"
+     << "  SDOperand Tmp2 = CurDAG->getTargetConstant(C2, MVT::i32);\n"
      << "  AddToISelQueue(Chain);\n"
-     << "  SDOperand Ops[] = { Tmp, Chain };\n"
+     << "  SDOperand Ops[] = { Tmp1, Tmp2, Chain };\n"
      << "  return CurDAG->getTargetNode(TargetInstrInfo::LABEL,\n"
-     << "                               MVT::Other, Ops, 2);\n"
+     << "                               MVT::Other, Ops, 3);\n"
+     << "}\n\n";
+
+  OS << "SDNode *Select_DECLARE(const SDOperand &N) {\n"
+     << "  SDOperand Chain = N.getOperand(0);\n"
+     << "  SDOperand N1 = N.getOperand(1);\n"
+     << "  SDOperand N2 = N.getOperand(2);\n"
+     << "  if (!isa<FrameIndexSDNode>(N1) || !isa<GlobalAddressSDNode>(N2)) {\n"
+     << "    cerr << \"Cannot yet select llvm.dbg.declare: \";\n"
+     << "    N.Val->dump(CurDAG);\n"
+     << "    abort();\n"
+     << "  }\n"
+     << "  int FI = cast<FrameIndexSDNode>(N1)->getIndex();\n"
+     << "  GlobalValue *GV = cast<GlobalAddressSDNode>(N2)->getGlobal();\n"
+     << "  SDOperand Tmp1 = "
+     << "CurDAG->getTargetFrameIndex(FI, TLI.getPointerTy());\n"
+     << "  SDOperand Tmp2 = "
+     << "CurDAG->getTargetGlobalAddress(GV, TLI.getPointerTy());\n"
+     << "  AddToISelQueue(Chain);\n"
+     << "  SDOperand Ops[] = { Tmp1, Tmp2, Chain };\n"
+     << "  return CurDAG->getTargetNode(TargetInstrInfo::DECLARE,\n"
+     << "                               MVT::Other, Ops, 3);\n"
      << "}\n\n";
 
   OS << "SDNode *Select_EXTRACT_SUBREG(const SDOperand &N) {\n"
@@ -1751,13 +1884,14 @@ void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
      << "  }\n"
      << "  case ISD::INLINEASM: return Select_INLINEASM(N);\n"
      << "  case ISD::LABEL: return Select_LABEL(N);\n"
+     << "  case ISD::DECLARE: return Select_DECLARE(N);\n"
      << "  case ISD::EXTRACT_SUBREG: return Select_EXTRACT_SUBREG(N);\n"
      << "  case ISD::INSERT_SUBREG:  return Select_INSERT_SUBREG(N);\n";
 
     
   // Loop over all of the case statements, emiting a call to each method we
   // emitted above.
-  for (std::map<std::string, std::vector<PatternToMatch*> >::iterator
+  for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
          PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
        PBOI != E; ++PBOI) {
     const std::string &OpName = PBOI->first;
@@ -1825,24 +1959,20 @@ void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
 }
 
 void DAGISelEmitter::run(std::ostream &OS) {
-  CodeGenTarget Target;
-  EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
-                       " target", OS);
+  EmitSourceFileHeader("DAG Instruction Selector for the " +
+                       CGP.getTargetInfo().getName() + " target", OS);
   
   OS << "// *** NOTE: This file is #included into the middle of the target\n"
      << "// *** instruction selector class.  These functions are really "
      << "methods.\n\n";
   
-  OS << "#include \"llvm/Support/Compiler.h\"\n";
-
   OS << "// Instruction selector priority queue:\n"
      << "std::vector<SDNode*> ISelQueue;\n";
   OS << "/// Keep track of nodes which have already been added to queue.\n"
      << "unsigned char *ISelQueued;\n";
   OS << "/// Keep track of nodes which have already been selected.\n"
      << "unsigned char *ISelSelected;\n";
-  OS << "/// Dummy parameter to ReplaceAllUsesOfValueWith().\n"
-     << "std::vector<SDNode*> ISelKilled;\n\n";
+
 
   OS << "/// IsChainCompatible - Returns true if Chain is Op or Chain does\n";
   OS << "/// not reach Op.\n";
@@ -1890,37 +2020,52 @@ void DAGISelEmitter::run(std::ostream &OS) {
   OS << "  }\n";
   OS << "}\n\n";
 
-  OS << "inline void RemoveKilled() {\n";
-OS << "  unsigned NumKilled = ISelKilled.size();\n";
-  OS << "  if (NumKilled) {\n";
-  OS << "    for (unsigned i = 0; i != NumKilled; ++i) {\n";
-  OS << "      SDNode *Temp = ISelKilled[i];\n";
-  OS << "      ISelQueue.erase(std::remove(ISelQueue.begin(), ISelQueue.end(), "
-     << "Temp), ISelQueue.end());\n";
-  OS << "    };\n";
- OS << "    std::make_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
-  OS << "    ISelKilled.clear();\n";
-  OS << "  }\n";
+  
+  OS << "class VISIBILITY_HIDDEN ISelQueueUpdater :\n";
+  OS << "  public SelectionDAG::DAGUpdateListener {\n";
+  OS << "    std::vector<SDNode*> &ISelQueue;\n";
+  OS << "    bool HadDelete;\n";
+  OS << "  public:\n";
+  OS << "    ISelQueueUpdater(std::vector<SDNode*> &isq)\n";
+  OS << "      : ISelQueue(isq), HadDelete(false) {}\n";
+  OS << "    \n";
+  OS << "    bool hadDelete() const { return HadDelete; }\n";
+  OS << "    \n";
+  OS << "    virtual void NodeDeleted(SDNode *N) {\n";
+  OS << "      ISelQueue.erase(std::remove(ISelQueue.begin(), ISelQueue.end(),";
+  OS << " N),\n                      ISelQueue.end());\n";
+  OS << "      HadDelete = true;\n";
+  OS << "    }\n";
+  OS << "    \n";
+  OS << "    // Ignore updates.\n";
+  OS << "    virtual void NodeUpdated(SDNode *N) {}\n";
+  OS << "  };\n";
+  
+  OS << "inline void UpdateQueue(const ISelQueueUpdater &ISQU) {\n";
+  OS << "  if (ISQU.hadDelete())\n";
+  OS << "    std::make_heap(ISelQueue.begin(), ISelQueue.end(),isel_sort());\n";
   OS << "}\n\n";
 
   OS << "void ReplaceUses(SDOperand F, SDOperand T) DISABLE_INLINE {\n";
-  OS << "  CurDAG->ReplaceAllUsesOfValueWith(F, T, &ISelKilled);\n";
+  OS << "  ISelQueueUpdater ISQU(ISelQueue);\n";
+  OS << "  CurDAG->ReplaceAllUsesOfValueWith(F, T, &ISQU);\n";
   OS << "  setSelected(F.Val->getNodeId());\n";
-  OS << "  RemoveKilled();\n";
+  OS << "  UpdateQueue(ISQU);\n";
   OS << "}\n";
   OS << "void ReplaceUses(SDNode *F, SDNode *T) DISABLE_INLINE {\n";
   OS << "  unsigned FNumVals = F->getNumValues();\n";
   OS << "  unsigned TNumVals = T->getNumValues();\n";
+  OS << "  ISelQueueUpdater ISQU(ISelQueue);\n";
   OS << "  if (FNumVals != TNumVals) {\n";
   OS << "    for (unsigned i = 0, e = std::min(FNumVals, TNumVals); "
      << "i < e; ++i)\n";
   OS << "      CurDAG->ReplaceAllUsesOfValueWith(SDOperand(F, i), "
-     << "SDOperand(T, i), &ISelKilled);\n";
+     << "SDOperand(T, i), &ISQU);\n";
   OS << "  } else {\n";
-  OS << "    CurDAG->ReplaceAllUsesWith(F, T, &ISelKilled);\n";
+  OS << "    CurDAG->ReplaceAllUsesWith(F, T, &ISQU);\n";
   OS << "  }\n";
   OS << "  setSelected(F->getNodeId());\n";
-  OS << "  RemoveKilled();\n";
+  OS << "  UpdateQueue(ISQU);\n";
   OS << "}\n\n";
 
   OS << "// SelectRoot - Top level entry to DAG isel.\n";
@@ -1947,8 +2092,9 @@ OS << "  unsigned NumKilled = ISelKilled.size();\n";
   OS << "        if (ResNode)\n";
   OS << "          ReplaceUses(Node, ResNode);\n";
   OS << "        if (Node->use_empty()) { // Don't delete EntryToken, etc.\n";
-  OS << "          CurDAG->RemoveDeadNode(Node, ISelKilled);\n";
-  OS << "          RemoveKilled();\n";
+  OS << "          ISelQueueUpdater ISQU(ISelQueue);\n";
+  OS << "          CurDAG->RemoveDeadNode(Node, &ISQU);\n";
+  OS << "          UpdateQueue(ISQU);\n";
   OS << "        }\n";
   OS << "      }\n";
   OS << "    }\n";
@@ -1961,12 +2107,11 @@ OS << "  unsigned NumKilled = ISelKilled.size();\n";
   OS << "  return Dummy.getValue();\n";
   OS << "}\n";
   
-  CodegenDAGPatterns CGP(Records, OS);
-
-  this->CGP = &CGP;
+  EmitNodeTransforms(OS);
+  EmitPredicateFunctions(OS);
   
   DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
-  for (CodegenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
+  for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
        I != E; ++I) {
     DOUT << "PATTERN: ";   DEBUG(I->getSrcPattern()->dump());
     DOUT << "\nRESULT:  "; DEBUG(I->getDstPattern()->dump());