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