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