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