hoist some funky logic into CodeGenInstruction
[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/ADT/STLExtras.h"
19 #include "llvm/Support/Debug.h"
20 #include <set>
21 #include <algorithm>
22 using namespace llvm;
23
24 //===----------------------------------------------------------------------===//
25 //  EEVT::TypeSet Implementation
26 //===----------------------------------------------------------------------===//
27
28 static inline bool isInteger(MVT::SimpleValueType VT) {
29   return EVT(VT).isInteger();
30 }
31 static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
32   return EVT(VT).isFloatingPoint();
33 }
34 static inline bool isVector(MVT::SimpleValueType VT) {
35   return EVT(VT).isVector();
36 }
37 static inline bool isScalar(MVT::SimpleValueType VT) {
38   return !EVT(VT).isVector();
39 }
40
41 EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
42   if (VT == MVT::iAny)
43     EnforceInteger(TP);
44   else if (VT == MVT::fAny)
45     EnforceFloatingPoint(TP);
46   else if (VT == MVT::vAny)
47     EnforceVector(TP);
48   else {
49     assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
50             VT == MVT::iPTRAny) && "Not a concrete type!");
51     TypeVec.push_back(VT);
52   }
53 }
54
55
56 EEVT::TypeSet::TypeSet(const std::vector<MVT::SimpleValueType> &VTList) {
57   assert(!VTList.empty() && "empty list?");
58   TypeVec.append(VTList.begin(), VTList.end());
59   
60   if (!VTList.empty())
61     assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
62            VTList[0] != MVT::fAny);
63   
64   // Remove duplicates.
65   array_pod_sort(TypeVec.begin(), TypeVec.end());
66   TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
67 }
68
69 /// FillWithPossibleTypes - Set to all legal types and return true, only valid
70 /// on completely unknown type sets.
71 bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
72                                           bool (*Pred)(MVT::SimpleValueType),
73                                           const char *PredicateName) {
74   assert(isCompletelyUnknown());
75   const std::vector<MVT::SimpleValueType> &LegalTypes = 
76     TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
77   
78   for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
79     if (Pred == 0 || Pred(LegalTypes[i]))
80       TypeVec.push_back(LegalTypes[i]);
81
82   // If we have nothing that matches the predicate, bail out.
83   if (TypeVec.empty())
84     TP.error("Type inference contradiction found, no " +
85              std::string(PredicateName) + " types found");  
86   // No need to sort with one element.
87   if (TypeVec.size() == 1) return true;
88
89   // Remove duplicates.
90   array_pod_sort(TypeVec.begin(), TypeVec.end());
91   TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
92   
93   return true;
94 }
95
96 /// hasIntegerTypes - Return true if this TypeSet contains iAny or an
97 /// integer value type.
98 bool EEVT::TypeSet::hasIntegerTypes() const {
99   for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
100     if (isInteger(TypeVec[i]))
101       return true;
102   return false;
103 }  
104
105 /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
106 /// a floating point value type.
107 bool EEVT::TypeSet::hasFloatingPointTypes() const {
108   for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
109     if (isFloatingPoint(TypeVec[i]))
110       return true;
111   return false;
112 }  
113
114 /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
115 /// value type.
116 bool EEVT::TypeSet::hasVectorTypes() const {
117   for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
118     if (isVector(TypeVec[i]))
119       return true;
120   return false;
121 }
122
123
124 std::string EEVT::TypeSet::getName() const {
125   if (TypeVec.empty()) return "<empty>";
126   
127   std::string Result;
128     
129   for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
130     std::string VTName = llvm::getEnumName(TypeVec[i]);
131     // Strip off MVT:: prefix if present.
132     if (VTName.substr(0,5) == "MVT::")
133       VTName = VTName.substr(5);
134     if (i) Result += ':';
135     Result += VTName;
136   }
137   
138   if (TypeVec.size() == 1)
139     return Result;
140   return "{" + Result + "}";
141 }
142
143 /// MergeInTypeInfo - This merges in type information from the specified
144 /// argument.  If 'this' changes, it returns true.  If the two types are
145 /// contradictory (e.g. merge f32 into i32) then this throws an exception.
146 bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
147   if (InVT.isCompletelyUnknown() || *this == InVT)
148     return false;
149   
150   if (isCompletelyUnknown()) {
151     *this = InVT;
152     return true;
153   }
154   
155   assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
156   
157   // Handle the abstract cases, seeing if we can resolve them better.
158   switch (TypeVec[0]) {
159   default: break;
160   case MVT::iPTR:
161   case MVT::iPTRAny:
162     if (InVT.hasIntegerTypes()) {
163       EEVT::TypeSet InCopy(InVT);
164       InCopy.EnforceInteger(TP);
165       InCopy.EnforceScalar(TP);
166       
167       if (InCopy.isConcrete()) {
168         // If the RHS has one integer type, upgrade iPTR to i32.
169         TypeVec[0] = InVT.TypeVec[0];
170         return true;
171       }
172       
173       // If the input has multiple scalar integers, this doesn't add any info.
174       if (!InCopy.isCompletelyUnknown())
175         return false;
176     }
177     break;
178   }
179   
180   // If the input constraint is iAny/iPTR and this is an integer type list,
181   // remove non-integer types from the list.
182   if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
183       hasIntegerTypes()) {
184     bool MadeChange = EnforceInteger(TP);
185     
186     // If we're merging in iPTR/iPTRAny and the node currently has a list of
187     // multiple different integer types, replace them with a single iPTR.
188     if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
189         TypeVec.size() != 1) {
190       TypeVec.resize(1);
191       TypeVec[0] = InVT.TypeVec[0];
192       MadeChange = true;
193     }
194     
195     return MadeChange;
196   }
197   
198   // If this is a type list and the RHS is a typelist as well, eliminate entries
199   // from this list that aren't in the other one.
200   bool MadeChange = false;
201   TypeSet InputSet(*this);
202
203   for (unsigned i = 0; i != TypeVec.size(); ++i) {
204     bool InInVT = false;
205     for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
206       if (TypeVec[i] == InVT.TypeVec[j]) {
207         InInVT = true;
208         break;
209       }
210     
211     if (InInVT) continue;
212     TypeVec.erase(TypeVec.begin()+i--);
213     MadeChange = true;
214   }
215   
216   // If we removed all of our types, we have a type contradiction.
217   if (!TypeVec.empty())
218     return MadeChange;
219   
220   // FIXME: Really want an SMLoc here!
221   TP.error("Type inference contradiction found, merging '" +
222            InVT.getName() + "' into '" + InputSet.getName() + "'");
223   return true; // unreachable
224 }
225
226 /// EnforceInteger - Remove all non-integer types from this set.
227 bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
228   // If we know nothing, then get the full set.
229   if (TypeVec.empty())
230     return FillWithPossibleTypes(TP, isInteger, "integer");
231   if (!hasFloatingPointTypes())
232     return false;
233
234   TypeSet InputSet(*this);
235   
236   // Filter out all the fp types.
237   for (unsigned i = 0; i != TypeVec.size(); ++i)
238     if (!isInteger(TypeVec[i]))
239       TypeVec.erase(TypeVec.begin()+i--);
240   
241   if (TypeVec.empty())
242     TP.error("Type inference contradiction found, '" +
243              InputSet.getName() + "' needs to be integer");
244   return true;
245 }
246
247 /// EnforceFloatingPoint - Remove all integer types from this set.
248 bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
249   // If we know nothing, then get the full set.
250   if (TypeVec.empty())
251     return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
252
253   if (!hasIntegerTypes())
254     return false;
255
256   TypeSet InputSet(*this);
257   
258   // Filter out all the fp types.
259   for (unsigned i = 0; i != TypeVec.size(); ++i)
260     if (!isFloatingPoint(TypeVec[i]))
261       TypeVec.erase(TypeVec.begin()+i--);
262   
263   if (TypeVec.empty())
264     TP.error("Type inference contradiction found, '" +
265              InputSet.getName() + "' needs to be floating point");
266   return true;
267 }
268
269 /// EnforceScalar - Remove all vector types from this.
270 bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
271   // If we know nothing, then get the full set.
272   if (TypeVec.empty())
273     return FillWithPossibleTypes(TP, isScalar, "scalar");
274
275   if (!hasVectorTypes())
276     return false;
277
278   TypeSet InputSet(*this);
279   
280   // Filter out all the vector types.
281   for (unsigned i = 0; i != TypeVec.size(); ++i)
282     if (!isScalar(TypeVec[i]))
283       TypeVec.erase(TypeVec.begin()+i--);
284   
285   if (TypeVec.empty())
286     TP.error("Type inference contradiction found, '" +
287              InputSet.getName() + "' needs to be scalar");
288   return true;
289 }
290
291 /// EnforceVector - Remove all vector types from this.
292 bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
293   // If we know nothing, then get the full set.
294   if (TypeVec.empty())
295     return FillWithPossibleTypes(TP, isVector, "vector");
296
297   TypeSet InputSet(*this);
298   bool MadeChange = false;
299   
300   // Filter out all the scalar types.
301   for (unsigned i = 0; i != TypeVec.size(); ++i)
302     if (!isVector(TypeVec[i])) {
303       TypeVec.erase(TypeVec.begin()+i--);
304       MadeChange = true;
305     }
306   
307   if (TypeVec.empty())
308     TP.error("Type inference contradiction found, '" +
309              InputSet.getName() + "' needs to be a vector");
310   return MadeChange;
311 }
312
313
314
315 /// EnforceSmallerThan - 'this' must be a smaller VT than Other.  Update
316 /// this an other based on this information.
317 bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
318   // Both operands must be integer or FP, but we don't care which.
319   bool MadeChange = false;
320   
321   if (isCompletelyUnknown())
322     MadeChange = FillWithPossibleTypes(TP);
323
324   if (Other.isCompletelyUnknown())
325     MadeChange = Other.FillWithPossibleTypes(TP);
326     
327   // If one side is known to be integer or known to be FP but the other side has
328   // no information, get at least the type integrality info in there.
329   if (!hasFloatingPointTypes())
330     MadeChange |= Other.EnforceInteger(TP);
331   else if (!hasIntegerTypes())
332     MadeChange |= Other.EnforceFloatingPoint(TP);
333   if (!Other.hasFloatingPointTypes())
334     MadeChange |= EnforceInteger(TP);
335   else if (!Other.hasIntegerTypes())
336     MadeChange |= EnforceFloatingPoint(TP);
337   
338   assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
339          "Should have a type list now");
340   
341   // If one contains vectors but the other doesn't pull vectors out.
342   if (!hasVectorTypes())
343     MadeChange |= Other.EnforceScalar(TP);
344   if (!hasVectorTypes())
345     MadeChange |= EnforceScalar(TP);
346   
347   // This code does not currently handle nodes which have multiple types,
348   // where some types are integer, and some are fp.  Assert that this is not
349   // the case.
350   assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
351          !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
352          "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
353   
354   // Okay, find the smallest type from the current set and remove it from the
355   // largest set.
356   MVT::SimpleValueType Smallest = TypeVec[0];
357   for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
358     if (TypeVec[i] < Smallest)
359       Smallest = TypeVec[i];
360   
361   // If this is the only type in the large set, the constraint can never be
362   // satisfied.
363   if (Other.TypeVec.size() == 1 && Other.TypeVec[0] == Smallest)
364     TP.error("Type inference contradiction found, '" +
365              Other.getName() + "' has nothing larger than '" + getName() +"'!");
366   
367   SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
368     std::find(Other.TypeVec.begin(), Other.TypeVec.end(), Smallest);
369   if (TVI != Other.TypeVec.end()) {
370     Other.TypeVec.erase(TVI);
371     MadeChange = true;
372   }
373   
374   // Okay, find the largest type in the Other set and remove it from the
375   // current set.
376   MVT::SimpleValueType Largest = Other.TypeVec[0];
377   for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
378     if (Other.TypeVec[i] > Largest)
379       Largest = Other.TypeVec[i];
380   
381   // If this is the only type in the small set, the constraint can never be
382   // satisfied.
383   if (TypeVec.size() == 1 && TypeVec[0] == Largest)
384     TP.error("Type inference contradiction found, '" +
385              getName() + "' has nothing smaller than '" + Other.getName()+"'!");
386   
387   TVI = std::find(TypeVec.begin(), TypeVec.end(), Largest);
388   if (TVI != TypeVec.end()) {
389     TypeVec.erase(TVI);
390     MadeChange = true;
391   }
392   
393   return MadeChange;
394 }
395
396 /// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
397 /// whose element is specified by VTOperand.
398 bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
399                                            TreePattern &TP) {
400   // "This" must be a vector and "VTOperand" must be a scalar.
401   bool MadeChange = false;
402   MadeChange |= EnforceVector(TP);
403   MadeChange |= VTOperand.EnforceScalar(TP);
404
405   // If we know the vector type, it forces the scalar to agree.
406   if (isConcrete()) {
407     EVT IVT = getConcrete();
408     IVT = IVT.getVectorElementType();
409     return MadeChange | 
410       VTOperand.MergeInTypeInfo(IVT.getSimpleVT().SimpleTy, TP);
411   }
412
413   // If the scalar type is known, filter out vector types whose element types
414   // disagree.
415   if (!VTOperand.isConcrete())
416     return MadeChange;
417   
418   MVT::SimpleValueType VT = VTOperand.getConcrete();
419   
420   TypeSet InputSet(*this);
421   
422   // Filter out all the types which don't have the right element type.
423   for (unsigned i = 0; i != TypeVec.size(); ++i) {
424     assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
425     if (EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
426       TypeVec.erase(TypeVec.begin()+i--);
427       MadeChange = true;
428     }
429   }
430   
431   if (TypeVec.empty())  // FIXME: Really want an SMLoc here!
432     TP.error("Type inference contradiction found, forcing '" +
433              InputSet.getName() + "' to have a vector element");
434   return MadeChange;
435 }
436
437 //===----------------------------------------------------------------------===//
438 // Helpers for working with extended types.
439
440 bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
441   return LHS->getID() < RHS->getID();
442 }
443
444 /// Dependent variable map for CodeGenDAGPattern variant generation
445 typedef std::map<std::string, int> DepVarMap;
446
447 /// Const iterator shorthand for DepVarMap
448 typedef DepVarMap::const_iterator DepVarMap_citer;
449
450 namespace {
451 void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
452   if (N->isLeaf()) {
453     if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
454       DepMap[N->getName()]++;
455     }
456   } else {
457     for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
458       FindDepVarsOf(N->getChild(i), DepMap);
459   }
460 }
461
462 //! Find dependent variables within child patterns
463 /*!
464  */
465 void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
466   DepVarMap depcounts;
467   FindDepVarsOf(N, depcounts);
468   for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
469     if (i->second > 1) {            // std::pair<std::string, int>
470       DepVars.insert(i->first);
471     }
472   }
473 }
474
475 //! Dump the dependent variable set:
476 void DumpDepVars(MultipleUseVarSet &DepVars) {
477   if (DepVars.empty()) {
478     DEBUG(errs() << "<empty set>");
479   } else {
480     DEBUG(errs() << "[ ");
481     for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
482          i != e; ++i) {
483       DEBUG(errs() << (*i) << " ");
484     }
485     DEBUG(errs() << "]");
486   }
487 }
488 }
489
490 //===----------------------------------------------------------------------===//
491 // PatternToMatch implementation
492 //
493
494 /// getPredicateCheck - Return a single string containing all of this
495 /// pattern's predicates concatenated with "&&" operators.
496 ///
497 std::string PatternToMatch::getPredicateCheck() const {
498   std::string PredicateCheck;
499   for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
500     if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
501       Record *Def = Pred->getDef();
502       if (!Def->isSubClassOf("Predicate")) {
503 #ifndef NDEBUG
504         Def->dump();
505 #endif
506         assert(0 && "Unknown predicate type!");
507       }
508       if (!PredicateCheck.empty())
509         PredicateCheck += " && ";
510       PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
511     }
512   }
513
514   return PredicateCheck;
515 }
516
517 //===----------------------------------------------------------------------===//
518 // SDTypeConstraint implementation
519 //
520
521 SDTypeConstraint::SDTypeConstraint(Record *R) {
522   OperandNo = R->getValueAsInt("OperandNum");
523   
524   if (R->isSubClassOf("SDTCisVT")) {
525     ConstraintType = SDTCisVT;
526     x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
527   } else if (R->isSubClassOf("SDTCisPtrTy")) {
528     ConstraintType = SDTCisPtrTy;
529   } else if (R->isSubClassOf("SDTCisInt")) {
530     ConstraintType = SDTCisInt;
531   } else if (R->isSubClassOf("SDTCisFP")) {
532     ConstraintType = SDTCisFP;
533   } else if (R->isSubClassOf("SDTCisVec")) {
534     ConstraintType = SDTCisVec;
535   } else if (R->isSubClassOf("SDTCisSameAs")) {
536     ConstraintType = SDTCisSameAs;
537     x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
538   } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
539     ConstraintType = SDTCisVTSmallerThanOp;
540     x.SDTCisVTSmallerThanOp_Info.OtherOperandNum = 
541       R->getValueAsInt("OtherOperandNum");
542   } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
543     ConstraintType = SDTCisOpSmallerThanOp;
544     x.SDTCisOpSmallerThanOp_Info.BigOperandNum = 
545       R->getValueAsInt("BigOperandNum");
546   } else if (R->isSubClassOf("SDTCisEltOfVec")) {
547     ConstraintType = SDTCisEltOfVec;
548     x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
549   } else {
550     errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
551     exit(1);
552   }
553 }
554
555 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
556 /// N, and the result number in ResNo.
557 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
558                                       const SDNodeInfo &NodeInfo,
559                                       unsigned &ResNo) {
560   unsigned NumResults = NodeInfo.getNumResults();
561   if (OpNo < NumResults) {
562     ResNo = OpNo;
563     return N;
564   }
565   
566   OpNo -= NumResults;
567   
568   if (OpNo >= N->getNumChildren()) {
569     errs() << "Invalid operand number in type constraint " 
570            << (OpNo+NumResults) << " ";
571     N->dump();
572     errs() << '\n';
573     exit(1);
574   }
575
576   return N->getChild(OpNo);
577 }
578
579 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
580 /// constraint to the nodes operands.  This returns true if it makes a
581 /// change, false otherwise.  If a type contradiction is found, throw an
582 /// exception.
583 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
584                                            const SDNodeInfo &NodeInfo,
585                                            TreePattern &TP) const {
586   // Check that the number of operands is sane.  Negative operands -> varargs.
587   if (NodeInfo.getNumOperands() >= 0) {
588     if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
589       TP.error(N->getOperator()->getName() + " node requires exactly " +
590                itostr(NodeInfo.getNumOperands()) + " operands!");
591   }
592
593   unsigned ResNo = 0; // The result number being referenced.
594   TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
595   
596   switch (ConstraintType) {
597   default: assert(0 && "Unknown constraint type!");
598   case SDTCisVT:
599     // Operand must be a particular type.
600     return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
601   case SDTCisPtrTy:
602     // Operand must be same as target pointer type.
603     return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
604   case SDTCisInt:
605     // Require it to be one of the legal integer VTs.
606     return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
607   case SDTCisFP:
608     // Require it to be one of the legal fp VTs.
609     return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
610   case SDTCisVec:
611     // Require it to be one of the legal vector VTs.
612     return NodeToApply->getExtType(ResNo).EnforceVector(TP);
613   case SDTCisSameAs: {
614     unsigned OResNo = 0;
615     TreePatternNode *OtherNode =
616       getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
617     return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
618            OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
619   }
620   case SDTCisVTSmallerThanOp: {
621     // The NodeToApply must be a leaf node that is a VT.  OtherOperandNum must
622     // have an integer type that is smaller than the VT.
623     if (!NodeToApply->isLeaf() ||
624         !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
625         !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
626                ->isSubClassOf("ValueType"))
627       TP.error(N->getOperator()->getName() + " expects a VT operand!");
628     MVT::SimpleValueType VT =
629      getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
630     
631     EEVT::TypeSet TypeListTmp(VT, TP);
632     
633     unsigned OResNo = 0;
634     TreePatternNode *OtherNode =
635       getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
636                     OResNo);
637
638     return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
639   }
640   case SDTCisOpSmallerThanOp: {
641     unsigned BResNo = 0;
642     TreePatternNode *BigOperand =
643       getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
644                     BResNo);
645     return NodeToApply->getExtType(ResNo).
646                   EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
647   }
648   case SDTCisEltOfVec: {
649     unsigned VResNo = 0;
650     TreePatternNode *VecOperand =
651       getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
652                     VResNo);
653     
654     // Filter vector types out of VecOperand that don't have the right element
655     // type.
656     return VecOperand->getExtType(VResNo).
657       EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
658   }
659   }  
660   return false;
661 }
662
663 //===----------------------------------------------------------------------===//
664 // SDNodeInfo implementation
665 //
666 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
667   EnumName    = R->getValueAsString("Opcode");
668   SDClassName = R->getValueAsString("SDClass");
669   Record *TypeProfile = R->getValueAsDef("TypeProfile");
670   NumResults = TypeProfile->getValueAsInt("NumResults");
671   NumOperands = TypeProfile->getValueAsInt("NumOperands");
672   
673   // Parse the properties.
674   Properties = 0;
675   std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
676   for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
677     if (PropList[i]->getName() == "SDNPCommutative") {
678       Properties |= 1 << SDNPCommutative;
679     } else if (PropList[i]->getName() == "SDNPAssociative") {
680       Properties |= 1 << SDNPAssociative;
681     } else if (PropList[i]->getName() == "SDNPHasChain") {
682       Properties |= 1 << SDNPHasChain;
683     } else if (PropList[i]->getName() == "SDNPOutFlag") {
684       Properties |= 1 << SDNPOutFlag;
685     } else if (PropList[i]->getName() == "SDNPInFlag") {
686       Properties |= 1 << SDNPInFlag;
687     } else if (PropList[i]->getName() == "SDNPOptInFlag") {
688       Properties |= 1 << SDNPOptInFlag;
689     } else if (PropList[i]->getName() == "SDNPMayStore") {
690       Properties |= 1 << SDNPMayStore;
691     } else if (PropList[i]->getName() == "SDNPMayLoad") {
692       Properties |= 1 << SDNPMayLoad;
693     } else if (PropList[i]->getName() == "SDNPSideEffect") {
694       Properties |= 1 << SDNPSideEffect;
695     } else if (PropList[i]->getName() == "SDNPMemOperand") {
696       Properties |= 1 << SDNPMemOperand;
697     } else if (PropList[i]->getName() == "SDNPVariadic") {
698       Properties |= 1 << SDNPVariadic;
699     } else {
700       errs() << "Unknown SD Node property '" << PropList[i]->getName()
701              << "' on node '" << R->getName() << "'!\n";
702       exit(1);
703     }
704   }
705   
706   
707   // Parse the type constraints.
708   std::vector<Record*> ConstraintList =
709     TypeProfile->getValueAsListOfDefs("Constraints");
710   TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
711 }
712
713 /// getKnownType - If the type constraints on this node imply a fixed type
714 /// (e.g. all stores return void, etc), then return it as an
715 /// MVT::SimpleValueType.  Otherwise, return EEVT::Other.
716 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
717   unsigned NumResults = getNumResults();
718   assert(NumResults <= 1 &&
719          "We only work with nodes with zero or one result so far!");
720   assert(ResNo == 0 && "Only handles single result nodes so far");
721   
722   for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
723     // Make sure that this applies to the correct node result.
724     if (TypeConstraints[i].OperandNo >= NumResults)  // FIXME: need value #
725       continue;
726     
727     switch (TypeConstraints[i].ConstraintType) {
728     default: break;
729     case SDTypeConstraint::SDTCisVT:
730       return TypeConstraints[i].x.SDTCisVT_Info.VT;
731     case SDTypeConstraint::SDTCisPtrTy:
732       return MVT::iPTR;
733     }
734   }
735   return MVT::Other;
736 }
737
738 //===----------------------------------------------------------------------===//
739 // TreePatternNode implementation
740 //
741
742 TreePatternNode::~TreePatternNode() {
743 #if 0 // FIXME: implement refcounted tree nodes!
744   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
745     delete getChild(i);
746 #endif
747 }
748
749 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
750   if (Operator->getName() == "set" ||
751       Operator->getName() == "implicit")
752     return 0;  // All return nothing.
753   
754   if (Operator->isSubClassOf("Intrinsic"))
755     return CDP.getIntrinsic(Operator).IS.RetVTs.size();
756   
757   if (Operator->isSubClassOf("SDNode"))
758     return CDP.getSDNodeInfo(Operator).getNumResults();
759   
760   if (Operator->isSubClassOf("PatFrag")) {
761     // If we've already parsed this pattern fragment, get it.  Otherwise, handle
762     // the forward reference case where one pattern fragment references another
763     // before it is processed.
764     if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
765       return PFRec->getOnlyTree()->getNumTypes();
766     
767     // Get the result tree.
768     DagInit *Tree = Operator->getValueAsDag("Fragment");
769     Record *Op = 0;
770     if (Tree && dynamic_cast<DefInit*>(Tree->getOperator()))
771       Op = dynamic_cast<DefInit*>(Tree->getOperator())->getDef();
772     assert(Op && "Invalid Fragment");
773     return GetNumNodeResults(Op, CDP);
774   }
775   
776   if (Operator->isSubClassOf("Instruction")) {
777     CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
778
779     // FIXME: Should allow access to all the results here.
780     unsigned NumDefsToAdd = InstInfo.NumDefs ? 1 : 0;
781     
782     // Add on one implicit def if it has a resolvable type.
783     if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
784       ++NumDefsToAdd;
785     return NumDefsToAdd;
786   }
787   
788   if (Operator->isSubClassOf("SDNodeXForm"))
789     return 1;  // FIXME: Generalize SDNodeXForm
790   
791   Operator->dump();
792   errs() << "Unhandled node in GetNumNodeResults\n";
793   exit(1);
794 }
795
796 void TreePatternNode::print(raw_ostream &OS) const {
797   if (isLeaf())
798     OS << *getLeafValue();
799   else
800     OS << '(' << getOperator()->getName();
801
802   for (unsigned i = 0, e = Types.size(); i != e; ++i)
803     OS << ':' << getExtType(i).getName();
804
805   if (!isLeaf()) {
806     if (getNumChildren() != 0) {
807       OS << " ";
808       getChild(0)->print(OS);
809       for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
810         OS << ", ";
811         getChild(i)->print(OS);
812       }
813     }
814     OS << ")";
815   }
816   
817   for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
818     OS << "<<P:" << PredicateFns[i] << ">>";
819   if (TransformFn)
820     OS << "<<X:" << TransformFn->getName() << ">>";
821   if (!getName().empty())
822     OS << ":$" << getName();
823
824 }
825 void TreePatternNode::dump() const {
826   print(errs());
827 }
828
829 /// isIsomorphicTo - Return true if this node is recursively
830 /// isomorphic to the specified node.  For this comparison, the node's
831 /// entire state is considered. The assigned name is ignored, since
832 /// nodes with differing names are considered isomorphic. However, if
833 /// the assigned name is present in the dependent variable set, then
834 /// the assigned name is considered significant and the node is
835 /// isomorphic if the names match.
836 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
837                                      const MultipleUseVarSet &DepVars) const {
838   if (N == this) return true;
839   if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
840       getPredicateFns() != N->getPredicateFns() ||
841       getTransformFn() != N->getTransformFn())
842     return false;
843
844   if (isLeaf()) {
845     if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
846       if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
847         return ((DI->getDef() == NDI->getDef())
848                 && (DepVars.find(getName()) == DepVars.end()
849                     || getName() == N->getName()));
850       }
851     }
852     return getLeafValue() == N->getLeafValue();
853   }
854   
855   if (N->getOperator() != getOperator() ||
856       N->getNumChildren() != getNumChildren()) return false;
857   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
858     if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
859       return false;
860   return true;
861 }
862
863 /// clone - Make a copy of this tree and all of its children.
864 ///
865 TreePatternNode *TreePatternNode::clone() const {
866   TreePatternNode *New;
867   if (isLeaf()) {
868     New = new TreePatternNode(getLeafValue(), getNumTypes());
869   } else {
870     std::vector<TreePatternNode*> CChildren;
871     CChildren.reserve(Children.size());
872     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
873       CChildren.push_back(getChild(i)->clone());
874     New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
875   }
876   New->setName(getName());
877   New->Types = Types;
878   New->setPredicateFns(getPredicateFns());
879   New->setTransformFn(getTransformFn());
880   return New;
881 }
882
883 /// RemoveAllTypes - Recursively strip all the types of this tree.
884 void TreePatternNode::RemoveAllTypes() {
885   for (unsigned i = 0, e = Types.size(); i != e; ++i)
886     Types[i] = EEVT::TypeSet();  // Reset to unknown type.
887   if (isLeaf()) return;
888   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
889     getChild(i)->RemoveAllTypes();
890 }
891
892
893 /// SubstituteFormalArguments - Replace the formal arguments in this tree
894 /// with actual values specified by ArgMap.
895 void TreePatternNode::
896 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
897   if (isLeaf()) return;
898   
899   for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
900     TreePatternNode *Child = getChild(i);
901     if (Child->isLeaf()) {
902       Init *Val = Child->getLeafValue();
903       if (dynamic_cast<DefInit*>(Val) &&
904           static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
905         // We found a use of a formal argument, replace it with its value.
906         TreePatternNode *NewChild = ArgMap[Child->getName()];
907         assert(NewChild && "Couldn't find formal argument!");
908         assert((Child->getPredicateFns().empty() ||
909                 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
910                "Non-empty child predicate clobbered!");
911         setChild(i, NewChild);
912       }
913     } else {
914       getChild(i)->SubstituteFormalArguments(ArgMap);
915     }
916   }
917 }
918
919
920 /// InlinePatternFragments - If this pattern refers to any pattern
921 /// fragments, inline them into place, giving us a pattern without any
922 /// PatFrag references.
923 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
924   if (isLeaf()) return this;  // nothing to do.
925   Record *Op = getOperator();
926   
927   if (!Op->isSubClassOf("PatFrag")) {
928     // Just recursively inline children nodes.
929     for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
930       TreePatternNode *Child = getChild(i);
931       TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
932
933       assert((Child->getPredicateFns().empty() ||
934               NewChild->getPredicateFns() == Child->getPredicateFns()) &&
935              "Non-empty child predicate clobbered!");
936
937       setChild(i, NewChild);
938     }
939     return this;
940   }
941
942   // Otherwise, we found a reference to a fragment.  First, look up its
943   // TreePattern record.
944   TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
945   
946   // Verify that we are passing the right number of operands.
947   if (Frag->getNumArgs() != Children.size())
948     TP.error("'" + Op->getName() + "' fragment requires " +
949              utostr(Frag->getNumArgs()) + " operands!");
950
951   TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
952
953   std::string Code = Op->getValueAsCode("Predicate");
954   if (!Code.empty())
955     FragTree->addPredicateFn("Predicate_"+Op->getName());
956
957   // Resolve formal arguments to their actual value.
958   if (Frag->getNumArgs()) {
959     // Compute the map of formal to actual arguments.
960     std::map<std::string, TreePatternNode*> ArgMap;
961     for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
962       ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
963   
964     FragTree->SubstituteFormalArguments(ArgMap);
965   }
966   
967   FragTree->setName(getName());
968   for (unsigned i = 0, e = Types.size(); i != e; ++i)
969     FragTree->UpdateNodeType(i, getExtType(i), TP);
970
971   // Transfer in the old predicates.
972   for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
973     FragTree->addPredicateFn(getPredicateFns()[i]);
974
975   // Get a new copy of this fragment to stitch into here.
976   //delete this;    // FIXME: implement refcounting!
977   
978   // The fragment we inlined could have recursive inlining that is needed.  See
979   // if there are any pattern fragments in it and inline them as needed.
980   return FragTree->InlinePatternFragments(TP);
981 }
982
983 /// getImplicitType - Check to see if the specified record has an implicit
984 /// type which should be applied to it.  This will infer the type of register
985 /// references from the register file information, for example.
986 ///
987 static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
988                                      bool NotRegisters, TreePattern &TP) {
989   // Check to see if this is a register or a register class.
990   if (R->isSubClassOf("RegisterClass")) {
991     assert(ResNo == 0 && "Regclass ref only has one result!");
992     if (NotRegisters) 
993       return EEVT::TypeSet(); // Unknown.
994     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
995     return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
996   }
997   
998   if (R->isSubClassOf("PatFrag")) {
999     assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
1000     // Pattern fragment types will be resolved when they are inlined.
1001     return EEVT::TypeSet(); // Unknown.
1002   }
1003   
1004   if (R->isSubClassOf("Register")) {
1005     assert(ResNo == 0 && "Registers only produce one result!");
1006     if (NotRegisters) 
1007       return EEVT::TypeSet(); // Unknown.
1008     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1009     return EEVT::TypeSet(T.getRegisterVTs(R));
1010   }
1011   
1012   if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
1013     assert(ResNo == 0 && "This node only has one result!");
1014     // Using a VTSDNode or CondCodeSDNode.
1015     return EEVT::TypeSet(MVT::Other, TP);
1016   }
1017   
1018   if (R->isSubClassOf("ComplexPattern")) {
1019     assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
1020     if (NotRegisters) 
1021       return EEVT::TypeSet(); // Unknown.
1022    return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1023                          TP);
1024   }
1025   if (R->isSubClassOf("PointerLikeRegClass")) {
1026     assert(ResNo == 0 && "Regclass can only have one result!");
1027     return EEVT::TypeSet(MVT::iPTR, TP);
1028   }
1029   
1030   if (R->getName() == "node" || R->getName() == "srcvalue" ||
1031       R->getName() == "zero_reg") {
1032     // Placeholder.
1033     return EEVT::TypeSet(); // Unknown.
1034   }
1035   
1036   TP.error("Unknown node flavor used in pattern: " + R->getName());
1037   return EEVT::TypeSet(MVT::Other, TP);
1038 }
1039
1040
1041 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1042 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
1043 const CodeGenIntrinsic *TreePatternNode::
1044 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1045   if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1046       getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1047       getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1048     return 0;
1049     
1050   unsigned IID = 
1051     dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
1052   return &CDP.getIntrinsicInfo(IID);
1053 }
1054
1055 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1056 /// return the ComplexPattern information, otherwise return null.
1057 const ComplexPattern *
1058 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1059   if (!isLeaf()) return 0;
1060   
1061   DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
1062   if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1063     return &CGP.getComplexPattern(DI->getDef());
1064   return 0;
1065 }
1066
1067 /// NodeHasProperty - Return true if this node has the specified property.
1068 bool TreePatternNode::NodeHasProperty(SDNP Property,
1069                                       const CodeGenDAGPatterns &CGP) const {
1070   if (isLeaf()) {
1071     if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1072       return CP->hasProperty(Property);
1073     return false;
1074   }
1075   
1076   Record *Operator = getOperator();
1077   if (!Operator->isSubClassOf("SDNode")) return false;
1078   
1079   return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1080 }
1081
1082
1083
1084
1085 /// TreeHasProperty - Return true if any node in this tree has the specified
1086 /// property.
1087 bool TreePatternNode::TreeHasProperty(SDNP Property,
1088                                       const CodeGenDAGPatterns &CGP) const {
1089   if (NodeHasProperty(Property, CGP))
1090     return true;
1091   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1092     if (getChild(i)->TreeHasProperty(Property, CGP))
1093       return true;
1094   return false;
1095 }  
1096
1097 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1098 /// commutative intrinsic.
1099 bool
1100 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1101   if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1102     return Int->isCommutative;
1103   return false;
1104 }
1105
1106
1107 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1108 /// this node and its children in the tree.  This returns true if it makes a
1109 /// change, false otherwise.  If a type contradiction is found, throw an
1110 /// exception.
1111 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1112   CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1113   if (isLeaf()) {
1114     if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1115       // If it's a regclass or something else known, include the type.
1116       bool MadeChange = false;
1117       for (unsigned i = 0, e = Types.size(); i != e; ++i)
1118         MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1119                                                         NotRegisters, TP), TP);
1120       return MadeChange;
1121     }
1122     
1123     if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
1124       assert(Types.size() == 1 && "Invalid IntInit");
1125       
1126       // Int inits are always integers. :)
1127       bool MadeChange = Types[0].EnforceInteger(TP);
1128       
1129       if (!Types[0].isConcrete())
1130         return MadeChange;
1131       
1132       MVT::SimpleValueType VT = getType(0);
1133       if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1134         return MadeChange;
1135       
1136       unsigned Size = EVT(VT).getSizeInBits();
1137       // Make sure that the value is representable for this type.
1138       if (Size >= 32) return MadeChange;
1139       
1140       int Val = (II->getValue() << (32-Size)) >> (32-Size);
1141       if (Val == II->getValue()) return MadeChange;
1142       
1143       // If sign-extended doesn't fit, does it fit as unsigned?
1144       unsigned ValueMask;
1145       unsigned UnsignedVal;
1146       ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1147       UnsignedVal = unsigned(II->getValue());
1148
1149       if ((ValueMask & UnsignedVal) == UnsignedVal)
1150         return MadeChange;
1151       
1152       TP.error("Integer value '" + itostr(II->getValue())+
1153                "' is out of range for type '" + getEnumName(getType(0)) + "'!");
1154       return MadeChange;
1155     }
1156     return false;
1157   }
1158   
1159   // special handling for set, which isn't really an SDNode.
1160   if (getOperator()->getName() == "set") {
1161     assert(getNumTypes() == 0 && "Set doesn't produce a value");
1162     assert(getNumChildren() >= 2 && "Missing RHS of a set?");
1163     unsigned NC = getNumChildren();
1164     
1165     TreePatternNode *SetVal = getChild(NC-1);
1166     bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1167
1168     for (unsigned i = 0; i < NC-1; ++i) {
1169       TreePatternNode *Child = getChild(i);
1170       MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1171     
1172       // Types of operands must match.
1173       MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1174       MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
1175     }
1176     return MadeChange;
1177   }
1178   
1179   if (getOperator()->getName() == "implicit") {
1180     assert(getNumTypes() == 0 && "Node doesn't produce a value");
1181
1182     bool MadeChange = false;
1183     for (unsigned i = 0; i < getNumChildren(); ++i)
1184       MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1185     return MadeChange;
1186   }
1187   
1188   if (getOperator()->getName() == "COPY_TO_REGCLASS") {
1189     bool MadeChange = false;
1190     MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1191     MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
1192     
1193     assert(getChild(0)->getNumTypes() == 1 &&
1194            getChild(1)->getNumTypes() == 1 && "Unhandled case");
1195     
1196     // child #1 of COPY_TO_REGCLASS should be a register class.  We don't care
1197     // what type it gets, so if it didn't get a concrete type just give it the
1198     // first viable type from the reg class.
1199     if (!getChild(1)->hasTypeSet(0) &&
1200         !getChild(1)->getExtType(0).isCompletelyUnknown()) {
1201       MVT::SimpleValueType RCVT = getChild(1)->getExtType(0).getTypeList()[0];
1202       MadeChange |= getChild(1)->UpdateNodeType(0, RCVT, TP);
1203     }
1204     return MadeChange;
1205   }
1206   
1207   if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1208     bool MadeChange = false;
1209
1210     // Apply the result type to the node.
1211     unsigned NumRetVTs = Int->IS.RetVTs.size();
1212     unsigned NumParamVTs = Int->IS.ParamVTs.size();
1213     
1214     for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1215       MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
1216
1217     if (getNumChildren() != NumParamVTs + 1)
1218       TP.error("Intrinsic '" + Int->Name + "' expects " +
1219                utostr(NumParamVTs) + " operands, not " +
1220                utostr(getNumChildren() - 1) + " operands!");
1221
1222     // Apply type info to the intrinsic ID.
1223     MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
1224     
1225     for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1226       MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1227       
1228       MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1229       assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1230       MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
1231     }
1232     return MadeChange;
1233   }
1234   
1235   if (getOperator()->isSubClassOf("SDNode")) {
1236     const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1237     
1238     bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1239     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1240       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1241     return MadeChange;
1242   }
1243   
1244   if (getOperator()->isSubClassOf("Instruction")) {
1245     const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1246     CodeGenInstruction &InstInfo =
1247       CDP.getTargetInfo().getInstruction(getOperator());
1248     
1249     bool MadeChange = false;
1250
1251     // Apply the result types to the node, these come from the things in the
1252     // (outs) list of the instruction.
1253     // FIXME: Cap at one result so far.
1254     unsigned NumResultsToAdd = InstInfo.NumDefs ? 1 : 0;
1255     for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo) {
1256       Record *ResultNode = Inst.getResult(ResNo);
1257       
1258       if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
1259         MadeChange |= UpdateNodeType(ResNo, MVT::iPTR, TP);
1260       } else if (ResultNode->getName() == "unknown") {
1261         // Nothing to do.
1262       } else {
1263         assert(ResultNode->isSubClassOf("RegisterClass") &&
1264                "Operands should be register classes!");
1265         const CodeGenRegisterClass &RC = 
1266           CDP.getTargetInfo().getRegisterClass(ResultNode);
1267         MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
1268       }
1269     }
1270     
1271     // If the instruction has implicit defs, we apply the first one as a result.
1272     // FIXME: This sucks, it should apply all implicit defs.
1273     if (!InstInfo.ImplicitDefs.empty()) {
1274       unsigned ResNo = NumResultsToAdd;
1275       
1276       // FIXME: Generalize to multiple possible types and multiple possible
1277       // ImplicitDefs.
1278       MVT::SimpleValueType VT =
1279         InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
1280       
1281       if (VT != MVT::Other)
1282         MadeChange |= UpdateNodeType(ResNo, VT, TP);
1283     }
1284     
1285     // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1286     // be the same.
1287     if (getOperator()->getName() == "INSERT_SUBREG") {
1288       assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1289       MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1290       MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
1291     }
1292
1293     unsigned ChildNo = 0;
1294     for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1295       Record *OperandNode = Inst.getOperand(i);
1296       
1297       // If the instruction expects a predicate or optional def operand, we
1298       // codegen this by setting the operand to it's default value if it has a
1299       // non-empty DefaultOps field.
1300       if ((OperandNode->isSubClassOf("PredicateOperand") ||
1301            OperandNode->isSubClassOf("OptionalDefOperand")) &&
1302           !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1303         continue;
1304        
1305       // Verify that we didn't run out of provided operands.
1306       if (ChildNo >= getNumChildren())
1307         TP.error("Instruction '" + getOperator()->getName() +
1308                  "' expects more operands than were provided.");
1309       
1310       MVT::SimpleValueType VT;
1311       TreePatternNode *Child = getChild(ChildNo++);
1312       unsigned ChildResNo = 0;  // Instructions always use res #0 of their op.
1313       
1314       if (OperandNode->isSubClassOf("RegisterClass")) {
1315         const CodeGenRegisterClass &RC = 
1316           CDP.getTargetInfo().getRegisterClass(OperandNode);
1317         MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
1318       } else if (OperandNode->isSubClassOf("Operand")) {
1319         VT = getValueType(OperandNode->getValueAsDef("Type"));
1320         MadeChange |= Child->UpdateNodeType(ChildResNo, VT, TP);
1321       } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
1322         MadeChange |= Child->UpdateNodeType(ChildResNo, MVT::iPTR, TP);
1323       } else if (OperandNode->getName() == "unknown") {
1324         // Nothing to do.
1325       } else {
1326         assert(0 && "Unknown operand type!");
1327         abort();
1328       }
1329       MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1330     }
1331
1332     if (ChildNo != getNumChildren())
1333       TP.error("Instruction '" + getOperator()->getName() +
1334                "' was provided too many operands!");
1335     
1336     return MadeChange;
1337   }
1338   
1339   assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1340   
1341   // Node transforms always take one operand.
1342   if (getNumChildren() != 1)
1343     TP.error("Node transform '" + getOperator()->getName() +
1344              "' requires one operand!");
1345
1346   bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1347
1348   
1349   // If either the output or input of the xform does not have exact
1350   // type info. We assume they must be the same. Otherwise, it is perfectly
1351   // legal to transform from one type to a completely different type.
1352 #if 0
1353   if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1354     bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1355     MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1356     return MadeChange;
1357   }
1358 #endif
1359   return MadeChange;
1360 }
1361
1362 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1363 /// RHS of a commutative operation, not the on LHS.
1364 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1365   if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1366     return true;
1367   if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1368     return true;
1369   return false;
1370 }
1371
1372
1373 /// canPatternMatch - If it is impossible for this pattern to match on this
1374 /// target, fill in Reason and return false.  Otherwise, return true.  This is
1375 /// used as a sanity check for .td files (to prevent people from writing stuff
1376 /// that can never possibly work), and to prevent the pattern permuter from
1377 /// generating stuff that is useless.
1378 bool TreePatternNode::canPatternMatch(std::string &Reason, 
1379                                       const CodeGenDAGPatterns &CDP) {
1380   if (isLeaf()) return true;
1381
1382   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1383     if (!getChild(i)->canPatternMatch(Reason, CDP))
1384       return false;
1385
1386   // If this is an intrinsic, handle cases that would make it not match.  For
1387   // example, if an operand is required to be an immediate.
1388   if (getOperator()->isSubClassOf("Intrinsic")) {
1389     // TODO:
1390     return true;
1391   }
1392   
1393   // If this node is a commutative operator, check that the LHS isn't an
1394   // immediate.
1395   const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1396   bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1397   if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1398     // Scan all of the operands of the node and make sure that only the last one
1399     // is a constant node, unless the RHS also is.
1400     if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1401       bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1402       for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1403         if (OnlyOnRHSOfCommutative(getChild(i))) {
1404           Reason="Immediate value must be on the RHS of commutative operators!";
1405           return false;
1406         }
1407     }
1408   }
1409   
1410   return true;
1411 }
1412
1413 //===----------------------------------------------------------------------===//
1414 // TreePattern implementation
1415 //
1416
1417 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1418                          CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1419   isInputPattern = isInput;
1420   for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1421     Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
1422 }
1423
1424 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1425                          CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1426   isInputPattern = isInput;
1427   Trees.push_back(ParseTreePattern(Pat));
1428 }
1429
1430 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1431                          CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1432   isInputPattern = isInput;
1433   Trees.push_back(Pat);
1434 }
1435
1436 void TreePattern::error(const std::string &Msg) const {
1437   dump();
1438   throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1439 }
1440
1441 void TreePattern::ComputeNamedNodes() {
1442   for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1443     ComputeNamedNodes(Trees[i]);
1444 }
1445
1446 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1447   if (!N->getName().empty())
1448     NamedNodes[N->getName()].push_back(N);
1449   
1450   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1451     ComputeNamedNodes(N->getChild(i));
1452 }
1453
1454
1455 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1456   DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1457   if (!OpDef) error("Pattern has unexpected operator type!");
1458   Record *Operator = OpDef->getDef();
1459   
1460   if (Operator->isSubClassOf("ValueType")) {
1461     // If the operator is a ValueType, then this must be "type cast" of a leaf
1462     // node.
1463     if (Dag->getNumArgs() != 1)
1464       error("Type cast only takes one operand!");
1465     
1466     Init *Arg = Dag->getArg(0);
1467     TreePatternNode *New;
1468     if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1469       Record *R = DI->getDef();
1470       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1471         Dag->setArg(0, new DagInit(DI, "",
1472                                 std::vector<std::pair<Init*, std::string> >()));
1473         return ParseTreePattern(Dag);
1474       }
1475       
1476       // Input argument?
1477       if (R->getName() == "node") {
1478         if (Dag->getArgName(0).empty())
1479           error("'node' argument requires a name to match with operand list");
1480         Args.push_back(Dag->getArgName(0));
1481       }
1482       
1483       New = new TreePatternNode(DI, 1);
1484     } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1485       New = ParseTreePattern(DI);
1486     } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1487       New = new TreePatternNode(II, 1);
1488       if (!Dag->getArgName(0).empty())
1489         error("Constant int argument should not have a name!");
1490     } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1491       // Turn this into an IntInit.
1492       Init *II = BI->convertInitializerTo(new IntRecTy());
1493       if (II == 0 || !dynamic_cast<IntInit*>(II))
1494         error("Bits value must be constants!");
1495       
1496       New = new TreePatternNode(dynamic_cast<IntInit*>(II), 1);
1497       if (!Dag->getArgName(0).empty())
1498         error("Constant int argument should not have a name!");
1499     } else {
1500       Arg->dump();
1501       error("Unknown leaf value for tree pattern!");
1502       return 0;
1503     }
1504     
1505     // Apply the type cast.
1506     assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1507     New->UpdateNodeType(0, getValueType(Operator), *this);
1508     if (New->getNumChildren() == 0)
1509       New->setName(Dag->getArgName(0));
1510     return New;
1511   }
1512   
1513   // Verify that this is something that makes sense for an operator.
1514   if (!Operator->isSubClassOf("PatFrag") && 
1515       !Operator->isSubClassOf("SDNode") &&
1516       !Operator->isSubClassOf("Instruction") && 
1517       !Operator->isSubClassOf("SDNodeXForm") &&
1518       !Operator->isSubClassOf("Intrinsic") &&
1519       Operator->getName() != "set" &&
1520       Operator->getName() != "implicit")
1521     error("Unrecognized node '" + Operator->getName() + "'!");
1522   
1523   //  Check to see if this is something that is illegal in an input pattern.
1524   if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1525                          Operator->isSubClassOf("SDNodeXForm")))
1526     error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1527   
1528   std::vector<TreePatternNode*> Children;
1529   
1530   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1531     Init *Arg = Dag->getArg(i);
1532     if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1533       Children.push_back(ParseTreePattern(DI));
1534       if (Children.back()->getName().empty())
1535         Children.back()->setName(Dag->getArgName(i));
1536     } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1537       Record *R = DefI->getDef();
1538       // Direct reference to a leaf DagNode or PatFrag?  Turn it into a
1539       // TreePatternNode if its own.
1540       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1541         Dag->setArg(i, new DagInit(DefI, "",
1542                               std::vector<std::pair<Init*, std::string> >()));
1543         --i;  // Revisit this node...
1544       } else {
1545         TreePatternNode *Node = new TreePatternNode(DefI, 1);
1546         Node->setName(Dag->getArgName(i));
1547         Children.push_back(Node);
1548         
1549         // Input argument?
1550         if (R->getName() == "node") {
1551           if (Dag->getArgName(i).empty())
1552             error("'node' argument requires a name to match with operand list");
1553           Args.push_back(Dag->getArgName(i));
1554         }
1555       }
1556     } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1557       TreePatternNode *Node = new TreePatternNode(II, 1);
1558       if (!Dag->getArgName(i).empty())
1559         error("Constant int argument should not have a name!");
1560       Children.push_back(Node);
1561     } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1562       // Turn this into an IntInit.
1563       Init *II = BI->convertInitializerTo(new IntRecTy());
1564       if (II == 0 || !dynamic_cast<IntInit*>(II))
1565         error("Bits value must be constants!");
1566       
1567       TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II),1);
1568       if (!Dag->getArgName(i).empty())
1569         error("Constant int argument should not have a name!");
1570       Children.push_back(Node);
1571     } else {
1572       errs() << '"';
1573       Arg->dump();
1574       errs() << "\": ";
1575       error("Unknown leaf value for tree pattern!");
1576     }
1577   }
1578   
1579   // If the operator is an intrinsic, then this is just syntactic sugar for for
1580   // (intrinsic_* <number>, ..children..).  Pick the right intrinsic node, and 
1581   // convert the intrinsic name to a number.
1582   if (Operator->isSubClassOf("Intrinsic")) {
1583     const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1584     unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1585
1586     // If this intrinsic returns void, it must have side-effects and thus a
1587     // chain.
1588     if (Int.IS.RetVTs.empty()) {
1589       Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1590     } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1591       // Has side-effects, requires chain.
1592       Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1593     } else {
1594       // Otherwise, no chain.
1595       Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1596     }
1597     
1598     TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID), 1);
1599     Children.insert(Children.begin(), IIDNode);
1600   }
1601   
1602   unsigned NumResults = GetNumNodeResults(Operator, CDP);
1603   TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
1604   Result->setName(Dag->getName());
1605   return Result;
1606 }
1607
1608 /// InferAllTypes - Infer/propagate as many types throughout the expression
1609 /// patterns as possible.  Return true if all types are inferred, false
1610 /// otherwise.  Throw an exception if a type contradiction is found.
1611 bool TreePattern::
1612 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1613   if (NamedNodes.empty())
1614     ComputeNamedNodes();
1615
1616   bool MadeChange = true;
1617   while (MadeChange) {
1618     MadeChange = false;
1619     for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1620       MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1621
1622     // If there are constraints on our named nodes, apply them.
1623     for (StringMap<SmallVector<TreePatternNode*,1> >::iterator 
1624          I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1625       SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
1626       
1627       // If we have input named node types, propagate their types to the named
1628       // values here.
1629       if (InNamedTypes) {
1630         // FIXME: Should be error?
1631         assert(InNamedTypes->count(I->getKey()) &&
1632                "Named node in output pattern but not input pattern?");
1633
1634         const SmallVectorImpl<TreePatternNode*> &InNodes =
1635           InNamedTypes->find(I->getKey())->second;
1636
1637         // The input types should be fully resolved by now.
1638         for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1639           // If this node is a register class, and it is the root of the pattern
1640           // then we're mapping something onto an input register.  We allow
1641           // changing the type of the input register in this case.  This allows
1642           // us to match things like:
1643           //  def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1644           if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1645             DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1646             if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1647               continue;
1648           }
1649           
1650           assert(Nodes[i]->getNumTypes() == 1 &&
1651                  InNodes[0]->getNumTypes() == 1 &&
1652                  "FIXME: cannot name multiple result nodes yet");
1653           MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
1654                                                  *this);
1655         }
1656       }
1657       
1658       // If there are multiple nodes with the same name, they must all have the
1659       // same type.
1660       if (I->second.size() > 1) {
1661         for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
1662           TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
1663           assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
1664                  "FIXME: cannot name multiple result nodes yet");
1665           
1666           MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
1667           MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
1668         }
1669       }
1670     }
1671   }
1672   
1673   bool HasUnresolvedTypes = false;
1674   for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1675     HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1676   return !HasUnresolvedTypes;
1677 }
1678
1679 void TreePattern::print(raw_ostream &OS) const {
1680   OS << getRecord()->getName();
1681   if (!Args.empty()) {
1682     OS << "(" << Args[0];
1683     for (unsigned i = 1, e = Args.size(); i != e; ++i)
1684       OS << ", " << Args[i];
1685     OS << ")";
1686   }
1687   OS << ": ";
1688   
1689   if (Trees.size() > 1)
1690     OS << "[\n";
1691   for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1692     OS << "\t";
1693     Trees[i]->print(OS);
1694     OS << "\n";
1695   }
1696
1697   if (Trees.size() > 1)
1698     OS << "]\n";
1699 }
1700
1701 void TreePattern::dump() const { print(errs()); }
1702
1703 //===----------------------------------------------------------------------===//
1704 // CodeGenDAGPatterns implementation
1705 //
1706
1707 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
1708   Intrinsics = LoadIntrinsics(Records, false);
1709   TgtIntrinsics = LoadIntrinsics(Records, true);
1710   ParseNodeInfo();
1711   ParseNodeTransforms();
1712   ParseComplexPatterns();
1713   ParsePatternFragments();
1714   ParseDefaultOperands();
1715   ParseInstructions();
1716   ParsePatterns();
1717   
1718   // Generate variants.  For example, commutative patterns can match
1719   // multiple ways.  Add them to PatternsToMatch as well.
1720   GenerateVariants();
1721
1722   // Infer instruction flags.  For example, we can detect loads,
1723   // stores, and side effects in many cases by examining an
1724   // instruction's pattern.
1725   InferInstructionFlags();
1726 }
1727
1728 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
1729   for (pf_iterator I = PatternFragments.begin(),
1730        E = PatternFragments.end(); I != E; ++I)
1731     delete I->second;
1732 }
1733
1734
1735 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
1736   Record *N = Records.getDef(Name);
1737   if (!N || !N->isSubClassOf("SDNode")) {
1738     errs() << "Error getting SDNode '" << Name << "'!\n";
1739     exit(1);
1740   }
1741   return N;
1742 }
1743
1744 // Parse all of the SDNode definitions for the target, populating SDNodes.
1745 void CodeGenDAGPatterns::ParseNodeInfo() {
1746   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1747   while (!Nodes.empty()) {
1748     SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1749     Nodes.pop_back();
1750   }
1751
1752   // Get the builtin intrinsic nodes.
1753   intrinsic_void_sdnode     = getSDNodeNamed("intrinsic_void");
1754   intrinsic_w_chain_sdnode  = getSDNodeNamed("intrinsic_w_chain");
1755   intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1756 }
1757
1758 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1759 /// map, and emit them to the file as functions.
1760 void CodeGenDAGPatterns::ParseNodeTransforms() {
1761   std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1762   while (!Xforms.empty()) {
1763     Record *XFormNode = Xforms.back();
1764     Record *SDNode = XFormNode->getValueAsDef("Opcode");
1765     std::string Code = XFormNode->getValueAsCode("XFormFunction");
1766     SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
1767
1768     Xforms.pop_back();
1769   }
1770 }
1771
1772 void CodeGenDAGPatterns::ParseComplexPatterns() {
1773   std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1774   while (!AMs.empty()) {
1775     ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1776     AMs.pop_back();
1777   }
1778 }
1779
1780
1781 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1782 /// file, building up the PatternFragments map.  After we've collected them all,
1783 /// inline fragments together as necessary, so that there are no references left
1784 /// inside a pattern fragment to a pattern fragment.
1785 ///
1786 void CodeGenDAGPatterns::ParsePatternFragments() {
1787   std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1788   
1789   // First step, parse all of the fragments.
1790   for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1791     DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1792     TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1793     PatternFragments[Fragments[i]] = P;
1794     
1795     // Validate the argument list, converting it to set, to discard duplicates.
1796     std::vector<std::string> &Args = P->getArgList();
1797     std::set<std::string> OperandsSet(Args.begin(), Args.end());
1798     
1799     if (OperandsSet.count(""))
1800       P->error("Cannot have unnamed 'node' values in pattern fragment!");
1801     
1802     // Parse the operands list.
1803     DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1804     DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1805     // Special cases: ops == outs == ins. Different names are used to
1806     // improve readability.
1807     if (!OpsOp ||
1808         (OpsOp->getDef()->getName() != "ops" &&
1809          OpsOp->getDef()->getName() != "outs" &&
1810          OpsOp->getDef()->getName() != "ins"))
1811       P->error("Operands list should start with '(ops ... '!");
1812     
1813     // Copy over the arguments.       
1814     Args.clear();
1815     for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1816       if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1817           static_cast<DefInit*>(OpsList->getArg(j))->
1818           getDef()->getName() != "node")
1819         P->error("Operands list should all be 'node' values.");
1820       if (OpsList->getArgName(j).empty())
1821         P->error("Operands list should have names for each operand!");
1822       if (!OperandsSet.count(OpsList->getArgName(j)))
1823         P->error("'" + OpsList->getArgName(j) +
1824                  "' does not occur in pattern or was multiply specified!");
1825       OperandsSet.erase(OpsList->getArgName(j));
1826       Args.push_back(OpsList->getArgName(j));
1827     }
1828     
1829     if (!OperandsSet.empty())
1830       P->error("Operands list does not contain an entry for operand '" +
1831                *OperandsSet.begin() + "'!");
1832
1833     // If there is a code init for this fragment, keep track of the fact that
1834     // this fragment uses it.
1835     std::string Code = Fragments[i]->getValueAsCode("Predicate");
1836     if (!Code.empty())
1837       P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
1838     
1839     // If there is a node transformation corresponding to this, keep track of
1840     // it.
1841     Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1842     if (!getSDNodeTransform(Transform).second.empty())    // not noop xform?
1843       P->getOnlyTree()->setTransformFn(Transform);
1844   }
1845   
1846   // Now that we've parsed all of the tree fragments, do a closure on them so
1847   // that there are not references to PatFrags left inside of them.
1848   for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1849     TreePattern *ThePat = PatternFragments[Fragments[i]];
1850     ThePat->InlinePatternFragments();
1851         
1852     // Infer as many types as possible.  Don't worry about it if we don't infer
1853     // all of them, some may depend on the inputs of the pattern.
1854     try {
1855       ThePat->InferAllTypes();
1856     } catch (...) {
1857       // If this pattern fragment is not supported by this target (no types can
1858       // satisfy its constraints), just ignore it.  If the bogus pattern is
1859       // actually used by instructions, the type consistency error will be
1860       // reported there.
1861     }
1862     
1863     // If debugging, print out the pattern fragment result.
1864     DEBUG(ThePat->dump());
1865   }
1866 }
1867
1868 void CodeGenDAGPatterns::ParseDefaultOperands() {
1869   std::vector<Record*> DefaultOps[2];
1870   DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1871   DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1872
1873   // Find some SDNode.
1874   assert(!SDNodes.empty() && "No SDNodes parsed?");
1875   Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1876   
1877   for (unsigned iter = 0; iter != 2; ++iter) {
1878     for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1879       DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1880     
1881       // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1882       // SomeSDnode so that we can parse this.
1883       std::vector<std::pair<Init*, std::string> > Ops;
1884       for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1885         Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1886                                      DefaultInfo->getArgName(op)));
1887       DagInit *DI = new DagInit(SomeSDNode, "", Ops);
1888     
1889       // Create a TreePattern to parse this.
1890       TreePattern P(DefaultOps[iter][i], DI, false, *this);
1891       assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1892
1893       // Copy the operands over into a DAGDefaultOperand.
1894       DAGDefaultOperand DefaultOpInfo;
1895     
1896       TreePatternNode *T = P.getTree(0);
1897       for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1898         TreePatternNode *TPN = T->getChild(op);
1899         while (TPN->ApplyTypeConstraints(P, false))
1900           /* Resolve all types */;
1901       
1902         if (TPN->ContainsUnresolvedType()) {
1903           if (iter == 0)
1904             throw "Value #" + utostr(i) + " of PredicateOperand '" +
1905               DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
1906           else
1907             throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1908               DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
1909         }
1910         DefaultOpInfo.DefaultOps.push_back(TPN);
1911       }
1912
1913       // Insert it into the DefaultOperands map so we can find it later.
1914       DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1915     }
1916   }
1917 }
1918
1919 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1920 /// instruction input.  Return true if this is a real use.
1921 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1922                       std::map<std::string, TreePatternNode*> &InstInputs,
1923                       std::vector<Record*> &InstImpInputs) {
1924   // No name -> not interesting.
1925   if (Pat->getName().empty()) {
1926     if (Pat->isLeaf()) {
1927       DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1928       if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1929         I->error("Input " + DI->getDef()->getName() + " must be named!");
1930       else if (DI && DI->getDef()->isSubClassOf("Register")) 
1931         InstImpInputs.push_back(DI->getDef());
1932     }
1933     return false;
1934   }
1935
1936   Record *Rec;
1937   if (Pat->isLeaf()) {
1938     DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1939     if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1940     Rec = DI->getDef();
1941   } else {
1942     Rec = Pat->getOperator();
1943   }
1944
1945   // SRCVALUE nodes are ignored.
1946   if (Rec->getName() == "srcvalue")
1947     return false;
1948
1949   TreePatternNode *&Slot = InstInputs[Pat->getName()];
1950   if (!Slot) {
1951     Slot = Pat;
1952     return true;
1953   }
1954   Record *SlotRec;
1955   if (Slot->isLeaf()) {
1956     SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1957   } else {
1958     assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1959     SlotRec = Slot->getOperator();
1960   }
1961   
1962   // Ensure that the inputs agree if we've already seen this input.
1963   if (Rec != SlotRec)
1964     I->error("All $" + Pat->getName() + " inputs must agree with each other");
1965   if (Slot->getExtTypes() != Pat->getExtTypes())
1966     I->error("All $" + Pat->getName() + " inputs must agree with each other");
1967   return true;
1968 }
1969
1970 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1971 /// part of "I", the instruction), computing the set of inputs and outputs of
1972 /// the pattern.  Report errors if we see anything naughty.
1973 void CodeGenDAGPatterns::
1974 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1975                             std::map<std::string, TreePatternNode*> &InstInputs,
1976                             std::map<std::string, TreePatternNode*>&InstResults,
1977                             std::vector<Record*> &InstImpInputs,
1978                             std::vector<Record*> &InstImpResults) {
1979   if (Pat->isLeaf()) {
1980     bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1981     if (!isUse && Pat->getTransformFn())
1982       I->error("Cannot specify a transform function for a non-input value!");
1983     return;
1984   }
1985   
1986   if (Pat->getOperator()->getName() == "implicit") {
1987     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1988       TreePatternNode *Dest = Pat->getChild(i);
1989       if (!Dest->isLeaf())
1990         I->error("implicitly defined value should be a register!");
1991     
1992       DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1993       if (!Val || !Val->getDef()->isSubClassOf("Register"))
1994         I->error("implicitly defined value should be a register!");
1995       InstImpResults.push_back(Val->getDef());
1996     }
1997     return;
1998   }
1999   
2000   if (Pat->getOperator()->getName() != "set") {
2001     // If this is not a set, verify that the children nodes are not void typed,
2002     // and recurse.
2003     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2004       if (Pat->getChild(i)->getNumTypes() == 0)
2005         I->error("Cannot have void nodes inside of patterns!");
2006       FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2007                                   InstImpInputs, InstImpResults);
2008     }
2009     
2010     // If this is a non-leaf node with no children, treat it basically as if
2011     // it were a leaf.  This handles nodes like (imm).
2012     bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
2013     
2014     if (!isUse && Pat->getTransformFn())
2015       I->error("Cannot specify a transform function for a non-input value!");
2016     return;
2017   }
2018   
2019   // Otherwise, this is a set, validate and collect instruction results.
2020   if (Pat->getNumChildren() == 0)
2021     I->error("set requires operands!");
2022   
2023   if (Pat->getTransformFn())
2024     I->error("Cannot specify a transform function on a set node!");
2025   
2026   // Check the set destinations.
2027   unsigned NumDests = Pat->getNumChildren()-1;
2028   for (unsigned i = 0; i != NumDests; ++i) {
2029     TreePatternNode *Dest = Pat->getChild(i);
2030     if (!Dest->isLeaf())
2031       I->error("set destination should be a register!");
2032     
2033     DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2034     if (!Val)
2035       I->error("set destination should be a register!");
2036
2037     if (Val->getDef()->isSubClassOf("RegisterClass") ||
2038         Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
2039       if (Dest->getName().empty())
2040         I->error("set destination must have a name!");
2041       if (InstResults.count(Dest->getName()))
2042         I->error("cannot set '" + Dest->getName() +"' multiple times");
2043       InstResults[Dest->getName()] = Dest;
2044     } else if (Val->getDef()->isSubClassOf("Register")) {
2045       InstImpResults.push_back(Val->getDef());
2046     } else {
2047       I->error("set destination should be a register!");
2048     }
2049   }
2050     
2051   // Verify and collect info from the computation.
2052   FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2053                               InstInputs, InstResults,
2054                               InstImpInputs, InstImpResults);
2055 }
2056
2057 //===----------------------------------------------------------------------===//
2058 // Instruction Analysis
2059 //===----------------------------------------------------------------------===//
2060
2061 class InstAnalyzer {
2062   const CodeGenDAGPatterns &CDP;
2063   bool &mayStore;
2064   bool &mayLoad;
2065   bool &HasSideEffects;
2066   bool &IsVariadic;
2067 public:
2068   InstAnalyzer(const CodeGenDAGPatterns &cdp,
2069                bool &maystore, bool &mayload, bool &hse, bool &isv)
2070     : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse),
2071       IsVariadic(isv) {
2072   }
2073
2074   /// Analyze - Analyze the specified instruction, returning true if the
2075   /// instruction had a pattern.
2076   bool Analyze(Record *InstRecord) {
2077     const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
2078     if (Pattern == 0) {
2079       HasSideEffects = 1;
2080       return false;  // No pattern.
2081     }
2082
2083     // FIXME: Assume only the first tree is the pattern. The others are clobber
2084     // nodes.
2085     AnalyzeNode(Pattern->getTree(0));
2086     return true;
2087   }
2088
2089 private:
2090   void AnalyzeNode(const TreePatternNode *N) {
2091     if (N->isLeaf()) {
2092       if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2093         Record *LeafRec = DI->getDef();
2094         // Handle ComplexPattern leaves.
2095         if (LeafRec->isSubClassOf("ComplexPattern")) {
2096           const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2097           if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2098           if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2099           if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2100         }
2101       }
2102       return;
2103     }
2104
2105     // Analyze children.
2106     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2107       AnalyzeNode(N->getChild(i));
2108
2109     // Ignore set nodes, which are not SDNodes.
2110     if (N->getOperator()->getName() == "set")
2111       return;
2112
2113     // Get information about the SDNode for the operator.
2114     const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2115
2116     // Notice properties of the node.
2117     if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2118     if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2119     if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2120     if (OpInfo.hasProperty(SDNPVariadic)) IsVariadic = true;
2121
2122     if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2123       // If this is an intrinsic, analyze it.
2124       if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2125         mayLoad = true;// These may load memory.
2126
2127       if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
2128         mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2129
2130       if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
2131         // WriteMem intrinsics can have other strange effects.
2132         HasSideEffects = true;
2133     }
2134   }
2135
2136 };
2137
2138 static void InferFromPattern(const CodeGenInstruction &Inst,
2139                              bool &MayStore, bool &MayLoad,
2140                              bool &HasSideEffects, bool &IsVariadic,
2141                              const CodeGenDAGPatterns &CDP) {
2142   MayStore = MayLoad = HasSideEffects = IsVariadic = false;
2143
2144   bool HadPattern =
2145     InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects, IsVariadic)
2146     .Analyze(Inst.TheDef);
2147
2148   // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2149   if (Inst.mayStore) {  // If the .td file explicitly sets mayStore, use it.
2150     // If we decided that this is a store from the pattern, then the .td file
2151     // entry is redundant.
2152     if (MayStore)
2153       fprintf(stderr,
2154               "Warning: mayStore flag explicitly set on instruction '%s'"
2155               " but flag already inferred from pattern.\n",
2156               Inst.TheDef->getName().c_str());
2157     MayStore = true;
2158   }
2159
2160   if (Inst.mayLoad) {  // If the .td file explicitly sets mayLoad, use it.
2161     // If we decided that this is a load from the pattern, then the .td file
2162     // entry is redundant.
2163     if (MayLoad)
2164       fprintf(stderr,
2165               "Warning: mayLoad flag explicitly set on instruction '%s'"
2166               " but flag already inferred from pattern.\n",
2167               Inst.TheDef->getName().c_str());
2168     MayLoad = true;
2169   }
2170
2171   if (Inst.neverHasSideEffects) {
2172     if (HadPattern)
2173       fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2174               "which already has a pattern\n", Inst.TheDef->getName().c_str());
2175     HasSideEffects = false;
2176   }
2177
2178   if (Inst.hasSideEffects) {
2179     if (HasSideEffects)
2180       fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2181               "which already inferred this.\n", Inst.TheDef->getName().c_str());
2182     HasSideEffects = true;
2183   }
2184   
2185   if (Inst.isVariadic)
2186     IsVariadic = true;  // Can warn if we want.
2187 }
2188
2189 /// ParseInstructions - Parse all of the instructions, inlining and resolving
2190 /// any fragments involved.  This populates the Instructions list with fully
2191 /// resolved instructions.
2192 void CodeGenDAGPatterns::ParseInstructions() {
2193   std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2194   
2195   for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2196     ListInit *LI = 0;
2197     
2198     if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2199       LI = Instrs[i]->getValueAsListInit("Pattern");
2200     
2201     // If there is no pattern, only collect minimal information about the
2202     // instruction for its operand list.  We have to assume that there is one
2203     // result, as we have no detailed info.
2204     if (!LI || LI->getSize() == 0) {
2205       std::vector<Record*> Results;
2206       std::vector<Record*> Operands;
2207       
2208       CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
2209
2210       if (InstInfo.OperandList.size() != 0) {
2211         if (InstInfo.NumDefs == 0) {
2212           // These produce no results
2213           for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
2214             Operands.push_back(InstInfo.OperandList[j].Rec);
2215         } else {
2216           // Assume the first operand is the result.
2217           Results.push_back(InstInfo.OperandList[0].Rec);
2218       
2219           // The rest are inputs.
2220           for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
2221             Operands.push_back(InstInfo.OperandList[j].Rec);
2222         }
2223       }
2224       
2225       // Create and insert the instruction.
2226       std::vector<Record*> ImpResults;
2227       std::vector<Record*> ImpOperands;
2228       Instructions.insert(std::make_pair(Instrs[i], 
2229                           DAGInstruction(0, Results, Operands, ImpResults,
2230                                          ImpOperands)));
2231       continue;  // no pattern.
2232     }
2233     
2234     // Parse the instruction.
2235     TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2236     // Inline pattern fragments into it.
2237     I->InlinePatternFragments();
2238     
2239     // Infer as many types as possible.  If we cannot infer all of them, we can
2240     // never do anything with this instruction pattern: report it to the user.
2241     if (!I->InferAllTypes())
2242       I->error("Could not infer all types in pattern!");
2243     
2244     // InstInputs - Keep track of all of the inputs of the instruction, along 
2245     // with the record they are declared as.
2246     std::map<std::string, TreePatternNode*> InstInputs;
2247     
2248     // InstResults - Keep track of all the virtual registers that are 'set'
2249     // in the instruction, including what reg class they are.
2250     std::map<std::string, TreePatternNode*> InstResults;
2251
2252     std::vector<Record*> InstImpInputs;
2253     std::vector<Record*> InstImpResults;
2254     
2255     // Verify that the top-level forms in the instruction are of void type, and
2256     // fill in the InstResults map.
2257     for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2258       TreePatternNode *Pat = I->getTree(j);
2259       if (Pat->getNumTypes() != 0)
2260         I->error("Top-level forms in instruction pattern should have"
2261                  " void types");
2262
2263       // Find inputs and outputs, and verify the structure of the uses/defs.
2264       FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2265                                   InstImpInputs, InstImpResults);
2266     }
2267
2268     // Now that we have inputs and outputs of the pattern, inspect the operands
2269     // list for the instruction.  This determines the order that operands are
2270     // added to the machine instruction the node corresponds to.
2271     unsigned NumResults = InstResults.size();
2272
2273     // Parse the operands list from the (ops) list, validating it.
2274     assert(I->getArgList().empty() && "Args list should still be empty here!");
2275     CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
2276
2277     // Check that all of the results occur first in the list.
2278     std::vector<Record*> Results;
2279     TreePatternNode *Res0Node = 0;
2280     for (unsigned i = 0; i != NumResults; ++i) {
2281       if (i == CGI.OperandList.size())
2282         I->error("'" + InstResults.begin()->first +
2283                  "' set but does not appear in operand list!");
2284       const std::string &OpName = CGI.OperandList[i].Name;
2285       
2286       // Check that it exists in InstResults.
2287       TreePatternNode *RNode = InstResults[OpName];
2288       if (RNode == 0)
2289         I->error("Operand $" + OpName + " does not exist in operand list!");
2290         
2291       if (i == 0)
2292         Res0Node = RNode;
2293       Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2294       if (R == 0)
2295         I->error("Operand $" + OpName + " should be a set destination: all "
2296                  "outputs must occur before inputs in operand list!");
2297       
2298       if (CGI.OperandList[i].Rec != R)
2299         I->error("Operand $" + OpName + " class mismatch!");
2300       
2301       // Remember the return type.
2302       Results.push_back(CGI.OperandList[i].Rec);
2303       
2304       // Okay, this one checks out.
2305       InstResults.erase(OpName);
2306     }
2307
2308     // Loop over the inputs next.  Make a copy of InstInputs so we can destroy
2309     // the copy while we're checking the inputs.
2310     std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2311
2312     std::vector<TreePatternNode*> ResultNodeOperands;
2313     std::vector<Record*> Operands;
2314     for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
2315       CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
2316       const std::string &OpName = Op.Name;
2317       if (OpName.empty())
2318         I->error("Operand #" + utostr(i) + " in operands list has no name!");
2319
2320       if (!InstInputsCheck.count(OpName)) {
2321         // If this is an predicate operand or optional def operand with an
2322         // DefaultOps set filled in, we can ignore this.  When we codegen it,
2323         // we will do so as always executed.
2324         if (Op.Rec->isSubClassOf("PredicateOperand") ||
2325             Op.Rec->isSubClassOf("OptionalDefOperand")) {
2326           // Does it have a non-empty DefaultOps field?  If so, ignore this
2327           // operand.
2328           if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2329             continue;
2330         }
2331         I->error("Operand $" + OpName +
2332                  " does not appear in the instruction pattern");
2333       }
2334       TreePatternNode *InVal = InstInputsCheck[OpName];
2335       InstInputsCheck.erase(OpName);   // It occurred, remove from map.
2336       
2337       if (InVal->isLeaf() &&
2338           dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2339         Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2340         if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2341           I->error("Operand $" + OpName + "'s register class disagrees"
2342                    " between the operand and pattern");
2343       }
2344       Operands.push_back(Op.Rec);
2345       
2346       // Construct the result for the dest-pattern operand list.
2347       TreePatternNode *OpNode = InVal->clone();
2348       
2349       // No predicate is useful on the result.
2350       OpNode->clearPredicateFns();
2351       
2352       // Promote the xform function to be an explicit node if set.
2353       if (Record *Xform = OpNode->getTransformFn()) {
2354         OpNode->setTransformFn(0);
2355         std::vector<TreePatternNode*> Children;
2356         Children.push_back(OpNode);
2357         OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
2358       }
2359       
2360       ResultNodeOperands.push_back(OpNode);
2361     }
2362     
2363     if (!InstInputsCheck.empty())
2364       I->error("Input operand $" + InstInputsCheck.begin()->first +
2365                " occurs in pattern but not in operands list!");
2366
2367     TreePatternNode *ResultPattern =
2368       new TreePatternNode(I->getRecord(), ResultNodeOperands,
2369                           GetNumNodeResults(I->getRecord(), *this));
2370     // Copy fully inferred output node type to instruction result pattern.
2371     for (unsigned i = 0; i != NumResults; ++i)
2372       ResultPattern->setType(i, Res0Node->getExtType(i));
2373
2374     // Create and insert the instruction.
2375     // FIXME: InstImpResults and InstImpInputs should not be part of
2376     // DAGInstruction.
2377     DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
2378     Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2379
2380     // Use a temporary tree pattern to infer all types and make sure that the
2381     // constructed result is correct.  This depends on the instruction already
2382     // being inserted into the Instructions map.
2383     TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
2384     Temp.InferAllTypes(&I->getNamedNodesMap());
2385
2386     DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2387     TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2388     
2389     DEBUG(I->dump());
2390   }
2391    
2392   // If we can, convert the instructions to be patterns that are matched!
2393   for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2394         Instructions.begin(),
2395        E = Instructions.end(); II != E; ++II) {
2396     DAGInstruction &TheInst = II->second;
2397     const TreePattern *I = TheInst.getPattern();
2398     if (I == 0) continue;  // No pattern.
2399
2400     // FIXME: Assume only the first tree is the pattern. The others are clobber
2401     // nodes.
2402     TreePatternNode *Pattern = I->getTree(0);
2403     TreePatternNode *SrcPattern;
2404     if (Pattern->getOperator()->getName() == "set") {
2405       SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2406     } else{
2407       // Not a set (store or something?)
2408       SrcPattern = Pattern;
2409     }
2410     
2411     Record *Instr = II->first;
2412     AddPatternToMatch(I,
2413                       PatternToMatch(Instr->getValueAsListInit("Predicates"),
2414                                      SrcPattern,
2415                                      TheInst.getResultPattern(),
2416                                      TheInst.getImpResults(),
2417                                      Instr->getValueAsInt("AddedComplexity"),
2418                                      Instr->getID()));
2419   }
2420 }
2421
2422
2423 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2424
2425 static void FindNames(const TreePatternNode *P, 
2426                       std::map<std::string, NameRecord> &Names,
2427                       const TreePattern *PatternTop) {
2428   if (!P->getName().empty()) {
2429     NameRecord &Rec = Names[P->getName()];
2430     // If this is the first instance of the name, remember the node.
2431     if (Rec.second++ == 0)
2432       Rec.first = P;
2433     else if (Rec.first->getExtTypes() != P->getExtTypes())
2434       PatternTop->error("repetition of value: $" + P->getName() +
2435                         " where different uses have different types!");
2436   }
2437   
2438   if (!P->isLeaf()) {
2439     for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2440       FindNames(P->getChild(i), Names, PatternTop);
2441   }
2442 }
2443
2444 void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2445                                            const PatternToMatch &PTM) {
2446   // Do some sanity checking on the pattern we're about to match.
2447   std::string Reason;
2448   if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
2449     Pattern->error("Pattern can never match: " + Reason);
2450   
2451   // If the source pattern's root is a complex pattern, that complex pattern
2452   // must specify the nodes it can potentially match.
2453   if (const ComplexPattern *CP =
2454         PTM.getSrcPattern()->getComplexPatternInfo(*this))
2455     if (CP->getRootNodes().empty())
2456       Pattern->error("ComplexPattern at root must specify list of opcodes it"
2457                      " could match");
2458   
2459   
2460   // Find all of the named values in the input and output, ensure they have the
2461   // same type.
2462   std::map<std::string, NameRecord> SrcNames, DstNames;
2463   FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2464   FindNames(PTM.getDstPattern(), DstNames, Pattern);
2465
2466   // Scan all of the named values in the destination pattern, rejecting them if
2467   // they don't exist in the input pattern.
2468   for (std::map<std::string, NameRecord>::iterator
2469        I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
2470     if (SrcNames[I->first].first == 0)
2471       Pattern->error("Pattern has input without matching name in output: $" +
2472                      I->first);
2473   }
2474   
2475   // Scan all of the named values in the source pattern, rejecting them if the
2476   // name isn't used in the dest, and isn't used to tie two values together.
2477   for (std::map<std::string, NameRecord>::iterator
2478        I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2479     if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2480       Pattern->error("Pattern has dead named input: $" + I->first);
2481   
2482   PatternsToMatch.push_back(PTM);
2483 }
2484
2485
2486
2487 void CodeGenDAGPatterns::InferInstructionFlags() {
2488   const std::vector<const CodeGenInstruction*> &Instructions =
2489     Target.getInstructionsByEnumValue();
2490   for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2491     CodeGenInstruction &InstInfo =
2492       const_cast<CodeGenInstruction &>(*Instructions[i]);
2493     // Determine properties of the instruction from its pattern.
2494     bool MayStore, MayLoad, HasSideEffects, IsVariadic;
2495     InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, IsVariadic,
2496                      *this);
2497     InstInfo.mayStore = MayStore;
2498     InstInfo.mayLoad = MayLoad;
2499     InstInfo.hasSideEffects = HasSideEffects;
2500     InstInfo.isVariadic = IsVariadic;
2501   }
2502 }
2503
2504 /// Given a pattern result with an unresolved type, see if we can find one
2505 /// instruction with an unresolved result type.  Force this result type to an
2506 /// arbitrary element if it's possible types to converge results.
2507 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2508   if (N->isLeaf())
2509     return false;
2510   
2511   // Analyze children.
2512   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2513     if (ForceArbitraryInstResultType(N->getChild(i), TP))
2514       return true;
2515
2516   if (!N->getOperator()->isSubClassOf("Instruction"))
2517     return false;
2518
2519   // If this type is already concrete or completely unknown we can't do
2520   // anything.
2521   for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
2522     if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
2523       continue;
2524   
2525     // Otherwise, force its type to the first possibility (an arbitrary choice).
2526     if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
2527       return true;
2528   }
2529   
2530   return false;
2531 }
2532
2533 void CodeGenDAGPatterns::ParsePatterns() {
2534   std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2535
2536   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2537     Record *CurPattern = Patterns[i];
2538     DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
2539     TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
2540
2541     // Inline pattern fragments into it.
2542     Pattern->InlinePatternFragments();
2543     
2544     ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
2545     if (LI->getSize() == 0) continue;  // no pattern.
2546     
2547     // Parse the instruction.
2548     TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
2549     
2550     // Inline pattern fragments into it.
2551     Result->InlinePatternFragments();
2552
2553     if (Result->getNumTrees() != 1)
2554       Result->error("Cannot handle instructions producing instructions "
2555                     "with temporaries yet!");
2556     
2557     bool IterateInference;
2558     bool InferredAllPatternTypes, InferredAllResultTypes;
2559     do {
2560       // Infer as many types as possible.  If we cannot infer all of them, we
2561       // can never do anything with this pattern: report it to the user.
2562       InferredAllPatternTypes =
2563         Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
2564       
2565       // Infer as many types as possible.  If we cannot infer all of them, we
2566       // can never do anything with this pattern: report it to the user.
2567       InferredAllResultTypes =
2568         Result->InferAllTypes(&Pattern->getNamedNodesMap());
2569
2570       IterateInference = false;
2571       
2572       // Apply the type of the result to the source pattern.  This helps us
2573       // resolve cases where the input type is known to be a pointer type (which
2574       // is considered resolved), but the result knows it needs to be 32- or
2575       // 64-bits.  Infer the other way for good measure.
2576       for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
2577                                         Pattern->getTree(0)->getNumTypes());
2578            i != e; ++i) {
2579         IterateInference = Pattern->getTree(0)->
2580           UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
2581         IterateInference |= Result->getTree(0)->
2582           UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
2583       }
2584       
2585       // If our iteration has converged and the input pattern's types are fully
2586       // resolved but the result pattern is not fully resolved, we may have a
2587       // situation where we have two instructions in the result pattern and
2588       // the instructions require a common register class, but don't care about
2589       // what actual MVT is used.  This is actually a bug in our modelling:
2590       // output patterns should have register classes, not MVTs.
2591       //
2592       // In any case, to handle this, we just go through and disambiguate some
2593       // arbitrary types to the result pattern's nodes.
2594       if (!IterateInference && InferredAllPatternTypes &&
2595           !InferredAllResultTypes)
2596         IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2597                                                         *Result);
2598     } while (IterateInference);
2599     
2600     // Verify that we inferred enough types that we can do something with the
2601     // pattern and result.  If these fire the user has to add type casts.
2602     if (!InferredAllPatternTypes)
2603       Pattern->error("Could not infer all types in pattern!");
2604     if (!InferredAllResultTypes) {
2605       Pattern->dump();
2606       Result->error("Could not infer all types in pattern result!");
2607     }
2608     
2609     // Validate that the input pattern is correct.
2610     std::map<std::string, TreePatternNode*> InstInputs;
2611     std::map<std::string, TreePatternNode*> InstResults;
2612     std::vector<Record*> InstImpInputs;
2613     std::vector<Record*> InstImpResults;
2614     for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2615       FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2616                                   InstInputs, InstResults,
2617                                   InstImpInputs, InstImpResults);
2618
2619     // Promote the xform function to be an explicit node if set.
2620     TreePatternNode *DstPattern = Result->getOnlyTree();
2621     std::vector<TreePatternNode*> ResultNodeOperands;
2622     for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2623       TreePatternNode *OpNode = DstPattern->getChild(ii);
2624       if (Record *Xform = OpNode->getTransformFn()) {
2625         OpNode->setTransformFn(0);
2626         std::vector<TreePatternNode*> Children;
2627         Children.push_back(OpNode);
2628         OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
2629       }
2630       ResultNodeOperands.push_back(OpNode);
2631     }
2632     DstPattern = Result->getOnlyTree();
2633     if (!DstPattern->isLeaf())
2634       DstPattern = new TreePatternNode(DstPattern->getOperator(),
2635                                        ResultNodeOperands,
2636                                        DstPattern->getNumTypes());
2637     
2638     for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
2639       DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
2640     
2641     TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2642     Temp.InferAllTypes();
2643
2644     
2645     AddPatternToMatch(Pattern,
2646                     PatternToMatch(CurPattern->getValueAsListInit("Predicates"),
2647                                    Pattern->getTree(0),
2648                                    Temp.getOnlyTree(), InstImpResults,
2649                                    CurPattern->getValueAsInt("AddedComplexity"),
2650                                    CurPattern->getID()));
2651   }
2652 }
2653
2654 /// CombineChildVariants - Given a bunch of permutations of each child of the
2655 /// 'operator' node, put them together in all possible ways.
2656 static void CombineChildVariants(TreePatternNode *Orig, 
2657                const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2658                                  std::vector<TreePatternNode*> &OutVariants,
2659                                  CodeGenDAGPatterns &CDP,
2660                                  const MultipleUseVarSet &DepVars) {
2661   // Make sure that each operand has at least one variant to choose from.
2662   for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2663     if (ChildVariants[i].empty())
2664       return;
2665         
2666   // The end result is an all-pairs construction of the resultant pattern.
2667   std::vector<unsigned> Idxs;
2668   Idxs.resize(ChildVariants.size());
2669   bool NotDone;
2670   do {
2671 #ifndef NDEBUG
2672     DEBUG(if (!Idxs.empty()) {
2673             errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2674               for (unsigned i = 0; i < Idxs.size(); ++i) {
2675                 errs() << Idxs[i] << " ";
2676             }
2677             errs() << "]\n";
2678           });
2679 #endif
2680     // Create the variant and add it to the output list.
2681     std::vector<TreePatternNode*> NewChildren;
2682     for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2683       NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2684     TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
2685                                              Orig->getNumTypes());
2686     
2687     // Copy over properties.
2688     R->setName(Orig->getName());
2689     R->setPredicateFns(Orig->getPredicateFns());
2690     R->setTransformFn(Orig->getTransformFn());
2691     for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
2692       R->setType(i, Orig->getExtType(i));
2693     
2694     // If this pattern cannot match, do not include it as a variant.
2695     std::string ErrString;
2696     if (!R->canPatternMatch(ErrString, CDP)) {
2697       delete R;
2698     } else {
2699       bool AlreadyExists = false;
2700       
2701       // Scan to see if this pattern has already been emitted.  We can get
2702       // duplication due to things like commuting:
2703       //   (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2704       // which are the same pattern.  Ignore the dups.
2705       for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
2706         if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
2707           AlreadyExists = true;
2708           break;
2709         }
2710       
2711       if (AlreadyExists)
2712         delete R;
2713       else
2714         OutVariants.push_back(R);
2715     }
2716     
2717     // Increment indices to the next permutation by incrementing the
2718     // indicies from last index backward, e.g., generate the sequence
2719     // [0, 0], [0, 1], [1, 0], [1, 1].
2720     int IdxsIdx;
2721     for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2722       if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2723         Idxs[IdxsIdx] = 0;
2724       else
2725         break;
2726     }
2727     NotDone = (IdxsIdx >= 0);
2728   } while (NotDone);
2729 }
2730
2731 /// CombineChildVariants - A helper function for binary operators.
2732 ///
2733 static void CombineChildVariants(TreePatternNode *Orig, 
2734                                  const std::vector<TreePatternNode*> &LHS,
2735                                  const std::vector<TreePatternNode*> &RHS,
2736                                  std::vector<TreePatternNode*> &OutVariants,
2737                                  CodeGenDAGPatterns &CDP,
2738                                  const MultipleUseVarSet &DepVars) {
2739   std::vector<std::vector<TreePatternNode*> > ChildVariants;
2740   ChildVariants.push_back(LHS);
2741   ChildVariants.push_back(RHS);
2742   CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
2743 }  
2744
2745
2746 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2747                                      std::vector<TreePatternNode *> &Children) {
2748   assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2749   Record *Operator = N->getOperator();
2750   
2751   // Only permit raw nodes.
2752   if (!N->getName().empty() || !N->getPredicateFns().empty() ||
2753       N->getTransformFn()) {
2754     Children.push_back(N);
2755     return;
2756   }
2757
2758   if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2759     Children.push_back(N->getChild(0));
2760   else
2761     GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2762
2763   if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2764     Children.push_back(N->getChild(1));
2765   else
2766     GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2767 }
2768
2769 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2770 /// the (potentially recursive) pattern by using algebraic laws.
2771 ///
2772 static void GenerateVariantsOf(TreePatternNode *N,
2773                                std::vector<TreePatternNode*> &OutVariants,
2774                                CodeGenDAGPatterns &CDP,
2775                                const MultipleUseVarSet &DepVars) {
2776   // We cannot permute leaves.
2777   if (N->isLeaf()) {
2778     OutVariants.push_back(N);
2779     return;
2780   }
2781
2782   // Look up interesting info about the node.
2783   const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2784
2785   // If this node is associative, re-associate.
2786   if (NodeInfo.hasProperty(SDNPAssociative)) {
2787     // Re-associate by pulling together all of the linked operators 
2788     std::vector<TreePatternNode*> MaximalChildren;
2789     GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2790
2791     // Only handle child sizes of 3.  Otherwise we'll end up trying too many
2792     // permutations.
2793     if (MaximalChildren.size() == 3) {
2794       // Find the variants of all of our maximal children.
2795       std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
2796       GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2797       GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2798       GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
2799       
2800       // There are only two ways we can permute the tree:
2801       //   (A op B) op C    and    A op (B op C)
2802       // Within these forms, we can also permute A/B/C.
2803       
2804       // Generate legal pair permutations of A/B/C.
2805       std::vector<TreePatternNode*> ABVariants;
2806       std::vector<TreePatternNode*> BAVariants;
2807       std::vector<TreePatternNode*> ACVariants;
2808       std::vector<TreePatternNode*> CAVariants;
2809       std::vector<TreePatternNode*> BCVariants;
2810       std::vector<TreePatternNode*> CBVariants;
2811       CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2812       CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2813       CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2814       CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2815       CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2816       CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
2817
2818       // Combine those into the result: (x op x) op x
2819       CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2820       CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2821       CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2822       CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2823       CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2824       CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
2825
2826       // Combine those into the result: x op (x op x)
2827       CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2828       CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2829       CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2830       CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2831       CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2832       CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
2833       return;
2834     }
2835   }
2836   
2837   // Compute permutations of all children.
2838   std::vector<std::vector<TreePatternNode*> > ChildVariants;
2839   ChildVariants.resize(N->getNumChildren());
2840   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2841     GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
2842
2843   // Build all permutations based on how the children were formed.
2844   CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
2845
2846   // If this node is commutative, consider the commuted order.
2847   bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2848   if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2849     assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2850            "Commutative but doesn't have 2 children!");
2851     // Don't count children which are actually register references.
2852     unsigned NC = 0;
2853     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2854       TreePatternNode *Child = N->getChild(i);
2855       if (Child->isLeaf())
2856         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2857           Record *RR = DI->getDef();
2858           if (RR->isSubClassOf("Register"))
2859             continue;
2860         }
2861       NC++;
2862     }
2863     // Consider the commuted order.
2864     if (isCommIntrinsic) {
2865       // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2866       // operands are the commutative operands, and there might be more operands
2867       // after those.
2868       assert(NC >= 3 &&
2869              "Commutative intrinsic should have at least 3 childrean!");
2870       std::vector<std::vector<TreePatternNode*> > Variants;
2871       Variants.push_back(ChildVariants[0]); // Intrinsic id.
2872       Variants.push_back(ChildVariants[2]);
2873       Variants.push_back(ChildVariants[1]);
2874       for (unsigned i = 3; i != NC; ++i)
2875         Variants.push_back(ChildVariants[i]);
2876       CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2877     } else if (NC == 2)
2878       CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
2879                            OutVariants, CDP, DepVars);
2880   }
2881 }
2882
2883
2884 // GenerateVariants - Generate variants.  For example, commutative patterns can
2885 // match multiple ways.  Add them to PatternsToMatch as well.
2886 void CodeGenDAGPatterns::GenerateVariants() {
2887   DEBUG(errs() << "Generating instruction variants.\n");
2888   
2889   // Loop over all of the patterns we've collected, checking to see if we can
2890   // generate variants of the instruction, through the exploitation of
2891   // identities.  This permits the target to provide aggressive matching without
2892   // the .td file having to contain tons of variants of instructions.
2893   //
2894   // Note that this loop adds new patterns to the PatternsToMatch list, but we
2895   // intentionally do not reconsider these.  Any variants of added patterns have
2896   // already been added.
2897   //
2898   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2899     MultipleUseVarSet             DepVars;
2900     std::vector<TreePatternNode*> Variants;
2901     FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
2902     DEBUG(errs() << "Dependent/multiply used variables: ");
2903     DEBUG(DumpDepVars(DepVars));
2904     DEBUG(errs() << "\n");
2905     GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
2906
2907     assert(!Variants.empty() && "Must create at least original variant!");
2908     Variants.erase(Variants.begin());  // Remove the original pattern.
2909
2910     if (Variants.empty())  // No variants for this pattern.
2911       continue;
2912
2913     DEBUG(errs() << "FOUND VARIANTS OF: ";
2914           PatternsToMatch[i].getSrcPattern()->dump();
2915           errs() << "\n");
2916
2917     for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2918       TreePatternNode *Variant = Variants[v];
2919
2920       DEBUG(errs() << "  VAR#" << v <<  ": ";
2921             Variant->dump();
2922             errs() << "\n");
2923       
2924       // Scan to see if an instruction or explicit pattern already matches this.
2925       bool AlreadyExists = false;
2926       for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2927         // Skip if the top level predicates do not match.
2928         if (PatternsToMatch[i].getPredicates() !=
2929             PatternsToMatch[p].getPredicates())
2930           continue;
2931         // Check to see if this variant already exists.
2932         if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
2933           DEBUG(errs() << "  *** ALREADY EXISTS, ignoring variant.\n");
2934           AlreadyExists = true;
2935           break;
2936         }
2937       }
2938       // If we already have it, ignore the variant.
2939       if (AlreadyExists) continue;
2940
2941       // Otherwise, add it to the list of patterns we have.
2942       PatternsToMatch.
2943         push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2944                                  Variant, PatternsToMatch[i].getDstPattern(),
2945                                  PatternsToMatch[i].getDstRegs(),
2946                                  PatternsToMatch[i].getAddedComplexity(),
2947                                  Record::getNewUID()));
2948     }
2949
2950     DEBUG(errs() << "\n");
2951   }
2952 }
2953