Better error message when unrecognized opcode is seen.
[oota-llvm.git] / utils / TableGen / DAGISelEmitter.cpp
1 //===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This tablegen backend emits a DAG instruction selector.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "DAGISelEmitter.h"
15 #include "Record.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/Debug.h"
18 #include <algorithm>
19 #include <set>
20 using namespace llvm;
21
22 //===----------------------------------------------------------------------===//
23 // Helpers for working with extended types.
24
25 /// FilterVTs - Filter a list of VT's according to a predicate.
26 ///
27 template<typename T>
28 static std::vector<MVT::ValueType> 
29 FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
30   std::vector<MVT::ValueType> Result;
31   for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
32     if (Filter(InVTs[i]))
33       Result.push_back(InVTs[i]);
34   return Result;
35 }
36
37 /// isExtIntegerVT - Return true if the specified extended value type is
38 /// integer, or isInt.
39 static bool isExtIntegerVT(unsigned char VT) {
40   return VT == MVT::isInt ||
41         (VT < MVT::LAST_VALUETYPE && MVT::isInteger((MVT::ValueType)VT));
42 }
43
44 /// isExtFloatingPointVT - Return true if the specified extended value type is
45 /// floating point, or isFP.
46 static bool isExtFloatingPointVT(unsigned char VT) {
47   return VT == MVT::isFP ||
48         (VT < MVT::LAST_VALUETYPE && MVT::isFloatingPoint((MVT::ValueType)VT));
49 }
50
51 //===----------------------------------------------------------------------===//
52 // SDTypeConstraint implementation
53 //
54
55 SDTypeConstraint::SDTypeConstraint(Record *R) {
56   OperandNo = R->getValueAsInt("OperandNum");
57   
58   if (R->isSubClassOf("SDTCisVT")) {
59     ConstraintType = SDTCisVT;
60     x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
61   } else if (R->isSubClassOf("SDTCisInt")) {
62     ConstraintType = SDTCisInt;
63   } else if (R->isSubClassOf("SDTCisFP")) {
64     ConstraintType = SDTCisFP;
65   } else if (R->isSubClassOf("SDTCisSameAs")) {
66     ConstraintType = SDTCisSameAs;
67     x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
68   } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
69     ConstraintType = SDTCisVTSmallerThanOp;
70     x.SDTCisVTSmallerThanOp_Info.OtherOperandNum = 
71       R->getValueAsInt("OtherOperandNum");
72   } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
73     ConstraintType = SDTCisOpSmallerThanOp;
74     x.SDTCisOpSmallerThanOp_Info.BigOperandNum = 
75       R->getValueAsInt("BigOperandNum");
76   } else {
77     std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
78     exit(1);
79   }
80 }
81
82 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
83 /// N, which has NumResults results.
84 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
85                                                  TreePatternNode *N,
86                                                  unsigned NumResults) const {
87   assert(NumResults == 1 && "We only work with single result nodes so far!");
88   
89   if (OpNo < NumResults)
90     return N;  // FIXME: need value #
91   else
92     return N->getChild(OpNo-NumResults);
93 }
94
95 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
96 /// constraint to the nodes operands.  This returns true if it makes a
97 /// change, false otherwise.  If a type contradiction is found, throw an
98 /// exception.
99 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
100                                            const SDNodeInfo &NodeInfo,
101                                            TreePattern &TP) const {
102   unsigned NumResults = NodeInfo.getNumResults();
103   assert(NumResults == 1 && "We only work with single result nodes so far!");
104   
105   // Check that the number of operands is sane.
106   if (NodeInfo.getNumOperands() >= 0) {
107     if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
108       TP.error(N->getOperator()->getName() + " node requires exactly " +
109                itostr(NodeInfo.getNumOperands()) + " operands!");
110   }
111
112   const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
113   
114   TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
115   
116   switch (ConstraintType) {
117   default: assert(0 && "Unknown constraint type!");
118   case SDTCisVT:
119     // Operand must be a particular type.
120     return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
121   case SDTCisInt: {
122     // If there is only one integer type supported, this must be it.
123     std::vector<MVT::ValueType> IntVTs =
124       FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
125
126     // If we found exactly one supported integer type, apply it.
127     if (IntVTs.size() == 1)
128       return NodeToApply->UpdateNodeType(IntVTs[0], TP);
129     return NodeToApply->UpdateNodeType(MVT::isInt, TP);
130   }
131   case SDTCisFP: {
132     // If there is only one FP type supported, this must be it.
133     std::vector<MVT::ValueType> FPVTs =
134       FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
135         
136     // If we found exactly one supported FP type, apply it.
137     if (FPVTs.size() == 1)
138       return NodeToApply->UpdateNodeType(FPVTs[0], TP);
139     return NodeToApply->UpdateNodeType(MVT::isFP, TP);
140   }
141   case SDTCisSameAs: {
142     TreePatternNode *OtherNode =
143       getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
144     return NodeToApply->UpdateNodeType(OtherNode->getExtType(), TP) |
145            OtherNode->UpdateNodeType(NodeToApply->getExtType(), TP);
146   }
147   case SDTCisVTSmallerThanOp: {
148     // The NodeToApply must be a leaf node that is a VT.  OtherOperandNum must
149     // have an integer type that is smaller than the VT.
150     if (!NodeToApply->isLeaf() ||
151         !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
152         !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
153                ->isSubClassOf("ValueType"))
154       TP.error(N->getOperator()->getName() + " expects a VT operand!");
155     MVT::ValueType VT =
156      getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
157     if (!MVT::isInteger(VT))
158       TP.error(N->getOperator()->getName() + " VT operand must be integer!");
159     
160     TreePatternNode *OtherNode =
161       getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
162     
163     // It must be integer.
164     bool MadeChange = false;
165     MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
166     
167     if (OtherNode->hasTypeSet() && OtherNode->getType() <= VT)
168       OtherNode->UpdateNodeType(MVT::Other, TP);  // Throw an error.
169     return false;
170   }
171   case SDTCisOpSmallerThanOp: {
172     TreePatternNode *BigOperand =
173       getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
174
175     // Both operands must be integer or FP, but we don't care which.
176     bool MadeChange = false;
177     
178     if (isExtIntegerVT(NodeToApply->getExtType()))
179       MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
180     else if (isExtFloatingPointVT(NodeToApply->getExtType()))
181       MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
182     if (isExtIntegerVT(BigOperand->getExtType()))
183       MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
184     else if (isExtFloatingPointVT(BigOperand->getExtType()))
185       MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
186
187     std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
188     
189     if (isExtIntegerVT(NodeToApply->getExtType())) {
190       VTs = FilterVTs(VTs, MVT::isInteger);
191     } else if (isExtFloatingPointVT(NodeToApply->getExtType())) {
192       VTs = FilterVTs(VTs, MVT::isFloatingPoint);
193     } else {
194       VTs.clear();
195     }
196
197     switch (VTs.size()) {
198     default:         // Too many VT's to pick from.
199     case 0: break;   // No info yet.
200     case 1: 
201       // Only one VT of this flavor.  Cannot ever satisify the constraints.
202       return NodeToApply->UpdateNodeType(MVT::Other, TP);  // throw
203     case 2:
204       // If we have exactly two possible types, the little operand must be the
205       // small one, the big operand should be the big one.  Common with 
206       // float/double for example.
207       assert(VTs[0] < VTs[1] && "Should be sorted!");
208       MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
209       MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
210       break;
211     }    
212     return MadeChange;
213   }
214   }  
215   return false;
216 }
217
218
219 //===----------------------------------------------------------------------===//
220 // SDNodeInfo implementation
221 //
222 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
223   EnumName    = R->getValueAsString("Opcode");
224   SDClassName = R->getValueAsString("SDClass");
225   Record *TypeProfile = R->getValueAsDef("TypeProfile");
226   NumResults = TypeProfile->getValueAsInt("NumResults");
227   NumOperands = TypeProfile->getValueAsInt("NumOperands");
228   
229   // Parse the properties.
230   Properties = 0;
231   std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
232   for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
233     if (PropList[i]->getName() == "SDNPCommutative") {
234       Properties |= 1 << SDNPCommutative;
235     } else if (PropList[i]->getName() == "SDNPAssociative") {
236       Properties |= 1 << SDNPAssociative;
237     } else {
238       std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
239                 << "' on node '" << R->getName() << "'!\n";
240       exit(1);
241     }
242   }
243   
244   
245   // Parse the type constraints.
246   std::vector<Record*> ConstraintList =
247     TypeProfile->getValueAsListOfDefs("Constraints");
248   TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
249 }
250
251 //===----------------------------------------------------------------------===//
252 // TreePatternNode implementation
253 //
254
255 TreePatternNode::~TreePatternNode() {
256 #if 0 // FIXME: implement refcounted tree nodes!
257   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
258     delete getChild(i);
259 #endif
260 }
261
262 /// UpdateNodeType - Set the node type of N to VT if VT contains
263 /// information.  If N already contains a conflicting type, then throw an
264 /// exception.  This returns true if any information was updated.
265 ///
266 bool TreePatternNode::UpdateNodeType(unsigned char VT, TreePattern &TP) {
267   if (VT == MVT::isUnknown || getExtType() == VT) return false;
268   if (getExtType() == MVT::isUnknown) {
269     setType(VT);
270     return true;
271   }
272   
273   // If we are told this is to be an int or FP type, and it already is, ignore
274   // the advice.
275   if ((VT == MVT::isInt && isExtIntegerVT(getExtType())) ||
276       (VT == MVT::isFP  && isExtFloatingPointVT(getExtType())))
277     return false;
278       
279   // If we know this is an int or fp type, and we are told it is a specific one,
280   // take the advice.
281   if ((getExtType() == MVT::isInt && isExtIntegerVT(VT)) ||
282       (getExtType() == MVT::isFP  && isExtFloatingPointVT(VT))) {
283     setType(VT);
284     return true;
285   }      
286
287   if (isLeaf()) {
288     dump();
289     TP.error("Type inference contradiction found in node!");
290   } else {
291     TP.error("Type inference contradiction found in node " + 
292              getOperator()->getName() + "!");
293   }
294   return true; // unreachable
295 }
296
297
298 void TreePatternNode::print(std::ostream &OS) const {
299   if (isLeaf()) {
300     OS << *getLeafValue();
301   } else {
302     OS << "(" << getOperator()->getName();
303   }
304   
305   switch (getExtType()) {
306   case MVT::Other: OS << ":Other"; break;
307   case MVT::isInt: OS << ":isInt"; break;
308   case MVT::isFP : OS << ":isFP"; break;
309   case MVT::isUnknown: ; /*OS << ":?";*/ break;
310   default:  OS << ":" << getType(); break;
311   }
312
313   if (!isLeaf()) {
314     if (getNumChildren() != 0) {
315       OS << " ";
316       getChild(0)->print(OS);
317       for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
318         OS << ", ";
319         getChild(i)->print(OS);
320       }
321     }
322     OS << ")";
323   }
324   
325   if (!PredicateFn.empty())
326     OS << "<<P:" << PredicateFn << ">>";
327   if (TransformFn)
328     OS << "<<X:" << TransformFn->getName() << ">>";
329   if (!getName().empty())
330     OS << ":$" << getName();
331
332 }
333 void TreePatternNode::dump() const {
334   print(std::cerr);
335 }
336
337 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
338 /// the specified node.  For this comparison, all of the state of the node
339 /// is considered, except for the assigned name.  Nodes with differing names
340 /// that are otherwise identical are considered isomorphic.
341 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
342   if (N == this) return true;
343   if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
344       getPredicateFn() != N->getPredicateFn() ||
345       getTransformFn() != N->getTransformFn())
346     return false;
347
348   if (isLeaf()) {
349     if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
350       if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
351         return DI->getDef() == NDI->getDef();
352     return getLeafValue() == N->getLeafValue();
353   }
354   
355   if (N->getOperator() != getOperator() ||
356       N->getNumChildren() != getNumChildren()) return false;
357   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
358     if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
359       return false;
360   return true;
361 }
362
363 /// clone - Make a copy of this tree and all of its children.
364 ///
365 TreePatternNode *TreePatternNode::clone() const {
366   TreePatternNode *New;
367   if (isLeaf()) {
368     New = new TreePatternNode(getLeafValue());
369   } else {
370     std::vector<TreePatternNode*> CChildren;
371     CChildren.reserve(Children.size());
372     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
373       CChildren.push_back(getChild(i)->clone());
374     New = new TreePatternNode(getOperator(), CChildren);
375   }
376   New->setName(getName());
377   New->setType(getExtType());
378   New->setPredicateFn(getPredicateFn());
379   New->setTransformFn(getTransformFn());
380   return New;
381 }
382
383 /// SubstituteFormalArguments - Replace the formal arguments in this tree
384 /// with actual values specified by ArgMap.
385 void TreePatternNode::
386 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
387   if (isLeaf()) return;
388   
389   for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
390     TreePatternNode *Child = getChild(i);
391     if (Child->isLeaf()) {
392       Init *Val = Child->getLeafValue();
393       if (dynamic_cast<DefInit*>(Val) &&
394           static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
395         // We found a use of a formal argument, replace it with its value.
396         Child = ArgMap[Child->getName()];
397         assert(Child && "Couldn't find formal argument!");
398         setChild(i, Child);
399       }
400     } else {
401       getChild(i)->SubstituteFormalArguments(ArgMap);
402     }
403   }
404 }
405
406
407 /// InlinePatternFragments - If this pattern refers to any pattern
408 /// fragments, inline them into place, giving us a pattern without any
409 /// PatFrag references.
410 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
411   if (isLeaf()) return this;  // nothing to do.
412   Record *Op = getOperator();
413   
414   if (!Op->isSubClassOf("PatFrag")) {
415     // Just recursively inline children nodes.
416     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
417       setChild(i, getChild(i)->InlinePatternFragments(TP));
418     return this;
419   }
420
421   // Otherwise, we found a reference to a fragment.  First, look up its
422   // TreePattern record.
423   TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
424   
425   // Verify that we are passing the right number of operands.
426   if (Frag->getNumArgs() != Children.size())
427     TP.error("'" + Op->getName() + "' fragment requires " +
428              utostr(Frag->getNumArgs()) + " operands!");
429
430   TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
431
432   // Resolve formal arguments to their actual value.
433   if (Frag->getNumArgs()) {
434     // Compute the map of formal to actual arguments.
435     std::map<std::string, TreePatternNode*> ArgMap;
436     for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
437       ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
438   
439     FragTree->SubstituteFormalArguments(ArgMap);
440   }
441   
442   FragTree->setName(getName());
443   
444   // Get a new copy of this fragment to stitch into here.
445   //delete this;    // FIXME: implement refcounting!
446   return FragTree;
447 }
448
449 /// getIntrinsicType - Check to see if the specified record has an intrinsic
450 /// type which should be applied to it.  This infer the type of register
451 /// references from the register file information, for example.
452 ///
453 static unsigned char getIntrinsicType(Record *R, bool NotRegisters,
454                                       TreePattern &TP) {
455   // Check to see if this is a register or a register class...
456   if (R->isSubClassOf("RegisterClass")) {
457     if (NotRegisters) return MVT::isUnknown;
458     return getValueType(R->getValueAsDef("RegType"));
459   } else if (R->isSubClassOf("PatFrag")) {
460     // Pattern fragment types will be resolved when they are inlined.
461     return MVT::isUnknown;
462   } else if (R->isSubClassOf("Register")) {
463     //const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
464     // TODO: if a register appears in exactly one regclass, we could use that
465     // type info.
466     return MVT::isUnknown;
467   } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
468     // Using a VTSDNode or CondCodeSDNode.
469     return MVT::Other;
470   } else if (R->getName() == "node") {
471     // Placeholder.
472     return MVT::isUnknown;
473   }
474   
475   TP.error("Unknown node flavor used in pattern: " + R->getName());
476   return MVT::Other;
477 }
478
479 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
480 /// this node and its children in the tree.  This returns true if it makes a
481 /// change, false otherwise.  If a type contradiction is found, throw an
482 /// exception.
483 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
484   if (isLeaf()) {
485     if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
486       // If it's a regclass or something else known, include the type.
487       return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
488                             TP);
489     } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
490       // Int inits are always integers. :)
491       bool MadeChange = UpdateNodeType(MVT::isInt, TP);
492       
493       if (hasTypeSet()) {
494         unsigned Size = MVT::getSizeInBits(getType());
495         // Make sure that the value is representable for this type.
496         if (Size < 32) {
497           int Val = (II->getValue() << (32-Size)) >> (32-Size);
498           if (Val != II->getValue())
499             TP.error("Sign-extended integer value '" + itostr(II->getValue()) +
500                      "' is out of range for type 'MVT::" + 
501                      getEnumName(getType()) + "'!");
502         }
503       }
504       
505       return MadeChange;
506     }
507     return false;
508   }
509   
510   // special handling for set, which isn't really an SDNode.
511   if (getOperator()->getName() == "set") {
512     assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
513     bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
514     MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
515     
516     // Types of operands must match.
517     MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtType(), TP);
518     MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtType(), TP);
519     MadeChange |= UpdateNodeType(MVT::isVoid, TP);
520     return MadeChange;
521   } else if (getOperator()->isSubClassOf("SDNode")) {
522     const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
523     
524     bool MadeChange = NI.ApplyTypeConstraints(this, TP);
525     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
526       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
527     return MadeChange;  
528   } else if (getOperator()->isSubClassOf("Instruction")) {
529     const DAGInstruction &Inst =
530       TP.getDAGISelEmitter().getInstruction(getOperator());
531     
532     assert(Inst.getNumResults() == 1 && "Only supports one result instrs!");
533     // Apply the result type to the node
534     bool MadeChange = UpdateNodeType(Inst.getResultType(0), TP);
535
536     if (getNumChildren() != Inst.getNumOperands())
537       TP.error("Instruction '" + getOperator()->getName() + " expects " +
538                utostr(Inst.getNumOperands()) + " operands, not " +
539                utostr(getNumChildren()) + " operands!");
540     for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
541       MadeChange |= getChild(i)->UpdateNodeType(Inst.getOperandType(i), TP);
542       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
543     }
544     return MadeChange;
545   } else {
546     assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
547     
548     // Node transforms always take one operand, and take and return the same
549     // type.
550     if (getNumChildren() != 1)
551       TP.error("Node transform '" + getOperator()->getName() +
552                "' requires one operand!");
553     bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
554     MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
555     return MadeChange;
556   }
557 }
558
559 /// canPatternMatch - If it is impossible for this pattern to match on this
560 /// target, fill in Reason and return false.  Otherwise, return true.  This is
561 /// used as a santity check for .td files (to prevent people from writing stuff
562 /// that can never possibly work), and to prevent the pattern permuter from
563 /// generating stuff that is useless.
564 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
565   if (isLeaf()) return true;
566
567   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
568     if (!getChild(i)->canPatternMatch(Reason, ISE))
569       return false;
570   
571   // If this node is a commutative operator, check that the LHS isn't an
572   // immediate.
573   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
574   if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
575     // Scan all of the operands of the node and make sure that only the last one
576     // is a constant node.
577     for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
578       if (!getChild(i)->isLeaf() && 
579           getChild(i)->getOperator()->getName() == "imm") {
580         Reason = "Immediate value must be on the RHS of commutative operators!";
581         return false;
582       }
583   }
584   
585   return true;
586 }
587
588 //===----------------------------------------------------------------------===//
589 // TreePattern implementation
590 //
591
592 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
593                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
594    isInputPattern = isInput;
595    for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
596      Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
597 }
598
599 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
600                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
601   isInputPattern = isInput;
602   Trees.push_back(ParseTreePattern(Pat));
603 }
604
605 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
606                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
607   isInputPattern = isInput;
608   Trees.push_back(Pat);
609 }
610
611
612
613 void TreePattern::error(const std::string &Msg) const {
614   dump();
615   throw "In " + TheRecord->getName() + ": " + Msg;
616 }
617
618 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
619   Record *Operator = Dag->getNodeType();
620   
621   if (Operator->isSubClassOf("ValueType")) {
622     // If the operator is a ValueType, then this must be "type cast" of a leaf
623     // node.
624     if (Dag->getNumArgs() != 1)
625       error("Type cast only takes one operand!");
626     
627     Init *Arg = Dag->getArg(0);
628     TreePatternNode *New;
629     if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
630       Record *R = DI->getDef();
631       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
632         Dag->setArg(0, new DagInit(R,
633                                 std::vector<std::pair<Init*, std::string> >()));
634         return ParseTreePattern(Dag);
635       }   
636       
637       New = new TreePatternNode(DI);
638     } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
639       New = ParseTreePattern(DI);
640     } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
641       New = new TreePatternNode(II);
642       if (!Dag->getArgName(0).empty())
643         error("Constant int argument should not have a name!");
644     } else {
645       Arg->dump();
646       error("Unknown leaf value for tree pattern!");
647       return 0;
648     }
649     
650     // Apply the type cast.
651     New->UpdateNodeType(getValueType(Operator), *this);
652     New->setName(Dag->getArgName(0));
653     return New;
654   }
655   
656   // Verify that this is something that makes sense for an operator.
657   if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
658       !Operator->isSubClassOf("Instruction") && 
659       !Operator->isSubClassOf("SDNodeXForm") &&
660       Operator->getName() != "set")
661     error("Unrecognized node '" + Operator->getName() + "'!");
662   
663   //  Check to see if this is something that is illegal in an input pattern.
664   if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
665       Operator->isSubClassOf("SDNodeXForm")))
666     error("Cannot use '" + Operator->getName() + "' in an input pattern!");
667   
668   std::vector<TreePatternNode*> Children;
669   
670   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
671     Init *Arg = Dag->getArg(i);
672     if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
673       Children.push_back(ParseTreePattern(DI));
674       if (Children.back()->getName().empty())
675         Children.back()->setName(Dag->getArgName(i));
676     } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
677       Record *R = DefI->getDef();
678       // Direct reference to a leaf DagNode or PatFrag?  Turn it into a
679       // TreePatternNode if its own.
680       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
681         Dag->setArg(i, new DagInit(R,
682                               std::vector<std::pair<Init*, std::string> >()));
683         --i;  // Revisit this node...
684       } else {
685         TreePatternNode *Node = new TreePatternNode(DefI);
686         Node->setName(Dag->getArgName(i));
687         Children.push_back(Node);
688         
689         // Input argument?
690         if (R->getName() == "node") {
691           if (Dag->getArgName(i).empty())
692             error("'node' argument requires a name to match with operand list");
693           Args.push_back(Dag->getArgName(i));
694         }
695       }
696     } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
697       TreePatternNode *Node = new TreePatternNode(II);
698       if (!Dag->getArgName(i).empty())
699         error("Constant int argument should not have a name!");
700       Children.push_back(Node);
701     } else {
702       std::cerr << '"';
703       Arg->dump();
704       std::cerr << "\": ";
705       error("Unknown leaf value for tree pattern!");
706     }
707   }
708   
709   return new TreePatternNode(Operator, Children);
710 }
711
712 /// InferAllTypes - Infer/propagate as many types throughout the expression
713 /// patterns as possible.  Return true if all types are infered, false
714 /// otherwise.  Throw an exception if a type contradiction is found.
715 bool TreePattern::InferAllTypes() {
716   bool MadeChange = true;
717   while (MadeChange) {
718     MadeChange = false;
719     for (unsigned i = 0, e = Trees.size(); i != e; ++i)
720       MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
721   }
722   
723   bool HasUnresolvedTypes = false;
724   for (unsigned i = 0, e = Trees.size(); i != e; ++i)
725     HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
726   return !HasUnresolvedTypes;
727 }
728
729 void TreePattern::print(std::ostream &OS) const {
730   OS << getRecord()->getName();
731   if (!Args.empty()) {
732     OS << "(" << Args[0];
733     for (unsigned i = 1, e = Args.size(); i != e; ++i)
734       OS << ", " << Args[i];
735     OS << ")";
736   }
737   OS << ": ";
738   
739   if (Trees.size() > 1)
740     OS << "[\n";
741   for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
742     OS << "\t";
743     Trees[i]->print(OS);
744     OS << "\n";
745   }
746
747   if (Trees.size() > 1)
748     OS << "]\n";
749 }
750
751 void TreePattern::dump() const { print(std::cerr); }
752
753
754
755 //===----------------------------------------------------------------------===//
756 // DAGISelEmitter implementation
757 //
758
759 // Parse all of the SDNode definitions for the target, populating SDNodes.
760 void DAGISelEmitter::ParseNodeInfo() {
761   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
762   while (!Nodes.empty()) {
763     SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
764     Nodes.pop_back();
765   }
766 }
767
768 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
769 /// map, and emit them to the file as functions.
770 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
771   OS << "\n// Node transformations.\n";
772   std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
773   while (!Xforms.empty()) {
774     Record *XFormNode = Xforms.back();
775     Record *SDNode = XFormNode->getValueAsDef("Opcode");
776     std::string Code = XFormNode->getValueAsCode("XFormFunction");
777     SDNodeXForms.insert(std::make_pair(XFormNode,
778                                        std::make_pair(SDNode, Code)));
779
780     if (!Code.empty()) {
781       std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
782       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
783
784       OS << "inline SDOperand Transform_" << XFormNode->getName()
785          << "(SDNode *" << C2 << ") {\n";
786       if (ClassName != "SDNode")
787         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
788       OS << Code << "\n}\n";
789     }
790
791     Xforms.pop_back();
792   }
793 }
794
795
796
797 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
798 /// file, building up the PatternFragments map.  After we've collected them all,
799 /// inline fragments together as necessary, so that there are no references left
800 /// inside a pattern fragment to a pattern fragment.
801 ///
802 /// This also emits all of the predicate functions to the output file.
803 ///
804 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
805   std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
806   
807   // First step, parse all of the fragments and emit predicate functions.
808   OS << "\n// Predicate functions.\n";
809   for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
810     DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
811     TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
812     PatternFragments[Fragments[i]] = P;
813     
814     // Validate the argument list, converting it to map, to discard duplicates.
815     std::vector<std::string> &Args = P->getArgList();
816     std::set<std::string> OperandsMap(Args.begin(), Args.end());
817     
818     if (OperandsMap.count(""))
819       P->error("Cannot have unnamed 'node' values in pattern fragment!");
820     
821     // Parse the operands list.
822     DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
823     if (OpsList->getNodeType()->getName() != "ops")
824       P->error("Operands list should start with '(ops ... '!");
825     
826     // Copy over the arguments.       
827     Args.clear();
828     for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
829       if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
830           static_cast<DefInit*>(OpsList->getArg(j))->
831           getDef()->getName() != "node")
832         P->error("Operands list should all be 'node' values.");
833       if (OpsList->getArgName(j).empty())
834         P->error("Operands list should have names for each operand!");
835       if (!OperandsMap.count(OpsList->getArgName(j)))
836         P->error("'" + OpsList->getArgName(j) +
837                  "' does not occur in pattern or was multiply specified!");
838       OperandsMap.erase(OpsList->getArgName(j));
839       Args.push_back(OpsList->getArgName(j));
840     }
841     
842     if (!OperandsMap.empty())
843       P->error("Operands list does not contain an entry for operand '" +
844                *OperandsMap.begin() + "'!");
845
846     // If there is a code init for this fragment, emit the predicate code and
847     // keep track of the fact that this fragment uses it.
848     std::string Code = Fragments[i]->getValueAsCode("Predicate");
849     if (!Code.empty()) {
850       assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
851       std::string ClassName =
852         getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
853       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
854       
855       OS << "inline bool Predicate_" << Fragments[i]->getName()
856          << "(SDNode *" << C2 << ") {\n";
857       if (ClassName != "SDNode")
858         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
859       OS << Code << "\n}\n";
860       P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
861     }
862     
863     // If there is a node transformation corresponding to this, keep track of
864     // it.
865     Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
866     if (!getSDNodeTransform(Transform).second.empty())    // not noop xform?
867       P->getOnlyTree()->setTransformFn(Transform);
868   }
869   
870   OS << "\n\n";
871
872   // Now that we've parsed all of the tree fragments, do a closure on them so
873   // that there are not references to PatFrags left inside of them.
874   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
875        E = PatternFragments.end(); I != E; ++I) {
876     TreePattern *ThePat = I->second;
877     ThePat->InlinePatternFragments();
878         
879     // Infer as many types as possible.  Don't worry about it if we don't infer
880     // all of them, some may depend on the inputs of the pattern.
881     try {
882       ThePat->InferAllTypes();
883     } catch (...) {
884       // If this pattern fragment is not supported by this target (no types can
885       // satisfy its constraints), just ignore it.  If the bogus pattern is
886       // actually used by instructions, the type consistency error will be
887       // reported there.
888     }
889     
890     // If debugging, print out the pattern fragment result.
891     DEBUG(ThePat->dump());
892   }
893 }
894
895 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
896 /// instruction input.  Return true if this is a real use.
897 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
898                       std::map<std::string, TreePatternNode*> &InstInputs) {
899   // No name -> not interesting.
900   if (Pat->getName().empty()) {
901     if (Pat->isLeaf()) {
902       DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
903       if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
904         I->error("Input " + DI->getDef()->getName() + " must be named!");
905
906     }
907     return false;
908   }
909
910   Record *Rec;
911   if (Pat->isLeaf()) {
912     DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
913     if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
914     Rec = DI->getDef();
915   } else {
916     assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
917     Rec = Pat->getOperator();
918   }
919
920   TreePatternNode *&Slot = InstInputs[Pat->getName()];
921   if (!Slot) {
922     Slot = Pat;
923   } else {
924     Record *SlotRec;
925     if (Slot->isLeaf()) {
926       SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
927     } else {
928       assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
929       SlotRec = Slot->getOperator();
930     }
931     
932     // Ensure that the inputs agree if we've already seen this input.
933     if (Rec != SlotRec)
934       I->error("All $" + Pat->getName() + " inputs must agree with each other");
935     if (Slot->getExtType() != Pat->getExtType())
936       I->error("All $" + Pat->getName() + " inputs must agree with each other");
937   }
938   return true;
939 }
940
941 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
942 /// part of "I", the instruction), computing the set of inputs and outputs of
943 /// the pattern.  Report errors if we see anything naughty.
944 void DAGISelEmitter::
945 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
946                             std::map<std::string, TreePatternNode*> &InstInputs,
947                             std::map<std::string, Record*> &InstResults) {
948   if (Pat->isLeaf()) {
949     bool isUse = HandleUse(I, Pat, InstInputs);
950     if (!isUse && Pat->getTransformFn())
951       I->error("Cannot specify a transform function for a non-input value!");
952     return;
953   } else if (Pat->getOperator()->getName() != "set") {
954     // If this is not a set, verify that the children nodes are not void typed,
955     // and recurse.
956     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
957       if (Pat->getChild(i)->getExtType() == MVT::isVoid)
958         I->error("Cannot have void nodes inside of patterns!");
959       FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
960     }
961     
962     // If this is a non-leaf node with no children, treat it basically as if
963     // it were a leaf.  This handles nodes like (imm).
964     bool isUse = false;
965     if (Pat->getNumChildren() == 0)
966       isUse = HandleUse(I, Pat, InstInputs);
967     
968     if (!isUse && Pat->getTransformFn())
969       I->error("Cannot specify a transform function for a non-input value!");
970     return;
971   } 
972   
973   // Otherwise, this is a set, validate and collect instruction results.
974   if (Pat->getNumChildren() == 0)
975     I->error("set requires operands!");
976   else if (Pat->getNumChildren() & 1)
977     I->error("set requires an even number of operands");
978   
979   if (Pat->getTransformFn())
980     I->error("Cannot specify a transform function on a set node!");
981   
982   // Check the set destinations.
983   unsigned NumValues = Pat->getNumChildren()/2;
984   for (unsigned i = 0; i != NumValues; ++i) {
985     TreePatternNode *Dest = Pat->getChild(i);
986     if (!Dest->isLeaf())
987       I->error("set destination should be a virtual register!");
988     
989     DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
990     if (!Val)
991       I->error("set destination should be a virtual register!");
992     
993     if (!Val->getDef()->isSubClassOf("RegisterClass"))
994       I->error("set destination should be a virtual register!");
995     if (Dest->getName().empty())
996       I->error("set destination must have a name!");
997     if (InstResults.count(Dest->getName()))
998       I->error("cannot set '" + Dest->getName() +"' multiple times");
999     InstResults[Dest->getName()] = Val->getDef();
1000
1001     // Verify and collect info from the computation.
1002     FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1003                                 InstInputs, InstResults);
1004   }
1005 }
1006
1007
1008 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1009 /// any fragments involved.  This populates the Instructions list with fully
1010 /// resolved instructions.
1011 void DAGISelEmitter::ParseInstructions() {
1012   std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1013   
1014   for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1015     ListInit *LI = 0;
1016     
1017     if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1018       LI = Instrs[i]->getValueAsListInit("Pattern");
1019     
1020     // If there is no pattern, only collect minimal information about the
1021     // instruction for its operand list.  We have to assume that there is one
1022     // result, as we have no detailed info.
1023     if (!LI || LI->getSize() == 0) {
1024       std::vector<MVT::ValueType> ResultTypes;
1025       std::vector<MVT::ValueType> OperandTypes;
1026       
1027       CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1028       
1029       // Doesn't even define a result?
1030       if (InstInfo.OperandList.size() == 0)
1031         continue;
1032       
1033       // Assume the first operand is the result.
1034       ResultTypes.push_back(InstInfo.OperandList[0].Ty);
1035       
1036       // The rest are inputs.
1037       for (unsigned j = 1, e = InstInfo.OperandList.size(); j != e; ++j)
1038         OperandTypes.push_back(InstInfo.OperandList[j].Ty);
1039       
1040       // Create and insert the instruction.
1041       Instructions.insert(std::make_pair(Instrs[i], 
1042                             DAGInstruction(0, ResultTypes, OperandTypes)));
1043       continue;  // no pattern.
1044     }
1045     
1046     // Parse the instruction.
1047     TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1048     // Inline pattern fragments into it.
1049     I->InlinePatternFragments();
1050     
1051     // Infer as many types as possible.  If we cannot infer all of them, we can
1052     // never do anything with this instruction pattern: report it to the user.
1053     if (!I->InferAllTypes())
1054       I->error("Could not infer all types in pattern!");
1055     
1056     // InstInputs - Keep track of all of the inputs of the instruction, along 
1057     // with the record they are declared as.
1058     std::map<std::string, TreePatternNode*> InstInputs;
1059     
1060     // InstResults - Keep track of all the virtual registers that are 'set'
1061     // in the instruction, including what reg class they are.
1062     std::map<std::string, Record*> InstResults;
1063     
1064     // Verify that the top-level forms in the instruction are of void type, and
1065     // fill in the InstResults map.
1066     for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1067       TreePatternNode *Pat = I->getTree(j);
1068       if (Pat->getExtType() != MVT::isVoid) {
1069         I->dump();
1070         I->error("Top-level forms in instruction pattern should have"
1071                  " void types");
1072       }
1073
1074       // Find inputs and outputs, and verify the structure of the uses/defs.
1075       FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
1076     }
1077
1078     // Now that we have inputs and outputs of the pattern, inspect the operands
1079     // list for the instruction.  This determines the order that operands are
1080     // added to the machine instruction the node corresponds to.
1081     unsigned NumResults = InstResults.size();
1082
1083     // Parse the operands list from the (ops) list, validating it.
1084     std::vector<std::string> &Args = I->getArgList();
1085     assert(Args.empty() && "Args list should still be empty here!");
1086     CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1087
1088     // Check that all of the results occur first in the list.
1089     std::vector<MVT::ValueType> ResultTypes;
1090     for (unsigned i = 0; i != NumResults; ++i) {
1091       if (i == CGI.OperandList.size())
1092         I->error("'" + InstResults.begin()->first +
1093                  "' set but does not appear in operand list!");
1094       const std::string &OpName = CGI.OperandList[i].Name;
1095       
1096       // Check that it exists in InstResults.
1097       Record *R = InstResults[OpName];
1098       if (R == 0)
1099         I->error("Operand $" + OpName + " should be a set destination: all "
1100                  "outputs must occur before inputs in operand list!");
1101       
1102       if (CGI.OperandList[i].Rec != R)
1103         I->error("Operand $" + OpName + " class mismatch!");
1104       
1105       // Remember the return type.
1106       ResultTypes.push_back(CGI.OperandList[i].Ty);
1107       
1108       // Okay, this one checks out.
1109       InstResults.erase(OpName);
1110     }
1111
1112     // Loop over the inputs next.  Make a copy of InstInputs so we can destroy
1113     // the copy while we're checking the inputs.
1114     std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1115
1116     std::vector<TreePatternNode*> ResultNodeOperands;
1117     std::vector<MVT::ValueType> OperandTypes;
1118     for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1119       const std::string &OpName = CGI.OperandList[i].Name;
1120       if (OpName.empty())
1121         I->error("Operand #" + utostr(i) + " in operands list has no name!");
1122
1123       if (!InstInputsCheck.count(OpName))
1124         I->error("Operand $" + OpName +
1125                  " does not appear in the instruction pattern");
1126       TreePatternNode *InVal = InstInputsCheck[OpName];
1127       InstInputsCheck.erase(OpName);   // It occurred, remove from map.
1128       if (CGI.OperandList[i].Ty != InVal->getExtType())
1129         I->error("Operand $" + OpName +
1130                  "'s type disagrees between the operand and pattern");
1131       OperandTypes.push_back(InVal->getType());
1132       
1133       // Construct the result for the dest-pattern operand list.
1134       TreePatternNode *OpNode = InVal->clone();
1135       
1136       // No predicate is useful on the result.
1137       OpNode->setPredicateFn("");
1138       
1139       // Promote the xform function to be an explicit node if set.
1140       if (Record *Xform = OpNode->getTransformFn()) {
1141         OpNode->setTransformFn(0);
1142         std::vector<TreePatternNode*> Children;
1143         Children.push_back(OpNode);
1144         OpNode = new TreePatternNode(Xform, Children);
1145       }
1146       
1147       ResultNodeOperands.push_back(OpNode);
1148     }
1149     
1150     if (!InstInputsCheck.empty())
1151       I->error("Input operand $" + InstInputsCheck.begin()->first +
1152                " occurs in pattern but not in operands list!");
1153
1154     TreePatternNode *ResultPattern =
1155       new TreePatternNode(I->getRecord(), ResultNodeOperands);
1156
1157     // Create and insert the instruction.
1158     DAGInstruction TheInst(I, ResultTypes, OperandTypes);
1159     Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1160
1161     // Use a temporary tree pattern to infer all types and make sure that the
1162     // constructed result is correct.  This depends on the instruction already
1163     // being inserted into the Instructions map.
1164     TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1165     Temp.InferAllTypes();
1166
1167     DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1168     TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1169     
1170     DEBUG(I->dump());
1171   }
1172    
1173   // If we can, convert the instructions to be patterns that are matched!
1174   for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1175        E = Instructions.end(); II != E; ++II) {
1176     TreePattern *I = II->second.getPattern();
1177     if (I == 0) continue;  // No pattern.
1178     
1179     if (I->getNumTrees() != 1) {
1180       std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1181       continue;
1182     }
1183     TreePatternNode *Pattern = I->getTree(0);
1184     if (Pattern->getOperator()->getName() != "set")
1185       continue;  // Not a set (store or something?)
1186     
1187     if (Pattern->getNumChildren() != 2)
1188       continue;  // Not a set of a single value (not handled so far)
1189     
1190     TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
1191     
1192     std::string Reason;
1193     if (!SrcPattern->canPatternMatch(Reason, *this))
1194       I->error("Instruction can never match: " + Reason);
1195     
1196     TreePatternNode *DstPattern = II->second.getResultPattern();
1197     PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
1198   }
1199 }
1200
1201 void DAGISelEmitter::ParsePatterns() {
1202   std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1203
1204   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1205     DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1206     TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1207
1208     // Inline pattern fragments into it.
1209     Pattern->InlinePatternFragments();
1210     
1211     // Infer as many types as possible.  If we cannot infer all of them, we can
1212     // never do anything with this pattern: report it to the user.
1213     if (!Pattern->InferAllTypes())
1214       Pattern->error("Could not infer all types in pattern!");
1215
1216     // Validate that the input pattern is correct.
1217     {
1218       std::map<std::string, TreePatternNode*> InstInputs;
1219       std::map<std::string, Record*> InstResults;
1220       FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1221                                   InstInputs, InstResults);
1222     }
1223     
1224     ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1225     if (LI->getSize() == 0) continue;  // no pattern.
1226     
1227     // Parse the instruction.
1228     TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1229     
1230     // Inline pattern fragments into it.
1231     Result->InlinePatternFragments();
1232     
1233     // Infer as many types as possible.  If we cannot infer all of them, we can
1234     // never do anything with this pattern: report it to the user.
1235     if (!Result->InferAllTypes())
1236       Result->error("Could not infer all types in pattern result!");
1237    
1238     if (Result->getNumTrees() != 1)
1239       Result->error("Cannot handle instructions producing instructions "
1240                     "with temporaries yet!");
1241
1242     std::string Reason;
1243     if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1244       Pattern->error("Pattern can never match: " + Reason);
1245     
1246     PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1247                                              Result->getOnlyTree()));
1248   }
1249 }
1250
1251 /// CombineChildVariants - Given a bunch of permutations of each child of the
1252 /// 'operator' node, put them together in all possible ways.
1253 static void CombineChildVariants(TreePatternNode *Orig, 
1254                const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1255                                  std::vector<TreePatternNode*> &OutVariants,
1256                                  DAGISelEmitter &ISE) {
1257   // Make sure that each operand has at least one variant to choose from.
1258   for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1259     if (ChildVariants[i].empty())
1260       return;
1261         
1262   // The end result is an all-pairs construction of the resultant pattern.
1263   std::vector<unsigned> Idxs;
1264   Idxs.resize(ChildVariants.size());
1265   bool NotDone = true;
1266   while (NotDone) {
1267     // Create the variant and add it to the output list.
1268     std::vector<TreePatternNode*> NewChildren;
1269     for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1270       NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1271     TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1272     
1273     // Copy over properties.
1274     R->setName(Orig->getName());
1275     R->setPredicateFn(Orig->getPredicateFn());
1276     R->setTransformFn(Orig->getTransformFn());
1277     R->setType(Orig->getExtType());
1278     
1279     // If this pattern cannot every match, do not include it as a variant.
1280     std::string ErrString;
1281     if (!R->canPatternMatch(ErrString, ISE)) {
1282       delete R;
1283     } else {
1284       bool AlreadyExists = false;
1285       
1286       // Scan to see if this pattern has already been emitted.  We can get
1287       // duplication due to things like commuting:
1288       //   (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1289       // which are the same pattern.  Ignore the dups.
1290       for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1291         if (R->isIsomorphicTo(OutVariants[i])) {
1292           AlreadyExists = true;
1293           break;
1294         }
1295       
1296       if (AlreadyExists)
1297         delete R;
1298       else
1299         OutVariants.push_back(R);
1300     }
1301     
1302     // Increment indices to the next permutation.
1303     NotDone = false;
1304     // Look for something we can increment without causing a wrap-around.
1305     for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1306       if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1307         NotDone = true;   // Found something to increment.
1308         break;
1309       }
1310       Idxs[IdxsIdx] = 0;
1311     }
1312   }
1313 }
1314
1315 /// CombineChildVariants - A helper function for binary operators.
1316 ///
1317 static void CombineChildVariants(TreePatternNode *Orig, 
1318                                  const std::vector<TreePatternNode*> &LHS,
1319                                  const std::vector<TreePatternNode*> &RHS,
1320                                  std::vector<TreePatternNode*> &OutVariants,
1321                                  DAGISelEmitter &ISE) {
1322   std::vector<std::vector<TreePatternNode*> > ChildVariants;
1323   ChildVariants.push_back(LHS);
1324   ChildVariants.push_back(RHS);
1325   CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1326 }  
1327
1328
1329 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1330                                      std::vector<TreePatternNode *> &Children) {
1331   assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1332   Record *Operator = N->getOperator();
1333   
1334   // Only permit raw nodes.
1335   if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1336       N->getTransformFn()) {
1337     Children.push_back(N);
1338     return;
1339   }
1340
1341   if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1342     Children.push_back(N->getChild(0));
1343   else
1344     GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1345
1346   if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1347     Children.push_back(N->getChild(1));
1348   else
1349     GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1350 }
1351
1352 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1353 /// the (potentially recursive) pattern by using algebraic laws.
1354 ///
1355 static void GenerateVariantsOf(TreePatternNode *N,
1356                                std::vector<TreePatternNode*> &OutVariants,
1357                                DAGISelEmitter &ISE) {
1358   // We cannot permute leaves.
1359   if (N->isLeaf()) {
1360     OutVariants.push_back(N);
1361     return;
1362   }
1363
1364   // Look up interesting info about the node.
1365   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1366
1367   // If this node is associative, reassociate.
1368   if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1369     // Reassociate by pulling together all of the linked operators 
1370     std::vector<TreePatternNode*> MaximalChildren;
1371     GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1372
1373     // Only handle child sizes of 3.  Otherwise we'll end up trying too many
1374     // permutations.
1375     if (MaximalChildren.size() == 3) {
1376       // Find the variants of all of our maximal children.
1377       std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1378       GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1379       GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1380       GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1381       
1382       // There are only two ways we can permute the tree:
1383       //   (A op B) op C    and    A op (B op C)
1384       // Within these forms, we can also permute A/B/C.
1385       
1386       // Generate legal pair permutations of A/B/C.
1387       std::vector<TreePatternNode*> ABVariants;
1388       std::vector<TreePatternNode*> BAVariants;
1389       std::vector<TreePatternNode*> ACVariants;
1390       std::vector<TreePatternNode*> CAVariants;
1391       std::vector<TreePatternNode*> BCVariants;
1392       std::vector<TreePatternNode*> CBVariants;
1393       CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1394       CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1395       CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1396       CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1397       CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1398       CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1399
1400       // Combine those into the result: (x op x) op x
1401       CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1402       CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1403       CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1404       CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1405       CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1406       CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1407
1408       // Combine those into the result: x op (x op x)
1409       CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1410       CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1411       CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1412       CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1413       CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1414       CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1415       return;
1416     }
1417   }
1418   
1419   // Compute permutations of all children.
1420   std::vector<std::vector<TreePatternNode*> > ChildVariants;
1421   ChildVariants.resize(N->getNumChildren());
1422   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1423     GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1424
1425   // Build all permutations based on how the children were formed.
1426   CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1427
1428   // If this node is commutative, consider the commuted order.
1429   if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1430     assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1431     // Consider the commuted order.
1432     CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1433                          OutVariants, ISE);
1434   }
1435 }
1436
1437
1438 // GenerateVariants - Generate variants.  For example, commutative patterns can
1439 // match multiple ways.  Add them to PatternsToMatch as well.
1440 void DAGISelEmitter::GenerateVariants() {
1441   
1442   DEBUG(std::cerr << "Generating instruction variants.\n");
1443   
1444   // Loop over all of the patterns we've collected, checking to see if we can
1445   // generate variants of the instruction, through the exploitation of
1446   // identities.  This permits the target to provide agressive matching without
1447   // the .td file having to contain tons of variants of instructions.
1448   //
1449   // Note that this loop adds new patterns to the PatternsToMatch list, but we
1450   // intentionally do not reconsider these.  Any variants of added patterns have
1451   // already been added.
1452   //
1453   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1454     std::vector<TreePatternNode*> Variants;
1455     GenerateVariantsOf(PatternsToMatch[i].first, Variants, *this);
1456
1457     assert(!Variants.empty() && "Must create at least original variant!");
1458     Variants.erase(Variants.begin());  // Remove the original pattern.
1459
1460     if (Variants.empty())  // No variants for this pattern.
1461       continue;
1462
1463     DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1464           PatternsToMatch[i].first->dump();
1465           std::cerr << "\n");
1466
1467     for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1468       TreePatternNode *Variant = Variants[v];
1469
1470       DEBUG(std::cerr << "  VAR#" << v <<  ": ";
1471             Variant->dump();
1472             std::cerr << "\n");
1473       
1474       // Scan to see if an instruction or explicit pattern already matches this.
1475       bool AlreadyExists = false;
1476       for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1477         // Check to see if this variant already exists.
1478         if (Variant->isIsomorphicTo(PatternsToMatch[p].first)) {
1479           DEBUG(std::cerr << "  *** ALREADY EXISTS, ignoring variant.\n");
1480           AlreadyExists = true;
1481           break;
1482         }
1483       }
1484       // If we already have it, ignore the variant.
1485       if (AlreadyExists) continue;
1486
1487       // Otherwise, add it to the list of patterns we have.
1488       PatternsToMatch.push_back(std::make_pair(Variant, 
1489                                                PatternsToMatch[i].second));
1490     }
1491
1492     DEBUG(std::cerr << "\n");
1493   }
1494 }
1495
1496
1497 /// getPatternSize - Return the 'size' of this pattern.  We want to match large
1498 /// patterns before small ones.  This is used to determine the size of a
1499 /// pattern.
1500 static unsigned getPatternSize(TreePatternNode *P) {
1501   assert(isExtIntegerVT(P->getExtType()) || 
1502          isExtFloatingPointVT(P->getExtType()) &&
1503          "Not a valid pattern node to size!");
1504   unsigned Size = 1;  // The node itself.
1505   
1506   // Count children in the count if they are also nodes.
1507   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1508     TreePatternNode *Child = P->getChild(i);
1509     if (!Child->isLeaf() && Child->getExtType() != MVT::Other)
1510       Size += getPatternSize(Child);
1511     else if (Child->isLeaf() && dynamic_cast<IntInit*>(Child->getLeafValue())) {
1512       ++Size;  // Matches a ConstantSDNode.
1513     }
1514   }
1515   
1516   return Size;
1517 }
1518
1519 /// getResultPatternCost - Compute the number of instructions for this pattern.
1520 /// This is a temporary hack.  We should really include the instruction
1521 /// latencies in this calculation.
1522 static unsigned getResultPatternCost(TreePatternNode *P) {
1523   if (P->isLeaf()) return 0;
1524   
1525   unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1526   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1527     Cost += getResultPatternCost(P->getChild(i));
1528   return Cost;
1529 }
1530
1531 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1532 // In particular, we want to match maximal patterns first and lowest cost within
1533 // a particular complexity first.
1534 struct PatternSortingPredicate {
1535   bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1536                   DAGISelEmitter::PatternToMatch *RHS) {
1537     unsigned LHSSize = getPatternSize(LHS->first);
1538     unsigned RHSSize = getPatternSize(RHS->first);
1539     if (LHSSize > RHSSize) return true;   // LHS -> bigger -> less cost
1540     if (LHSSize < RHSSize) return false;
1541     
1542     // If the patterns have equal complexity, compare generated instruction cost
1543     return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1544   }
1545 };
1546
1547 /// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
1548 /// if the match fails.  At this point, we already know that the opcode for N
1549 /// matches, and the SDNode for the result has the RootName specified name.
1550 void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
1551                                          const std::string &RootName,
1552                                      std::map<std::string,std::string> &VarMap,
1553                                          unsigned PatternNo, std::ostream &OS) {
1554   if (N->isLeaf()) {
1555     if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1556       OS << "      if (cast<ConstantSDNode>(" << RootName
1557          << ")->getSignExtended() != " << II->getValue() << ")\n"
1558          << "        goto P" << PatternNo << "Fail;\n";
1559       return;
1560     }
1561     assert(0 && "Cannot match this as a leaf value!");
1562     abort();
1563   }
1564   
1565   // If this node has a name associated with it, capture it in VarMap.  If
1566   // we already saw this in the pattern, emit code to verify dagness.
1567   if (!N->getName().empty()) {
1568     std::string &VarMapEntry = VarMap[N->getName()];
1569     if (VarMapEntry.empty()) {
1570       VarMapEntry = RootName;
1571     } else {
1572       // If we get here, this is a second reference to a specific name.  Since
1573       // we already have checked that the first reference is valid, we don't
1574       // have to recursively match it, just check that it's the same as the
1575       // previously named thing.
1576       OS << "      if (" << VarMapEntry << " != " << RootName
1577          << ") goto P" << PatternNo << "Fail;\n";
1578       return;
1579     }
1580   }
1581   
1582   // Emit code to load the child nodes and match their contents recursively.
1583   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1584     OS << "      SDOperand " << RootName << i <<" = " << RootName
1585        << ".getOperand(" << i << ");\n";
1586     TreePatternNode *Child = N->getChild(i);
1587     
1588     if (!Child->isLeaf()) {
1589       // If it's not a leaf, recursively match.
1590       const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
1591       OS << "      if (" << RootName << i << ".getOpcode() != "
1592          << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
1593       EmitMatchForPattern(Child, RootName + utostr(i), VarMap, PatternNo, OS);
1594     } else {
1595       // If this child has a name associated with it, capture it in VarMap.  If
1596       // we already saw this in the pattern, emit code to verify dagness.
1597       if (!Child->getName().empty()) {
1598         std::string &VarMapEntry = VarMap[Child->getName()];
1599         if (VarMapEntry.empty()) {
1600           VarMapEntry = RootName + utostr(i);
1601         } else {
1602           // If we get here, this is a second reference to a specific name.  Since
1603           // we already have checked that the first reference is valid, we don't
1604           // have to recursively match it, just check that it's the same as the
1605           // previously named thing.
1606           OS << "      if (" << VarMapEntry << " != " << RootName << i
1607           << ") goto P" << PatternNo << "Fail;\n";
1608           continue;
1609         }
1610       }
1611       
1612       // Handle leaves of various types.
1613       if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1614         Record *LeafRec = DI->getDef();
1615         if (LeafRec->isSubClassOf("RegisterClass")) {
1616           // Handle register references.  Nothing to do here.
1617         } else if (LeafRec->isSubClassOf("ValueType")) {
1618           // Make sure this is the specified value type.
1619           OS << "      if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1620           << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1621           << "Fail;\n";
1622         } else if (LeafRec->isSubClassOf("CondCode")) {
1623           // Make sure this is the specified cond code.
1624           OS << "      if (cast<CondCodeSDNode>(" << RootName << i
1625              << ")->get() != " << "ISD::" << LeafRec->getName()
1626              << ") goto P" << PatternNo << "Fail;\n";
1627         } else {
1628           Child->dump();
1629           assert(0 && "Unknown leaf type!");
1630         }
1631       } else if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
1632         OS << "      if (!isa<ConstantSDNode>(" << RootName << i << ") ||\n"
1633            << "          cast<ConstantSDNode>(" << RootName << i
1634            << ")->getSignExtended() != " << II->getValue() << ")\n"
1635            << "        goto P" << PatternNo << "Fail;\n";
1636       } else {
1637         Child->dump();
1638         assert(0 && "Unknown leaf type!");
1639       }
1640     }
1641   }
1642   
1643   // If there is a node predicate for this, emit the call.
1644   if (!N->getPredicateFn().empty())
1645     OS << "      if (!" << N->getPredicateFn() << "(" << RootName
1646        << ".Val)) goto P" << PatternNo << "Fail;\n";
1647 }
1648
1649 /// CodeGenPatternResult - Emit the action for a pattern.  Now that it has
1650 /// matched, we actually have to build a DAG!
1651 unsigned DAGISelEmitter::
1652 CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1653                      std::map<std::string,std::string> &VariableMap, 
1654                      std::ostream &OS, bool isRoot) {
1655   // This is something selected from the pattern we matched.
1656   if (!N->getName().empty()) {
1657     assert(!isRoot && "Root of pattern cannot be a leaf!");
1658     std::string &Val = VariableMap[N->getName()];
1659     assert(!Val.empty() &&
1660            "Variable referenced but not defined and not caught earlier!");
1661     if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1662       // Already selected this operand, just return the tmpval.
1663       return atoi(Val.c_str()+3);
1664     }
1665     
1666     unsigned ResNo = Ctr++;
1667     if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1668       switch (N->getType()) {
1669       default: assert(0 && "Unknown type for constant node!");
1670       case MVT::i1:  OS << "      bool Tmp"; break;
1671       case MVT::i8:  OS << "      unsigned char Tmp"; break;
1672       case MVT::i16: OS << "      unsigned short Tmp"; break;
1673       case MVT::i32: OS << "      unsigned Tmp"; break;
1674       case MVT::i64: OS << "      uint64_t Tmp"; break;
1675       }
1676       OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1677       OS << "      SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1678          << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1679     } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
1680       OS << "      SDOperand Tmp" << ResNo << " = " << Val << ";\n";
1681     } else {
1682       OS << "      SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1683     }
1684     // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1685     // value if used multiple times by this pattern result.
1686     Val = "Tmp"+utostr(ResNo);
1687     return ResNo;
1688   }
1689   
1690   if (N->isLeaf()) {
1691     // If this is an explicit register reference, handle it.
1692     if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1693       unsigned ResNo = Ctr++;
1694       if (DI->getDef()->isSubClassOf("Register")) {
1695         OS << "      SDOperand Tmp" << ResNo << " = CurDAG->getRegister("
1696            << getQualifiedName(DI->getDef()) << ", MVT::"
1697            << getEnumName(N->getType())
1698            << ");\n";
1699         return ResNo;
1700       }
1701     } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1702       unsigned ResNo = Ctr++;
1703       OS << "      SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant("
1704          << II->getValue() << ", MVT::"
1705         << getEnumName(N->getType())
1706         << ");\n";
1707       return ResNo;
1708     }
1709     
1710     N->dump();
1711     assert(0 && "Unknown leaf type!");
1712     return ~0U;
1713   }
1714
1715   Record *Op = N->getOperator();
1716   if (Op->isSubClassOf("Instruction")) {
1717     // Emit all of the operands.
1718     std::vector<unsigned> Ops;
1719     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1720       Ops.push_back(CodeGenPatternResult(N->getChild(i), Ctr, VariableMap, OS));
1721
1722     CodeGenInstruction &II = Target.getInstruction(Op->getName());
1723     unsigned ResNo = Ctr++;
1724     
1725     if (!isRoot) {
1726       OS << "      SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1727          << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1728          << getEnumName(N->getType());
1729       for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1730         OS << ", Tmp" << Ops[i];
1731       OS << ");\n";
1732     } else {
1733       // If this instruction is the root, and if there is only one use of it,
1734       // use SelectNodeTo instead of getTargetNode to avoid an allocation.
1735       OS << "      if (N.Val->hasOneUse()) {\n";
1736       OS << "        CurDAG->SelectNodeTo(N.Val, "
1737          << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1738          << getEnumName(N->getType());
1739       for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1740         OS << ", Tmp" << Ops[i];
1741       OS << ");\n";
1742       OS << "        return N;\n";
1743       OS << "      } else {\n";
1744       OS << "        return CodeGenMap[N] = CurDAG->getTargetNode("
1745       << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1746       << getEnumName(N->getType());
1747       for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1748         OS << ", Tmp" << Ops[i];
1749       OS << ");\n";
1750       OS << "      }\n";
1751     }
1752     return ResNo;
1753   } else if (Op->isSubClassOf("SDNodeXForm")) {
1754     assert(N->getNumChildren() == 1 && "node xform should have one child!");
1755     unsigned OpVal = CodeGenPatternResult(N->getChild(0), Ctr, VariableMap, OS);
1756     
1757     unsigned ResNo = Ctr++;
1758     OS << "      SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1759        << "(Tmp" << OpVal << ".Val);\n";
1760     if (isRoot) {
1761       OS << "      CodeGenMap[N] = Tmp" << ResNo << ";\n";
1762       OS << "      return Tmp" << ResNo << ";\n";
1763     }
1764     return ResNo;
1765   } else {
1766     N->dump();
1767     assert(0 && "Unknown node in result pattern!");
1768     return ~0U;
1769   }
1770 }
1771
1772 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1773 /// type information from it.
1774 static void RemoveAllTypes(TreePatternNode *N) {
1775   N->setType(MVT::isUnknown);
1776   if (!N->isLeaf())
1777     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1778       RemoveAllTypes(N->getChild(i));
1779 }
1780
1781 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
1782 /// add it to the tree.  'Pat' and 'Other' are isomorphic trees except that 
1783 /// 'Pat' may be missing types.  If we find an unresolved type to add a check
1784 /// for, this returns true otherwise false if Pat has all types.
1785 static bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1786                                const std::string &Prefix, unsigned PatternNo,
1787                                std::ostream &OS) {
1788   // Did we find one?
1789   if (!Pat->hasTypeSet()) {
1790     // Move a type over from 'other' to 'pat'.
1791     Pat->setType(Other->getType());
1792     OS << "      if (" << Prefix << ".getValueType() != MVT::"
1793        << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
1794     return true;
1795   } else if (Pat->isLeaf()) {
1796     return false;
1797   }
1798   
1799   for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i)
1800     if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1801                            Prefix + utostr(i), PatternNo, OS))
1802       return true;
1803   return false;
1804 }
1805
1806 Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1807   Record *N = Records.getDef(Name);
1808   assert(N && N->isSubClassOf("SDNode") && "Bad argument");
1809   return N;
1810 }
1811
1812 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1813 /// stream to match the pattern, and generate the code for the match if it
1814 /// succeeds.
1815 void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1816                                         std::ostream &OS) {
1817   static unsigned PatternCount = 0;
1818   unsigned PatternNo = PatternCount++;
1819   OS << "    { // Pattern #" << PatternNo << ": ";
1820   Pattern.first->print(OS);
1821   OS << "\n      // Emits: ";
1822   Pattern.second->print(OS);
1823   OS << "\n";
1824   OS << "      // Pattern complexity = " << getPatternSize(Pattern.first)
1825      << "  cost = " << getResultPatternCost(Pattern.second) << "\n";
1826
1827   // Emit the matcher, capturing named arguments in VariableMap.
1828   std::map<std::string,std::string> VariableMap;
1829   EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
1830   
1831   // TP - Get *SOME* tree pattern, we don't care which.
1832   TreePattern &TP = *PatternFragments.begin()->second;
1833   
1834   // At this point, we know that we structurally match the pattern, but the
1835   // types of the nodes may not match.  Figure out the fewest number of type 
1836   // comparisons we need to emit.  For example, if there is only one integer
1837   // type supported by a target, there should be no type comparisons at all for
1838   // integer patterns!
1839   //
1840   // To figure out the fewest number of type checks needed, clone the pattern,
1841   // remove the types, then perform type inference on the pattern as a whole.
1842   // If there are unresolved types, emit an explicit check for those types,
1843   // apply the type to the tree, then rerun type inference.  Iterate until all
1844   // types are resolved.
1845   //
1846   TreePatternNode *Pat = Pattern.first->clone();
1847   RemoveAllTypes(Pat);
1848   
1849   do {
1850     // Resolve/propagate as many types as possible.
1851     try {
1852       bool MadeChange = true;
1853       while (MadeChange)
1854         MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
1855     } catch (...) {
1856       assert(0 && "Error: could not find consistent types for something we"
1857              " already decided was ok!");
1858       abort();
1859     }
1860
1861     // Insert a check for an unresolved type and add it to the tree.  If we find
1862     // an unresolved type to add a check for, this returns true and we iterate,
1863     // otherwise we are done.
1864   } while (InsertOneTypeCheck(Pat, Pattern.first, "N", PatternNo, OS));
1865   
1866   unsigned TmpNo = 0;
1867   CodeGenPatternResult(Pattern.second, TmpNo,
1868                        VariableMap, OS, true /*the root*/);
1869   delete Pat;
1870   
1871   OS << "    }\n  P" << PatternNo << "Fail:\n";
1872 }
1873
1874
1875 namespace {
1876   /// CompareByRecordName - An ordering predicate that implements less-than by
1877   /// comparing the names records.
1878   struct CompareByRecordName {
1879     bool operator()(const Record *LHS, const Record *RHS) const {
1880       // Sort by name first.
1881       if (LHS->getName() < RHS->getName()) return true;
1882       // If both names are equal, sort by pointer.
1883       return LHS->getName() == RHS->getName() && LHS < RHS;
1884     }
1885   };
1886 }
1887
1888 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1889   std::string InstNS = Target.inst_begin()->second.Namespace;
1890   if (!InstNS.empty()) InstNS += "::";
1891   
1892   // Emit boilerplate.
1893   OS << "// The main instruction selector code.\n"
1894      << "SDOperand SelectCode(SDOperand N) {\n"
1895      << "  if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1896      << "      N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1897      << "INSTRUCTION_LIST_END))\n"
1898      << "    return N;   // Already selected.\n\n"
1899      << "  if (!N.Val->hasOneUse()) {\n"
1900   << "    std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
1901      << "    if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
1902      << "  }\n"
1903      << "  switch (N.getOpcode()) {\n"
1904      << "  default: break;\n"
1905      << "  case ISD::EntryToken:       // These leaves remain the same.\n"
1906      << "    return N;\n"
1907      << "  case ISD::AssertSext:\n"
1908      << "  case ISD::AssertZext: {\n"
1909      << "    SDOperand Tmp0 = Select(N.getOperand(0));\n"
1910      << "    if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
1911      << "    return Tmp0;\n"
1912      << "  }\n"
1913      << "  case ISD::TokenFactor:\n"
1914      << "    if (N.getNumOperands() == 2) {\n"
1915      << "      SDOperand Op0 = Select(N.getOperand(0));\n"
1916      << "      SDOperand Op1 = Select(N.getOperand(1));\n"
1917      << "      return CodeGenMap[N] =\n"
1918      << "          CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
1919      << "    } else {\n"
1920      << "      std::vector<SDOperand> Ops;\n"
1921      << "      for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1922      << "        Ops.push_back(Select(N.getOperand(i)));\n"
1923      << "       return CodeGenMap[N] = \n"
1924      << "               CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
1925      << "    }\n"
1926      << "  case ISD::CopyFromReg: {\n"
1927      << "    SDOperand Chain = Select(N.getOperand(0));\n"
1928      << "    if (Chain == N.getOperand(0)) return N; // No change\n"
1929      << "    SDOperand New = CurDAG->getCopyFromReg(Chain,\n"
1930      << "                    cast<RegisterSDNode>(N.getOperand(1))->getReg(),\n"
1931      << "                                         N.Val->getValueType(0));\n"
1932      << "    return New.getValue(N.ResNo);\n"
1933      << "  }\n"
1934      << "  case ISD::CopyToReg: {\n"
1935      << "    SDOperand Chain = Select(N.getOperand(0));\n"
1936      << "    SDOperand Reg = N.getOperand(1);\n"
1937      << "    SDOperand Val = Select(N.getOperand(2));\n"
1938      << "    return CodeGenMap[N] = \n"
1939      << "                   CurDAG->getNode(ISD::CopyToReg, MVT::Other,\n"
1940      << "                                   Chain, Reg, Val);\n"
1941      << "  }\n";
1942     
1943   // Group the patterns by their top-level opcodes.
1944   std::map<Record*, std::vector<PatternToMatch*>,
1945            CompareByRecordName> PatternsByOpcode;
1946   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
1947     if (!PatternsToMatch[i].first->isLeaf()) {
1948       PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
1949          .push_back(&PatternsToMatch[i]);
1950     } else {
1951       if (IntInit *II = 
1952              dynamic_cast<IntInit*>(PatternsToMatch[i].first->getLeafValue())) {
1953         PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
1954       } else {
1955         std::cerr << "Unrecognized opcode '";
1956         PatternsToMatch[i].first->dump();
1957         std::cerr << "' on tree pattern '";
1958         std::cerr << PatternsToMatch[i].second->getOperator()->getName();
1959         std::cerr << "'!\n";
1960         exit(1);
1961       }
1962     }
1963   
1964   // Loop over all of the case statements.
1965   for (std::map<Record*, std::vector<PatternToMatch*>,
1966                 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
1967        E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
1968     const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
1969     std::vector<PatternToMatch*> &Patterns = PBOI->second;
1970     
1971     OS << "  case " << OpcodeInfo.getEnumName() << ":\n";
1972
1973     // We want to emit all of the matching code now.  However, we want to emit
1974     // the matches in order of minimal cost.  Sort the patterns so the least
1975     // cost one is at the start.
1976     std::stable_sort(Patterns.begin(), Patterns.end(),
1977                      PatternSortingPredicate());
1978     
1979     for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1980       EmitCodeForPattern(*Patterns[i], OS);
1981     OS << "    break;\n\n";
1982   }
1983   
1984
1985   OS << "  } // end of big switch.\n\n"
1986      << "  std::cerr << \"Cannot yet select: \";\n"
1987      << "  N.Val->dump();\n"
1988      << "  std::cerr << '\\n';\n"
1989      << "  abort();\n"
1990      << "}\n";
1991 }
1992
1993 void DAGISelEmitter::run(std::ostream &OS) {
1994   EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1995                        " target", OS);
1996   
1997   OS << "// *** NOTE: This file is #included into the middle of the target\n"
1998      << "// *** instruction selector class.  These functions are really "
1999      << "methods.\n\n";
2000   
2001   OS << "// Instance var to keep track of multiply used nodes that have \n"
2002      << "// already been selected.\n"
2003      << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
2004   
2005   ParseNodeInfo();
2006   ParseNodeTransforms(OS);
2007   ParsePatternFragments(OS);
2008   ParseInstructions();
2009   ParsePatterns();
2010   
2011   // Generate variants.  For example, commutative patterns can match
2012   // multiple ways.  Add them to PatternsToMatch as well.
2013   GenerateVariants();
2014
2015   
2016   DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
2017         for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2018           std::cerr << "PATTERN: ";  PatternsToMatch[i].first->dump();
2019           std::cerr << "\nRESULT:  ";PatternsToMatch[i].second->dump();
2020           std::cerr << "\n";
2021         });
2022   
2023   // At this point, we have full information about the 'Patterns' we need to
2024   // parse, both implicitly from instructions as well as from explicit pattern
2025   // definitions.  Emit the resultant instruction selector.
2026   EmitInstructionSelector(OS);  
2027   
2028   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
2029        E = PatternFragments.end(); I != E; ++I)
2030     delete I->second;
2031   PatternFragments.clear();
2032
2033   Instructions.clear();
2034 }