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