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