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