Tweak pattern complexity calc.
[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 template<typename T>
38 static std::vector<unsigned char> 
39 FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
40   std::vector<unsigned char> Result;
41   for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
42     if (Filter((MVT::ValueType)InVTs[i]))
43       Result.push_back(InVTs[i]);
44   return Result;
45 }
46
47 static std::vector<unsigned char>
48 ConvertVTs(const std::vector<MVT::ValueType> &InVTs) {
49   std::vector<unsigned char> Result;
50   for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
51       Result.push_back(InVTs[i]);
52   return Result;
53 }
54
55 static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
56                              const std::vector<unsigned char> &RHS) {
57   if (LHS.size() > RHS.size()) return false;
58   for (unsigned i = 0, e = LHS.size(); i != e; ++i)
59     if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
60       return false;
61   return true;
62 }
63
64 /// isExtIntegerVT - Return true if the specified extended value type vector
65 /// contains isInt or an integer value type.
66 static bool isExtIntegerInVTs(std::vector<unsigned char> EVTs) {
67   assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
68   return EVTs[0] == MVT::isInt || !(FilterEVTs(EVTs, MVT::isInteger).empty());
69 }
70
71 /// isExtFloatingPointVT - Return true if the specified extended value type 
72 /// vector contains isFP or a FP value type.
73 static bool isExtFloatingPointInVTs(std::vector<unsigned char> EVTs) {
74   assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
75   return EVTs[0] == MVT::isFP || !(FilterEVTs(EVTs, MVT::isFloatingPoint).empty());
76 }
77
78 //===----------------------------------------------------------------------===//
79 // SDTypeConstraint implementation
80 //
81
82 SDTypeConstraint::SDTypeConstraint(Record *R) {
83   OperandNo = R->getValueAsInt("OperandNum");
84   
85   if (R->isSubClassOf("SDTCisVT")) {
86     ConstraintType = SDTCisVT;
87     x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
88   } else if (R->isSubClassOf("SDTCisPtrTy")) {
89     ConstraintType = SDTCisPtrTy;
90   } else if (R->isSubClassOf("SDTCisInt")) {
91     ConstraintType = SDTCisInt;
92   } else if (R->isSubClassOf("SDTCisFP")) {
93     ConstraintType = SDTCisFP;
94   } else if (R->isSubClassOf("SDTCisSameAs")) {
95     ConstraintType = SDTCisSameAs;
96     x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
97   } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
98     ConstraintType = SDTCisVTSmallerThanOp;
99     x.SDTCisVTSmallerThanOp_Info.OtherOperandNum = 
100       R->getValueAsInt("OtherOperandNum");
101   } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
102     ConstraintType = SDTCisOpSmallerThanOp;
103     x.SDTCisOpSmallerThanOp_Info.BigOperandNum = 
104       R->getValueAsInt("BigOperandNum");
105   } else {
106     std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
107     exit(1);
108   }
109 }
110
111 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
112 /// N, which has NumResults results.
113 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
114                                                  TreePatternNode *N,
115                                                  unsigned NumResults) const {
116   assert(NumResults <= 1 &&
117          "We only work with nodes with zero or one result so far!");
118   
119   if (OpNo < NumResults)
120     return N;  // FIXME: need value #
121   else
122     return N->getChild(OpNo-NumResults);
123 }
124
125 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
126 /// constraint to the nodes operands.  This returns true if it makes a
127 /// change, false otherwise.  If a type contradiction is found, throw an
128 /// exception.
129 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
130                                            const SDNodeInfo &NodeInfo,
131                                            TreePattern &TP) const {
132   unsigned NumResults = NodeInfo.getNumResults();
133   assert(NumResults <= 1 &&
134          "We only work with nodes with zero or one result so far!");
135   
136   // Check that the number of operands is sane.
137   if (NodeInfo.getNumOperands() >= 0) {
138     if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
139       TP.error(N->getOperator()->getName() + " node requires exactly " +
140                itostr(NodeInfo.getNumOperands()) + " operands!");
141   }
142
143   const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
144   
145   TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
146   
147   switch (ConstraintType) {
148   default: assert(0 && "Unknown constraint type!");
149   case SDTCisVT:
150     // Operand must be a particular type.
151     return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
152   case SDTCisPtrTy: {
153     // Operand must be same as target pointer type.
154     return NodeToApply->UpdateNodeType(CGT.getPointerType(), TP);
155   }
156   case SDTCisInt: {
157     // If there is only one integer type supported, this must be it.
158     std::vector<MVT::ValueType> IntVTs =
159       FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
160
161     // If we found exactly one supported integer type, apply it.
162     if (IntVTs.size() == 1)
163       return NodeToApply->UpdateNodeType(IntVTs[0], TP);
164     return NodeToApply->UpdateNodeType(MVT::isInt, TP);
165   }
166   case SDTCisFP: {
167     // If there is only one FP type supported, this must be it.
168     std::vector<MVT::ValueType> FPVTs =
169       FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
170         
171     // If we found exactly one supported FP type, apply it.
172     if (FPVTs.size() == 1)
173       return NodeToApply->UpdateNodeType(FPVTs[0], TP);
174     return NodeToApply->UpdateNodeType(MVT::isFP, TP);
175   }
176   case SDTCisSameAs: {
177     TreePatternNode *OtherNode =
178       getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
179     return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
180            OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
181   }
182   case SDTCisVTSmallerThanOp: {
183     // The NodeToApply must be a leaf node that is a VT.  OtherOperandNum must
184     // have an integer type that is smaller than the VT.
185     if (!NodeToApply->isLeaf() ||
186         !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
187         !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
188                ->isSubClassOf("ValueType"))
189       TP.error(N->getOperator()->getName() + " expects a VT operand!");
190     MVT::ValueType VT =
191      getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
192     if (!MVT::isInteger(VT))
193       TP.error(N->getOperator()->getName() + " VT operand must be integer!");
194     
195     TreePatternNode *OtherNode =
196       getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
197     
198     // It must be integer.
199     bool MadeChange = false;
200     MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
201     
202     // This code only handles nodes that have one type set.  Assert here so
203     // that we can change this if we ever need to deal with multiple value
204     // types at this point.
205     assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
206     if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
207       OtherNode->UpdateNodeType(MVT::Other, TP);  // Throw an error.
208     return false;
209   }
210   case SDTCisOpSmallerThanOp: {
211     TreePatternNode *BigOperand =
212       getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
213
214     // Both operands must be integer or FP, but we don't care which.
215     bool MadeChange = false;
216     
217     // This code does not currently handle nodes which have multiple types,
218     // where some types are integer, and some are fp.  Assert that this is not
219     // the case.
220     assert(!(isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
221              isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
222            !(isExtIntegerInVTs(BigOperand->getExtTypes()) &&
223              isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
224            "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
225     if (isExtIntegerInVTs(NodeToApply->getExtTypes()))
226       MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
227     else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
228       MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
229     if (isExtIntegerInVTs(BigOperand->getExtTypes()))
230       MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
231     else if (isExtFloatingPointInVTs(BigOperand->getExtTypes()))
232       MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
233
234     std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
235     
236     if (isExtIntegerInVTs(NodeToApply->getExtTypes())) {
237       VTs = FilterVTs(VTs, MVT::isInteger);
238     } else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
239       VTs = FilterVTs(VTs, MVT::isFloatingPoint);
240     } else {
241       VTs.clear();
242     }
243
244     switch (VTs.size()) {
245     default:         // Too many VT's to pick from.
246     case 0: break;   // No info yet.
247     case 1: 
248       // Only one VT of this flavor.  Cannot ever satisify the constraints.
249       return NodeToApply->UpdateNodeType(MVT::Other, TP);  // throw
250     case 2:
251       // If we have exactly two possible types, the little operand must be the
252       // small one, the big operand should be the big one.  Common with 
253       // float/double for example.
254       assert(VTs[0] < VTs[1] && "Should be sorted!");
255       MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
256       MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
257       break;
258     }    
259     return MadeChange;
260   }
261   }  
262   return false;
263 }
264
265
266 //===----------------------------------------------------------------------===//
267 // SDNodeInfo implementation
268 //
269 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
270   EnumName    = R->getValueAsString("Opcode");
271   SDClassName = R->getValueAsString("SDClass");
272   Record *TypeProfile = R->getValueAsDef("TypeProfile");
273   NumResults = TypeProfile->getValueAsInt("NumResults");
274   NumOperands = TypeProfile->getValueAsInt("NumOperands");
275   
276   // Parse the properties.
277   Properties = 0;
278   std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
279   for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
280     if (PropList[i]->getName() == "SDNPCommutative") {
281       Properties |= 1 << SDNPCommutative;
282     } else if (PropList[i]->getName() == "SDNPAssociative") {
283       Properties |= 1 << SDNPAssociative;
284     } else if (PropList[i]->getName() == "SDNPHasChain") {
285       Properties |= 1 << SDNPHasChain;
286     } else {
287       std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
288                 << "' on node '" << R->getName() << "'!\n";
289       exit(1);
290     }
291   }
292   
293   
294   // Parse the type constraints.
295   std::vector<Record*> ConstraintList =
296     TypeProfile->getValueAsListOfDefs("Constraints");
297   TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
298 }
299
300 //===----------------------------------------------------------------------===//
301 // TreePatternNode implementation
302 //
303
304 TreePatternNode::~TreePatternNode() {
305 #if 0 // FIXME: implement refcounted tree nodes!
306   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
307     delete getChild(i);
308 #endif
309 }
310
311 /// UpdateNodeType - Set the node type of N to VT if VT contains
312 /// information.  If N already contains a conflicting type, then throw an
313 /// exception.  This returns true if any information was updated.
314 ///
315 bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
316                                      TreePattern &TP) {
317   assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
318   
319   if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs)) 
320     return false;
321   if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
322     setTypes(ExtVTs);
323     return true;
324   }
325   
326   if (ExtVTs[0] == MVT::isInt && isExtIntegerInVTs(getExtTypes())) {
327     assert(hasTypeSet() && "should be handled above!");
328     std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
329     if (getExtTypes() == FVTs)
330       return false;
331     setTypes(FVTs);
332     return true;
333   }
334   if (ExtVTs[0] == MVT::isFP  && isExtFloatingPointInVTs(getExtTypes())) {
335     assert(hasTypeSet() && "should be handled above!");
336     std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
337     if (getExtTypes() == FVTs)
338       return false;
339     setTypes(FVTs);
340     return true;
341   }
342       
343   // If we know this is an int or fp type, and we are told it is a specific one,
344   // take the advice.
345   //
346   // Similarly, we should probably set the type here to the intersection of
347   // {isInt|isFP} and ExtVTs
348   if ((getExtTypeNum(0) == MVT::isInt && isExtIntegerInVTs(ExtVTs)) ||
349       (getExtTypeNum(0) == MVT::isFP  && isExtFloatingPointInVTs(ExtVTs))) {
350     setTypes(ExtVTs);
351     return true;
352   }      
353
354   if (isLeaf()) {
355     dump();
356     std::cerr << " ";
357     TP.error("Type inference contradiction found in node!");
358   } else {
359     TP.error("Type inference contradiction found in node " + 
360              getOperator()->getName() + "!");
361   }
362   return true; // unreachable
363 }
364
365
366 void TreePatternNode::print(std::ostream &OS) const {
367   if (isLeaf()) {
368     OS << *getLeafValue();
369   } else {
370     OS << "(" << getOperator()->getName();
371   }
372   
373   // FIXME: At some point we should handle printing all the value types for 
374   // nodes that are multiply typed.
375   switch (getExtTypeNum(0)) {
376   case MVT::Other: OS << ":Other"; break;
377   case MVT::isInt: OS << ":isInt"; break;
378   case MVT::isFP : OS << ":isFP"; break;
379   case MVT::isUnknown: ; /*OS << ":?";*/ break;
380   default:  OS << ":" << getTypeNum(0); break;
381   }
382
383   if (!isLeaf()) {
384     if (getNumChildren() != 0) {
385       OS << " ";
386       getChild(0)->print(OS);
387       for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
388         OS << ", ";
389         getChild(i)->print(OS);
390       }
391     }
392     OS << ")";
393   }
394   
395   if (!PredicateFn.empty())
396     OS << "<<P:" << PredicateFn << ">>";
397   if (TransformFn)
398     OS << "<<X:" << TransformFn->getName() << ">>";
399   if (!getName().empty())
400     OS << ":$" << getName();
401
402 }
403 void TreePatternNode::dump() const {
404   print(std::cerr);
405 }
406
407 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
408 /// the specified node.  For this comparison, all of the state of the node
409 /// is considered, except for the assigned name.  Nodes with differing names
410 /// that are otherwise identical are considered isomorphic.
411 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
412   if (N == this) return true;
413   if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
414       getPredicateFn() != N->getPredicateFn() ||
415       getTransformFn() != N->getTransformFn())
416     return false;
417
418   if (isLeaf()) {
419     if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
420       if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
421         return DI->getDef() == NDI->getDef();
422     return getLeafValue() == N->getLeafValue();
423   }
424   
425   if (N->getOperator() != getOperator() ||
426       N->getNumChildren() != getNumChildren()) return false;
427   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
428     if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
429       return false;
430   return true;
431 }
432
433 /// clone - Make a copy of this tree and all of its children.
434 ///
435 TreePatternNode *TreePatternNode::clone() const {
436   TreePatternNode *New;
437   if (isLeaf()) {
438     New = new TreePatternNode(getLeafValue());
439   } else {
440     std::vector<TreePatternNode*> CChildren;
441     CChildren.reserve(Children.size());
442     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
443       CChildren.push_back(getChild(i)->clone());
444     New = new TreePatternNode(getOperator(), CChildren);
445   }
446   New->setName(getName());
447   New->setTypes(getExtTypes());
448   New->setPredicateFn(getPredicateFn());
449   New->setTransformFn(getTransformFn());
450   return New;
451 }
452
453 /// SubstituteFormalArguments - Replace the formal arguments in this tree
454 /// with actual values specified by ArgMap.
455 void TreePatternNode::
456 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
457   if (isLeaf()) return;
458   
459   for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
460     TreePatternNode *Child = getChild(i);
461     if (Child->isLeaf()) {
462       Init *Val = Child->getLeafValue();
463       if (dynamic_cast<DefInit*>(Val) &&
464           static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
465         // We found a use of a formal argument, replace it with its value.
466         Child = ArgMap[Child->getName()];
467         assert(Child && "Couldn't find formal argument!");
468         setChild(i, Child);
469       }
470     } else {
471       getChild(i)->SubstituteFormalArguments(ArgMap);
472     }
473   }
474 }
475
476
477 /// InlinePatternFragments - If this pattern refers to any pattern
478 /// fragments, inline them into place, giving us a pattern without any
479 /// PatFrag references.
480 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
481   if (isLeaf()) return this;  // nothing to do.
482   Record *Op = getOperator();
483   
484   if (!Op->isSubClassOf("PatFrag")) {
485     // Just recursively inline children nodes.
486     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
487       setChild(i, getChild(i)->InlinePatternFragments(TP));
488     return this;
489   }
490
491   // Otherwise, we found a reference to a fragment.  First, look up its
492   // TreePattern record.
493   TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
494   
495   // Verify that we are passing the right number of operands.
496   if (Frag->getNumArgs() != Children.size())
497     TP.error("'" + Op->getName() + "' fragment requires " +
498              utostr(Frag->getNumArgs()) + " operands!");
499
500   TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
501
502   // Resolve formal arguments to their actual value.
503   if (Frag->getNumArgs()) {
504     // Compute the map of formal to actual arguments.
505     std::map<std::string, TreePatternNode*> ArgMap;
506     for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
507       ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
508   
509     FragTree->SubstituteFormalArguments(ArgMap);
510   }
511   
512   FragTree->setName(getName());
513   FragTree->UpdateNodeType(getExtTypes(), TP);
514   
515   // Get a new copy of this fragment to stitch into here.
516   //delete this;    // FIXME: implement refcounting!
517   return FragTree;
518 }
519
520 /// getIntrinsicType - Check to see if the specified record has an intrinsic
521 /// type which should be applied to it.  This infer the type of register
522 /// references from the register file information, for example.
523 ///
524 static std::vector<unsigned char> getIntrinsicType(Record *R, bool NotRegisters,
525                                       TreePattern &TP) {
526   // Some common return values
527   std::vector<unsigned char> Unknown(1, MVT::isUnknown);
528   std::vector<unsigned char> Other(1, MVT::Other);
529
530   // Check to see if this is a register or a register class...
531   if (R->isSubClassOf("RegisterClass")) {
532     if (NotRegisters) 
533       return Unknown;
534     const CodeGenRegisterClass &RC = 
535       TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
536     return ConvertVTs(RC.getValueTypes());
537   } else if (R->isSubClassOf("PatFrag")) {
538     // Pattern fragment types will be resolved when they are inlined.
539     return Unknown;
540   } else if (R->isSubClassOf("Register")) {
541     // If the register appears in exactly one regclass, and the regclass has one
542     // value type, use it as the known type.
543     const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
544     if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
545       return ConvertVTs(RC->getValueTypes());
546     return Unknown;
547   } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
548     // Using a VTSDNode or CondCodeSDNode.
549     return Other;
550   } else if (R->isSubClassOf("ComplexPattern")) {
551     std::vector<unsigned char>
552     ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
553     return ComplexPat;
554   } else if (R->getName() == "node" || R->getName() == "srcvalue") {
555     // Placeholder.
556     return Unknown;
557   }
558   
559   TP.error("Unknown node flavor used in pattern: " + R->getName());
560   return Other;
561 }
562
563 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
564 /// this node and its children in the tree.  This returns true if it makes a
565 /// change, false otherwise.  If a type contradiction is found, throw an
566 /// exception.
567 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
568   if (isLeaf()) {
569     if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
570       // If it's a regclass or something else known, include the type.
571       return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
572                             TP);
573     } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
574       // Int inits are always integers. :)
575       bool MadeChange = UpdateNodeType(MVT::isInt, TP);
576       
577       if (hasTypeSet()) {
578         // At some point, it may make sense for this tree pattern to have
579         // multiple types.  Assert here that it does not, so we revisit this
580         // code when appropriate.
581         assert(getExtTypes().size() == 1 && "TreePattern has too many types!");
582         
583         unsigned Size = MVT::getSizeInBits(getTypeNum(0));
584         // Make sure that the value is representable for this type.
585         if (Size < 32) {
586           int Val = (II->getValue() << (32-Size)) >> (32-Size);
587           if (Val != II->getValue())
588             TP.error("Sign-extended integer value '" + itostr(II->getValue()) +
589                      "' is out of range for type 'MVT::" + 
590                      getEnumName(getTypeNum(0)) + "'!");
591         }
592       }
593       
594       return MadeChange;
595     }
596     return false;
597   }
598   
599   // special handling for set, which isn't really an SDNode.
600   if (getOperator()->getName() == "set") {
601     assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
602     bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
603     MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
604     
605     // Types of operands must match.
606     MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
607     MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
608     MadeChange |= UpdateNodeType(MVT::isVoid, TP);
609     return MadeChange;
610   } else if (getOperator()->isSubClassOf("SDNode")) {
611     const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
612     
613     bool MadeChange = NI.ApplyTypeConstraints(this, TP);
614     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
615       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
616     // Branch, etc. do not produce results and top-level forms in instr pattern
617     // must have void types.
618     if (NI.getNumResults() == 0)
619       MadeChange |= UpdateNodeType(MVT::isVoid, TP);
620     return MadeChange;  
621   } else if (getOperator()->isSubClassOf("Instruction")) {
622     const DAGInstruction &Inst =
623       TP.getDAGISelEmitter().getInstruction(getOperator());
624     bool MadeChange = false;
625     unsigned NumResults = Inst.getNumResults();
626     
627     assert(NumResults <= 1 &&
628            "Only supports zero or one result instrs!");
629     // Apply the result type to the node
630     if (NumResults == 0) {
631       MadeChange = UpdateNodeType(MVT::isVoid, TP);
632     } else {
633       Record *ResultNode = Inst.getResult(0);
634       assert(ResultNode->isSubClassOf("RegisterClass") &&
635              "Operands should be register classes!");
636
637       const CodeGenRegisterClass &RC = 
638         TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(ResultNode);
639       MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
640     }
641
642     if (getNumChildren() != Inst.getNumOperands())
643       TP.error("Instruction '" + getOperator()->getName() + " expects " +
644                utostr(Inst.getNumOperands()) + " operands, not " +
645                utostr(getNumChildren()) + " operands!");
646     for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
647       Record *OperandNode = Inst.getOperand(i);
648       MVT::ValueType VT;
649       if (OperandNode->isSubClassOf("RegisterClass")) {
650         const CodeGenRegisterClass &RC = 
651           TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(OperandNode);
652         //VT = RC.getValueTypeNum(0);
653         MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
654                                                  TP);
655       } else if (OperandNode->isSubClassOf("Operand")) {
656         VT = getValueType(OperandNode->getValueAsDef("Type"));
657         MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
658       } else {
659         assert(0 && "Unknown operand type!");
660         abort();
661       }
662       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
663     }
664     return MadeChange;
665   } else {
666     assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
667     
668     // Node transforms always take one operand, and take and return the same
669     // type.
670     if (getNumChildren() != 1)
671       TP.error("Node transform '" + getOperator()->getName() +
672                "' requires one operand!");
673     bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
674     MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
675     return MadeChange;
676   }
677 }
678
679 /// canPatternMatch - If it is impossible for this pattern to match on this
680 /// target, fill in Reason and return false.  Otherwise, return true.  This is
681 /// used as a santity check for .td files (to prevent people from writing stuff
682 /// that can never possibly work), and to prevent the pattern permuter from
683 /// generating stuff that is useless.
684 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
685   if (isLeaf()) return true;
686
687   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
688     if (!getChild(i)->canPatternMatch(Reason, ISE))
689       return false;
690
691   // If this node is a commutative operator, check that the LHS isn't an
692   // immediate.
693   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
694   if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
695     // Scan all of the operands of the node and make sure that only the last one
696     // is a constant node.
697     for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
698       if (!getChild(i)->isLeaf() && 
699           getChild(i)->getOperator()->getName() == "imm") {
700         Reason = "Immediate value must be on the RHS of commutative operators!";
701         return false;
702       }
703   }
704   
705   return true;
706 }
707
708 //===----------------------------------------------------------------------===//
709 // TreePattern implementation
710 //
711
712 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
713                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
714    isInputPattern = isInput;
715    for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
716      Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
717 }
718
719 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
720                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
721   isInputPattern = isInput;
722   Trees.push_back(ParseTreePattern(Pat));
723 }
724
725 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
726                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
727   isInputPattern = isInput;
728   Trees.push_back(Pat);
729 }
730
731
732
733 void TreePattern::error(const std::string &Msg) const {
734   dump();
735   throw "In " + TheRecord->getName() + ": " + Msg;
736 }
737
738 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
739   Record *Operator = Dag->getNodeType();
740   
741   if (Operator->isSubClassOf("ValueType")) {
742     // If the operator is a ValueType, then this must be "type cast" of a leaf
743     // node.
744     if (Dag->getNumArgs() != 1)
745       error("Type cast only takes one operand!");
746     
747     Init *Arg = Dag->getArg(0);
748     TreePatternNode *New;
749     if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
750       Record *R = DI->getDef();
751       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
752         Dag->setArg(0, new DagInit(R,
753                                 std::vector<std::pair<Init*, std::string> >()));
754         return ParseTreePattern(Dag);
755       }
756       New = new TreePatternNode(DI);
757     } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
758       New = ParseTreePattern(DI);
759     } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
760       New = new TreePatternNode(II);
761       if (!Dag->getArgName(0).empty())
762         error("Constant int argument should not have a name!");
763     } else {
764       Arg->dump();
765       error("Unknown leaf value for tree pattern!");
766       return 0;
767     }
768     
769     // Apply the type cast.
770     New->UpdateNodeType(getValueType(Operator), *this);
771     New->setName(Dag->getArgName(0));
772     return New;
773   }
774   
775   // Verify that this is something that makes sense for an operator.
776   if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
777       !Operator->isSubClassOf("Instruction") && 
778       !Operator->isSubClassOf("SDNodeXForm") &&
779       Operator->getName() != "set")
780     error("Unrecognized node '" + Operator->getName() + "'!");
781   
782   //  Check to see if this is something that is illegal in an input pattern.
783   if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
784       Operator->isSubClassOf("SDNodeXForm")))
785     error("Cannot use '" + Operator->getName() + "' in an input pattern!");
786   
787   std::vector<TreePatternNode*> Children;
788   
789   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
790     Init *Arg = Dag->getArg(i);
791     if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
792       Children.push_back(ParseTreePattern(DI));
793       if (Children.back()->getName().empty())
794         Children.back()->setName(Dag->getArgName(i));
795     } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
796       Record *R = DefI->getDef();
797       // Direct reference to a leaf DagNode or PatFrag?  Turn it into a
798       // TreePatternNode if its own.
799       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
800         Dag->setArg(i, new DagInit(R,
801                               std::vector<std::pair<Init*, std::string> >()));
802         --i;  // Revisit this node...
803       } else {
804         TreePatternNode *Node = new TreePatternNode(DefI);
805         Node->setName(Dag->getArgName(i));
806         Children.push_back(Node);
807         
808         // Input argument?
809         if (R->getName() == "node") {
810           if (Dag->getArgName(i).empty())
811             error("'node' argument requires a name to match with operand list");
812           Args.push_back(Dag->getArgName(i));
813         }
814       }
815     } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
816       TreePatternNode *Node = new TreePatternNode(II);
817       if (!Dag->getArgName(i).empty())
818         error("Constant int argument should not have a name!");
819       Children.push_back(Node);
820     } else {
821       std::cerr << '"';
822       Arg->dump();
823       std::cerr << "\": ";
824       error("Unknown leaf value for tree pattern!");
825     }
826   }
827   
828   return new TreePatternNode(Operator, Children);
829 }
830
831 /// InferAllTypes - Infer/propagate as many types throughout the expression
832 /// patterns as possible.  Return true if all types are infered, false
833 /// otherwise.  Throw an exception if a type contradiction is found.
834 bool TreePattern::InferAllTypes() {
835   bool MadeChange = true;
836   while (MadeChange) {
837     MadeChange = false;
838     for (unsigned i = 0, e = Trees.size(); i != e; ++i)
839       MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
840   }
841   
842   bool HasUnresolvedTypes = false;
843   for (unsigned i = 0, e = Trees.size(); i != e; ++i)
844     HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
845   return !HasUnresolvedTypes;
846 }
847
848 void TreePattern::print(std::ostream &OS) const {
849   OS << getRecord()->getName();
850   if (!Args.empty()) {
851     OS << "(" << Args[0];
852     for (unsigned i = 1, e = Args.size(); i != e; ++i)
853       OS << ", " << Args[i];
854     OS << ")";
855   }
856   OS << ": ";
857   
858   if (Trees.size() > 1)
859     OS << "[\n";
860   for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
861     OS << "\t";
862     Trees[i]->print(OS);
863     OS << "\n";
864   }
865
866   if (Trees.size() > 1)
867     OS << "]\n";
868 }
869
870 void TreePattern::dump() const { print(std::cerr); }
871
872
873
874 //===----------------------------------------------------------------------===//
875 // DAGISelEmitter implementation
876 //
877
878 // Parse all of the SDNode definitions for the target, populating SDNodes.
879 void DAGISelEmitter::ParseNodeInfo() {
880   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
881   while (!Nodes.empty()) {
882     SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
883     Nodes.pop_back();
884   }
885 }
886
887 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
888 /// map, and emit them to the file as functions.
889 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
890   OS << "\n// Node transformations.\n";
891   std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
892   while (!Xforms.empty()) {
893     Record *XFormNode = Xforms.back();
894     Record *SDNode = XFormNode->getValueAsDef("Opcode");
895     std::string Code = XFormNode->getValueAsCode("XFormFunction");
896     SDNodeXForms.insert(std::make_pair(XFormNode,
897                                        std::make_pair(SDNode, Code)));
898
899     if (!Code.empty()) {
900       std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
901       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
902
903       OS << "inline SDOperand Transform_" << XFormNode->getName()
904          << "(SDNode *" << C2 << ") {\n";
905       if (ClassName != "SDNode")
906         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
907       OS << Code << "\n}\n";
908     }
909
910     Xforms.pop_back();
911   }
912 }
913
914 void DAGISelEmitter::ParseComplexPatterns() {
915   std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
916   while (!AMs.empty()) {
917     ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
918     AMs.pop_back();
919   }
920 }
921
922
923 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
924 /// file, building up the PatternFragments map.  After we've collected them all,
925 /// inline fragments together as necessary, so that there are no references left
926 /// inside a pattern fragment to a pattern fragment.
927 ///
928 /// This also emits all of the predicate functions to the output file.
929 ///
930 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
931   std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
932   
933   // First step, parse all of the fragments and emit predicate functions.
934   OS << "\n// Predicate functions.\n";
935   for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
936     DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
937     TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
938     PatternFragments[Fragments[i]] = P;
939     
940     // Validate the argument list, converting it to map, to discard duplicates.
941     std::vector<std::string> &Args = P->getArgList();
942     std::set<std::string> OperandsMap(Args.begin(), Args.end());
943     
944     if (OperandsMap.count(""))
945       P->error("Cannot have unnamed 'node' values in pattern fragment!");
946     
947     // Parse the operands list.
948     DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
949     if (OpsList->getNodeType()->getName() != "ops")
950       P->error("Operands list should start with '(ops ... '!");
951     
952     // Copy over the arguments.       
953     Args.clear();
954     for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
955       if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
956           static_cast<DefInit*>(OpsList->getArg(j))->
957           getDef()->getName() != "node")
958         P->error("Operands list should all be 'node' values.");
959       if (OpsList->getArgName(j).empty())
960         P->error("Operands list should have names for each operand!");
961       if (!OperandsMap.count(OpsList->getArgName(j)))
962         P->error("'" + OpsList->getArgName(j) +
963                  "' does not occur in pattern or was multiply specified!");
964       OperandsMap.erase(OpsList->getArgName(j));
965       Args.push_back(OpsList->getArgName(j));
966     }
967     
968     if (!OperandsMap.empty())
969       P->error("Operands list does not contain an entry for operand '" +
970                *OperandsMap.begin() + "'!");
971
972     // If there is a code init for this fragment, emit the predicate code and
973     // keep track of the fact that this fragment uses it.
974     std::string Code = Fragments[i]->getValueAsCode("Predicate");
975     if (!Code.empty()) {
976       assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
977       std::string ClassName =
978         getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
979       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
980       
981       OS << "inline bool Predicate_" << Fragments[i]->getName()
982          << "(SDNode *" << C2 << ") {\n";
983       if (ClassName != "SDNode")
984         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
985       OS << Code << "\n}\n";
986       P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
987     }
988     
989     // If there is a node transformation corresponding to this, keep track of
990     // it.
991     Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
992     if (!getSDNodeTransform(Transform).second.empty())    // not noop xform?
993       P->getOnlyTree()->setTransformFn(Transform);
994   }
995   
996   OS << "\n\n";
997
998   // Now that we've parsed all of the tree fragments, do a closure on them so
999   // that there are not references to PatFrags left inside of them.
1000   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1001        E = PatternFragments.end(); I != E; ++I) {
1002     TreePattern *ThePat = I->second;
1003     ThePat->InlinePatternFragments();
1004         
1005     // Infer as many types as possible.  Don't worry about it if we don't infer
1006     // all of them, some may depend on the inputs of the pattern.
1007     try {
1008       ThePat->InferAllTypes();
1009     } catch (...) {
1010       // If this pattern fragment is not supported by this target (no types can
1011       // satisfy its constraints), just ignore it.  If the bogus pattern is
1012       // actually used by instructions, the type consistency error will be
1013       // reported there.
1014     }
1015     
1016     // If debugging, print out the pattern fragment result.
1017     DEBUG(ThePat->dump());
1018   }
1019 }
1020
1021 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1022 /// instruction input.  Return true if this is a real use.
1023 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1024                       std::map<std::string, TreePatternNode*> &InstInputs,
1025                       std::vector<Record*> &InstImpInputs) {
1026   // No name -> not interesting.
1027   if (Pat->getName().empty()) {
1028     if (Pat->isLeaf()) {
1029       DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1030       if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1031         I->error("Input " + DI->getDef()->getName() + " must be named!");
1032       else if (DI && DI->getDef()->isSubClassOf("Register")) 
1033         InstImpInputs.push_back(DI->getDef());
1034     }
1035     return false;
1036   }
1037
1038   Record *Rec;
1039   if (Pat->isLeaf()) {
1040     DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1041     if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1042     Rec = DI->getDef();
1043   } else {
1044     assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1045     Rec = Pat->getOperator();
1046   }
1047
1048   // SRCVALUE nodes are ignored.
1049   if (Rec->getName() == "srcvalue")
1050     return false;
1051
1052   TreePatternNode *&Slot = InstInputs[Pat->getName()];
1053   if (!Slot) {
1054     Slot = Pat;
1055   } else {
1056     Record *SlotRec;
1057     if (Slot->isLeaf()) {
1058       SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1059     } else {
1060       assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1061       SlotRec = Slot->getOperator();
1062     }
1063     
1064     // Ensure that the inputs agree if we've already seen this input.
1065     if (Rec != SlotRec)
1066       I->error("All $" + Pat->getName() + " inputs must agree with each other");
1067     if (Slot->getExtTypes() != Pat->getExtTypes())
1068       I->error("All $" + Pat->getName() + " inputs must agree with each other");
1069   }
1070   return true;
1071 }
1072
1073 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1074 /// part of "I", the instruction), computing the set of inputs and outputs of
1075 /// the pattern.  Report errors if we see anything naughty.
1076 void DAGISelEmitter::
1077 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1078                             std::map<std::string, TreePatternNode*> &InstInputs,
1079                             std::map<std::string, Record*> &InstResults,
1080                             std::vector<Record*> &InstImpInputs,
1081                             std::vector<Record*> &InstImpResults) {
1082   if (Pat->isLeaf()) {
1083     bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1084     if (!isUse && Pat->getTransformFn())
1085       I->error("Cannot specify a transform function for a non-input value!");
1086     return;
1087   } else if (Pat->getOperator()->getName() != "set") {
1088     // If this is not a set, verify that the children nodes are not void typed,
1089     // and recurse.
1090     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1091       if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1092         I->error("Cannot have void nodes inside of patterns!");
1093       FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1094                                   InstImpInputs, InstImpResults);
1095     }
1096     
1097     // If this is a non-leaf node with no children, treat it basically as if
1098     // it were a leaf.  This handles nodes like (imm).
1099     bool isUse = false;
1100     if (Pat->getNumChildren() == 0)
1101       isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1102     
1103     if (!isUse && Pat->getTransformFn())
1104       I->error("Cannot specify a transform function for a non-input value!");
1105     return;
1106   } 
1107   
1108   // Otherwise, this is a set, validate and collect instruction results.
1109   if (Pat->getNumChildren() == 0)
1110     I->error("set requires operands!");
1111   else if (Pat->getNumChildren() & 1)
1112     I->error("set requires an even number of operands");
1113   
1114   if (Pat->getTransformFn())
1115     I->error("Cannot specify a transform function on a set node!");
1116   
1117   // Check the set destinations.
1118   unsigned NumValues = Pat->getNumChildren()/2;
1119   for (unsigned i = 0; i != NumValues; ++i) {
1120     TreePatternNode *Dest = Pat->getChild(i);
1121     if (!Dest->isLeaf())
1122       I->error("set destination should be a register!");
1123     
1124     DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1125     if (!Val)
1126       I->error("set destination should be a register!");
1127
1128     if (Val->getDef()->isSubClassOf("RegisterClass")) {
1129       if (Dest->getName().empty())
1130         I->error("set destination must have a name!");
1131       if (InstResults.count(Dest->getName()))
1132         I->error("cannot set '" + Dest->getName() +"' multiple times");
1133       InstResults[Dest->getName()] = Val->getDef();
1134     } else if (Val->getDef()->isSubClassOf("Register")) {
1135       InstImpResults.push_back(Val->getDef());
1136     } else {
1137       I->error("set destination should be a register!");
1138     }
1139     
1140     // Verify and collect info from the computation.
1141     FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1142                                 InstInputs, InstResults,
1143                                 InstImpInputs, InstImpResults);
1144   }
1145 }
1146
1147 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1148 /// any fragments involved.  This populates the Instructions list with fully
1149 /// resolved instructions.
1150 void DAGISelEmitter::ParseInstructions() {
1151   std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1152   
1153   for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1154     ListInit *LI = 0;
1155     
1156     if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1157       LI = Instrs[i]->getValueAsListInit("Pattern");
1158     
1159     // If there is no pattern, only collect minimal information about the
1160     // instruction for its operand list.  We have to assume that there is one
1161     // result, as we have no detailed info.
1162     if (!LI || LI->getSize() == 0) {
1163       std::vector<Record*> Results;
1164       std::vector<Record*> Operands;
1165       
1166       CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1167
1168       if (InstInfo.OperandList.size() != 0) {
1169         // FIXME: temporary hack...
1170         if (InstInfo.noResults) {
1171           // These produce no results
1172           for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1173             Operands.push_back(InstInfo.OperandList[j].Rec);
1174         } else {
1175           // Assume the first operand is the result.
1176           Results.push_back(InstInfo.OperandList[0].Rec);
1177       
1178           // The rest are inputs.
1179           for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1180             Operands.push_back(InstInfo.OperandList[j].Rec);
1181         }
1182       }
1183       
1184       // Create and insert the instruction.
1185       std::vector<Record*> ImpResults;
1186       std::vector<Record*> ImpOperands;
1187       Instructions.insert(std::make_pair(Instrs[i], 
1188                           DAGInstruction(0, Results, Operands, ImpResults,
1189                                          ImpOperands)));
1190       continue;  // no pattern.
1191     }
1192     
1193     // Parse the instruction.
1194     TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1195     // Inline pattern fragments into it.
1196     I->InlinePatternFragments();
1197     
1198     // Infer as many types as possible.  If we cannot infer all of them, we can
1199     // never do anything with this instruction pattern: report it to the user.
1200     if (!I->InferAllTypes())
1201       I->error("Could not infer all types in pattern!");
1202     
1203     // InstInputs - Keep track of all of the inputs of the instruction, along 
1204     // with the record they are declared as.
1205     std::map<std::string, TreePatternNode*> InstInputs;
1206     
1207     // InstResults - Keep track of all the virtual registers that are 'set'
1208     // in the instruction, including what reg class they are.
1209     std::map<std::string, Record*> InstResults;
1210
1211     std::vector<Record*> InstImpInputs;
1212     std::vector<Record*> InstImpResults;
1213     
1214     // Verify that the top-level forms in the instruction are of void type, and
1215     // fill in the InstResults map.
1216     for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1217       TreePatternNode *Pat = I->getTree(j);
1218       if (Pat->getExtTypeNum(0) != MVT::isVoid)
1219         I->error("Top-level forms in instruction pattern should have"
1220                  " void types");
1221
1222       // Find inputs and outputs, and verify the structure of the uses/defs.
1223       FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1224                                   InstImpInputs, InstImpResults);
1225     }
1226
1227     // Now that we have inputs and outputs of the pattern, inspect the operands
1228     // list for the instruction.  This determines the order that operands are
1229     // added to the machine instruction the node corresponds to.
1230     unsigned NumResults = InstResults.size();
1231
1232     // Parse the operands list from the (ops) list, validating it.
1233     std::vector<std::string> &Args = I->getArgList();
1234     assert(Args.empty() && "Args list should still be empty here!");
1235     CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1236
1237     // Check that all of the results occur first in the list.
1238     std::vector<Record*> Results;
1239     for (unsigned i = 0; i != NumResults; ++i) {
1240       if (i == CGI.OperandList.size())
1241         I->error("'" + InstResults.begin()->first +
1242                  "' set but does not appear in operand list!");
1243       const std::string &OpName = CGI.OperandList[i].Name;
1244       
1245       // Check that it exists in InstResults.
1246       Record *R = InstResults[OpName];
1247       if (R == 0)
1248         I->error("Operand $" + OpName + " should be a set destination: all "
1249                  "outputs must occur before inputs in operand list!");
1250       
1251       if (CGI.OperandList[i].Rec != R)
1252         I->error("Operand $" + OpName + " class mismatch!");
1253       
1254       // Remember the return type.
1255       Results.push_back(CGI.OperandList[i].Rec);
1256       
1257       // Okay, this one checks out.
1258       InstResults.erase(OpName);
1259     }
1260
1261     // Loop over the inputs next.  Make a copy of InstInputs so we can destroy
1262     // the copy while we're checking the inputs.
1263     std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1264
1265     std::vector<TreePatternNode*> ResultNodeOperands;
1266     std::vector<Record*> Operands;
1267     for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1268       const std::string &OpName = CGI.OperandList[i].Name;
1269       if (OpName.empty())
1270         I->error("Operand #" + utostr(i) + " in operands list has no name!");
1271
1272       if (!InstInputsCheck.count(OpName))
1273         I->error("Operand $" + OpName +
1274                  " does not appear in the instruction pattern");
1275       TreePatternNode *InVal = InstInputsCheck[OpName];
1276       InstInputsCheck.erase(OpName);   // It occurred, remove from map.
1277       
1278       if (InVal->isLeaf() &&
1279           dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1280         Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1281         if (CGI.OperandList[i].Rec != InRec &&
1282             !InRec->isSubClassOf("ComplexPattern"))
1283           I->error("Operand $" + OpName +
1284                    "'s register class disagrees between the operand and pattern");
1285       }
1286       Operands.push_back(CGI.OperandList[i].Rec);
1287       
1288       // Construct the result for the dest-pattern operand list.
1289       TreePatternNode *OpNode = InVal->clone();
1290       
1291       // No predicate is useful on the result.
1292       OpNode->setPredicateFn("");
1293       
1294       // Promote the xform function to be an explicit node if set.
1295       if (Record *Xform = OpNode->getTransformFn()) {
1296         OpNode->setTransformFn(0);
1297         std::vector<TreePatternNode*> Children;
1298         Children.push_back(OpNode);
1299         OpNode = new TreePatternNode(Xform, Children);
1300       }
1301       
1302       ResultNodeOperands.push_back(OpNode);
1303     }
1304     
1305     if (!InstInputsCheck.empty())
1306       I->error("Input operand $" + InstInputsCheck.begin()->first +
1307                " occurs in pattern but not in operands list!");
1308
1309     TreePatternNode *ResultPattern =
1310       new TreePatternNode(I->getRecord(), ResultNodeOperands);
1311
1312     // Create and insert the instruction.
1313     DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1314     Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1315
1316     // Use a temporary tree pattern to infer all types and make sure that the
1317     // constructed result is correct.  This depends on the instruction already
1318     // being inserted into the Instructions map.
1319     TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1320     Temp.InferAllTypes();
1321
1322     DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1323     TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1324     
1325     DEBUG(I->dump());
1326   }
1327    
1328   // If we can, convert the instructions to be patterns that are matched!
1329   for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1330        E = Instructions.end(); II != E; ++II) {
1331     DAGInstruction &TheInst = II->second;
1332     TreePattern *I = TheInst.getPattern();
1333     if (I == 0) continue;  // No pattern.
1334
1335     if (I->getNumTrees() != 1) {
1336       std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1337       continue;
1338     }
1339     TreePatternNode *Pattern = I->getTree(0);
1340     TreePatternNode *SrcPattern;
1341     if (Pattern->getOperator()->getName() == "set") {
1342       if (Pattern->getNumChildren() != 2)
1343         continue;  // Not a set of a single value (not handled so far)
1344
1345       SrcPattern = Pattern->getChild(1)->clone();    
1346     } else{
1347       // Not a set (store or something?)
1348       SrcPattern = Pattern;
1349     }
1350     
1351     std::string Reason;
1352     if (!SrcPattern->canPatternMatch(Reason, *this))
1353       I->error("Instruction can never match: " + Reason);
1354     
1355     Record *Instr = II->first;
1356     TreePatternNode *DstPattern = TheInst.getResultPattern();
1357     PatternsToMatch.
1358       push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1359                                SrcPattern, DstPattern));
1360   }
1361 }
1362
1363 void DAGISelEmitter::ParsePatterns() {
1364   std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1365
1366   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1367     DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1368     TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1369
1370     // Inline pattern fragments into it.
1371     Pattern->InlinePatternFragments();
1372     
1373     // Infer as many types as possible.  If we cannot infer all of them, we can
1374     // never do anything with this pattern: report it to the user.
1375     if (!Pattern->InferAllTypes())
1376       Pattern->error("Could not infer all types in pattern!");
1377
1378     // Validate that the input pattern is correct.
1379     {
1380       std::map<std::string, TreePatternNode*> InstInputs;
1381       std::map<std::string, Record*> InstResults;
1382       std::vector<Record*> InstImpInputs;
1383       std::vector<Record*> InstImpResults;
1384       FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1385                                   InstInputs, InstResults,
1386                                   InstImpInputs, InstImpResults);
1387     }
1388     
1389     ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1390     if (LI->getSize() == 0) continue;  // no pattern.
1391     
1392     // Parse the instruction.
1393     TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1394     
1395     // Inline pattern fragments into it.
1396     Result->InlinePatternFragments();
1397     
1398     // Infer as many types as possible.  If we cannot infer all of them, we can
1399     // never do anything with this pattern: report it to the user.
1400     if (!Result->InferAllTypes())
1401       Result->error("Could not infer all types in pattern result!");
1402    
1403     if (Result->getNumTrees() != 1)
1404       Result->error("Cannot handle instructions producing instructions "
1405                     "with temporaries yet!");
1406
1407     std::string Reason;
1408     if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1409       Pattern->error("Pattern can never match: " + Reason);
1410     
1411     PatternsToMatch.
1412       push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1413                                Pattern->getOnlyTree(),
1414                                Result->getOnlyTree()));
1415   }
1416 }
1417
1418 /// CombineChildVariants - Given a bunch of permutations of each child of the
1419 /// 'operator' node, put them together in all possible ways.
1420 static void CombineChildVariants(TreePatternNode *Orig, 
1421                const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1422                                  std::vector<TreePatternNode*> &OutVariants,
1423                                  DAGISelEmitter &ISE) {
1424   // Make sure that each operand has at least one variant to choose from.
1425   for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1426     if (ChildVariants[i].empty())
1427       return;
1428         
1429   // The end result is an all-pairs construction of the resultant pattern.
1430   std::vector<unsigned> Idxs;
1431   Idxs.resize(ChildVariants.size());
1432   bool NotDone = true;
1433   while (NotDone) {
1434     // Create the variant and add it to the output list.
1435     std::vector<TreePatternNode*> NewChildren;
1436     for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1437       NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1438     TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1439     
1440     // Copy over properties.
1441     R->setName(Orig->getName());
1442     R->setPredicateFn(Orig->getPredicateFn());
1443     R->setTransformFn(Orig->getTransformFn());
1444     R->setTypes(Orig->getExtTypes());
1445     
1446     // If this pattern cannot every match, do not include it as a variant.
1447     std::string ErrString;
1448     if (!R->canPatternMatch(ErrString, ISE)) {
1449       delete R;
1450     } else {
1451       bool AlreadyExists = false;
1452       
1453       // Scan to see if this pattern has already been emitted.  We can get
1454       // duplication due to things like commuting:
1455       //   (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1456       // which are the same pattern.  Ignore the dups.
1457       for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1458         if (R->isIsomorphicTo(OutVariants[i])) {
1459           AlreadyExists = true;
1460           break;
1461         }
1462       
1463       if (AlreadyExists)
1464         delete R;
1465       else
1466         OutVariants.push_back(R);
1467     }
1468     
1469     // Increment indices to the next permutation.
1470     NotDone = false;
1471     // Look for something we can increment without causing a wrap-around.
1472     for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1473       if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1474         NotDone = true;   // Found something to increment.
1475         break;
1476       }
1477       Idxs[IdxsIdx] = 0;
1478     }
1479   }
1480 }
1481
1482 /// CombineChildVariants - A helper function for binary operators.
1483 ///
1484 static void CombineChildVariants(TreePatternNode *Orig, 
1485                                  const std::vector<TreePatternNode*> &LHS,
1486                                  const std::vector<TreePatternNode*> &RHS,
1487                                  std::vector<TreePatternNode*> &OutVariants,
1488                                  DAGISelEmitter &ISE) {
1489   std::vector<std::vector<TreePatternNode*> > ChildVariants;
1490   ChildVariants.push_back(LHS);
1491   ChildVariants.push_back(RHS);
1492   CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1493 }  
1494
1495
1496 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1497                                      std::vector<TreePatternNode *> &Children) {
1498   assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1499   Record *Operator = N->getOperator();
1500   
1501   // Only permit raw nodes.
1502   if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1503       N->getTransformFn()) {
1504     Children.push_back(N);
1505     return;
1506   }
1507
1508   if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1509     Children.push_back(N->getChild(0));
1510   else
1511     GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1512
1513   if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1514     Children.push_back(N->getChild(1));
1515   else
1516     GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1517 }
1518
1519 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1520 /// the (potentially recursive) pattern by using algebraic laws.
1521 ///
1522 static void GenerateVariantsOf(TreePatternNode *N,
1523                                std::vector<TreePatternNode*> &OutVariants,
1524                                DAGISelEmitter &ISE) {
1525   // We cannot permute leaves.
1526   if (N->isLeaf()) {
1527     OutVariants.push_back(N);
1528     return;
1529   }
1530
1531   // Look up interesting info about the node.
1532   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1533
1534   // If this node is associative, reassociate.
1535   if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1536     // Reassociate by pulling together all of the linked operators 
1537     std::vector<TreePatternNode*> MaximalChildren;
1538     GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1539
1540     // Only handle child sizes of 3.  Otherwise we'll end up trying too many
1541     // permutations.
1542     if (MaximalChildren.size() == 3) {
1543       // Find the variants of all of our maximal children.
1544       std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1545       GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1546       GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1547       GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1548       
1549       // There are only two ways we can permute the tree:
1550       //   (A op B) op C    and    A op (B op C)
1551       // Within these forms, we can also permute A/B/C.
1552       
1553       // Generate legal pair permutations of A/B/C.
1554       std::vector<TreePatternNode*> ABVariants;
1555       std::vector<TreePatternNode*> BAVariants;
1556       std::vector<TreePatternNode*> ACVariants;
1557       std::vector<TreePatternNode*> CAVariants;
1558       std::vector<TreePatternNode*> BCVariants;
1559       std::vector<TreePatternNode*> CBVariants;
1560       CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1561       CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1562       CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1563       CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1564       CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1565       CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1566
1567       // Combine those into the result: (x op x) op x
1568       CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1569       CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1570       CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1571       CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1572       CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1573       CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1574
1575       // Combine those into the result: x op (x op x)
1576       CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1577       CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1578       CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1579       CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1580       CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1581       CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1582       return;
1583     }
1584   }
1585   
1586   // Compute permutations of all children.
1587   std::vector<std::vector<TreePatternNode*> > ChildVariants;
1588   ChildVariants.resize(N->getNumChildren());
1589   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1590     GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1591
1592   // Build all permutations based on how the children were formed.
1593   CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1594
1595   // If this node is commutative, consider the commuted order.
1596   if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1597     assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1598     // Consider the commuted order.
1599     CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1600                          OutVariants, ISE);
1601   }
1602 }
1603
1604
1605 // GenerateVariants - Generate variants.  For example, commutative patterns can
1606 // match multiple ways.  Add them to PatternsToMatch as well.
1607 void DAGISelEmitter::GenerateVariants() {
1608   
1609   DEBUG(std::cerr << "Generating instruction variants.\n");
1610   
1611   // Loop over all of the patterns we've collected, checking to see if we can
1612   // generate variants of the instruction, through the exploitation of
1613   // identities.  This permits the target to provide agressive matching without
1614   // the .td file having to contain tons of variants of instructions.
1615   //
1616   // Note that this loop adds new patterns to the PatternsToMatch list, but we
1617   // intentionally do not reconsider these.  Any variants of added patterns have
1618   // already been added.
1619   //
1620   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1621     std::vector<TreePatternNode*> Variants;
1622     GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
1623
1624     assert(!Variants.empty() && "Must create at least original variant!");
1625     Variants.erase(Variants.begin());  // Remove the original pattern.
1626
1627     if (Variants.empty())  // No variants for this pattern.
1628       continue;
1629
1630     DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1631           PatternsToMatch[i].getSrcPattern()->dump();
1632           std::cerr << "\n");
1633
1634     for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1635       TreePatternNode *Variant = Variants[v];
1636
1637       DEBUG(std::cerr << "  VAR#" << v <<  ": ";
1638             Variant->dump();
1639             std::cerr << "\n");
1640       
1641       // Scan to see if an instruction or explicit pattern already matches this.
1642       bool AlreadyExists = false;
1643       for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1644         // Check to see if this variant already exists.
1645         if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
1646           DEBUG(std::cerr << "  *** ALREADY EXISTS, ignoring variant.\n");
1647           AlreadyExists = true;
1648           break;
1649         }
1650       }
1651       // If we already have it, ignore the variant.
1652       if (AlreadyExists) continue;
1653
1654       // Otherwise, add it to the list of patterns we have.
1655       PatternsToMatch.
1656         push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1657                                  Variant, PatternsToMatch[i].getDstPattern()));
1658     }
1659
1660     DEBUG(std::cerr << "\n");
1661   }
1662 }
1663
1664
1665 // NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1666 // ComplexPattern.
1667 static bool NodeIsComplexPattern(TreePatternNode *N)
1668 {
1669   return (N->isLeaf() &&
1670           dynamic_cast<DefInit*>(N->getLeafValue()) &&
1671           static_cast<DefInit*>(N->getLeafValue())->getDef()->
1672           isSubClassOf("ComplexPattern"));
1673 }
1674
1675 // NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1676 // is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1677 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1678                                                    DAGISelEmitter &ISE)
1679 {
1680   if (N->isLeaf() &&
1681       dynamic_cast<DefInit*>(N->getLeafValue()) &&
1682       static_cast<DefInit*>(N->getLeafValue())->getDef()->
1683       isSubClassOf("ComplexPattern")) {
1684     return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1685                                   ->getDef());
1686   }
1687   return NULL;
1688 }
1689
1690 /// getPatternSize - Return the 'size' of this pattern.  We want to match large
1691 /// patterns before small ones.  This is used to determine the size of a
1692 /// pattern.
1693 static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
1694   unsigned Size = 2;  // The node itself.
1695
1696   // FIXME: This is a hack to statically increase the priority of patterns
1697   // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1698   // Later we can allow complexity / cost for each pattern to be (optionally)
1699   // specified. To get best possible pattern match we'll need to dynamically
1700   // calculate the complexity of all patterns a dag can potentially map to.
1701   const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1702   if (AM)
1703     Size += AM->getNumOperands();
1704     
1705   // Count children in the count if they are also nodes.
1706   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1707     TreePatternNode *Child = P->getChild(i);
1708     if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
1709       Size += getPatternSize(Child, ISE);
1710     else if (Child->isLeaf()) {
1711       Size += getPatternSize(Child, ISE);
1712       if (dynamic_cast<IntInit*>(Child->getLeafValue())) 
1713         // Matches a ConstantSDNode. More specific to any immediate.
1714         ++Size;
1715     }
1716   }
1717   
1718   return Size;
1719 }
1720
1721 /// getResultPatternCost - Compute the number of instructions for this pattern.
1722 /// This is a temporary hack.  We should really include the instruction
1723 /// latencies in this calculation.
1724 static unsigned getResultPatternCost(TreePatternNode *P) {
1725   if (P->isLeaf()) return 0;
1726   
1727   unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1728   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1729     Cost += getResultPatternCost(P->getChild(i));
1730   return Cost;
1731 }
1732
1733 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1734 // In particular, we want to match maximal patterns first and lowest cost within
1735 // a particular complexity first.
1736 struct PatternSortingPredicate {
1737   PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1738   DAGISelEmitter &ISE;
1739
1740   bool operator()(PatternToMatch *LHS,
1741                   PatternToMatch *RHS) {
1742     unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1743     unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
1744     if (LHSSize > RHSSize) return true;   // LHS -> bigger -> less cost
1745     if (LHSSize < RHSSize) return false;
1746     
1747     // If the patterns have equal complexity, compare generated instruction cost
1748     return getResultPatternCost(LHS->getDstPattern()) <
1749       getResultPatternCost(RHS->getDstPattern());
1750   }
1751 };
1752
1753 /// getRegisterValueType - Look up and return the first ValueType of specified 
1754 /// RegisterClass record
1755 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
1756   if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1757     return RC->getValueTypeNum(0);
1758   return MVT::Other;
1759 }
1760
1761
1762 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1763 /// type information from it.
1764 static void RemoveAllTypes(TreePatternNode *N) {
1765   N->removeTypes();
1766   if (!N->isLeaf())
1767     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1768       RemoveAllTypes(N->getChild(i));
1769 }
1770
1771 Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1772   Record *N = Records.getDef(Name);
1773   assert(N && N->isSubClassOf("SDNode") && "Bad argument");
1774   return N;
1775 }
1776
1777 /// NodeHasChain - return true if TreePatternNode has the property
1778 /// 'hasChain', meaning it reads a ctrl-flow chain operand and writes
1779 /// a chain result.
1780 static bool NodeHasChain(TreePatternNode *N, DAGISelEmitter &ISE)
1781 {
1782   if (N->isLeaf()) return false;
1783   Record *Operator = N->getOperator();
1784   if (!Operator->isSubClassOf("SDNode")) return false;
1785
1786   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
1787   return NodeInfo.hasProperty(SDNodeInfo::SDNPHasChain);
1788 }
1789
1790 static bool PatternHasCtrlDep(TreePatternNode *N, DAGISelEmitter &ISE)
1791 {
1792   if (NodeHasChain(N, ISE))
1793     return true;
1794   else {
1795     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1796       TreePatternNode *Child = N->getChild(i);
1797       if (PatternHasCtrlDep(Child, ISE))
1798         return true;
1799     }
1800   }
1801
1802   return false;
1803 }
1804
1805 class PatternCodeEmitter {
1806 private:
1807   DAGISelEmitter &ISE;
1808
1809   // Predicates.
1810   ListInit *Predicates;
1811   // Instruction selector pattern.
1812   TreePatternNode *Pattern;
1813   // Matched instruction.
1814   TreePatternNode *Instruction;
1815   unsigned PatternNo;
1816   std::ostream &OS;
1817   // Node to name mapping
1818   std::map<std::string,std::string> VariableMap;
1819   // Names of all the folded nodes which produce chains.
1820   std::vector<std::pair<std::string, unsigned> > FoldedChains;
1821   unsigned TmpNo;
1822
1823 public:
1824   PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
1825                      TreePatternNode *pattern, TreePatternNode *instr,
1826                      unsigned PatNum, std::ostream &os) :
1827     ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
1828     PatternNo(PatNum), OS(os), TmpNo(0) {}
1829
1830   /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
1831   /// if the match fails. At this point, we already know that the opcode for N
1832   /// matches, and the SDNode for the result has the RootName specified name.
1833   void EmitMatchCode(TreePatternNode *N, const std::string &RootName,
1834                      bool &FoundChain, bool isRoot = false) {
1835
1836     // Emit instruction predicates. Each predicate is just a string for now.
1837     if (isRoot) {
1838       for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
1839         if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
1840           Record *Def = Pred->getDef();
1841           if (Def->isSubClassOf("Predicate")) {
1842             if (i == 0)
1843               OS << "      if (";
1844             else
1845               OS << " && ";
1846             OS << "!(" << Def->getValueAsString("CondString") << ")";
1847             if (i == e-1)
1848               OS << ") goto P" << PatternNo << "Fail;\n";
1849           } else {
1850             Def->dump();
1851             assert(0 && "Unknown predicate type!");
1852           }
1853         }
1854       }
1855     }
1856
1857     if (N->isLeaf()) {
1858       if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1859         OS << "      if (cast<ConstantSDNode>(" << RootName
1860            << ")->getSignExtended() != " << II->getValue() << ")\n"
1861            << "        goto P" << PatternNo << "Fail;\n";
1862         return;
1863       } else if (!NodeIsComplexPattern(N)) {
1864         assert(0 && "Cannot match this as a leaf value!");
1865         abort();
1866       }
1867     }
1868   
1869     // If this node has a name associated with it, capture it in VariableMap.  If
1870     // we already saw this in the pattern, emit code to verify dagness.
1871     if (!N->getName().empty()) {
1872       std::string &VarMapEntry = VariableMap[N->getName()];
1873       if (VarMapEntry.empty()) {
1874         VarMapEntry = RootName;
1875       } else {
1876         // If we get here, this is a second reference to a specific name.  Since
1877         // we already have checked that the first reference is valid, we don't
1878         // have to recursively match it, just check that it's the same as the
1879         // previously named thing.
1880         OS << "      if (" << VarMapEntry << " != " << RootName
1881            << ") goto P" << PatternNo << "Fail;\n";
1882         return;
1883       }
1884     }
1885
1886
1887     // Emit code to load the child nodes and match their contents recursively.
1888     unsigned OpNo = 0;
1889     bool HasChain = NodeHasChain(N, ISE);
1890     if (HasChain) {
1891       OpNo = 1;
1892       if (!isRoot) {
1893         const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
1894         OS << "      if (!" << RootName << ".hasOneUse()) goto P"
1895            << PatternNo << "Fail;   // Multiple uses of actual result?\n";
1896         OS << "      if (CodeGenMap.count(" << RootName
1897            << ".getValue(" << CInfo.getNumResults() << "))) goto P"
1898            << PatternNo << "Fail;   // Already selected for a chain use?\n";
1899       }
1900       if (!FoundChain) {
1901         OS << "      SDOperand Chain = " << RootName << ".getOperand(0);\n";
1902         FoundChain = true;
1903       }
1904     }
1905
1906     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1907       OS << "      SDOperand " << RootName << OpNo << " = "
1908          << RootName << ".getOperand(" << OpNo << ");\n";
1909       TreePatternNode *Child = N->getChild(i);
1910     
1911       if (!Child->isLeaf()) {
1912         // If it's not a leaf, recursively match.
1913         const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
1914         OS << "      if (" << RootName << OpNo << ".getOpcode() != "
1915            << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
1916         EmitMatchCode(Child, RootName + utostr(OpNo), FoundChain);
1917         if (NodeHasChain(Child, ISE)) {
1918           FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
1919                                                 CInfo.getNumResults()));
1920         }
1921       } else {
1922         // If this child has a name associated with it, capture it in VarMap.  If
1923         // we already saw this in the pattern, emit code to verify dagness.
1924         if (!Child->getName().empty()) {
1925           std::string &VarMapEntry = VariableMap[Child->getName()];
1926           if (VarMapEntry.empty()) {
1927             VarMapEntry = RootName + utostr(OpNo);
1928           } else {
1929             // If we get here, this is a second reference to a specific name.  Since
1930             // we already have checked that the first reference is valid, we don't
1931             // have to recursively match it, just check that it's the same as the
1932             // previously named thing.
1933             OS << "      if (" << VarMapEntry << " != " << RootName << OpNo
1934                << ") goto P" << PatternNo << "Fail;\n";
1935             continue;
1936           }
1937         }
1938       
1939         // Handle leaves of various types.
1940         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1941           Record *LeafRec = DI->getDef();
1942           if (LeafRec->isSubClassOf("RegisterClass")) {
1943             // Handle register references.  Nothing to do here.
1944           } else if (LeafRec->isSubClassOf("Register")) {
1945             // Handle register references.
1946           } else if (LeafRec->isSubClassOf("ComplexPattern")) {
1947             // Handle complex pattern. Nothing to do here.
1948           } else if (LeafRec->getName() == "srcvalue") {
1949             // Place holder for SRCVALUE nodes. Nothing to do here.
1950           } else if (LeafRec->isSubClassOf("ValueType")) {
1951             // Make sure this is the specified value type.
1952             OS << "      if (cast<VTSDNode>(" << RootName << OpNo << ")->getVT() != "
1953                << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1954                << "Fail;\n";
1955           } else if (LeafRec->isSubClassOf("CondCode")) {
1956             // Make sure this is the specified cond code.
1957             OS << "      if (cast<CondCodeSDNode>(" << RootName << OpNo
1958                << ")->get() != " << "ISD::" << LeafRec->getName()
1959                << ") goto P" << PatternNo << "Fail;\n";
1960           } else {
1961             Child->dump();
1962             std::cerr << " ";
1963             assert(0 && "Unknown leaf type!");
1964           }
1965         } else if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
1966           OS << "      if (!isa<ConstantSDNode>(" << RootName << OpNo << ") ||\n"
1967              << "          cast<ConstantSDNode>(" << RootName << OpNo
1968              << ")->getSignExtended() != " << II->getValue() << ")\n"
1969              << "        goto P" << PatternNo << "Fail;\n";
1970         } else {
1971           Child->dump();
1972           assert(0 && "Unknown leaf type!");
1973         }
1974       }
1975     }
1976
1977     // If there is a node predicate for this, emit the call.
1978     if (!N->getPredicateFn().empty())
1979       OS << "      if (!" << N->getPredicateFn() << "(" << RootName
1980          << ".Val)) goto P" << PatternNo << "Fail;\n";
1981   }
1982
1983   /// EmitResultCode - Emit the action for a pattern.  Now that it has matched
1984   /// we actually have to build a DAG!
1985   std::pair<unsigned, unsigned>
1986   EmitResultCode(TreePatternNode *N, bool isRoot = false) {
1987     // This is something selected from the pattern we matched.
1988     if (!N->getName().empty()) {
1989       assert(!isRoot && "Root of pattern cannot be a leaf!");
1990       std::string &Val = VariableMap[N->getName()];
1991       assert(!Val.empty() &&
1992              "Variable referenced but not defined and not caught earlier!");
1993       if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1994         // Already selected this operand, just return the tmpval.
1995         return std::make_pair(1, atoi(Val.c_str()+3));
1996       }
1997
1998       const ComplexPattern *CP;
1999       unsigned ResNo = TmpNo++;
2000       unsigned NumRes = 1;
2001       if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
2002         assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2003         switch (N->getTypeNum(0)) {
2004           default: assert(0 && "Unknown type for constant node!");
2005           case MVT::i1:  OS << "      bool Tmp"; break;
2006           case MVT::i8:  OS << "      unsigned char Tmp"; break;
2007           case MVT::i16: OS << "      unsigned short Tmp"; break;
2008           case MVT::i32: OS << "      unsigned Tmp"; break;
2009           case MVT::i64: OS << "      uint64_t Tmp"; break;
2010         }
2011         OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
2012         OS << "      SDOperand Tmp" << utostr(ResNo)
2013            << " = CurDAG->getTargetConstant(Tmp"
2014            << ResNo << "C, MVT::" << getEnumName(N->getTypeNum(0)) << ");\n";
2015       } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
2016         OS << "      SDOperand Tmp" << ResNo << " = " << Val << ";\n";
2017       } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
2018         OS << "      SDOperand Tmp" << ResNo << " = " << Val << ";\n";
2019       } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2020         OS << "      SDOperand Tmp" << ResNo << " = " << Val << ";\n";
2021       } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2022         std::string Fn = CP->getSelectFunc();
2023         NumRes = CP->getNumOperands();
2024         OS << "      SDOperand ";
2025         for (unsigned i = 0; i < NumRes - 1; ++i)
2026           OS << "Tmp" << (i+ResNo) << ",";
2027         OS << "Tmp" << (NumRes - 1 + ResNo) << ";\n";
2028         
2029         OS << "      if (!" << Fn << "(" << Val;
2030         for (unsigned i = 0; i < NumRes; i++)
2031           OS << ", Tmp" << i + ResNo;
2032         OS << ")) goto P" << PatternNo << "Fail;\n";
2033         TmpNo = ResNo + NumRes;
2034       } else {
2035         OS << "      SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
2036       }
2037       // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2038       // value if used multiple times by this pattern result.
2039       Val = "Tmp"+utostr(ResNo);
2040       return std::make_pair(NumRes, ResNo);
2041     }
2042   
2043     if (N->isLeaf()) {
2044       // If this is an explicit register reference, handle it.
2045       if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2046         unsigned ResNo = TmpNo++;
2047         if (DI->getDef()->isSubClassOf("Register")) {
2048           OS << "      SDOperand Tmp" << ResNo << " = CurDAG->getRegister("
2049              << ISE.getQualifiedName(DI->getDef()) << ", MVT::"
2050              << getEnumName(N->getTypeNum(0))
2051              << ");\n";
2052           return std::make_pair(1, ResNo);
2053         }
2054       } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2055         unsigned ResNo = TmpNo++;
2056         assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2057         OS << "      SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant("
2058            << II->getValue() << ", MVT::"
2059            << getEnumName(N->getTypeNum(0))
2060            << ");\n";
2061         return std::make_pair(1, ResNo);
2062       }
2063     
2064       N->dump();
2065       assert(0 && "Unknown leaf type!");
2066       return std::make_pair(1, ~0U);
2067     }
2068
2069     Record *Op = N->getOperator();
2070     if (Op->isSubClassOf("Instruction")) {
2071       const CodeGenTarget &CGT = ISE.getTargetInfo();
2072       CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2073       const DAGInstruction &Inst = ISE.getInstruction(Op);
2074       bool HasImpInputs  = Inst.getNumImpOperands() > 0;
2075       bool HasImpResults = Inst.getNumImpResults() > 0;
2076       bool HasInFlag  = II.hasInFlag  || HasImpInputs;
2077       bool HasOutFlag = II.hasOutFlag || HasImpResults;
2078       bool HasChain   = II.hasCtrlDep;
2079
2080       if (isRoot && PatternHasCtrlDep(Pattern, ISE))
2081         HasChain = true;
2082       if (HasInFlag || HasOutFlag)
2083         OS << "      SDOperand InFlag = SDOperand(0, 0);\n";
2084
2085       // Determine operand emission order. Complex pattern first.
2086       std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2087       std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2088       for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2089         TreePatternNode *Child = N->getChild(i);
2090         if (i == 0) {
2091           EmitOrder.push_back(std::make_pair(i, Child));
2092           OI = EmitOrder.begin();
2093         } else if (NodeIsComplexPattern(Child)) {
2094           OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2095         } else {
2096           EmitOrder.push_back(std::make_pair(i, Child));
2097         }
2098       }
2099
2100       // Emit all of the operands.
2101       std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2102       for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2103         unsigned OpOrder       = EmitOrder[i].first;
2104         TreePatternNode *Child = EmitOrder[i].second;
2105         std::pair<unsigned, unsigned> NumTemp =  EmitResultCode(Child);
2106         NumTemps[OpOrder] = NumTemp;
2107       }
2108
2109       // List all the operands in the right order.
2110       std::vector<unsigned> Ops;
2111       for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2112         for (unsigned j = 0; j < NumTemps[i].first; j++)
2113           Ops.push_back(NumTemps[i].second + j);
2114       }
2115
2116       // Emit all the chain and CopyToReg stuff.
2117       if (HasChain)
2118         OS << "      Chain = Select(Chain);\n";
2119       if (HasInFlag)
2120         EmitInFlags(Pattern, "N", HasChain, II.hasInFlag, true);
2121
2122       unsigned NumResults = Inst.getNumResults();    
2123       unsigned ResNo = TmpNo++;
2124       if (!isRoot) {
2125         OS << "      SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
2126            << II.Namespace << "::" << II.TheDef->getName();
2127         if (N->getTypeNum(0) != MVT::isVoid)
2128           OS << ", MVT::" << getEnumName(N->getTypeNum(0));
2129         if (HasOutFlag)
2130           OS << ", MVT::Flag";
2131
2132         unsigned LastOp = 0;
2133         for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2134           LastOp = Ops[i];
2135           OS << ", Tmp" << LastOp;
2136         }
2137         OS << ");\n";
2138         if (HasChain) {
2139           // Must have at least one result
2140           OS << "      Chain = Tmp" << LastOp << ".getValue("
2141              << NumResults << ");\n";
2142         }
2143       } else if (HasChain || HasOutFlag) {
2144         OS << "      SDOperand Result = CurDAG->getTargetNode("
2145            << II.Namespace << "::" << II.TheDef->getName();
2146
2147         // Output order: results, chain, flags
2148         // Result types.
2149         if (NumResults > 0) { 
2150           if (N->getTypeNum(0) != MVT::isVoid)
2151             OS << ", MVT::" << getEnumName(N->getTypeNum(0));
2152         }
2153         if (HasChain)
2154           OS << ", MVT::Other";
2155         if (HasOutFlag)
2156           OS << ", MVT::Flag";
2157
2158         // Inputs.
2159         for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2160           OS << ", Tmp" << Ops[i];
2161         if (HasChain)  OS << ", Chain";
2162         if (HasInFlag) OS << ", InFlag";
2163         OS << ");\n";
2164
2165         unsigned ValNo = 0;
2166         for (unsigned i = 0; i < NumResults; i++) {
2167           OS << "      CodeGenMap[N.getValue(" << ValNo << ")] = Result"
2168              << ".getValue(" << ValNo << ");\n";
2169           ValNo++;
2170         }
2171
2172         if (HasChain)
2173           OS << "      Chain = Result.getValue(" << ValNo << ");\n";
2174
2175         if (HasOutFlag)
2176           OS << "      InFlag = Result.getValue("
2177              << ValNo + (unsigned)HasChain << ");\n";
2178
2179         if (HasImpResults) {
2180           if (EmitCopyFromRegs(N, HasChain)) {
2181             OS << "      CodeGenMap[N.getValue(" << ValNo << ")] = "
2182                << "Result.getValue(" << ValNo << ");\n";
2183             ValNo++;
2184             HasChain = true;
2185           }
2186         }
2187
2188         // User does not expect that the instruction produces a chain!
2189         bool AddedChain = HasChain && !NodeHasChain(Pattern, ISE);
2190         if (NodeHasChain(Pattern, ISE))
2191           OS << "      CodeGenMap[N.getValue(" << ValNo++  << ")] = Chain;\n";
2192
2193         if (FoldedChains.size() > 0) {
2194           OS << "      ";
2195           for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
2196             OS << "CodeGenMap[" << FoldedChains[j].first << ".getValue("
2197                << FoldedChains[j].second << ")] = ";
2198           OS << "Chain;\n";
2199         }
2200
2201         if (HasOutFlag)
2202           OS << "      CodeGenMap[N.getValue(" << ValNo << ")] = InFlag;\n";
2203
2204         if (AddedChain && HasOutFlag) {
2205           if (NumResults == 0) {
2206             OS << "      return Result.getValue(N.ResNo+1);\n";
2207           } else {
2208             OS << "      if (N.ResNo < " << NumResults << ")\n";
2209             OS << "        return Result.getValue(N.ResNo);\n";
2210             OS << "      else\n";
2211             OS << "        return Result.getValue(N.ResNo+1);\n";
2212           }
2213         } else {
2214           OS << "      return Result.getValue(N.ResNo);\n";
2215         }
2216       } else {
2217         // If this instruction is the root, and if there is only one use of it,
2218         // use SelectNodeTo instead of getTargetNode to avoid an allocation.
2219         OS << "      if (N.Val->hasOneUse()) {\n";
2220         OS << "        return CurDAG->SelectNodeTo(N.Val, "
2221            << II.Namespace << "::" << II.TheDef->getName();
2222         if (N->getTypeNum(0) != MVT::isVoid)
2223           OS << ", MVT::" << getEnumName(N->getTypeNum(0));
2224         if (HasOutFlag)
2225           OS << ", MVT::Flag";
2226         for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2227           OS << ", Tmp" << Ops[i];
2228         if (HasInFlag)
2229           OS << ", InFlag";
2230         OS << ");\n";
2231         OS << "      } else {\n";
2232         OS << "        return CodeGenMap[N] = CurDAG->getTargetNode("
2233            << II.Namespace << "::" << II.TheDef->getName();
2234         if (N->getTypeNum(0) != MVT::isVoid)
2235           OS << ", MVT::" << getEnumName(N->getTypeNum(0));
2236         if (HasOutFlag)
2237           OS << ", MVT::Flag";
2238         for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2239           OS << ", Tmp" << Ops[i];
2240         if (HasInFlag)
2241           OS << ", InFlag";
2242         OS << ");\n";
2243         OS << "      }\n";
2244       }
2245
2246       return std::make_pair(1, ResNo);
2247     } else if (Op->isSubClassOf("SDNodeXForm")) {
2248       assert(N->getNumChildren() == 1 && "node xform should have one child!");
2249       unsigned OpVal = EmitResultCode(N->getChild(0)).second;
2250       unsigned ResNo = TmpNo++;
2251       OS << "      SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
2252          << "(Tmp" << OpVal << ".Val);\n";
2253       if (isRoot) {
2254         OS << "      CodeGenMap[N] = Tmp" << ResNo << ";\n";
2255         OS << "      return Tmp" << ResNo << ";\n";
2256       }
2257       return std::make_pair(1, ResNo);
2258     } else {
2259       N->dump();
2260       assert(0 && "Unknown node in result pattern!");
2261       return std::make_pair(1, ~0U);
2262     }
2263   }
2264
2265   /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
2266   /// add it to the tree.  'Pat' and 'Other' are isomorphic trees except that 
2267   /// 'Pat' may be missing types.  If we find an unresolved type to add a check
2268   /// for, this returns true otherwise false if Pat has all types.
2269   bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2270                           const std::string &Prefix) {
2271     // Did we find one?
2272     if (!Pat->hasTypeSet()) {
2273       // Move a type over from 'other' to 'pat'.
2274       Pat->setTypes(Other->getExtTypes());
2275       OS << "      if (" << Prefix << ".Val->getValueType(0) != MVT::"
2276          << getName(Pat->getTypeNum(0)) << ") goto P" << PatternNo << "Fail;\n";
2277       return true;
2278     }
2279   
2280     unsigned OpNo = (unsigned) NodeHasChain(Pat, ISE);
2281     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2282       if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2283                              Prefix + utostr(OpNo)))
2284         return true;
2285     return false;
2286   }
2287
2288 private:
2289   /// EmitInFlags - Emit the flag operands for the DAG that is
2290   /// being built.
2291   void EmitInFlags(TreePatternNode *N, const std::string &RootName,
2292                    bool HasChain, bool HasInFlag, bool isRoot = false) {
2293     const CodeGenTarget &T = ISE.getTargetInfo();
2294     unsigned OpNo = (unsigned) NodeHasChain(N, ISE);
2295     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2296       TreePatternNode *Child = N->getChild(i);
2297       if (!Child->isLeaf()) {
2298         EmitInFlags(Child, RootName + utostr(OpNo), HasChain, HasInFlag);
2299       } else {
2300         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2301           Record *RR = DI->getDef();
2302           if (RR->isSubClassOf("Register")) {
2303             MVT::ValueType RVT = getRegisterValueType(RR, T);
2304             if (RVT == MVT::Flag) {
2305               OS << "      InFlag = Select(" << RootName << OpNo << ");\n";
2306             } else if (HasChain) {
2307               OS << "      SDOperand " << RootName << "CR" << i << ";\n";
2308               OS << "      " << RootName << "CR" << i
2309                  << "  = CurDAG->getCopyToReg(Chain, CurDAG->getRegister("
2310                  << ISE.getQualifiedName(RR) << ", MVT::"
2311                  << getEnumName(RVT) << ")"
2312                  << ", Select(" << RootName << OpNo << "), InFlag);\n";
2313               OS << "      Chain  = " << RootName << "CR" << i
2314                  << ".getValue(0);\n";
2315               OS << "      InFlag = " << RootName << "CR" << i
2316                  << ".getValue(1);\n";
2317             } else {
2318               OS << "      InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode()"
2319                  << ", CurDAG->getRegister(" << ISE.getQualifiedName(RR)
2320                  << ", MVT::" << getEnumName(RVT) << ")"
2321                  << ", Select(" << RootName << OpNo
2322                  << "), InFlag).getValue(1);\n";
2323             }
2324           }
2325         }
2326       }
2327     }
2328
2329     if (isRoot && HasInFlag) {
2330       OS << "      SDOperand " << RootName << OpNo << " = " << RootName
2331          << ".getOperand(" << OpNo << ");\n";
2332       OS << "      InFlag = Select(" << RootName << OpNo << ");\n";
2333     }
2334   }
2335
2336   /// EmitCopyFromRegs - Emit code to copy result to physical registers
2337   /// as specified by the instruction. It returns true if any copy is
2338   /// emitted.
2339   bool EmitCopyFromRegs(TreePatternNode *N, bool HasChain) {
2340     bool RetVal = false;
2341     Record *Op = N->getOperator();
2342     if (Op->isSubClassOf("Instruction")) {
2343       const DAGInstruction &Inst = ISE.getInstruction(Op);
2344       const CodeGenTarget &CGT = ISE.getTargetInfo();
2345       CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2346       unsigned NumImpResults  = Inst.getNumImpResults();
2347       for (unsigned i = 0; i < NumImpResults; i++) {
2348         Record *RR = Inst.getImpResult(i);
2349         if (RR->isSubClassOf("Register")) {
2350           MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2351           if (RVT != MVT::Flag) {
2352             if (HasChain) {
2353               OS << "      Result = CurDAG->getCopyFromReg(Chain, "
2354                  << ISE.getQualifiedName(RR)
2355                  << ", MVT::" << getEnumName(RVT) << ", InFlag);\n";
2356               OS << "      Chain  = Result.getValue(1);\n";
2357               OS << "      InFlag = Result.getValue(2);\n";
2358             } else {
2359               OS << "      Chain;\n";
2360               OS << "      Result = CurDAG->getCopyFromReg("
2361                  << "CurDAG->getEntryNode(), ISE.getQualifiedName(RR)"
2362                  << ", MVT::" << getEnumName(RVT) << ", InFlag);\n";
2363               OS << "      Chain  = Result.getValue(1);\n";
2364               OS << "      InFlag = Result.getValue(2);\n";
2365             }
2366             RetVal = true;
2367           }
2368         }
2369       }
2370     }
2371     return RetVal;
2372   }
2373 };
2374
2375 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2376 /// stream to match the pattern, and generate the code for the match if it
2377 /// succeeds.
2378 void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
2379                                         std::ostream &OS) {
2380   static unsigned PatternCount = 0;
2381   unsigned PatternNo = PatternCount++;
2382   OS << "    { // Pattern #" << PatternNo << ": ";
2383   Pattern.getSrcPattern()->print(OS);
2384   OS << "\n      // Emits: ";
2385   Pattern.getDstPattern()->print(OS);
2386   OS << "\n";
2387   OS << "      // Pattern complexity = "
2388      << getPatternSize(Pattern.getSrcPattern(), *this)
2389      << "  cost = "
2390      << getResultPatternCost(Pattern.getDstPattern()) << "\n";
2391
2392   PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2393                              Pattern.getSrcPattern(), Pattern.getDstPattern(),
2394                              PatternNo, OS);
2395
2396   // Emit the matcher, capturing named arguments in VariableMap.
2397   bool FoundChain = false;
2398   Emitter.EmitMatchCode(Pattern.getSrcPattern(), "N", FoundChain,
2399                         true /*the root*/);
2400
2401   // TP - Get *SOME* tree pattern, we don't care which.
2402   TreePattern &TP = *PatternFragments.begin()->second;
2403   
2404   // At this point, we know that we structurally match the pattern, but the
2405   // types of the nodes may not match.  Figure out the fewest number of type 
2406   // comparisons we need to emit.  For example, if there is only one integer
2407   // type supported by a target, there should be no type comparisons at all for
2408   // integer patterns!
2409   //
2410   // To figure out the fewest number of type checks needed, clone the pattern,
2411   // remove the types, then perform type inference on the pattern as a whole.
2412   // If there are unresolved types, emit an explicit check for those types,
2413   // apply the type to the tree, then rerun type inference.  Iterate until all
2414   // types are resolved.
2415   //
2416   TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
2417   RemoveAllTypes(Pat);
2418   
2419   do {
2420     // Resolve/propagate as many types as possible.
2421     try {
2422       bool MadeChange = true;
2423       while (MadeChange)
2424         MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
2425     } catch (...) {
2426       assert(0 && "Error: could not find consistent types for something we"
2427              " already decided was ok!");
2428       abort();
2429     }
2430
2431     // Insert a check for an unresolved type and add it to the tree.  If we find
2432     // an unresolved type to add a check for, this returns true and we iterate,
2433     // otherwise we are done.
2434   } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
2435
2436   Emitter.EmitResultCode(Pattern.getDstPattern(), true /*the root*/);
2437
2438   delete Pat;
2439   
2440   OS << "    }\n  P" << PatternNo << "Fail:\n";
2441 }
2442
2443
2444 namespace {
2445   /// CompareByRecordName - An ordering predicate that implements less-than by
2446   /// comparing the names records.
2447   struct CompareByRecordName {
2448     bool operator()(const Record *LHS, const Record *RHS) const {
2449       // Sort by name first.
2450       if (LHS->getName() < RHS->getName()) return true;
2451       // If both names are equal, sort by pointer.
2452       return LHS->getName() == RHS->getName() && LHS < RHS;
2453     }
2454   };
2455 }
2456
2457 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
2458   std::string InstNS = Target.inst_begin()->second.Namespace;
2459   if (!InstNS.empty()) InstNS += "::";
2460   
2461   // Group the patterns by their top-level opcodes.
2462   std::map<Record*, std::vector<PatternToMatch*>,
2463     CompareByRecordName> PatternsByOpcode;
2464   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2465     TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
2466     if (!Node->isLeaf()) {
2467       PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
2468     } else {
2469       const ComplexPattern *CP;
2470       if (IntInit *II = 
2471           dynamic_cast<IntInit*>(Node->getLeafValue())) {
2472         PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
2473       } else if ((CP = NodeGetComplexPattern(Node, *this))) {
2474         std::vector<Record*> OpNodes = CP->getRootNodes();
2475         for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
2476           PatternsByOpcode[OpNodes[j]].insert(PatternsByOpcode[OpNodes[j]].begin(),
2477                                               &PatternsToMatch[i]);
2478         }
2479       } else {
2480         std::cerr << "Unrecognized opcode '";
2481         Node->dump();
2482         std::cerr << "' on tree pattern '";
2483         std::cerr << PatternsToMatch[i].getDstPattern()->getOperator()->getName();
2484         std::cerr << "'!\n";
2485         exit(1);
2486       }
2487     }
2488   }
2489   
2490   // Emit one Select_* method for each top-level opcode.  We do this instead of
2491   // emitting one giant switch statement to support compilers where this will
2492   // result in the recursive functions taking less stack space.
2493   for (std::map<Record*, std::vector<PatternToMatch*>,
2494        CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2495        E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
2496     OS << "SDOperand Select_" << PBOI->first->getName() << "(SDOperand N) {\n";
2497     
2498     const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
2499     std::vector<PatternToMatch*> &Patterns = PBOI->second;
2500     
2501     // We want to emit all of the matching code now.  However, we want to emit
2502     // the matches in order of minimal cost.  Sort the patterns so the least
2503     // cost one is at the start.
2504     std::stable_sort(Patterns.begin(), Patterns.end(),
2505                      PatternSortingPredicate(*this));
2506     
2507     for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2508       EmitCodeForPattern(*Patterns[i], OS);
2509     
2510     OS << "  std::cerr << \"Cannot yet select: \";\n"
2511        << "  N.Val->dump(CurDAG);\n"
2512        << "  std::cerr << '\\n';\n"
2513        << "  abort();\n"
2514        << "}\n\n";
2515   }
2516   
2517   // Emit boilerplate.
2518   OS << "// The main instruction selector code.\n"
2519      << "SDOperand SelectCode(SDOperand N) {\n"
2520      << "  if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
2521      << "      N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
2522      << "INSTRUCTION_LIST_END))\n"
2523      << "    return N;   // Already selected.\n\n"
2524     << "  std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
2525      << "  if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
2526      << "  switch (N.getOpcode()) {\n"
2527      << "  default: break;\n"
2528      << "  case ISD::EntryToken:       // These leaves remain the same.\n"
2529      << "  case ISD::BasicBlock:\n"
2530      << "    return N;\n"
2531      << "  case ISD::AssertSext:\n"
2532      << "  case ISD::AssertZext: {\n"
2533      << "    SDOperand Tmp0 = Select(N.getOperand(0));\n"
2534      << "    if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
2535      << "    return Tmp0;\n"
2536      << "  }\n"
2537      << "  case ISD::TokenFactor:\n"
2538      << "    if (N.getNumOperands() == 2) {\n"
2539      << "      SDOperand Op0 = Select(N.getOperand(0));\n"
2540      << "      SDOperand Op1 = Select(N.getOperand(1));\n"
2541      << "      return CodeGenMap[N] =\n"
2542      << "          CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
2543      << "    } else {\n"
2544      << "      std::vector<SDOperand> Ops;\n"
2545      << "      for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
2546      << "        Ops.push_back(Select(N.getOperand(i)));\n"
2547      << "       return CodeGenMap[N] = \n"
2548      << "               CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
2549      << "    }\n"
2550      << "  case ISD::CopyFromReg: {\n"
2551      << "    SDOperand Chain = Select(N.getOperand(0));\n"
2552      << "    unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
2553      << "    MVT::ValueType VT = N.Val->getValueType(0);\n"
2554      << "    if (N.Val->getNumValues() == 2) {\n"
2555      << "      if (Chain == N.getOperand(0)) return N; // No change\n"
2556      << "      SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
2557      << "      CodeGenMap[N.getValue(0)] = New;\n"
2558      << "      CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2559      << "      return New.getValue(N.ResNo);\n"
2560      << "    } else {\n"
2561      << "      SDOperand Flag(0, 0);\n"
2562      << "      if (N.getNumOperands() == 3) Flag = Select(N.getOperand(2));\n"
2563      << "      if (Chain == N.getOperand(0) &&\n"
2564      << "          (N.getNumOperands() == 2 || Flag == N.getOperand(2)))\n"
2565      << "        return N; // No change\n"
2566      << "      SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
2567      << "      CodeGenMap[N.getValue(0)] = New;\n"
2568      << "      CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2569      << "      CodeGenMap[N.getValue(2)] = New.getValue(2);\n"
2570      << "      return New.getValue(N.ResNo);\n"
2571      << "    }\n"
2572      << "  }\n"
2573      << "  case ISD::CopyToReg: {\n"
2574      << "    SDOperand Chain = Select(N.getOperand(0));\n"
2575      << "    unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
2576      << "    SDOperand Val = Select(N.getOperand(2));\n"
2577      << "    SDOperand Result = N;\n"
2578      << "    if (N.Val->getNumValues() == 1) {\n"
2579      << "      if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
2580      << "        Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
2581      << "      return CodeGenMap[N] = Result;\n"
2582      << "    } else {\n"
2583      << "      SDOperand Flag(0, 0);\n"
2584      << "      if (N.getNumOperands() == 4) Flag = Select(N.getOperand(3));\n"
2585      << "      if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
2586      << "          (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
2587      << "        Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
2588      << "      CodeGenMap[N.getValue(0)] = Result;\n"
2589      << "      CodeGenMap[N.getValue(1)] = Result.getValue(1);\n"
2590      << "      return Result.getValue(N.ResNo);\n"
2591      << "    }\n"
2592      << "  }\n";
2593     
2594   // Loop over all of the case statements, emiting a call to each method we
2595   // emitted above.
2596   for (std::map<Record*, std::vector<PatternToMatch*>,
2597                 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2598        E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
2599     const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
2600     OS << "  case " << OpcodeInfo.getEnumName() << ": "
2601        << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
2602        << "return Select_" << PBOI->first->getName() << "(N);\n";
2603   }
2604
2605   OS << "  } // end of big switch.\n\n"
2606      << "  std::cerr << \"Cannot yet select: \";\n"
2607      << "  N.Val->dump(CurDAG);\n"
2608      << "  std::cerr << '\\n';\n"
2609      << "  abort();\n"
2610      << "}\n";
2611 }
2612
2613 void DAGISelEmitter::run(std::ostream &OS) {
2614   EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
2615                        " target", OS);
2616   
2617   OS << "// *** NOTE: This file is #included into the middle of the target\n"
2618      << "// *** instruction selector class.  These functions are really "
2619      << "methods.\n\n";
2620   
2621   OS << "// Instance var to keep track of multiply used nodes that have \n"
2622      << "// already been selected.\n"
2623      << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
2624   
2625   ParseNodeInfo();
2626   ParseNodeTransforms(OS);
2627   ParseComplexPatterns();
2628   ParsePatternFragments(OS);
2629   ParseInstructions();
2630   ParsePatterns();
2631   
2632   // Generate variants.  For example, commutative patterns can match
2633   // multiple ways.  Add them to PatternsToMatch as well.
2634   GenerateVariants();
2635
2636   
2637   DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
2638         for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2639           std::cerr << "PATTERN: ";  PatternsToMatch[i].getSrcPattern()->dump();
2640           std::cerr << "\nRESULT:  ";PatternsToMatch[i].getDstPattern()->dump();
2641           std::cerr << "\n";
2642         });
2643   
2644   // At this point, we have full information about the 'Patterns' we need to
2645   // parse, both implicitly from instructions as well as from explicit pattern
2646   // definitions.  Emit the resultant instruction selector.
2647   EmitInstructionSelector(OS);  
2648   
2649   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
2650        E = PatternFragments.end(); I != E; ++I)
2651     delete I->second;
2652   PatternFragments.clear();
2653
2654   Instructions.clear();
2655 }