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