Create a new class, MemOperand, for describing memory references
[oota-llvm.git] / utils / TableGen / DAGISelEmitter.cpp
1 //===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This tablegen backend emits a DAG instruction selector.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "DAGISelEmitter.h"
15 #include "Record.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/MathExtras.h"
19 #include "llvm/Support/Streams.h"
20 #include <algorithm>
21 using namespace llvm;
22
23 //===----------------------------------------------------------------------===//
24 // DAGISelEmitter Helper methods
25 //
26
27 /// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
28 /// ComplexPattern.
29 static bool NodeIsComplexPattern(TreePatternNode *N) {
30   return (N->isLeaf() &&
31           dynamic_cast<DefInit*>(N->getLeafValue()) &&
32           static_cast<DefInit*>(N->getLeafValue())->getDef()->
33           isSubClassOf("ComplexPattern"));
34 }
35
36 /// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
37 /// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
38 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
39                                                    CodeGenDAGPatterns &CGP) {
40   if (N->isLeaf() &&
41       dynamic_cast<DefInit*>(N->getLeafValue()) &&
42       static_cast<DefInit*>(N->getLeafValue())->getDef()->
43       isSubClassOf("ComplexPattern")) {
44     return &CGP.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
45                                        ->getDef());
46   }
47   return NULL;
48 }
49
50 /// getPatternSize - Return the 'size' of this pattern.  We want to match large
51 /// patterns before small ones.  This is used to determine the size of a
52 /// pattern.
53 static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
54   assert((MVT::isExtIntegerInVTs(P->getExtTypes()) || 
55           MVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
56           P->getExtTypeNum(0) == MVT::isVoid ||
57           P->getExtTypeNum(0) == MVT::Flag ||
58           P->getExtTypeNum(0) == MVT::iPTR) && 
59          "Not a valid pattern node to size!");
60   unsigned Size = 3;  // The node itself.
61   // If the root node is a ConstantSDNode, increases its size.
62   // e.g. (set R32:$dst, 0).
63   if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
64     Size += 2;
65
66   // FIXME: This is a hack to statically increase the priority of patterns
67   // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
68   // Later we can allow complexity / cost for each pattern to be (optionally)
69   // specified. To get best possible pattern match we'll need to dynamically
70   // calculate the complexity of all patterns a dag can potentially map to.
71   const ComplexPattern *AM = NodeGetComplexPattern(P, CGP);
72   if (AM)
73     Size += AM->getNumOperands() * 3;
74
75   // If this node has some predicate function that must match, it adds to the
76   // complexity of this node.
77   if (!P->getPredicateFn().empty())
78     ++Size;
79   
80   // Count children in the count if they are also nodes.
81   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
82     TreePatternNode *Child = P->getChild(i);
83     if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
84       Size += getPatternSize(Child, CGP);
85     else if (Child->isLeaf()) {
86       if (dynamic_cast<IntInit*>(Child->getLeafValue())) 
87         Size += 5;  // Matches a ConstantSDNode (+3) and a specific value (+2).
88       else if (NodeIsComplexPattern(Child))
89         Size += getPatternSize(Child, CGP);
90       else if (!Child->getPredicateFn().empty())
91         ++Size;
92     }
93   }
94   
95   return Size;
96 }
97
98 /// getResultPatternCost - Compute the number of instructions for this pattern.
99 /// This is a temporary hack.  We should really include the instruction
100 /// latencies in this calculation.
101 static unsigned getResultPatternCost(TreePatternNode *P,
102                                      CodeGenDAGPatterns &CGP) {
103   if (P->isLeaf()) return 0;
104   
105   unsigned Cost = 0;
106   Record *Op = P->getOperator();
107   if (Op->isSubClassOf("Instruction")) {
108     Cost++;
109     CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
110     if (II.usesCustomDAGSchedInserter)
111       Cost += 10;
112   }
113   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
114     Cost += getResultPatternCost(P->getChild(i), CGP);
115   return Cost;
116 }
117
118 /// getResultPatternCodeSize - Compute the code size of instructions for this
119 /// pattern.
120 static unsigned getResultPatternSize(TreePatternNode *P, 
121                                      CodeGenDAGPatterns &CGP) {
122   if (P->isLeaf()) return 0;
123
124   unsigned Cost = 0;
125   Record *Op = P->getOperator();
126   if (Op->isSubClassOf("Instruction")) {
127     Cost += Op->getValueAsInt("CodeSize");
128   }
129   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
130     Cost += getResultPatternSize(P->getChild(i), CGP);
131   return Cost;
132 }
133
134 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
135 // In particular, we want to match maximal patterns first and lowest cost within
136 // a particular complexity first.
137 struct PatternSortingPredicate {
138   PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
139   CodeGenDAGPatterns &CGP;
140
141   bool operator()(const PatternToMatch *LHS,
142                   const PatternToMatch *RHS) {
143     unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
144     unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
145     LHSSize += LHS->getAddedComplexity();
146     RHSSize += RHS->getAddedComplexity();
147     if (LHSSize > RHSSize) return true;   // LHS -> bigger -> less cost
148     if (LHSSize < RHSSize) return false;
149     
150     // If the patterns have equal complexity, compare generated instruction cost
151     unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
152     unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
153     if (LHSCost < RHSCost) return true;
154     if (LHSCost > RHSCost) return false;
155
156     return getResultPatternSize(LHS->getDstPattern(), CGP) <
157       getResultPatternSize(RHS->getDstPattern(), CGP);
158   }
159 };
160
161 /// getRegisterValueType - Look up and return the first ValueType of specified 
162 /// RegisterClass record
163 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
164   if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
165     return RC->getValueTypeNum(0);
166   return MVT::Other;
167 }
168
169
170 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
171 /// type information from it.
172 static void RemoveAllTypes(TreePatternNode *N) {
173   N->removeTypes();
174   if (!N->isLeaf())
175     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
176       RemoveAllTypes(N->getChild(i));
177 }
178
179 /// NodeHasProperty - return true if TreePatternNode has the specified
180 /// property.
181 static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
182                             CodeGenDAGPatterns &CGP) {
183   if (N->isLeaf()) {
184     const ComplexPattern *CP = NodeGetComplexPattern(N, CGP);
185     if (CP)
186       return CP->hasProperty(Property);
187     return false;
188   }
189   Record *Operator = N->getOperator();
190   if (!Operator->isSubClassOf("SDNode")) return false;
191
192   return CGP.getSDNodeInfo(Operator).hasProperty(Property);
193 }
194
195 static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
196                                CodeGenDAGPatterns &CGP) {
197   if (NodeHasProperty(N, Property, CGP))
198     return true;
199
200   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
201     TreePatternNode *Child = N->getChild(i);
202     if (PatternHasProperty(Child, Property, CGP))
203       return true;
204   }
205
206   return false;
207 }
208
209 //===----------------------------------------------------------------------===//
210 // Node Transformation emitter implementation.
211 //
212 void DAGISelEmitter::EmitNodeTransforms(std::ostream &OS) {
213   // Walk the pattern fragments, adding them to a map, which sorts them by
214   // name.
215   typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
216   NXsByNameTy NXsByName;
217
218   for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
219        I != E; ++I)
220     NXsByName.insert(std::make_pair(I->first->getName(), I->second));
221   
222   OS << "\n// Node transformations.\n";
223   
224   for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
225        I != E; ++I) {
226     Record *SDNode = I->second.first;
227     std::string Code = I->second.second;
228     
229     if (Code.empty()) continue;  // Empty code?  Skip it.
230     
231     std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
232     const char *C2 = ClassName == "SDNode" ? "N" : "inN";
233     
234     OS << "inline SDOperand Transform_" << I->first << "(SDNode *" << C2
235        << ") {\n";
236     if (ClassName != "SDNode")
237       OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
238     OS << Code << "\n}\n";
239   }
240 }
241
242 //===----------------------------------------------------------------------===//
243 // Predicate emitter implementation.
244 //
245
246 void DAGISelEmitter::EmitPredicateFunctions(std::ostream &OS) {
247   OS << "\n// Predicate functions.\n";
248
249   // Walk the pattern fragments, adding them to a map, which sorts them by
250   // name.
251   typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
252   PFsByNameTy PFsByName;
253
254   for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
255        I != E; ++I)
256     PFsByName.insert(std::make_pair(I->first->getName(), *I));
257
258   
259   for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
260        I != E; ++I) {
261     Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
262     TreePattern *P = I->second.second;
263     
264     // If there is a code init for this fragment, emit the predicate code.
265     std::string Code = PatFragRecord->getValueAsCode("Predicate");
266     if (Code.empty()) continue;
267     
268     if (P->getOnlyTree()->isLeaf())
269       OS << "inline bool Predicate_" << PatFragRecord->getName()
270       << "(SDNode *N) {\n";
271     else {
272       std::string ClassName =
273         CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
274       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
275       
276       OS << "inline bool Predicate_" << PatFragRecord->getName()
277          << "(SDNode *" << C2 << ") {\n";
278       if (ClassName != "SDNode")
279         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
280     }
281     OS << Code << "\n}\n";
282   }
283   
284   OS << "\n\n";
285 }
286
287
288 //===----------------------------------------------------------------------===//
289 // PatternCodeEmitter implementation.
290 //
291 class PatternCodeEmitter {
292 private:
293   CodeGenDAGPatterns &CGP;
294
295   // Predicates.
296   ListInit *Predicates;
297   // Pattern cost.
298   unsigned Cost;
299   // Instruction selector pattern.
300   TreePatternNode *Pattern;
301   // Matched instruction.
302   TreePatternNode *Instruction;
303   
304   // Node to name mapping
305   std::map<std::string, std::string> VariableMap;
306   // Node to operator mapping
307   std::map<std::string, Record*> OperatorMap;
308   // Names of all the folded nodes which produce chains.
309   std::vector<std::pair<std::string, unsigned> > FoldedChains;
310   // Original input chain(s).
311   std::vector<std::pair<std::string, std::string> > OrigChains;
312   std::set<std::string> Duplicates;
313
314   /// LSI - Load/Store information.
315   /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
316   /// for each memory access. This facilitates the use of AliasAnalysis in
317   /// the backend.
318   std::vector<std::string> LSI;
319
320   /// GeneratedCode - This is the buffer that we emit code to.  The first int
321   /// indicates whether this is an exit predicate (something that should be
322   /// tested, and if true, the match fails) [when 1], or normal code to emit
323   /// [when 0], or initialization code to emit [when 2].
324   std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
325   /// GeneratedDecl - This is the set of all SDOperand declarations needed for
326   /// the set of patterns for each top-level opcode.
327   std::set<std::string> &GeneratedDecl;
328   /// TargetOpcodes - The target specific opcodes used by the resulting
329   /// instructions.
330   std::vector<std::string> &TargetOpcodes;
331   std::vector<std::string> &TargetVTs;
332
333   std::string ChainName;
334   unsigned TmpNo;
335   unsigned OpcNo;
336   unsigned VTNo;
337   
338   void emitCheck(const std::string &S) {
339     if (!S.empty())
340       GeneratedCode.push_back(std::make_pair(1, S));
341   }
342   void emitCode(const std::string &S) {
343     if (!S.empty())
344       GeneratedCode.push_back(std::make_pair(0, S));
345   }
346   void emitInit(const std::string &S) {
347     if (!S.empty())
348       GeneratedCode.push_back(std::make_pair(2, S));
349   }
350   void emitDecl(const std::string &S) {
351     assert(!S.empty() && "Invalid declaration");
352     GeneratedDecl.insert(S);
353   }
354   void emitOpcode(const std::string &Opc) {
355     TargetOpcodes.push_back(Opc);
356     OpcNo++;
357   }
358   void emitVT(const std::string &VT) {
359     TargetVTs.push_back(VT);
360     VTNo++;
361   }
362 public:
363   PatternCodeEmitter(CodeGenDAGPatterns &cgp, ListInit *preds,
364                      TreePatternNode *pattern, TreePatternNode *instr,
365                      std::vector<std::pair<unsigned, std::string> > &gc,
366                      std::set<std::string> &gd,
367                      std::vector<std::string> &to,
368                      std::vector<std::string> &tv)
369   : CGP(cgp), Predicates(preds), Pattern(pattern), Instruction(instr),
370     GeneratedCode(gc), GeneratedDecl(gd),
371     TargetOpcodes(to), TargetVTs(tv),
372     TmpNo(0), OpcNo(0), VTNo(0) {}
373
374   /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
375   /// if the match fails. At this point, we already know that the opcode for N
376   /// matches, and the SDNode for the result has the RootName specified name.
377   void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
378                      const std::string &RootName, const std::string &ChainSuffix,
379                      bool &FoundChain) {
380
381     // Save loads/stores matched by a pattern.
382     if (!N->isLeaf() && N->getName().empty() &&
383         ((N->getOperator()->getName() == "ld") ||
384           (N->getOperator()->getName() == "st") ||
385           (N->getOperator()->getName() == "ist"))) {
386       LSI.push_back(RootName);
387     }
388
389     bool isRoot = (P == NULL);
390     // Emit instruction predicates. Each predicate is just a string for now.
391     if (isRoot) {
392       std::string PredicateCheck;
393       for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
394         if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
395           Record *Def = Pred->getDef();
396           if (!Def->isSubClassOf("Predicate")) {
397 #ifndef NDEBUG
398             Def->dump();
399 #endif
400             assert(0 && "Unknown predicate type!");
401           }
402           if (!PredicateCheck.empty())
403             PredicateCheck += " && ";
404           PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
405         }
406       }
407       
408       emitCheck(PredicateCheck);
409     }
410
411     if (N->isLeaf()) {
412       if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
413         emitCheck("cast<ConstantSDNode>(" + RootName +
414                   ")->getSignExtended() == " + itostr(II->getValue()));
415         return;
416       } else if (!NodeIsComplexPattern(N)) {
417         assert(0 && "Cannot match this as a leaf value!");
418         abort();
419       }
420     }
421   
422     // If this node has a name associated with it, capture it in VariableMap. If
423     // we already saw this in the pattern, emit code to verify dagness.
424     if (!N->getName().empty()) {
425       std::string &VarMapEntry = VariableMap[N->getName()];
426       if (VarMapEntry.empty()) {
427         VarMapEntry = RootName;
428       } else {
429         // If we get here, this is a second reference to a specific name.  Since
430         // we already have checked that the first reference is valid, we don't
431         // have to recursively match it, just check that it's the same as the
432         // previously named thing.
433         emitCheck(VarMapEntry + " == " + RootName);
434         return;
435       }
436
437       if (!N->isLeaf())
438         OperatorMap[N->getName()] = N->getOperator();
439     }
440
441
442     // Emit code to load the child nodes and match their contents recursively.
443     unsigned OpNo = 0;
444     bool NodeHasChain = NodeHasProperty   (N, SDNPHasChain, CGP);
445     bool HasChain     = PatternHasProperty(N, SDNPHasChain, CGP);
446     bool EmittedUseCheck = false;
447     if (HasChain) {
448       if (NodeHasChain)
449         OpNo = 1;
450       if (!isRoot) {
451         // Multiple uses of actual result?
452         emitCheck(RootName + ".hasOneUse()");
453         EmittedUseCheck = true;
454         if (NodeHasChain) {
455           // If the immediate use can somehow reach this node through another
456           // path, then can't fold it either or it will create a cycle.
457           // e.g. In the following diagram, XX can reach ld through YY. If
458           // ld is folded into XX, then YY is both a predecessor and a successor
459           // of XX.
460           //
461           //         [ld]
462           //         ^  ^
463           //         |  |
464           //        /   \---
465           //      /        [YY]
466           //      |         ^
467           //     [XX]-------|
468           bool NeedCheck = false;
469           if (P != Pattern)
470             NeedCheck = true;
471           else {
472             const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
473             NeedCheck =
474               P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
475               P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
476               P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
477               PInfo.getNumOperands() > 1 ||
478               PInfo.hasProperty(SDNPHasChain) ||
479               PInfo.hasProperty(SDNPInFlag) ||
480               PInfo.hasProperty(SDNPOptInFlag);
481           }
482
483           if (NeedCheck) {
484             std::string ParentName(RootName.begin(), RootName.end()-1);
485             emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
486                       ".Val, N.Val)");
487           }
488         }
489       }
490
491       if (NodeHasChain) {
492         if (FoundChain) {
493           emitCheck("(" + ChainName + ".Val == " + RootName + ".Val || "
494                     "IsChainCompatible(" + ChainName + ".Val, " +
495                     RootName + ".Val))");
496           OrigChains.push_back(std::make_pair(ChainName, RootName));
497         } else
498           FoundChain = true;
499         ChainName = "Chain" + ChainSuffix;
500         emitInit("SDOperand " + ChainName + " = " + RootName +
501                  ".getOperand(0);");
502       }
503     }
504
505     // Don't fold any node which reads or writes a flag and has multiple uses.
506     // FIXME: We really need to separate the concepts of flag and "glue". Those
507     // real flag results, e.g. X86CMP output, can have multiple uses.
508     // FIXME: If the optional incoming flag does not exist. Then it is ok to
509     // fold it.
510     if (!isRoot &&
511         (PatternHasProperty(N, SDNPInFlag, CGP) ||
512          PatternHasProperty(N, SDNPOptInFlag, CGP) ||
513          PatternHasProperty(N, SDNPOutFlag, CGP))) {
514       if (!EmittedUseCheck) {
515         // Multiple uses of actual result?
516         emitCheck(RootName + ".hasOneUse()");
517       }
518     }
519
520     // If there is a node predicate for this, emit the call.
521     if (!N->getPredicateFn().empty())
522       emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
523
524     
525     // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
526     // a constant without a predicate fn that has more that one bit set, handle
527     // this as a special case.  This is usually for targets that have special
528     // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
529     // handling stuff).  Using these instructions is often far more efficient
530     // than materializing the constant.  Unfortunately, both the instcombiner
531     // and the dag combiner can often infer that bits are dead, and thus drop
532     // them from the mask in the dag.  For example, it might turn 'AND X, 255'
533     // into 'AND X, 254' if it knows the low bit is set.  Emit code that checks
534     // to handle this.
535     if (!N->isLeaf() && 
536         (N->getOperator()->getName() == "and" || 
537          N->getOperator()->getName() == "or") &&
538         N->getChild(1)->isLeaf() &&
539         N->getChild(1)->getPredicateFn().empty()) {
540       if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
541         if (!isPowerOf2_32(II->getValue())) {  // Don't bother with single bits.
542           emitInit("SDOperand " + RootName + "0" + " = " +
543                    RootName + ".getOperand(" + utostr(0) + ");");
544           emitInit("SDOperand " + RootName + "1" + " = " +
545                    RootName + ".getOperand(" + utostr(1) + ");");
546
547           emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
548           const char *MaskPredicate = N->getOperator()->getName() == "or"
549             ? "CheckOrMask(" : "CheckAndMask(";
550           emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
551                     RootName + "1), " + itostr(II->getValue()) + ")");
552           
553           EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
554                              ChainSuffix + utostr(0), FoundChain);
555           return;
556         }
557       }
558     }
559     
560     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
561       emitInit("SDOperand " + RootName + utostr(OpNo) + " = " +
562                RootName + ".getOperand(" +utostr(OpNo) + ");");
563
564       EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
565                          ChainSuffix + utostr(OpNo), FoundChain);
566     }
567
568     // Handle cases when root is a complex pattern.
569     const ComplexPattern *CP;
570     if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
571       std::string Fn = CP->getSelectFunc();
572       unsigned NumOps = CP->getNumOperands();
573       for (unsigned i = 0; i < NumOps; ++i) {
574         emitDecl("CPTmp" + utostr(i));
575         emitCode("SDOperand CPTmp" + utostr(i) + ";");
576       }
577       if (CP->hasProperty(SDNPHasChain)) {
578         emitDecl("CPInChain");
579         emitDecl("Chain" + ChainSuffix);
580         emitCode("SDOperand CPInChain;");
581         emitCode("SDOperand Chain" + ChainSuffix + ";");
582       }
583
584       std::string Code = Fn + "(" + RootName + ", " + RootName;
585       for (unsigned i = 0; i < NumOps; i++)
586         Code += ", CPTmp" + utostr(i);
587       if (CP->hasProperty(SDNPHasChain)) {
588         ChainName = "Chain" + ChainSuffix;
589         Code += ", CPInChain, Chain" + ChainSuffix;
590       }
591       emitCheck(Code + ")");
592     }
593   }
594
595   void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
596                           const std::string &RootName,
597                           const std::string &ChainSuffix, bool &FoundChain) {
598     if (!Child->isLeaf()) {
599       // If it's not a leaf, recursively match.
600       const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
601       emitCheck(RootName + ".getOpcode() == " +
602                 CInfo.getEnumName());
603       EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
604       if (NodeHasProperty(Child, SDNPHasChain, CGP))
605         FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
606     } else {
607       // If this child has a name associated with it, capture it in VarMap. If
608       // we already saw this in the pattern, emit code to verify dagness.
609       if (!Child->getName().empty()) {
610         std::string &VarMapEntry = VariableMap[Child->getName()];
611         if (VarMapEntry.empty()) {
612           VarMapEntry = RootName;
613         } else {
614           // If we get here, this is a second reference to a specific name.
615           // Since we already have checked that the first reference is valid,
616           // we don't have to recursively match it, just check that it's the
617           // same as the previously named thing.
618           emitCheck(VarMapEntry + " == " + RootName);
619           Duplicates.insert(RootName);
620           return;
621         }
622       }
623       
624       // Handle leaves of various types.
625       if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
626         Record *LeafRec = DI->getDef();
627         if (LeafRec->isSubClassOf("RegisterClass") || 
628             LeafRec->getName() == "ptr_rc") {
629           // Handle register references.  Nothing to do here.
630         } else if (LeafRec->isSubClassOf("Register")) {
631           // Handle register references.
632         } else if (LeafRec->isSubClassOf("ComplexPattern")) {
633           // Handle complex pattern.
634           const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
635           std::string Fn = CP->getSelectFunc();
636           unsigned NumOps = CP->getNumOperands();
637           for (unsigned i = 0; i < NumOps; ++i) {
638             emitDecl("CPTmp" + utostr(i));
639             emitCode("SDOperand CPTmp" + utostr(i) + ";");
640           }
641           if (CP->hasProperty(SDNPHasChain)) {
642             const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
643             FoldedChains.push_back(std::make_pair("CPInChain",
644                                                   PInfo.getNumResults()));
645             ChainName = "Chain" + ChainSuffix;
646             emitDecl("CPInChain");
647             emitDecl(ChainName);
648             emitCode("SDOperand CPInChain;");
649             emitCode("SDOperand " + ChainName + ";");
650           }
651           
652           std::string Code = Fn + "(N, ";
653           if (CP->hasProperty(SDNPHasChain)) {
654             std::string ParentName(RootName.begin(), RootName.end()-1);
655             Code += ParentName + ", ";
656           }
657           Code += RootName;
658           for (unsigned i = 0; i < NumOps; i++)
659             Code += ", CPTmp" + utostr(i);
660           if (CP->hasProperty(SDNPHasChain))
661             Code += ", CPInChain, Chain" + ChainSuffix;
662           emitCheck(Code + ")");
663         } else if (LeafRec->getName() == "srcvalue") {
664           // Place holder for SRCVALUE nodes. Nothing to do here.
665         } else if (LeafRec->isSubClassOf("ValueType")) {
666           // Make sure this is the specified value type.
667           emitCheck("cast<VTSDNode>(" + RootName +
668                     ")->getVT() == MVT::" + LeafRec->getName());
669         } else if (LeafRec->isSubClassOf("CondCode")) {
670           // Make sure this is the specified cond code.
671           emitCheck("cast<CondCodeSDNode>(" + RootName +
672                     ")->get() == ISD::" + LeafRec->getName());
673         } else {
674 #ifndef NDEBUG
675           Child->dump();
676           cerr << " ";
677 #endif
678           assert(0 && "Unknown leaf type!");
679         }
680         
681         // If there is a node predicate for this, emit the call.
682         if (!Child->getPredicateFn().empty())
683           emitCheck(Child->getPredicateFn() + "(" + RootName +
684                     ".Val)");
685       } else if (IntInit *II =
686                  dynamic_cast<IntInit*>(Child->getLeafValue())) {
687         emitCheck("isa<ConstantSDNode>(" + RootName + ")");
688         unsigned CTmp = TmpNo++;
689         emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
690                  RootName + ")->getSignExtended();");
691         
692         emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
693       } else {
694 #ifndef NDEBUG
695         Child->dump();
696 #endif
697         assert(0 && "Unknown leaf type!");
698       }
699     }
700   }
701
702   /// EmitResultCode - Emit the action for a pattern.  Now that it has matched
703   /// we actually have to build a DAG!
704   std::vector<std::string>
705   EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
706                  bool InFlagDecled, bool ResNodeDecled,
707                  bool LikeLeaf = false, bool isRoot = false) {
708     // List of arguments of getTargetNode() or SelectNodeTo().
709     std::vector<std::string> NodeOps;
710     // This is something selected from the pattern we matched.
711     if (!N->getName().empty()) {
712       const std::string &VarName = N->getName();
713       std::string Val = VariableMap[VarName];
714       bool ModifiedVal = false;
715       assert(!Val.empty() &&
716              "Variable referenced but not defined and not caught earlier!");
717       if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
718         // Already selected this operand, just return the tmpval.
719         NodeOps.push_back(Val);
720         return NodeOps;
721       }
722
723       const ComplexPattern *CP;
724       unsigned ResNo = TmpNo++;
725       if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
726         assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
727         std::string CastType;
728         std::string TmpVar =  "Tmp" + utostr(ResNo);
729         switch (N->getTypeNum(0)) {
730         default:
731           cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
732                << " type as an immediate constant. Aborting\n";
733           abort();
734         case MVT::i1:  CastType = "bool"; break;
735         case MVT::i8:  CastType = "unsigned char"; break;
736         case MVT::i16: CastType = "unsigned short"; break;
737         case MVT::i32: CastType = "unsigned"; break;
738         case MVT::i64: CastType = "uint64_t"; break;
739         }
740         emitCode("SDOperand " + TmpVar + 
741                  " = CurDAG->getTargetConstant(((" + CastType +
742                  ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
743                  getEnumName(N->getTypeNum(0)) + ");");
744         // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
745         // value if used multiple times by this pattern result.
746         Val = TmpVar;
747         ModifiedVal = true;
748         NodeOps.push_back(Val);
749       } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
750         Record *Op = OperatorMap[N->getName()];
751         // Transform ExternalSymbol to TargetExternalSymbol
752         if (Op && Op->getName() == "externalsym") {
753           std::string TmpVar = "Tmp"+utostr(ResNo);
754           emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
755                    "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
756                    Val + ")->getSymbol(), " +
757                    getEnumName(N->getTypeNum(0)) + ");");
758           // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
759           // this value if used multiple times by this pattern result.
760           Val = TmpVar;
761           ModifiedVal = true;
762         }
763         NodeOps.push_back(Val);
764       } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
765                  || N->getOperator()->getName() == "tglobaltlsaddr")) {
766         Record *Op = OperatorMap[N->getName()];
767         // Transform GlobalAddress to TargetGlobalAddress
768         if (Op && (Op->getName() == "globaladdr" ||
769                    Op->getName() == "globaltlsaddr")) {
770           std::string TmpVar = "Tmp" + utostr(ResNo);
771           emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
772                    "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
773                    ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
774                    ");");
775           // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
776           // this value if used multiple times by this pattern result.
777           Val = TmpVar;
778           ModifiedVal = true;
779         }
780         NodeOps.push_back(Val);
781       } else if (!N->isLeaf()
782                  && (N->getOperator()->getName() == "texternalsym"
783                       || N->getOperator()->getName() == "tconstpool")) {
784         // Do not rewrite the variable name, since we don't generate a new
785         // temporary.
786         NodeOps.push_back(Val);
787       } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
788         for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
789           emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
790           NodeOps.push_back("CPTmp" + utostr(i));
791         }
792       } else {
793         // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
794         // node even if it isn't one. Don't select it.
795         if (!LikeLeaf) {
796           emitCode("AddToISelQueue(" + Val + ");");
797           if (isRoot && N->isLeaf()) {
798             emitCode("ReplaceUses(N, " + Val + ");");
799             emitCode("return NULL;");
800           }
801         }
802         NodeOps.push_back(Val);
803       }
804
805       if (ModifiedVal) {
806         VariableMap[VarName] = Val;
807       }
808       return NodeOps;
809     }
810     if (N->isLeaf()) {
811       // If this is an explicit register reference, handle it.
812       if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
813         unsigned ResNo = TmpNo++;
814         if (DI->getDef()->isSubClassOf("Register")) {
815           emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
816                    getQualifiedName(DI->getDef()) + ", " +
817                    getEnumName(N->getTypeNum(0)) + ");");
818           NodeOps.push_back("Tmp" + utostr(ResNo));
819           return NodeOps;
820         } else if (DI->getDef()->getName() == "zero_reg") {
821           emitCode("SDOperand Tmp" + utostr(ResNo) +
822                    " = CurDAG->getRegister(0, " +
823                    getEnumName(N->getTypeNum(0)) + ");");
824           NodeOps.push_back("Tmp" + utostr(ResNo));
825           return NodeOps;
826         }
827       } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
828         unsigned ResNo = TmpNo++;
829         assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
830         emitCode("SDOperand Tmp" + utostr(ResNo) + 
831                  " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
832                  ", " + getEnumName(N->getTypeNum(0)) + ");");
833         NodeOps.push_back("Tmp" + utostr(ResNo));
834         return NodeOps;
835       }
836     
837 #ifndef NDEBUG
838       N->dump();
839 #endif
840       assert(0 && "Unknown leaf type!");
841       return NodeOps;
842     }
843
844     Record *Op = N->getOperator();
845     if (Op->isSubClassOf("Instruction")) {
846       const CodeGenTarget &CGT = CGP.getTargetInfo();
847       CodeGenInstruction &II = CGT.getInstruction(Op->getName());
848       const DAGInstruction &Inst = CGP.getInstruction(Op);
849       const TreePattern *InstPat = Inst.getPattern();
850       // FIXME: Assume actual pattern comes before "implicit".
851       TreePatternNode *InstPatNode =
852         isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
853                : (InstPat ? InstPat->getTree(0) : NULL);
854       if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
855         InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
856       }
857       bool HasVarOps     = isRoot && II.isVariadic;
858       // FIXME: fix how we deal with physical register operands.
859       bool HasImpInputs  = isRoot && Inst.getNumImpOperands() > 0;
860       bool HasImpResults = isRoot && DstRegs.size() > 0;
861       bool NodeHasOptInFlag = isRoot &&
862         PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
863       bool NodeHasInFlag  = isRoot &&
864         PatternHasProperty(Pattern, SDNPInFlag, CGP);
865       bool NodeHasOutFlag = isRoot &&
866         PatternHasProperty(Pattern, SDNPOutFlag, CGP);
867       bool NodeHasChain = InstPatNode &&
868         PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
869       bool InputHasChain = isRoot &&
870         NodeHasProperty(Pattern, SDNPHasChain, CGP);
871       unsigned NumResults = Inst.getNumResults();    
872       unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
873
874       if (NodeHasOptInFlag) {
875         emitCode("bool HasInFlag = "
876            "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
877       }
878       if (HasVarOps)
879         emitCode("SmallVector<SDOperand, 8> Ops" + utostr(OpcNo) + ";");
880
881       // How many results is this pattern expected to produce?
882       unsigned NumPatResults = 0;
883       for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
884         MVT::ValueType VT = Pattern->getTypeNum(i);
885         if (VT != MVT::isVoid && VT != MVT::Flag)
886           NumPatResults++;
887       }
888
889       if (OrigChains.size() > 0) {
890         // The original input chain is being ignored. If it is not just
891         // pointing to the op that's being folded, we should create a
892         // TokenFactor with it and the chain of the folded op as the new chain.
893         // We could potentially be doing multiple levels of folding, in that
894         // case, the TokenFactor can have more operands.
895         emitCode("SmallVector<SDOperand, 8> InChains;");
896         for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
897           emitCode("if (" + OrigChains[i].first + ".Val != " +
898                    OrigChains[i].second + ".Val) {");
899           emitCode("  AddToISelQueue(" + OrigChains[i].first + ");");
900           emitCode("  InChains.push_back(" + OrigChains[i].first + ");");
901           emitCode("}");
902         }
903         emitCode("AddToISelQueue(" + ChainName + ");");
904         emitCode("InChains.push_back(" + ChainName + ");");
905         emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
906                  "&InChains[0], InChains.size());");
907       }
908
909       // Loop over all of the operands of the instruction pattern, emitting code
910       // to fill them all in.  The node 'N' usually has number children equal to
911       // the number of input operands of the instruction.  However, in cases
912       // where there are predicate operands for an instruction, we need to fill
913       // in the 'execute always' values.  Match up the node operands to the
914       // instruction operands to do this.
915       std::vector<std::string> AllOps;
916       unsigned NumEAInputs = 0; // # of synthesized 'execute always' inputs.
917       for (unsigned ChildNo = 0, InstOpNo = NumResults;
918            InstOpNo != II.OperandList.size(); ++InstOpNo) {
919         std::vector<std::string> Ops;
920         
921         // If this is a normal operand or a predicate operand without
922         // 'execute always', emit it.
923         Record *OperandNode = II.OperandList[InstOpNo].Rec;
924         if ((!OperandNode->isSubClassOf("PredicateOperand") &&
925              !OperandNode->isSubClassOf("OptionalDefOperand")) ||
926             CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
927           Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
928                                InFlagDecled, ResNodeDecled);
929           AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
930           ++ChildNo;
931         } else {
932           // Otherwise, this is a predicate or optional def operand, emit the
933           // 'default ops' operands.
934           const DAGDefaultOperand &DefaultOp =
935             CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
936           for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
937             Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
938                                  InFlagDecled, ResNodeDecled);
939             AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
940             NumEAInputs += Ops.size();
941           }
942         }
943       }
944
945       // Generate MemOperandSDNodes nodes for each memory accesses covered by this
946       // pattern.
947       if (isRoot) {
948         std::vector<std::string>::const_iterator mi, mie;
949         for (mi = LSI.begin(), mie = LSI.end(); mi != mie; ++mi) {
950           emitCode("SDOperand LSI_" + *mi + " = "
951                    "CurDAG->getMemOperand(cast<LSBaseSDNode>(" +
952                    *mi + ")->getMemOperand());");
953           AllOps.push_back("LSI_" + *mi);
954         }
955       }
956
957       // Emit all the chain and CopyToReg stuff.
958       bool ChainEmitted = NodeHasChain;
959       if (NodeHasChain)
960         emitCode("AddToISelQueue(" + ChainName + ");");
961       if (NodeHasInFlag || HasImpInputs)
962         EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
963                              InFlagDecled, ResNodeDecled, true);
964       if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
965         if (!InFlagDecled) {
966           emitCode("SDOperand InFlag(0, 0);");
967           InFlagDecled = true;
968         }
969         if (NodeHasOptInFlag) {
970           emitCode("if (HasInFlag) {");
971           emitCode("  InFlag = N.getOperand(N.getNumOperands()-1);");
972           emitCode("  AddToISelQueue(InFlag);");
973           emitCode("}");
974         }
975       }
976
977       unsigned ResNo = TmpNo++;
978       if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
979           NodeHasOptInFlag || HasImpResults) {
980         std::string Code;
981         std::string Code2;
982         std::string NodeName;
983         if (!isRoot) {
984           NodeName = "Tmp" + utostr(ResNo);
985           Code2 = "SDOperand " + NodeName + "(";
986         } else {
987           NodeName = "ResNode";
988           if (!ResNodeDecled) {
989             Code2 = "SDNode *" + NodeName + " = ";
990             ResNodeDecled = true;
991           } else
992             Code2 = NodeName + " = ";
993         }
994
995         Code += "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
996         unsigned OpsNo = OpcNo;
997         emitOpcode(II.Namespace + "::" + II.TheDef->getName());
998
999         // Output order: results, chain, flags
1000         // Result types.
1001         if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1002           Code += ", VT" + utostr(VTNo);
1003           emitVT(getEnumName(N->getTypeNum(0)));
1004         }
1005         // Add types for implicit results in physical registers, scheduler will
1006         // care of adding copyfromreg nodes.
1007         for (unsigned i = 0; i < NumDstRegs; i++) {
1008           Record *RR = DstRegs[i];
1009           if (RR->isSubClassOf("Register")) {
1010             MVT::ValueType RVT = getRegisterValueType(RR, CGT);
1011             Code += ", " + getEnumName(RVT);
1012           }
1013         }
1014         if (NodeHasChain)
1015           Code += ", MVT::Other";
1016         if (NodeHasOutFlag)
1017           Code += ", MVT::Flag";
1018
1019         // Figure out how many fixed inputs the node has.  This is important to
1020         // know which inputs are the variable ones if present.
1021         unsigned NumInputs = AllOps.size();
1022         NumInputs += NodeHasChain;
1023         
1024         // Inputs.
1025         if (HasVarOps) {
1026           for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1027             emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1028           AllOps.clear();
1029         }
1030
1031         if (HasVarOps) {
1032           // Figure out whether any operands at the end of the op list are not
1033           // part of the variable section.
1034           std::string EndAdjust;
1035           if (NodeHasInFlag || HasImpInputs)
1036             EndAdjust = "-1";  // Always has one flag.
1037           else if (NodeHasOptInFlag)
1038             EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1039
1040           emitCode("for (unsigned i = " + utostr(NumInputs - NumEAInputs) +
1041                    ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1042
1043           emitCode("  AddToISelQueue(N.getOperand(i));");
1044           emitCode("  Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
1045           emitCode("}");
1046         }
1047
1048         if (NodeHasChain) {
1049           if (HasVarOps)
1050             emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1051           else
1052             AllOps.push_back(ChainName);
1053         }
1054
1055         if (HasVarOps) {
1056           if (NodeHasInFlag || HasImpInputs)
1057             emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1058           else if (NodeHasOptInFlag) {
1059             emitCode("if (HasInFlag)");
1060             emitCode("  Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1061           }
1062           Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1063             ".size()";
1064         } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1065           AllOps.push_back("InFlag");
1066
1067         unsigned NumOps = AllOps.size();
1068         if (NumOps) {
1069           if (!NodeHasOptInFlag && NumOps < 4) {
1070             for (unsigned i = 0; i != NumOps; ++i)
1071               Code += ", " + AllOps[i];
1072           } else {
1073             std::string OpsCode = "SDOperand Ops" + utostr(OpsNo) + "[] = { ";
1074             for (unsigned i = 0; i != NumOps; ++i) {
1075               OpsCode += AllOps[i];
1076               if (i != NumOps-1)
1077                 OpsCode += ", ";
1078             }
1079             emitCode(OpsCode + " };");
1080             Code += ", Ops" + utostr(OpsNo) + ", ";
1081             if (NodeHasOptInFlag) {
1082               Code += "HasInFlag ? ";
1083               Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1084             } else
1085               Code += utostr(NumOps);
1086           }
1087         }
1088             
1089         if (!isRoot)
1090           Code += "), 0";
1091         emitCode(Code2 + Code + ");");
1092
1093         if (NodeHasChain)
1094           // Remember which op produces the chain.
1095           if (!isRoot)
1096             emitCode(ChainName + " = SDOperand(" + NodeName +
1097                      ".Val, " + utostr(NumResults+NumDstRegs) + ");");
1098           else
1099             emitCode(ChainName + " = SDOperand(" + NodeName +
1100                      ", " + utostr(NumResults+NumDstRegs) + ");");
1101
1102         if (!isRoot) {
1103           NodeOps.push_back("Tmp" + utostr(ResNo));
1104           return NodeOps;
1105         }
1106
1107         bool NeedReplace = false;
1108         if (NodeHasOutFlag) {
1109           if (!InFlagDecled) {
1110             emitCode("SDOperand InFlag(ResNode, " + 
1111                    utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
1112             InFlagDecled = true;
1113           } else
1114             emitCode("InFlag = SDOperand(ResNode, " + 
1115                    utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
1116         }
1117
1118         if (FoldedChains.size() > 0) {
1119           std::string Code;
1120           for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
1121             emitCode("ReplaceUses(SDOperand(" +
1122                      FoldedChains[j].first + ".Val, " + 
1123                      utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " +
1124                      utostr(NumResults+NumDstRegs) + "));");
1125           NeedReplace = true;
1126         }
1127
1128         if (NodeHasOutFlag) {
1129           emitCode("ReplaceUses(SDOperand(N.Val, " +
1130                    utostr(NumPatResults + (unsigned)InputHasChain)
1131                    +"), InFlag);");
1132           NeedReplace = true;
1133         }
1134
1135         if (NeedReplace && InputHasChain)
1136           emitCode("ReplaceUses(SDOperand(N.Val, " + 
1137                    utostr(NumPatResults) + "), SDOperand(" + ChainName
1138                    + ".Val, " + ChainName + ".ResNo" + "));");
1139
1140         // User does not expect the instruction would produce a chain!
1141         if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1142           ;
1143         } else if (InputHasChain && !NodeHasChain) {
1144           // One of the inner node produces a chain.
1145           if (NodeHasOutFlag)
1146             emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults+1) +
1147                      "), SDOperand(ResNode, N.ResNo-1));");
1148           emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults) +
1149                    "), " + ChainName + ");");
1150         }
1151
1152         emitCode("return ResNode;");
1153       } else {
1154         std::string Code = "return CurDAG->SelectNodeTo(N.Val, Opc" +
1155           utostr(OpcNo);
1156         if (N->getTypeNum(0) != MVT::isVoid)
1157           Code += ", VT" + utostr(VTNo);
1158         if (NodeHasOutFlag)
1159           Code += ", MVT::Flag";
1160
1161         if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1162           AllOps.push_back("InFlag");
1163
1164         unsigned NumOps = AllOps.size();
1165         if (NumOps) {
1166           if (!NodeHasOptInFlag && NumOps < 4) {
1167             for (unsigned i = 0; i != NumOps; ++i)
1168               Code += ", " + AllOps[i];
1169           } else {
1170             std::string OpsCode = "SDOperand Ops" + utostr(OpcNo) + "[] = { ";
1171             for (unsigned i = 0; i != NumOps; ++i) {
1172               OpsCode += AllOps[i];
1173               if (i != NumOps-1)
1174                 OpsCode += ", ";
1175             }
1176             emitCode(OpsCode + " };");
1177             Code += ", Ops" + utostr(OpcNo) + ", ";
1178             Code += utostr(NumOps);
1179           }
1180         }
1181         emitCode(Code + ");");
1182         emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1183         if (N->getTypeNum(0) != MVT::isVoid)
1184           emitVT(getEnumName(N->getTypeNum(0)));
1185       }
1186
1187       return NodeOps;
1188     } else if (Op->isSubClassOf("SDNodeXForm")) {
1189       assert(N->getNumChildren() == 1 && "node xform should have one child!");
1190       // PatLeaf node - the operand may or may not be a leaf node. But it should
1191       // behave like one.
1192       std::vector<std::string> Ops =
1193         EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1194                        ResNodeDecled, true);
1195       unsigned ResNo = TmpNo++;
1196       emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1197                + "(" + Ops.back() + ".Val);");
1198       NodeOps.push_back("Tmp" + utostr(ResNo));
1199       if (isRoot)
1200         emitCode("return Tmp" + utostr(ResNo) + ".Val;");
1201       return NodeOps;
1202     } else {
1203       N->dump();
1204       cerr << "\n";
1205       throw std::string("Unknown node in result pattern!");
1206     }
1207   }
1208
1209   /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1210   /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that 
1211   /// 'Pat' may be missing types.  If we find an unresolved type to add a check
1212   /// for, this returns true otherwise false if Pat has all types.
1213   bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1214                           const std::string &Prefix, bool isRoot = false) {
1215     // Did we find one?
1216     if (Pat->getExtTypes() != Other->getExtTypes()) {
1217       // Move a type over from 'other' to 'pat'.
1218       Pat->setTypes(Other->getExtTypes());
1219       // The top level node type is checked outside of the select function.
1220       if (!isRoot)
1221         emitCheck(Prefix + ".Val->getValueType(0) == " +
1222                   getName(Pat->getTypeNum(0)));
1223       return true;
1224     }
1225   
1226     unsigned OpNo =
1227       (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
1228     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1229       if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1230                              Prefix + utostr(OpNo)))
1231         return true;
1232     return false;
1233   }
1234
1235 private:
1236   /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1237   /// being built.
1238   void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1239                             bool &ChainEmitted, bool &InFlagDecled,
1240                             bool &ResNodeDecled, bool isRoot = false) {
1241     const CodeGenTarget &T = CGP.getTargetInfo();
1242     unsigned OpNo =
1243       (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1244     bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
1245     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1246       TreePatternNode *Child = N->getChild(i);
1247       if (!Child->isLeaf()) {
1248         EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1249                              InFlagDecled, ResNodeDecled);
1250       } else {
1251         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1252           if (!Child->getName().empty()) {
1253             std::string Name = RootName + utostr(OpNo);
1254             if (Duplicates.find(Name) != Duplicates.end())
1255               // A duplicate! Do not emit a copy for this node.
1256               continue;
1257           }
1258
1259           Record *RR = DI->getDef();
1260           if (RR->isSubClassOf("Register")) {
1261             MVT::ValueType RVT = getRegisterValueType(RR, T);
1262             if (RVT == MVT::Flag) {
1263               if (!InFlagDecled) {
1264                 emitCode("SDOperand InFlag = " + RootName + utostr(OpNo) + ";");
1265                 InFlagDecled = true;
1266               } else
1267                 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1268               emitCode("AddToISelQueue(InFlag);");
1269             } else {
1270               if (!ChainEmitted) {
1271                 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
1272                 ChainName = "Chain";
1273                 ChainEmitted = true;
1274               }
1275               emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
1276               if (!InFlagDecled) {
1277                 emitCode("SDOperand InFlag(0, 0);");
1278                 InFlagDecled = true;
1279               }
1280               std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1281               emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
1282                        ", " + getQualifiedName(RR) +
1283                        ", " +  RootName + utostr(OpNo) + ", InFlag).Val;");
1284               ResNodeDecled = true;
1285               emitCode(ChainName + " = SDOperand(ResNode, 0);");
1286               emitCode("InFlag = SDOperand(ResNode, 1);");
1287             }
1288           }
1289         }
1290       }
1291     }
1292
1293     if (HasInFlag) {
1294       if (!InFlagDecled) {
1295         emitCode("SDOperand InFlag = " + RootName +
1296                ".getOperand(" + utostr(OpNo) + ");");
1297         InFlagDecled = true;
1298       } else
1299         emitCode("InFlag = " + RootName +
1300                ".getOperand(" + utostr(OpNo) + ");");
1301       emitCode("AddToISelQueue(InFlag);");
1302     }
1303   }
1304 };
1305
1306 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1307 /// stream to match the pattern, and generate the code for the match if it
1308 /// succeeds.  Returns true if the pattern is not guaranteed to match.
1309 void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
1310                   std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1311                                            std::set<std::string> &GeneratedDecl,
1312                                         std::vector<std::string> &TargetOpcodes,
1313                                           std::vector<std::string> &TargetVTs) {
1314   PatternCodeEmitter Emitter(CGP, Pattern.getPredicates(),
1315                              Pattern.getSrcPattern(), Pattern.getDstPattern(),
1316                              GeneratedCode, GeneratedDecl,
1317                              TargetOpcodes, TargetVTs);
1318
1319   // Emit the matcher, capturing named arguments in VariableMap.
1320   bool FoundChain = false;
1321   Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1322
1323   // TP - Get *SOME* tree pattern, we don't care which.
1324   TreePattern &TP = *CGP.pf_begin()->second;
1325   
1326   // At this point, we know that we structurally match the pattern, but the
1327   // types of the nodes may not match.  Figure out the fewest number of type 
1328   // comparisons we need to emit.  For example, if there is only one integer
1329   // type supported by a target, there should be no type comparisons at all for
1330   // integer patterns!
1331   //
1332   // To figure out the fewest number of type checks needed, clone the pattern,
1333   // remove the types, then perform type inference on the pattern as a whole.
1334   // If there are unresolved types, emit an explicit check for those types,
1335   // apply the type to the tree, then rerun type inference.  Iterate until all
1336   // types are resolved.
1337   //
1338   TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1339   RemoveAllTypes(Pat);
1340   
1341   do {
1342     // Resolve/propagate as many types as possible.
1343     try {
1344       bool MadeChange = true;
1345       while (MadeChange)
1346         MadeChange = Pat->ApplyTypeConstraints(TP,
1347                                                true/*Ignore reg constraints*/);
1348     } catch (...) {
1349       assert(0 && "Error: could not find consistent types for something we"
1350              " already decided was ok!");
1351       abort();
1352     }
1353
1354     // Insert a check for an unresolved type and add it to the tree.  If we find
1355     // an unresolved type to add a check for, this returns true and we iterate,
1356     // otherwise we are done.
1357   } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1358
1359   Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
1360                          false, false, false, true);
1361   delete Pat;
1362 }
1363
1364 /// EraseCodeLine - Erase one code line from all of the patterns.  If removing
1365 /// a line causes any of them to be empty, remove them and return true when
1366 /// done.
1367 static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*, 
1368                           std::vector<std::pair<unsigned, std::string> > > >
1369                           &Patterns) {
1370   bool ErasedPatterns = false;
1371   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1372     Patterns[i].second.pop_back();
1373     if (Patterns[i].second.empty()) {
1374       Patterns.erase(Patterns.begin()+i);
1375       --i; --e;
1376       ErasedPatterns = true;
1377     }
1378   }
1379   return ErasedPatterns;
1380 }
1381
1382 /// EmitPatterns - Emit code for at least one pattern, but try to group common
1383 /// code together between the patterns.
1384 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*, 
1385                               std::vector<std::pair<unsigned, std::string> > > >
1386                                   &Patterns, unsigned Indent,
1387                                   std::ostream &OS) {
1388   typedef std::pair<unsigned, std::string> CodeLine;
1389   typedef std::vector<CodeLine> CodeList;
1390   typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
1391   
1392   if (Patterns.empty()) return;
1393   
1394   // Figure out how many patterns share the next code line.  Explicitly copy
1395   // FirstCodeLine so that we don't invalidate a reference when changing
1396   // Patterns.
1397   const CodeLine FirstCodeLine = Patterns.back().second.back();
1398   unsigned LastMatch = Patterns.size()-1;
1399   while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1400     --LastMatch;
1401   
1402   // If not all patterns share this line, split the list into two pieces.  The
1403   // first chunk will use this line, the second chunk won't.
1404   if (LastMatch != 0) {
1405     PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1406     PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1407     
1408     // FIXME: Emit braces?
1409     if (Shared.size() == 1) {
1410       const PatternToMatch &Pattern = *Shared.back().first;
1411       OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1412       Pattern.getSrcPattern()->print(OS);
1413       OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1414       Pattern.getDstPattern()->print(OS);
1415       OS << "\n";
1416       unsigned AddedComplexity = Pattern.getAddedComplexity();
1417       OS << std::string(Indent, ' ') << "// Pattern complexity = "
1418          << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1419          << "  cost = "
1420          << getResultPatternCost(Pattern.getDstPattern(), CGP)
1421          << "  size = "
1422          << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1423     }
1424     if (FirstCodeLine.first != 1) {
1425       OS << std::string(Indent, ' ') << "{\n";
1426       Indent += 2;
1427     }
1428     EmitPatterns(Shared, Indent, OS);
1429     if (FirstCodeLine.first != 1) {
1430       Indent -= 2;
1431       OS << std::string(Indent, ' ') << "}\n";
1432     }
1433     
1434     if (Other.size() == 1) {
1435       const PatternToMatch &Pattern = *Other.back().first;
1436       OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1437       Pattern.getSrcPattern()->print(OS);
1438       OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1439       Pattern.getDstPattern()->print(OS);
1440       OS << "\n";
1441       unsigned AddedComplexity = Pattern.getAddedComplexity();
1442       OS << std::string(Indent, ' ') << "// Pattern complexity = "
1443          << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1444          << "  cost = "
1445          << getResultPatternCost(Pattern.getDstPattern(), CGP)
1446          << "  size = "
1447          << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1448     }
1449     EmitPatterns(Other, Indent, OS);
1450     return;
1451   }
1452   
1453   // Remove this code from all of the patterns that share it.
1454   bool ErasedPatterns = EraseCodeLine(Patterns);
1455   
1456   bool isPredicate = FirstCodeLine.first == 1;
1457   
1458   // Otherwise, every pattern in the list has this line.  Emit it.
1459   if (!isPredicate) {
1460     // Normal code.
1461     OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1462   } else {
1463     OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1464     
1465     // If the next code line is another predicate, and if all of the pattern
1466     // in this group share the same next line, emit it inline now.  Do this
1467     // until we run out of common predicates.
1468     while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1469       // Check that all of fhe patterns in Patterns end with the same predicate.
1470       bool AllEndWithSamePredicate = true;
1471       for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1472         if (Patterns[i].second.back() != Patterns.back().second.back()) {
1473           AllEndWithSamePredicate = false;
1474           break;
1475         }
1476       // If all of the predicates aren't the same, we can't share them.
1477       if (!AllEndWithSamePredicate) break;
1478       
1479       // Otherwise we can.  Emit it shared now.
1480       OS << " &&\n" << std::string(Indent+4, ' ')
1481          << Patterns.back().second.back().second;
1482       ErasedPatterns = EraseCodeLine(Patterns);
1483     }
1484     
1485     OS << ") {\n";
1486     Indent += 2;
1487   }
1488   
1489   EmitPatterns(Patterns, Indent, OS);
1490   
1491   if (isPredicate)
1492     OS << std::string(Indent-2, ' ') << "}\n";
1493 }
1494
1495 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
1496   return CGP.getSDNodeInfo(Op).getEnumName();
1497 }
1498
1499 static std::string getLegalCName(std::string OpName) {
1500   std::string::size_type pos = OpName.find("::");
1501   if (pos != std::string::npos)
1502     OpName.replace(pos, 2, "_");
1503   return OpName;
1504 }
1505
1506 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1507   const CodeGenTarget &Target = CGP.getTargetInfo();
1508   
1509   // Get the namespace to insert instructions into.  Make sure not to pick up
1510   // "TargetInstrInfo" by accidentally getting the namespace off the PHI
1511   // instruction or something.
1512   std::string InstNS;
1513   for (CodeGenTarget::inst_iterator i = Target.inst_begin(),
1514        e = Target.inst_end(); i != e; ++i) {
1515     InstNS = i->second.Namespace;
1516     if (InstNS != "TargetInstrInfo")
1517       break;
1518   }
1519   
1520   if (!InstNS.empty()) InstNS += "::";
1521   
1522   // Group the patterns by their top-level opcodes.
1523   std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
1524   // All unique target node emission functions.
1525   std::map<std::string, unsigned> EmitFunctions;
1526   for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1527        E = CGP.ptm_end(); I != E; ++I) {
1528     const PatternToMatch &Pattern = *I;
1529
1530     TreePatternNode *Node = Pattern.getSrcPattern();
1531     if (!Node->isLeaf()) {
1532       PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
1533         push_back(&Pattern);
1534     } else {
1535       const ComplexPattern *CP;
1536       if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
1537         PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
1538           push_back(&Pattern);
1539       } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
1540         std::vector<Record*> OpNodes = CP->getRootNodes();
1541         for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
1542           PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1543             .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
1544                     &Pattern);
1545         }
1546       } else {
1547         cerr << "Unrecognized opcode '";
1548         Node->dump();
1549         cerr << "' on tree pattern '";
1550         cerr << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
1551         exit(1);
1552       }
1553     }
1554   }
1555
1556   // For each opcode, there might be multiple select functions, one per
1557   // ValueType of the node (or its first operand if it doesn't produce a
1558   // non-chain result.
1559   std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1560
1561   // Emit one Select_* method for each top-level opcode.  We do this instead of
1562   // emitting one giant switch statement to support compilers where this will
1563   // result in the recursive functions taking less stack space.
1564   for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1565          PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1566        PBOI != E; ++PBOI) {
1567     const std::string &OpName = PBOI->first;
1568     std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
1569     assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1570
1571     // We want to emit all of the matching code now.  However, we want to emit
1572     // the matches in order of minimal cost.  Sort the patterns so the least
1573     // cost one is at the start.
1574     std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
1575                      PatternSortingPredicate(CGP));
1576
1577     // Split them into groups by type.
1578     std::map<MVT::ValueType, std::vector<const PatternToMatch*> >PatternsByType;
1579     for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
1580       const PatternToMatch *Pat = PatternsOfOp[i];
1581       TreePatternNode *SrcPat = Pat->getSrcPattern();
1582       MVT::ValueType VT = SrcPat->getTypeNum(0);
1583       std::map<MVT::ValueType, 
1584                std::vector<const PatternToMatch*> >::iterator TI = 
1585         PatternsByType.find(VT);
1586       if (TI != PatternsByType.end())
1587         TI->second.push_back(Pat);
1588       else {
1589         std::vector<const PatternToMatch*> PVec;
1590         PVec.push_back(Pat);
1591         PatternsByType.insert(std::make_pair(VT, PVec));
1592       }
1593     }
1594
1595     for (std::map<MVT::ValueType, std::vector<const PatternToMatch*> >::iterator
1596            II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1597          ++II) {
1598       MVT::ValueType OpVT = II->first;
1599       std::vector<const PatternToMatch*> &Patterns = II->second;
1600       typedef std::vector<std::pair<unsigned,std::string> > CodeList;
1601       typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
1602     
1603       std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
1604       std::vector<std::vector<std::string> > PatternOpcodes;
1605       std::vector<std::vector<std::string> > PatternVTs;
1606       std::vector<std::set<std::string> > PatternDecls;
1607       for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1608         CodeList GeneratedCode;
1609         std::set<std::string> GeneratedDecl;
1610         std::vector<std::string> TargetOpcodes;
1611         std::vector<std::string> TargetVTs;
1612         GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1613                                TargetOpcodes, TargetVTs);
1614         CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1615         PatternDecls.push_back(GeneratedDecl);
1616         PatternOpcodes.push_back(TargetOpcodes);
1617         PatternVTs.push_back(TargetVTs);
1618       }
1619     
1620       // Scan the code to see if all of the patterns are reachable and if it is
1621       // possible that the last one might not match.
1622       bool mightNotMatch = true;
1623       for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1624         CodeList &GeneratedCode = CodeForPatterns[i].second;
1625         mightNotMatch = false;
1626
1627         for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1628           if (GeneratedCode[j].first == 1) { // predicate.
1629             mightNotMatch = true;
1630             break;
1631           }
1632         }
1633       
1634         // If this pattern definitely matches, and if it isn't the last one, the
1635         // patterns after it CANNOT ever match.  Error out.
1636         if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1637           cerr << "Pattern '";
1638           CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
1639           cerr << "' is impossible to select!\n";
1640           exit(1);
1641         }
1642       }
1643
1644       // Factor target node emission code (emitted by EmitResultCode) into
1645       // separate functions. Uniquing and share them among all instruction
1646       // selection routines.
1647       for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1648         CodeList &GeneratedCode = CodeForPatterns[i].second;
1649         std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1650         std::vector<std::string> &TargetVTs = PatternVTs[i];
1651         std::set<std::string> Decls = PatternDecls[i];
1652         std::vector<std::string> AddedInits;
1653         int CodeSize = (int)GeneratedCode.size();
1654         int LastPred = -1;
1655         for (int j = CodeSize-1; j >= 0; --j) {
1656           if (LastPred == -1 && GeneratedCode[j].first == 1)
1657             LastPred = j;
1658           else if (LastPred != -1 && GeneratedCode[j].first == 2)
1659             AddedInits.push_back(GeneratedCode[j].second);
1660         }
1661
1662         std::string CalleeCode = "(const SDOperand &N";
1663         std::string CallerCode = "(N";
1664         for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1665           CalleeCode += ", unsigned Opc" + utostr(j);
1666           CallerCode += ", " + TargetOpcodes[j];
1667         }
1668         for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1669           CalleeCode += ", MVT::ValueType VT" + utostr(j);
1670           CallerCode += ", " + TargetVTs[j];
1671         }
1672         for (std::set<std::string>::iterator
1673                I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1674           std::string Name = *I;
1675           CalleeCode += ", SDOperand &" + Name;
1676           CallerCode += ", " + Name;
1677         }
1678         CallerCode += ");";
1679         CalleeCode += ") ";
1680         // Prevent emission routines from being inlined to reduce selection
1681         // routines stack frame sizes.
1682         CalleeCode += "DISABLE_INLINE ";
1683         CalleeCode += "{\n";
1684
1685         for (std::vector<std::string>::const_reverse_iterator
1686                I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1687           CalleeCode += "  " + *I + "\n";
1688
1689         for (int j = LastPred+1; j < CodeSize; ++j)
1690           CalleeCode += "  " + GeneratedCode[j].second + "\n";
1691         for (int j = LastPred+1; j < CodeSize; ++j)
1692           GeneratedCode.pop_back();
1693         CalleeCode += "}\n";
1694
1695         // Uniquing the emission routines.
1696         unsigned EmitFuncNum;
1697         std::map<std::string, unsigned>::iterator EFI =
1698           EmitFunctions.find(CalleeCode);
1699         if (EFI != EmitFunctions.end()) {
1700           EmitFuncNum = EFI->second;
1701         } else {
1702           EmitFuncNum = EmitFunctions.size();
1703           EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1704           OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1705         }
1706
1707         // Replace the emission code within selection routines with calls to the
1708         // emission functions.
1709         CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
1710         GeneratedCode.push_back(std::make_pair(false, CallerCode));
1711       }
1712
1713       // Print function.
1714       std::string OpVTStr;
1715       if (OpVT == MVT::iPTR) {
1716         OpVTStr = "_iPTR";
1717       } else if (OpVT == MVT::isVoid) {
1718         // Nodes with a void result actually have a first result type of either
1719         // Other (a chain) or Flag.  Since there is no one-to-one mapping from
1720         // void to this case, we handle it specially here.
1721       } else {
1722         OpVTStr = "_" + getEnumName(OpVT).substr(5);  // Skip 'MVT::'
1723       }
1724       std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1725         OpcodeVTMap.find(OpName);
1726       if (OpVTI == OpcodeVTMap.end()) {
1727         std::vector<std::string> VTSet;
1728         VTSet.push_back(OpVTStr);
1729         OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1730       } else
1731         OpVTI->second.push_back(OpVTStr);
1732
1733       OS << "SDNode *Select_" << getLegalCName(OpName)
1734          << OpVTStr << "(const SDOperand &N) {\n";    
1735
1736       // Loop through and reverse all of the CodeList vectors, as we will be
1737       // accessing them from their logical front, but accessing the end of a
1738       // vector is more efficient.
1739       for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1740         CodeList &GeneratedCode = CodeForPatterns[i].second;
1741         std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1742       }
1743     
1744       // Next, reverse the list of patterns itself for the same reason.
1745       std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1746     
1747       // Emit all of the patterns now, grouped together to share code.
1748       EmitPatterns(CodeForPatterns, 2, OS);
1749     
1750       // If the last pattern has predicates (which could fail) emit code to
1751       // catch the case where nothing handles a pattern.
1752       if (mightNotMatch) {
1753         OS << "  cerr << \"Cannot yet select: \";\n";
1754         if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1755             OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1756             OpName != "ISD::INTRINSIC_VOID") {
1757           OS << "  N.Val->dump(CurDAG);\n";
1758         } else {
1759           OS << "  unsigned iid = cast<ConstantSDNode>(N.getOperand("
1760             "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1761              << "  cerr << \"intrinsic %\"<< "
1762             "Intrinsic::getName((Intrinsic::ID)iid);\n";
1763         }
1764         OS << "  cerr << '\\n';\n"
1765            << "  abort();\n"
1766            << "  return NULL;\n";
1767       }
1768       OS << "}\n\n";
1769     }
1770   }
1771   
1772   // Emit boilerplate.
1773   OS << "SDNode *Select_INLINEASM(SDOperand N) {\n"
1774      << "  std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
1775      << "  SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n\n"
1776     
1777      << "  // Ensure that the asm operands are themselves selected.\n"
1778      << "  for (unsigned j = 0, e = Ops.size(); j != e; ++j)\n"
1779      << "    AddToISelQueue(Ops[j]);\n\n"
1780     
1781      << "  std::vector<MVT::ValueType> VTs;\n"
1782      << "  VTs.push_back(MVT::Other);\n"
1783      << "  VTs.push_back(MVT::Flag);\n"
1784      << "  SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
1785                  "Ops.size());\n"
1786      << "  return New.Val;\n"
1787      << "}\n\n";
1788   
1789   OS << "SDNode *Select_LABEL(const SDOperand &N) {\n"
1790      << "  SDOperand Chain = N.getOperand(0);\n"
1791      << "  SDOperand N1 = N.getOperand(1);\n"
1792      << "  unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1793      << "  SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1794      << "  AddToISelQueue(Chain);\n"
1795      << "  SDOperand Ops[] = { Tmp, Chain };\n"
1796      << "  return CurDAG->getTargetNode(TargetInstrInfo::LABEL,\n"
1797      << "                               MVT::Other, Ops, 2);\n"
1798      << "}\n\n";
1799
1800   OS << "SDNode *Select_EXTRACT_SUBREG(const SDOperand &N) {\n"
1801      << "  SDOperand N0 = N.getOperand(0);\n"
1802      << "  SDOperand N1 = N.getOperand(1);\n"
1803      << "  unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1804      << "  SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1805      << "  AddToISelQueue(N0);\n"
1806      << "  SDOperand Ops[] = { N0, Tmp };\n"
1807      << "  return CurDAG->getTargetNode(TargetInstrInfo::EXTRACT_SUBREG,\n"
1808      << "                               N.getValueType(), Ops, 2);\n"
1809      << "}\n\n";
1810
1811   OS << "SDNode *Select_INSERT_SUBREG(const SDOperand &N) {\n"
1812      << "  SDOperand N0 = N.getOperand(0);\n"
1813      << "  SDOperand N1 = N.getOperand(1);\n"
1814      << "  SDOperand N2 = N.getOperand(2);\n"
1815      << "  unsigned C = cast<ConstantSDNode>(N2)->getValue();\n"
1816      << "  SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1817      << "  AddToISelQueue(N1);\n"
1818      << "  SDOperand Ops[] = { N0, N1, Tmp };\n"
1819      << "  if (N0.getOpcode() == ISD::UNDEF) {\n"
1820      << "    return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
1821      << "                                 N.getValueType(), Ops+1, 2);\n"
1822      << "  } else {\n"
1823      << "    AddToISelQueue(N0);\n"
1824      << "    return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
1825      << "                                 N.getValueType(), Ops, 3);\n"
1826      << "  }\n"
1827      << "}\n\n";
1828
1829   OS << "// The main instruction selector code.\n"
1830      << "SDNode *SelectCode(SDOperand N) {\n"
1831      << "  if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1832      << "      N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1833      << "INSTRUCTION_LIST_END)) {\n"
1834      << "    return NULL;   // Already selected.\n"
1835      << "  }\n\n"
1836      << "  MVT::ValueType NVT = N.Val->getValueType(0);\n"
1837      << "  switch (N.getOpcode()) {\n"
1838      << "  default: break;\n"
1839      << "  case ISD::EntryToken:       // These leaves remain the same.\n"
1840      << "  case ISD::BasicBlock:\n"
1841      << "  case ISD::Register:\n"
1842      << "  case ISD::HANDLENODE:\n"
1843      << "  case ISD::TargetConstant:\n"
1844      << "  case ISD::TargetConstantPool:\n"
1845      << "  case ISD::TargetFrameIndex:\n"
1846      << "  case ISD::TargetExternalSymbol:\n"
1847      << "  case ISD::TargetJumpTable:\n"
1848      << "  case ISD::TargetGlobalTLSAddress:\n"
1849      << "  case ISD::TargetGlobalAddress: {\n"
1850      << "    return NULL;\n"
1851      << "  }\n"
1852      << "  case ISD::AssertSext:\n"
1853      << "  case ISD::AssertZext: {\n"
1854      << "    AddToISelQueue(N.getOperand(0));\n"
1855      << "    ReplaceUses(N, N.getOperand(0));\n"
1856      << "    return NULL;\n"
1857      << "  }\n"
1858      << "  case ISD::TokenFactor:\n"
1859      << "  case ISD::CopyFromReg:\n"
1860      << "  case ISD::CopyToReg: {\n"
1861      << "    for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1862      << "      AddToISelQueue(N.getOperand(i));\n"
1863      << "    return NULL;\n"
1864      << "  }\n"
1865      << "  case ISD::INLINEASM: return Select_INLINEASM(N);\n"
1866      << "  case ISD::LABEL: return Select_LABEL(N);\n"
1867      << "  case ISD::EXTRACT_SUBREG: return Select_EXTRACT_SUBREG(N);\n"
1868      << "  case ISD::INSERT_SUBREG:  return Select_INSERT_SUBREG(N);\n";
1869
1870     
1871   // Loop over all of the case statements, emiting a call to each method we
1872   // emitted above.
1873   for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1874          PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1875        PBOI != E; ++PBOI) {
1876     const std::string &OpName = PBOI->first;
1877     // Potentially multiple versions of select for this opcode. One for each
1878     // ValueType of the node (or its first true operand if it doesn't produce a
1879     // result.
1880     std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1881       OpcodeVTMap.find(OpName);
1882     std::vector<std::string> &OpVTs = OpVTI->second;
1883     OS << "  case " << OpName << ": {\n";
1884     // Keep track of whether we see a pattern that has an iPtr result.
1885     bool HasPtrPattern = false;
1886     bool HasDefaultPattern = false;
1887       
1888     OS << "    switch (NVT) {\n";
1889     for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1890       std::string &VTStr = OpVTs[i];
1891       if (VTStr.empty()) {
1892         HasDefaultPattern = true;
1893         continue;
1894       }
1895
1896       // If this is a match on iPTR: don't emit it directly, we need special
1897       // code.
1898       if (VTStr == "_iPTR") {
1899         HasPtrPattern = true;
1900         continue;
1901       }
1902       OS << "    case MVT::" << VTStr.substr(1) << ":\n"
1903          << "      return Select_" << getLegalCName(OpName)
1904          << VTStr << "(N);\n";
1905     }
1906     OS << "    default:\n";
1907       
1908     // If there is an iPTR result version of this pattern, emit it here.
1909     if (HasPtrPattern) {
1910       OS << "      if (NVT == TLI.getPointerTy())\n";
1911       OS << "        return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
1912     }
1913     if (HasDefaultPattern) {
1914       OS << "      return Select_" << getLegalCName(OpName) << "(N);\n";
1915     }
1916     OS << "      break;\n";
1917     OS << "    }\n";
1918     OS << "    break;\n";
1919     OS << "  }\n";
1920   }
1921
1922   OS << "  } // end of big switch.\n\n"
1923      << "  cerr << \"Cannot yet select: \";\n"
1924      << "  if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
1925      << "      N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
1926      << "      N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
1927      << "    N.Val->dump(CurDAG);\n"
1928      << "  } else {\n"
1929      << "    unsigned iid = cast<ConstantSDNode>(N.getOperand("
1930                "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1931      << "    cerr << \"intrinsic %\"<< "
1932                "Intrinsic::getName((Intrinsic::ID)iid);\n"
1933      << "  }\n"
1934      << "  cerr << '\\n';\n"
1935      << "  abort();\n"
1936      << "  return NULL;\n"
1937      << "}\n";
1938 }
1939
1940 void DAGISelEmitter::run(std::ostream &OS) {
1941   EmitSourceFileHeader("DAG Instruction Selector for the " +
1942                        CGP.getTargetInfo().getName() + " target", OS);
1943   
1944   OS << "// *** NOTE: This file is #included into the middle of the target\n"
1945      << "// *** instruction selector class.  These functions are really "
1946      << "methods.\n\n";
1947   
1948   OS << "#include \"llvm/Support/Compiler.h\"\n";
1949
1950   OS << "// Instruction selector priority queue:\n"
1951      << "std::vector<SDNode*> ISelQueue;\n";
1952   OS << "/// Keep track of nodes which have already been added to queue.\n"
1953      << "unsigned char *ISelQueued;\n";
1954   OS << "/// Keep track of nodes which have already been selected.\n"
1955      << "unsigned char *ISelSelected;\n";
1956   OS << "/// Dummy parameter to ReplaceAllUsesOfValueWith().\n"
1957      << "std::vector<SDNode*> ISelKilled;\n\n";
1958
1959   OS << "/// IsChainCompatible - Returns true if Chain is Op or Chain does\n";
1960   OS << "/// not reach Op.\n";
1961   OS << "static bool IsChainCompatible(SDNode *Chain, SDNode *Op) {\n";
1962   OS << "  if (Chain->getOpcode() == ISD::EntryToken)\n";
1963   OS << "    return true;\n";
1964   OS << "  else if (Chain->getOpcode() == ISD::TokenFactor)\n";
1965   OS << "    return false;\n";
1966   OS << "  else if (Chain->getNumOperands() > 0) {\n";
1967   OS << "    SDOperand C0 = Chain->getOperand(0);\n";
1968   OS << "    if (C0.getValueType() == MVT::Other)\n";
1969   OS << "      return C0.Val != Op && IsChainCompatible(C0.Val, Op);\n";
1970   OS << "  }\n";
1971   OS << "  return true;\n";
1972   OS << "}\n";
1973
1974   OS << "/// Sorting functions for the selection queue.\n"
1975      << "struct isel_sort : public std::binary_function"
1976      << "<SDNode*, SDNode*, bool> {\n"
1977      << "  bool operator()(const SDNode* left, const SDNode* right) "
1978      << "const {\n"
1979      << "    return (left->getNodeId() > right->getNodeId());\n"
1980      << "  }\n"
1981      << "};\n\n";
1982
1983   OS << "inline void setQueued(int Id) {\n";
1984   OS << "  ISelQueued[Id / 8] |= 1 << (Id % 8);\n";
1985   OS << "}\n";
1986   OS << "inline bool isQueued(int Id) {\n";
1987   OS << "  return ISelQueued[Id / 8] & (1 << (Id % 8));\n";
1988   OS << "}\n";
1989   OS << "inline void setSelected(int Id) {\n";
1990   OS << "  ISelSelected[Id / 8] |= 1 << (Id % 8);\n";
1991   OS << "}\n";
1992   OS << "inline bool isSelected(int Id) {\n";
1993   OS << "  return ISelSelected[Id / 8] & (1 << (Id % 8));\n";
1994   OS << "}\n\n";
1995
1996   OS << "void AddToISelQueue(SDOperand N) DISABLE_INLINE {\n";
1997   OS << "  int Id = N.Val->getNodeId();\n";
1998   OS << "  if (Id != -1 && !isQueued(Id)) {\n";
1999   OS << "    ISelQueue.push_back(N.Val);\n";
2000  OS << "    std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
2001   OS << "    setQueued(Id);\n";
2002   OS << "  }\n";
2003   OS << "}\n\n";
2004
2005   OS << "inline void RemoveKilled() {\n";
2006 OS << "  unsigned NumKilled = ISelKilled.size();\n";
2007   OS << "  if (NumKilled) {\n";
2008   OS << "    for (unsigned i = 0; i != NumKilled; ++i) {\n";
2009   OS << "      SDNode *Temp = ISelKilled[i];\n";
2010   OS << "      ISelQueue.erase(std::remove(ISelQueue.begin(), ISelQueue.end(), "
2011      << "Temp), ISelQueue.end());\n";
2012   OS << "    };\n";
2013  OS << "    std::make_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
2014   OS << "    ISelKilled.clear();\n";
2015   OS << "  }\n";
2016   OS << "}\n\n";
2017
2018   OS << "void ReplaceUses(SDOperand F, SDOperand T) DISABLE_INLINE {\n";
2019   OS << "  CurDAG->ReplaceAllUsesOfValueWith(F, T, &ISelKilled);\n";
2020   OS << "  setSelected(F.Val->getNodeId());\n";
2021   OS << "  RemoveKilled();\n";
2022   OS << "}\n";
2023   OS << "void ReplaceUses(SDNode *F, SDNode *T) DISABLE_INLINE {\n";
2024   OS << "  unsigned FNumVals = F->getNumValues();\n";
2025   OS << "  unsigned TNumVals = T->getNumValues();\n";
2026   OS << "  if (FNumVals != TNumVals) {\n";
2027   OS << "    for (unsigned i = 0, e = std::min(FNumVals, TNumVals); "
2028      << "i < e; ++i)\n";
2029   OS << "      CurDAG->ReplaceAllUsesOfValueWith(SDOperand(F, i), "
2030      << "SDOperand(T, i), &ISelKilled);\n";
2031   OS << "  } else {\n";
2032   OS << "    CurDAG->ReplaceAllUsesWith(F, T, &ISelKilled);\n";
2033   OS << "  }\n";
2034   OS << "  setSelected(F->getNodeId());\n";
2035   OS << "  RemoveKilled();\n";
2036   OS << "}\n\n";
2037
2038   OS << "// SelectRoot - Top level entry to DAG isel.\n";
2039   OS << "SDOperand SelectRoot(SDOperand Root) {\n";
2040   OS << "  SelectRootInit();\n";
2041   OS << "  unsigned NumBytes = (DAGSize + 7) / 8;\n";
2042   OS << "  ISelQueued   = new unsigned char[NumBytes];\n";
2043   OS << "  ISelSelected = new unsigned char[NumBytes];\n";
2044   OS << "  memset(ISelQueued,   0, NumBytes);\n";
2045   OS << "  memset(ISelSelected, 0, NumBytes);\n";
2046   OS << "\n";
2047   OS << "  // Create a dummy node (which is not added to allnodes), that adds\n"
2048      << "  // a reference to the root node, preventing it from being deleted,\n"
2049      << "  // and tracking any changes of the root.\n"
2050      << "  HandleSDNode Dummy(CurDAG->getRoot());\n"
2051      << "  ISelQueue.push_back(CurDAG->getRoot().Val);\n";
2052   OS << "  while (!ISelQueue.empty()) {\n";
2053   OS << "    SDNode *Node = ISelQueue.front();\n";
2054   OS << "    std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
2055   OS << "    ISelQueue.pop_back();\n";
2056   OS << "    if (!isSelected(Node->getNodeId())) {\n";
2057   OS << "      SDNode *ResNode = Select(SDOperand(Node, 0));\n";
2058   OS << "      if (ResNode != Node) {\n";
2059   OS << "        if (ResNode)\n";
2060   OS << "          ReplaceUses(Node, ResNode);\n";
2061   OS << "        if (Node->use_empty()) { // Don't delete EntryToken, etc.\n";
2062   OS << "          CurDAG->RemoveDeadNode(Node, ISelKilled);\n";
2063   OS << "          RemoveKilled();\n";
2064   OS << "        }\n";
2065   OS << "      }\n";
2066   OS << "    }\n";
2067   OS << "  }\n";
2068   OS << "\n";
2069   OS << "  delete[] ISelQueued;\n";
2070   OS << "  ISelQueued = NULL;\n";
2071   OS << "  delete[] ISelSelected;\n";
2072   OS << "  ISelSelected = NULL;\n";
2073   OS << "  return Dummy.getValue();\n";
2074   OS << "}\n";
2075   
2076   EmitNodeTransforms(OS);
2077   EmitPredicateFunctions(OS);
2078   
2079   DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
2080   for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
2081        I != E; ++I) {
2082     DOUT << "PATTERN: ";   DEBUG(I->getSrcPattern()->dump());
2083     DOUT << "\nRESULT:  "; DEBUG(I->getDstPattern()->dump());
2084     DOUT << "\n";
2085   }
2086   
2087   // At this point, we have full information about the 'Patterns' we need to
2088   // parse, both implicitly from instructions as well as from explicit pattern
2089   // definitions.  Emit the resultant instruction selector.
2090   EmitInstructionSelector(OS);  
2091   
2092 }