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