Make negative immediates in patterns work correctly, silence some warnings
[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     return false;
490   }
491   
492   // special handling for set, which isn't really an SDNode.
493   if (getOperator()->getName() == "set") {
494     assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
495     bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
496     MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
497     
498     // Types of operands must match.
499     MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtType(), TP);
500     MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtType(), TP);
501     MadeChange |= UpdateNodeType(MVT::isVoid, TP);
502     return MadeChange;
503   } else if (getOperator()->isSubClassOf("SDNode")) {
504     const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
505     
506     bool MadeChange = NI.ApplyTypeConstraints(this, TP);
507     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
508       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
509     return MadeChange;  
510   } else if (getOperator()->isSubClassOf("Instruction")) {
511     const DAGInstruction &Inst =
512       TP.getDAGISelEmitter().getInstruction(getOperator());
513     
514     assert(Inst.getNumResults() == 1 && "Only supports one result instrs!");
515     // Apply the result type to the node
516     bool MadeChange = UpdateNodeType(Inst.getResultType(0), TP);
517
518     if (getNumChildren() != Inst.getNumOperands())
519       TP.error("Instruction '" + getOperator()->getName() + " expects " +
520                utostr(Inst.getNumOperands()) + " operands, not " +
521                utostr(getNumChildren()) + " operands!");
522     for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
523       MadeChange |= getChild(i)->UpdateNodeType(Inst.getOperandType(i), TP);
524       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
525     }
526     return MadeChange;
527   } else {
528     assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
529     
530     // Node transforms always take one operand, and take and return the same
531     // type.
532     if (getNumChildren() != 1)
533       TP.error("Node transform '" + getOperator()->getName() +
534                "' requires one operand!");
535     bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
536     MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
537     return MadeChange;
538   }
539 }
540
541 /// canPatternMatch - If it is impossible for this pattern to match on this
542 /// target, fill in Reason and return false.  Otherwise, return true.  This is
543 /// used as a santity check for .td files (to prevent people from writing stuff
544 /// that can never possibly work), and to prevent the pattern permuter from
545 /// generating stuff that is useless.
546 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
547   if (isLeaf()) return true;
548
549   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
550     if (!getChild(i)->canPatternMatch(Reason, ISE))
551       return false;
552   
553   // If this node is a commutative operator, check that the LHS isn't an
554   // immediate.
555   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
556   if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
557     // Scan all of the operands of the node and make sure that only the last one
558     // is a constant node.
559     for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
560       if (!getChild(i)->isLeaf() && 
561           getChild(i)->getOperator()->getName() == "imm") {
562         Reason = "Immediate value must be on the RHS of commutative operators!";
563         return false;
564       }
565   }
566   
567   return true;
568 }
569
570 //===----------------------------------------------------------------------===//
571 // TreePattern implementation
572 //
573
574 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
575                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
576    isInputPattern = isInput;
577    for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
578      Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
579 }
580
581 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
582                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
583   isInputPattern = isInput;
584   Trees.push_back(ParseTreePattern(Pat));
585 }
586
587 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
588                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
589   isInputPattern = isInput;
590   Trees.push_back(Pat);
591 }
592
593
594
595 void TreePattern::error(const std::string &Msg) const {
596   dump();
597   throw "In " + TheRecord->getName() + ": " + Msg;
598 }
599
600 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
601   Record *Operator = Dag->getNodeType();
602   
603   if (Operator->isSubClassOf("ValueType")) {
604     // If the operator is a ValueType, then this must be "type cast" of a leaf
605     // node.
606     if (Dag->getNumArgs() != 1)
607       error("Type cast only takes one operand!");
608     
609     Init *Arg = Dag->getArg(0);
610     TreePatternNode *New;
611     if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
612       Record *R = DI->getDef();
613       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
614         Dag->setArg(0, new DagInit(R,
615                                 std::vector<std::pair<Init*, std::string> >()));
616         TreePatternNode *TPN = ParseTreePattern(Dag);
617         TPN->setName(Dag->getArgName(0));
618         return TPN;
619       }   
620       
621       New = new TreePatternNode(DI);
622     } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
623       New = ParseTreePattern(DI);
624     } else {
625       Arg->dump();
626       error("Unknown leaf value for tree pattern!");
627       return 0;
628     }
629     
630     // Apply the type cast.
631     New->UpdateNodeType(getValueType(Operator), *this);
632     return New;
633   }
634   
635   // Verify that this is something that makes sense for an operator.
636   if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
637       !Operator->isSubClassOf("Instruction") && 
638       !Operator->isSubClassOf("SDNodeXForm") &&
639       Operator->getName() != "set")
640     error("Unrecognized node '" + Operator->getName() + "'!");
641   
642   //  Check to see if this is something that is illegal in an input pattern.
643   if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
644       Operator->isSubClassOf("SDNodeXForm")))
645     error("Cannot use '" + Operator->getName() + "' in an input pattern!");
646   
647   std::vector<TreePatternNode*> Children;
648   
649   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
650     Init *Arg = Dag->getArg(i);
651     if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
652       Children.push_back(ParseTreePattern(DI));
653       Children.back()->setName(Dag->getArgName(i));
654     } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
655       Record *R = DefI->getDef();
656       // Direct reference to a leaf DagNode or PatFrag?  Turn it into a
657       // TreePatternNode if its own.
658       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
659         Dag->setArg(i, new DagInit(R,
660                               std::vector<std::pair<Init*, std::string> >()));
661         --i;  // Revisit this node...
662       } else {
663         TreePatternNode *Node = new TreePatternNode(DefI);
664         Node->setName(Dag->getArgName(i));
665         Children.push_back(Node);
666         
667         // Input argument?
668         if (R->getName() == "node") {
669           if (Dag->getArgName(i).empty())
670             error("'node' argument requires a name to match with operand list");
671           Args.push_back(Dag->getArgName(i));
672         }
673       }
674     } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
675       TreePatternNode *Node = new TreePatternNode(II);
676       if (!Dag->getArgName(i).empty())
677         error("Constant int argument should not have a name!");
678       Children.push_back(Node);
679     } else {
680       std::cerr << '"';
681       Arg->dump();
682       std::cerr << "\": ";
683       error("Unknown leaf value for tree pattern!");
684     }
685   }
686   
687   return new TreePatternNode(Operator, Children);
688 }
689
690 /// InferAllTypes - Infer/propagate as many types throughout the expression
691 /// patterns as possible.  Return true if all types are infered, false
692 /// otherwise.  Throw an exception if a type contradiction is found.
693 bool TreePattern::InferAllTypes() {
694   bool MadeChange = true;
695   while (MadeChange) {
696     MadeChange = false;
697     for (unsigned i = 0, e = Trees.size(); i != e; ++i)
698       MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
699   }
700   
701   bool HasUnresolvedTypes = false;
702   for (unsigned i = 0, e = Trees.size(); i != e; ++i)
703     HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
704   return !HasUnresolvedTypes;
705 }
706
707 void TreePattern::print(std::ostream &OS) const {
708   OS << getRecord()->getName();
709   if (!Args.empty()) {
710     OS << "(" << Args[0];
711     for (unsigned i = 1, e = Args.size(); i != e; ++i)
712       OS << ", " << Args[i];
713     OS << ")";
714   }
715   OS << ": ";
716   
717   if (Trees.size() > 1)
718     OS << "[\n";
719   for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
720     OS << "\t";
721     Trees[i]->print(OS);
722     OS << "\n";
723   }
724
725   if (Trees.size() > 1)
726     OS << "]\n";
727 }
728
729 void TreePattern::dump() const { print(std::cerr); }
730
731
732
733 //===----------------------------------------------------------------------===//
734 // DAGISelEmitter implementation
735 //
736
737 // Parse all of the SDNode definitions for the target, populating SDNodes.
738 void DAGISelEmitter::ParseNodeInfo() {
739   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
740   while (!Nodes.empty()) {
741     SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
742     Nodes.pop_back();
743   }
744 }
745
746 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
747 /// map, and emit them to the file as functions.
748 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
749   OS << "\n// Node transformations.\n";
750   std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
751   while (!Xforms.empty()) {
752     Record *XFormNode = Xforms.back();
753     Record *SDNode = XFormNode->getValueAsDef("Opcode");
754     std::string Code = XFormNode->getValueAsCode("XFormFunction");
755     SDNodeXForms.insert(std::make_pair(XFormNode,
756                                        std::make_pair(SDNode, Code)));
757
758     if (!Code.empty()) {
759       std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
760       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
761
762       OS << "inline SDOperand Transform_" << XFormNode->getName()
763          << "(SDNode *" << C2 << ") {\n";
764       if (ClassName != "SDNode")
765         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
766       OS << Code << "\n}\n";
767     }
768
769     Xforms.pop_back();
770   }
771 }
772
773
774
775 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
776 /// file, building up the PatternFragments map.  After we've collected them all,
777 /// inline fragments together as necessary, so that there are no references left
778 /// inside a pattern fragment to a pattern fragment.
779 ///
780 /// This also emits all of the predicate functions to the output file.
781 ///
782 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
783   std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
784   
785   // First step, parse all of the fragments and emit predicate functions.
786   OS << "\n// Predicate functions.\n";
787   for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
788     DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
789     TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
790     PatternFragments[Fragments[i]] = P;
791     
792     // Validate the argument list, converting it to map, to discard duplicates.
793     std::vector<std::string> &Args = P->getArgList();
794     std::set<std::string> OperandsMap(Args.begin(), Args.end());
795     
796     if (OperandsMap.count(""))
797       P->error("Cannot have unnamed 'node' values in pattern fragment!");
798     
799     // Parse the operands list.
800     DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
801     if (OpsList->getNodeType()->getName() != "ops")
802       P->error("Operands list should start with '(ops ... '!");
803     
804     // Copy over the arguments.       
805     Args.clear();
806     for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
807       if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
808           static_cast<DefInit*>(OpsList->getArg(j))->
809           getDef()->getName() != "node")
810         P->error("Operands list should all be 'node' values.");
811       if (OpsList->getArgName(j).empty())
812         P->error("Operands list should have names for each operand!");
813       if (!OperandsMap.count(OpsList->getArgName(j)))
814         P->error("'" + OpsList->getArgName(j) +
815                  "' does not occur in pattern or was multiply specified!");
816       OperandsMap.erase(OpsList->getArgName(j));
817       Args.push_back(OpsList->getArgName(j));
818     }
819     
820     if (!OperandsMap.empty())
821       P->error("Operands list does not contain an entry for operand '" +
822                *OperandsMap.begin() + "'!");
823
824     // If there is a code init for this fragment, emit the predicate code and
825     // keep track of the fact that this fragment uses it.
826     std::string Code = Fragments[i]->getValueAsCode("Predicate");
827     if (!Code.empty()) {
828       assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
829       std::string ClassName =
830         getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
831       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
832       
833       OS << "inline bool Predicate_" << Fragments[i]->getName()
834          << "(SDNode *" << C2 << ") {\n";
835       if (ClassName != "SDNode")
836         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
837       OS << Code << "\n}\n";
838       P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
839     }
840     
841     // If there is a node transformation corresponding to this, keep track of
842     // it.
843     Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
844     if (!getSDNodeTransform(Transform).second.empty())    // not noop xform?
845       P->getOnlyTree()->setTransformFn(Transform);
846   }
847   
848   OS << "\n\n";
849
850   // Now that we've parsed all of the tree fragments, do a closure on them so
851   // that there are not references to PatFrags left inside of them.
852   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
853        E = PatternFragments.end(); I != E; ++I) {
854     TreePattern *ThePat = I->second;
855     ThePat->InlinePatternFragments();
856         
857     // Infer as many types as possible.  Don't worry about it if we don't infer
858     // all of them, some may depend on the inputs of the pattern.
859     try {
860       ThePat->InferAllTypes();
861     } catch (...) {
862       // If this pattern fragment is not supported by this target (no types can
863       // satisfy its constraints), just ignore it.  If the bogus pattern is
864       // actually used by instructions, the type consistency error will be
865       // reported there.
866     }
867     
868     // If debugging, print out the pattern fragment result.
869     DEBUG(ThePat->dump());
870   }
871 }
872
873 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
874 /// instruction input.  Return true if this is a real use.
875 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
876                       std::map<std::string, TreePatternNode*> &InstInputs) {
877   // No name -> not interesting.
878   if (Pat->getName().empty()) {
879     if (Pat->isLeaf()) {
880       DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
881       if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
882         I->error("Input " + DI->getDef()->getName() + " must be named!");
883
884     }
885     return false;
886   }
887
888   Record *Rec;
889   if (Pat->isLeaf()) {
890     DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
891     if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
892     Rec = DI->getDef();
893   } else {
894     assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
895     Rec = Pat->getOperator();
896   }
897
898   TreePatternNode *&Slot = InstInputs[Pat->getName()];
899   if (!Slot) {
900     Slot = Pat;
901   } else {
902     Record *SlotRec;
903     if (Slot->isLeaf()) {
904       SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
905     } else {
906       assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
907       SlotRec = Slot->getOperator();
908     }
909     
910     // Ensure that the inputs agree if we've already seen this input.
911     if (Rec != SlotRec)
912       I->error("All $" + Pat->getName() + " inputs must agree with each other");
913     if (Slot->getExtType() != Pat->getExtType())
914       I->error("All $" + Pat->getName() + " inputs must agree with each other");
915   }
916   return true;
917 }
918
919 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
920 /// part of "I", the instruction), computing the set of inputs and outputs of
921 /// the pattern.  Report errors if we see anything naughty.
922 void DAGISelEmitter::
923 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
924                             std::map<std::string, TreePatternNode*> &InstInputs,
925                             std::map<std::string, Record*> &InstResults) {
926   if (Pat->isLeaf()) {
927     bool isUse = HandleUse(I, Pat, InstInputs);
928     if (!isUse && Pat->getTransformFn())
929       I->error("Cannot specify a transform function for a non-input value!");
930     return;
931   } else if (Pat->getOperator()->getName() != "set") {
932     // If this is not a set, verify that the children nodes are not void typed,
933     // and recurse.
934     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
935       if (Pat->getChild(i)->getExtType() == MVT::isVoid)
936         I->error("Cannot have void nodes inside of patterns!");
937       FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
938     }
939     
940     // If this is a non-leaf node with no children, treat it basically as if
941     // it were a leaf.  This handles nodes like (imm).
942     bool isUse = false;
943     if (Pat->getNumChildren() == 0)
944       isUse = HandleUse(I, Pat, InstInputs);
945     
946     if (!isUse && Pat->getTransformFn())
947       I->error("Cannot specify a transform function for a non-input value!");
948     return;
949   } 
950   
951   // Otherwise, this is a set, validate and collect instruction results.
952   if (Pat->getNumChildren() == 0)
953     I->error("set requires operands!");
954   else if (Pat->getNumChildren() & 1)
955     I->error("set requires an even number of operands");
956   
957   if (Pat->getTransformFn())
958     I->error("Cannot specify a transform function on a set node!");
959   
960   // Check the set destinations.
961   unsigned NumValues = Pat->getNumChildren()/2;
962   for (unsigned i = 0; i != NumValues; ++i) {
963     TreePatternNode *Dest = Pat->getChild(i);
964     if (!Dest->isLeaf())
965       I->error("set destination should be a virtual register!");
966     
967     DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
968     if (!Val)
969       I->error("set destination should be a virtual register!");
970     
971     if (!Val->getDef()->isSubClassOf("RegisterClass"))
972       I->error("set destination should be a virtual register!");
973     if (Dest->getName().empty())
974       I->error("set destination must have a name!");
975     if (InstResults.count(Dest->getName()))
976       I->error("cannot set '" + Dest->getName() +"' multiple times");
977     InstResults[Dest->getName()] = Val->getDef();
978
979     // Verify and collect info from the computation.
980     FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
981                                 InstInputs, InstResults);
982   }
983 }
984
985
986 /// ParseInstructions - Parse all of the instructions, inlining and resolving
987 /// any fragments involved.  This populates the Instructions list with fully
988 /// resolved instructions.
989 void DAGISelEmitter::ParseInstructions() {
990   std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
991   
992   for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
993     ListInit *LI = 0;
994     
995     if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
996       LI = Instrs[i]->getValueAsListInit("Pattern");
997     
998     // If there is no pattern, only collect minimal information about the
999     // instruction for its operand list.  We have to assume that there is one
1000     // result, as we have no detailed info.
1001     if (!LI || LI->getSize() == 0) {
1002       std::vector<MVT::ValueType> ResultTypes;
1003       std::vector<MVT::ValueType> OperandTypes;
1004       
1005       CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1006       
1007       // Doesn't even define a result?
1008       if (InstInfo.OperandList.size() == 0)
1009         continue;
1010       
1011       // Assume the first operand is the result.
1012       ResultTypes.push_back(InstInfo.OperandList[0].Ty);
1013       
1014       // The rest are inputs.
1015       for (unsigned j = 1, e = InstInfo.OperandList.size(); j != e; ++j)
1016         OperandTypes.push_back(InstInfo.OperandList[j].Ty);
1017       
1018       // Create and insert the instruction.
1019       Instructions.insert(std::make_pair(Instrs[i], 
1020                             DAGInstruction(0, ResultTypes, OperandTypes)));
1021       continue;  // no pattern.
1022     }
1023     
1024     // Parse the instruction.
1025     TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1026     // Inline pattern fragments into it.
1027     I->InlinePatternFragments();
1028     
1029     // Infer as many types as possible.  If we cannot infer all of them, we can
1030     // never do anything with this instruction pattern: report it to the user.
1031     if (!I->InferAllTypes())
1032       I->error("Could not infer all types in pattern!");
1033     
1034     // InstInputs - Keep track of all of the inputs of the instruction, along 
1035     // with the record they are declared as.
1036     std::map<std::string, TreePatternNode*> InstInputs;
1037     
1038     // InstResults - Keep track of all the virtual registers that are 'set'
1039     // in the instruction, including what reg class they are.
1040     std::map<std::string, Record*> InstResults;
1041     
1042     // Verify that the top-level forms in the instruction are of void type, and
1043     // fill in the InstResults map.
1044     for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1045       TreePatternNode *Pat = I->getTree(j);
1046       if (Pat->getExtType() != MVT::isVoid) {
1047         I->dump();
1048         I->error("Top-level forms in instruction pattern should have"
1049                  " void types");
1050       }
1051
1052       // Find inputs and outputs, and verify the structure of the uses/defs.
1053       FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
1054     }
1055
1056     // Now that we have inputs and outputs of the pattern, inspect the operands
1057     // list for the instruction.  This determines the order that operands are
1058     // added to the machine instruction the node corresponds to.
1059     unsigned NumResults = InstResults.size();
1060
1061     // Parse the operands list from the (ops) list, validating it.
1062     std::vector<std::string> &Args = I->getArgList();
1063     assert(Args.empty() && "Args list should still be empty here!");
1064     CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1065
1066     // Check that all of the results occur first in the list.
1067     std::vector<MVT::ValueType> ResultTypes;
1068     for (unsigned i = 0; i != NumResults; ++i) {
1069       if (i == CGI.OperandList.size())
1070         I->error("'" + InstResults.begin()->first +
1071                  "' set but does not appear in operand list!");
1072       const std::string &OpName = CGI.OperandList[i].Name;
1073       
1074       // Check that it exists in InstResults.
1075       Record *R = InstResults[OpName];
1076       if (R == 0)
1077         I->error("Operand $" + OpName + " should be a set destination: all "
1078                  "outputs must occur before inputs in operand list!");
1079       
1080       if (CGI.OperandList[i].Rec != R)
1081         I->error("Operand $" + OpName + " class mismatch!");
1082       
1083       // Remember the return type.
1084       ResultTypes.push_back(CGI.OperandList[i].Ty);
1085       
1086       // Okay, this one checks out.
1087       InstResults.erase(OpName);
1088     }
1089
1090     // Loop over the inputs next.  Make a copy of InstInputs so we can destroy
1091     // the copy while we're checking the inputs.
1092     std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1093
1094     std::vector<TreePatternNode*> ResultNodeOperands;
1095     std::vector<MVT::ValueType> OperandTypes;
1096     for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1097       const std::string &OpName = CGI.OperandList[i].Name;
1098       if (OpName.empty())
1099         I->error("Operand #" + utostr(i) + " in operands list has no name!");
1100
1101       if (!InstInputsCheck.count(OpName))
1102         I->error("Operand $" + OpName +
1103                  " does not appear in the instruction pattern");
1104       TreePatternNode *InVal = InstInputsCheck[OpName];
1105       InstInputsCheck.erase(OpName);   // It occurred, remove from map.
1106       if (CGI.OperandList[i].Ty != InVal->getExtType())
1107         I->error("Operand $" + OpName +
1108                  "'s type disagrees between the operand and pattern");
1109       OperandTypes.push_back(InVal->getType());
1110       
1111       // Construct the result for the dest-pattern operand list.
1112       TreePatternNode *OpNode = InVal->clone();
1113       
1114       // No predicate is useful on the result.
1115       OpNode->setPredicateFn("");
1116       
1117       // Promote the xform function to be an explicit node if set.
1118       if (Record *Xform = OpNode->getTransformFn()) {
1119         OpNode->setTransformFn(0);
1120         std::vector<TreePatternNode*> Children;
1121         Children.push_back(OpNode);
1122         OpNode = new TreePatternNode(Xform, Children);
1123       }
1124       
1125       ResultNodeOperands.push_back(OpNode);
1126     }
1127     
1128     if (!InstInputsCheck.empty())
1129       I->error("Input operand $" + InstInputsCheck.begin()->first +
1130                " occurs in pattern but not in operands list!");
1131
1132     TreePatternNode *ResultPattern =
1133       new TreePatternNode(I->getRecord(), ResultNodeOperands);
1134
1135     // Create and insert the instruction.
1136     DAGInstruction TheInst(I, ResultTypes, OperandTypes);
1137     Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1138
1139     // Use a temporary tree pattern to infer all types and make sure that the
1140     // constructed result is correct.  This depends on the instruction already
1141     // being inserted into the Instructions map.
1142     TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1143     Temp.InferAllTypes();
1144
1145     DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1146     TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1147     
1148     DEBUG(I->dump());
1149   }
1150    
1151   // If we can, convert the instructions to be patterns that are matched!
1152   for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1153        E = Instructions.end(); II != E; ++II) {
1154     TreePattern *I = II->second.getPattern();
1155     if (I == 0) continue;  // No pattern.
1156     
1157     if (I->getNumTrees() != 1) {
1158       std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1159       continue;
1160     }
1161     TreePatternNode *Pattern = I->getTree(0);
1162     if (Pattern->getOperator()->getName() != "set")
1163       continue;  // Not a set (store or something?)
1164     
1165     if (Pattern->getNumChildren() != 2)
1166       continue;  // Not a set of a single value (not handled so far)
1167     
1168     TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
1169     
1170     std::string Reason;
1171     if (!SrcPattern->canPatternMatch(Reason, *this))
1172       I->error("Instruction can never match: " + Reason);
1173     
1174     TreePatternNode *DstPattern = II->second.getResultPattern();
1175     PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
1176   }
1177 }
1178
1179 void DAGISelEmitter::ParsePatterns() {
1180   std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1181
1182   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1183     DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1184     TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1185
1186     // Inline pattern fragments into it.
1187     Pattern->InlinePatternFragments();
1188     
1189     // Infer as many types as possible.  If we cannot infer all of them, we can
1190     // never do anything with this pattern: report it to the user.
1191     if (!Pattern->InferAllTypes())
1192       Pattern->error("Could not infer all types in pattern!");
1193     
1194     ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1195     if (LI->getSize() == 0) continue;  // no pattern.
1196     
1197     // Parse the instruction.
1198     TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1199     
1200     // Inline pattern fragments into it.
1201     Result->InlinePatternFragments();
1202     
1203     // Infer as many types as possible.  If we cannot infer all of them, we can
1204     // never do anything with this pattern: report it to the user.
1205     if (!Result->InferAllTypes())
1206       Result->error("Could not infer all types in pattern result!");
1207    
1208     if (Result->getNumTrees() != 1)
1209       Result->error("Cannot handle instructions producing instructions "
1210                     "with temporaries yet!");
1211
1212     std::string Reason;
1213     if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1214       Pattern->error("Pattern can never match: " + Reason);
1215     
1216     PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1217                                              Result->getOnlyTree()));
1218   }
1219 }
1220
1221 /// CombineChildVariants - Given a bunch of permutations of each child of the
1222 /// 'operator' node, put them together in all possible ways.
1223 static void CombineChildVariants(TreePatternNode *Orig, 
1224                const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1225                                  std::vector<TreePatternNode*> &OutVariants,
1226                                  DAGISelEmitter &ISE) {
1227   // Make sure that each operand has at least one variant to choose from.
1228   for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1229     if (ChildVariants[i].empty())
1230       return;
1231         
1232   // The end result is an all-pairs construction of the resultant pattern.
1233   std::vector<unsigned> Idxs;
1234   Idxs.resize(ChildVariants.size());
1235   bool NotDone = true;
1236   while (NotDone) {
1237     // Create the variant and add it to the output list.
1238     std::vector<TreePatternNode*> NewChildren;
1239     for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1240       NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1241     TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1242     
1243     // Copy over properties.
1244     R->setName(Orig->getName());
1245     R->setPredicateFn(Orig->getPredicateFn());
1246     R->setTransformFn(Orig->getTransformFn());
1247     R->setType(Orig->getExtType());
1248     
1249     // If this pattern cannot every match, do not include it as a variant.
1250     std::string ErrString;
1251     if (!R->canPatternMatch(ErrString, ISE)) {
1252       delete R;
1253     } else {
1254       bool AlreadyExists = false;
1255       
1256       // Scan to see if this pattern has already been emitted.  We can get
1257       // duplication due to things like commuting:
1258       //   (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1259       // which are the same pattern.  Ignore the dups.
1260       for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1261         if (R->isIsomorphicTo(OutVariants[i])) {
1262           AlreadyExists = true;
1263           break;
1264         }
1265       
1266       if (AlreadyExists)
1267         delete R;
1268       else
1269         OutVariants.push_back(R);
1270     }
1271     
1272     // Increment indices to the next permutation.
1273     NotDone = false;
1274     // Look for something we can increment without causing a wrap-around.
1275     for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1276       if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1277         NotDone = true;   // Found something to increment.
1278         break;
1279       }
1280       Idxs[IdxsIdx] = 0;
1281     }
1282   }
1283 }
1284
1285 /// CombineChildVariants - A helper function for binary operators.
1286 ///
1287 static void CombineChildVariants(TreePatternNode *Orig, 
1288                                  const std::vector<TreePatternNode*> &LHS,
1289                                  const std::vector<TreePatternNode*> &RHS,
1290                                  std::vector<TreePatternNode*> &OutVariants,
1291                                  DAGISelEmitter &ISE) {
1292   std::vector<std::vector<TreePatternNode*> > ChildVariants;
1293   ChildVariants.push_back(LHS);
1294   ChildVariants.push_back(RHS);
1295   CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1296 }  
1297
1298
1299 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1300                                      std::vector<TreePatternNode *> &Children) {
1301   assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1302   Record *Operator = N->getOperator();
1303   
1304   // Only permit raw nodes.
1305   if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1306       N->getTransformFn()) {
1307     Children.push_back(N);
1308     return;
1309   }
1310
1311   if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1312     Children.push_back(N->getChild(0));
1313   else
1314     GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1315
1316   if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1317     Children.push_back(N->getChild(1));
1318   else
1319     GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1320 }
1321
1322 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1323 /// the (potentially recursive) pattern by using algebraic laws.
1324 ///
1325 static void GenerateVariantsOf(TreePatternNode *N,
1326                                std::vector<TreePatternNode*> &OutVariants,
1327                                DAGISelEmitter &ISE) {
1328   // We cannot permute leaves.
1329   if (N->isLeaf()) {
1330     OutVariants.push_back(N);
1331     return;
1332   }
1333
1334   // Look up interesting info about the node.
1335   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1336
1337   // If this node is associative, reassociate.
1338   if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1339     // Reassociate by pulling together all of the linked operators 
1340     std::vector<TreePatternNode*> MaximalChildren;
1341     GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1342
1343     // Only handle child sizes of 3.  Otherwise we'll end up trying too many
1344     // permutations.
1345     if (MaximalChildren.size() == 3) {
1346       // Find the variants of all of our maximal children.
1347       std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1348       GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1349       GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1350       GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1351       
1352       // There are only two ways we can permute the tree:
1353       //   (A op B) op C    and    A op (B op C)
1354       // Within these forms, we can also permute A/B/C.
1355       
1356       // Generate legal pair permutations of A/B/C.
1357       std::vector<TreePatternNode*> ABVariants;
1358       std::vector<TreePatternNode*> BAVariants;
1359       std::vector<TreePatternNode*> ACVariants;
1360       std::vector<TreePatternNode*> CAVariants;
1361       std::vector<TreePatternNode*> BCVariants;
1362       std::vector<TreePatternNode*> CBVariants;
1363       CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1364       CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1365       CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1366       CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1367       CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1368       CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1369
1370       // Combine those into the result: (x op x) op x
1371       CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1372       CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1373       CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1374       CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1375       CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1376       CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1377
1378       // Combine those into the result: x op (x op x)
1379       CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1380       CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1381       CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1382       CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1383       CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1384       CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1385       return;
1386     }
1387   }
1388   
1389   // Compute permutations of all children.
1390   std::vector<std::vector<TreePatternNode*> > ChildVariants;
1391   ChildVariants.resize(N->getNumChildren());
1392   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1393     GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1394
1395   // Build all permutations based on how the children were formed.
1396   CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1397
1398   // If this node is commutative, consider the commuted order.
1399   if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1400     assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1401     // Consider the commuted order.
1402     CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1403                          OutVariants, ISE);
1404   }
1405 }
1406
1407
1408 // GenerateVariants - Generate variants.  For example, commutative patterns can
1409 // match multiple ways.  Add them to PatternsToMatch as well.
1410 void DAGISelEmitter::GenerateVariants() {
1411   
1412   DEBUG(std::cerr << "Generating instruction variants.\n");
1413   
1414   // Loop over all of the patterns we've collected, checking to see if we can
1415   // generate variants of the instruction, through the exploitation of
1416   // identities.  This permits the target to provide agressive matching without
1417   // the .td file having to contain tons of variants of instructions.
1418   //
1419   // Note that this loop adds new patterns to the PatternsToMatch list, but we
1420   // intentionally do not reconsider these.  Any variants of added patterns have
1421   // already been added.
1422   //
1423   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1424     std::vector<TreePatternNode*> Variants;
1425     GenerateVariantsOf(PatternsToMatch[i].first, Variants, *this);
1426
1427     assert(!Variants.empty() && "Must create at least original variant!");
1428     Variants.erase(Variants.begin());  // Remove the original pattern.
1429
1430     if (Variants.empty())  // No variants for this pattern.
1431       continue;
1432
1433     DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1434           PatternsToMatch[i].first->dump();
1435           std::cerr << "\n");
1436
1437     for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1438       TreePatternNode *Variant = Variants[v];
1439
1440       DEBUG(std::cerr << "  VAR#" << v <<  ": ";
1441             Variant->dump();
1442             std::cerr << "\n");
1443       
1444       // Scan to see if an instruction or explicit pattern already matches this.
1445       bool AlreadyExists = false;
1446       for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1447         // Check to see if this variant already exists.
1448         if (Variant->isIsomorphicTo(PatternsToMatch[p].first)) {
1449           DEBUG(std::cerr << "  *** ALREADY EXISTS, ignoring variant.\n");
1450           AlreadyExists = true;
1451           break;
1452         }
1453       }
1454       // If we already have it, ignore the variant.
1455       if (AlreadyExists) continue;
1456
1457       // Otherwise, add it to the list of patterns we have.
1458       PatternsToMatch.push_back(std::make_pair(Variant, 
1459                                                PatternsToMatch[i].second));
1460     }
1461
1462     DEBUG(std::cerr << "\n");
1463   }
1464 }
1465
1466
1467 /// getPatternSize - Return the 'size' of this pattern.  We want to match large
1468 /// patterns before small ones.  This is used to determine the size of a
1469 /// pattern.
1470 static unsigned getPatternSize(TreePatternNode *P) {
1471   assert(isExtIntegerVT(P->getExtType()) || 
1472          isExtFloatingPointVT(P->getExtType()) &&
1473          "Not a valid pattern node to size!");
1474   unsigned Size = 1;  // The node itself.
1475   
1476   // Count children in the count if they are also nodes.
1477   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1478     TreePatternNode *Child = P->getChild(i);
1479     if (!Child->isLeaf() && Child->getExtType() != MVT::Other)
1480       Size += getPatternSize(Child);
1481     else if (Child->isLeaf() && dynamic_cast<IntInit*>(Child->getLeafValue())) {
1482       ++Size;  // Matches a ConstantSDNode.
1483     }
1484   }
1485   
1486   return Size;
1487 }
1488
1489 /// getResultPatternCost - Compute the number of instructions for this pattern.
1490 /// This is a temporary hack.  We should really include the instruction
1491 /// latencies in this calculation.
1492 static unsigned getResultPatternCost(TreePatternNode *P) {
1493   if (P->isLeaf()) return 0;
1494   
1495   unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1496   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1497     Cost += getResultPatternCost(P->getChild(i));
1498   return Cost;
1499 }
1500
1501 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1502 // In particular, we want to match maximal patterns first and lowest cost within
1503 // a particular complexity first.
1504 struct PatternSortingPredicate {
1505   bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1506                   DAGISelEmitter::PatternToMatch *RHS) {
1507     unsigned LHSSize = getPatternSize(LHS->first);
1508     unsigned RHSSize = getPatternSize(RHS->first);
1509     if (LHSSize > RHSSize) return true;   // LHS -> bigger -> less cost
1510     if (LHSSize < RHSSize) return false;
1511     
1512     // If the patterns have equal complexity, compare generated instruction cost
1513     return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1514   }
1515 };
1516
1517 /// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
1518 /// if the match fails.  At this point, we already know that the opcode for N
1519 /// matches, and the SDNode for the result has the RootName specified name.
1520 void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
1521                                          const std::string &RootName,
1522                                      std::map<std::string,std::string> &VarMap,
1523                                          unsigned PatternNo, std::ostream &OS) {
1524   assert(!N->isLeaf() && "Cannot match against a leaf!");
1525   
1526   // If this node has a name associated with it, capture it in VarMap.  If
1527   // we already saw this in the pattern, emit code to verify dagness.
1528   if (!N->getName().empty()) {
1529     std::string &VarMapEntry = VarMap[N->getName()];
1530     if (VarMapEntry.empty()) {
1531       VarMapEntry = RootName;
1532     } else {
1533       // If we get here, this is a second reference to a specific name.  Since
1534       // we already have checked that the first reference is valid, we don't
1535       // have to recursively match it, just check that it's the same as the
1536       // previously named thing.
1537       OS << "      if (" << VarMapEntry << " != " << RootName
1538          << ") goto P" << PatternNo << "Fail;\n";
1539       return;
1540     }
1541   }
1542   
1543   // Emit code to load the child nodes and match their contents recursively.
1544   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1545     OS << "      SDOperand " << RootName << i <<" = " << RootName
1546        << ".getOperand(" << i << ");\n";
1547     TreePatternNode *Child = N->getChild(i);
1548     
1549     if (!Child->isLeaf()) {
1550       // If it's not a leaf, recursively match.
1551       const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
1552       OS << "      if (" << RootName << i << ".getOpcode() != "
1553          << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
1554       EmitMatchForPattern(Child, RootName + utostr(i), VarMap, PatternNo, OS);
1555     } else {
1556       // If this child has a name associated with it, capture it in VarMap.  If
1557       // we already saw this in the pattern, emit code to verify dagness.
1558       if (!Child->getName().empty()) {
1559         std::string &VarMapEntry = VarMap[Child->getName()];
1560         if (VarMapEntry.empty()) {
1561           VarMapEntry = RootName + utostr(i);
1562         } else {
1563           // If we get here, this is a second reference to a specific name.  Since
1564           // we already have checked that the first reference is valid, we don't
1565           // have to recursively match it, just check that it's the same as the
1566           // previously named thing.
1567           OS << "      if (" << VarMapEntry << " != " << RootName << i
1568           << ") goto P" << PatternNo << "Fail;\n";
1569           continue;
1570         }
1571       }
1572       
1573       // Handle leaves of various types.
1574       if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1575         Record *LeafRec = DI->getDef();
1576         if (LeafRec->isSubClassOf("RegisterClass")) {
1577           // Handle register references.  Nothing to do here.
1578         } else if (LeafRec->isSubClassOf("ValueType")) {
1579           // Make sure this is the specified value type.
1580           OS << "      if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1581           << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1582           << "Fail;\n";
1583         } else if (LeafRec->isSubClassOf("CondCode")) {
1584           // Make sure this is the specified cond code.
1585           OS << "      if (cast<CondCodeSDNode>(" << RootName << i
1586              << ")->get() != " << "ISD::" << LeafRec->getName()
1587              << ") goto P" << PatternNo << "Fail;\n";
1588         } else {
1589           Child->dump();
1590           assert(0 && "Unknown leaf type!");
1591         }
1592       } else if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
1593         OS << "      if (!isa<ConstantSDNode>(" << RootName << i << ") ||\n"
1594            << "          cast<ConstantSDNode>(" << RootName << i
1595            << ")->getSignExtended() != " << II->getValue() << ")\n"
1596            << "        goto P" << PatternNo << "Fail;\n";
1597       } else {
1598         Child->dump();
1599         assert(0 && "Unknown leaf type!");
1600       }
1601     }
1602   }
1603   
1604   // If there is a node predicate for this, emit the call.
1605   if (!N->getPredicateFn().empty())
1606     OS << "      if (!" << N->getPredicateFn() << "(" << RootName
1607        << ".Val)) goto P" << PatternNo << "Fail;\n";
1608 }
1609
1610 /// CodeGenPatternResult - Emit the action for a pattern.  Now that it has
1611 /// matched, we actually have to build a DAG!
1612 unsigned DAGISelEmitter::
1613 CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1614                      std::map<std::string,std::string> &VariableMap, 
1615                      std::ostream &OS, bool isRoot) {
1616   // This is something selected from the pattern we matched.
1617   if (!N->getName().empty()) {
1618     assert(!isRoot && "Root of pattern cannot be a leaf!");
1619     std::string &Val = VariableMap[N->getName()];
1620     assert(!Val.empty() &&
1621            "Variable referenced but not defined and not caught earlier!");
1622     if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1623       // Already selected this operand, just return the tmpval.
1624       return atoi(Val.c_str()+3);
1625     }
1626     
1627     unsigned ResNo = Ctr++;
1628     if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1629       switch (N->getType()) {
1630       default: assert(0 && "Unknown type for constant node!");
1631       case MVT::i1:  OS << "      bool Tmp"; break;
1632       case MVT::i8:  OS << "      unsigned char Tmp"; break;
1633       case MVT::i16: OS << "      unsigned short Tmp"; break;
1634       case MVT::i32: OS << "      unsigned Tmp"; break;
1635       case MVT::i64: OS << "      uint64_t Tmp"; break;
1636       }
1637       OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1638       OS << "      SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1639          << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1640     } else {
1641       OS << "      SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1642     }
1643     // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1644     // value if used multiple times by this pattern result.
1645     Val = "Tmp"+utostr(ResNo);
1646     return ResNo;
1647   }
1648   
1649   if (N->isLeaf()) {
1650     // If this is an explicit register reference, handle it.
1651     if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1652       unsigned ResNo = Ctr++;
1653       if (DI->getDef()->isSubClassOf("Register")) {
1654         OS << "      SDOperand Tmp" << ResNo << " = CurDAG->getRegister("
1655            << getQualifiedName(DI->getDef()) << ", MVT::"
1656            << getEnumName(N->getType())
1657            << ");\n";
1658         return ResNo;
1659       }
1660     } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1661       unsigned ResNo = Ctr++;
1662       OS << "      SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant("
1663          << II->getValue() << ", MVT::"
1664         << getEnumName(N->getType())
1665         << ");\n";
1666       return ResNo;
1667     }
1668     
1669     N->dump();
1670     assert(0 && "Unknown leaf type!");
1671     return ~0U;
1672   }
1673
1674   Record *Op = N->getOperator();
1675   if (Op->isSubClassOf("Instruction")) {
1676     // Emit all of the operands.
1677     std::vector<unsigned> Ops;
1678     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1679       Ops.push_back(CodeGenPatternResult(N->getChild(i), Ctr, VariableMap, OS));
1680
1681     CodeGenInstruction &II = Target.getInstruction(Op->getName());
1682     unsigned ResNo = Ctr++;
1683     
1684     if (!isRoot) {
1685       OS << "      SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1686          << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1687          << getEnumName(N->getType());
1688       for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1689         OS << ", Tmp" << Ops[i];
1690       OS << ");\n";
1691     } else {
1692       // If this instruction is the root, and if there is only one use of it,
1693       // use SelectNodeTo instead of getTargetNode to avoid an allocation.
1694       OS << "      if (N.Val->hasOneUse()) {\n";
1695       OS << "        CurDAG->SelectNodeTo(N.Val, "
1696          << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1697          << getEnumName(N->getType());
1698       for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1699         OS << ", Tmp" << Ops[i];
1700       OS << ");\n";
1701       OS << "        return N;\n";
1702       OS << "      } else {\n";
1703       OS << "        return CodeGenMap[N] = CurDAG->getTargetNode("
1704       << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1705       << getEnumName(N->getType());
1706       for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1707         OS << ", Tmp" << Ops[i];
1708       OS << ");\n";
1709       OS << "      }\n";
1710     }
1711     return ResNo;
1712   } else if (Op->isSubClassOf("SDNodeXForm")) {
1713     assert(N->getNumChildren() == 1 && "node xform should have one child!");
1714     unsigned OpVal = CodeGenPatternResult(N->getChild(0), Ctr, VariableMap, OS);
1715     
1716     unsigned ResNo = Ctr++;
1717     OS << "      SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1718        << "(Tmp" << OpVal << ".Val);\n";
1719     if (isRoot) {
1720       OS << "      CodeGenMap[N] = Tmp" << ResNo << ";\n";
1721       OS << "      return Tmp" << ResNo << ";\n";
1722     }
1723     return ResNo;
1724   } else {
1725     N->dump();
1726     assert(0 && "Unknown node in result pattern!");
1727     return ~0U;
1728   }
1729 }
1730
1731 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1732 /// type information from it.
1733 static void RemoveAllTypes(TreePatternNode *N) {
1734   N->setType(MVT::isUnknown);
1735   if (!N->isLeaf())
1736     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1737       RemoveAllTypes(N->getChild(i));
1738 }
1739
1740 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
1741 /// add it to the tree.  'Pat' and 'Other' are isomorphic trees except that 
1742 /// 'Pat' may be missing types.  If we find an unresolved type to add a check
1743 /// for, this returns true otherwise false if Pat has all types.
1744 static bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1745                                const std::string &Prefix, unsigned PatternNo,
1746                                std::ostream &OS) {
1747   // Did we find one?
1748   if (!Pat->hasTypeSet()) {
1749     // Move a type over from 'other' to 'pat'.
1750     Pat->setType(Other->getType());
1751     OS << "      if (" << Prefix << ".getValueType() != MVT::"
1752        << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
1753     return true;
1754   } else if (Pat->isLeaf()) {
1755     return false;
1756   }
1757   
1758   for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i)
1759     if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1760                            Prefix + utostr(i), PatternNo, OS))
1761       return true;
1762   return false;
1763 }
1764
1765 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1766 /// stream to match the pattern, and generate the code for the match if it
1767 /// succeeds.
1768 void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1769                                         std::ostream &OS) {
1770   static unsigned PatternCount = 0;
1771   unsigned PatternNo = PatternCount++;
1772   OS << "    { // Pattern #" << PatternNo << ": ";
1773   Pattern.first->print(OS);
1774   OS << "\n      // Emits: ";
1775   Pattern.second->print(OS);
1776   OS << "\n";
1777   OS << "      // Pattern complexity = " << getPatternSize(Pattern.first)
1778      << "  cost = " << getResultPatternCost(Pattern.second) << "\n";
1779
1780   // Emit the matcher, capturing named arguments in VariableMap.
1781   std::map<std::string,std::string> VariableMap;
1782   EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
1783   
1784   // TP - Get *SOME* tree pattern, we don't care which.
1785   TreePattern &TP = *PatternFragments.begin()->second;
1786   
1787   // At this point, we know that we structurally match the pattern, but the
1788   // types of the nodes may not match.  Figure out the fewest number of type 
1789   // comparisons we need to emit.  For example, if there is only one integer
1790   // type supported by a target, there should be no type comparisons at all for
1791   // integer patterns!
1792   //
1793   // To figure out the fewest number of type checks needed, clone the pattern,
1794   // remove the types, then perform type inference on the pattern as a whole.
1795   // If there are unresolved types, emit an explicit check for those types,
1796   // apply the type to the tree, then rerun type inference.  Iterate until all
1797   // types are resolved.
1798   //
1799   TreePatternNode *Pat = Pattern.first->clone();
1800   RemoveAllTypes(Pat);
1801   
1802   do {
1803     // Resolve/propagate as many types as possible.
1804     try {
1805       bool MadeChange = true;
1806       while (MadeChange)
1807         MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
1808     } catch (...) {
1809       assert(0 && "Error: could not find consistent types for something we"
1810              " already decided was ok!");
1811       abort();
1812     }
1813
1814     // Insert a check for an unresolved type and add it to the tree.  If we find
1815     // an unresolved type to add a check for, this returns true and we iterate,
1816     // otherwise we are done.
1817   } while (InsertOneTypeCheck(Pat, Pattern.first, "N", PatternNo, OS));
1818   
1819   unsigned TmpNo = 0;
1820   CodeGenPatternResult(Pattern.second, TmpNo,
1821                        VariableMap, OS, true /*the root*/);
1822   delete Pat;
1823   
1824   OS << "    }\n  P" << PatternNo << "Fail:\n";
1825 }
1826
1827
1828 namespace {
1829   /// CompareByRecordName - An ordering predicate that implements less-than by
1830   /// comparing the names records.
1831   struct CompareByRecordName {
1832     bool operator()(const Record *LHS, const Record *RHS) const {
1833       // Sort by name first.
1834       if (LHS->getName() < RHS->getName()) return true;
1835       // If both names are equal, sort by pointer.
1836       return LHS->getName() == RHS->getName() && LHS < RHS;
1837     }
1838   };
1839 }
1840
1841 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1842   std::string InstNS = Target.inst_begin()->second.Namespace;
1843   if (!InstNS.empty()) InstNS += "::";
1844   
1845   // Emit boilerplate.
1846   OS << "// The main instruction selector code.\n"
1847      << "SDOperand SelectCode(SDOperand N) {\n"
1848      << "  if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1849      << "      N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1850      << "INSTRUCTION_LIST_END))\n"
1851      << "    return N;   // Already selected.\n\n"
1852      << "  if (!N.Val->hasOneUse()) {\n"
1853   << "    std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
1854      << "    if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
1855      << "  }\n"
1856      << "  switch (N.getOpcode()) {\n"
1857      << "  default: break;\n"
1858      << "  case ISD::EntryToken:       // These leaves remain the same.\n"
1859      << "    return N;\n"
1860      << "  case ISD::AssertSext:\n"
1861      << "  case ISD::AssertZext: {\n"
1862      << "    SDOperand Tmp0 = Select(N.getOperand(0));\n"
1863      << "    if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
1864      << "    return Tmp0;\n"
1865      << "  }\n"
1866      << "  case ISD::TokenFactor:\n"
1867      << "    if (N.getNumOperands() == 2) {\n"
1868      << "      SDOperand Op0 = Select(N.getOperand(0));\n"
1869      << "      SDOperand Op1 = Select(N.getOperand(1));\n"
1870      << "      return CodeGenMap[N] =\n"
1871      << "          CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
1872      << "    } else {\n"
1873      << "      std::vector<SDOperand> Ops;\n"
1874      << "      for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1875      << "        Ops.push_back(Select(N.getOperand(i)));\n"
1876      << "       return CodeGenMap[N] = \n"
1877      << "               CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
1878      << "    }\n"
1879      << "  case ISD::CopyFromReg: {\n"
1880      << "    SDOperand Chain = Select(N.getOperand(0));\n"
1881      << "    if (Chain == N.getOperand(0)) return N; // No change\n"
1882      << "    SDOperand New = CurDAG->getCopyFromReg(Chain,\n"
1883      << "                    cast<RegisterSDNode>(N.getOperand(1))->getReg(),\n"
1884      << "                                         N.Val->getValueType(0));\n"
1885      << "    return New.getValue(N.ResNo);\n"
1886      << "  }\n"
1887      << "  case ISD::CopyToReg: {\n"
1888      << "    SDOperand Chain = Select(N.getOperand(0));\n"
1889      << "    SDOperand Reg = N.getOperand(1);\n"
1890      << "    SDOperand Val = Select(N.getOperand(2));\n"
1891      << "    return CodeGenMap[N] = \n"
1892      << "                   CurDAG->getNode(ISD::CopyToReg, MVT::Other,\n"
1893      << "                                   Chain, Reg, Val);\n"
1894      << "  }\n";
1895     
1896   // Group the patterns by their top-level opcodes.
1897   std::map<Record*, std::vector<PatternToMatch*>,
1898            CompareByRecordName> PatternsByOpcode;
1899   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
1900     PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
1901       .push_back(&PatternsToMatch[i]);
1902   
1903   // Loop over all of the case statements.
1904   for (std::map<Record*, std::vector<PatternToMatch*>,
1905                 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
1906        E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
1907     const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
1908     std::vector<PatternToMatch*> &Patterns = PBOI->second;
1909     
1910     OS << "  case " << OpcodeInfo.getEnumName() << ":\n";
1911
1912     // We want to emit all of the matching code now.  However, we want to emit
1913     // the matches in order of minimal cost.  Sort the patterns so the least
1914     // cost one is at the start.
1915     std::stable_sort(Patterns.begin(), Patterns.end(),
1916                      PatternSortingPredicate());
1917     
1918     for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1919       EmitCodeForPattern(*Patterns[i], OS);
1920     OS << "    break;\n\n";
1921   }
1922   
1923
1924   OS << "  } // end of big switch.\n\n"
1925      << "  std::cerr << \"Cannot yet select: \";\n"
1926      << "  N.Val->dump();\n"
1927      << "  std::cerr << '\\n';\n"
1928      << "  abort();\n"
1929      << "}\n";
1930 }
1931
1932 void DAGISelEmitter::run(std::ostream &OS) {
1933   EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1934                        " target", OS);
1935   
1936   OS << "// *** NOTE: This file is #included into the middle of the target\n"
1937      << "// *** instruction selector class.  These functions are really "
1938      << "methods.\n\n";
1939   
1940   OS << "// Instance var to keep track of multiply used nodes that have \n"
1941      << "// already been selected.\n"
1942      << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
1943   
1944   ParseNodeInfo();
1945   ParseNodeTransforms(OS);
1946   ParsePatternFragments(OS);
1947   ParseInstructions();
1948   ParsePatterns();
1949   
1950   // Generate variants.  For example, commutative patterns can match
1951   // multiple ways.  Add them to PatternsToMatch as well.
1952   GenerateVariants();
1953
1954   
1955   DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
1956         for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1957           std::cerr << "PATTERN: ";  PatternsToMatch[i].first->dump();
1958           std::cerr << "\nRESULT:  ";PatternsToMatch[i].second->dump();
1959           std::cerr << "\n";
1960         });
1961   
1962   // At this point, we have full information about the 'Patterns' we need to
1963   // parse, both implicitly from instructions as well as from explicit pattern
1964   // definitions.  Emit the resultant instruction selector.
1965   EmitInstructionSelector(OS);  
1966   
1967   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1968        E = PatternFragments.end(); I != E; ++I)
1969     delete I->second;
1970   PatternFragments.clear();
1971
1972   Instructions.clear();
1973 }