4a399cdfc03155bbd695ab7bea8e1ae7edf91ed6
[oota-llvm.git] / utils / TableGen / DAGISelEmitter.cpp
1 //===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This tablegen backend emits a DAG instruction selector.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "DAGISelEmitter.h"
15 #include "Record.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/Debug.h"
18 #include <algorithm>
19 #include <set>
20 using namespace llvm;
21
22 //===----------------------------------------------------------------------===//
23 // Helpers for working with extended types.
24
25 /// FilterVTs - Filter a list of VT's according to a predicate.
26 ///
27 template<typename T>
28 static std::vector<MVT::ValueType> 
29 FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
30   std::vector<MVT::ValueType> Result;
31   for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
32     if (Filter(InVTs[i]))
33       Result.push_back(InVTs[i]);
34   return Result;
35 }
36
37 template<typename T>
38 static std::vector<unsigned char> 
39 FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
40   std::vector<unsigned char> Result;
41   for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
42     if (Filter((MVT::ValueType)InVTs[i]))
43       Result.push_back(InVTs[i]);
44   return Result;
45 }
46
47 static std::vector<unsigned char>
48 ConvertVTs(const std::vector<MVT::ValueType> &InVTs) {
49   std::vector<unsigned char> Result;
50   for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
51       Result.push_back(InVTs[i]);
52   return Result;
53 }
54
55 static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
56                              const std::vector<unsigned char> &RHS) {
57   if (LHS.size() > RHS.size()) return false;
58   for (unsigned i = 0, e = LHS.size(); i != e; ++i)
59     if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
60       return false;
61   return true;
62 }
63
64 /// isExtIntegerVT - Return true if the specified extended value type vector
65 /// contains isInt or an integer value type.
66 static bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
67   assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
68   return EVTs[0] == MVT::isInt || !(FilterEVTs(EVTs, MVT::isInteger).empty());
69 }
70
71 /// isExtFloatingPointVT - Return true if the specified extended value type 
72 /// vector contains isFP or a FP value type.
73 static bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
74   assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
75   return EVTs[0] == MVT::isFP ||
76          !(FilterEVTs(EVTs, MVT::isFloatingPoint).empty());
77 }
78
79 //===----------------------------------------------------------------------===//
80 // SDTypeConstraint implementation
81 //
82
83 SDTypeConstraint::SDTypeConstraint(Record *R) {
84   OperandNo = R->getValueAsInt("OperandNum");
85   
86   if (R->isSubClassOf("SDTCisVT")) {
87     ConstraintType = SDTCisVT;
88     x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
89   } else if (R->isSubClassOf("SDTCisPtrTy")) {
90     ConstraintType = SDTCisPtrTy;
91   } else if (R->isSubClassOf("SDTCisInt")) {
92     ConstraintType = SDTCisInt;
93   } else if (R->isSubClassOf("SDTCisFP")) {
94     ConstraintType = SDTCisFP;
95   } else if (R->isSubClassOf("SDTCisSameAs")) {
96     ConstraintType = SDTCisSameAs;
97     x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
98   } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
99     ConstraintType = SDTCisVTSmallerThanOp;
100     x.SDTCisVTSmallerThanOp_Info.OtherOperandNum = 
101       R->getValueAsInt("OtherOperandNum");
102   } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
103     ConstraintType = SDTCisOpSmallerThanOp;
104     x.SDTCisOpSmallerThanOp_Info.BigOperandNum = 
105       R->getValueAsInt("BigOperandNum");
106   } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
107     ConstraintType = SDTCisIntVectorOfSameSize;
108     x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
109       R->getValueAsInt("OtherOpNum");
110   } else {
111     std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
112     exit(1);
113   }
114 }
115
116 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
117 /// N, which has NumResults results.
118 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
119                                                  TreePatternNode *N,
120                                                  unsigned NumResults) const {
121   assert(NumResults <= 1 &&
122          "We only work with nodes with zero or one result so far!");
123   
124   if (OpNo < NumResults)
125     return N;  // FIXME: need value #
126   else
127     return N->getChild(OpNo-NumResults);
128 }
129
130 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
131 /// constraint to the nodes operands.  This returns true if it makes a
132 /// change, false otherwise.  If a type contradiction is found, throw an
133 /// exception.
134 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
135                                            const SDNodeInfo &NodeInfo,
136                                            TreePattern &TP) const {
137   unsigned NumResults = NodeInfo.getNumResults();
138   assert(NumResults <= 1 &&
139          "We only work with nodes with zero or one result so far!");
140   
141   // Check that the number of operands is sane.
142   if (NodeInfo.getNumOperands() >= 0) {
143     if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
144       TP.error(N->getOperator()->getName() + " node requires exactly " +
145                itostr(NodeInfo.getNumOperands()) + " operands!");
146   }
147
148   const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
149   
150   TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
151   
152   switch (ConstraintType) {
153   default: assert(0 && "Unknown constraint type!");
154   case SDTCisVT:
155     // Operand must be a particular type.
156     return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
157   case SDTCisPtrTy: {
158     // Operand must be same as target pointer type.
159     return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
160   }
161   case SDTCisInt: {
162     // If there is only one integer type supported, this must be it.
163     std::vector<MVT::ValueType> IntVTs =
164       FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
165
166     // If we found exactly one supported integer type, apply it.
167     if (IntVTs.size() == 1)
168       return NodeToApply->UpdateNodeType(IntVTs[0], TP);
169     return NodeToApply->UpdateNodeType(MVT::isInt, TP);
170   }
171   case SDTCisFP: {
172     // If there is only one FP type supported, this must be it.
173     std::vector<MVT::ValueType> FPVTs =
174       FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
175         
176     // If we found exactly one supported FP type, apply it.
177     if (FPVTs.size() == 1)
178       return NodeToApply->UpdateNodeType(FPVTs[0], TP);
179     return NodeToApply->UpdateNodeType(MVT::isFP, TP);
180   }
181   case SDTCisSameAs: {
182     TreePatternNode *OtherNode =
183       getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
184     return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
185            OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
186   }
187   case SDTCisVTSmallerThanOp: {
188     // The NodeToApply must be a leaf node that is a VT.  OtherOperandNum must
189     // have an integer type that is smaller than the VT.
190     if (!NodeToApply->isLeaf() ||
191         !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
192         !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
193                ->isSubClassOf("ValueType"))
194       TP.error(N->getOperator()->getName() + " expects a VT operand!");
195     MVT::ValueType VT =
196      getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
197     if (!MVT::isInteger(VT))
198       TP.error(N->getOperator()->getName() + " VT operand must be integer!");
199     
200     TreePatternNode *OtherNode =
201       getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
202     
203     // It must be integer.
204     bool MadeChange = false;
205     MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
206     
207     // This code only handles nodes that have one type set.  Assert here so
208     // that we can change this if we ever need to deal with multiple value
209     // types at this point.
210     assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
211     if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
212       OtherNode->UpdateNodeType(MVT::Other, TP);  // Throw an error.
213     return false;
214   }
215   case SDTCisOpSmallerThanOp: {
216     TreePatternNode *BigOperand =
217       getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
218
219     // Both operands must be integer or FP, but we don't care which.
220     bool MadeChange = false;
221     
222     // This code does not currently handle nodes which have multiple types,
223     // where some types are integer, and some are fp.  Assert that this is not
224     // the case.
225     assert(!(isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
226              isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
227            !(isExtIntegerInVTs(BigOperand->getExtTypes()) &&
228              isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
229            "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
230     if (isExtIntegerInVTs(NodeToApply->getExtTypes()))
231       MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
232     else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
233       MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
234     if (isExtIntegerInVTs(BigOperand->getExtTypes()))
235       MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
236     else if (isExtFloatingPointInVTs(BigOperand->getExtTypes()))
237       MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
238
239     std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
240     
241     if (isExtIntegerInVTs(NodeToApply->getExtTypes())) {
242       VTs = FilterVTs(VTs, MVT::isInteger);
243     } else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
244       VTs = FilterVTs(VTs, MVT::isFloatingPoint);
245     } else {
246       VTs.clear();
247     }
248
249     switch (VTs.size()) {
250     default:         // Too many VT's to pick from.
251     case 0: break;   // No info yet.
252     case 1: 
253       // Only one VT of this flavor.  Cannot ever satisify the constraints.
254       return NodeToApply->UpdateNodeType(MVT::Other, TP);  // throw
255     case 2:
256       // If we have exactly two possible types, the little operand must be the
257       // small one, the big operand should be the big one.  Common with 
258       // float/double for example.
259       assert(VTs[0] < VTs[1] && "Should be sorted!");
260       MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
261       MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
262       break;
263     }    
264     return MadeChange;
265   }
266   case SDTCisIntVectorOfSameSize: {
267     TreePatternNode *OtherOperand =
268       getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
269                     N, NumResults);
270     if (OtherOperand->hasTypeSet()) {
271       if (!MVT::isVector(OtherOperand->getTypeNum(0)))
272         TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
273       MVT::ValueType IVT = OtherOperand->getTypeNum(0);
274       IVT = MVT::getIntVectorWithNumElements(MVT::getVectorNumElements(IVT));
275       return NodeToApply->UpdateNodeType(IVT, TP);
276     }
277     return false;
278   }
279   }  
280   return false;
281 }
282
283
284 //===----------------------------------------------------------------------===//
285 // SDNodeInfo implementation
286 //
287 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
288   EnumName    = R->getValueAsString("Opcode");
289   SDClassName = R->getValueAsString("SDClass");
290   Record *TypeProfile = R->getValueAsDef("TypeProfile");
291   NumResults = TypeProfile->getValueAsInt("NumResults");
292   NumOperands = TypeProfile->getValueAsInt("NumOperands");
293   
294   // Parse the properties.
295   Properties = 0;
296   std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
297   for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
298     if (PropList[i]->getName() == "SDNPCommutative") {
299       Properties |= 1 << SDNPCommutative;
300     } else if (PropList[i]->getName() == "SDNPAssociative") {
301       Properties |= 1 << SDNPAssociative;
302     } else if (PropList[i]->getName() == "SDNPHasChain") {
303       Properties |= 1 << SDNPHasChain;
304     } else if (PropList[i]->getName() == "SDNPOutFlag") {
305       Properties |= 1 << SDNPOutFlag;
306     } else if (PropList[i]->getName() == "SDNPInFlag") {
307       Properties |= 1 << SDNPInFlag;
308     } else if (PropList[i]->getName() == "SDNPOptInFlag") {
309       Properties |= 1 << SDNPOptInFlag;
310     } else {
311       std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
312                 << "' on node '" << R->getName() << "'!\n";
313       exit(1);
314     }
315   }
316   
317   
318   // Parse the type constraints.
319   std::vector<Record*> ConstraintList =
320     TypeProfile->getValueAsListOfDefs("Constraints");
321   TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
322 }
323
324 //===----------------------------------------------------------------------===//
325 // TreePatternNode implementation
326 //
327
328 TreePatternNode::~TreePatternNode() {
329 #if 0 // FIXME: implement refcounted tree nodes!
330   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
331     delete getChild(i);
332 #endif
333 }
334
335 /// UpdateNodeType - Set the node type of N to VT if VT contains
336 /// information.  If N already contains a conflicting type, then throw an
337 /// exception.  This returns true if any information was updated.
338 ///
339 bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
340                                      TreePattern &TP) {
341   assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
342   
343   if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs)) 
344     return false;
345   if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
346     setTypes(ExtVTs);
347     return true;
348   }
349
350   if (getExtTypeNum(0) == MVT::iPTR) {
351     if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::isInt)
352       return false;
353     if (isExtIntegerInVTs(ExtVTs)) {
354       std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, MVT::isInteger);
355       if (FVTs.size()) {
356         setTypes(ExtVTs);
357         return true;
358       }
359     }
360   }
361   
362   if (ExtVTs[0] == MVT::isInt && isExtIntegerInVTs(getExtTypes())) {
363     assert(hasTypeSet() && "should be handled above!");
364     std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
365     if (getExtTypes() == FVTs)
366       return false;
367     setTypes(FVTs);
368     return true;
369   }
370   if (ExtVTs[0] == MVT::iPTR && isExtIntegerInVTs(getExtTypes())) {
371     //assert(hasTypeSet() && "should be handled above!");
372     std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
373     if (getExtTypes() == FVTs)
374       return false;
375     if (FVTs.size()) {
376       setTypes(FVTs);
377       return true;
378     }
379   }      
380   if (ExtVTs[0] == MVT::isFP  && isExtFloatingPointInVTs(getExtTypes())) {
381     assert(hasTypeSet() && "should be handled above!");
382     std::vector<unsigned char> FVTs =
383       FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
384     if (getExtTypes() == FVTs)
385       return false;
386     setTypes(FVTs);
387     return true;
388   }
389       
390   // If we know this is an int or fp type, and we are told it is a specific one,
391   // take the advice.
392   //
393   // Similarly, we should probably set the type here to the intersection of
394   // {isInt|isFP} and ExtVTs
395   if ((getExtTypeNum(0) == MVT::isInt && isExtIntegerInVTs(ExtVTs)) ||
396       (getExtTypeNum(0) == MVT::isFP  && isExtFloatingPointInVTs(ExtVTs))) {
397     setTypes(ExtVTs);
398     return true;
399   }
400   if (getExtTypeNum(0) == MVT::isInt && ExtVTs[0] == MVT::iPTR) {
401     setTypes(ExtVTs);
402     return true;
403   }
404
405   if (isLeaf()) {
406     dump();
407     std::cerr << " ";
408     TP.error("Type inference contradiction found in node!");
409   } else {
410     TP.error("Type inference contradiction found in node " + 
411              getOperator()->getName() + "!");
412   }
413   return true; // unreachable
414 }
415
416
417 void TreePatternNode::print(std::ostream &OS) const {
418   if (isLeaf()) {
419     OS << *getLeafValue();
420   } else {
421     OS << "(" << getOperator()->getName();
422   }
423   
424   // FIXME: At some point we should handle printing all the value types for 
425   // nodes that are multiply typed.
426   switch (getExtTypeNum(0)) {
427   case MVT::Other: OS << ":Other"; break;
428   case MVT::isInt: OS << ":isInt"; break;
429   case MVT::isFP : OS << ":isFP"; break;
430   case MVT::isUnknown: ; /*OS << ":?";*/ break;
431   case MVT::iPTR:  OS << ":iPTR"; break;
432   default:  OS << ":" << getTypeNum(0); break;
433   }
434
435   if (!isLeaf()) {
436     if (getNumChildren() != 0) {
437       OS << " ";
438       getChild(0)->print(OS);
439       for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
440         OS << ", ";
441         getChild(i)->print(OS);
442       }
443     }
444     OS << ")";
445   }
446   
447   if (!PredicateFn.empty())
448     OS << "<<P:" << PredicateFn << ">>";
449   if (TransformFn)
450     OS << "<<X:" << TransformFn->getName() << ">>";
451   if (!getName().empty())
452     OS << ":$" << getName();
453
454 }
455 void TreePatternNode::dump() const {
456   print(std::cerr);
457 }
458
459 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
460 /// the specified node.  For this comparison, all of the state of the node
461 /// is considered, except for the assigned name.  Nodes with differing names
462 /// that are otherwise identical are considered isomorphic.
463 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
464   if (N == this) return true;
465   if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
466       getPredicateFn() != N->getPredicateFn() ||
467       getTransformFn() != N->getTransformFn())
468     return false;
469
470   if (isLeaf()) {
471     if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
472       if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
473         return DI->getDef() == NDI->getDef();
474     return getLeafValue() == N->getLeafValue();
475   }
476   
477   if (N->getOperator() != getOperator() ||
478       N->getNumChildren() != getNumChildren()) return false;
479   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
480     if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
481       return false;
482   return true;
483 }
484
485 /// clone - Make a copy of this tree and all of its children.
486 ///
487 TreePatternNode *TreePatternNode::clone() const {
488   TreePatternNode *New;
489   if (isLeaf()) {
490     New = new TreePatternNode(getLeafValue());
491   } else {
492     std::vector<TreePatternNode*> CChildren;
493     CChildren.reserve(Children.size());
494     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
495       CChildren.push_back(getChild(i)->clone());
496     New = new TreePatternNode(getOperator(), CChildren);
497   }
498   New->setName(getName());
499   New->setTypes(getExtTypes());
500   New->setPredicateFn(getPredicateFn());
501   New->setTransformFn(getTransformFn());
502   return New;
503 }
504
505 /// SubstituteFormalArguments - Replace the formal arguments in this tree
506 /// with actual values specified by ArgMap.
507 void TreePatternNode::
508 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
509   if (isLeaf()) return;
510   
511   for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
512     TreePatternNode *Child = getChild(i);
513     if (Child->isLeaf()) {
514       Init *Val = Child->getLeafValue();
515       if (dynamic_cast<DefInit*>(Val) &&
516           static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
517         // We found a use of a formal argument, replace it with its value.
518         Child = ArgMap[Child->getName()];
519         assert(Child && "Couldn't find formal argument!");
520         setChild(i, Child);
521       }
522     } else {
523       getChild(i)->SubstituteFormalArguments(ArgMap);
524     }
525   }
526 }
527
528
529 /// InlinePatternFragments - If this pattern refers to any pattern
530 /// fragments, inline them into place, giving us a pattern without any
531 /// PatFrag references.
532 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
533   if (isLeaf()) return this;  // nothing to do.
534   Record *Op = getOperator();
535   
536   if (!Op->isSubClassOf("PatFrag")) {
537     // Just recursively inline children nodes.
538     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
539       setChild(i, getChild(i)->InlinePatternFragments(TP));
540     return this;
541   }
542
543   // Otherwise, we found a reference to a fragment.  First, look up its
544   // TreePattern record.
545   TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
546   
547   // Verify that we are passing the right number of operands.
548   if (Frag->getNumArgs() != Children.size())
549     TP.error("'" + Op->getName() + "' fragment requires " +
550              utostr(Frag->getNumArgs()) + " operands!");
551
552   TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
553
554   // Resolve formal arguments to their actual value.
555   if (Frag->getNumArgs()) {
556     // Compute the map of formal to actual arguments.
557     std::map<std::string, TreePatternNode*> ArgMap;
558     for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
559       ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
560   
561     FragTree->SubstituteFormalArguments(ArgMap);
562   }
563   
564   FragTree->setName(getName());
565   FragTree->UpdateNodeType(getExtTypes(), TP);
566   
567   // Get a new copy of this fragment to stitch into here.
568   //delete this;    // FIXME: implement refcounting!
569   return FragTree;
570 }
571
572 /// getImplicitType - Check to see if the specified record has an implicit
573 /// type which should be applied to it.  This infer the type of register
574 /// references from the register file information, for example.
575 ///
576 static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
577                                       TreePattern &TP) {
578   // Some common return values
579   std::vector<unsigned char> Unknown(1, MVT::isUnknown);
580   std::vector<unsigned char> Other(1, MVT::Other);
581
582   // Check to see if this is a register or a register class...
583   if (R->isSubClassOf("RegisterClass")) {
584     if (NotRegisters) 
585       return Unknown;
586     const CodeGenRegisterClass &RC = 
587       TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
588     return ConvertVTs(RC.getValueTypes());
589   } else if (R->isSubClassOf("PatFrag")) {
590     // Pattern fragment types will be resolved when they are inlined.
591     return Unknown;
592   } else if (R->isSubClassOf("Register")) {
593     if (NotRegisters) 
594       return Unknown;
595     const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
596     return T.getRegisterVTs(R);
597   } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
598     // Using a VTSDNode or CondCodeSDNode.
599     return Other;
600   } else if (R->isSubClassOf("ComplexPattern")) {
601     if (NotRegisters) 
602       return Unknown;
603     std::vector<unsigned char>
604     ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
605     return ComplexPat;
606   } else if (R->getName() == "node" || R->getName() == "srcvalue") {
607     // Placeholder.
608     return Unknown;
609   }
610   
611   TP.error("Unknown node flavor used in pattern: " + R->getName());
612   return Other;
613 }
614
615 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
616 /// this node and its children in the tree.  This returns true if it makes a
617 /// change, false otherwise.  If a type contradiction is found, throw an
618 /// exception.
619 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
620   DAGISelEmitter &ISE = TP.getDAGISelEmitter();
621   if (isLeaf()) {
622     if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
623       // If it's a regclass or something else known, include the type.
624       return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
625     } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
626       // Int inits are always integers. :)
627       bool MadeChange = UpdateNodeType(MVT::isInt, TP);
628       
629       if (hasTypeSet()) {
630         // At some point, it may make sense for this tree pattern to have
631         // multiple types.  Assert here that it does not, so we revisit this
632         // code when appropriate.
633         assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
634         MVT::ValueType VT = getTypeNum(0);
635         for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
636           assert(getTypeNum(i) == VT && "TreePattern has too many types!");
637         
638         VT = getTypeNum(0);
639         if (VT != MVT::iPTR) {
640           unsigned Size = MVT::getSizeInBits(VT);
641           // Make sure that the value is representable for this type.
642           if (Size < 32) {
643             int Val = (II->getValue() << (32-Size)) >> (32-Size);
644             if (Val != II->getValue())
645               TP.error("Sign-extended integer value '" + itostr(II->getValue())+
646                        "' is out of range for type '" + 
647                        getEnumName(getTypeNum(0)) + "'!");
648           }
649         }
650       }
651       
652       return MadeChange;
653     }
654     return false;
655   }
656   
657   // special handling for set, which isn't really an SDNode.
658   if (getOperator()->getName() == "set") {
659     assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
660     bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
661     MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
662     
663     // Types of operands must match.
664     MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
665     MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
666     MadeChange |= UpdateNodeType(MVT::isVoid, TP);
667     return MadeChange;
668   } else if (getOperator() == ISE.get_intrinsic_void_sdnode() ||
669              getOperator() == ISE.get_intrinsic_w_chain_sdnode() ||
670              getOperator() == ISE.get_intrinsic_wo_chain_sdnode()) {
671     unsigned IID = 
672     dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
673     const CodeGenIntrinsic &Int = ISE.getIntrinsicInfo(IID);
674     bool MadeChange = false;
675     
676     // Apply the result type to the node.
677     MadeChange = UpdateNodeType(Int.ArgVTs[0], TP);
678     
679     if (getNumChildren() != Int.ArgVTs.size())
680       TP.error("Intrinsic '" + Int.Name + "' expects " +
681                utostr(Int.ArgVTs.size()-1) + " operands, not " +
682                utostr(getNumChildren()-1) + " operands!");
683
684     // Apply type info to the intrinsic ID.
685     MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
686     
687     for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
688       MVT::ValueType OpVT = Int.ArgVTs[i];
689       MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
690       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
691     }
692     return MadeChange;
693   } else if (getOperator()->isSubClassOf("SDNode")) {
694     const SDNodeInfo &NI = ISE.getSDNodeInfo(getOperator());
695     
696     bool MadeChange = NI.ApplyTypeConstraints(this, TP);
697     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
698       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
699     // Branch, etc. do not produce results and top-level forms in instr pattern
700     // must have void types.
701     if (NI.getNumResults() == 0)
702       MadeChange |= UpdateNodeType(MVT::isVoid, TP);
703     
704     // If this is a vector_shuffle operation, apply types to the build_vector
705     // operation.  The types of the integers don't matter, but this ensures they
706     // won't get checked.
707     if (getOperator()->getName() == "vector_shuffle" &&
708         getChild(2)->getOperator()->getName() == "build_vector") {
709       TreePatternNode *BV = getChild(2);
710       const std::vector<MVT::ValueType> &LegalVTs
711         = ISE.getTargetInfo().getLegalValueTypes();
712       MVT::ValueType LegalIntVT = MVT::Other;
713       for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
714         if (MVT::isInteger(LegalVTs[i]) && !MVT::isVector(LegalVTs[i])) {
715           LegalIntVT = LegalVTs[i];
716           break;
717         }
718       assert(LegalIntVT != MVT::Other && "No legal integer VT?");
719             
720       for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
721         MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
722     }
723     return MadeChange;  
724   } else if (getOperator()->isSubClassOf("Instruction")) {
725     const DAGInstruction &Inst = ISE.getInstruction(getOperator());
726     bool MadeChange = false;
727     unsigned NumResults = Inst.getNumResults();
728     
729     assert(NumResults <= 1 &&
730            "Only supports zero or one result instrs!");
731     // Apply the result type to the node
732     if (NumResults == 0) {
733       MadeChange = UpdateNodeType(MVT::isVoid, TP);
734     } else {
735       Record *ResultNode = Inst.getResult(0);
736       assert(ResultNode->isSubClassOf("RegisterClass") &&
737              "Operands should be register classes!");
738
739       const CodeGenRegisterClass &RC = 
740         ISE.getTargetInfo().getRegisterClass(ResultNode);
741       MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
742     }
743
744     if (getNumChildren() != Inst.getNumOperands())
745       TP.error("Instruction '" + getOperator()->getName() + " expects " +
746                utostr(Inst.getNumOperands()) + " operands, not " +
747                utostr(getNumChildren()) + " operands!");
748     for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
749       Record *OperandNode = Inst.getOperand(i);
750       MVT::ValueType VT;
751       if (OperandNode->isSubClassOf("RegisterClass")) {
752         const CodeGenRegisterClass &RC = 
753           ISE.getTargetInfo().getRegisterClass(OperandNode);
754         //VT = RC.getValueTypeNum(0);
755         MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
756                                                  TP);
757       } else if (OperandNode->isSubClassOf("Operand")) {
758         VT = getValueType(OperandNode->getValueAsDef("Type"));
759         MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
760       } else {
761         assert(0 && "Unknown operand type!");
762         abort();
763       }
764       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
765     }
766     return MadeChange;
767   } else {
768     assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
769     
770     // Node transforms always take one operand.
771     if (getNumChildren() != 1)
772       TP.error("Node transform '" + getOperator()->getName() +
773                "' requires one operand!");
774
775     // If either the output or input of the xform does not have exact
776     // type info. We assume they must be the same. Otherwise, it is perfectly
777     // legal to transform from one type to a completely different type.
778     if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
779       bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
780       MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
781       return MadeChange;
782     }
783     return false;
784   }
785 }
786
787 /// canPatternMatch - If it is impossible for this pattern to match on this
788 /// target, fill in Reason and return false.  Otherwise, return true.  This is
789 /// used as a santity check for .td files (to prevent people from writing stuff
790 /// that can never possibly work), and to prevent the pattern permuter from
791 /// generating stuff that is useless.
792 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
793   if (isLeaf()) return true;
794
795   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
796     if (!getChild(i)->canPatternMatch(Reason, ISE))
797       return false;
798
799   // If this is an intrinsic, handle cases that would make it not match.  For
800   // example, if an operand is required to be an immediate.
801   if (getOperator()->isSubClassOf("Intrinsic")) {
802     // TODO:
803     return true;
804   }
805   
806   // If this node is a commutative operator, check that the LHS isn't an
807   // immediate.
808   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
809   if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
810     // Scan all of the operands of the node and make sure that only the last one
811     // is a constant node.
812     for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
813       if (!getChild(i)->isLeaf() && 
814           getChild(i)->getOperator()->getName() == "imm") {
815         Reason = "Immediate value must be on the RHS of commutative operators!";
816         return false;
817       }
818   }
819   
820   return true;
821 }
822
823 //===----------------------------------------------------------------------===//
824 // TreePattern implementation
825 //
826
827 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
828                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
829    isInputPattern = isInput;
830    for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
831      Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
832 }
833
834 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
835                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
836   isInputPattern = isInput;
837   Trees.push_back(ParseTreePattern(Pat));
838 }
839
840 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
841                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
842   isInputPattern = isInput;
843   Trees.push_back(Pat);
844 }
845
846
847
848 void TreePattern::error(const std::string &Msg) const {
849   dump();
850   throw "In " + TheRecord->getName() + ": " + Msg;
851 }
852
853 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
854   DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
855   if (!OpDef) error("Pattern has unexpected operator type!");
856   Record *Operator = OpDef->getDef();
857   
858   if (Operator->isSubClassOf("ValueType")) {
859     // If the operator is a ValueType, then this must be "type cast" of a leaf
860     // node.
861     if (Dag->getNumArgs() != 1)
862       error("Type cast only takes one operand!");
863     
864     Init *Arg = Dag->getArg(0);
865     TreePatternNode *New;
866     if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
867       Record *R = DI->getDef();
868       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
869         Dag->setArg(0, new DagInit(DI,
870                                 std::vector<std::pair<Init*, std::string> >()));
871         return ParseTreePattern(Dag);
872       }
873       New = new TreePatternNode(DI);
874     } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
875       New = ParseTreePattern(DI);
876     } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
877       New = new TreePatternNode(II);
878       if (!Dag->getArgName(0).empty())
879         error("Constant int argument should not have a name!");
880     } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
881       // Turn this into an IntInit.
882       Init *II = BI->convertInitializerTo(new IntRecTy());
883       if (II == 0 || !dynamic_cast<IntInit*>(II))
884         error("Bits value must be constants!");
885       
886       New = new TreePatternNode(dynamic_cast<IntInit*>(II));
887       if (!Dag->getArgName(0).empty())
888         error("Constant int argument should not have a name!");
889     } else {
890       Arg->dump();
891       error("Unknown leaf value for tree pattern!");
892       return 0;
893     }
894     
895     // Apply the type cast.
896     New->UpdateNodeType(getValueType(Operator), *this);
897     New->setName(Dag->getArgName(0));
898     return New;
899   }
900   
901   // Verify that this is something that makes sense for an operator.
902   if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
903       !Operator->isSubClassOf("Instruction") && 
904       !Operator->isSubClassOf("SDNodeXForm") &&
905       !Operator->isSubClassOf("Intrinsic") &&
906       Operator->getName() != "set")
907     error("Unrecognized node '" + Operator->getName() + "'!");
908   
909   //  Check to see if this is something that is illegal in an input pattern.
910   if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
911                          Operator->isSubClassOf("SDNodeXForm")))
912     error("Cannot use '" + Operator->getName() + "' in an input pattern!");
913   
914   std::vector<TreePatternNode*> Children;
915   
916   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
917     Init *Arg = Dag->getArg(i);
918     if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
919       Children.push_back(ParseTreePattern(DI));
920       if (Children.back()->getName().empty())
921         Children.back()->setName(Dag->getArgName(i));
922     } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
923       Record *R = DefI->getDef();
924       // Direct reference to a leaf DagNode or PatFrag?  Turn it into a
925       // TreePatternNode if its own.
926       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
927         Dag->setArg(i, new DagInit(DefI,
928                               std::vector<std::pair<Init*, std::string> >()));
929         --i;  // Revisit this node...
930       } else {
931         TreePatternNode *Node = new TreePatternNode(DefI);
932         Node->setName(Dag->getArgName(i));
933         Children.push_back(Node);
934         
935         // Input argument?
936         if (R->getName() == "node") {
937           if (Dag->getArgName(i).empty())
938             error("'node' argument requires a name to match with operand list");
939           Args.push_back(Dag->getArgName(i));
940         }
941       }
942     } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
943       TreePatternNode *Node = new TreePatternNode(II);
944       if (!Dag->getArgName(i).empty())
945         error("Constant int argument should not have a name!");
946       Children.push_back(Node);
947     } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
948       // Turn this into an IntInit.
949       Init *II = BI->convertInitializerTo(new IntRecTy());
950       if (II == 0 || !dynamic_cast<IntInit*>(II))
951         error("Bits value must be constants!");
952       
953       TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
954       if (!Dag->getArgName(i).empty())
955         error("Constant int argument should not have a name!");
956       Children.push_back(Node);
957     } else {
958       std::cerr << '"';
959       Arg->dump();
960       std::cerr << "\": ";
961       error("Unknown leaf value for tree pattern!");
962     }
963   }
964   
965   // If the operator is an intrinsic, then this is just syntactic sugar for for
966   // (intrinsic_* <number>, ..children..).  Pick the right intrinsic node, and 
967   // convert the intrinsic name to a number.
968   if (Operator->isSubClassOf("Intrinsic")) {
969     const CodeGenIntrinsic &Int = getDAGISelEmitter().getIntrinsic(Operator);
970     unsigned IID = getDAGISelEmitter().getIntrinsicID(Operator)+1;
971
972     // If this intrinsic returns void, it must have side-effects and thus a
973     // chain.
974     if (Int.ArgVTs[0] == MVT::isVoid) {
975       Operator = getDAGISelEmitter().get_intrinsic_void_sdnode();
976     } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
977       // Has side-effects, requires chain.
978       Operator = getDAGISelEmitter().get_intrinsic_w_chain_sdnode();
979     } else {
980       // Otherwise, no chain.
981       Operator = getDAGISelEmitter().get_intrinsic_wo_chain_sdnode();
982     }
983     
984     TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
985     Children.insert(Children.begin(), IIDNode);
986   }
987   
988   return new TreePatternNode(Operator, Children);
989 }
990
991 /// InferAllTypes - Infer/propagate as many types throughout the expression
992 /// patterns as possible.  Return true if all types are infered, false
993 /// otherwise.  Throw an exception if a type contradiction is found.
994 bool TreePattern::InferAllTypes() {
995   bool MadeChange = true;
996   while (MadeChange) {
997     MadeChange = false;
998     for (unsigned i = 0, e = Trees.size(); i != e; ++i)
999       MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1000   }
1001   
1002   bool HasUnresolvedTypes = false;
1003   for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1004     HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1005   return !HasUnresolvedTypes;
1006 }
1007
1008 void TreePattern::print(std::ostream &OS) const {
1009   OS << getRecord()->getName();
1010   if (!Args.empty()) {
1011     OS << "(" << Args[0];
1012     for (unsigned i = 1, e = Args.size(); i != e; ++i)
1013       OS << ", " << Args[i];
1014     OS << ")";
1015   }
1016   OS << ": ";
1017   
1018   if (Trees.size() > 1)
1019     OS << "[\n";
1020   for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1021     OS << "\t";
1022     Trees[i]->print(OS);
1023     OS << "\n";
1024   }
1025
1026   if (Trees.size() > 1)
1027     OS << "]\n";
1028 }
1029
1030 void TreePattern::dump() const { print(std::cerr); }
1031
1032
1033
1034 //===----------------------------------------------------------------------===//
1035 // DAGISelEmitter implementation
1036 //
1037
1038 // Parse all of the SDNode definitions for the target, populating SDNodes.
1039 void DAGISelEmitter::ParseNodeInfo() {
1040   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1041   while (!Nodes.empty()) {
1042     SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1043     Nodes.pop_back();
1044   }
1045
1046   // Get the buildin intrinsic nodes.
1047   intrinsic_void_sdnode     = getSDNodeNamed("intrinsic_void");
1048   intrinsic_w_chain_sdnode  = getSDNodeNamed("intrinsic_w_chain");
1049   intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1050 }
1051
1052 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1053 /// map, and emit them to the file as functions.
1054 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
1055   OS << "\n// Node transformations.\n";
1056   std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1057   while (!Xforms.empty()) {
1058     Record *XFormNode = Xforms.back();
1059     Record *SDNode = XFormNode->getValueAsDef("Opcode");
1060     std::string Code = XFormNode->getValueAsCode("XFormFunction");
1061     SDNodeXForms.insert(std::make_pair(XFormNode,
1062                                        std::make_pair(SDNode, Code)));
1063
1064     if (!Code.empty()) {
1065       std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
1066       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1067
1068       OS << "inline SDOperand Transform_" << XFormNode->getName()
1069          << "(SDNode *" << C2 << ") {\n";
1070       if (ClassName != "SDNode")
1071         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1072       OS << Code << "\n}\n";
1073     }
1074
1075     Xforms.pop_back();
1076   }
1077 }
1078
1079 void DAGISelEmitter::ParseComplexPatterns() {
1080   std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1081   while (!AMs.empty()) {
1082     ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1083     AMs.pop_back();
1084   }
1085 }
1086
1087
1088 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1089 /// file, building up the PatternFragments map.  After we've collected them all,
1090 /// inline fragments together as necessary, so that there are no references left
1091 /// inside a pattern fragment to a pattern fragment.
1092 ///
1093 /// This also emits all of the predicate functions to the output file.
1094 ///
1095 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
1096   std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1097   
1098   // First step, parse all of the fragments and emit predicate functions.
1099   OS << "\n// Predicate functions.\n";
1100   for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1101     DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1102     TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1103     PatternFragments[Fragments[i]] = P;
1104     
1105     // Validate the argument list, converting it to map, to discard duplicates.
1106     std::vector<std::string> &Args = P->getArgList();
1107     std::set<std::string> OperandsMap(Args.begin(), Args.end());
1108     
1109     if (OperandsMap.count(""))
1110       P->error("Cannot have unnamed 'node' values in pattern fragment!");
1111     
1112     // Parse the operands list.
1113     DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1114     DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1115     if (!OpsOp || OpsOp->getDef()->getName() != "ops")
1116       P->error("Operands list should start with '(ops ... '!");
1117     
1118     // Copy over the arguments.       
1119     Args.clear();
1120     for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1121       if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1122           static_cast<DefInit*>(OpsList->getArg(j))->
1123           getDef()->getName() != "node")
1124         P->error("Operands list should all be 'node' values.");
1125       if (OpsList->getArgName(j).empty())
1126         P->error("Operands list should have names for each operand!");
1127       if (!OperandsMap.count(OpsList->getArgName(j)))
1128         P->error("'" + OpsList->getArgName(j) +
1129                  "' does not occur in pattern or was multiply specified!");
1130       OperandsMap.erase(OpsList->getArgName(j));
1131       Args.push_back(OpsList->getArgName(j));
1132     }
1133     
1134     if (!OperandsMap.empty())
1135       P->error("Operands list does not contain an entry for operand '" +
1136                *OperandsMap.begin() + "'!");
1137
1138     // If there is a code init for this fragment, emit the predicate code and
1139     // keep track of the fact that this fragment uses it.
1140     std::string Code = Fragments[i]->getValueAsCode("Predicate");
1141     if (!Code.empty()) {
1142       assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
1143       std::string ClassName =
1144         getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
1145       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1146       
1147       OS << "inline bool Predicate_" << Fragments[i]->getName()
1148          << "(SDNode *" << C2 << ") {\n";
1149       if (ClassName != "SDNode")
1150         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1151       OS << Code << "\n}\n";
1152       P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
1153     }
1154     
1155     // If there is a node transformation corresponding to this, keep track of
1156     // it.
1157     Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1158     if (!getSDNodeTransform(Transform).second.empty())    // not noop xform?
1159       P->getOnlyTree()->setTransformFn(Transform);
1160   }
1161   
1162   OS << "\n\n";
1163
1164   // Now that we've parsed all of the tree fragments, do a closure on them so
1165   // that there are not references to PatFrags left inside of them.
1166   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1167        E = PatternFragments.end(); I != E; ++I) {
1168     TreePattern *ThePat = I->second;
1169     ThePat->InlinePatternFragments();
1170         
1171     // Infer as many types as possible.  Don't worry about it if we don't infer
1172     // all of them, some may depend on the inputs of the pattern.
1173     try {
1174       ThePat->InferAllTypes();
1175     } catch (...) {
1176       // If this pattern fragment is not supported by this target (no types can
1177       // satisfy its constraints), just ignore it.  If the bogus pattern is
1178       // actually used by instructions, the type consistency error will be
1179       // reported there.
1180     }
1181     
1182     // If debugging, print out the pattern fragment result.
1183     DEBUG(ThePat->dump());
1184   }
1185 }
1186
1187 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1188 /// instruction input.  Return true if this is a real use.
1189 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1190                       std::map<std::string, TreePatternNode*> &InstInputs,
1191                       std::vector<Record*> &InstImpInputs) {
1192   // No name -> not interesting.
1193   if (Pat->getName().empty()) {
1194     if (Pat->isLeaf()) {
1195       DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1196       if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1197         I->error("Input " + DI->getDef()->getName() + " must be named!");
1198       else if (DI && DI->getDef()->isSubClassOf("Register")) 
1199         InstImpInputs.push_back(DI->getDef());
1200     }
1201     return false;
1202   }
1203
1204   Record *Rec;
1205   if (Pat->isLeaf()) {
1206     DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1207     if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1208     Rec = DI->getDef();
1209   } else {
1210     assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1211     Rec = Pat->getOperator();
1212   }
1213
1214   // SRCVALUE nodes are ignored.
1215   if (Rec->getName() == "srcvalue")
1216     return false;
1217
1218   TreePatternNode *&Slot = InstInputs[Pat->getName()];
1219   if (!Slot) {
1220     Slot = Pat;
1221   } else {
1222     Record *SlotRec;
1223     if (Slot->isLeaf()) {
1224       SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1225     } else {
1226       assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1227       SlotRec = Slot->getOperator();
1228     }
1229     
1230     // Ensure that the inputs agree if we've already seen this input.
1231     if (Rec != SlotRec)
1232       I->error("All $" + Pat->getName() + " inputs must agree with each other");
1233     if (Slot->getExtTypes() != Pat->getExtTypes())
1234       I->error("All $" + Pat->getName() + " inputs must agree with each other");
1235   }
1236   return true;
1237 }
1238
1239 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1240 /// part of "I", the instruction), computing the set of inputs and outputs of
1241 /// the pattern.  Report errors if we see anything naughty.
1242 void DAGISelEmitter::
1243 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1244                             std::map<std::string, TreePatternNode*> &InstInputs,
1245                             std::map<std::string, TreePatternNode*>&InstResults,
1246                             std::vector<Record*> &InstImpInputs,
1247                             std::vector<Record*> &InstImpResults) {
1248   if (Pat->isLeaf()) {
1249     bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1250     if (!isUse && Pat->getTransformFn())
1251       I->error("Cannot specify a transform function for a non-input value!");
1252     return;
1253   } else if (Pat->getOperator()->getName() != "set") {
1254     // If this is not a set, verify that the children nodes are not void typed,
1255     // and recurse.
1256     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1257       if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1258         I->error("Cannot have void nodes inside of patterns!");
1259       FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1260                                   InstImpInputs, InstImpResults);
1261     }
1262     
1263     // If this is a non-leaf node with no children, treat it basically as if
1264     // it were a leaf.  This handles nodes like (imm).
1265     bool isUse = false;
1266     if (Pat->getNumChildren() == 0)
1267       isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1268     
1269     if (!isUse && Pat->getTransformFn())
1270       I->error("Cannot specify a transform function for a non-input value!");
1271     return;
1272   } 
1273   
1274   // Otherwise, this is a set, validate and collect instruction results.
1275   if (Pat->getNumChildren() == 0)
1276     I->error("set requires operands!");
1277   else if (Pat->getNumChildren() & 1)
1278     I->error("set requires an even number of operands");
1279   
1280   if (Pat->getTransformFn())
1281     I->error("Cannot specify a transform function on a set node!");
1282   
1283   // Check the set destinations.
1284   unsigned NumValues = Pat->getNumChildren()/2;
1285   for (unsigned i = 0; i != NumValues; ++i) {
1286     TreePatternNode *Dest = Pat->getChild(i);
1287     if (!Dest->isLeaf())
1288       I->error("set destination should be a register!");
1289     
1290     DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1291     if (!Val)
1292       I->error("set destination should be a register!");
1293
1294     if (Val->getDef()->isSubClassOf("RegisterClass")) {
1295       if (Dest->getName().empty())
1296         I->error("set destination must have a name!");
1297       if (InstResults.count(Dest->getName()))
1298         I->error("cannot set '" + Dest->getName() +"' multiple times");
1299       InstResults[Dest->getName()] = Dest;
1300     } else if (Val->getDef()->isSubClassOf("Register")) {
1301       InstImpResults.push_back(Val->getDef());
1302     } else {
1303       I->error("set destination should be a register!");
1304     }
1305     
1306     // Verify and collect info from the computation.
1307     FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1308                                 InstInputs, InstResults,
1309                                 InstImpInputs, InstImpResults);
1310   }
1311 }
1312
1313 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1314 /// any fragments involved.  This populates the Instructions list with fully
1315 /// resolved instructions.
1316 void DAGISelEmitter::ParseInstructions() {
1317   std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1318   
1319   for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1320     ListInit *LI = 0;
1321     
1322     if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1323       LI = Instrs[i]->getValueAsListInit("Pattern");
1324     
1325     // If there is no pattern, only collect minimal information about the
1326     // instruction for its operand list.  We have to assume that there is one
1327     // result, as we have no detailed info.
1328     if (!LI || LI->getSize() == 0) {
1329       std::vector<Record*> Results;
1330       std::vector<Record*> Operands;
1331       
1332       CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1333
1334       if (InstInfo.OperandList.size() != 0) {
1335         // FIXME: temporary hack...
1336         if (InstInfo.noResults) {
1337           // These produce no results
1338           for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1339             Operands.push_back(InstInfo.OperandList[j].Rec);
1340         } else {
1341           // Assume the first operand is the result.
1342           Results.push_back(InstInfo.OperandList[0].Rec);
1343       
1344           // The rest are inputs.
1345           for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1346             Operands.push_back(InstInfo.OperandList[j].Rec);
1347         }
1348       }
1349       
1350       // Create and insert the instruction.
1351       std::vector<Record*> ImpResults;
1352       std::vector<Record*> ImpOperands;
1353       Instructions.insert(std::make_pair(Instrs[i], 
1354                           DAGInstruction(0, Results, Operands, ImpResults,
1355                                          ImpOperands)));
1356       continue;  // no pattern.
1357     }
1358     
1359     // Parse the instruction.
1360     TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1361     // Inline pattern fragments into it.
1362     I->InlinePatternFragments();
1363     
1364     // Infer as many types as possible.  If we cannot infer all of them, we can
1365     // never do anything with this instruction pattern: report it to the user.
1366     if (!I->InferAllTypes())
1367       I->error("Could not infer all types in pattern!");
1368     
1369     // InstInputs - Keep track of all of the inputs of the instruction, along 
1370     // with the record they are declared as.
1371     std::map<std::string, TreePatternNode*> InstInputs;
1372     
1373     // InstResults - Keep track of all the virtual registers that are 'set'
1374     // in the instruction, including what reg class they are.
1375     std::map<std::string, TreePatternNode*> InstResults;
1376
1377     std::vector<Record*> InstImpInputs;
1378     std::vector<Record*> InstImpResults;
1379     
1380     // Verify that the top-level forms in the instruction are of void type, and
1381     // fill in the InstResults map.
1382     for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1383       TreePatternNode *Pat = I->getTree(j);
1384       if (Pat->getExtTypeNum(0) != MVT::isVoid)
1385         I->error("Top-level forms in instruction pattern should have"
1386                  " void types");
1387
1388       // Find inputs and outputs, and verify the structure of the uses/defs.
1389       FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1390                                   InstImpInputs, InstImpResults);
1391     }
1392
1393     // Now that we have inputs and outputs of the pattern, inspect the operands
1394     // list for the instruction.  This determines the order that operands are
1395     // added to the machine instruction the node corresponds to.
1396     unsigned NumResults = InstResults.size();
1397
1398     // Parse the operands list from the (ops) list, validating it.
1399     std::vector<std::string> &Args = I->getArgList();
1400     assert(Args.empty() && "Args list should still be empty here!");
1401     CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1402
1403     // Check that all of the results occur first in the list.
1404     std::vector<Record*> Results;
1405     TreePatternNode *Res0Node = NULL;
1406     for (unsigned i = 0; i != NumResults; ++i) {
1407       if (i == CGI.OperandList.size())
1408         I->error("'" + InstResults.begin()->first +
1409                  "' set but does not appear in operand list!");
1410       const std::string &OpName = CGI.OperandList[i].Name;
1411       
1412       // Check that it exists in InstResults.
1413       TreePatternNode *RNode = InstResults[OpName];
1414       if (RNode == 0)
1415         I->error("Operand $" + OpName + " does not exist in operand list!");
1416         
1417       if (i == 0)
1418         Res0Node = RNode;
1419       Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1420       if (R == 0)
1421         I->error("Operand $" + OpName + " should be a set destination: all "
1422                  "outputs must occur before inputs in operand list!");
1423       
1424       if (CGI.OperandList[i].Rec != R)
1425         I->error("Operand $" + OpName + " class mismatch!");
1426       
1427       // Remember the return type.
1428       Results.push_back(CGI.OperandList[i].Rec);
1429       
1430       // Okay, this one checks out.
1431       InstResults.erase(OpName);
1432     }
1433
1434     // Loop over the inputs next.  Make a copy of InstInputs so we can destroy
1435     // the copy while we're checking the inputs.
1436     std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1437
1438     std::vector<TreePatternNode*> ResultNodeOperands;
1439     std::vector<Record*> Operands;
1440     for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1441       const std::string &OpName = CGI.OperandList[i].Name;
1442       if (OpName.empty())
1443         I->error("Operand #" + utostr(i) + " in operands list has no name!");
1444
1445       if (!InstInputsCheck.count(OpName))
1446         I->error("Operand $" + OpName +
1447                  " does not appear in the instruction pattern");
1448       TreePatternNode *InVal = InstInputsCheck[OpName];
1449       InstInputsCheck.erase(OpName);   // It occurred, remove from map.
1450       
1451       if (InVal->isLeaf() &&
1452           dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1453         Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1454         if (CGI.OperandList[i].Rec != InRec &&
1455             !InRec->isSubClassOf("ComplexPattern"))
1456           I->error("Operand $" + OpName + "'s register class disagrees"
1457                    " between the operand and pattern");
1458       }
1459       Operands.push_back(CGI.OperandList[i].Rec);
1460       
1461       // Construct the result for the dest-pattern operand list.
1462       TreePatternNode *OpNode = InVal->clone();
1463       
1464       // No predicate is useful on the result.
1465       OpNode->setPredicateFn("");
1466       
1467       // Promote the xform function to be an explicit node if set.
1468       if (Record *Xform = OpNode->getTransformFn()) {
1469         OpNode->setTransformFn(0);
1470         std::vector<TreePatternNode*> Children;
1471         Children.push_back(OpNode);
1472         OpNode = new TreePatternNode(Xform, Children);
1473       }
1474       
1475       ResultNodeOperands.push_back(OpNode);
1476     }
1477     
1478     if (!InstInputsCheck.empty())
1479       I->error("Input operand $" + InstInputsCheck.begin()->first +
1480                " occurs in pattern but not in operands list!");
1481
1482     TreePatternNode *ResultPattern =
1483       new TreePatternNode(I->getRecord(), ResultNodeOperands);
1484     // Copy fully inferred output node type to instruction result pattern.
1485     if (NumResults > 0)
1486       ResultPattern->setTypes(Res0Node->getExtTypes());
1487
1488     // Create and insert the instruction.
1489     DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1490     Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1491
1492     // Use a temporary tree pattern to infer all types and make sure that the
1493     // constructed result is correct.  This depends on the instruction already
1494     // being inserted into the Instructions map.
1495     TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1496     Temp.InferAllTypes();
1497
1498     DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1499     TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1500     
1501     DEBUG(I->dump());
1502   }
1503    
1504   // If we can, convert the instructions to be patterns that are matched!
1505   for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1506        E = Instructions.end(); II != E; ++II) {
1507     DAGInstruction &TheInst = II->second;
1508     TreePattern *I = TheInst.getPattern();
1509     if (I == 0) continue;  // No pattern.
1510
1511     if (I->getNumTrees() != 1) {
1512       std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1513       continue;
1514     }
1515     TreePatternNode *Pattern = I->getTree(0);
1516     TreePatternNode *SrcPattern;
1517     if (Pattern->getOperator()->getName() == "set") {
1518       if (Pattern->getNumChildren() != 2)
1519         continue;  // Not a set of a single value (not handled so far)
1520
1521       SrcPattern = Pattern->getChild(1)->clone();    
1522     } else{
1523       // Not a set (store or something?)
1524       SrcPattern = Pattern;
1525     }
1526     
1527     std::string Reason;
1528     if (!SrcPattern->canPatternMatch(Reason, *this))
1529       I->error("Instruction can never match: " + Reason);
1530     
1531     Record *Instr = II->first;
1532     TreePatternNode *DstPattern = TheInst.getResultPattern();
1533     PatternsToMatch.
1534       push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1535                                SrcPattern, DstPattern,
1536                                Instr->getValueAsInt("AddedComplexity")));
1537   }
1538 }
1539
1540 void DAGISelEmitter::ParsePatterns() {
1541   std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1542
1543   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1544     DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1545     TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1546
1547     // Inline pattern fragments into it.
1548     Pattern->InlinePatternFragments();
1549     
1550     // Infer as many types as possible.  If we cannot infer all of them, we can
1551     // never do anything with this pattern: report it to the user.
1552     if (!Pattern->InferAllTypes())
1553       Pattern->error("Could not infer all types in pattern!");
1554
1555     // Validate that the input pattern is correct.
1556     {
1557       std::map<std::string, TreePatternNode*> InstInputs;
1558       std::map<std::string, TreePatternNode*> InstResults;
1559       std::vector<Record*> InstImpInputs;
1560       std::vector<Record*> InstImpResults;
1561       FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1562                                   InstInputs, InstResults,
1563                                   InstImpInputs, InstImpResults);
1564     }
1565     
1566     ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1567     if (LI->getSize() == 0) continue;  // no pattern.
1568     
1569     // Parse the instruction.
1570     TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1571     
1572     // Inline pattern fragments into it.
1573     Result->InlinePatternFragments();
1574     
1575     // Infer as many types as possible.  If we cannot infer all of them, we can
1576     // never do anything with this pattern: report it to the user.
1577     if (!Result->InferAllTypes())
1578       Result->error("Could not infer all types in pattern result!");
1579    
1580     if (Result->getNumTrees() != 1)
1581       Result->error("Cannot handle instructions producing instructions "
1582                     "with temporaries yet!");
1583
1584     // Promote the xform function to be an explicit node if set.
1585     std::vector<TreePatternNode*> ResultNodeOperands;
1586     TreePatternNode *DstPattern = Result->getOnlyTree();
1587     for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1588       TreePatternNode *OpNode = DstPattern->getChild(ii);
1589       if (Record *Xform = OpNode->getTransformFn()) {
1590         OpNode->setTransformFn(0);
1591         std::vector<TreePatternNode*> Children;
1592         Children.push_back(OpNode);
1593         OpNode = new TreePatternNode(Xform, Children);
1594       }
1595       ResultNodeOperands.push_back(OpNode);
1596     }
1597     DstPattern = Result->getOnlyTree();
1598     if (!DstPattern->isLeaf())
1599       DstPattern = new TreePatternNode(DstPattern->getOperator(),
1600                                        ResultNodeOperands);
1601     DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1602     TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1603     Temp.InferAllTypes();
1604
1605     std::string Reason;
1606     if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1607       Pattern->error("Pattern can never match: " + Reason);
1608     
1609     PatternsToMatch.
1610       push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1611                                Pattern->getOnlyTree(),
1612                                Temp.getOnlyTree(),
1613                                Patterns[i]->getValueAsInt("AddedComplexity")));
1614   }
1615 }
1616
1617 /// CombineChildVariants - Given a bunch of permutations of each child of the
1618 /// 'operator' node, put them together in all possible ways.
1619 static void CombineChildVariants(TreePatternNode *Orig, 
1620                const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1621                                  std::vector<TreePatternNode*> &OutVariants,
1622                                  DAGISelEmitter &ISE) {
1623   // Make sure that each operand has at least one variant to choose from.
1624   for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1625     if (ChildVariants[i].empty())
1626       return;
1627         
1628   // The end result is an all-pairs construction of the resultant pattern.
1629   std::vector<unsigned> Idxs;
1630   Idxs.resize(ChildVariants.size());
1631   bool NotDone = true;
1632   while (NotDone) {
1633     // Create the variant and add it to the output list.
1634     std::vector<TreePatternNode*> NewChildren;
1635     for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1636       NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1637     TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1638     
1639     // Copy over properties.
1640     R->setName(Orig->getName());
1641     R->setPredicateFn(Orig->getPredicateFn());
1642     R->setTransformFn(Orig->getTransformFn());
1643     R->setTypes(Orig->getExtTypes());
1644     
1645     // If this pattern cannot every match, do not include it as a variant.
1646     std::string ErrString;
1647     if (!R->canPatternMatch(ErrString, ISE)) {
1648       delete R;
1649     } else {
1650       bool AlreadyExists = false;
1651       
1652       // Scan to see if this pattern has already been emitted.  We can get
1653       // duplication due to things like commuting:
1654       //   (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1655       // which are the same pattern.  Ignore the dups.
1656       for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1657         if (R->isIsomorphicTo(OutVariants[i])) {
1658           AlreadyExists = true;
1659           break;
1660         }
1661       
1662       if (AlreadyExists)
1663         delete R;
1664       else
1665         OutVariants.push_back(R);
1666     }
1667     
1668     // Increment indices to the next permutation.
1669     NotDone = false;
1670     // Look for something we can increment without causing a wrap-around.
1671     for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1672       if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1673         NotDone = true;   // Found something to increment.
1674         break;
1675       }
1676       Idxs[IdxsIdx] = 0;
1677     }
1678   }
1679 }
1680
1681 /// CombineChildVariants - A helper function for binary operators.
1682 ///
1683 static void CombineChildVariants(TreePatternNode *Orig, 
1684                                  const std::vector<TreePatternNode*> &LHS,
1685                                  const std::vector<TreePatternNode*> &RHS,
1686                                  std::vector<TreePatternNode*> &OutVariants,
1687                                  DAGISelEmitter &ISE) {
1688   std::vector<std::vector<TreePatternNode*> > ChildVariants;
1689   ChildVariants.push_back(LHS);
1690   ChildVariants.push_back(RHS);
1691   CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1692 }  
1693
1694
1695 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1696                                      std::vector<TreePatternNode *> &Children) {
1697   assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1698   Record *Operator = N->getOperator();
1699   
1700   // Only permit raw nodes.
1701   if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1702       N->getTransformFn()) {
1703     Children.push_back(N);
1704     return;
1705   }
1706
1707   if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1708     Children.push_back(N->getChild(0));
1709   else
1710     GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1711
1712   if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1713     Children.push_back(N->getChild(1));
1714   else
1715     GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1716 }
1717
1718 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1719 /// the (potentially recursive) pattern by using algebraic laws.
1720 ///
1721 static void GenerateVariantsOf(TreePatternNode *N,
1722                                std::vector<TreePatternNode*> &OutVariants,
1723                                DAGISelEmitter &ISE) {
1724   // We cannot permute leaves.
1725   if (N->isLeaf()) {
1726     OutVariants.push_back(N);
1727     return;
1728   }
1729
1730   // Look up interesting info about the node.
1731   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1732
1733   // If this node is associative, reassociate.
1734   if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1735     // Reassociate by pulling together all of the linked operators 
1736     std::vector<TreePatternNode*> MaximalChildren;
1737     GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1738
1739     // Only handle child sizes of 3.  Otherwise we'll end up trying too many
1740     // permutations.
1741     if (MaximalChildren.size() == 3) {
1742       // Find the variants of all of our maximal children.
1743       std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1744       GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1745       GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1746       GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1747       
1748       // There are only two ways we can permute the tree:
1749       //   (A op B) op C    and    A op (B op C)
1750       // Within these forms, we can also permute A/B/C.
1751       
1752       // Generate legal pair permutations of A/B/C.
1753       std::vector<TreePatternNode*> ABVariants;
1754       std::vector<TreePatternNode*> BAVariants;
1755       std::vector<TreePatternNode*> ACVariants;
1756       std::vector<TreePatternNode*> CAVariants;
1757       std::vector<TreePatternNode*> BCVariants;
1758       std::vector<TreePatternNode*> CBVariants;
1759       CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1760       CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1761       CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1762       CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1763       CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1764       CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1765
1766       // Combine those into the result: (x op x) op x
1767       CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1768       CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1769       CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1770       CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1771       CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1772       CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1773
1774       // Combine those into the result: x op (x op x)
1775       CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1776       CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1777       CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1778       CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1779       CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1780       CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1781       return;
1782     }
1783   }
1784   
1785   // Compute permutations of all children.
1786   std::vector<std::vector<TreePatternNode*> > ChildVariants;
1787   ChildVariants.resize(N->getNumChildren());
1788   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1789     GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1790
1791   // Build all permutations based on how the children were formed.
1792   CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1793
1794   // If this node is commutative, consider the commuted order.
1795   if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1796     assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1797     // Consider the commuted order.
1798     CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1799                          OutVariants, ISE);
1800   }
1801 }
1802
1803
1804 // GenerateVariants - Generate variants.  For example, commutative patterns can
1805 // match multiple ways.  Add them to PatternsToMatch as well.
1806 void DAGISelEmitter::GenerateVariants() {
1807   
1808   DEBUG(std::cerr << "Generating instruction variants.\n");
1809   
1810   // Loop over all of the patterns we've collected, checking to see if we can
1811   // generate variants of the instruction, through the exploitation of
1812   // identities.  This permits the target to provide agressive matching without
1813   // the .td file having to contain tons of variants of instructions.
1814   //
1815   // Note that this loop adds new patterns to the PatternsToMatch list, but we
1816   // intentionally do not reconsider these.  Any variants of added patterns have
1817   // already been added.
1818   //
1819   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1820     std::vector<TreePatternNode*> Variants;
1821     GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
1822
1823     assert(!Variants.empty() && "Must create at least original variant!");
1824     Variants.erase(Variants.begin());  // Remove the original pattern.
1825
1826     if (Variants.empty())  // No variants for this pattern.
1827       continue;
1828
1829     DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1830           PatternsToMatch[i].getSrcPattern()->dump();
1831           std::cerr << "\n");
1832
1833     for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1834       TreePatternNode *Variant = Variants[v];
1835
1836       DEBUG(std::cerr << "  VAR#" << v <<  ": ";
1837             Variant->dump();
1838             std::cerr << "\n");
1839       
1840       // Scan to see if an instruction or explicit pattern already matches this.
1841       bool AlreadyExists = false;
1842       for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1843         // Check to see if this variant already exists.
1844         if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
1845           DEBUG(std::cerr << "  *** ALREADY EXISTS, ignoring variant.\n");
1846           AlreadyExists = true;
1847           break;
1848         }
1849       }
1850       // If we already have it, ignore the variant.
1851       if (AlreadyExists) continue;
1852
1853       // Otherwise, add it to the list of patterns we have.
1854       PatternsToMatch.
1855         push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1856                                  Variant, PatternsToMatch[i].getDstPattern(),
1857                                  PatternsToMatch[i].getAddedComplexity()));
1858     }
1859
1860     DEBUG(std::cerr << "\n");
1861   }
1862 }
1863
1864
1865 // NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1866 // ComplexPattern.
1867 static bool NodeIsComplexPattern(TreePatternNode *N)
1868 {
1869   return (N->isLeaf() &&
1870           dynamic_cast<DefInit*>(N->getLeafValue()) &&
1871           static_cast<DefInit*>(N->getLeafValue())->getDef()->
1872           isSubClassOf("ComplexPattern"));
1873 }
1874
1875 // NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1876 // is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1877 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1878                                                    DAGISelEmitter &ISE)
1879 {
1880   if (N->isLeaf() &&
1881       dynamic_cast<DefInit*>(N->getLeafValue()) &&
1882       static_cast<DefInit*>(N->getLeafValue())->getDef()->
1883       isSubClassOf("ComplexPattern")) {
1884     return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1885                                   ->getDef());
1886   }
1887   return NULL;
1888 }
1889
1890 /// getPatternSize - Return the 'size' of this pattern.  We want to match large
1891 /// patterns before small ones.  This is used to determine the size of a
1892 /// pattern.
1893 static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
1894   assert((isExtIntegerInVTs(P->getExtTypes()) || 
1895           isExtFloatingPointInVTs(P->getExtTypes()) ||
1896           P->getExtTypeNum(0) == MVT::isVoid ||
1897           P->getExtTypeNum(0) == MVT::Flag ||
1898           P->getExtTypeNum(0) == MVT::iPTR) && 
1899          "Not a valid pattern node to size!");
1900   unsigned Size = 2;  // The node itself.
1901   // If the root node is a ConstantSDNode, increases its size.
1902   // e.g. (set R32:$dst, 0).
1903   if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
1904     Size++;
1905
1906   // FIXME: This is a hack to statically increase the priority of patterns
1907   // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1908   // Later we can allow complexity / cost for each pattern to be (optionally)
1909   // specified. To get best possible pattern match we'll need to dynamically
1910   // calculate the complexity of all patterns a dag can potentially map to.
1911   const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1912   if (AM)
1913     Size += AM->getNumOperands() * 2;
1914
1915   // If this node has some predicate function that must match, it adds to the
1916   // complexity of this node.
1917   if (!P->getPredicateFn().empty())
1918     ++Size;
1919   
1920   // Count children in the count if they are also nodes.
1921   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1922     TreePatternNode *Child = P->getChild(i);
1923     if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
1924       Size += getPatternSize(Child, ISE);
1925     else if (Child->isLeaf()) {
1926       if (dynamic_cast<IntInit*>(Child->getLeafValue())) 
1927         Size += 3;  // Matches a ConstantSDNode (+2) and a specific value (+1).
1928       else if (NodeIsComplexPattern(Child))
1929         Size += getPatternSize(Child, ISE);
1930       else if (!Child->getPredicateFn().empty())
1931         ++Size;
1932     }
1933   }
1934   
1935   return Size;
1936 }
1937
1938 /// getResultPatternCost - Compute the number of instructions for this pattern.
1939 /// This is a temporary hack.  We should really include the instruction
1940 /// latencies in this calculation.
1941 static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
1942   if (P->isLeaf()) return 0;
1943   
1944   unsigned Cost = 0;
1945   Record *Op = P->getOperator();
1946   if (Op->isSubClassOf("Instruction")) {
1947     Cost++;
1948     CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
1949     if (II.usesCustomDAGSchedInserter)
1950       Cost += 10;
1951   }
1952   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1953     Cost += getResultPatternCost(P->getChild(i), ISE);
1954   return Cost;
1955 }
1956
1957 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1958 // In particular, we want to match maximal patterns first and lowest cost within
1959 // a particular complexity first.
1960 struct PatternSortingPredicate {
1961   PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1962   DAGISelEmitter &ISE;
1963
1964   bool operator()(PatternToMatch *LHS,
1965                   PatternToMatch *RHS) {
1966     unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1967     unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
1968     LHSSize += LHS->getAddedComplexity();
1969     RHSSize += RHS->getAddedComplexity();
1970     if (LHSSize > RHSSize) return true;   // LHS -> bigger -> less cost
1971     if (LHSSize < RHSSize) return false;
1972     
1973     // If the patterns have equal complexity, compare generated instruction cost
1974     return getResultPatternCost(LHS->getDstPattern(), ISE) <
1975       getResultPatternCost(RHS->getDstPattern(), ISE);
1976   }
1977 };
1978
1979 /// getRegisterValueType - Look up and return the first ValueType of specified 
1980 /// RegisterClass record
1981 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
1982   if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1983     return RC->getValueTypeNum(0);
1984   return MVT::Other;
1985 }
1986
1987
1988 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1989 /// type information from it.
1990 static void RemoveAllTypes(TreePatternNode *N) {
1991   N->removeTypes();
1992   if (!N->isLeaf())
1993     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1994       RemoveAllTypes(N->getChild(i));
1995 }
1996
1997 Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1998   Record *N = Records.getDef(Name);
1999   if (!N || !N->isSubClassOf("SDNode")) {
2000     std::cerr << "Error getting SDNode '" << Name << "'!\n";
2001     exit(1);
2002   }
2003   return N;
2004 }
2005
2006 /// NodeHasProperty - return true if TreePatternNode has the specified
2007 /// property.
2008 static bool NodeHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
2009                             DAGISelEmitter &ISE)
2010 {
2011   if (N->isLeaf()) return false;
2012   Record *Operator = N->getOperator();
2013   if (!Operator->isSubClassOf("SDNode")) return false;
2014
2015   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
2016   return NodeInfo.hasProperty(Property);
2017 }
2018
2019 static bool PatternHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
2020                                DAGISelEmitter &ISE)
2021 {
2022   if (NodeHasProperty(N, Property, ISE))
2023     return true;
2024
2025   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2026     TreePatternNode *Child = N->getChild(i);
2027     if (PatternHasProperty(Child, Property, ISE))
2028       return true;
2029   }
2030
2031   return false;
2032 }
2033
2034 class PatternCodeEmitter {
2035 private:
2036   DAGISelEmitter &ISE;
2037
2038   // Predicates.
2039   ListInit *Predicates;
2040   // Pattern cost.
2041   unsigned Cost;
2042   // Instruction selector pattern.
2043   TreePatternNode *Pattern;
2044   // Matched instruction.
2045   TreePatternNode *Instruction;
2046   
2047   // Node to name mapping
2048   std::map<std::string, std::string> VariableMap;
2049   // Node to operator mapping
2050   std::map<std::string, Record*> OperatorMap;
2051   // Names of all the folded nodes which produce chains.
2052   std::vector<std::pair<std::string, unsigned> > FoldedChains;
2053   std::set<std::string> Duplicates;
2054   /// These nodes are being marked "in-flight" so they cannot be folded.
2055   std::vector<std::string> InflightNodes;
2056
2057   /// GeneratedCode - This is the buffer that we emit code to.  The first bool
2058   /// indicates whether this is an exit predicate (something that should be
2059   /// tested, and if true, the match fails) [when true] or normal code to emit
2060   /// [when false].
2061   std::vector<std::pair<bool, std::string> > &GeneratedCode;
2062   /// GeneratedDecl - This is the set of all SDOperand declarations needed for
2063   /// the set of patterns for each top-level opcode.
2064   std::set<std::pair<bool, std::string> > &GeneratedDecl;
2065
2066   std::string ChainName;
2067   bool NewTF;
2068   bool DoReplace;
2069   unsigned TmpNo;
2070   
2071   void emitCheck(const std::string &S) {
2072     if (!S.empty())
2073       GeneratedCode.push_back(std::make_pair(true, S));
2074   }
2075   void emitCode(const std::string &S) {
2076     if (!S.empty())
2077       GeneratedCode.push_back(std::make_pair(false, S));
2078   }
2079   void emitDecl(const std::string &S, bool isSDNode=false) {
2080     assert(!S.empty() && "Invalid declaration");
2081     GeneratedDecl.insert(std::make_pair(isSDNode, S));
2082   }
2083 public:
2084   PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
2085                      TreePatternNode *pattern, TreePatternNode *instr,
2086                      std::vector<std::pair<bool, std::string> > &gc,
2087                      std::set<std::pair<bool, std::string> > &gd,
2088                      bool dorep)
2089   : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
2090     GeneratedCode(gc), GeneratedDecl(gd),
2091     NewTF(false), DoReplace(dorep), TmpNo(0) {}
2092
2093   /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
2094   /// if the match fails. At this point, we already know that the opcode for N
2095   /// matches, and the SDNode for the result has the RootName specified name.
2096   void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
2097                      const std::string &RootName, const std::string &ParentName,
2098                      const std::string &ChainSuffix, bool &FoundChain) {
2099     bool isRoot = (P == NULL);
2100     // Emit instruction predicates. Each predicate is just a string for now.
2101     if (isRoot) {
2102       std::string PredicateCheck;
2103       for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
2104         if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
2105           Record *Def = Pred->getDef();
2106           if (!Def->isSubClassOf("Predicate")) {
2107             Def->dump();
2108             assert(0 && "Unknown predicate type!");
2109           }
2110           if (!PredicateCheck.empty())
2111             PredicateCheck += " || ";
2112           PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
2113         }
2114       }
2115       
2116       emitCheck(PredicateCheck);
2117     }
2118
2119     if (N->isLeaf()) {
2120       if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2121         emitCheck("cast<ConstantSDNode>(" + RootName +
2122                   ")->getSignExtended() == " + itostr(II->getValue()));
2123         return;
2124       } else if (!NodeIsComplexPattern(N)) {
2125         assert(0 && "Cannot match this as a leaf value!");
2126         abort();
2127       }
2128     }
2129   
2130     // If this node has a name associated with it, capture it in VariableMap. If
2131     // we already saw this in the pattern, emit code to verify dagness.
2132     if (!N->getName().empty()) {
2133       std::string &VarMapEntry = VariableMap[N->getName()];
2134       if (VarMapEntry.empty()) {
2135         VarMapEntry = RootName;
2136       } else {
2137         // If we get here, this is a second reference to a specific name.  Since
2138         // we already have checked that the first reference is valid, we don't
2139         // have to recursively match it, just check that it's the same as the
2140         // previously named thing.
2141         emitCheck(VarMapEntry + " == " + RootName);
2142         return;
2143       }
2144
2145       if (!N->isLeaf())
2146         OperatorMap[N->getName()] = N->getOperator();
2147     }
2148
2149
2150     // Emit code to load the child nodes and match their contents recursively.
2151     unsigned OpNo = 0;
2152     bool NodeHasChain = NodeHasProperty   (N, SDNodeInfo::SDNPHasChain, ISE);
2153     bool HasChain     = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2154     bool HasOutFlag   = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag,  ISE);
2155     bool EmittedUseCheck = false;
2156     bool EmittedSlctedCheck = false;
2157     if (HasChain) {
2158       if (NodeHasChain)
2159         OpNo = 1;
2160       if (!isRoot) {
2161         const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2162         // Not in flight?
2163         emitCheck("InFlightSet.count(" + RootName + ".Val) == 0");
2164         // Multiple uses of actual result?
2165         emitCheck(RootName + ".hasOneUse()");
2166         EmittedUseCheck = true;
2167         // hasOneUse() check is not strong enough. If the original node has
2168         // already been selected, it may have been replaced with another.
2169         for (unsigned j = 0; j != CInfo.getNumResults(); j++)
2170           emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
2171                     "))");
2172         
2173         EmittedSlctedCheck = true;
2174         if (NodeHasChain) {
2175           // FIXME: Don't fold if 1) the parent node writes a flag, 2) the node
2176           // has a chain use.
2177           // This a workaround for this problem:
2178           //
2179           //          [ch, r : ld]
2180           //             ^ ^
2181           //             | |
2182           //      [XX]--/   \- [flag : cmp]
2183           //       ^             ^
2184           //       |             |
2185           //       \---[br flag]-
2186           //
2187           // cmp + br should be considered as a single node as they are flagged
2188           // together. So, if the ld is folded into the cmp, the XX node in the
2189           // graph is now both an operand and a use of the ld/cmp/br node.
2190           if (NodeHasProperty(P, SDNodeInfo::SDNPOutFlag, ISE))
2191             emitCheck(ParentName + ".Val->isOnlyUse(" +  RootName + ".Val)");
2192
2193           // If the immediate use can somehow reach this node through another
2194           // path, then can't fold it either or it will create a cycle.
2195           // e.g. In the following diagram, XX can reach ld through YY. If
2196           // ld is folded into XX, then YY is both a predecessor and a successor
2197           // of XX.
2198           //
2199           //         [ld]
2200           //         ^  ^
2201           //         |  |
2202           //        /   \---
2203           //      /        [YY]
2204           //      |         ^
2205           //     [XX]-------|
2206           const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2207           if (PInfo.getNumOperands() > 1 ||
2208               PInfo.hasProperty(SDNodeInfo::SDNPHasChain) ||
2209               PInfo.hasProperty(SDNodeInfo::SDNPInFlag) ||
2210               PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag))
2211             if (PInfo.getNumOperands() > 1) {
2212               emitCheck("!isNonImmUse(" + ParentName + ".Val, " + RootName +
2213                         ".Val)");
2214             } else {
2215               emitCheck("(" + ParentName + ".getNumOperands() == 1 || !" +
2216                         "isNonImmUse(" + ParentName + ".Val, " + RootName +
2217                         ".Val))");
2218             }
2219         }
2220       }
2221
2222       if (NodeHasChain) {
2223         ChainName = "Chain" + ChainSuffix;
2224         emitDecl(ChainName);
2225         if (FoundChain) {
2226          // FIXME: temporary workaround for a common case where chain
2227          // is a TokenFactor and the previous "inner" chain is an operand.
2228           NewTF = true;
2229           emitDecl("OldTF", true);
2230           emitCheck("(" + ChainName + " = UpdateFoldedChain(CurDAG, " +
2231                     RootName + ".Val, Chain.Val, OldTF)).Val");
2232         } else {
2233           FoundChain = true;
2234           emitCode(ChainName + " = " + RootName + ".getOperand(0);");
2235         }
2236       }
2237     }
2238
2239     // Don't fold any node which reads or writes a flag and has multiple uses.
2240     // FIXME: We really need to separate the concepts of flag and "glue". Those
2241     // real flag results, e.g. X86CMP output, can have multiple uses.
2242     // FIXME: If the optional incoming flag does not exist. Then it is ok to
2243     // fold it.
2244     if (!isRoot &&
2245         (PatternHasProperty(N, SDNodeInfo::SDNPInFlag, ISE) ||
2246          PatternHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE) ||
2247          PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE))) {
2248       const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2249       if (!EmittedUseCheck) {
2250         // Multiple uses of actual result?
2251         emitCheck(RootName + ".hasOneUse()");
2252       }
2253       if (!EmittedSlctedCheck)
2254         // hasOneUse() check is not strong enough. If the original node has
2255         // already been selected, it may have been replaced with another.
2256         for (unsigned j = 0; j < CInfo.getNumResults(); j++)
2257           emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
2258                     "))");
2259     }
2260
2261     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2262       emitDecl(RootName + utostr(OpNo));
2263       emitCode(RootName + utostr(OpNo) + " = " +
2264                RootName + ".getOperand(" +utostr(OpNo) + ");");
2265       TreePatternNode *Child = N->getChild(i);
2266     
2267       if (!Child->isLeaf()) {
2268         // If it's not a leaf, recursively match.
2269         const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
2270         emitCheck(RootName + utostr(OpNo) + ".getOpcode() == " +
2271                   CInfo.getEnumName());
2272         EmitMatchCode(Child, N, RootName + utostr(OpNo), RootName,
2273                       ChainSuffix + utostr(OpNo), FoundChain);
2274         if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE))
2275           FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
2276                                                 CInfo.getNumResults()));
2277       } else {
2278         // If this child has a name associated with it, capture it in VarMap. If
2279         // we already saw this in the pattern, emit code to verify dagness.
2280         if (!Child->getName().empty()) {
2281           std::string &VarMapEntry = VariableMap[Child->getName()];
2282           if (VarMapEntry.empty()) {
2283             VarMapEntry = RootName + utostr(OpNo);
2284           } else {
2285             // If we get here, this is a second reference to a specific name.
2286             // Since we already have checked that the first reference is valid,
2287             // we don't have to recursively match it, just check that it's the
2288             // same as the previously named thing.
2289             emitCheck(VarMapEntry + " == " + RootName + utostr(OpNo));
2290             Duplicates.insert(RootName + utostr(OpNo));
2291             continue;
2292           }
2293         }
2294       
2295         // Handle leaves of various types.
2296         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2297           Record *LeafRec = DI->getDef();
2298           if (LeafRec->isSubClassOf("RegisterClass")) {
2299             // Handle register references.  Nothing to do here.
2300           } else if (LeafRec->isSubClassOf("Register")) {
2301             // Handle register references.
2302           } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2303             // Handle complex pattern. Nothing to do here.
2304           } else if (LeafRec->getName() == "srcvalue") {
2305             // Place holder for SRCVALUE nodes. Nothing to do here.
2306           } else if (LeafRec->isSubClassOf("ValueType")) {
2307             // Make sure this is the specified value type.
2308             emitCheck("cast<VTSDNode>(" + RootName + utostr(OpNo) +
2309                       ")->getVT() == MVT::" + LeafRec->getName());
2310           } else if (LeafRec->isSubClassOf("CondCode")) {
2311             // Make sure this is the specified cond code.
2312             emitCheck("cast<CondCodeSDNode>(" + RootName + utostr(OpNo) +
2313                       ")->get() == ISD::" + LeafRec->getName());
2314           } else {
2315             Child->dump();
2316             std::cerr << " ";
2317             assert(0 && "Unknown leaf type!");
2318           }
2319         } else if (IntInit *II =
2320                        dynamic_cast<IntInit*>(Child->getLeafValue())) {
2321           emitCheck("isa<ConstantSDNode>(" + RootName + utostr(OpNo) + ")");
2322           unsigned CTmp = TmpNo++;
2323           emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
2324                    RootName + utostr(OpNo) + ")->getSignExtended();");
2325
2326           emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
2327         } else {
2328           Child->dump();
2329           assert(0 && "Unknown leaf type!");
2330         }
2331       }
2332     }
2333
2334     // If there is a node predicate for this, emit the call.
2335     if (!N->getPredicateFn().empty())
2336       emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
2337   }
2338
2339   /// EmitResultCode - Emit the action for a pattern.  Now that it has matched
2340   /// we actually have to build a DAG!
2341   std::pair<unsigned, unsigned>
2342   EmitResultCode(TreePatternNode *N, bool LikeLeaf = false,
2343                  bool isRoot = false) {
2344     // This is something selected from the pattern we matched.
2345     if (!N->getName().empty()) {
2346       std::string &Val = VariableMap[N->getName()];
2347       assert(!Val.empty() &&
2348              "Variable referenced but not defined and not caught earlier!");
2349       if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2350         // Already selected this operand, just return the tmpval.
2351         return std::make_pair(1, atoi(Val.c_str()+3));
2352       }
2353
2354       const ComplexPattern *CP;
2355       unsigned ResNo = TmpNo++;
2356       unsigned NumRes = 1;
2357       if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
2358         assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2359         std::string CastType;
2360         switch (N->getTypeNum(0)) {
2361         default: assert(0 && "Unknown type for constant node!");
2362         case MVT::i1:  CastType = "bool"; break;
2363         case MVT::i8:  CastType = "unsigned char"; break;
2364         case MVT::i16: CastType = "unsigned short"; break;
2365         case MVT::i32: CastType = "unsigned"; break;
2366         case MVT::i64: CastType = "uint64_t"; break;
2367         }
2368         emitCode(CastType + " Tmp" + utostr(ResNo) + "C = (" + CastType + 
2369                  ")cast<ConstantSDNode>(" + Val + ")->getValue();");
2370         emitDecl("Tmp" + utostr(ResNo));
2371         emitCode("Tmp" + utostr(ResNo) + 
2372                  " = CurDAG->getTargetConstant(Tmp" + utostr(ResNo) + 
2373                  "C, " + getEnumName(N->getTypeNum(0)) + ");");
2374       } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2375         Record *Op = OperatorMap[N->getName()];
2376         // Transform ExternalSymbol to TargetExternalSymbol
2377         if (Op && Op->getName() == "externalsym") {
2378           emitDecl("Tmp" + utostr(ResNo));
2379           emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2380                    "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
2381                    Val + ")->getSymbol(), " +
2382                    getEnumName(N->getTypeNum(0)) + ");");
2383         } else {
2384           emitDecl("Tmp" + utostr(ResNo));
2385           emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2386         }
2387       } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
2388         Record *Op = OperatorMap[N->getName()];
2389         // Transform GlobalAddress to TargetGlobalAddress
2390         if (Op && Op->getName() == "globaladdr") {
2391           emitDecl("Tmp" + utostr(ResNo));
2392           emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2393                    "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
2394                    ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
2395                    ");");
2396         } else {
2397           emitDecl("Tmp" + utostr(ResNo));
2398           emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2399         }
2400       } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2401         emitDecl("Tmp" + utostr(ResNo));
2402         emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2403       } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
2404         emitDecl("Tmp" + utostr(ResNo));
2405         emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2406       } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2407         std::string Fn = CP->getSelectFunc();
2408         NumRes = CP->getNumOperands();
2409         for (unsigned i = 0; i < NumRes; ++i)
2410           emitDecl("CPTmp" + utostr(i+ResNo));
2411
2412         std::string Code = "bool Match = " + Fn + "(" + Val;
2413         for (unsigned i = 0; i < NumRes; i++)
2414           Code += ", CPTmp" + utostr(i + ResNo);
2415         emitCode(Code + ");");
2416         if (InflightNodes.size()) {
2417           // Remove the in-flight nodes if the ComplexPattern does not match!
2418           emitCode("if (!Match) {");
2419           for (std::vector<std::string>::iterator AI = InflightNodes.begin(),
2420                  AE = InflightNodes.end(); AI != AE; ++AI)
2421             emitCode("  InFlightSet.erase(" + *AI + ".Val);");
2422           emitCode("}");
2423         }
2424
2425         emitCheck("Match");
2426
2427         for (unsigned i = 0; i < NumRes; ++i) {
2428           emitCode("InFlightSet.insert(CPTmp" + utostr(i+ResNo) + ".Val);");
2429           InflightNodes.push_back("CPTmp" + utostr(i+ResNo));
2430         }
2431         for (unsigned i = 0; i < NumRes; ++i) {
2432           emitDecl("Tmp" + utostr(i+ResNo));
2433           emitCode("Select(Tmp" + utostr(i+ResNo) + ", CPTmp" +
2434                    utostr(i+ResNo) + ");");
2435         }
2436
2437         TmpNo = ResNo + NumRes;
2438       } else {
2439         emitDecl("Tmp" + utostr(ResNo));
2440         // This node, probably wrapped in a SDNodeXForms, behaves like a leaf
2441         // node even if it isn't one. Don't select it.
2442         if (LikeLeaf)
2443           emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2444         else {
2445           emitCode("Select(Tmp" + utostr(ResNo) + ", " + Val + ");");
2446         }
2447
2448         if (isRoot && N->isLeaf()) {
2449           emitCode("Result = Tmp" + utostr(ResNo) + ";");
2450           emitCode("return;");
2451         }
2452       }
2453       // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2454       // value if used multiple times by this pattern result.
2455       Val = "Tmp"+utostr(ResNo);
2456       return std::make_pair(NumRes, ResNo);
2457     }
2458     if (N->isLeaf()) {
2459       // If this is an explicit register reference, handle it.
2460       if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2461         unsigned ResNo = TmpNo++;
2462         if (DI->getDef()->isSubClassOf("Register")) {
2463           emitDecl("Tmp" + utostr(ResNo));
2464           emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
2465                    ISE.getQualifiedName(DI->getDef()) + ", " +
2466                    getEnumName(N->getTypeNum(0)) + ");");
2467           return std::make_pair(1, ResNo);
2468         }
2469       } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2470         unsigned ResNo = TmpNo++;
2471         assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2472         emitDecl("Tmp" + utostr(ResNo));
2473         emitCode("Tmp" + utostr(ResNo) + 
2474                  " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
2475                  ", " + getEnumName(N->getTypeNum(0)) + ");");
2476         return std::make_pair(1, ResNo);
2477       }
2478     
2479       N->dump();
2480       assert(0 && "Unknown leaf type!");
2481       return std::make_pair(1, ~0U);
2482     }
2483
2484     Record *Op = N->getOperator();
2485     if (Op->isSubClassOf("Instruction")) {
2486       const CodeGenTarget &CGT = ISE.getTargetInfo();
2487       CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2488       const DAGInstruction &Inst = ISE.getInstruction(Op);
2489       TreePattern *InstPat = Inst.getPattern();
2490       TreePatternNode *InstPatNode =
2491         isRoot ? (InstPat ? InstPat->getOnlyTree() : Pattern)
2492                : (InstPat ? InstPat->getOnlyTree() : NULL);
2493       if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
2494         InstPatNode = InstPatNode->getChild(1);
2495       }
2496       bool HasImpInputs  = isRoot && Inst.getNumImpOperands() > 0;
2497       bool HasImpResults = isRoot && Inst.getNumImpResults() > 0;
2498       bool NodeHasOptInFlag = isRoot &&
2499         PatternHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
2500       bool NodeHasInFlag  = isRoot &&
2501         PatternHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
2502       bool NodeHasOutFlag = HasImpResults || (isRoot &&
2503         PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
2504       bool NodeHasChain = InstPatNode &&
2505         PatternHasProperty(InstPatNode, SDNodeInfo::SDNPHasChain, ISE);
2506       bool InputHasChain = isRoot &&
2507         NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
2508
2509       if (NodeHasInFlag || NodeHasOutFlag || NodeHasOptInFlag || HasImpInputs)
2510         emitDecl("InFlag");
2511       if (NodeHasOptInFlag)
2512         emitCode("bool HasOptInFlag = false;");
2513
2514       // How many results is this pattern expected to produce?
2515       unsigned PatResults = 0;
2516       for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2517         MVT::ValueType VT = Pattern->getTypeNum(i);
2518         if (VT != MVT::isVoid && VT != MVT::Flag)
2519           PatResults++;
2520       }
2521
2522       // Determine operand emission order. Complex pattern first.
2523       std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2524       std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2525       for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2526         TreePatternNode *Child = N->getChild(i);
2527         if (i == 0) {
2528           EmitOrder.push_back(std::make_pair(i, Child));
2529           OI = EmitOrder.begin();
2530         } else if (NodeIsComplexPattern(Child)) {
2531           OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2532         } else {
2533           EmitOrder.push_back(std::make_pair(i, Child));
2534         }
2535       }
2536
2537       // Make sure these operands which would be selected won't be folded while
2538       // the isel traverses the DAG upward.
2539       for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2540         TreePatternNode *Child = EmitOrder[i].second;
2541         if (!Child->getName().empty()) {
2542           std::string &Val = VariableMap[Child->getName()];
2543           assert(!Val.empty() &&
2544                  "Variable referenced but not defined and not caught earlier!");
2545           if (Child->isLeaf() && !NodeGetComplexPattern(Child, ISE)) {
2546             emitCode("InFlightSet.insert(" + Val + ".Val);");
2547             InflightNodes.push_back(Val);
2548           }
2549         }
2550       }
2551
2552       // Emit all of the operands.
2553       std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2554       for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2555         unsigned OpOrder       = EmitOrder[i].first;
2556         TreePatternNode *Child = EmitOrder[i].second;
2557         std::pair<unsigned, unsigned> NumTemp =  EmitResultCode(Child);
2558         NumTemps[OpOrder] = NumTemp;
2559       }
2560
2561       // List all the operands in the right order.
2562       std::vector<unsigned> Ops;
2563       for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2564         for (unsigned j = 0; j < NumTemps[i].first; j++)
2565           Ops.push_back(NumTemps[i].second + j);
2566       }
2567
2568       // Emit all the chain and CopyToReg stuff.
2569       bool ChainEmitted = NodeHasChain;
2570       if (NodeHasChain)
2571         emitCode("Select(" + ChainName + ", " + ChainName + ");");
2572       if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
2573         EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true);
2574
2575       if (isRoot) {
2576         // The operands have been selected. Remove them from InFlightSet.
2577         for (std::vector<std::string>::iterator AI = InflightNodes.begin(),
2578                AE = InflightNodes.end(); AI != AE; ++AI)
2579           emitCode("InFlightSet.erase(" + *AI + ".Val);");
2580       }
2581
2582       unsigned NumResults = Inst.getNumResults();    
2583       unsigned ResNo = TmpNo++;
2584       if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
2585           NodeHasOptInFlag) {
2586         if (NodeHasOptInFlag) {
2587           unsigned FlagNo = (unsigned) NodeHasChain + Pattern->getNumChildren();
2588           emitDecl("ResNode", true);
2589           emitCode("if (HasOptInFlag)");
2590           std::string Code = "  ResNode = CurDAG->getTargetNode(" +
2591              II.Namespace + "::" + II.TheDef->getName();
2592
2593           // Output order: results, chain, flags
2594           // Result types.
2595           if (PatResults > 0) { 
2596             if (N->getTypeNum(0) != MVT::isVoid)
2597               Code += ", " + getEnumName(N->getTypeNum(0));
2598           }
2599           if (NodeHasChain)
2600             Code += ", MVT::Other";
2601           if (NodeHasOutFlag)
2602             Code += ", MVT::Flag";
2603
2604           // Inputs.
2605           for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2606             Code += ", Tmp" + utostr(Ops[i]);
2607           if (NodeHasChain)  Code += ", " + ChainName;
2608           emitCode(Code + ", InFlag);");
2609
2610           emitCode("else");
2611           Code = "  ResNode = CurDAG->getTargetNode(" + II.Namespace + "::" +
2612                  II.TheDef->getName();
2613
2614           // Output order: results, chain, flags
2615           // Result types.
2616           if (PatResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2617             Code += ", " + getEnumName(N->getTypeNum(0));
2618           if (NodeHasChain)
2619             Code += ", MVT::Other";
2620           if (NodeHasOutFlag)
2621             Code += ", MVT::Flag";
2622
2623           // Inputs.
2624           for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2625             Code += ", Tmp" + utostr(Ops[i]);
2626           if (NodeHasChain) Code += ", " + ChainName + ");";
2627           emitCode(Code);
2628
2629           if (NodeHasChain)
2630             // Remember which op produces the chain.
2631             emitCode(ChainName + " = SDOperand(ResNode" +
2632                      ", " + utostr(PatResults) + ");");
2633         } else {
2634           std::string Code;
2635           std::string NodeName;
2636           if (!isRoot) {
2637             NodeName = "Tmp" + utostr(ResNo);
2638             emitDecl(NodeName);
2639             Code = NodeName + " = SDOperand(";
2640           } else {
2641             NodeName = "ResNode";
2642             emitDecl(NodeName, true);
2643             Code = NodeName + " = ";
2644           }
2645           Code += "CurDAG->getTargetNode(" +
2646             II.Namespace + "::" + II.TheDef->getName();
2647
2648           // Output order: results, chain, flags
2649           // Result types.
2650           if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2651             Code += ", " + getEnumName(N->getTypeNum(0));
2652           if (NodeHasChain)
2653             Code += ", MVT::Other";
2654           if (NodeHasOutFlag)
2655             Code += ", MVT::Flag";
2656
2657           // Inputs.
2658           for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2659             Code += ", Tmp" + utostr(Ops[i]);
2660           if (NodeHasChain) Code += ", " + ChainName;
2661           if (NodeHasInFlag || HasImpInputs) Code += ", InFlag";
2662           if (!isRoot)
2663             emitCode(Code + "), 0);");
2664           else
2665             emitCode(Code + ");");
2666
2667           if (NodeHasChain)
2668             // Remember which op produces the chain.
2669             if (!isRoot)
2670               emitCode(ChainName + " = SDOperand(" + NodeName +
2671                        ".Val, " + utostr(PatResults) + ");");
2672             else
2673               emitCode(ChainName + " = SDOperand(" + NodeName +
2674                        ", " + utostr(PatResults) + ");");
2675         }
2676
2677         if (!isRoot)
2678           return std::make_pair(1, ResNo);
2679
2680         if (NewTF)
2681           emitCode("if (OldTF) "
2682                    "SelectionDAG::InsertISelMapEntry(CodeGenMap, OldTF, 0, " +
2683                    ChainName + ".Val, 0);");
2684
2685         for (unsigned i = 0; i < NumResults; i++)
2686           emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2687                    utostr(i) + ", ResNode, " + utostr(i) + ");");
2688
2689         if (NodeHasOutFlag)
2690           emitCode("InFlag = SDOperand(ResNode, " + 
2691                    utostr(NumResults + (unsigned)NodeHasChain) + ");");
2692
2693         if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) {
2694           emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
2695                    "0, ResNode, 0);");
2696           NumResults = 1;
2697         }
2698
2699         if (InputHasChain) {
2700           emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " + 
2701                    utostr(PatResults) + ", " + ChainName + ".Val, " +
2702                    ChainName + ".ResNo" + ");");
2703           if (DoReplace)
2704             emitCode("if (N.ResNo == 0) AddHandleReplacement(N.Val, " +
2705                      utostr(PatResults) + ", " + ChainName + ".Val, " +
2706                      ChainName + ".ResNo" + ");");
2707         }
2708
2709         if (FoldedChains.size() > 0) {
2710           std::string Code;
2711           for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
2712             emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, " +
2713                      FoldedChains[j].first + ".Val, " + 
2714                      utostr(FoldedChains[j].second) + ", ResNode, " +
2715                      utostr(NumResults) + ");");
2716
2717           for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
2718             std::string Code =
2719               FoldedChains[j].first + ".Val, " +
2720               utostr(FoldedChains[j].second) + ", ";
2721             emitCode("AddHandleReplacement(" + Code + "ResNode, " +
2722                      utostr(NumResults) + ");");
2723           }
2724         }
2725
2726         if (NodeHasOutFlag)
2727           emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2728                    utostr(PatResults + (unsigned)InputHasChain) +
2729                    ", InFlag.Val, InFlag.ResNo);");
2730
2731         // User does not expect the instruction would produce a chain!
2732         bool AddedChain = NodeHasChain && !InputHasChain;
2733         if (AddedChain && NodeHasOutFlag) {
2734           if (PatResults == 0) {
2735             emitCode("Result = SDOperand(ResNode, N.ResNo+1);");
2736           } else {
2737             emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
2738             emitCode("  Result = SDOperand(ResNode, N.ResNo);");
2739             emitCode("else");
2740             emitCode("  Result = SDOperand(ResNode, N.ResNo+1);");
2741           }
2742         } else if (InputHasChain && !NodeHasChain) {
2743           // One of the inner node produces a chain.
2744           emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
2745           emitCode("  Result = SDOperand(ResNode, N.ResNo);");
2746           if (NodeHasOutFlag) {
2747             emitCode("else if (N.ResNo > " + utostr(PatResults) + ")");
2748             emitCode("  Result = SDOperand(ResNode, N.ResNo-1);");
2749           }
2750           emitCode("else");
2751           emitCode("  Result = SDOperand(" + ChainName + ".Val, " + ChainName + ".ResNo);");
2752         } else {
2753           emitCode("Result = SDOperand(ResNode, N.ResNo);");
2754         }
2755       } else {
2756         // If this instruction is the root, and if there is only one use of it,
2757         // use SelectNodeTo instead of getTargetNode to avoid an allocation.
2758         emitCode("if (N.Val->hasOneUse()) {");
2759         std::string Code = "  Result = CurDAG->SelectNodeTo(N.Val, " +
2760           II.Namespace + "::" + II.TheDef->getName();
2761         if (N->getTypeNum(0) != MVT::isVoid)
2762           Code += ", " + getEnumName(N->getTypeNum(0));
2763         if (NodeHasOutFlag)
2764           Code += ", MVT::Flag";
2765         for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2766           Code += ", Tmp" + utostr(Ops[i]);
2767         if (NodeHasInFlag || HasImpInputs)
2768           Code += ", InFlag";
2769         emitCode(Code + ");");
2770         emitCode("} else {");
2771         emitDecl("ResNode", true);
2772         Code = "  ResNode = CurDAG->getTargetNode(" +
2773                II.Namespace + "::" + II.TheDef->getName();
2774         if (N->getTypeNum(0) != MVT::isVoid)
2775           Code += ", " + getEnumName(N->getTypeNum(0));
2776         if (NodeHasOutFlag)
2777           Code += ", MVT::Flag";
2778         for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2779           Code += ", Tmp" + utostr(Ops[i]);
2780         if (NodeHasInFlag || HasImpInputs)
2781           Code += ", InFlag";
2782         emitCode(Code + ");");
2783         emitCode("  SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
2784                  "ResNode, 0);");
2785         emitCode("  Result = SDOperand(ResNode, 0);");
2786         emitCode("}");
2787       }
2788
2789       if (isRoot)
2790         emitCode("return;");
2791       return std::make_pair(1, ResNo);
2792     } else if (Op->isSubClassOf("SDNodeXForm")) {
2793       assert(N->getNumChildren() == 1 && "node xform should have one child!");
2794       // PatLeaf node - the operand may or may not be a leaf node. But it should
2795       // behave like one.
2796       unsigned OpVal = EmitResultCode(N->getChild(0), true).second;
2797       unsigned ResNo = TmpNo++;
2798       emitDecl("Tmp" + utostr(ResNo));
2799       emitCode("Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
2800                + "(Tmp" + utostr(OpVal) + ".Val);");
2801       if (isRoot) {
2802         emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val,"
2803                  "N.ResNo, Tmp" + utostr(ResNo) + ".Val, Tmp" +
2804                  utostr(ResNo) + ".ResNo);");
2805         emitCode("Result = Tmp" + utostr(ResNo) + ";");
2806         emitCode("return;");
2807       }
2808       return std::make_pair(1, ResNo);
2809     } else {
2810       N->dump();
2811       std::cerr << "\n";
2812       throw std::string("Unknown node in result pattern!");
2813     }
2814   }
2815
2816   /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2817   /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that 
2818   /// 'Pat' may be missing types.  If we find an unresolved type to add a check
2819   /// for, this returns true otherwise false if Pat has all types.
2820   bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2821                           const std::string &Prefix) {
2822     // Did we find one?
2823     if (Pat->getExtTypes() != Other->getExtTypes()) {
2824       // Move a type over from 'other' to 'pat'.
2825       Pat->setTypes(Other->getExtTypes());
2826       emitCheck(Prefix + ".Val->getValueType(0) == MVT::" +
2827                 getName(Pat->getTypeNum(0)));
2828       return true;
2829     }
2830   
2831     unsigned OpNo =
2832       (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
2833     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2834       if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2835                              Prefix + utostr(OpNo)))
2836         return true;
2837     return false;
2838   }
2839
2840 private:
2841   /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
2842   /// being built.
2843   void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
2844                             bool &ChainEmitted, bool isRoot = false) {
2845     const CodeGenTarget &T = ISE.getTargetInfo();
2846     unsigned OpNo =
2847       (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2848     bool HasInFlag = NodeHasProperty(N, SDNodeInfo::SDNPInFlag, ISE);
2849     bool HasOptInFlag = NodeHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE);
2850     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2851       TreePatternNode *Child = N->getChild(i);
2852       if (!Child->isLeaf()) {
2853         EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted);
2854       } else {
2855         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2856           if (!Child->getName().empty()) {
2857             std::string Name = RootName + utostr(OpNo);
2858             if (Duplicates.find(Name) != Duplicates.end())
2859               // A duplicate! Do not emit a copy for this node.
2860               continue;
2861           }
2862
2863           Record *RR = DI->getDef();
2864           if (RR->isSubClassOf("Register")) {
2865             MVT::ValueType RVT = getRegisterValueType(RR, T);
2866             if (RVT == MVT::Flag) {
2867               emitCode("Select(InFlag, " + RootName + utostr(OpNo) + ");");
2868             } else {
2869               if (!ChainEmitted) {
2870                 emitDecl("Chain");
2871                 emitCode("Chain = CurDAG->getEntryNode();");
2872                 ChainName = "Chain";
2873                 ChainEmitted = true;
2874               }
2875               emitCode("Select(" + RootName + utostr(OpNo) + ", " +
2876                        RootName + utostr(OpNo) + ");");
2877               emitCode("ResNode = CurDAG->getCopyToReg(" + ChainName +
2878                        ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) +
2879                        ", " + getEnumName(RVT) + "), " +
2880                        RootName + utostr(OpNo) + ", InFlag).Val;");
2881               emitCode(ChainName + " = SDOperand(ResNode, 0);");
2882               emitCode("InFlag = SDOperand(ResNode, 1);");
2883             }
2884           }
2885         }
2886       }
2887     }
2888
2889     if (HasInFlag || HasOptInFlag) {
2890       std::string Code;
2891       if (HasOptInFlag) {
2892         emitCode("if (" + RootName + ".getNumOperands() == " + utostr(OpNo+1) +
2893                  ") {");
2894         Code = "  ";
2895       }
2896       emitCode(Code + "Select(InFlag, " + RootName +
2897                ".getOperand(" + utostr(OpNo) + "));");
2898       if (HasOptInFlag) {
2899         emitCode("  HasOptInFlag = true;");
2900         emitCode("}");
2901       }
2902     }
2903   }
2904
2905   /// EmitCopyFromRegs - Emit code to copy result to physical registers
2906   /// as specified by the instruction. It returns true if any copy is
2907   /// emitted.
2908   bool EmitCopyFromRegs(TreePatternNode *N, bool &ChainEmitted) {
2909     bool RetVal = false;
2910     Record *Op = N->getOperator();
2911     if (Op->isSubClassOf("Instruction")) {
2912       const DAGInstruction &Inst = ISE.getInstruction(Op);
2913       const CodeGenTarget &CGT = ISE.getTargetInfo();
2914       unsigned NumImpResults  = Inst.getNumImpResults();
2915       for (unsigned i = 0; i < NumImpResults; i++) {
2916         Record *RR = Inst.getImpResult(i);
2917         if (RR->isSubClassOf("Register")) {
2918           MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2919           if (RVT != MVT::Flag) {
2920             if (!ChainEmitted) {
2921               emitDecl("Chain");
2922               emitCode("Chain = CurDAG->getEntryNode();");
2923               ChainEmitted = true;
2924               ChainName = "Chain";
2925             }
2926             emitCode("ResNode = CurDAG->getCopyFromReg(" + ChainName + ", " +
2927                      ISE.getQualifiedName(RR) + ", " + getEnumName(RVT) +
2928                      ", InFlag).Val;");
2929             emitCode(ChainName + " = SDOperand(ResNode, 1);");
2930             emitCode("InFlag = SDOperand(ResNode, 2);");
2931             RetVal = true;
2932           }
2933         }
2934       }
2935     }
2936     return RetVal;
2937   }
2938 };
2939
2940 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2941 /// stream to match the pattern, and generate the code for the match if it
2942 /// succeeds.  Returns true if the pattern is not guaranteed to match.
2943 void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
2944                       std::vector<std::pair<bool, std::string> > &GeneratedCode,
2945                          std::set<std::pair<bool, std::string> > &GeneratedDecl,
2946                                             bool DoReplace) {
2947   PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2948                              Pattern.getSrcPattern(), Pattern.getDstPattern(),
2949                              GeneratedCode, GeneratedDecl, DoReplace);
2950
2951   // Emit the matcher, capturing named arguments in VariableMap.
2952   bool FoundChain = false;
2953   Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", "", FoundChain);
2954
2955   // TP - Get *SOME* tree pattern, we don't care which.
2956   TreePattern &TP = *PatternFragments.begin()->second;
2957   
2958   // At this point, we know that we structurally match the pattern, but the
2959   // types of the nodes may not match.  Figure out the fewest number of type 
2960   // comparisons we need to emit.  For example, if there is only one integer
2961   // type supported by a target, there should be no type comparisons at all for
2962   // integer patterns!
2963   //
2964   // To figure out the fewest number of type checks needed, clone the pattern,
2965   // remove the types, then perform type inference on the pattern as a whole.
2966   // If there are unresolved types, emit an explicit check for those types,
2967   // apply the type to the tree, then rerun type inference.  Iterate until all
2968   // types are resolved.
2969   //
2970   TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
2971   RemoveAllTypes(Pat);
2972   
2973   do {
2974     // Resolve/propagate as many types as possible.
2975     try {
2976       bool MadeChange = true;
2977       while (MadeChange)
2978         MadeChange = Pat->ApplyTypeConstraints(TP,
2979                                                true/*Ignore reg constraints*/);
2980     } catch (...) {
2981       assert(0 && "Error: could not find consistent types for something we"
2982              " already decided was ok!");
2983       abort();
2984     }
2985
2986     // Insert a check for an unresolved type and add it to the tree.  If we find
2987     // an unresolved type to add a check for, this returns true and we iterate,
2988     // otherwise we are done.
2989   } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
2990
2991   Emitter.EmitResultCode(Pattern.getDstPattern(), false, true /*the root*/);
2992   delete Pat;
2993 }
2994
2995 /// EraseCodeLine - Erase one code line from all of the patterns.  If removing
2996 /// a line causes any of them to be empty, remove them and return true when
2997 /// done.
2998 static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*, 
2999                           std::vector<std::pair<bool, std::string> > > >
3000                           &Patterns) {
3001   bool ErasedPatterns = false;
3002   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3003     Patterns[i].second.pop_back();
3004     if (Patterns[i].second.empty()) {
3005       Patterns.erase(Patterns.begin()+i);
3006       --i; --e;
3007       ErasedPatterns = true;
3008     }
3009   }
3010   return ErasedPatterns;
3011 }
3012
3013 /// EmitPatterns - Emit code for at least one pattern, but try to group common
3014 /// code together between the patterns.
3015 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*, 
3016                                   std::vector<std::pair<bool, std::string> > > >
3017                                   &Patterns, unsigned Indent,
3018                                   std::ostream &OS) {
3019   typedef std::pair<bool, std::string> CodeLine;
3020   typedef std::vector<CodeLine> CodeList;
3021   typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
3022   
3023   if (Patterns.empty()) return;
3024   
3025   // Figure out how many patterns share the next code line.  Explicitly copy
3026   // FirstCodeLine so that we don't invalidate a reference when changing
3027   // Patterns.
3028   const CodeLine FirstCodeLine = Patterns.back().second.back();
3029   unsigned LastMatch = Patterns.size()-1;
3030   while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
3031     --LastMatch;
3032   
3033   // If not all patterns share this line, split the list into two pieces.  The
3034   // first chunk will use this line, the second chunk won't.
3035   if (LastMatch != 0) {
3036     PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
3037     PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
3038     
3039     // FIXME: Emit braces?
3040     if (Shared.size() == 1) {
3041       PatternToMatch &Pattern = *Shared.back().first;
3042       OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3043       Pattern.getSrcPattern()->print(OS);
3044       OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3045       Pattern.getDstPattern()->print(OS);
3046       OS << "\n";
3047       unsigned AddedComplexity = Pattern.getAddedComplexity();
3048       OS << std::string(Indent, ' ') << "// Pattern complexity = "
3049          << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
3050          << "  cost = "
3051          << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
3052     }
3053     if (!FirstCodeLine.first) {
3054       OS << std::string(Indent, ' ') << "{\n";
3055       Indent += 2;
3056     }
3057     EmitPatterns(Shared, Indent, OS);
3058     if (!FirstCodeLine.first) {
3059       Indent -= 2;
3060       OS << std::string(Indent, ' ') << "}\n";
3061     }
3062     
3063     if (Other.size() == 1) {
3064       PatternToMatch &Pattern = *Other.back().first;
3065       OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3066       Pattern.getSrcPattern()->print(OS);
3067       OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3068       Pattern.getDstPattern()->print(OS);
3069       OS << "\n";
3070       unsigned AddedComplexity = Pattern.getAddedComplexity();
3071       OS << std::string(Indent, ' ') << "// Pattern complexity = "
3072          << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
3073          << "  cost = "
3074          << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
3075     }
3076     EmitPatterns(Other, Indent, OS);
3077     return;
3078   }
3079   
3080   // Remove this code from all of the patterns that share it.
3081   bool ErasedPatterns = EraseCodeLine(Patterns);
3082   
3083   bool isPredicate = FirstCodeLine.first;
3084   
3085   // Otherwise, every pattern in the list has this line.  Emit it.
3086   if (!isPredicate) {
3087     // Normal code.
3088     OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
3089   } else {
3090     OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
3091     
3092     // If the next code line is another predicate, and if all of the pattern
3093     // in this group share the same next line, emit it inline now.  Do this
3094     // until we run out of common predicates.
3095     while (!ErasedPatterns && Patterns.back().second.back().first) {
3096       // Check that all of fhe patterns in Patterns end with the same predicate.
3097       bool AllEndWithSamePredicate = true;
3098       for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
3099         if (Patterns[i].second.back() != Patterns.back().second.back()) {
3100           AllEndWithSamePredicate = false;
3101           break;
3102         }
3103       // If all of the predicates aren't the same, we can't share them.
3104       if (!AllEndWithSamePredicate) break;
3105       
3106       // Otherwise we can.  Emit it shared now.
3107       OS << " &&\n" << std::string(Indent+4, ' ')
3108          << Patterns.back().second.back().second;
3109       ErasedPatterns = EraseCodeLine(Patterns);
3110     }
3111     
3112     OS << ") {\n";
3113     Indent += 2;
3114   }
3115   
3116   EmitPatterns(Patterns, Indent, OS);
3117   
3118   if (isPredicate)
3119     OS << std::string(Indent-2, ' ') << "}\n";
3120 }
3121
3122
3123
3124 namespace {
3125   /// CompareByRecordName - An ordering predicate that implements less-than by
3126   /// comparing the names records.
3127   struct CompareByRecordName {
3128     bool operator()(const Record *LHS, const Record *RHS) const {
3129       // Sort by name first.
3130       if (LHS->getName() < RHS->getName()) return true;
3131       // If both names are equal, sort by pointer.
3132       return LHS->getName() == RHS->getName() && LHS < RHS;
3133     }
3134   };
3135 }
3136
3137 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
3138   std::string InstNS = Target.inst_begin()->second.Namespace;
3139   if (!InstNS.empty()) InstNS += "::";
3140   
3141   // Group the patterns by their top-level opcodes.
3142   std::map<Record*, std::vector<PatternToMatch*>,
3143     CompareByRecordName> PatternsByOpcode;
3144   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3145     TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
3146     if (!Node->isLeaf()) {
3147       PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
3148     } else {
3149       const ComplexPattern *CP;
3150       if (IntInit *II = 
3151           dynamic_cast<IntInit*>(Node->getLeafValue())) {
3152         PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
3153       } else if ((CP = NodeGetComplexPattern(Node, *this))) {
3154         std::vector<Record*> OpNodes = CP->getRootNodes();
3155         for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
3156           PatternsByOpcode[OpNodes[j]]
3157             .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
3158         }
3159       } else {
3160         std::cerr << "Unrecognized opcode '";
3161         Node->dump();
3162         std::cerr << "' on tree pattern '";
3163         std::cerr << 
3164            PatternsToMatch[i].getDstPattern()->getOperator()->getName();
3165         std::cerr << "'!\n";
3166         exit(1);
3167       }
3168     }
3169   }
3170   
3171   // Emit one Select_* method for each top-level opcode.  We do this instead of
3172   // emitting one giant switch statement to support compilers where this will
3173   // result in the recursive functions taking less stack space.
3174   for (std::map<Record*, std::vector<PatternToMatch*>,
3175        CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3176        E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
3177     const std::string &OpName = PBOI->first->getName();
3178     OS << "void Select_" << OpName << "(SDOperand &Result, SDOperand N) {\n";
3179     
3180     const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
3181     bool OptSlctOrder = 
3182       (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) &&
3183        OpcodeInfo.getNumResults() > 0);
3184
3185     if (OptSlctOrder) {
3186       OS << "  if (N.ResNo == " << OpcodeInfo.getNumResults()
3187          << " && N.getValue(0).hasOneUse()) {\n"
3188          << "    SDOperand Dummy = "
3189          << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n"
3190          << "    SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
3191          << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3192          << "    SelectionDAG::InsertISelMapEntry(HandleMap, N.Val, "
3193          << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3194          << "    Result = Dummy;\n"
3195          << "    return;\n"
3196          << "  }\n";
3197     }
3198
3199     std::vector<PatternToMatch*> &Patterns = PBOI->second;
3200     assert(!Patterns.empty() && "No patterns but map has entry?");
3201     
3202     // We want to emit all of the matching code now.  However, we want to emit
3203     // the matches in order of minimal cost.  Sort the patterns so the least
3204     // cost one is at the start.
3205     std::stable_sort(Patterns.begin(), Patterns.end(),
3206                      PatternSortingPredicate(*this));
3207
3208     typedef std::vector<std::pair<bool, std::string> > CodeList;
3209     typedef std::set<std::string> DeclSet;
3210     
3211     std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
3212     std::set<std::pair<bool, std::string> > GeneratedDecl;
3213     for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3214       CodeList GeneratedCode;
3215       GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
3216                              OptSlctOrder);
3217       CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
3218     }
3219     
3220     // Scan the code to see if all of the patterns are reachable and if it is
3221     // possible that the last one might not match.
3222     bool mightNotMatch = true;
3223     for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3224       CodeList &GeneratedCode = CodeForPatterns[i].second;
3225       mightNotMatch = false;
3226
3227       for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
3228         if (GeneratedCode[j].first) { // predicate.
3229           mightNotMatch = true;
3230           break;
3231         }
3232       }
3233       
3234       // If this pattern definitely matches, and if it isn't the last one, the
3235       // patterns after it CANNOT ever match.  Error out.
3236       if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
3237         std::cerr << "Pattern '";
3238         CodeForPatterns[i+1].first->getSrcPattern()->print(OS);
3239         std::cerr << "' is impossible to select!\n";
3240         exit(1);
3241       }
3242     }
3243
3244     // Print all declarations.
3245     for (std::set<std::pair<bool, std::string> >::iterator
3246          I = GeneratedDecl.begin(), E = GeneratedDecl.end(); I != E; ++I)
3247       if (I->first)
3248         OS << "  SDNode *" << I->second << ";\n";
3249       else
3250         OS << "  SDOperand " << I->second << "(0, 0);\n";
3251
3252     // Loop through and reverse all of the CodeList vectors, as we will be
3253     // accessing them from their logical front, but accessing the end of a
3254     // vector is more efficient.
3255     for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3256       CodeList &GeneratedCode = CodeForPatterns[i].second;
3257       std::reverse(GeneratedCode.begin(), GeneratedCode.end());
3258     }
3259     
3260     // Next, reverse the list of patterns itself for the same reason.
3261     std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
3262     
3263     // Emit all of the patterns now, grouped together to share code.
3264     EmitPatterns(CodeForPatterns, 2, OS);
3265     
3266     // If the last pattern has predicates (which could fail) emit code to catch
3267     // the case where nothing handles a pattern.
3268     if (mightNotMatch) {
3269       OS << "  std::cerr << \"Cannot yet select: \";\n";
3270       if (OpcodeInfo.getEnumName() != "ISD::INTRINSIC_W_CHAIN" &&
3271           OpcodeInfo.getEnumName() != "ISD::INTRINSIC_WO_CHAIN" &&
3272           OpcodeInfo.getEnumName() != "ISD::INTRINSIC_VOID") {
3273         OS << "  N.Val->dump(CurDAG);\n";
3274       } else {
3275         OS << "  unsigned iid = cast<ConstantSDNode>(N.getOperand("
3276                "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3277            << "  std::cerr << \"intrinsic %\"<< "
3278                          "Intrinsic::getName((Intrinsic::ID)iid);\n";
3279       }
3280       OS << "  std::cerr << '\\n';\n"
3281          << "  abort();\n";
3282     }
3283     OS << "}\n\n";
3284   }
3285   
3286   // Emit boilerplate.
3287   OS << "void Select_INLINEASM(SDOperand& Result, SDOperand N) {\n"
3288      << "  std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
3289      << "  Select(Ops[0], N.getOperand(0)); // Select the chain.\n\n"
3290      << "  // Select the flag operand.\n"
3291      << "  if (Ops.back().getValueType() == MVT::Flag)\n"
3292      << "    Select(Ops.back(), Ops.back());\n"
3293      << "  SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n"
3294      << "  std::vector<MVT::ValueType> VTs;\n"
3295      << "  VTs.push_back(MVT::Other);\n"
3296      << "  VTs.push_back(MVT::Flag);\n"
3297      << "  SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n"
3298     << "  SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, New.Val, 0);\n"
3299     << "  SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, New.Val, 1);\n"
3300      << "  Result = New.getValue(N.ResNo);\n"
3301      << "  return;\n"
3302      << "}\n\n";
3303   
3304   OS << "// The main instruction selector code.\n"
3305      << "void SelectCode(SDOperand &Result, SDOperand N) {\n"
3306      << "  if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
3307      << "      N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
3308      << "INSTRUCTION_LIST_END)) {\n"
3309      << "    Result = N;\n"
3310      << "    return;   // Already selected.\n"
3311      << "  }\n\n"
3312     << "  std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
3313      << "  if (CGMI != CodeGenMap.end()) {\n"
3314      << "    Result = CGMI->second;\n"
3315      << "    return;\n"
3316      << "  }\n\n"
3317      << "  switch (N.getOpcode()) {\n"
3318      << "  default: break;\n"
3319      << "  case ISD::EntryToken:       // These leaves remain the same.\n"
3320      << "  case ISD::BasicBlock:\n"
3321      << "  case ISD::Register:\n"
3322      << "  case ISD::HANDLENODE:\n"
3323      << "  case ISD::TargetConstant:\n"
3324      << "  case ISD::TargetConstantPool:\n"
3325      << "  case ISD::TargetFrameIndex:\n"
3326      << "  case ISD::TargetJumpTable:\n"
3327      << "  case ISD::TargetGlobalAddress: {\n"
3328      << "    Result = N;\n"
3329      << "    return;\n"
3330      << "  }\n"
3331      << "  case ISD::AssertSext:\n"
3332      << "  case ISD::AssertZext: {\n"
3333      << "    SDOperand Tmp0;\n"
3334      << "    Select(Tmp0, N.getOperand(0));\n"
3335      << "    if (!N.Val->hasOneUse())\n"
3336      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3337      << "Tmp0.Val, Tmp0.ResNo);\n"
3338      << "    Result = Tmp0;\n"
3339      << "    return;\n"
3340      << "  }\n"
3341      << "  case ISD::TokenFactor:\n"
3342      << "    if (N.getNumOperands() == 2) {\n"
3343      << "      SDOperand Op0, Op1;\n"
3344      << "      Select(Op0, N.getOperand(0));\n"
3345      << "      Select(Op1, N.getOperand(1));\n"
3346      << "      Result = \n"
3347      << "          CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
3348      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3349      << "Result.Val, Result.ResNo);\n"
3350      << "    } else {\n"
3351      << "      std::vector<SDOperand> Ops;\n"
3352      << "      for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n"
3353      << "        SDOperand Val;\n"
3354      << "        Select(Val, N.getOperand(i));\n"
3355      << "        Ops.push_back(Val);\n"
3356      << "      }\n"
3357      << "      Result = \n"
3358      << "          CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
3359      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3360      << "Result.Val, Result.ResNo);\n"
3361      << "    }\n"
3362      << "    return;\n"
3363      << "  case ISD::CopyFromReg: {\n"
3364      << "    SDOperand Chain;\n"
3365      << "    Select(Chain, N.getOperand(0));\n"
3366      << "    unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3367      << "    MVT::ValueType VT = N.Val->getValueType(0);\n"
3368      << "    if (N.Val->getNumValues() == 2) {\n"
3369      << "      if (Chain == N.getOperand(0)) {\n"
3370      << "        Result = N; // No change\n"
3371      << "        return;\n"
3372      << "      }\n"
3373      << "      SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
3374      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3375      << "New.Val, 0);\n"
3376      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3377      << "New.Val, 1);\n"
3378      << "      Result = New.getValue(N.ResNo);\n"
3379      << "      return;\n"
3380      << "    } else {\n"
3381      << "      SDOperand Flag;\n"
3382      << "      if (N.getNumOperands() == 3) Select(Flag, N.getOperand(2));\n"
3383      << "      if (Chain == N.getOperand(0) &&\n"
3384      << "          (N.getNumOperands() == 2 || Flag == N.getOperand(2))) {\n"
3385      << "        Result = N; // No change\n"
3386      << "        return;\n"
3387      << "      }\n"
3388      << "      SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
3389      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3390      << "New.Val, 0);\n"
3391      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3392      << "New.Val, 1);\n"
3393      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 2, "
3394      << "New.Val, 2);\n"
3395      << "      Result = New.getValue(N.ResNo);\n"
3396      << "      return;\n"
3397      << "    }\n"
3398      << "  }\n"
3399      << "  case ISD::CopyToReg: {\n"
3400      << "    SDOperand Chain;\n"
3401      << "    Select(Chain, N.getOperand(0));\n"
3402      << "    unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3403      << "    SDOperand Val;\n"
3404      << "    Select(Val, N.getOperand(2));\n"
3405      << "    Result = N;\n"
3406      << "    if (N.Val->getNumValues() == 1) {\n"
3407      << "      if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
3408      << "        Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
3409      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3410      << "Result.Val, 0);\n"
3411      << "    } else {\n"
3412      << "      SDOperand Flag(0, 0);\n"
3413      << "      if (N.getNumOperands() == 4) Select(Flag, N.getOperand(3));\n"
3414      << "      if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
3415      << "          (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
3416      << "        Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
3417      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3418      << "Result.Val, 0);\n"
3419      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3420      << "Result.Val, 1);\n"
3421      << "      Result = Result.getValue(N.ResNo);\n"
3422      << "    }\n"
3423      << "    return;\n"
3424      << "  }\n"
3425      << "  case ISD::INLINEASM:  Select_INLINEASM(Result, N); return;\n";
3426
3427     
3428   // Loop over all of the case statements, emiting a call to each method we
3429   // emitted above.
3430   for (std::map<Record*, std::vector<PatternToMatch*>,
3431                 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3432        E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
3433     const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
3434     OS << "  case " << OpcodeInfo.getEnumName() << ": "
3435        << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
3436        << "Select_" << PBOI->first->getName() << "(Result, N); return;\n";
3437   }
3438
3439   OS << "  } // end of big switch.\n\n"
3440      << "  std::cerr << \"Cannot yet select: \";\n"
3441      << "  if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
3442      << "      N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
3443      << "      N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
3444      << "    N.Val->dump(CurDAG);\n"
3445      << "  } else {\n"
3446      << "    unsigned iid = cast<ConstantSDNode>(N.getOperand("
3447                "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3448      << "    std::cerr << \"intrinsic %\"<< "
3449                         "Intrinsic::getName((Intrinsic::ID)iid);\n"
3450      << "  }\n"
3451      << "  std::cerr << '\\n';\n"
3452      << "  abort();\n"
3453      << "}\n";
3454 }
3455
3456 void DAGISelEmitter::run(std::ostream &OS) {
3457   EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3458                        " target", OS);
3459   
3460   OS << "// *** NOTE: This file is #included into the middle of the target\n"
3461      << "// *** instruction selector class.  These functions are really "
3462      << "methods.\n\n";
3463   
3464   OS << "// Instance var to keep track of multiply used nodes that have \n"
3465      << "// already been selected.\n"
3466      << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
3467
3468   OS << "// Instance var to keep track of mapping of chain generating nodes\n"
3469      << "// and their place handle nodes.\n";
3470   OS << "std::map<SDOperand, SDOperand> HandleMap;\n";
3471   OS << "// Instance var to keep track of mapping of place handle nodes\n"
3472      << "// and their replacement nodes.\n";
3473   OS << "std::map<SDOperand, SDOperand> ReplaceMap;\n";
3474   OS << "// Keep track of nodes that are currently being selecte and therefore\n"
3475      << "// should not be folded.\n";
3476   OS << "std::set<SDNode*> InFlightSet;\n";
3477
3478   OS << "\n";
3479   OS << "static void findNonImmUse(SDNode* Use, SDNode* Def, bool &found, "
3480      << "std::set<SDNode *> &Visited) {\n";
3481   OS << "  if (found || !Visited.insert(Use).second) return;\n";
3482   OS << "  for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3483   OS << "    SDNode *N = Use->getOperand(i).Val;\n";
3484   OS << "    if (N != Def) {\n";
3485   OS << "      findNonImmUse(N, Def, found, Visited);\n";
3486   OS << "    } else {\n";
3487   OS << "      found = true;\n";
3488   OS << "      break;\n";
3489   OS << "    }\n";
3490   OS << "  }\n";
3491   OS << "}\n";
3492
3493   OS << "\n";
3494   OS << "static bool isNonImmUse(SDNode* Use, SDNode* Def) {\n";
3495   OS << "  std::set<SDNode *> Visited;\n";
3496   OS << "  bool found = false;\n";
3497   OS << "  for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3498   OS << "    SDNode *N = Use->getOperand(i).Val;\n";
3499   OS << "    if (N != Def) {\n";
3500   OS << "      findNonImmUse(N, Def, found, Visited);\n";
3501   OS << "      if (found) break;\n";
3502   OS << "    }\n";
3503   OS << "  }\n";
3504   OS << "  return found;\n";
3505   OS << "}\n";
3506
3507   OS << "\n";
3508   OS << "// AddHandleReplacement - Note the pending replacement node for a\n"
3509      << "// handle node in ReplaceMap.\n";
3510   OS << "void AddHandleReplacement(SDNode *H, unsigned HNum, SDNode *R, "
3511      << "unsigned RNum) {\n";
3512   OS << "  SDOperand N(H, HNum);\n";
3513   OS << "  std::map<SDOperand, SDOperand>::iterator HMI = HandleMap.find(N);\n";
3514   OS << "  if (HMI != HandleMap.end()) {\n";
3515   OS << "    ReplaceMap[HMI->second] = SDOperand(R, RNum);\n";
3516   OS << "    HandleMap.erase(N);\n";
3517   OS << "  }\n";
3518   OS << "}\n";
3519
3520   OS << "\n";
3521   OS << "// SelectDanglingHandles - Select replacements for all `dangling`\n";
3522   OS << "// handles.Some handles do not yet have replacements because the\n";
3523   OS << "// nodes they replacements have only dead readers.\n";
3524   OS << "void SelectDanglingHandles() {\n";
3525   OS << "  for (std::map<SDOperand, SDOperand>::iterator I = "
3526      << "HandleMap.begin(),\n"
3527      << "         E = HandleMap.end(); I != E; ++I) {\n";
3528   OS << "    SDOperand N = I->first;\n";
3529   OS << "    SDOperand R;\n";
3530   OS << "    Select(R, N.getValue(0));\n";
3531   OS << "    AddHandleReplacement(N.Val, N.ResNo, R.Val, R.ResNo);\n";
3532   OS << "  }\n";
3533   OS << "}\n";
3534   OS << "\n";
3535   OS << "// ReplaceHandles - Replace all the handles with the real target\n";
3536   OS << "// specific nodes.\n";
3537   OS << "void ReplaceHandles() {\n";
3538   OS << "  for (std::map<SDOperand, SDOperand>::iterator I = "
3539      << "ReplaceMap.begin(),\n"
3540      << "        E = ReplaceMap.end(); I != E; ++I) {\n";
3541   OS << "    SDOperand From = I->first;\n";
3542   OS << "    SDOperand To   = I->second;\n";
3543   OS << "    for (SDNode::use_iterator UI = From.Val->use_begin(), "
3544      << "E = From.Val->use_end(); UI != E; ++UI) {\n";
3545   OS << "      SDNode *Use = *UI;\n";
3546   OS << "      std::vector<SDOperand> Ops;\n";
3547   OS << "      for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3548   OS << "        SDOperand O = Use->getOperand(i);\n";
3549   OS << "        if (O.Val == From.Val)\n";
3550   OS << "          Ops.push_back(To);\n";
3551   OS << "        else\n";
3552   OS << "          Ops.push_back(O);\n";
3553   OS << "      }\n";
3554   OS << "      SDOperand U = SDOperand(Use, 0);\n";
3555   OS << "      CurDAG->UpdateNodeOperands(U, Ops);\n";
3556   OS << "    }\n";
3557   OS << "  }\n";
3558   OS << "}\n";
3559
3560   OS << "\n";
3561   OS << "// UpdateFoldedChain - return a SDOperand of the new chain created\n";
3562   OS << "// if the folding were to happen. This is called when, for example,\n";
3563   OS << "// a load is folded into a store. If the store's chain is the load,\n";
3564   OS << "// then the resulting node's input chain would be the load's input\n";
3565   OS << "// chain. If the store's chain is a TokenFactor and the load's\n";
3566   OS << "// output chain feeds into in, then the new chain is a TokenFactor\n";
3567   OS << "// with the other operands along with the input chain of the load.\n";
3568   OS << "SDOperand UpdateFoldedChain(SelectionDAG *DAG, SDNode *N, "
3569      << "SDNode *Chain, SDNode* &OldTF) {\n";
3570   OS << "  OldTF = NULL;\n";
3571   OS << "  if (N == Chain) {\n";
3572   OS << "    return N->getOperand(0);\n";
3573   OS << "  } else if (Chain->getOpcode() == ISD::TokenFactor &&\n";
3574   OS << "             N->isOperand(Chain)) {\n";
3575   OS << "    SDOperand Ch = SDOperand(Chain, 0);\n";
3576   OS << "    std::map<SDOperand, SDOperand>::iterator CGMI = "
3577      << "CodeGenMap.find(Ch);\n";
3578   OS << "    if (CGMI != CodeGenMap.end())\n";
3579   OS << "      return SDOperand(0, 0);\n";
3580   OS << "    OldTF = Chain;\n";
3581   OS << "    std::vector<SDOperand> Ops;\n";
3582   OS << "    for (unsigned i = 0; i < Chain->getNumOperands(); ++i) {\n";
3583   OS << "      SDOperand Op = Chain->getOperand(i);\n";
3584   OS << "      if (Op.Val == N)\n";
3585   OS << "        Ops.push_back(N->getOperand(0));\n";
3586   OS << "      else\n";
3587   OS << "        Ops.push_back(Op);\n";
3588   OS << "    }\n";
3589   OS << "    return DAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n";
3590   OS << "  }\n";
3591   OS << "  return SDOperand(0, 0);\n";
3592   OS << "}\n";
3593
3594   OS << "\n";
3595   OS << "// SelectRoot - Top level entry to DAG isel.\n";
3596   OS << "SDOperand SelectRoot(SDOperand N) {\n";
3597   OS << "  SDOperand ResNode;\n";
3598   OS << "  Select(ResNode, N);\n";
3599   OS << "  SelectDanglingHandles();\n";
3600   OS << "  ReplaceHandles();\n";
3601   OS << "  ReplaceMap.clear();\n";
3602   OS << "  return ResNode;\n";
3603   OS << "}\n";
3604   
3605   Intrinsics = LoadIntrinsics(Records);
3606   ParseNodeInfo();
3607   ParseNodeTransforms(OS);
3608   ParseComplexPatterns();
3609   ParsePatternFragments(OS);
3610   ParseInstructions();
3611   ParsePatterns();
3612   
3613   // Generate variants.  For example, commutative patterns can match
3614   // multiple ways.  Add them to PatternsToMatch as well.
3615   GenerateVariants();
3616
3617   
3618   DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
3619         for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3620           std::cerr << "PATTERN: ";  PatternsToMatch[i].getSrcPattern()->dump();
3621           std::cerr << "\nRESULT:  ";PatternsToMatch[i].getDstPattern()->dump();
3622           std::cerr << "\n";
3623         });
3624   
3625   // At this point, we have full information about the 'Patterns' we need to
3626   // parse, both implicitly from instructions as well as from explicit pattern
3627   // definitions.  Emit the resultant instruction selector.
3628   EmitInstructionSelector(OS);  
3629   
3630   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3631        E = PatternFragments.end(); I != E; ++I)
3632     delete I->second;
3633   PatternFragments.clear();
3634
3635   Instructions.clear();
3636 }