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