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