18293314263ae73f389acb8530e31a93bb38370a
[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("CanBeFoldedBy(" + RootName + ".getNode(), " + ParentName +
526                       ".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           emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
587           const char *MaskPredicate = N->getOperator()->getName() == "or"
588             ? "CheckOrMask(" : "CheckAndMask(";
589           emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
590                     RootName + "1), INT64_C(" + itostr(II->getValue()) + "))");
591           
592           EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0), RootName,
593                              ChainSuffix + utostr(0), FoundChain);
594           return;
595         }
596       }
597     }
598     
599     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
600       emitInit("SDValue " + RootName + utostr(OpNo) + " = " +
601                RootName + ".getOperand(" +utostr(OpNo) + ");");
602
603       EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo), RootName,
604                          ChainSuffix + utostr(OpNo), FoundChain);
605     }
606
607     // Handle cases when root is a complex pattern.
608     const ComplexPattern *CP;
609     if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
610       std::string Fn = CP->getSelectFunc();
611       unsigned NumOps = CP->getNumOperands();
612       for (unsigned i = 0; i < NumOps; ++i) {
613         emitDecl("CPTmp" + utostr(i));
614         emitCode("SDValue CPTmp" + utostr(i) + ";");
615       }
616       if (CP->hasProperty(SDNPHasChain)) {
617         emitDecl("CPInChain");
618         emitDecl("Chain" + ChainSuffix);
619         emitCode("SDValue CPInChain;");
620         emitCode("SDValue Chain" + ChainSuffix + ";");
621       }
622
623       std::string Code = Fn + "(" + RootName + ", " + RootName;
624       for (unsigned i = 0; i < NumOps; i++)
625         Code += ", CPTmp" + utostr(i);
626       if (CP->hasProperty(SDNPHasChain)) {
627         ChainName = "Chain" + ChainSuffix;
628         Code += ", CPInChain, Chain" + ChainSuffix;
629       }
630       emitCheck(Code + ")");
631     }
632   }
633
634   void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
635                           const std::string &RootName, 
636                           const std::string &ParentRootName,
637                           const std::string &ChainSuffix, bool &FoundChain) {
638     if (!Child->isLeaf()) {
639       // If it's not a leaf, recursively match.
640       const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
641       emitCheck(RootName + ".getOpcode() == " +
642                 CInfo.getEnumName());
643       EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
644       bool HasChain = false;
645       if (NodeHasProperty(Child, SDNPHasChain, CGP)) {
646         HasChain = true;
647         FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
648       }
649       if (NodeHasProperty(Child, SDNPOutFlag, CGP)) {
650         assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
651                "Pattern folded multiple nodes which produce flags?");
652         FoldedFlag = std::make_pair(RootName,
653                                     CInfo.getNumResults() + (unsigned)HasChain);
654       }
655     } else {
656       // If this child has a name associated with it, capture it in VarMap. If
657       // we already saw this in the pattern, emit code to verify dagness.
658       if (!Child->getName().empty()) {
659         std::string &VarMapEntry = VariableMap[Child->getName()];
660         if (VarMapEntry.empty()) {
661           VarMapEntry = RootName;
662         } else {
663           // If we get here, this is a second reference to a specific name.
664           // Since we already have checked that the first reference is valid,
665           // we don't have to recursively match it, just check that it's the
666           // same as the previously named thing.
667           emitCheck(VarMapEntry + " == " + RootName);
668           Duplicates.insert(RootName);
669           return;
670         }
671       }
672       
673       // Handle leaves of various types.
674       if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
675         Record *LeafRec = DI->getDef();
676         if (LeafRec->isSubClassOf("RegisterClass") || 
677             LeafRec->getName() == "ptr_rc") {
678           // Handle register references.  Nothing to do here.
679         } else if (LeafRec->isSubClassOf("Register")) {
680           // Handle register references.
681         } else if (LeafRec->isSubClassOf("ComplexPattern")) {
682           // Handle complex pattern.
683           const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
684           std::string Fn = CP->getSelectFunc();
685           unsigned NumOps = CP->getNumOperands();
686           for (unsigned i = 0; i < NumOps; ++i) {
687             emitDecl("CPTmp" + utostr(i));
688             emitCode("SDValue CPTmp" + utostr(i) + ";");
689           }
690           if (CP->hasProperty(SDNPHasChain)) {
691             const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
692             FoldedChains.push_back(std::make_pair("CPInChain",
693                                                   PInfo.getNumResults()));
694             ChainName = "Chain" + ChainSuffix;
695             emitDecl("CPInChain");
696             emitDecl(ChainName);
697             emitCode("SDValue CPInChain;");
698             emitCode("SDValue " + ChainName + ";");
699           }
700           
701           std::string Code = Fn + "(";
702           if (CP->hasAttribute(CPAttrParentAsRoot)) {
703             Code += ParentRootName + ", ";
704           } else {
705             Code += "N, ";
706           }
707           if (CP->hasProperty(SDNPHasChain)) {
708             std::string ParentName(RootName.begin(), RootName.end()-1);
709             Code += ParentName + ", ";
710           }
711           Code += RootName;
712           for (unsigned i = 0; i < NumOps; i++)
713             Code += ", CPTmp" + utostr(i);
714           if (CP->hasProperty(SDNPHasChain))
715             Code += ", CPInChain, Chain" + ChainSuffix;
716           emitCheck(Code + ")");
717         } else if (LeafRec->getName() == "srcvalue") {
718           // Place holder for SRCVALUE nodes. Nothing to do here.
719         } else if (LeafRec->isSubClassOf("ValueType")) {
720           // Make sure this is the specified value type.
721           emitCheck("cast<VTSDNode>(" + RootName +
722                     ")->getVT() == MVT::" + LeafRec->getName());
723         } else if (LeafRec->isSubClassOf("CondCode")) {
724           // Make sure this is the specified cond code.
725           emitCheck("cast<CondCodeSDNode>(" + RootName +
726                     ")->get() == ISD::" + LeafRec->getName());
727         } else {
728 #ifndef NDEBUG
729           Child->dump();
730           cerr << " ";
731 #endif
732           assert(0 && "Unknown leaf type!");
733         }
734         
735         // If there are node predicates for this, emit the calls.
736         for (unsigned i = 0, e = Child->getPredicateFns().size(); i != e; ++i)
737           emitCheck(Child->getPredicateFns()[i] + "(" + RootName +
738                     ".getNode())");
739       } else if (IntInit *II =
740                  dynamic_cast<IntInit*>(Child->getLeafValue())) {
741         emitCheck("isa<ConstantSDNode>(" + RootName + ")");
742         unsigned CTmp = TmpNo++;
743         emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
744                  RootName + ")->getSExtValue();");
745         
746         emitCheck("CN" + utostr(CTmp) + " == "
747                   "INT64_C(" +itostr(II->getValue()) + ")");
748       } else {
749 #ifndef NDEBUG
750         Child->dump();
751 #endif
752         assert(0 && "Unknown leaf type!");
753       }
754     }
755   }
756
757   /// EmitResultCode - Emit the action for a pattern.  Now that it has matched
758   /// we actually have to build a DAG!
759   std::vector<std::string>
760   EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
761                  bool InFlagDecled, bool ResNodeDecled,
762                  bool LikeLeaf = false, bool isRoot = false) {
763     // List of arguments of getTargetNode() or SelectNodeTo().
764     std::vector<std::string> NodeOps;
765     // This is something selected from the pattern we matched.
766     if (!N->getName().empty()) {
767       const std::string &VarName = N->getName();
768       std::string Val = VariableMap[VarName];
769       bool ModifiedVal = false;
770       if (Val.empty()) {
771         cerr << "Variable '" << VarName << " referenced but not defined "
772              << "and not caught earlier!\n";
773         abort();
774       }
775       if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
776         // Already selected this operand, just return the tmpval.
777         NodeOps.push_back(Val);
778         return NodeOps;
779       }
780
781       const ComplexPattern *CP;
782       unsigned ResNo = TmpNo++;
783       if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
784         assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
785         std::string CastType;
786         std::string TmpVar =  "Tmp" + utostr(ResNo);
787         switch (N->getTypeNum(0)) {
788         default:
789           cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
790                << " type as an immediate constant. Aborting\n";
791           abort();
792         case MVT::i1:  CastType = "bool"; break;
793         case MVT::i8:  CastType = "unsigned char"; break;
794         case MVT::i16: CastType = "unsigned short"; break;
795         case MVT::i32: CastType = "unsigned"; break;
796         case MVT::i64: CastType = "uint64_t"; break;
797         }
798         emitCode("SDValue " + TmpVar + 
799                  " = CurDAG->getTargetConstant(((" + CastType +
800                  ") cast<ConstantSDNode>(" + Val + ")->getZExtValue()), " +
801                  getEnumName(N->getTypeNum(0)) + ");");
802         // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
803         // value if used multiple times by this pattern result.
804         Val = TmpVar;
805         ModifiedVal = true;
806         NodeOps.push_back(Val);
807       } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
808         assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
809         std::string TmpVar =  "Tmp" + utostr(ResNo);
810         emitCode("SDValue " + TmpVar + 
811                  " = CurDAG->getTargetConstantFP(*cast<ConstantFPSDNode>(" + 
812                  Val + ")->getConstantFPValue(), cast<ConstantFPSDNode>(" +
813                  Val + ")->getValueType(0));");
814         // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
815         // value if used multiple times by this pattern result.
816         Val = TmpVar;
817         ModifiedVal = true;
818         NodeOps.push_back(Val);
819       } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
820         Record *Op = OperatorMap[N->getName()];
821         // Transform ExternalSymbol to TargetExternalSymbol
822         if (Op && Op->getName() == "externalsym") {
823           std::string TmpVar = "Tmp"+utostr(ResNo);
824           emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
825                    "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
826                    Val + ")->getSymbol(), " +
827                    getEnumName(N->getTypeNum(0)) + ");");
828           // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
829           // this value if used multiple times by this pattern result.
830           Val = TmpVar;
831           ModifiedVal = true;
832         }
833         NodeOps.push_back(Val);
834       } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
835                  || N->getOperator()->getName() == "tglobaltlsaddr")) {
836         Record *Op = OperatorMap[N->getName()];
837         // Transform GlobalAddress to TargetGlobalAddress
838         if (Op && (Op->getName() == "globaladdr" ||
839                    Op->getName() == "globaltlsaddr")) {
840           std::string TmpVar = "Tmp" + utostr(ResNo);
841           emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
842                    "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
843                    ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
844                    ");");
845           // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
846           // this value if used multiple times by this pattern result.
847           Val = TmpVar;
848           ModifiedVal = true;
849         }
850         NodeOps.push_back(Val);
851       } else if (!N->isLeaf()
852                  && (N->getOperator()->getName() == "texternalsym"
853                       || N->getOperator()->getName() == "tconstpool")) {
854         // Do not rewrite the variable name, since we don't generate a new
855         // temporary.
856         NodeOps.push_back(Val);
857       } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
858         for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
859           NodeOps.push_back("CPTmp" + utostr(i));
860         }
861       } else {
862         // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
863         // node even if it isn't one. Don't select it.
864         if (!LikeLeaf) {
865           if (isRoot && N->isLeaf()) {
866             emitCode("ReplaceUses(N, " + Val + ");");
867             emitCode("return NULL;");
868           }
869         }
870         NodeOps.push_back(Val);
871       }
872
873       if (ModifiedVal) {
874         VariableMap[VarName] = Val;
875       }
876       return NodeOps;
877     }
878     if (N->isLeaf()) {
879       // If this is an explicit register reference, handle it.
880       if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
881         unsigned ResNo = TmpNo++;
882         if (DI->getDef()->isSubClassOf("Register")) {
883           emitCode("SDValue Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
884                    getQualifiedName(DI->getDef()) + ", " +
885                    getEnumName(N->getTypeNum(0)) + ");");
886           NodeOps.push_back("Tmp" + utostr(ResNo));
887           return NodeOps;
888         } else if (DI->getDef()->getName() == "zero_reg") {
889           emitCode("SDValue Tmp" + utostr(ResNo) +
890                    " = CurDAG->getRegister(0, " +
891                    getEnumName(N->getTypeNum(0)) + ");");
892           NodeOps.push_back("Tmp" + utostr(ResNo));
893           return NodeOps;
894         }
895       } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
896         unsigned ResNo = TmpNo++;
897         assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
898         emitCode("SDValue Tmp" + utostr(ResNo) + 
899                  " = CurDAG->getTargetConstant(0x" + itohexstr(II->getValue()) +
900                  "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
901         NodeOps.push_back("Tmp" + utostr(ResNo));
902         return NodeOps;
903       }
904     
905 #ifndef NDEBUG
906       N->dump();
907 #endif
908       assert(0 && "Unknown leaf type!");
909       return NodeOps;
910     }
911
912     Record *Op = N->getOperator();
913     if (Op->isSubClassOf("Instruction")) {
914       const CodeGenTarget &CGT = CGP.getTargetInfo();
915       CodeGenInstruction &II = CGT.getInstruction(Op->getName());
916       const DAGInstruction &Inst = CGP.getInstruction(Op);
917       const TreePattern *InstPat = Inst.getPattern();
918       // FIXME: Assume actual pattern comes before "implicit".
919       TreePatternNode *InstPatNode =
920         isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
921                : (InstPat ? InstPat->getTree(0) : NULL);
922       if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
923         InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
924       }
925       bool IsVariadic = isRoot && II.isVariadic;
926       // FIXME: fix how we deal with physical register operands.
927       bool HasImpInputs  = isRoot && Inst.getNumImpOperands() > 0;
928       bool HasImpResults = isRoot && DstRegs.size() > 0;
929       bool NodeHasOptInFlag = isRoot &&
930         PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
931       bool NodeHasInFlag  = isRoot &&
932         PatternHasProperty(Pattern, SDNPInFlag, CGP);
933       bool NodeHasOutFlag = isRoot &&
934         PatternHasProperty(Pattern, SDNPOutFlag, CGP);
935       bool NodeHasChain = InstPatNode &&
936         PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
937       bool InputHasChain = isRoot &&
938         NodeHasProperty(Pattern, SDNPHasChain, CGP);
939       unsigned NumResults = Inst.getNumResults();    
940       unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
941
942       // Record output varargs info.
943       OutputIsVariadic = IsVariadic;
944
945       if (NodeHasOptInFlag) {
946         emitCode("bool HasInFlag = "
947            "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
948       }
949       if (IsVariadic)
950         emitCode("SmallVector<SDValue, 8> Ops" + utostr(OpcNo) + ";");
951
952       // How many results is this pattern expected to produce?
953       unsigned NumPatResults = 0;
954       for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
955         MVT::SimpleValueType VT = Pattern->getTypeNum(i);
956         if (VT != MVT::isVoid && VT != MVT::Flag)
957           NumPatResults++;
958       }
959
960       if (OrigChains.size() > 0) {
961         // The original input chain is being ignored. If it is not just
962         // pointing to the op that's being folded, we should create a
963         // TokenFactor with it and the chain of the folded op as the new chain.
964         // We could potentially be doing multiple levels of folding, in that
965         // case, the TokenFactor can have more operands.
966         emitCode("SmallVector<SDValue, 8> InChains;");
967         for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
968           emitCode("if (" + OrigChains[i].first + ".getNode() != " +
969                    OrigChains[i].second + ".getNode()) {");
970           emitCode("  InChains.push_back(" + OrigChains[i].first + ");");
971           emitCode("}");
972         }
973         emitCode("InChains.push_back(" + ChainName + ");");
974         emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
975                  "&InChains[0], InChains.size());");
976         if (GenDebug) {
977           emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"yellow\");");
978           emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"black\");");
979         }
980       }
981
982       // Loop over all of the operands of the instruction pattern, emitting code
983       // to fill them all in.  The node 'N' usually has number children equal to
984       // the number of input operands of the instruction.  However, in cases
985       // where there are predicate operands for an instruction, we need to fill
986       // in the 'execute always' values.  Match up the node operands to the
987       // instruction operands to do this.
988       std::vector<std::string> AllOps;
989       for (unsigned ChildNo = 0, InstOpNo = NumResults;
990            InstOpNo != II.OperandList.size(); ++InstOpNo) {
991         std::vector<std::string> Ops;
992         
993         // Determine what to emit for this operand.
994         Record *OperandNode = II.OperandList[InstOpNo].Rec;
995         if ((OperandNode->isSubClassOf("PredicateOperand") ||
996              OperandNode->isSubClassOf("OptionalDefOperand")) &&
997             !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
998           // This is a predicate or optional def operand; emit the
999           // 'default ops' operands.
1000           const DAGDefaultOperand &DefaultOp =
1001             CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
1002           for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
1003             Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
1004                                  InFlagDecled, ResNodeDecled);
1005             AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1006           }
1007         } else {
1008           // Otherwise this is a normal operand or a predicate operand without
1009           // 'execute always'; emit it.
1010           Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
1011                                InFlagDecled, ResNodeDecled);
1012           AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1013           ++ChildNo;
1014         }
1015       }
1016
1017       // Emit all the chain and CopyToReg stuff.
1018       bool ChainEmitted = NodeHasChain;
1019       if (NodeHasInFlag || HasImpInputs)
1020         EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1021                              InFlagDecled, ResNodeDecled, true);
1022       if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
1023         if (!InFlagDecled) {
1024           emitCode("SDValue InFlag(0, 0);");
1025           InFlagDecled = true;
1026         }
1027         if (NodeHasOptInFlag) {
1028           emitCode("if (HasInFlag) {");
1029           emitCode("  InFlag = N.getOperand(N.getNumOperands()-1);");
1030           emitCode("}");
1031         }
1032       }
1033
1034       unsigned ResNo = TmpNo++;
1035
1036       unsigned OpsNo = OpcNo;
1037       std::string CodePrefix;
1038       bool ChainAssignmentNeeded = NodeHasChain && !isRoot;
1039       std::deque<std::string> After;
1040       std::string NodeName;
1041       if (!isRoot) {
1042         NodeName = "Tmp" + utostr(ResNo);
1043         CodePrefix = "SDValue " + NodeName + "(";
1044       } else {
1045         NodeName = "ResNode";
1046         if (!ResNodeDecled) {
1047           CodePrefix = "SDNode *" + NodeName + " = ";
1048           ResNodeDecled = true;
1049         } else
1050           CodePrefix = NodeName + " = ";
1051       }
1052
1053       std::string Code = "Opc" + utostr(OpcNo);
1054
1055       emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1056
1057       // Output order: results, chain, flags
1058       // Result types.
1059       if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1060         Code += ", VT" + utostr(VTNo);
1061         emitVT(getEnumName(N->getTypeNum(0)));
1062       }
1063       // Add types for implicit results in physical registers, scheduler will
1064       // care of adding copyfromreg nodes.
1065       for (unsigned i = 0; i < NumDstRegs; i++) {
1066         Record *RR = DstRegs[i];
1067         if (RR->isSubClassOf("Register")) {
1068           MVT::SimpleValueType RVT = getRegisterValueType(RR, CGT);
1069           Code += ", " + getEnumName(RVT);
1070         }
1071       }
1072       if (NodeHasChain)
1073         Code += ", MVT::Other";
1074       if (NodeHasOutFlag)
1075         Code += ", MVT::Flag";
1076
1077       // Inputs.
1078       if (IsVariadic) {
1079         for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1080           emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1081         AllOps.clear();
1082
1083         // Figure out whether any operands at the end of the op list are not
1084         // part of the variable section.
1085         std::string EndAdjust;
1086         if (NodeHasInFlag || HasImpInputs)
1087           EndAdjust = "-1";  // Always has one flag.
1088         else if (NodeHasOptInFlag)
1089           EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1090
1091         emitCode("for (unsigned i = NumInputRootOps + " + utostr(NodeHasChain) +
1092                  ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1093
1094         emitCode("  Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
1095         emitCode("}");
1096       }
1097
1098       // Generate MemOperandSDNodes nodes for each memory accesses covered by 
1099       // this pattern.
1100       if (II.isSimpleLoad | II.mayLoad | II.mayStore) {
1101         std::vector<std::string>::const_iterator mi, mie;
1102         for (mi = LSI.begin(), mie = LSI.end(); mi != mie; ++mi) {
1103           std::string LSIName = "LSI_" + *mi;
1104           emitCode("SDValue " + LSIName + " = "
1105                    "CurDAG->getMemOperand(cast<MemSDNode>(" +
1106                    *mi + ")->getMemOperand());");
1107           if (GenDebug) {
1108             emitCode("CurDAG->setSubgraphColor(" + LSIName +".getNode(), \"yellow\");");
1109             emitCode("CurDAG->setSubgraphColor(" + LSIName +".getNode(), \"black\");");
1110           }
1111           if (IsVariadic)
1112             emitCode("Ops" + utostr(OpsNo) + ".push_back(" + LSIName + ");");
1113           else
1114             AllOps.push_back(LSIName);
1115         }
1116       }
1117
1118       if (NodeHasChain) {
1119         if (IsVariadic)
1120           emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1121         else
1122           AllOps.push_back(ChainName);
1123       }
1124
1125       if (IsVariadic) {
1126         if (NodeHasInFlag || HasImpInputs)
1127           emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1128         else if (NodeHasOptInFlag) {
1129           emitCode("if (HasInFlag)");
1130           emitCode("  Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1131         }
1132         Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1133           ".size()";
1134       } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1135         AllOps.push_back("InFlag");
1136
1137       unsigned NumOps = AllOps.size();
1138       if (NumOps) {
1139         if (!NodeHasOptInFlag && NumOps < 4) {
1140           for (unsigned i = 0; i != NumOps; ++i)
1141             Code += ", " + AllOps[i];
1142         } else {
1143           std::string OpsCode = "SDValue Ops" + utostr(OpsNo) + "[] = { ";
1144           for (unsigned i = 0; i != NumOps; ++i) {
1145             OpsCode += AllOps[i];
1146             if (i != NumOps-1)
1147               OpsCode += ", ";
1148           }
1149           emitCode(OpsCode + " };");
1150           Code += ", Ops" + utostr(OpsNo) + ", ";
1151           if (NodeHasOptInFlag) {
1152             Code += "HasInFlag ? ";
1153             Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1154           } else
1155             Code += utostr(NumOps);
1156         }
1157       }
1158           
1159       if (!isRoot)
1160         Code += "), 0";
1161
1162       std::vector<std::string> ReplaceFroms;
1163       std::vector<std::string> ReplaceTos;
1164       if (!isRoot) {
1165         NodeOps.push_back("Tmp" + utostr(ResNo));
1166       } else {
1167
1168       if (NodeHasOutFlag) {
1169         if (!InFlagDecled) {
1170           After.push_back("SDValue InFlag(ResNode, " + 
1171                           utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1172                           ");");
1173           InFlagDecled = true;
1174         } else
1175           After.push_back("InFlag = SDValue(ResNode, " + 
1176                           utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1177                           ");");
1178       }
1179
1180       if (FoldedChains.size() > 0) {
1181         std::string Code;
1182         for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
1183           ReplaceFroms.push_back("SDValue(" +
1184                                  FoldedChains[j].first + ".getNode(), " +
1185                                  utostr(FoldedChains[j].second) +
1186                                  ")");
1187           ReplaceTos.push_back("SDValue(ResNode, " +
1188                                utostr(NumResults+NumDstRegs) + ")");
1189         }
1190       }
1191
1192       if (NodeHasOutFlag) {
1193         if (FoldedFlag.first != "") {
1194           ReplaceFroms.push_back("SDValue(" + FoldedFlag.first + ".getNode(), " +
1195                                  utostr(FoldedFlag.second) + ")");
1196           ReplaceTos.push_back("InFlag");
1197         } else {
1198           assert(NodeHasProperty(Pattern, SDNPOutFlag, CGP));
1199           ReplaceFroms.push_back("SDValue(N.getNode(), " +
1200                                  utostr(NumPatResults + (unsigned)InputHasChain)
1201                                  + ")");
1202           ReplaceTos.push_back("InFlag");
1203         }
1204       }
1205
1206       if (!ReplaceFroms.empty() && InputHasChain) {
1207         ReplaceFroms.push_back("SDValue(N.getNode(), " +
1208                                utostr(NumPatResults) + ")");
1209         ReplaceTos.push_back("SDValue(" + ChainName + ".getNode(), " +
1210                              ChainName + ".getResNo()" + ")");
1211         ChainAssignmentNeeded |= NodeHasChain;
1212       }
1213
1214       // User does not expect the instruction would produce a chain!
1215       if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1216         ;
1217       } else if (InputHasChain && !NodeHasChain) {
1218         // One of the inner node produces a chain.
1219         if (NodeHasOutFlag) {
1220           ReplaceFroms.push_back("SDValue(N.getNode(), " +
1221                                  utostr(NumPatResults+1) +
1222                                  ")");
1223           ReplaceTos.push_back("SDValue(ResNode, N.getResNo()-1)");
1224         }
1225         ReplaceFroms.push_back("SDValue(N.getNode(), " +
1226                                utostr(NumPatResults) + ")");
1227         ReplaceTos.push_back(ChainName);
1228       }
1229       }
1230
1231       if (ChainAssignmentNeeded) {
1232         // Remember which op produces the chain.
1233         std::string ChainAssign;
1234         if (!isRoot)
1235           ChainAssign = ChainName + " = SDValue(" + NodeName +
1236                         ".getNode(), " + utostr(NumResults+NumDstRegs) + ");";
1237         else
1238           ChainAssign = ChainName + " = SDValue(" + NodeName +
1239                         ", " + utostr(NumResults+NumDstRegs) + ");";
1240
1241         After.push_front(ChainAssign);
1242       }
1243
1244       if (ReplaceFroms.size() == 1) {
1245         After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1246                         ReplaceTos[0] + ");");
1247       } else if (!ReplaceFroms.empty()) {
1248         After.push_back("const SDValue Froms[] = {");
1249         for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1250           After.push_back("  " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1251         After.push_back("};");
1252         After.push_back("const SDValue Tos[] = {");
1253         for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1254           After.push_back("  " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1255         After.push_back("};");
1256         After.push_back("ReplaceUses(Froms, Tos, " +
1257                         itostr(ReplaceFroms.size()) + ");");
1258       }
1259
1260       // We prefer to use SelectNodeTo since it avoids allocation when
1261       // possible and it avoids CSE map recalculation for the node's
1262       // users, however it's tricky to use in a non-root context.
1263       //
1264       // We also don't use if the pattern replacement is being used to
1265       // jettison a chain result, since morphing the node in place
1266       // would leave users of the chain dangling.
1267       //
1268       if (!isRoot || (InputHasChain && !NodeHasChain)) {
1269         Code = "CurDAG->getTargetNode(" + Code;
1270       } else {
1271         Code = "CurDAG->SelectNodeTo(N.getNode(), " + Code;
1272       }
1273       if (isRoot) {
1274         if (After.empty())
1275           CodePrefix = "return ";
1276         else
1277           After.push_back("return ResNode;");
1278       }
1279
1280       emitCode(CodePrefix + Code + ");");
1281
1282       if (GenDebug) {
1283         if (!isRoot) {
1284           emitCode("CurDAG->setSubgraphColor(" + NodeName +".getNode(), \"yellow\");");
1285           emitCode("CurDAG->setSubgraphColor(" + NodeName +".getNode(), \"black\");");
1286         }
1287         else {
1288           emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"yellow\");");
1289           emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"black\");");
1290         }
1291       }
1292
1293       for (unsigned i = 0, e = After.size(); i != e; ++i)
1294         emitCode(After[i]);
1295
1296       return NodeOps;
1297     }
1298     if (Op->isSubClassOf("SDNodeXForm")) {
1299       assert(N->getNumChildren() == 1 && "node xform should have one child!");
1300       // PatLeaf node - the operand may or may not be a leaf node. But it should
1301       // behave like one.
1302       std::vector<std::string> Ops =
1303         EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1304                        ResNodeDecled, true);
1305       unsigned ResNo = TmpNo++;
1306       emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1307                + "(" + Ops.back() + ".getNode());");
1308       NodeOps.push_back("Tmp" + utostr(ResNo));
1309       if (isRoot)
1310         emitCode("return Tmp" + utostr(ResNo) + ".getNode();");
1311       return NodeOps;
1312     }
1313
1314     N->dump();
1315     cerr << "\n";
1316     throw std::string("Unknown node in result pattern!");
1317   }
1318
1319   /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1320   /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that 
1321   /// 'Pat' may be missing types.  If we find an unresolved type to add a check
1322   /// for, this returns true otherwise false if Pat has all types.
1323   bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1324                           const std::string &Prefix, bool isRoot = false) {
1325     // Did we find one?
1326     if (Pat->getExtTypes() != Other->getExtTypes()) {
1327       // Move a type over from 'other' to 'pat'.
1328       Pat->setTypes(Other->getExtTypes());
1329       // The top level node type is checked outside of the select function.
1330       if (!isRoot)
1331         emitCheck(Prefix + ".getNode()->getValueType(0) == " +
1332                   getName(Pat->getTypeNum(0)));
1333       return true;
1334     }
1335   
1336     unsigned OpNo =
1337       (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
1338     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1339       if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1340                              Prefix + utostr(OpNo)))
1341         return true;
1342     return false;
1343   }
1344
1345 private:
1346   /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1347   /// being built.
1348   void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1349                             bool &ChainEmitted, bool &InFlagDecled,
1350                             bool &ResNodeDecled, bool isRoot = false) {
1351     const CodeGenTarget &T = CGP.getTargetInfo();
1352     unsigned OpNo =
1353       (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1354     bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
1355     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1356       TreePatternNode *Child = N->getChild(i);
1357       if (!Child->isLeaf()) {
1358         EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1359                              InFlagDecled, ResNodeDecled);
1360       } else {
1361         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1362           if (!Child->getName().empty()) {
1363             std::string Name = RootName + utostr(OpNo);
1364             if (Duplicates.find(Name) != Duplicates.end())
1365               // A duplicate! Do not emit a copy for this node.
1366               continue;
1367           }
1368
1369           Record *RR = DI->getDef();
1370           if (RR->isSubClassOf("Register")) {
1371             MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
1372             if (RVT == MVT::Flag) {
1373               if (!InFlagDecled) {
1374                 emitCode("SDValue InFlag = " + RootName + utostr(OpNo) + ";");
1375                 InFlagDecled = true;
1376               } else
1377                 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1378             } else {
1379               if (!ChainEmitted) {
1380                 emitCode("SDValue Chain = CurDAG->getEntryNode();");
1381                 ChainName = "Chain";
1382                 ChainEmitted = true;
1383               }
1384               if (!InFlagDecled) {
1385                 emitCode("SDValue InFlag(0, 0);");
1386                 InFlagDecled = true;
1387               }
1388               std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1389               emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
1390                        ", " + getQualifiedName(RR) +
1391                        ", " +  RootName + utostr(OpNo) + ", InFlag).getNode();");
1392               ResNodeDecled = true;
1393               emitCode(ChainName + " = SDValue(ResNode, 0);");
1394               emitCode("InFlag = SDValue(ResNode, 1);");
1395             }
1396           }
1397         }
1398       }
1399     }
1400
1401     if (HasInFlag) {
1402       if (!InFlagDecled) {
1403         emitCode("SDValue InFlag = " + RootName +
1404                ".getOperand(" + utostr(OpNo) + ");");
1405         InFlagDecled = true;
1406       } else
1407         emitCode("InFlag = " + RootName +
1408                ".getOperand(" + utostr(OpNo) + ");");
1409     }
1410   }
1411 };
1412
1413 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1414 /// stream to match the pattern, and generate the code for the match if it
1415 /// succeeds.  Returns true if the pattern is not guaranteed to match.
1416 void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
1417                   std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1418                                            std::set<std::string> &GeneratedDecl,
1419                                         std::vector<std::string> &TargetOpcodes,
1420                                             std::vector<std::string> &TargetVTs,
1421                                             bool &OutputIsVariadic,
1422                                             unsigned &NumInputRootOps) {
1423   OutputIsVariadic = false;
1424   NumInputRootOps = 0;
1425
1426   PatternCodeEmitter Emitter(CGP, Pattern.getPredicateCheck(),
1427                              Pattern.getSrcPattern(), Pattern.getDstPattern(),
1428                              GeneratedCode, GeneratedDecl,
1429                              TargetOpcodes, TargetVTs,
1430                              OutputIsVariadic, NumInputRootOps);
1431
1432   // Emit the matcher, capturing named arguments in VariableMap.
1433   bool FoundChain = false;
1434   Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1435
1436   // TP - Get *SOME* tree pattern, we don't care which.
1437   TreePattern &TP = *CGP.pf_begin()->second;
1438   
1439   // At this point, we know that we structurally match the pattern, but the
1440   // types of the nodes may not match.  Figure out the fewest number of type 
1441   // comparisons we need to emit.  For example, if there is only one integer
1442   // type supported by a target, there should be no type comparisons at all for
1443   // integer patterns!
1444   //
1445   // To figure out the fewest number of type checks needed, clone the pattern,
1446   // remove the types, then perform type inference on the pattern as a whole.
1447   // If there are unresolved types, emit an explicit check for those types,
1448   // apply the type to the tree, then rerun type inference.  Iterate until all
1449   // types are resolved.
1450   //
1451   TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1452   RemoveAllTypes(Pat);
1453   
1454   do {
1455     // Resolve/propagate as many types as possible.
1456     try {
1457       bool MadeChange = true;
1458       while (MadeChange)
1459         MadeChange = Pat->ApplyTypeConstraints(TP,
1460                                                true/*Ignore reg constraints*/);
1461     } catch (...) {
1462       assert(0 && "Error: could not find consistent types for something we"
1463              " already decided was ok!");
1464       abort();
1465     }
1466
1467     // Insert a check for an unresolved type and add it to the tree.  If we find
1468     // an unresolved type to add a check for, this returns true and we iterate,
1469     // otherwise we are done.
1470   } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1471
1472   Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
1473                          false, false, false, true);
1474   delete Pat;
1475 }
1476
1477 /// EraseCodeLine - Erase one code line from all of the patterns.  If removing
1478 /// a line causes any of them to be empty, remove them and return true when
1479 /// done.
1480 static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*, 
1481                           std::vector<std::pair<unsigned, std::string> > > >
1482                           &Patterns) {
1483   bool ErasedPatterns = false;
1484   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1485     Patterns[i].second.pop_back();
1486     if (Patterns[i].second.empty()) {
1487       Patterns.erase(Patterns.begin()+i);
1488       --i; --e;
1489       ErasedPatterns = true;
1490     }
1491   }
1492   return ErasedPatterns;
1493 }
1494
1495 /// EmitPatterns - Emit code for at least one pattern, but try to group common
1496 /// code together between the patterns.
1497 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*, 
1498                               std::vector<std::pair<unsigned, std::string> > > >
1499                                   &Patterns, unsigned Indent,
1500                                   std::ostream &OS) {
1501   typedef std::pair<unsigned, std::string> CodeLine;
1502   typedef std::vector<CodeLine> CodeList;
1503   typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
1504   
1505   if (Patterns.empty()) return;
1506   
1507   // Figure out how many patterns share the next code line.  Explicitly copy
1508   // FirstCodeLine so that we don't invalidate a reference when changing
1509   // Patterns.
1510   const CodeLine FirstCodeLine = Patterns.back().second.back();
1511   unsigned LastMatch = Patterns.size()-1;
1512   while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1513     --LastMatch;
1514   
1515   // If not all patterns share this line, split the list into two pieces.  The
1516   // first chunk will use this line, the second chunk won't.
1517   if (LastMatch != 0) {
1518     PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1519     PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1520     
1521     // FIXME: Emit braces?
1522     if (Shared.size() == 1) {
1523       const PatternToMatch &Pattern = *Shared.back().first;
1524       OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1525       Pattern.getSrcPattern()->print(OS);
1526       OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1527       Pattern.getDstPattern()->print(OS);
1528       OS << "\n";
1529       unsigned AddedComplexity = Pattern.getAddedComplexity();
1530       OS << std::string(Indent, ' ') << "// Pattern complexity = "
1531          << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1532          << "  cost = "
1533          << getResultPatternCost(Pattern.getDstPattern(), CGP)
1534          << "  size = "
1535          << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1536     }
1537     if (FirstCodeLine.first != 1) {
1538       OS << std::string(Indent, ' ') << "{\n";
1539       Indent += 2;
1540     }
1541     EmitPatterns(Shared, Indent, OS);
1542     if (FirstCodeLine.first != 1) {
1543       Indent -= 2;
1544       OS << std::string(Indent, ' ') << "}\n";
1545     }
1546     
1547     if (Other.size() == 1) {
1548       const PatternToMatch &Pattern = *Other.back().first;
1549       OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1550       Pattern.getSrcPattern()->print(OS);
1551       OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1552       Pattern.getDstPattern()->print(OS);
1553       OS << "\n";
1554       unsigned AddedComplexity = Pattern.getAddedComplexity();
1555       OS << std::string(Indent, ' ') << "// Pattern complexity = "
1556          << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1557          << "  cost = "
1558          << getResultPatternCost(Pattern.getDstPattern(), CGP)
1559          << "  size = "
1560          << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1561     }
1562     EmitPatterns(Other, Indent, OS);
1563     return;
1564   }
1565   
1566   // Remove this code from all of the patterns that share it.
1567   bool ErasedPatterns = EraseCodeLine(Patterns);
1568   
1569   bool isPredicate = FirstCodeLine.first == 1;
1570   
1571   // Otherwise, every pattern in the list has this line.  Emit it.
1572   if (!isPredicate) {
1573     // Normal code.
1574     OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1575   } else {
1576     OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1577     
1578     // If the next code line is another predicate, and if all of the pattern
1579     // in this group share the same next line, emit it inline now.  Do this
1580     // until we run out of common predicates.
1581     while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1582       // Check that all of fhe patterns in Patterns end with the same predicate.
1583       bool AllEndWithSamePredicate = true;
1584       for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1585         if (Patterns[i].second.back() != Patterns.back().second.back()) {
1586           AllEndWithSamePredicate = false;
1587           break;
1588         }
1589       // If all of the predicates aren't the same, we can't share them.
1590       if (!AllEndWithSamePredicate) break;
1591       
1592       // Otherwise we can.  Emit it shared now.
1593       OS << " &&\n" << std::string(Indent+4, ' ')
1594          << Patterns.back().second.back().second;
1595       ErasedPatterns = EraseCodeLine(Patterns);
1596     }
1597     
1598     OS << ") {\n";
1599     Indent += 2;
1600   }
1601   
1602   EmitPatterns(Patterns, Indent, OS);
1603   
1604   if (isPredicate)
1605     OS << std::string(Indent-2, ' ') << "}\n";
1606 }
1607
1608 static std::string getLegalCName(std::string OpName) {
1609   std::string::size_type pos = OpName.find("::");
1610   if (pos != std::string::npos)
1611     OpName.replace(pos, 2, "_");
1612   return OpName;
1613 }
1614
1615 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1616   const CodeGenTarget &Target = CGP.getTargetInfo();
1617   
1618   // Get the namespace to insert instructions into.
1619   std::string InstNS = Target.getInstNamespace();
1620   if (!InstNS.empty()) InstNS += "::";
1621   
1622   // Group the patterns by their top-level opcodes.
1623   std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
1624   // All unique target node emission functions.
1625   std::map<std::string, unsigned> EmitFunctions;
1626   for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1627        E = CGP.ptm_end(); I != E; ++I) {
1628     const PatternToMatch &Pattern = *I;
1629
1630     TreePatternNode *Node = Pattern.getSrcPattern();
1631     if (!Node->isLeaf()) {
1632       PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
1633         push_back(&Pattern);
1634     } else {
1635       const ComplexPattern *CP;
1636       if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
1637         PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
1638           push_back(&Pattern);
1639       } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
1640         std::vector<Record*> OpNodes = CP->getRootNodes();
1641         for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
1642           PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1643             .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
1644                     &Pattern);
1645         }
1646       } else {
1647         cerr << "Unrecognized opcode '";
1648         Node->dump();
1649         cerr << "' on tree pattern '";
1650         cerr << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
1651         exit(1);
1652       }
1653     }
1654   }
1655
1656   // For each opcode, there might be multiple select functions, one per
1657   // ValueType of the node (or its first operand if it doesn't produce a
1658   // non-chain result.
1659   std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1660
1661   // Emit one Select_* method for each top-level opcode.  We do this instead of
1662   // emitting one giant switch statement to support compilers where this will
1663   // result in the recursive functions taking less stack space.
1664   for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1665          PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1666        PBOI != E; ++PBOI) {
1667     const std::string &OpName = PBOI->first;
1668     std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
1669     assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1670
1671     // Split them into groups by type.
1672     std::map<MVT::SimpleValueType,
1673              std::vector<const PatternToMatch*> > PatternsByType;
1674     for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
1675       const PatternToMatch *Pat = PatternsOfOp[i];
1676       TreePatternNode *SrcPat = Pat->getSrcPattern();
1677       PatternsByType[SrcPat->getTypeNum(0)].push_back(Pat);
1678     }
1679
1680     for (std::map<MVT::SimpleValueType,
1681                   std::vector<const PatternToMatch*> >::iterator
1682            II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1683          ++II) {
1684       MVT::SimpleValueType OpVT = II->first;
1685       std::vector<const PatternToMatch*> &Patterns = II->second;
1686       typedef std::pair<unsigned, std::string> CodeLine;
1687       typedef std::vector<CodeLine> CodeList;
1688       typedef CodeList::iterator CodeListI;
1689     
1690       std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
1691       std::vector<std::vector<std::string> > PatternOpcodes;
1692       std::vector<std::vector<std::string> > PatternVTs;
1693       std::vector<std::set<std::string> > PatternDecls;
1694       std::vector<bool> OutputIsVariadicFlags;
1695       std::vector<unsigned> NumInputRootOpsCounts;
1696       for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1697         CodeList GeneratedCode;
1698         std::set<std::string> GeneratedDecl;
1699         std::vector<std::string> TargetOpcodes;
1700         std::vector<std::string> TargetVTs;
1701         bool OutputIsVariadic;
1702         unsigned NumInputRootOps;
1703         GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1704                                TargetOpcodes, TargetVTs,
1705                                OutputIsVariadic, NumInputRootOps);
1706         CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1707         PatternDecls.push_back(GeneratedDecl);
1708         PatternOpcodes.push_back(TargetOpcodes);
1709         PatternVTs.push_back(TargetVTs);
1710         OutputIsVariadicFlags.push_back(OutputIsVariadic);
1711         NumInputRootOpsCounts.push_back(NumInputRootOps);
1712       }
1713     
1714       // Factor target node emission code (emitted by EmitResultCode) into
1715       // separate functions. Uniquing and share them among all instruction
1716       // selection routines.
1717       for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1718         CodeList &GeneratedCode = CodeForPatterns[i].second;
1719         std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1720         std::vector<std::string> &TargetVTs = PatternVTs[i];
1721         std::set<std::string> Decls = PatternDecls[i];
1722         bool OutputIsVariadic = OutputIsVariadicFlags[i];
1723         unsigned NumInputRootOps = NumInputRootOpsCounts[i];
1724         std::vector<std::string> AddedInits;
1725         int CodeSize = (int)GeneratedCode.size();
1726         int LastPred = -1;
1727         for (int j = CodeSize-1; j >= 0; --j) {
1728           if (LastPred == -1 && GeneratedCode[j].first == 1)
1729             LastPred = j;
1730           else if (LastPred != -1 && GeneratedCode[j].first == 2)
1731             AddedInits.push_back(GeneratedCode[j].second);
1732         }
1733
1734         std::string CalleeCode = "(const SDValue &N";
1735         std::string CallerCode = "(N";
1736         for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1737           CalleeCode += ", unsigned Opc" + utostr(j);
1738           CallerCode += ", " + TargetOpcodes[j];
1739         }
1740         for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1741           CalleeCode += ", MVT VT" + utostr(j);
1742           CallerCode += ", " + TargetVTs[j];
1743         }
1744         for (std::set<std::string>::iterator
1745                I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1746           std::string Name = *I;
1747           CalleeCode += ", SDValue &" + Name;
1748           CallerCode += ", " + Name;
1749         }
1750
1751         if (OutputIsVariadic) {
1752           CalleeCode += ", unsigned NumInputRootOps";
1753           CallerCode += ", " + utostr(NumInputRootOps);
1754         }
1755
1756         CallerCode += ");";
1757         CalleeCode += ") ";
1758         // Prevent emission routines from being inlined to reduce selection
1759         // routines stack frame sizes.
1760         CalleeCode += "DISABLE_INLINE ";
1761         CalleeCode += "{\n";
1762
1763         for (std::vector<std::string>::const_reverse_iterator
1764                I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1765           CalleeCode += "  " + *I + "\n";
1766
1767         for (int j = LastPred+1; j < CodeSize; ++j)
1768           CalleeCode += "  " + GeneratedCode[j].second + "\n";
1769         for (int j = LastPred+1; j < CodeSize; ++j)
1770           GeneratedCode.pop_back();
1771         CalleeCode += "}\n";
1772
1773         // Uniquing the emission routines.
1774         unsigned EmitFuncNum;
1775         std::map<std::string, unsigned>::iterator EFI =
1776           EmitFunctions.find(CalleeCode);
1777         if (EFI != EmitFunctions.end()) {
1778           EmitFuncNum = EFI->second;
1779         } else {
1780           EmitFuncNum = EmitFunctions.size();
1781           EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1782           OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1783         }
1784
1785         // Replace the emission code within selection routines with calls to the
1786         // emission functions.
1787         if (GenDebug) {
1788           GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N.getNode(), \"red\");"));
1789         }
1790         CallerCode = "SDNode *Result = Emit_" + utostr(EmitFuncNum) + CallerCode;
1791         GeneratedCode.push_back(std::make_pair(3, CallerCode));
1792         if (GenDebug) {
1793           GeneratedCode.push_back(std::make_pair(0, "if(Result) {"));
1794           GeneratedCode.push_back(std::make_pair(0, "  CurDAG->setSubgraphColor(Result, \"yellow\");"));
1795           GeneratedCode.push_back(std::make_pair(0, "  CurDAG->setSubgraphColor(Result, \"black\");"));
1796           GeneratedCode.push_back(std::make_pair(0, "}"));
1797           //GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N.getNode(), \"black\");"));
1798         }
1799         GeneratedCode.push_back(std::make_pair(0, "return Result;"));
1800       }
1801
1802       // Print function.
1803       std::string OpVTStr;
1804       if (OpVT == MVT::iPTR) {
1805         OpVTStr = "_iPTR";
1806       } else if (OpVT == MVT::iPTRAny) {
1807         OpVTStr = "_iPTRAny";
1808       } else if (OpVT == MVT::isVoid) {
1809         // Nodes with a void result actually have a first result type of either
1810         // Other (a chain) or Flag.  Since there is no one-to-one mapping from
1811         // void to this case, we handle it specially here.
1812       } else {
1813         OpVTStr = "_" + getEnumName(OpVT).substr(5);  // Skip 'MVT::'
1814       }
1815       std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1816         OpcodeVTMap.find(OpName);
1817       if (OpVTI == OpcodeVTMap.end()) {
1818         std::vector<std::string> VTSet;
1819         VTSet.push_back(OpVTStr);
1820         OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1821       } else
1822         OpVTI->second.push_back(OpVTStr);
1823
1824       OS << "SDNode *Select_" << getLegalCName(OpName)
1825          << OpVTStr << "(const SDValue &N) {\n";    
1826
1827       // We want to emit all of the matching code now.  However, we want to emit
1828       // the matches in order of minimal cost.  Sort the patterns so the least
1829       // cost one is at the start.
1830       std::stable_sort(CodeForPatterns.begin(), CodeForPatterns.end(),
1831                        PatternSortingPredicate(CGP));
1832
1833       // Scan the code to see if all of the patterns are reachable and if it is
1834       // possible that the last one might not match.
1835       bool mightNotMatch = true;
1836       for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1837         CodeList &GeneratedCode = CodeForPatterns[i].second;
1838         mightNotMatch = false;
1839
1840         for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1841           if (GeneratedCode[j].first == 1) { // predicate.
1842             mightNotMatch = true;
1843             break;
1844           }
1845         }
1846       
1847         // If this pattern definitely matches, and if it isn't the last one, the
1848         // patterns after it CANNOT ever match.  Error out.
1849         if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1850           cerr << "Pattern '";
1851           CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
1852           cerr << "' is impossible to select!\n";
1853           exit(1);
1854         }
1855       }
1856
1857       // Loop through and reverse all of the CodeList vectors, as we will be
1858       // accessing them from their logical front, but accessing the end of a
1859       // vector is more efficient.
1860       for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1861         CodeList &GeneratedCode = CodeForPatterns[i].second;
1862         std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1863       }
1864     
1865       // Next, reverse the list of patterns itself for the same reason.
1866       std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1867     
1868       // Emit all of the patterns now, grouped together to share code.
1869       EmitPatterns(CodeForPatterns, 2, OS);
1870     
1871       // If the last pattern has predicates (which could fail) emit code to
1872       // catch the case where nothing handles a pattern.
1873       if (mightNotMatch) {
1874         OS << "\n";
1875         if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1876             OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1877             OpName != "ISD::INTRINSIC_VOID")
1878           OS << "  CannotYetSelect(N);\n";
1879         else
1880           OS << "  CannotYetSelectIntrinsic(N);\n";
1881
1882         OS << "  return NULL;\n";
1883       }
1884       OS << "}\n\n";
1885     }
1886   }
1887   
1888   // Emit boilerplate.
1889   OS << "SDNode *Select_INLINEASM(SDValue N) {\n"
1890      << "  std::vector<SDValue> Ops(N.getNode()->op_begin(), N.getNode()->op_end());\n"
1891      << "  SelectInlineAsmMemoryOperands(Ops);\n\n"
1892     
1893      << "  std::vector<MVT> VTs;\n"
1894      << "  VTs.push_back(MVT::Other);\n"
1895      << "  VTs.push_back(MVT::Flag);\n"
1896      << "  SDValue New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
1897                  "Ops.size());\n"
1898      << "  return New.getNode();\n"
1899      << "}\n\n";
1900
1901   OS << "SDNode *Select_UNDEF(const SDValue &N) {\n"
1902      << "  return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::IMPLICIT_DEF,\n"
1903      << "                              N.getValueType());\n"
1904      << "}\n\n";
1905
1906   OS << "SDNode *Select_DBG_LABEL(const SDValue &N) {\n"
1907      << "  SDValue Chain = N.getOperand(0);\n"
1908      << "  unsigned C = cast<LabelSDNode>(N)->getLabelID();\n"
1909      << "  SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1910      << "  return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::DBG_LABEL,\n"
1911      << "                              MVT::Other, Tmp, Chain);\n"
1912      << "}\n\n";
1913
1914   OS << "SDNode *Select_EH_LABEL(const SDValue &N) {\n"
1915      << "  SDValue Chain = N.getOperand(0);\n"
1916      << "  unsigned C = cast<LabelSDNode>(N)->getLabelID();\n"
1917      << "  SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1918      << "  return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::EH_LABEL,\n"
1919      << "                              MVT::Other, Tmp, Chain);\n"
1920      << "}\n\n";
1921
1922   OS << "SDNode *Select_DECLARE(const SDValue &N) {\n"
1923      << "  SDValue Chain = N.getOperand(0);\n"
1924      << "  SDValue N1 = N.getOperand(1);\n"
1925      << "  SDValue N2 = N.getOperand(2);\n"
1926      << "  if (!isa<FrameIndexSDNode>(N1) || !isa<GlobalAddressSDNode>(N2)) {\n"
1927      << "    CannotYetSelect(N);\n"
1928      << "  }\n"
1929      << "  int FI = cast<FrameIndexSDNode>(N1)->getIndex();\n"
1930      << "  GlobalValue *GV = cast<GlobalAddressSDNode>(N2)->getGlobal();\n"
1931      << "  SDValue Tmp1 = "
1932      << "CurDAG->getTargetFrameIndex(FI, TLI.getPointerTy());\n"
1933      << "  SDValue Tmp2 = "
1934      << "CurDAG->getTargetGlobalAddress(GV, TLI.getPointerTy());\n"
1935      << "  return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::DECLARE,\n"
1936      << "                              MVT::Other, Tmp1, Tmp2, Chain);\n"
1937      << "}\n\n";
1938
1939   OS << "SDNode *Select_EXTRACT_SUBREG(const SDValue &N) {\n"
1940      << "  SDValue N0 = N.getOperand(0);\n"
1941      << "  SDValue N1 = N.getOperand(1);\n"
1942      << "  unsigned C = cast<ConstantSDNode>(N1)->getZExtValue();\n"
1943      << "  SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1944      << "  return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::EXTRACT_SUBREG,\n"
1945      << "                              N.getValueType(), N0, Tmp);\n"
1946      << "}\n\n";
1947
1948   OS << "SDNode *Select_INSERT_SUBREG(const SDValue &N) {\n"
1949      << "  SDValue N0 = N.getOperand(0);\n"
1950      << "  SDValue N1 = N.getOperand(1);\n"
1951      << "  SDValue N2 = N.getOperand(2);\n"
1952      << "  unsigned C = cast<ConstantSDNode>(N2)->getZExtValue();\n"
1953      << "  SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1954      << "  return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::INSERT_SUBREG,\n"
1955      << "                              N.getValueType(), N0, N1, Tmp);\n"
1956      << "}\n\n";
1957
1958   OS << "// The main instruction selector code.\n"
1959      << "SDNode *SelectCode(SDValue N) {\n"
1960      << "  if (N.isMachineOpcode()) {\n"
1961      << "    return NULL;   // Already selected.\n"
1962      << "  }\n\n"
1963      << "  MVT::SimpleValueType NVT = N.getNode()->getValueType(0).getSimpleVT();\n"
1964      << "  switch (N.getOpcode()) {\n"
1965      << "  default: break;\n"
1966      << "  case ISD::EntryToken:       // These leaves remain the same.\n"
1967      << "  case ISD::MEMOPERAND:\n"
1968      << "  case ISD::BasicBlock:\n"
1969      << "  case ISD::Register:\n"
1970      << "  case ISD::HANDLENODE:\n"
1971      << "  case ISD::TargetConstant:\n"
1972      << "  case ISD::TargetConstantFP:\n"
1973      << "  case ISD::TargetConstantPool:\n"
1974      << "  case ISD::TargetFrameIndex:\n"
1975      << "  case ISD::TargetExternalSymbol:\n"
1976      << "  case ISD::TargetJumpTable:\n"
1977      << "  case ISD::TargetGlobalTLSAddress:\n"
1978      << "  case ISD::TargetGlobalAddress:\n"
1979      << "  case ISD::TokenFactor:\n"
1980      << "  case ISD::CopyFromReg:\n"
1981      << "  case ISD::CopyToReg: {\n"
1982      << "    return NULL;\n"
1983      << "  }\n"
1984      << "  case ISD::AssertSext:\n"
1985      << "  case ISD::AssertZext: {\n"
1986      << "    ReplaceUses(N, N.getOperand(0));\n"
1987      << "    return NULL;\n"
1988      << "  }\n"
1989      << "  case ISD::INLINEASM: return Select_INLINEASM(N);\n"
1990      << "  case ISD::DBG_LABEL: return Select_DBG_LABEL(N);\n"
1991      << "  case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
1992      << "  case ISD::DECLARE: return Select_DECLARE(N);\n"
1993      << "  case ISD::EXTRACT_SUBREG: return Select_EXTRACT_SUBREG(N);\n"
1994      << "  case ISD::INSERT_SUBREG: return Select_INSERT_SUBREG(N);\n"
1995      << "  case ISD::UNDEF: return Select_UNDEF(N);\n";
1996
1997   // Loop over all of the case statements, emiting a call to each method we
1998   // emitted above.
1999   for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
2000          PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
2001        PBOI != E; ++PBOI) {
2002     const std::string &OpName = PBOI->first;
2003     // Potentially multiple versions of select for this opcode. One for each
2004     // ValueType of the node (or its first true operand if it doesn't produce a
2005     // result.
2006     std::map<std::string, std::vector<std::string> >::iterator OpVTI =
2007       OpcodeVTMap.find(OpName);
2008     std::vector<std::string> &OpVTs = OpVTI->second;
2009     OS << "  case " << OpName << ": {\n";
2010     // Keep track of whether we see a pattern that has an iPtr result.
2011     bool HasPtrPattern = false;
2012     bool HasDefaultPattern = false;
2013       
2014     OS << "    switch (NVT) {\n";
2015     for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
2016       std::string &VTStr = OpVTs[i];
2017       if (VTStr.empty()) {
2018         HasDefaultPattern = true;
2019         continue;
2020       }
2021
2022       // If this is a match on iPTR: don't emit it directly, we need special
2023       // code.
2024       if (VTStr == "_iPTR") {
2025         HasPtrPattern = true;
2026         continue;
2027       }
2028       OS << "    case MVT::" << VTStr.substr(1) << ":\n"
2029          << "      return Select_" << getLegalCName(OpName)
2030          << VTStr << "(N);\n";
2031     }
2032     OS << "    default:\n";
2033       
2034     // If there is an iPTR result version of this pattern, emit it here.
2035     if (HasPtrPattern) {
2036       OS << "      if (TLI.getPointerTy() == NVT)\n";
2037       OS << "        return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
2038     }
2039     if (HasDefaultPattern) {
2040       OS << "      return Select_" << getLegalCName(OpName) << "(N);\n";
2041     }
2042     OS << "      break;\n";
2043     OS << "    }\n";
2044     OS << "    break;\n";
2045     OS << "  }\n";
2046   }
2047
2048   OS << "  } // end of big switch.\n\n"
2049      << "  if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
2050      << "      N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
2051      << "      N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
2052      << "    CannotYetSelect(N);\n"
2053      << "  } else {\n"
2054      << "    CannotYetSelectIntrinsic(N);\n"
2055      << "  }\n"
2056      << "  return NULL;\n"
2057      << "}\n\n";
2058
2059   OS << "void CannotYetSelect(SDValue N) DISABLE_INLINE {\n"
2060      << "  cerr << \"Cannot yet select: \";\n"
2061      << "  N.getNode()->dump(CurDAG);\n"
2062      << "  cerr << '\\n';\n"
2063      << "  abort();\n"
2064      << "}\n\n";
2065
2066   OS << "void CannotYetSelectIntrinsic(SDValue N) DISABLE_INLINE {\n"
2067      << "  cerr << \"Cannot yet select: \";\n"
2068      << "  unsigned iid = cast<ConstantSDNode>(N.getOperand("
2069      << "N.getOperand(0).getValueType() == MVT::Other))->getZExtValue();\n"
2070      << "  cerr << \"intrinsic %\"<< "
2071      << "Intrinsic::getName((Intrinsic::ID)iid);\n"
2072      << "  cerr << '\\n';\n"
2073      << "  abort();\n"
2074      << "}\n\n";
2075 }
2076
2077 void DAGISelEmitter::run(std::ostream &OS) {
2078   EmitSourceFileHeader("DAG Instruction Selector for the " +
2079                        CGP.getTargetInfo().getName() + " target", OS);
2080   
2081   OS << "// *** NOTE: This file is #included into the middle of the target\n"
2082      << "// *** instruction selector class.  These functions are really "
2083      << "methods.\n\n";
2084
2085   OS << "// Include standard, target-independent definitions and methods used\n"
2086      << "// by the instruction selector.\n";
2087   OS << "#include <llvm/CodeGen/DAGISelHeader.h>\n\n";
2088   
2089   EmitNodeTransforms(OS);
2090   EmitPredicateFunctions(OS);
2091   
2092   DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
2093   for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
2094        I != E; ++I) {
2095     DOUT << "PATTERN: ";   DEBUG(I->getSrcPattern()->dump());
2096     DOUT << "\nRESULT:  "; DEBUG(I->getDstPattern()->dump());
2097     DOUT << "\n";
2098   }
2099   
2100   // At this point, we have full information about the 'Patterns' we need to
2101   // parse, both implicitly from instructions as well as from explicit pattern
2102   // definitions.  Emit the resultant instruction selector.
2103   EmitInstructionSelector(OS);  
2104   
2105 }