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