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