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