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