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