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