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