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