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