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