Implement the last major missing piece in the DAG isel generator: when emitting
[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   ListInit *LI = R->getValueAsListInit("Properties");
232   for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
233     DefInit *DI = dynamic_cast<DefInit*>(LI->getElement(i));
234     assert(DI && "Properties list must be list of defs!");
235     if (DI->getDef()->getName() == "SDNPCommutative") {
236       Properties |= 1 << SDNPCommutative;
237     } else if (DI->getDef()->getName() == "SDNPAssociative") {
238       Properties |= 1 << SDNPAssociative;
239     } else {
240       std::cerr << "Unknown SD Node property '" << DI->getDef()->getName()
241                 << "' on node '" << R->getName() << "'!\n";
242       exit(1);
243     }
244   }
245   
246   
247   // Parse the type constraints.
248   ListInit *Constraints = TypeProfile->getValueAsListInit("Constraints");
249   for (unsigned i = 0, e = Constraints->getSize(); i != e; ++i) {
250     assert(dynamic_cast<DefInit*>(Constraints->getElement(i)) &&
251            "Constraints list should contain constraint definitions!");
252     Record *Constraint = 
253       static_cast<DefInit*>(Constraints->getElement(i))->getDef();
254     TypeConstraints.push_back(Constraint);
255   }
256 }
257
258 //===----------------------------------------------------------------------===//
259 // TreePatternNode implementation
260 //
261
262 TreePatternNode::~TreePatternNode() {
263 #if 0 // FIXME: implement refcounted tree nodes!
264   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
265     delete getChild(i);
266 #endif
267 }
268
269 /// UpdateNodeType - Set the node type of N to VT if VT contains
270 /// information.  If N already contains a conflicting type, then throw an
271 /// exception.  This returns true if any information was updated.
272 ///
273 bool TreePatternNode::UpdateNodeType(unsigned char VT, TreePattern &TP) {
274   if (VT == MVT::isUnknown || getExtType() == VT) return false;
275   if (getExtType() == MVT::isUnknown) {
276     setType(VT);
277     return true;
278   }
279   
280   // If we are told this is to be an int or FP type, and it already is, ignore
281   // the advice.
282   if ((VT == MVT::isInt && isExtIntegerVT(getExtType())) ||
283       (VT == MVT::isFP  && isExtFloatingPointVT(getExtType())))
284     return false;
285       
286   // If we know this is an int or fp type, and we are told it is a specific one,
287   // take the advice.
288   if ((getExtType() == MVT::isInt && isExtIntegerVT(VT)) ||
289       (getExtType() == MVT::isFP  && isExtFloatingPointVT(VT))) {
290     setType(VT);
291     return true;
292   }      
293
294   TP.error("Type inference contradiction found in node " + 
295            getOperator()->getName() + "!");
296   return true; // unreachable
297 }
298
299
300 void TreePatternNode::print(std::ostream &OS) const {
301   if (isLeaf()) {
302     OS << *getLeafValue();
303   } else {
304     OS << "(" << getOperator()->getName();
305   }
306   
307   switch (getExtType()) {
308   case MVT::Other: OS << ":Other"; break;
309   case MVT::isInt: OS << ":isInt"; break;
310   case MVT::isFP : OS << ":isFP"; break;
311   case MVT::isUnknown: ; /*OS << ":?";*/ break;
312   default:  OS << ":" << getType(); break;
313   }
314
315   if (!isLeaf()) {
316     if (getNumChildren() != 0) {
317       OS << " ";
318       getChild(0)->print(OS);
319       for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
320         OS << ", ";
321         getChild(i)->print(OS);
322       }
323     }
324     OS << ")";
325   }
326   
327   if (!PredicateFn.empty())
328     OS << "<<P:" << PredicateFn << ">>";
329   if (TransformFn)
330     OS << "<<X:" << TransformFn->getName() << ">>";
331   if (!getName().empty())
332     OS << ":$" << getName();
333
334 }
335 void TreePatternNode::dump() const {
336   print(std::cerr);
337 }
338
339 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
340 /// the specified node.  For this comparison, all of the state of the node
341 /// is considered, except for the assigned name.  Nodes with differing names
342 /// that are otherwise identical are considered isomorphic.
343 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
344   if (N == this) return true;
345   if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
346       getPredicateFn() != N->getPredicateFn() ||
347       getTransformFn() != N->getTransformFn())
348     return false;
349
350   if (isLeaf()) {
351     if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
352       if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
353         return DI->getDef() == NDI->getDef();
354     return getLeafValue() == N->getLeafValue();
355   }
356   
357   if (N->getOperator() != getOperator() ||
358       N->getNumChildren() != getNumChildren()) return false;
359   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
360     if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
361       return false;
362   return true;
363 }
364
365 /// clone - Make a copy of this tree and all of its children.
366 ///
367 TreePatternNode *TreePatternNode::clone() const {
368   TreePatternNode *New;
369   if (isLeaf()) {
370     New = new TreePatternNode(getLeafValue());
371   } else {
372     std::vector<TreePatternNode*> CChildren;
373     CChildren.reserve(Children.size());
374     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
375       CChildren.push_back(getChild(i)->clone());
376     New = new TreePatternNode(getOperator(), CChildren);
377   }
378   New->setName(getName());
379   New->setType(getExtType());
380   New->setPredicateFn(getPredicateFn());
381   New->setTransformFn(getTransformFn());
382   return New;
383 }
384
385 /// SubstituteFormalArguments - Replace the formal arguments in this tree
386 /// with actual values specified by ArgMap.
387 void TreePatternNode::
388 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
389   if (isLeaf()) return;
390   
391   for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
392     TreePatternNode *Child = getChild(i);
393     if (Child->isLeaf()) {
394       Init *Val = Child->getLeafValue();
395       if (dynamic_cast<DefInit*>(Val) &&
396           static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
397         // We found a use of a formal argument, replace it with its value.
398         Child = ArgMap[Child->getName()];
399         assert(Child && "Couldn't find formal argument!");
400         setChild(i, Child);
401       }
402     } else {
403       getChild(i)->SubstituteFormalArguments(ArgMap);
404     }
405   }
406 }
407
408
409 /// InlinePatternFragments - If this pattern refers to any pattern
410 /// fragments, inline them into place, giving us a pattern without any
411 /// PatFrag references.
412 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
413   if (isLeaf()) return this;  // nothing to do.
414   Record *Op = getOperator();
415   
416   if (!Op->isSubClassOf("PatFrag")) {
417     // Just recursively inline children nodes.
418     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
419       setChild(i, getChild(i)->InlinePatternFragments(TP));
420     return this;
421   }
422
423   // Otherwise, we found a reference to a fragment.  First, look up its
424   // TreePattern record.
425   TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
426   
427   // Verify that we are passing the right number of operands.
428   if (Frag->getNumArgs() != Children.size())
429     TP.error("'" + Op->getName() + "' fragment requires " +
430              utostr(Frag->getNumArgs()) + " operands!");
431
432   TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
433
434   // Resolve formal arguments to their actual value.
435   if (Frag->getNumArgs()) {
436     // Compute the map of formal to actual arguments.
437     std::map<std::string, TreePatternNode*> ArgMap;
438     for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
439       ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
440   
441     FragTree->SubstituteFormalArguments(ArgMap);
442   }
443   
444   FragTree->setName(getName());
445   
446   // Get a new copy of this fragment to stitch into here.
447   //delete this;    // FIXME: implement refcounting!
448   return FragTree;
449 }
450
451 /// getIntrinsicType - Check to see if the specified record has an intrinsic
452 /// type which should be applied to it.  This infer the type of register
453 /// references from the register file information, for example.
454 ///
455 static unsigned char getIntrinsicType(Record *R, bool NotRegisters,
456                                       TreePattern &TP) {
457   // Check to see if this is a register or a register class...
458   if (R->isSubClassOf("RegisterClass")) {
459     if (NotRegisters) return MVT::isUnknown;
460     return getValueType(R->getValueAsDef("RegType"));
461   } else if (R->isSubClassOf("PatFrag")) {
462     // Pattern fragment types will be resolved when they are inlined.
463     return MVT::isUnknown;
464   } else if (R->isSubClassOf("Register")) {
465     assert(0 && "Explicit registers not handled here yet!\n");
466     return MVT::isUnknown;
467   } else if (R->isSubClassOf("ValueType")) {
468     // Using a VTSDNode.
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,
575                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
576    for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
577      Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
578 }
579
580 TreePattern::TreePattern(Record *TheRec, DagInit *Pat,
581                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
582   Trees.push_back(ParseTreePattern(Pat));
583 }
584
585 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, 
586                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
587   Trees.push_back(Pat);
588 }
589
590
591
592 void TreePattern::error(const std::string &Msg) const {
593   dump();
594   throw "In " + TheRecord->getName() + ": " + Msg;
595 }
596
597 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
598   Record *Operator = Dag->getNodeType();
599   
600   if (Operator->isSubClassOf("ValueType")) {
601     // If the operator is a ValueType, then this must be "type cast" of a leaf
602     // node.
603     if (Dag->getNumArgs() != 1)
604       error("Type cast only takes one operand!");
605     
606     Init *Arg = Dag->getArg(0);
607     TreePatternNode *New;
608     if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
609       Record *R = DI->getDef();
610       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
611         Dag->setArg(0, new DagInit(R,
612                                 std::vector<std::pair<Init*, std::string> >()));
613         TreePatternNode *TPN = ParseTreePattern(Dag);
614         TPN->setName(Dag->getArgName(0));
615         return TPN;
616       }   
617       
618       New = new TreePatternNode(DI);
619     } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
620       New = ParseTreePattern(DI);
621     } else {
622       Arg->dump();
623       error("Unknown leaf value for tree pattern!");
624       return 0;
625     }
626     
627     // Apply the type cast.
628     New->UpdateNodeType(getValueType(Operator), *this);
629     return New;
630   }
631   
632   // Verify that this is something that makes sense for an operator.
633   if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
634       !Operator->isSubClassOf("Instruction") && 
635       !Operator->isSubClassOf("SDNodeXForm") &&
636       Operator->getName() != "set")
637     error("Unrecognized node '" + Operator->getName() + "'!");
638   
639   std::vector<TreePatternNode*> Children;
640   
641   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
642     Init *Arg = Dag->getArg(i);
643     if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
644       Children.push_back(ParseTreePattern(DI));
645       Children.back()->setName(Dag->getArgName(i));
646     } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
647       Record *R = DefI->getDef();
648       // Direct reference to a leaf DagNode or PatFrag?  Turn it into a
649       // TreePatternNode if its own.
650       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
651         Dag->setArg(i, new DagInit(R,
652                               std::vector<std::pair<Init*, std::string> >()));
653         --i;  // Revisit this node...
654       } else {
655         TreePatternNode *Node = new TreePatternNode(DefI);
656         Node->setName(Dag->getArgName(i));
657         Children.push_back(Node);
658         
659         // Input argument?
660         if (R->getName() == "node") {
661           if (Dag->getArgName(i).empty())
662             error("'node' argument requires a name to match with operand list");
663           Args.push_back(Dag->getArgName(i));
664         }
665       }
666     } else {
667       Arg->dump();
668       error("Unknown leaf value for tree pattern!");
669     }
670   }
671   
672   return new TreePatternNode(Operator, Children);
673 }
674
675 /// InferAllTypes - Infer/propagate as many types throughout the expression
676 /// patterns as possible.  Return true if all types are infered, false
677 /// otherwise.  Throw an exception if a type contradiction is found.
678 bool TreePattern::InferAllTypes() {
679   bool MadeChange = true;
680   while (MadeChange) {
681     MadeChange = false;
682     for (unsigned i = 0, e = Trees.size(); i != e; ++i)
683       MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
684   }
685   
686   bool HasUnresolvedTypes = false;
687   for (unsigned i = 0, e = Trees.size(); i != e; ++i)
688     HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
689   return !HasUnresolvedTypes;
690 }
691
692 void TreePattern::print(std::ostream &OS) const {
693   OS << getRecord()->getName();
694   if (!Args.empty()) {
695     OS << "(" << Args[0];
696     for (unsigned i = 1, e = Args.size(); i != e; ++i)
697       OS << ", " << Args[i];
698     OS << ")";
699   }
700   OS << ": ";
701   
702   if (Trees.size() > 1)
703     OS << "[\n";
704   for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
705     OS << "\t";
706     Trees[i]->print(OS);
707     OS << "\n";
708   }
709
710   if (Trees.size() > 1)
711     OS << "]\n";
712 }
713
714 void TreePattern::dump() const { print(std::cerr); }
715
716
717
718 //===----------------------------------------------------------------------===//
719 // DAGISelEmitter implementation
720 //
721
722 // Parse all of the SDNode definitions for the target, populating SDNodes.
723 void DAGISelEmitter::ParseNodeInfo() {
724   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
725   while (!Nodes.empty()) {
726     SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
727     Nodes.pop_back();
728   }
729 }
730
731 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
732 /// map, and emit them to the file as functions.
733 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
734   OS << "\n// Node transformations.\n";
735   std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
736   while (!Xforms.empty()) {
737     Record *XFormNode = Xforms.back();
738     Record *SDNode = XFormNode->getValueAsDef("Opcode");
739     std::string Code = XFormNode->getValueAsCode("XFormFunction");
740     SDNodeXForms.insert(std::make_pair(XFormNode,
741                                        std::make_pair(SDNode, Code)));
742
743     if (!Code.empty()) {
744       std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
745       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
746
747       OS << "inline SDOperand Transform_" << XFormNode->getName()
748          << "(SDNode *" << C2 << ") {\n";
749       if (ClassName != "SDNode")
750         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
751       OS << Code << "\n}\n";
752     }
753
754     Xforms.pop_back();
755   }
756 }
757
758
759
760 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
761 /// file, building up the PatternFragments map.  After we've collected them all,
762 /// inline fragments together as necessary, so that there are no references left
763 /// inside a pattern fragment to a pattern fragment.
764 ///
765 /// This also emits all of the predicate functions to the output file.
766 ///
767 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
768   std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
769   
770   // First step, parse all of the fragments and emit predicate functions.
771   OS << "\n// Predicate functions.\n";
772   for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
773     DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
774     TreePattern *P = new TreePattern(Fragments[i], Tree, *this);
775     PatternFragments[Fragments[i]] = P;
776     
777     // Validate the argument list, converting it to map, to discard duplicates.
778     std::vector<std::string> &Args = P->getArgList();
779     std::set<std::string> OperandsMap(Args.begin(), Args.end());
780     
781     if (OperandsMap.count(""))
782       P->error("Cannot have unnamed 'node' values in pattern fragment!");
783     
784     // Parse the operands list.
785     DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
786     if (OpsList->getNodeType()->getName() != "ops")
787       P->error("Operands list should start with '(ops ... '!");
788     
789     // Copy over the arguments.       
790     Args.clear();
791     for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
792       if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
793           static_cast<DefInit*>(OpsList->getArg(j))->
794           getDef()->getName() != "node")
795         P->error("Operands list should all be 'node' values.");
796       if (OpsList->getArgName(j).empty())
797         P->error("Operands list should have names for each operand!");
798       if (!OperandsMap.count(OpsList->getArgName(j)))
799         P->error("'" + OpsList->getArgName(j) +
800                  "' does not occur in pattern or was multiply specified!");
801       OperandsMap.erase(OpsList->getArgName(j));
802       Args.push_back(OpsList->getArgName(j));
803     }
804     
805     if (!OperandsMap.empty())
806       P->error("Operands list does not contain an entry for operand '" +
807                *OperandsMap.begin() + "'!");
808
809     // If there is a code init for this fragment, emit the predicate code and
810     // keep track of the fact that this fragment uses it.
811     std::string Code = Fragments[i]->getValueAsCode("Predicate");
812     if (!Code.empty()) {
813       assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
814       std::string ClassName =
815         getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
816       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
817       
818       OS << "inline bool Predicate_" << Fragments[i]->getName()
819          << "(SDNode *" << C2 << ") {\n";
820       if (ClassName != "SDNode")
821         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
822       OS << Code << "\n}\n";
823       P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
824     }
825     
826     // If there is a node transformation corresponding to this, keep track of
827     // it.
828     Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
829     if (!getSDNodeTransform(Transform).second.empty())    // not noop xform?
830       P->getOnlyTree()->setTransformFn(Transform);
831   }
832   
833   OS << "\n\n";
834
835   // Now that we've parsed all of the tree fragments, do a closure on them so
836   // that there are not references to PatFrags left inside of them.
837   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
838        E = PatternFragments.end(); I != E; ++I) {
839     TreePattern *ThePat = I->second;
840     ThePat->InlinePatternFragments();
841         
842     // Infer as many types as possible.  Don't worry about it if we don't infer
843     // all of them, some may depend on the inputs of the pattern.
844     try {
845       ThePat->InferAllTypes();
846     } catch (...) {
847       // If this pattern fragment is not supported by this target (no types can
848       // satisfy its constraints), just ignore it.  If the bogus pattern is
849       // actually used by instructions, the type consistency error will be
850       // reported there.
851     }
852     
853     // If debugging, print out the pattern fragment result.
854     DEBUG(ThePat->dump());
855   }
856 }
857
858 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
859 /// instruction input.  Return true if this is a real use.
860 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
861                       std::map<std::string, TreePatternNode*> &InstInputs) {
862   // No name -> not interesting.
863   if (Pat->getName().empty()) {
864     if (Pat->isLeaf()) {
865       DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
866       if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
867         I->error("Input " + DI->getDef()->getName() + " must be named!");
868
869     }
870     return false;
871   }
872
873   Record *Rec;
874   if (Pat->isLeaf()) {
875     DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
876     if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
877     Rec = DI->getDef();
878   } else {
879     assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
880     Rec = Pat->getOperator();
881   }
882
883   TreePatternNode *&Slot = InstInputs[Pat->getName()];
884   if (!Slot) {
885     Slot = Pat;
886   } else {
887     Record *SlotRec;
888     if (Slot->isLeaf()) {
889       SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
890     } else {
891       assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
892       SlotRec = Slot->getOperator();
893     }
894     
895     // Ensure that the inputs agree if we've already seen this input.
896     if (Rec != SlotRec)
897       I->error("All $" + Pat->getName() + " inputs must agree with each other");
898     if (Slot->getExtType() != Pat->getExtType())
899       I->error("All $" + Pat->getName() + " inputs must agree with each other");
900   }
901   return true;
902 }
903
904 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
905 /// part of "I", the instruction), computing the set of inputs and outputs of
906 /// the pattern.  Report errors if we see anything naughty.
907 void DAGISelEmitter::
908 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
909                             std::map<std::string, TreePatternNode*> &InstInputs,
910                             std::map<std::string, Record*> &InstResults) {
911   if (Pat->isLeaf()) {
912     bool isUse = HandleUse(I, Pat, InstInputs);
913     if (!isUse && Pat->getTransformFn())
914       I->error("Cannot specify a transform function for a non-input value!");
915     return;
916   } else if (Pat->getOperator()->getName() != "set") {
917     // If this is not a set, verify that the children nodes are not void typed,
918     // and recurse.
919     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
920       if (Pat->getChild(i)->getExtType() == MVT::isVoid)
921         I->error("Cannot have void nodes inside of patterns!");
922       FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
923     }
924     
925     // If this is a non-leaf node with no children, treat it basically as if
926     // it were a leaf.  This handles nodes like (imm).
927     bool isUse = false;
928     if (Pat->getNumChildren() == 0)
929       isUse = HandleUse(I, Pat, InstInputs);
930     
931     if (!isUse && Pat->getTransformFn())
932       I->error("Cannot specify a transform function for a non-input value!");
933     return;
934   } 
935   
936   // Otherwise, this is a set, validate and collect instruction results.
937   if (Pat->getNumChildren() == 0)
938     I->error("set requires operands!");
939   else if (Pat->getNumChildren() & 1)
940     I->error("set requires an even number of operands");
941   
942   if (Pat->getTransformFn())
943     I->error("Cannot specify a transform function on a set node!");
944   
945   // Check the set destinations.
946   unsigned NumValues = Pat->getNumChildren()/2;
947   for (unsigned i = 0; i != NumValues; ++i) {
948     TreePatternNode *Dest = Pat->getChild(i);
949     if (!Dest->isLeaf())
950       I->error("set destination should be a virtual register!");
951     
952     DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
953     if (!Val)
954       I->error("set destination should be a virtual register!");
955     
956     if (!Val->getDef()->isSubClassOf("RegisterClass"))
957       I->error("set destination should be a virtual register!");
958     if (Dest->getName().empty())
959       I->error("set destination must have a name!");
960     if (InstResults.count(Dest->getName()))
961       I->error("cannot set '" + Dest->getName() +"' multiple times");
962     InstResults[Dest->getName()] = Val->getDef();
963
964     // Verify and collect info from the computation.
965     FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
966                                 InstInputs, InstResults);
967   }
968 }
969
970
971 /// ParseInstructions - Parse all of the instructions, inlining and resolving
972 /// any fragments involved.  This populates the Instructions list with fully
973 /// resolved instructions.
974 void DAGISelEmitter::ParseInstructions() {
975   std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
976   
977   for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
978     if (!dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
979       continue; // no pattern yet, ignore it.
980     
981     ListInit *LI = Instrs[i]->getValueAsListInit("Pattern");
982     if (LI->getSize() == 0) continue;  // no pattern.
983     
984     // Parse the instruction.
985     TreePattern *I = new TreePattern(Instrs[i], LI, *this);
986     // Inline pattern fragments into it.
987     I->InlinePatternFragments();
988     
989     // Infer as many types as possible.  If we cannot infer all of them, we can
990     // never do anything with this instruction pattern: report it to the user.
991     if (!I->InferAllTypes())
992       I->error("Could not infer all types in pattern!");
993     
994     // InstInputs - Keep track of all of the inputs of the instruction, along 
995     // with the record they are declared as.
996     std::map<std::string, TreePatternNode*> InstInputs;
997     
998     // InstResults - Keep track of all the virtual registers that are 'set'
999     // in the instruction, including what reg class they are.
1000     std::map<std::string, Record*> InstResults;
1001     
1002     // Verify that the top-level forms in the instruction are of void type, and
1003     // fill in the InstResults map.
1004     for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1005       TreePatternNode *Pat = I->getTree(j);
1006       if (Pat->getExtType() != MVT::isVoid) {
1007         I->dump();
1008         I->error("Top-level forms in instruction pattern should have"
1009                  " void types");
1010       }
1011
1012       // Find inputs and outputs, and verify the structure of the uses/defs.
1013       FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
1014     }
1015
1016     // Now that we have inputs and outputs of the pattern, inspect the operands
1017     // list for the instruction.  This determines the order that operands are
1018     // added to the machine instruction the node corresponds to.
1019     unsigned NumResults = InstResults.size();
1020
1021     // Parse the operands list from the (ops) list, validating it.
1022     std::vector<std::string> &Args = I->getArgList();
1023     assert(Args.empty() && "Args list should still be empty here!");
1024     CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1025
1026     // Check that all of the results occur first in the list.
1027     std::vector<MVT::ValueType> ResultTypes;
1028     for (unsigned i = 0; i != NumResults; ++i) {
1029       if (i == CGI.OperandList.size())
1030         I->error("'" + InstResults.begin()->first +
1031                  "' set but does not appear in operand list!");
1032       const std::string &OpName = CGI.OperandList[i].Name;
1033       
1034       // Check that it exists in InstResults.
1035       Record *R = InstResults[OpName];
1036       if (R == 0)
1037         I->error("Operand $" + OpName + " should be a set destination: all "
1038                  "outputs must occur before inputs in operand list!");
1039       
1040       if (CGI.OperandList[i].Rec != R)
1041         I->error("Operand $" + OpName + " class mismatch!");
1042       
1043       // Remember the return type.
1044       ResultTypes.push_back(CGI.OperandList[i].Ty);
1045       
1046       // Okay, this one checks out.
1047       InstResults.erase(OpName);
1048     }
1049
1050     // Loop over the inputs next.  Make a copy of InstInputs so we can destroy
1051     // the copy while we're checking the inputs.
1052     std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1053
1054     std::vector<TreePatternNode*> ResultNodeOperands;
1055     std::vector<MVT::ValueType> OperandTypes;
1056     for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1057       const std::string &OpName = CGI.OperandList[i].Name;
1058       if (OpName.empty())
1059         I->error("Operand #" + utostr(i) + " in operands list has no name!");
1060
1061       if (!InstInputsCheck.count(OpName))
1062         I->error("Operand $" + OpName +
1063                  " does not appear in the instruction pattern");
1064       TreePatternNode *InVal = InstInputsCheck[OpName];
1065       InstInputsCheck.erase(OpName);   // It occurred, remove from map.
1066       if (CGI.OperandList[i].Ty != InVal->getExtType())
1067         I->error("Operand $" + OpName +
1068                  "'s type disagrees between the operand and pattern");
1069       OperandTypes.push_back(InVal->getType());
1070       
1071       // Construct the result for the dest-pattern operand list.
1072       TreePatternNode *OpNode = InVal->clone();
1073       
1074       // No predicate is useful on the result.
1075       OpNode->setPredicateFn("");
1076       
1077       // Promote the xform function to be an explicit node if set.
1078       if (Record *Xform = OpNode->getTransformFn()) {
1079         OpNode->setTransformFn(0);
1080         std::vector<TreePatternNode*> Children;
1081         Children.push_back(OpNode);
1082         OpNode = new TreePatternNode(Xform, Children);
1083       }
1084       
1085       ResultNodeOperands.push_back(OpNode);
1086     }
1087     
1088     if (!InstInputsCheck.empty())
1089       I->error("Input operand $" + InstInputsCheck.begin()->first +
1090                " occurs in pattern but not in operands list!");
1091
1092     TreePatternNode *ResultPattern =
1093       new TreePatternNode(I->getRecord(), ResultNodeOperands);
1094
1095     // Create and insert the instruction.
1096     DAGInstruction TheInst(I, ResultTypes, OperandTypes);
1097     Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1098
1099     // Use a temporary tree pattern to infer all types and make sure that the
1100     // constructed result is correct.  This depends on the instruction already
1101     // being inserted into the Instructions map.
1102     TreePattern Temp(I->getRecord(), ResultPattern, *this);
1103     Temp.InferAllTypes();
1104
1105     DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1106     TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1107     
1108     DEBUG(I->dump());
1109   }
1110    
1111   // If we can, convert the instructions to be patterns that are matched!
1112   for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1113        E = Instructions.end(); II != E; ++II) {
1114     TreePattern *I = II->second.getPattern();
1115     
1116     if (I->getNumTrees() != 1) {
1117       std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1118       continue;
1119     }
1120     TreePatternNode *Pattern = I->getTree(0);
1121     if (Pattern->getOperator()->getName() != "set")
1122       continue;  // Not a set (store or something?)
1123     
1124     if (Pattern->getNumChildren() != 2)
1125       continue;  // Not a set of a single value (not handled so far)
1126     
1127     TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
1128     
1129     std::string Reason;
1130     if (!SrcPattern->canPatternMatch(Reason, *this))
1131       I->error("Instruction can never match: " + Reason);
1132     
1133     TreePatternNode *DstPattern = II->second.getResultPattern();
1134     PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
1135   }
1136 }
1137
1138 void DAGISelEmitter::ParsePatterns() {
1139   std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1140
1141   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1142     DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1143     TreePattern *Pattern = new TreePattern(Patterns[i], Tree, *this);
1144
1145     // Inline pattern fragments into it.
1146     Pattern->InlinePatternFragments();
1147     
1148     // Infer as many types as possible.  If we cannot infer all of them, we can
1149     // never do anything with this pattern: report it to the user.
1150     if (!Pattern->InferAllTypes())
1151       Pattern->error("Could not infer all types in pattern!");
1152     
1153     ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1154     if (LI->getSize() == 0) continue;  // no pattern.
1155     
1156     // Parse the instruction.
1157     TreePattern *Result = new TreePattern(Patterns[i], LI, *this);
1158     
1159     // Inline pattern fragments into it.
1160     Result->InlinePatternFragments();
1161     
1162     // Infer as many types as possible.  If we cannot infer all of them, we can
1163     // never do anything with this pattern: report it to the user.
1164     if (!Result->InferAllTypes())
1165       Result->error("Could not infer all types in pattern result!");
1166    
1167     if (Result->getNumTrees() != 1)
1168       Result->error("Cannot handle instructions producing instructions "
1169                     "with temporaries yet!");
1170
1171     std::string Reason;
1172     if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1173       Pattern->error("Pattern can never match: " + Reason);
1174     
1175     PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1176                                              Result->getOnlyTree()));
1177   }
1178 }
1179
1180 /// CombineChildVariants - Given a bunch of permutations of each child of the
1181 /// 'operator' node, put them together in all possible ways.
1182 static void CombineChildVariants(TreePatternNode *Orig, 
1183                const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1184                                  std::vector<TreePatternNode*> &OutVariants,
1185                                  DAGISelEmitter &ISE) {
1186   // Make sure that each operand has at least one variant to choose from.
1187   for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1188     if (ChildVariants[i].empty())
1189       return;
1190         
1191   // The end result is an all-pairs construction of the resultant pattern.
1192   std::vector<unsigned> Idxs;
1193   Idxs.resize(ChildVariants.size());
1194   bool NotDone = true;
1195   while (NotDone) {
1196     // Create the variant and add it to the output list.
1197     std::vector<TreePatternNode*> NewChildren;
1198     for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1199       NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1200     TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1201     
1202     // Copy over properties.
1203     R->setName(Orig->getName());
1204     R->setPredicateFn(Orig->getPredicateFn());
1205     R->setTransformFn(Orig->getTransformFn());
1206     R->setType(Orig->getExtType());
1207     
1208     // If this pattern cannot every match, do not include it as a variant.
1209     std::string ErrString;
1210     if (!R->canPatternMatch(ErrString, ISE)) {
1211       delete R;
1212     } else {
1213       bool AlreadyExists = false;
1214       
1215       // Scan to see if this pattern has already been emitted.  We can get
1216       // duplication due to things like commuting:
1217       //   (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1218       // which are the same pattern.  Ignore the dups.
1219       for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1220         if (R->isIsomorphicTo(OutVariants[i])) {
1221           AlreadyExists = true;
1222           break;
1223         }
1224       
1225       if (AlreadyExists)
1226         delete R;
1227       else
1228         OutVariants.push_back(R);
1229     }
1230     
1231     // Increment indices to the next permutation.
1232     NotDone = false;
1233     // Look for something we can increment without causing a wrap-around.
1234     for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1235       if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1236         NotDone = true;   // Found something to increment.
1237         break;
1238       }
1239       Idxs[IdxsIdx] = 0;
1240     }
1241   }
1242 }
1243
1244 /// CombineChildVariants - A helper function for binary operators.
1245 ///
1246 static void CombineChildVariants(TreePatternNode *Orig, 
1247                                  const std::vector<TreePatternNode*> &LHS,
1248                                  const std::vector<TreePatternNode*> &RHS,
1249                                  std::vector<TreePatternNode*> &OutVariants,
1250                                  DAGISelEmitter &ISE) {
1251   std::vector<std::vector<TreePatternNode*> > ChildVariants;
1252   ChildVariants.push_back(LHS);
1253   ChildVariants.push_back(RHS);
1254   CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1255 }  
1256
1257
1258 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1259                                      std::vector<TreePatternNode *> &Children) {
1260   assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1261   Record *Operator = N->getOperator();
1262   
1263   // Only permit raw nodes.
1264   if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1265       N->getTransformFn()) {
1266     Children.push_back(N);
1267     return;
1268   }
1269
1270   if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1271     Children.push_back(N->getChild(0));
1272   else
1273     GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1274
1275   if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1276     Children.push_back(N->getChild(1));
1277   else
1278     GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1279 }
1280
1281 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1282 /// the (potentially recursive) pattern by using algebraic laws.
1283 ///
1284 static void GenerateVariantsOf(TreePatternNode *N,
1285                                std::vector<TreePatternNode*> &OutVariants,
1286                                DAGISelEmitter &ISE) {
1287   // We cannot permute leaves.
1288   if (N->isLeaf()) {
1289     OutVariants.push_back(N);
1290     return;
1291   }
1292
1293   // Look up interesting info about the node.
1294   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1295
1296   // If this node is associative, reassociate.
1297   if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1298     // Reassociate by pulling together all of the linked operators 
1299     std::vector<TreePatternNode*> MaximalChildren;
1300     GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1301
1302     // Only handle child sizes of 3.  Otherwise we'll end up trying too many
1303     // permutations.
1304     if (MaximalChildren.size() == 3) {
1305       // Find the variants of all of our maximal children.
1306       std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1307       GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1308       GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1309       GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1310       
1311       // There are only two ways we can permute the tree:
1312       //   (A op B) op C    and    A op (B op C)
1313       // Within these forms, we can also permute A/B/C.
1314       
1315       // Generate legal pair permutations of A/B/C.
1316       std::vector<TreePatternNode*> ABVariants;
1317       std::vector<TreePatternNode*> BAVariants;
1318       std::vector<TreePatternNode*> ACVariants;
1319       std::vector<TreePatternNode*> CAVariants;
1320       std::vector<TreePatternNode*> BCVariants;
1321       std::vector<TreePatternNode*> CBVariants;
1322       CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1323       CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1324       CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1325       CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1326       CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1327       CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1328
1329       // Combine those into the result: (x op x) op x
1330       CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1331       CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1332       CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1333       CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1334       CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1335       CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1336
1337       // Combine those into the result: x op (x op x)
1338       CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1339       CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1340       CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1341       CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1342       CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1343       CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1344       return;
1345     }
1346   }
1347   
1348   // Compute permutations of all children.
1349   std::vector<std::vector<TreePatternNode*> > ChildVariants;
1350   ChildVariants.resize(N->getNumChildren());
1351   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1352     GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1353
1354   // Build all permutations based on how the children were formed.
1355   CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1356
1357   // If this node is commutative, consider the commuted order.
1358   if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1359     assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1360     // Consider the commuted order.
1361     CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1362                          OutVariants, ISE);
1363   }
1364 }
1365
1366
1367 // GenerateVariants - Generate variants.  For example, commutative patterns can
1368 // match multiple ways.  Add them to PatternsToMatch as well.
1369 void DAGISelEmitter::GenerateVariants() {
1370   
1371   DEBUG(std::cerr << "Generating instruction variants.\n");
1372   
1373   // Loop over all of the patterns we've collected, checking to see if we can
1374   // generate variants of the instruction, through the exploitation of
1375   // identities.  This permits the target to provide agressive matching without
1376   // the .td file having to contain tons of variants of instructions.
1377   //
1378   // Note that this loop adds new patterns to the PatternsToMatch list, but we
1379   // intentionally do not reconsider these.  Any variants of added patterns have
1380   // already been added.
1381   //
1382   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1383     std::vector<TreePatternNode*> Variants;
1384     GenerateVariantsOf(PatternsToMatch[i].first, Variants, *this);
1385
1386     assert(!Variants.empty() && "Must create at least original variant!");
1387     Variants.erase(Variants.begin());  // Remove the original pattern.
1388
1389     if (Variants.empty())  // No variants for this pattern.
1390       continue;
1391
1392     DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1393           PatternsToMatch[i].first->dump();
1394           std::cerr << "\n");
1395
1396     for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1397       TreePatternNode *Variant = Variants[v];
1398
1399       DEBUG(std::cerr << "  VAR#" << v <<  ": ";
1400             Variant->dump();
1401             std::cerr << "\n");
1402       
1403       // Scan to see if an instruction or explicit pattern already matches this.
1404       bool AlreadyExists = false;
1405       for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1406         // Check to see if this variant already exists.
1407         if (Variant->isIsomorphicTo(PatternsToMatch[p].first)) {
1408           DEBUG(std::cerr << "  *** ALREADY EXISTS, ignoring variant.\n");
1409           AlreadyExists = true;
1410           break;
1411         }
1412       }
1413       // If we already have it, ignore the variant.
1414       if (AlreadyExists) continue;
1415
1416       // Otherwise, add it to the list of patterns we have.
1417       PatternsToMatch.push_back(std::make_pair(Variant, 
1418                                                PatternsToMatch[i].second));
1419     }
1420
1421     DEBUG(std::cerr << "\n");
1422   }
1423 }
1424
1425
1426 /// getPatternSize - Return the 'size' of this pattern.  We want to match large
1427 /// patterns before small ones.  This is used to determine the size of a
1428 /// pattern.
1429 static unsigned getPatternSize(TreePatternNode *P) {
1430   assert(isExtIntegerVT(P->getExtType()) || 
1431          isExtFloatingPointVT(P->getExtType()) &&
1432          "Not a valid pattern node to size!");
1433   unsigned Size = 1;  // The node itself.
1434   
1435   // Count children in the count if they are also nodes.
1436   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1437     TreePatternNode *Child = P->getChild(i);
1438     if (!Child->isLeaf() && Child->getExtType() != MVT::Other)
1439       Size += getPatternSize(Child);
1440   }
1441   
1442   return Size;
1443 }
1444
1445 /// getResultPatternCost - Compute the number of instructions for this pattern.
1446 /// This is a temporary hack.  We should really include the instruction
1447 /// latencies in this calculation.
1448 static unsigned getResultPatternCost(TreePatternNode *P) {
1449   if (P->isLeaf()) return 0;
1450   
1451   unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1452   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1453     Cost += getResultPatternCost(P->getChild(i));
1454   return Cost;
1455 }
1456
1457 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1458 // In particular, we want to match maximal patterns first and lowest cost within
1459 // a particular complexity first.
1460 struct PatternSortingPredicate {
1461   bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1462                   DAGISelEmitter::PatternToMatch *RHS) {
1463     unsigned LHSSize = getPatternSize(LHS->first);
1464     unsigned RHSSize = getPatternSize(RHS->first);
1465     if (LHSSize > RHSSize) return true;   // LHS -> bigger -> less cost
1466     if (LHSSize < RHSSize) return false;
1467     
1468     // If the patterns have equal complexity, compare generated instruction cost
1469     return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1470   }
1471 };
1472
1473 /// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
1474 /// if the match fails.  At this point, we already know that the opcode for N
1475 /// matches, and the SDNode for the result has the RootName specified name.
1476 void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
1477                                          const std::string &RootName,
1478                                      std::map<std::string,std::string> &VarMap,
1479                                          unsigned PatternNo, std::ostream &OS) {
1480   assert(!N->isLeaf() && "Cannot match against a leaf!");
1481   
1482   // If this node has a name associated with it, capture it in VarMap.  If
1483   // we already saw this in the pattern, emit code to verify dagness.
1484   if (!N->getName().empty()) {
1485     std::string &VarMapEntry = VarMap[N->getName()];
1486     if (VarMapEntry.empty()) {
1487       VarMapEntry = RootName;
1488     } else {
1489       // If we get here, this is a second reference to a specific name.  Since
1490       // we already have checked that the first reference is valid, we don't
1491       // have to recursively match it, just check that it's the same as the
1492       // previously named thing.
1493       OS << "      if (" << VarMapEntry << " != " << RootName
1494          << ") goto P" << PatternNo << "Fail;\n";
1495       return;
1496     }
1497   }
1498   
1499   // Emit code to load the child nodes and match their contents recursively.
1500   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1501     OS << "      SDOperand " << RootName << i <<" = " << RootName
1502        << ".getOperand(" << i << ");\n";
1503     TreePatternNode *Child = N->getChild(i);
1504     
1505     if (!Child->isLeaf()) {
1506       // If it's not a leaf, recursively match.
1507       const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
1508       OS << "      if (" << RootName << i << ".getOpcode() != "
1509          << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
1510       EmitMatchForPattern(Child, RootName + utostr(i), VarMap, PatternNo, OS);
1511     } else {
1512       // If this child has a name associated with it, capture it in VarMap.  If
1513       // we already saw this in the pattern, emit code to verify dagness.
1514       if (!Child->getName().empty()) {
1515         std::string &VarMapEntry = VarMap[Child->getName()];
1516         if (VarMapEntry.empty()) {
1517           VarMapEntry = RootName + utostr(i);
1518         } else {
1519           // If we get here, this is a second reference to a specific name.  Since
1520           // we already have checked that the first reference is valid, we don't
1521           // have to recursively match it, just check that it's the same as the
1522           // previously named thing.
1523           OS << "      if (" << VarMapEntry << " != " << RootName << i
1524           << ") goto P" << PatternNo << "Fail;\n";
1525           continue;
1526         }
1527       }
1528       
1529       // Handle leaves of various types.
1530       Init *LeafVal = Child->getLeafValue();
1531       Record *LeafRec = dynamic_cast<DefInit*>(LeafVal)->getDef();
1532       if (LeafRec->isSubClassOf("RegisterClass")) {
1533         // Handle register references.  Nothing to do here.
1534       } else if (LeafRec->isSubClassOf("ValueType")) {
1535         // Make sure this is the specified value type.
1536         OS << "      if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1537            << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1538            << "Fail;\n";
1539       } else {
1540         Child->dump();
1541         assert(0 && "Unknown leaf type!");
1542       }
1543     }
1544   }
1545   
1546   // If there is a node predicate for this, emit the call.
1547   if (!N->getPredicateFn().empty())
1548     OS << "      if (!" << N->getPredicateFn() << "(" << RootName
1549        << ".Val)) goto P" << PatternNo << "Fail;\n";
1550 }
1551
1552 /// CodeGenPatternResult - Emit the action for a pattern.  Now that it has
1553 /// matched, we actually have to build a DAG!
1554 unsigned DAGISelEmitter::
1555 CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1556                      std::map<std::string,std::string> &VariableMap, 
1557                      std::ostream &OS) {
1558   // This is something selected from the pattern we matched.
1559   if (!N->getName().empty()) {
1560     std::string &Val = VariableMap[N->getName()];
1561     assert(!Val.empty() &&
1562            "Variable referenced but not defined and not caught earlier!");
1563     if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1564       // Already selected this operand, just return the tmpval.
1565       return atoi(Val.c_str()+3);
1566     }
1567     
1568     unsigned ResNo = Ctr++;
1569     if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1570       switch (N->getType()) {
1571       default: assert(0 && "Unknown type for constant node!");
1572       case MVT::i1:  OS << "      bool Tmp"; break;
1573       case MVT::i8:  OS << "      unsigned char Tmp"; break;
1574       case MVT::i16: OS << "      unsigned short Tmp"; break;
1575       case MVT::i32: OS << "      unsigned Tmp"; break;
1576       case MVT::i64: OS << "      uint64_t Tmp"; break;
1577       }
1578       OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1579       OS << "      SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1580          << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1581     } else {
1582       OS << "      SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1583     }
1584     // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1585     // value if used multiple times by this pattern result.
1586     Val = "Tmp"+utostr(ResNo);
1587     return ResNo;
1588   }
1589   
1590   if (N->isLeaf()) {
1591     N->dump();
1592     assert(0 && "Unknown leaf type!");
1593     return ~0U;
1594   }
1595
1596   Record *Op = N->getOperator();
1597   if (Op->isSubClassOf("Instruction")) {
1598     // Emit all of the operands.
1599     std::vector<unsigned> Ops;
1600     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1601       Ops.push_back(CodeGenPatternResult(N->getChild(i), Ctr, VariableMap, OS));
1602
1603     CodeGenInstruction &II = Target.getInstruction(Op->getName());
1604     unsigned ResNo = Ctr++;
1605     
1606     OS << "      SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1607        << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1608        << getEnumName(N->getType());
1609     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1610       OS << ", Tmp" << Ops[i];
1611     OS << ");\n";
1612     return ResNo;
1613   } else if (Op->isSubClassOf("SDNodeXForm")) {
1614     assert(N->getNumChildren() == 1 && "node xform should have one child!");
1615     unsigned OpVal = CodeGenPatternResult(N->getChild(0), Ctr, VariableMap, OS);
1616     
1617     unsigned ResNo = Ctr++;
1618     OS << "      SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1619        << "(Tmp" << OpVal << ".Val);\n";
1620     return ResNo;
1621   } else {
1622     N->dump();
1623     assert(0 && "Unknown node in result pattern!");
1624     return ~0U;
1625   }
1626 }
1627
1628 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1629 /// type information from it.
1630 static void RemoveAllTypes(TreePatternNode *N) {
1631   N->setType(MVT::isUnknown);
1632   if (!N->isLeaf())
1633     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1634       RemoveAllTypes(N->getChild(i));
1635 }
1636
1637 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
1638 /// add it to the tree.  'Pat' and 'Other' are isomorphic trees except that 
1639 /// 'Pat' may be missing types.  If we find an unresolved type to add a check
1640 /// for, this returns true otherwise false if Pat has all types.
1641 static bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1642                                const std::string &Prefix, unsigned PatternNo,
1643                                std::ostream &OS) {
1644   // Did we find one?
1645   if (!Pat->hasTypeSet()) {
1646     // Move a type over from 'other' to 'pat'.
1647     Pat->setType(Other->getType());
1648     OS << "      if (" << Prefix << ".getValueType() != MVT::"
1649        << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
1650     return true;
1651   } else if (Pat->isLeaf()) {
1652     return false;
1653   }
1654   
1655   for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i)
1656     if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1657                            Prefix + utostr(i), PatternNo, OS))
1658       return true;
1659   return false;
1660 }
1661
1662 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1663 /// stream to match the pattern, and generate the code for the match if it
1664 /// succeeds.
1665 void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1666                                         std::ostream &OS) {
1667   static unsigned PatternCount = 0;
1668   unsigned PatternNo = PatternCount++;
1669   OS << "    { // Pattern #" << PatternNo << ": ";
1670   Pattern.first->print(OS);
1671   OS << "\n      // Emits: ";
1672   Pattern.second->print(OS);
1673   OS << "\n";
1674   OS << "      // Pattern complexity = " << getPatternSize(Pattern.first)
1675      << "  cost = " << getResultPatternCost(Pattern.second) << "\n";
1676
1677   // Emit the matcher, capturing named arguments in VariableMap.
1678   std::map<std::string,std::string> VariableMap;
1679   EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
1680   
1681   // TP - Get *SOME* tree pattern, we don't care which.
1682   TreePattern &TP = *PatternFragments.begin()->second;
1683   
1684   // At this point, we know that we structurally match the pattern, but the
1685   // types of the nodes may not match.  Figure out the fewest number of type 
1686   // comparisons we need to emit.  For example, if there is only one integer
1687   // type supported by a target, there should be no type comparisons at all for
1688   // integer patterns!
1689   //
1690   // To figure out the fewest number of type checks needed, clone the pattern,
1691   // remove the types, then perform type inference on the pattern as a whole.
1692   // If there are unresolved types, emit an explicit check for those types,
1693   // apply the type to the tree, then rerun type inference.  Iterate until all
1694   // types are resolved.
1695   //
1696   TreePatternNode *Pat = Pattern.first->clone();
1697   RemoveAllTypes(Pat);
1698   
1699   do {
1700     // Resolve/propagate as many types as possible.
1701     try {
1702       bool MadeChange = true;
1703       while (MadeChange)
1704         MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
1705     } catch (...) {
1706       assert(0 && "Error: could not find consistent types for something we"
1707              " already decided was ok!");
1708       abort();
1709     }
1710
1711     // Insert a check for an unresolved type and add it to the tree.  If we find
1712     // an unresolved type to add a check for, this returns true and we iterate,
1713     // otherwise we are done.
1714   } while (InsertOneTypeCheck(Pat, Pattern.first, "N", PatternNo, OS));
1715     
1716   unsigned TmpNo = 0;
1717   unsigned Res = CodeGenPatternResult(Pattern.second, TmpNo, VariableMap, OS);
1718   
1719   // Add the result to the map if it has multiple uses.
1720   OS << "      if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp" << Res << ";\n";
1721   OS << "      return Tmp" << Res << ";\n";
1722   delete Pat;
1723   
1724   OS << "    }\n  P" << PatternNo << "Fail:\n";
1725 }
1726
1727
1728 namespace {
1729   /// CompareByRecordName - An ordering predicate that implements less-than by
1730   /// comparing the names records.
1731   struct CompareByRecordName {
1732     bool operator()(const Record *LHS, const Record *RHS) const {
1733       // Sort by name first.
1734       if (LHS->getName() < RHS->getName()) return true;
1735       // If both names are equal, sort by pointer.
1736       return LHS->getName() == RHS->getName() && LHS < RHS;
1737     }
1738   };
1739 }
1740
1741 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1742   // Emit boilerplate.
1743   OS << "// The main instruction selector code.\n"
1744      << "SDOperand SelectCode(SDOperand N) {\n"
1745      << "  if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1746      << "      N.getOpcode() < PPCISD::FIRST_NUMBER)\n"
1747      << "    return N;   // Already selected.\n\n"
1748      << "  if (!N.Val->hasOneUse()) {\n"
1749   << "    std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
1750      << "    if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
1751      << "  }\n"
1752      << "  switch (N.getOpcode()) {\n"
1753      << "  default: break;\n"
1754      << "  case ISD::EntryToken:       // These leaves remain the same.\n"
1755      << "    return N;\n"
1756      << "  case ISD::AssertSext:\n"
1757      << "  case ISD::AssertZext: {\n"
1758      << "    SDOperand Tmp0 = Select(N.getOperand(0));\n"
1759      << "    if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
1760      << "    return Tmp0;\n"
1761      << "  }\n";
1762     
1763   // Group the patterns by their top-level opcodes.
1764   std::map<Record*, std::vector<PatternToMatch*>,
1765            CompareByRecordName> PatternsByOpcode;
1766   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
1767     PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
1768       .push_back(&PatternsToMatch[i]);
1769   
1770   // Loop over all of the case statements.
1771   for (std::map<Record*, std::vector<PatternToMatch*>,
1772                 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
1773        E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
1774     const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
1775     std::vector<PatternToMatch*> &Patterns = PBOI->second;
1776     
1777     OS << "  case " << OpcodeInfo.getEnumName() << ":\n";
1778
1779     // We want to emit all of the matching code now.  However, we want to emit
1780     // the matches in order of minimal cost.  Sort the patterns so the least
1781     // cost one is at the start.
1782     std::stable_sort(Patterns.begin(), Patterns.end(),
1783                      PatternSortingPredicate());
1784     
1785     for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1786       EmitCodeForPattern(*Patterns[i], OS);
1787     OS << "    break;\n\n";
1788   }
1789   
1790
1791   OS << "  } // end of big switch.\n\n"
1792      << "  std::cerr << \"Cannot yet select: \";\n"
1793      << "  N.Val->dump();\n"
1794      << "  std::cerr << '\\n';\n"
1795      << "  abort();\n"
1796      << "}\n";
1797 }
1798
1799 void DAGISelEmitter::run(std::ostream &OS) {
1800   EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1801                        " target", OS);
1802   
1803   OS << "// *** NOTE: This file is #included into the middle of the target\n"
1804      << "// *** instruction selector class.  These functions are really "
1805      << "methods.\n\n";
1806   
1807   OS << "// Instance var to keep track of multiply used nodes that have \n"
1808      << "// already been selected.\n"
1809      << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
1810   
1811   ParseNodeInfo();
1812   ParseNodeTransforms(OS);
1813   ParsePatternFragments(OS);
1814   ParseInstructions();
1815   ParsePatterns();
1816   
1817   // Generate variants.  For example, commutative patterns can match
1818   // multiple ways.  Add them to PatternsToMatch as well.
1819   GenerateVariants();
1820
1821   
1822   DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
1823         for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1824           std::cerr << "PATTERN: ";  PatternsToMatch[i].first->dump();
1825           std::cerr << "\nRESULT:  ";PatternsToMatch[i].second->dump();
1826           std::cerr << "\n";
1827         });
1828   
1829   // At this point, we have full information about the 'Patterns' we need to
1830   // parse, both implicitly from instructions as well as from explicit pattern
1831   // definitions.  Emit the resultant instruction selector.
1832   EmitInstructionSelector(OS);  
1833   
1834   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1835        E = PatternFragments.end(); I != E; ++I)
1836     delete I->second;
1837   PatternFragments.clear();
1838
1839   Instructions.clear();
1840 }