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/BitVector.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/TableGen/Error.h"
27 #include "llvm/TableGen/Record.h"
28 #include <algorithm>
29 #include <cstdio>
30 #include <set>
31 using namespace llvm;
32 
33 #define DEBUG_TYPE "dag-patterns"
34 
35 static inline bool isIntegerOrPtr(MVT VT) {
36   return VT.isInteger() || VT == MVT::iPTR;
37 }
38 static inline bool isFloatingPoint(MVT VT) {
39   return VT.isFloatingPoint();
40 }
41 static inline bool isVector(MVT VT) {
42   return VT.isVector();
43 }
44 static inline bool isScalar(MVT VT) {
45   return !VT.isVector();
46 }
47 
48 template <typename Predicate>
49 static bool berase_if(MachineValueTypeSet &S, Predicate P) {
50   bool Erased = false;
51   // It is ok to iterate over MachineValueTypeSet and remove elements from it
52   // at the same time.
53   for (MVT T : S) {
54     if (!P(T))
55       continue;
56     Erased = true;
57     S.erase(T);
58   }
59   return Erased;
60 }
61 
62 // --- TypeSetByHwMode
63 
64 // This is a parameterized type-set class. For each mode there is a list
65 // of types that are currently possible for a given tree node. Type
66 // inference will apply to each mode separately.
67 
68 TypeSetByHwMode::TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList) {
69   for (const ValueTypeByHwMode &VVT : VTList)
70     insert(VVT);
71 }
72 
73 bool TypeSetByHwMode::isValueTypeByHwMode(bool AllowEmpty) const {
74   for (const auto &I : *this) {
75     if (I.second.size() > 1)
76       return false;
77     if (!AllowEmpty && I.second.empty())
78       return false;
79   }
80   return true;
81 }
82 
83 ValueTypeByHwMode TypeSetByHwMode::getValueTypeByHwMode() const {
84   assert(isValueTypeByHwMode(true) &&
85          "The type set has multiple types for at least one HW mode");
86   ValueTypeByHwMode VVT;
87   for (const auto &I : *this) {
88     MVT T = I.second.empty() ? MVT::Other : *I.second.begin();
89     VVT.getOrCreateTypeForMode(I.first, T);
90   }
91   return VVT;
92 }
93 
94 bool TypeSetByHwMode::isPossible() const {
95   for (const auto &I : *this)
96     if (!I.second.empty())
97       return true;
98   return false;
99 }
100 
101 bool TypeSetByHwMode::insert(const ValueTypeByHwMode &VVT) {
102   bool Changed = false;
103   bool ContainsDefault = false;
104   MVT DT = MVT::Other;
105 
106   SmallDenseSet<unsigned, 4> Modes;
107   for (const auto &P : VVT) {
108     unsigned M = P.first;
109     Modes.insert(M);
110     // Make sure there exists a set for each specific mode from VVT.
111     Changed |= getOrCreate(M).insert(P.second).second;
112     // Cache VVT's default mode.
113     if (DefaultMode == M) {
114       ContainsDefault = true;
115       DT = P.second;
116     }
117   }
118 
119   // If VVT has a default mode, add the corresponding type to all
120   // modes in "this" that do not exist in VVT.
121   if (ContainsDefault)
122     for (auto &I : *this)
123       if (!Modes.count(I.first))
124         Changed |= I.second.insert(DT).second;
125 
126   return Changed;
127 }
128 
129 // Constrain the type set to be the intersection with VTS.
130 bool TypeSetByHwMode::constrain(const TypeSetByHwMode &VTS) {
131   bool Changed = false;
132   if (hasDefault()) {
133     for (const auto &I : VTS) {
134       unsigned M = I.first;
135       if (M == DefaultMode || hasMode(M))
136         continue;
137       Map.insert({M, Map.at(DefaultMode)});
138       Changed = true;
139     }
140   }
141 
142   for (auto &I : *this) {
143     unsigned M = I.first;
144     SetType &S = I.second;
145     if (VTS.hasMode(M) || VTS.hasDefault()) {
146       Changed |= intersect(I.second, VTS.get(M));
147     } else if (!S.empty()) {
148       S.clear();
149       Changed = true;
150     }
151   }
152   return Changed;
153 }
154 
155 template <typename Predicate>
156 bool TypeSetByHwMode::constrain(Predicate P) {
157   bool Changed = false;
158   for (auto &I : *this)
159     Changed |= berase_if(I.second, [&P](MVT VT) { return !P(VT); });
160   return Changed;
161 }
162 
163 template <typename Predicate>
164 bool TypeSetByHwMode::assign_if(const TypeSetByHwMode &VTS, Predicate P) {
165   assert(empty());
166   for (const auto &I : VTS) {
167     SetType &S = getOrCreate(I.first);
168     for (auto J : I.second)
169       if (P(J))
170         S.insert(J);
171   }
172   return !empty();
173 }
174 
175 void TypeSetByHwMode::writeToStream(raw_ostream &OS) const {
176   SmallVector<unsigned, 4> Modes;
177   Modes.reserve(Map.size());
178 
179   for (const auto &I : *this)
180     Modes.push_back(I.first);
181   if (Modes.empty()) {
182     OS << "{}";
183     return;
184   }
185   array_pod_sort(Modes.begin(), Modes.end());
186 
187   OS << '{';
188   for (unsigned M : Modes) {
189     OS << ' ' << getModeName(M) << ':';
190     writeToStream(get(M), OS);
191   }
192   OS << " }";
193 }
194 
195 void TypeSetByHwMode::writeToStream(const SetType &S, raw_ostream &OS) {
196   SmallVector<MVT, 4> Types(S.begin(), S.end());
197   array_pod_sort(Types.begin(), Types.end());
198 
199   OS << '[';
200   for (unsigned i = 0, e = Types.size(); i != e; ++i) {
201     OS << ValueTypeByHwMode::getMVTName(Types[i]);
202     if (i != e-1)
203       OS << ' ';
204   }
205   OS << ']';
206 }
207 
208 bool TypeSetByHwMode::operator==(const TypeSetByHwMode &VTS) const {
209   // The isSimple call is much quicker than hasDefault - check this first.
210   bool IsSimple = isSimple();
211   bool VTSIsSimple = VTS.isSimple();
212   if (IsSimple && VTSIsSimple)
213     return *begin() == *VTS.begin();
214 
215   // Speedup: We have a default if the set is simple.
216   bool HaveDefault = IsSimple || hasDefault();
217   bool VTSHaveDefault = VTSIsSimple || VTS.hasDefault();
218   if (HaveDefault != VTSHaveDefault)
219     return false;
220 
221   SmallDenseSet<unsigned, 4> Modes;
222   for (auto &I : *this)
223     Modes.insert(I.first);
224   for (const auto &I : VTS)
225     Modes.insert(I.first);
226 
227   if (HaveDefault) {
228     // Both sets have default mode.
229     for (unsigned M : Modes) {
230       if (get(M) != VTS.get(M))
231         return false;
232     }
233   } else {
234     // Neither set has default mode.
235     for (unsigned M : Modes) {
236       // If there is no default mode, an empty set is equivalent to not having
237       // the corresponding mode.
238       bool NoModeThis = !hasMode(M) || get(M).empty();
239       bool NoModeVTS = !VTS.hasMode(M) || VTS.get(M).empty();
240       if (NoModeThis != NoModeVTS)
241         return false;
242       if (!NoModeThis)
243         if (get(M) != VTS.get(M))
244           return false;
245     }
246   }
247 
248   return true;
249 }
250 
251 namespace llvm {
252   raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T) {
253     T.writeToStream(OS);
254     return OS;
255   }
256 }
257 
258 LLVM_DUMP_METHOD
259 void TypeSetByHwMode::dump() const {
260   dbgs() << *this << '\n';
261 }
262 
263 bool TypeSetByHwMode::intersect(SetType &Out, const SetType &In) {
264   bool OutP = Out.count(MVT::iPTR), InP = In.count(MVT::iPTR);
265   auto Int = [&In](MVT T) -> bool { return !In.count(T); };
266 
267   if (OutP == InP)
268     return berase_if(Out, Int);
269 
270   // Compute the intersection of scalars separately to account for only
271   // one set containing iPTR.
272   // The itersection of iPTR with a set of integer scalar types that does not
273   // include iPTR will result in the most specific scalar type:
274   // - iPTR is more specific than any set with two elements or more
275   // - iPTR is less specific than any single integer scalar type.
276   // For example
277   // { iPTR } * { i32 }     -> { i32 }
278   // { iPTR } * { i32 i64 } -> { iPTR }
279   // and
280   // { iPTR i32 } * { i32 }          -> { i32 }
281   // { iPTR i32 } * { i32 i64 }      -> { i32 i64 }
282   // { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 }
283 
284   // Compute the difference between the two sets in such a way that the
285   // iPTR is in the set that is being subtracted. This is to see if there
286   // are any extra scalars in the set without iPTR that are not in the
287   // set containing iPTR. Then the iPTR could be considered a "wildcard"
288   // matching these scalars. If there is only one such scalar, it would
289   // replace the iPTR, if there are more, the iPTR would be retained.
290   SetType Diff;
291   if (InP) {
292     Diff = Out;
293     berase_if(Diff, [&In](MVT T) { return In.count(T); });
294     // Pre-remove these elements and rely only on InP/OutP to determine
295     // whether a change has been made.
296     berase_if(Out, [&Diff](MVT T) { return Diff.count(T); });
297   } else {
298     Diff = In;
299     berase_if(Diff, [&Out](MVT T) { return Out.count(T); });
300     Out.erase(MVT::iPTR);
301   }
302 
303   // The actual intersection.
304   bool Changed = berase_if(Out, Int);
305   unsigned NumD = Diff.size();
306   if (NumD == 0)
307     return Changed;
308 
309   if (NumD == 1) {
310     Out.insert(*Diff.begin());
311     // This is a change only if Out was the one with iPTR (which is now
312     // being replaced).
313     Changed |= OutP;
314   } else {
315     // Multiple elements from Out are now replaced with iPTR.
316     Out.insert(MVT::iPTR);
317     Changed |= !OutP;
318   }
319   return Changed;
320 }
321 
322 bool TypeSetByHwMode::validate() const {
323 #ifndef NDEBUG
324   if (empty())
325     return true;
326   bool AllEmpty = true;
327   for (const auto &I : *this)
328     AllEmpty &= I.second.empty();
329   return !AllEmpty;
330 #endif
331   return true;
332 }
333 
334 // --- TypeInfer
335 
336 bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,
337                                 const TypeSetByHwMode &In) {
338   ValidateOnExit _1(Out, *this);
339   In.validate();
340   if (In.empty() || Out == In || TP.hasError())
341     return false;
342   if (Out.empty()) {
343     Out = In;
344     return true;
345   }
346 
347   bool Changed = Out.constrain(In);
348   if (Changed && Out.empty())
349     TP.error("Type contradiction");
350 
351   return Changed;
352 }
353 
354 bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) {
355   ValidateOnExit _1(Out, *this);
356   if (TP.hasError())
357     return false;
358   assert(!Out.empty() && "cannot pick from an empty set");
359 
360   bool Changed = false;
361   for (auto &I : Out) {
362     TypeSetByHwMode::SetType &S = I.second;
363     if (S.size() <= 1)
364       continue;
365     MVT T = *S.begin(); // Pick the first element.
366     S.clear();
367     S.insert(T);
368     Changed = true;
369   }
370   return Changed;
371 }
372 
373 bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) {
374   ValidateOnExit _1(Out, *this);
375   if (TP.hasError())
376     return false;
377   if (!Out.empty())
378     return Out.constrain(isIntegerOrPtr);
379 
380   return Out.assign_if(getLegalTypes(), isIntegerOrPtr);
381 }
382 
383 bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode &Out) {
384   ValidateOnExit _1(Out, *this);
385   if (TP.hasError())
386     return false;
387   if (!Out.empty())
388     return Out.constrain(isFloatingPoint);
389 
390   return Out.assign_if(getLegalTypes(), isFloatingPoint);
391 }
392 
393 bool TypeInfer::EnforceScalar(TypeSetByHwMode &Out) {
394   ValidateOnExit _1(Out, *this);
395   if (TP.hasError())
396     return false;
397   if (!Out.empty())
398     return Out.constrain(isScalar);
399 
400   return Out.assign_if(getLegalTypes(), isScalar);
401 }
402 
403 bool TypeInfer::EnforceVector(TypeSetByHwMode &Out) {
404   ValidateOnExit _1(Out, *this);
405   if (TP.hasError())
406     return false;
407   if (!Out.empty())
408     return Out.constrain(isVector);
409 
410   return Out.assign_if(getLegalTypes(), isVector);
411 }
412 
413 bool TypeInfer::EnforceAny(TypeSetByHwMode &Out) {
414   ValidateOnExit _1(Out, *this);
415   if (TP.hasError() || !Out.empty())
416     return false;
417 
418   Out = getLegalTypes();
419   return true;
420 }
421 
422 template <typename Iter, typename Pred, typename Less>
423 static Iter min_if(Iter B, Iter E, Pred P, Less L) {
424   if (B == E)
425     return E;
426   Iter Min = E;
427   for (Iter I = B; I != E; ++I) {
428     if (!P(*I))
429       continue;
430     if (Min == E || L(*I, *Min))
431       Min = I;
432   }
433   return Min;
434 }
435 
436 template <typename Iter, typename Pred, typename Less>
437 static Iter max_if(Iter B, Iter E, Pred P, Less L) {
438   if (B == E)
439     return E;
440   Iter Max = E;
441   for (Iter I = B; I != E; ++I) {
442     if (!P(*I))
443       continue;
444     if (Max == E || L(*Max, *I))
445       Max = I;
446   }
447   return Max;
448 }
449 
450 /// Make sure that for each type in Small, there exists a larger type in Big.
451 bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode &Small,
452                                    TypeSetByHwMode &Big) {
453   ValidateOnExit _1(Small, *this), _2(Big, *this);
454   if (TP.hasError())
455     return false;
456   bool Changed = false;
457 
458   if (Small.empty())
459     Changed |= EnforceAny(Small);
460   if (Big.empty())
461     Changed |= EnforceAny(Big);
462 
463   assert(Small.hasDefault() && Big.hasDefault());
464 
465   std::vector<unsigned> Modes = union_modes(Small, Big);
466 
467   // 1. Only allow integer or floating point types and make sure that
468   //    both sides are both integer or both floating point.
469   // 2. Make sure that either both sides have vector types, or neither
470   //    of them does.
471   for (unsigned M : Modes) {
472     TypeSetByHwMode::SetType &S = Small.get(M);
473     TypeSetByHwMode::SetType &B = Big.get(M);
474 
475     if (any_of(S, isIntegerOrPtr) && any_of(S, isIntegerOrPtr)) {
476       auto NotInt = [](MVT VT) { return !isIntegerOrPtr(VT); };
477       Changed |= berase_if(S, NotInt) |
478                  berase_if(B, NotInt);
479     } else if (any_of(S, isFloatingPoint) && any_of(B, isFloatingPoint)) {
480       auto NotFP = [](MVT VT) { return !isFloatingPoint(VT); };
481       Changed |= berase_if(S, NotFP) |
482                  berase_if(B, NotFP);
483     } else if (S.empty() || B.empty()) {
484       Changed = !S.empty() || !B.empty();
485       S.clear();
486       B.clear();
487     } else {
488       TP.error("Incompatible types");
489       return Changed;
490     }
491 
492     if (none_of(S, isVector) || none_of(B, isVector)) {
493       Changed |= berase_if(S, isVector) |
494                  berase_if(B, isVector);
495     }
496   }
497 
498   auto LT = [](MVT A, MVT B) -> bool {
499     return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
500            (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
501             A.getSizeInBits() < B.getSizeInBits());
502   };
503   auto LE = [](MVT A, MVT B) -> bool {
504     // This function is used when removing elements: when a vector is compared
505     // to a non-vector, it should return false (to avoid removal).
506     if (A.isVector() != B.isVector())
507       return false;
508 
509     // Note on the < comparison below:
510     // X86 has patterns like
511     //   (set VR128X:$dst, (v16i8 (X86vtrunc (v4i32 VR128X:$src1)))),
512     // where the truncated vector is given a type v16i8, while the source
513     // vector has type v4i32. They both have the same size in bits.
514     // The minimal type in the result is obviously v16i8, and when we remove
515     // all types from the source that are smaller-or-equal than v8i16, the
516     // only source type would also be removed (since it's equal in size).
517     return A.getScalarSizeInBits() <= B.getScalarSizeInBits() ||
518            A.getSizeInBits() < B.getSizeInBits();
519   };
520 
521   for (unsigned M : Modes) {
522     TypeSetByHwMode::SetType &S = Small.get(M);
523     TypeSetByHwMode::SetType &B = Big.get(M);
524     // MinS = min scalar in Small, remove all scalars from Big that are
525     // smaller-or-equal than MinS.
526     auto MinS = min_if(S.begin(), S.end(), isScalar, LT);
527     if (MinS != S.end())
528       Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinS));
529 
530     // MaxS = max scalar in Big, remove all scalars from Small that are
531     // larger than MaxS.
532     auto MaxS = max_if(B.begin(), B.end(), isScalar, LT);
533     if (MaxS != B.end())
534       Changed |= berase_if(S, std::bind(LE, *MaxS, std::placeholders::_1));
535 
536     // MinV = min vector in Small, remove all vectors from Big that are
537     // smaller-or-equal than MinV.
538     auto MinV = min_if(S.begin(), S.end(), isVector, LT);
539     if (MinV != S.end())
540       Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinV));
541 
542     // MaxV = max vector in Big, remove all vectors from Small that are
543     // larger than MaxV.
544     auto MaxV = max_if(B.begin(), B.end(), isVector, LT);
545     if (MaxV != B.end())
546       Changed |= berase_if(S, std::bind(LE, *MaxV, std::placeholders::_1));
547   }
548 
549   return Changed;
550 }
551 
552 /// 1. Ensure that for each type T in Vec, T is a vector type, and that
553 ///    for each type U in Elem, U is a scalar type.
554 /// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)
555 ///    type T in Vec, such that U is the element type of T.
556 bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
557                                        TypeSetByHwMode &Elem) {
558   ValidateOnExit _1(Vec, *this), _2(Elem, *this);
559   if (TP.hasError())
560     return false;
561   bool Changed = false;
562 
563   if (Vec.empty())
564     Changed |= EnforceVector(Vec);
565   if (Elem.empty())
566     Changed |= EnforceScalar(Elem);
567 
568   for (unsigned M : union_modes(Vec, Elem)) {
569     TypeSetByHwMode::SetType &V = Vec.get(M);
570     TypeSetByHwMode::SetType &E = Elem.get(M);
571 
572     Changed |= berase_if(V, isScalar);  // Scalar = !vector
573     Changed |= berase_if(E, isVector);  // Vector = !scalar
574     assert(!V.empty() && !E.empty());
575 
576     SmallSet<MVT,4> VT, ST;
577     // Collect element types from the "vector" set.
578     for (MVT T : V)
579       VT.insert(T.getVectorElementType());
580     // Collect scalar types from the "element" set.
581     for (MVT T : E)
582       ST.insert(T);
583 
584     // Remove from V all (vector) types whose element type is not in S.
585     Changed |= berase_if(V, [&ST](MVT T) -> bool {
586                               return !ST.count(T.getVectorElementType());
587                             });
588     // Remove from E all (scalar) types, for which there is no corresponding
589     // type in V.
590     Changed |= berase_if(E, [&VT](MVT T) -> bool { return !VT.count(T); });
591   }
592 
593   return Changed;
594 }
595 
596 bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
597                                        const ValueTypeByHwMode &VVT) {
598   TypeSetByHwMode Tmp(VVT);
599   ValidateOnExit _1(Vec, *this), _2(Tmp, *this);
600   return EnforceVectorEltTypeIs(Vec, Tmp);
601 }
602 
603 /// Ensure that for each type T in Sub, T is a vector type, and there
604 /// exists a type U in Vec such that U is a vector type with the same
605 /// element type as T and at least as many elements as T.
606 bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
607                                              TypeSetByHwMode &Sub) {
608   ValidateOnExit _1(Vec, *this), _2(Sub, *this);
609   if (TP.hasError())
610     return false;
611 
612   /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.
613   auto IsSubVec = [](MVT B, MVT P) -> bool {
614     if (!B.isVector() || !P.isVector())
615       return false;
616     // Logically a <4 x i32> is a valid subvector of <n x 4 x i32>
617     // but until there are obvious use-cases for this, keep the
618     // types separate.
619     if (B.isScalableVector() != P.isScalableVector())
620       return false;
621     if (B.getVectorElementType() != P.getVectorElementType())
622       return false;
623     return B.getVectorNumElements() < P.getVectorNumElements();
624   };
625 
626   /// Return true if S has no element (vector type) that T is a sub-vector of,
627   /// i.e. has the same element type as T and more elements.
628   auto NoSubV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
629     for (const auto &I : S)
630       if (IsSubVec(T, I))
631         return false;
632     return true;
633   };
634 
635   /// Return true if S has no element (vector type) that T is a super-vector
636   /// of, i.e. has the same element type as T and fewer elements.
637   auto NoSupV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
638     for (const auto &I : S)
639       if (IsSubVec(I, T))
640         return false;
641     return true;
642   };
643 
644   bool Changed = false;
645 
646   if (Vec.empty())
647     Changed |= EnforceVector(Vec);
648   if (Sub.empty())
649     Changed |= EnforceVector(Sub);
650 
651   for (unsigned M : union_modes(Vec, Sub)) {
652     TypeSetByHwMode::SetType &S = Sub.get(M);
653     TypeSetByHwMode::SetType &V = Vec.get(M);
654 
655     Changed |= berase_if(S, isScalar);
656 
657     // Erase all types from S that are not sub-vectors of a type in V.
658     Changed |= berase_if(S, std::bind(NoSubV, V, std::placeholders::_1));
659 
660     // Erase all types from V that are not super-vectors of a type in S.
661     Changed |= berase_if(V, std::bind(NoSupV, S, std::placeholders::_1));
662   }
663 
664   return Changed;
665 }
666 
667 /// 1. Ensure that V has a scalar type iff W has a scalar type.
668 /// 2. Ensure that for each vector type T in V, there exists a vector
669 ///    type U in W, such that T and U have the same number of elements.
670 /// 3. Ensure that for each vector type U in W, there exists a vector
671 ///    type T in V, such that T and U have the same number of elements
672 ///    (reverse of 2).
673 bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) {
674   ValidateOnExit _1(V, *this), _2(W, *this);
675   if (TP.hasError())
676     return false;
677 
678   bool Changed = false;
679   if (V.empty())
680     Changed |= EnforceAny(V);
681   if (W.empty())
682     Changed |= EnforceAny(W);
683 
684   // An actual vector type cannot have 0 elements, so we can treat scalars
685   // as zero-length vectors. This way both vectors and scalars can be
686   // processed identically.
687   auto NoLength = [](const SmallSet<unsigned,2> &Lengths, MVT T) -> bool {
688     return !Lengths.count(T.isVector() ? T.getVectorNumElements() : 0);
689   };
690 
691   for (unsigned M : union_modes(V, W)) {
692     TypeSetByHwMode::SetType &VS = V.get(M);
693     TypeSetByHwMode::SetType &WS = W.get(M);
694 
695     SmallSet<unsigned,2> VN, WN;
696     for (MVT T : VS)
697       VN.insert(T.isVector() ? T.getVectorNumElements() : 0);
698     for (MVT T : WS)
699       WN.insert(T.isVector() ? T.getVectorNumElements() : 0);
700 
701     Changed |= berase_if(VS, std::bind(NoLength, WN, std::placeholders::_1));
702     Changed |= berase_if(WS, std::bind(NoLength, VN, std::placeholders::_1));
703   }
704   return Changed;
705 }
706 
707 /// 1. Ensure that for each type T in A, there exists a type U in B,
708 ///    such that T and U have equal size in bits.
709 /// 2. Ensure that for each type U in B, there exists a type T in A
710 ///    such that T and U have equal size in bits (reverse of 1).
711 bool TypeInfer::EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B) {
712   ValidateOnExit _1(A, *this), _2(B, *this);
713   if (TP.hasError())
714     return false;
715   bool Changed = false;
716   if (A.empty())
717     Changed |= EnforceAny(A);
718   if (B.empty())
719     Changed |= EnforceAny(B);
720 
721   auto NoSize = [](const SmallSet<unsigned,2> &Sizes, MVT T) -> bool {
722     return !Sizes.count(T.getSizeInBits());
723   };
724 
725   for (unsigned M : union_modes(A, B)) {
726     TypeSetByHwMode::SetType &AS = A.get(M);
727     TypeSetByHwMode::SetType &BS = B.get(M);
728     SmallSet<unsigned,2> AN, BN;
729 
730     for (MVT T : AS)
731       AN.insert(T.getSizeInBits());
732     for (MVT T : BS)
733       BN.insert(T.getSizeInBits());
734 
735     Changed |= berase_if(AS, std::bind(NoSize, BN, std::placeholders::_1));
736     Changed |= berase_if(BS, std::bind(NoSize, AN, std::placeholders::_1));
737   }
738 
739   return Changed;
740 }
741 
742 void TypeInfer::expandOverloads(TypeSetByHwMode &VTS) {
743   ValidateOnExit _1(VTS, *this);
744   const TypeSetByHwMode &Legal = getLegalTypes();
745   assert(Legal.isDefaultOnly() && "Default-mode only expected");
746   const TypeSetByHwMode::SetType &LegalTypes = Legal.get(DefaultMode);
747 
748   for (auto &I : VTS)
749     expandOverloads(I.second, LegalTypes);
750 }
751 
752 void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out,
753                                 const TypeSetByHwMode::SetType &Legal) {
754   std::set<MVT> Ovs;
755   for (MVT T : Out) {
756     if (!T.isOverloaded())
757       continue;
758 
759     Ovs.insert(T);
760     // MachineValueTypeSet allows iteration and erasing.
761     Out.erase(T);
762   }
763 
764   for (MVT Ov : Ovs) {
765     switch (Ov.SimpleTy) {
766       case MVT::iPTRAny:
767         Out.insert(MVT::iPTR);
768         return;
769       case MVT::iAny:
770         for (MVT T : MVT::integer_valuetypes())
771           if (Legal.count(T))
772             Out.insert(T);
773         for (MVT T : MVT::integer_vector_valuetypes())
774           if (Legal.count(T))
775             Out.insert(T);
776         return;
777       case MVT::fAny:
778         for (MVT T : MVT::fp_valuetypes())
779           if (Legal.count(T))
780             Out.insert(T);
781         for (MVT T : MVT::fp_vector_valuetypes())
782           if (Legal.count(T))
783             Out.insert(T);
784         return;
785       case MVT::vAny:
786         for (MVT T : MVT::vector_valuetypes())
787           if (Legal.count(T))
788             Out.insert(T);
789         return;
790       case MVT::Any:
791         for (MVT T : MVT::all_valuetypes())
792           if (Legal.count(T))
793             Out.insert(T);
794         return;
795       default:
796         break;
797     }
798   }
799 }
800 
801 const TypeSetByHwMode &TypeInfer::getLegalTypes() {
802   if (!LegalTypesCached) {
803     TypeSetByHwMode::SetType &LegalTypes = LegalCache.getOrCreate(DefaultMode);
804     // Stuff all types from all modes into the default mode.
805     const TypeSetByHwMode &LTS = TP.getDAGPatterns().getLegalTypes();
806     for (const auto &I : LTS)
807       LegalTypes.insert(I.second);
808     LegalTypesCached = true;
809   }
810   assert(LegalCache.isDefaultOnly() && "Default-mode only expected");
811   return LegalCache;
812 }
813 
814 #ifndef NDEBUG
815 TypeInfer::ValidateOnExit::~ValidateOnExit() {
816   if (Infer.Validate && !VTS.validate()) {
817     dbgs() << "Type set is empty for each HW mode:\n"
818               "possible type contradiction in the pattern below "
819               "(use -print-records with llvm-tblgen to see all "
820               "expanded records).\n";
821     Infer.TP.dump();
822     llvm_unreachable(nullptr);
823   }
824 }
825 #endif
826 
827 //===----------------------------------------------------------------------===//
828 // TreePredicateFn Implementation
829 //===----------------------------------------------------------------------===//
830 
831 /// TreePredicateFn constructor.  Here 'N' is a subclass of PatFrag.
832 TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
833   assert(
834       (!hasPredCode() || !hasImmCode()) &&
835       ".td file corrupt: can't have a node predicate *and* an imm predicate");
836 }
837 
838 bool TreePredicateFn::hasPredCode() const {
839   return isLoad() || isStore() || isAtomic() ||
840          !PatFragRec->getRecord()->getValueAsString("PredicateCode").empty();
841 }
842 
843 std::string TreePredicateFn::getPredCode() const {
844   std::string Code = "";
845 
846   if (!isLoad() && !isStore() && !isAtomic()) {
847     Record *MemoryVT = getMemoryVT();
848 
849     if (MemoryVT)
850       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
851                       "MemoryVT requires IsLoad or IsStore");
852   }
853 
854   if (!isLoad() && !isStore()) {
855     if (isUnindexed())
856       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
857                       "IsUnindexed requires IsLoad or IsStore");
858 
859     Record *ScalarMemoryVT = getScalarMemoryVT();
860 
861     if (ScalarMemoryVT)
862       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
863                       "ScalarMemoryVT requires IsLoad or IsStore");
864   }
865 
866   if (isLoad() + isStore() + isAtomic() > 1)
867     PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
868                     "IsLoad, IsStore, and IsAtomic are mutually exclusive");
869 
870   if (isLoad()) {
871     if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&
872         !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&
873         getScalarMemoryVT() == nullptr)
874       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
875                       "IsLoad cannot be used by itself");
876   } else {
877     if (isNonExtLoad())
878       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
879                       "IsNonExtLoad requires IsLoad");
880     if (isAnyExtLoad())
881       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
882                       "IsAnyExtLoad requires IsLoad");
883     if (isSignExtLoad())
884       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
885                       "IsSignExtLoad requires IsLoad");
886     if (isZeroExtLoad())
887       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
888                       "IsZeroExtLoad requires IsLoad");
889   }
890 
891   if (isStore()) {
892     if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&
893         getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr)
894       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
895                       "IsStore cannot be used by itself");
896   } else {
897     if (isNonTruncStore())
898       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
899                       "IsNonTruncStore requires IsStore");
900     if (isTruncStore())
901       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
902                       "IsTruncStore requires IsStore");
903   }
904 
905   if (isAtomic()) {
906     if (getMemoryVT() == nullptr && !isAtomicOrderingMonotonic() &&
907         !isAtomicOrderingAcquire() && !isAtomicOrderingRelease() &&
908         !isAtomicOrderingAcquireRelease() &&
909         !isAtomicOrderingSequentiallyConsistent() &&
910         !isAtomicOrderingAcquireOrStronger() &&
911         !isAtomicOrderingReleaseOrStronger() &&
912         !isAtomicOrderingWeakerThanAcquire() &&
913         !isAtomicOrderingWeakerThanRelease())
914       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
915                       "IsAtomic cannot be used by itself");
916   } else {
917     if (isAtomicOrderingMonotonic())
918       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
919                       "IsAtomicOrderingMonotonic requires IsAtomic");
920     if (isAtomicOrderingAcquire())
921       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
922                       "IsAtomicOrderingAcquire requires IsAtomic");
923     if (isAtomicOrderingRelease())
924       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
925                       "IsAtomicOrderingRelease requires IsAtomic");
926     if (isAtomicOrderingAcquireRelease())
927       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
928                       "IsAtomicOrderingAcquireRelease requires IsAtomic");
929     if (isAtomicOrderingSequentiallyConsistent())
930       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
931                       "IsAtomicOrderingSequentiallyConsistent requires IsAtomic");
932     if (isAtomicOrderingAcquireOrStronger())
933       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
934                       "IsAtomicOrderingAcquireOrStronger requires IsAtomic");
935     if (isAtomicOrderingReleaseOrStronger())
936       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
937                       "IsAtomicOrderingReleaseOrStronger requires IsAtomic");
938     if (isAtomicOrderingWeakerThanAcquire())
939       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
940                       "IsAtomicOrderingWeakerThanAcquire requires IsAtomic");
941   }
942 
943   if (isLoad() || isStore() || isAtomic()) {
944     StringRef SDNodeName =
945         isLoad() ? "LoadSDNode" : isStore() ? "StoreSDNode" : "AtomicSDNode";
946 
947     Record *MemoryVT = getMemoryVT();
948 
949     if (MemoryVT)
950       Code += ("if (cast<" + SDNodeName + ">(N)->getMemoryVT() != MVT::" +
951                MemoryVT->getName() + ") return false;\n")
952                   .str();
953   }
954 
955   if (isAtomic() && isAtomicOrderingMonotonic())
956     Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
957             "AtomicOrdering::Monotonic) return false;\n";
958   if (isAtomic() && isAtomicOrderingAcquire())
959     Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
960             "AtomicOrdering::Acquire) return false;\n";
961   if (isAtomic() && isAtomicOrderingRelease())
962     Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
963             "AtomicOrdering::Release) return false;\n";
964   if (isAtomic() && isAtomicOrderingAcquireRelease())
965     Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
966             "AtomicOrdering::AcquireRelease) return false;\n";
967   if (isAtomic() && isAtomicOrderingSequentiallyConsistent())
968     Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
969             "AtomicOrdering::SequentiallyConsistent) return false;\n";
970 
971   if (isAtomic() && isAtomicOrderingAcquireOrStronger())
972     Code += "if (!isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
973             "return false;\n";
974   if (isAtomic() && isAtomicOrderingWeakerThanAcquire())
975     Code += "if (isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
976             "return false;\n";
977 
978   if (isAtomic() && isAtomicOrderingReleaseOrStronger())
979     Code += "if (!isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
980             "return false;\n";
981   if (isAtomic() && isAtomicOrderingWeakerThanRelease())
982     Code += "if (isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
983             "return false;\n";
984 
985   if (isLoad() || isStore()) {
986     StringRef SDNodeName = isLoad() ? "LoadSDNode" : "StoreSDNode";
987 
988     if (isUnindexed())
989       Code += ("if (cast<" + SDNodeName +
990                ">(N)->getAddressingMode() != ISD::UNINDEXED) "
991                "return false;\n")
992                   .str();
993 
994     if (isLoad()) {
995       if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
996            isZeroExtLoad()) > 1)
997         PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
998                         "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
999                         "IsZeroExtLoad are mutually exclusive");
1000       if (isNonExtLoad())
1001         Code += "if (cast<LoadSDNode>(N)->getExtensionType() != "
1002                 "ISD::NON_EXTLOAD) return false;\n";
1003       if (isAnyExtLoad())
1004         Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
1005                 "return false;\n";
1006       if (isSignExtLoad())
1007         Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
1008                 "return false;\n";
1009       if (isZeroExtLoad())
1010         Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
1011                 "return false;\n";
1012     } else {
1013       if ((isNonTruncStore() + isTruncStore()) > 1)
1014         PrintFatalError(
1015             getOrigPatFragRecord()->getRecord()->getLoc(),
1016             "IsNonTruncStore, and IsTruncStore are mutually exclusive");
1017       if (isNonTruncStore())
1018         Code +=
1019             " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1020       if (isTruncStore())
1021         Code +=
1022             " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1023     }
1024 
1025     Record *ScalarMemoryVT = getScalarMemoryVT();
1026 
1027     if (ScalarMemoryVT)
1028       Code += ("if (cast<" + SDNodeName +
1029                ">(N)->getMemoryVT().getScalarType() != MVT::" +
1030                ScalarMemoryVT->getName() + ") return false;\n")
1031                   .str();
1032   }
1033 
1034   std::string PredicateCode = PatFragRec->getRecord()->getValueAsString("PredicateCode");
1035 
1036   Code += PredicateCode;
1037 
1038   if (PredicateCode.empty() && !Code.empty())
1039     Code += "return true;\n";
1040 
1041   return Code;
1042 }
1043 
1044 bool TreePredicateFn::hasImmCode() const {
1045   return !PatFragRec->getRecord()->getValueAsString("ImmediateCode").empty();
1046 }
1047 
1048 std::string TreePredicateFn::getImmCode() const {
1049   return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
1050 }
1051 
1052 bool TreePredicateFn::immCodeUsesAPInt() const {
1053   return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
1054 }
1055 
1056 bool TreePredicateFn::immCodeUsesAPFloat() const {
1057   bool Unset;
1058   // The return value will be false when IsAPFloat is unset.
1059   return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
1060                                                                    Unset);
1061 }
1062 
1063 bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,
1064                                                    bool Value) const {
1065   bool Unset;
1066   bool Result =
1067       getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field, Unset);
1068   if (Unset)
1069     return false;
1070   return Result == Value;
1071 }
1072 bool TreePredicateFn::isLoad() const {
1073   return isPredefinedPredicateEqualTo("IsLoad", true);
1074 }
1075 bool TreePredicateFn::isStore() const {
1076   return isPredefinedPredicateEqualTo("IsStore", true);
1077 }
1078 bool TreePredicateFn::isAtomic() const {
1079   return isPredefinedPredicateEqualTo("IsAtomic", true);
1080 }
1081 bool TreePredicateFn::isUnindexed() const {
1082   return isPredefinedPredicateEqualTo("IsUnindexed", true);
1083 }
1084 bool TreePredicateFn::isNonExtLoad() const {
1085   return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
1086 }
1087 bool TreePredicateFn::isAnyExtLoad() const {
1088   return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
1089 }
1090 bool TreePredicateFn::isSignExtLoad() const {
1091   return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
1092 }
1093 bool TreePredicateFn::isZeroExtLoad() const {
1094   return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
1095 }
1096 bool TreePredicateFn::isNonTruncStore() const {
1097   return isPredefinedPredicateEqualTo("IsTruncStore", false);
1098 }
1099 bool TreePredicateFn::isTruncStore() const {
1100   return isPredefinedPredicateEqualTo("IsTruncStore", true);
1101 }
1102 bool TreePredicateFn::isAtomicOrderingMonotonic() const {
1103   return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true);
1104 }
1105 bool TreePredicateFn::isAtomicOrderingAcquire() const {
1106   return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true);
1107 }
1108 bool TreePredicateFn::isAtomicOrderingRelease() const {
1109   return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true);
1110 }
1111 bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
1112   return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true);
1113 }
1114 bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
1115   return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent",
1116                                       true);
1117 }
1118 bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {
1119   return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", true);
1120 }
1121 bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {
1122   return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", false);
1123 }
1124 bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {
1125   return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", true);
1126 }
1127 bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {
1128   return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", false);
1129 }
1130 Record *TreePredicateFn::getMemoryVT() const {
1131   Record *R = getOrigPatFragRecord()->getRecord();
1132   if (R->isValueUnset("MemoryVT"))
1133     return nullptr;
1134   return R->getValueAsDef("MemoryVT");
1135 }
1136 Record *TreePredicateFn::getScalarMemoryVT() const {
1137   Record *R = getOrigPatFragRecord()->getRecord();
1138   if (R->isValueUnset("ScalarMemoryVT"))
1139     return nullptr;
1140   return R->getValueAsDef("ScalarMemoryVT");
1141 }
1142 bool TreePredicateFn::hasGISelPredicateCode() const {
1143   return !PatFragRec->getRecord()
1144               ->getValueAsString("GISelPredicateCode")
1145               .empty();
1146 }
1147 std::string TreePredicateFn::getGISelPredicateCode() const {
1148   return PatFragRec->getRecord()->getValueAsString("GISelPredicateCode");
1149 }
1150 
1151 StringRef TreePredicateFn::getImmType() const {
1152   if (immCodeUsesAPInt())
1153     return "const APInt &";
1154   if (immCodeUsesAPFloat())
1155     return "const APFloat &";
1156   return "int64_t";
1157 }
1158 
1159 StringRef TreePredicateFn::getImmTypeIdentifier() const {
1160   if (immCodeUsesAPInt())
1161     return "APInt";
1162   else if (immCodeUsesAPFloat())
1163     return "APFloat";
1164   return "I64";
1165 }
1166 
1167 /// isAlwaysTrue - Return true if this is a noop predicate.
1168 bool TreePredicateFn::isAlwaysTrue() const {
1169   return !hasPredCode() && !hasImmCode();
1170 }
1171 
1172 /// Return the name to use in the generated code to reference this, this is
1173 /// "Predicate_foo" if from a pattern fragment "foo".
1174 std::string TreePredicateFn::getFnName() const {
1175   return "Predicate_" + PatFragRec->getRecord()->getName().str();
1176 }
1177 
1178 /// getCodeToRunOnSDNode - Return the code for the function body that
1179 /// evaluates this predicate.  The argument is expected to be in "Node",
1180 /// not N.  This handles casting and conversion to a concrete node type as
1181 /// appropriate.
1182 std::string TreePredicateFn::getCodeToRunOnSDNode() const {
1183   // Handle immediate predicates first.
1184   std::string ImmCode = getImmCode();
1185   if (!ImmCode.empty()) {
1186     if (isLoad())
1187       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1188                       "IsLoad cannot be used with ImmLeaf or its subclasses");
1189     if (isStore())
1190       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1191                       "IsStore cannot be used with ImmLeaf or its subclasses");
1192     if (isUnindexed())
1193       PrintFatalError(
1194           getOrigPatFragRecord()->getRecord()->getLoc(),
1195           "IsUnindexed cannot be used with ImmLeaf or its subclasses");
1196     if (isNonExtLoad())
1197       PrintFatalError(
1198           getOrigPatFragRecord()->getRecord()->getLoc(),
1199           "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
1200     if (isAnyExtLoad())
1201       PrintFatalError(
1202           getOrigPatFragRecord()->getRecord()->getLoc(),
1203           "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
1204     if (isSignExtLoad())
1205       PrintFatalError(
1206           getOrigPatFragRecord()->getRecord()->getLoc(),
1207           "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
1208     if (isZeroExtLoad())
1209       PrintFatalError(
1210           getOrigPatFragRecord()->getRecord()->getLoc(),
1211           "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
1212     if (isNonTruncStore())
1213       PrintFatalError(
1214           getOrigPatFragRecord()->getRecord()->getLoc(),
1215           "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
1216     if (isTruncStore())
1217       PrintFatalError(
1218           getOrigPatFragRecord()->getRecord()->getLoc(),
1219           "IsTruncStore cannot be used with ImmLeaf or its subclasses");
1220     if (getMemoryVT())
1221       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1222                       "MemoryVT cannot be used with ImmLeaf or its subclasses");
1223     if (getScalarMemoryVT())
1224       PrintFatalError(
1225           getOrigPatFragRecord()->getRecord()->getLoc(),
1226           "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
1227 
1228     std::string Result = ("    " + getImmType() + " Imm = ").str();
1229     if (immCodeUsesAPFloat())
1230       Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
1231     else if (immCodeUsesAPInt())
1232       Result += "cast<ConstantSDNode>(Node)->getAPIntValue();\n";
1233     else
1234       Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n";
1235     return Result + ImmCode;
1236   }
1237 
1238   // Handle arbitrary node predicates.
1239   assert(hasPredCode() && "Don't have any predicate code!");
1240   StringRef ClassName;
1241   if (PatFragRec->getOnlyTree()->isLeaf())
1242     ClassName = "SDNode";
1243   else {
1244     Record *Op = PatFragRec->getOnlyTree()->getOperator();
1245     ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
1246   }
1247   std::string Result;
1248   if (ClassName == "SDNode")
1249     Result = "    SDNode *N = Node;\n";
1250   else
1251     Result = "    auto *N = cast<" + ClassName.str() + ">(Node);\n";
1252 
1253   return Result + getPredCode();
1254 }
1255 
1256 //===----------------------------------------------------------------------===//
1257 // PatternToMatch implementation
1258 //
1259 
1260 /// getPatternSize - Return the 'size' of this pattern.  We want to match large
1261 /// patterns before small ones.  This is used to determine the size of a
1262 /// pattern.
1263 static unsigned getPatternSize(const TreePatternNode *P,
1264                                const CodeGenDAGPatterns &CGP) {
1265   unsigned Size = 3;  // The node itself.
1266   // If the root node is a ConstantSDNode, increases its size.
1267   // e.g. (set R32:$dst, 0).
1268   if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
1269     Size += 2;
1270 
1271   if (const ComplexPattern *AM = P->getComplexPatternInfo(CGP)) {
1272     Size += AM->getComplexity();
1273     // We don't want to count any children twice, so return early.
1274     return Size;
1275   }
1276 
1277   // If this node has some predicate function that must match, it adds to the
1278   // complexity of this node.
1279   if (!P->getPredicateFns().empty())
1280     ++Size;
1281 
1282   // Count children in the count if they are also nodes.
1283   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1284     const TreePatternNode *Child = P->getChild(i);
1285     if (!Child->isLeaf() && Child->getNumTypes()) {
1286       const TypeSetByHwMode &T0 = Child->getExtType(0);
1287       // At this point, all variable type sets should be simple, i.e. only
1288       // have a default mode.
1289       if (T0.getMachineValueType() != MVT::Other) {
1290         Size += getPatternSize(Child, CGP);
1291         continue;
1292       }
1293     }
1294     if (Child->isLeaf()) {
1295       if (isa<IntInit>(Child->getLeafValue()))
1296         Size += 5;  // Matches a ConstantSDNode (+3) and a specific value (+2).
1297       else if (Child->getComplexPatternInfo(CGP))
1298         Size += getPatternSize(Child, CGP);
1299       else if (!Child->getPredicateFns().empty())
1300         ++Size;
1301     }
1302   }
1303 
1304   return Size;
1305 }
1306 
1307 /// Compute the complexity metric for the input pattern.  This roughly
1308 /// corresponds to the number of nodes that are covered.
1309 int PatternToMatch::
1310 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
1311   return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
1312 }
1313 
1314 /// getPredicateCheck - Return a single string containing all of this
1315 /// pattern's predicates concatenated with "&&" operators.
1316 ///
1317 std::string PatternToMatch::getPredicateCheck() const {
1318   SmallVector<const Predicate*,4> PredList;
1319   for (const Predicate &P : Predicates)
1320     PredList.push_back(&P);
1321   llvm::sort(PredList.begin(), PredList.end(), deref<llvm::less>());
1322 
1323   std::string Check;
1324   for (unsigned i = 0, e = PredList.size(); i != e; ++i) {
1325     if (i != 0)
1326       Check += " && ";
1327     Check += '(' + PredList[i]->getCondString() + ')';
1328   }
1329   return Check;
1330 }
1331 
1332 //===----------------------------------------------------------------------===//
1333 // SDTypeConstraint implementation
1334 //
1335 
1336 SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
1337   OperandNo = R->getValueAsInt("OperandNum");
1338 
1339   if (R->isSubClassOf("SDTCisVT")) {
1340     ConstraintType = SDTCisVT;
1341     VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1342     for (const auto &P : VVT)
1343       if (P.second == MVT::isVoid)
1344         PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
1345   } else if (R->isSubClassOf("SDTCisPtrTy")) {
1346     ConstraintType = SDTCisPtrTy;
1347   } else if (R->isSubClassOf("SDTCisInt")) {
1348     ConstraintType = SDTCisInt;
1349   } else if (R->isSubClassOf("SDTCisFP")) {
1350     ConstraintType = SDTCisFP;
1351   } else if (R->isSubClassOf("SDTCisVec")) {
1352     ConstraintType = SDTCisVec;
1353   } else if (R->isSubClassOf("SDTCisSameAs")) {
1354     ConstraintType = SDTCisSameAs;
1355     x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
1356   } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
1357     ConstraintType = SDTCisVTSmallerThanOp;
1358     x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
1359       R->getValueAsInt("OtherOperandNum");
1360   } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
1361     ConstraintType = SDTCisOpSmallerThanOp;
1362     x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
1363       R->getValueAsInt("BigOperandNum");
1364   } else if (R->isSubClassOf("SDTCisEltOfVec")) {
1365     ConstraintType = SDTCisEltOfVec;
1366     x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
1367   } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
1368     ConstraintType = SDTCisSubVecOfVec;
1369     x.SDTCisSubVecOfVec_Info.OtherOperandNum =
1370       R->getValueAsInt("OtherOpNum");
1371   } else if (R->isSubClassOf("SDTCVecEltisVT")) {
1372     ConstraintType = SDTCVecEltisVT;
1373     VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1374     for (const auto &P : VVT) {
1375       MVT T = P.second;
1376       if (T.isVector())
1377         PrintFatalError(R->getLoc(),
1378                         "Cannot use vector type as SDTCVecEltisVT");
1379       if (!T.isInteger() && !T.isFloatingPoint())
1380         PrintFatalError(R->getLoc(), "Must use integer or floating point type "
1381                                      "as SDTCVecEltisVT");
1382     }
1383   } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
1384     ConstraintType = SDTCisSameNumEltsAs;
1385     x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
1386       R->getValueAsInt("OtherOperandNum");
1387   } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
1388     ConstraintType = SDTCisSameSizeAs;
1389     x.SDTCisSameSizeAs_Info.OtherOperandNum =
1390       R->getValueAsInt("OtherOperandNum");
1391   } else {
1392     PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
1393   }
1394 }
1395 
1396 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
1397 /// N, and the result number in ResNo.
1398 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
1399                                       const SDNodeInfo &NodeInfo,
1400                                       unsigned &ResNo) {
1401   unsigned NumResults = NodeInfo.getNumResults();
1402   if (OpNo < NumResults) {
1403     ResNo = OpNo;
1404     return N;
1405   }
1406 
1407   OpNo -= NumResults;
1408 
1409   if (OpNo >= N->getNumChildren()) {
1410     std::string S;
1411     raw_string_ostream OS(S);
1412     OS << "Invalid operand number in type constraint "
1413            << (OpNo+NumResults) << " ";
1414     N->print(OS);
1415     PrintFatalError(OS.str());
1416   }
1417 
1418   return N->getChild(OpNo);
1419 }
1420 
1421 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
1422 /// constraint to the nodes operands.  This returns true if it makes a
1423 /// change, false otherwise.  If a type contradiction is found, flag an error.
1424 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
1425                                            const SDNodeInfo &NodeInfo,
1426                                            TreePattern &TP) const {
1427   if (TP.hasError())
1428     return false;
1429 
1430   unsigned ResNo = 0; // The result number being referenced.
1431   TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
1432   TypeInfer &TI = TP.getInfer();
1433 
1434   switch (ConstraintType) {
1435   case SDTCisVT:
1436     // Operand must be a particular type.
1437     return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
1438   case SDTCisPtrTy:
1439     // Operand must be same as target pointer type.
1440     return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
1441   case SDTCisInt:
1442     // Require it to be one of the legal integer VTs.
1443      return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
1444   case SDTCisFP:
1445     // Require it to be one of the legal fp VTs.
1446     return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
1447   case SDTCisVec:
1448     // Require it to be one of the legal vector VTs.
1449     return TI.EnforceVector(NodeToApply->getExtType(ResNo));
1450   case SDTCisSameAs: {
1451     unsigned OResNo = 0;
1452     TreePatternNode *OtherNode =
1453       getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
1454     return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1455            OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
1456   }
1457   case SDTCisVTSmallerThanOp: {
1458     // The NodeToApply must be a leaf node that is a VT.  OtherOperandNum must
1459     // have an integer type that is smaller than the VT.
1460     if (!NodeToApply->isLeaf() ||
1461         !isa<DefInit>(NodeToApply->getLeafValue()) ||
1462         !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
1463                ->isSubClassOf("ValueType")) {
1464       TP.error(N->getOperator()->getName() + " expects a VT operand!");
1465       return false;
1466     }
1467     DefInit *DI = static_cast<DefInit*>(NodeToApply->getLeafValue());
1468     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1469     auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
1470     TypeSetByHwMode TypeListTmp(VVT);
1471 
1472     unsigned OResNo = 0;
1473     TreePatternNode *OtherNode =
1474       getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1475                     OResNo);
1476 
1477     return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo));
1478   }
1479   case SDTCisOpSmallerThanOp: {
1480     unsigned BResNo = 0;
1481     TreePatternNode *BigOperand =
1482       getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1483                     BResNo);
1484     return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
1485                                  BigOperand->getExtType(BResNo));
1486   }
1487   case SDTCisEltOfVec: {
1488     unsigned VResNo = 0;
1489     TreePatternNode *VecOperand =
1490       getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1491                     VResNo);
1492     // Filter vector types out of VecOperand that don't have the right element
1493     // type.
1494     return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
1495                                      NodeToApply->getExtType(ResNo));
1496   }
1497   case SDTCisSubVecOfVec: {
1498     unsigned VResNo = 0;
1499     TreePatternNode *BigVecOperand =
1500       getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1501                     VResNo);
1502 
1503     // Filter vector types out of BigVecOperand that don't have the
1504     // right subvector type.
1505     return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
1506                                            NodeToApply->getExtType(ResNo));
1507   }
1508   case SDTCVecEltisVT: {
1509     return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
1510   }
1511   case SDTCisSameNumEltsAs: {
1512     unsigned OResNo = 0;
1513     TreePatternNode *OtherNode =
1514       getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1515                     N, NodeInfo, OResNo);
1516     return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
1517                                  NodeToApply->getExtType(ResNo));
1518   }
1519   case SDTCisSameSizeAs: {
1520     unsigned OResNo = 0;
1521     TreePatternNode *OtherNode =
1522       getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1523                     N, NodeInfo, OResNo);
1524     return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
1525                               NodeToApply->getExtType(ResNo));
1526   }
1527   }
1528   llvm_unreachable("Invalid ConstraintType!");
1529 }
1530 
1531 // Update the node type to match an instruction operand or result as specified
1532 // in the ins or outs lists on the instruction definition. Return true if the
1533 // type was actually changed.
1534 bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1535                                              Record *Operand,
1536                                              TreePattern &TP) {
1537   // The 'unknown' operand indicates that types should be inferred from the
1538   // context.
1539   if (Operand->isSubClassOf("unknown_class"))
1540     return false;
1541 
1542   // The Operand class specifies a type directly.
1543   if (Operand->isSubClassOf("Operand")) {
1544     Record *R = Operand->getValueAsDef("Type");
1545     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1546     return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
1547   }
1548 
1549   // PointerLikeRegClass has a type that is determined at runtime.
1550   if (Operand->isSubClassOf("PointerLikeRegClass"))
1551     return UpdateNodeType(ResNo, MVT::iPTR, TP);
1552 
1553   // Both RegisterClass and RegisterOperand operands derive their types from a
1554   // register class def.
1555   Record *RC = nullptr;
1556   if (Operand->isSubClassOf("RegisterClass"))
1557     RC = Operand;
1558   else if (Operand->isSubClassOf("RegisterOperand"))
1559     RC = Operand->getValueAsDef("RegClass");
1560 
1561   assert(RC && "Unknown operand type");
1562   CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1563   return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1564 }
1565 
1566 bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1567   for (unsigned i = 0, e = Types.size(); i != e; ++i)
1568     if (!TP.getInfer().isConcrete(Types[i], true))
1569       return true;
1570   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1571     if (getChild(i)->ContainsUnresolvedType(TP))
1572       return true;
1573   return false;
1574 }
1575 
1576 bool TreePatternNode::hasProperTypeByHwMode() const {
1577   for (const TypeSetByHwMode &S : Types)
1578     if (!S.isDefaultOnly())
1579       return true;
1580   for (const TreePatternNodePtr &C : Children)
1581     if (C->hasProperTypeByHwMode())
1582       return true;
1583   return false;
1584 }
1585 
1586 bool TreePatternNode::hasPossibleType() const {
1587   for (const TypeSetByHwMode &S : Types)
1588     if (!S.isPossible())
1589       return false;
1590   for (const TreePatternNodePtr &C : Children)
1591     if (!C->hasPossibleType())
1592       return false;
1593   return true;
1594 }
1595 
1596 bool TreePatternNode::setDefaultMode(unsigned Mode) {
1597   for (TypeSetByHwMode &S : Types) {
1598     S.makeSimple(Mode);
1599     // Check if the selected mode had a type conflict.
1600     if (S.get(DefaultMode).empty())
1601       return false;
1602   }
1603   for (const TreePatternNodePtr &C : Children)
1604     if (!C->setDefaultMode(Mode))
1605       return false;
1606   return true;
1607 }
1608 
1609 //===----------------------------------------------------------------------===//
1610 // SDNodeInfo implementation
1611 //
1612 SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
1613   EnumName    = R->getValueAsString("Opcode");
1614   SDClassName = R->getValueAsString("SDClass");
1615   Record *TypeProfile = R->getValueAsDef("TypeProfile");
1616   NumResults = TypeProfile->getValueAsInt("NumResults");
1617   NumOperands = TypeProfile->getValueAsInt("NumOperands");
1618 
1619   // Parse the properties.
1620   Properties = parseSDPatternOperatorProperties(R);
1621 
1622   // Parse the type constraints.
1623   std::vector<Record*> ConstraintList =
1624     TypeProfile->getValueAsListOfDefs("Constraints");
1625   for (Record *R : ConstraintList)
1626     TypeConstraints.emplace_back(R, CGH);
1627 }
1628 
1629 /// getKnownType - If the type constraints on this node imply a fixed type
1630 /// (e.g. all stores return void, etc), then return it as an
1631 /// MVT::SimpleValueType.  Otherwise, return EEVT::Other.
1632 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
1633   unsigned NumResults = getNumResults();
1634   assert(NumResults <= 1 &&
1635          "We only work with nodes with zero or one result so far!");
1636   assert(ResNo == 0 && "Only handles single result nodes so far");
1637 
1638   for (const SDTypeConstraint &Constraint : TypeConstraints) {
1639     // Make sure that this applies to the correct node result.
1640     if (Constraint.OperandNo >= NumResults)  // FIXME: need value #
1641       continue;
1642 
1643     switch (Constraint.ConstraintType) {
1644     default: break;
1645     case SDTypeConstraint::SDTCisVT:
1646       if (Constraint.VVT.isSimple())
1647         return Constraint.VVT.getSimple().SimpleTy;
1648       break;
1649     case SDTypeConstraint::SDTCisPtrTy:
1650       return MVT::iPTR;
1651     }
1652   }
1653   return MVT::Other;
1654 }
1655 
1656 //===----------------------------------------------------------------------===//
1657 // TreePatternNode implementation
1658 //
1659 
1660 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1661   if (Operator->getName() == "set" ||
1662       Operator->getName() == "implicit")
1663     return 0;  // All return nothing.
1664 
1665   if (Operator->isSubClassOf("Intrinsic"))
1666     return CDP.getIntrinsic(Operator).IS.RetVTs.size();
1667 
1668   if (Operator->isSubClassOf("SDNode"))
1669     return CDP.getSDNodeInfo(Operator).getNumResults();
1670 
1671   if (Operator->isSubClassOf("PatFrags")) {
1672     // If we've already parsed this pattern fragment, get it.  Otherwise, handle
1673     // the forward reference case where one pattern fragment references another
1674     // before it is processed.
1675     if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator)) {
1676       // The number of results of a fragment with alternative records is the
1677       // maximum number of results across all alternatives.
1678       unsigned NumResults = 0;
1679       for (auto T : PFRec->getTrees())
1680         NumResults = std::max(NumResults, T->getNumTypes());
1681       return NumResults;
1682     }
1683 
1684     ListInit *LI = Operator->getValueAsListInit("Fragments");
1685     assert(LI && "Invalid Fragment");
1686     unsigned NumResults = 0;
1687     for (Init *I : LI->getValues()) {
1688       Record *Op = nullptr;
1689       if (DagInit *Dag = dyn_cast<DagInit>(I))
1690         if (DefInit *DI = dyn_cast<DefInit>(Dag->getOperator()))
1691           Op = DI->getDef();
1692       assert(Op && "Invalid Fragment");
1693       NumResults = std::max(NumResults, GetNumNodeResults(Op, CDP));
1694     }
1695     return NumResults;
1696   }
1697 
1698   if (Operator->isSubClassOf("Instruction")) {
1699     CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
1700 
1701     unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1702 
1703     // Subtract any defaulted outputs.
1704     for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1705       Record *OperandNode = InstInfo.Operands[i].Rec;
1706 
1707       if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1708           !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1709         --NumDefsToAdd;
1710     }
1711 
1712     // Add on one implicit def if it has a resolvable type.
1713     if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1714       ++NumDefsToAdd;
1715     return NumDefsToAdd;
1716   }
1717 
1718   if (Operator->isSubClassOf("SDNodeXForm"))
1719     return 1;  // FIXME: Generalize SDNodeXForm
1720 
1721   if (Operator->isSubClassOf("ValueType"))
1722     return 1;  // A type-cast of one result.
1723 
1724   if (Operator->isSubClassOf("ComplexPattern"))
1725     return 1;
1726 
1727   errs() << *Operator;
1728   PrintFatalError("Unhandled node in GetNumNodeResults");
1729 }
1730 
1731 void TreePatternNode::print(raw_ostream &OS) const {
1732   if (isLeaf())
1733     OS << *getLeafValue();
1734   else
1735     OS << '(' << getOperator()->getName();
1736 
1737   for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1738     OS << ':';
1739     getExtType(i).writeToStream(OS);
1740   }
1741 
1742   if (!isLeaf()) {
1743     if (getNumChildren() != 0) {
1744       OS << " ";
1745       getChild(0)->print(OS);
1746       for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1747         OS << ", ";
1748         getChild(i)->print(OS);
1749       }
1750     }
1751     OS << ")";
1752   }
1753 
1754   for (const TreePredicateFn &Pred : PredicateFns)
1755     OS << "<<P:" << Pred.getFnName() << ">>";
1756   if (TransformFn)
1757     OS << "<<X:" << TransformFn->getName() << ">>";
1758   if (!getName().empty())
1759     OS << ":$" << getName();
1760 
1761 }
1762 void TreePatternNode::dump() const {
1763   print(errs());
1764 }
1765 
1766 /// isIsomorphicTo - Return true if this node is recursively
1767 /// isomorphic to the specified node.  For this comparison, the node's
1768 /// entire state is considered. The assigned name is ignored, since
1769 /// nodes with differing names are considered isomorphic. However, if
1770 /// the assigned name is present in the dependent variable set, then
1771 /// the assigned name is considered significant and the node is
1772 /// isomorphic if the names match.
1773 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1774                                      const MultipleUseVarSet &DepVars) const {
1775   if (N == this) return true;
1776   if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1777       getPredicateFns() != N->getPredicateFns() ||
1778       getTransformFn() != N->getTransformFn())
1779     return false;
1780 
1781   if (isLeaf()) {
1782     if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1783       if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
1784         return ((DI->getDef() == NDI->getDef())
1785                 && (DepVars.find(getName()) == DepVars.end()
1786                     || getName() == N->getName()));
1787       }
1788     }
1789     return getLeafValue() == N->getLeafValue();
1790   }
1791 
1792   if (N->getOperator() != getOperator() ||
1793       N->getNumChildren() != getNumChildren()) return false;
1794   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1795     if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
1796       return false;
1797   return true;
1798 }
1799 
1800 /// clone - Make a copy of this tree and all of its children.
1801 ///
1802 TreePatternNodePtr TreePatternNode::clone() const {
1803   TreePatternNodePtr New;
1804   if (isLeaf()) {
1805     New = std::make_shared<TreePatternNode>(getLeafValue(), getNumTypes());
1806   } else {
1807     std::vector<TreePatternNodePtr> CChildren;
1808     CChildren.reserve(Children.size());
1809     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1810       CChildren.push_back(getChild(i)->clone());
1811     New = std::make_shared<TreePatternNode>(getOperator(), std::move(CChildren),
1812                                             getNumTypes());
1813   }
1814   New->setName(getName());
1815   New->Types = Types;
1816   New->setPredicateFns(getPredicateFns());
1817   New->setTransformFn(getTransformFn());
1818   return New;
1819 }
1820 
1821 /// RemoveAllTypes - Recursively strip all the types of this tree.
1822 void TreePatternNode::RemoveAllTypes() {
1823   // Reset to unknown type.
1824   std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
1825   if (isLeaf()) return;
1826   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1827     getChild(i)->RemoveAllTypes();
1828 }
1829 
1830 
1831 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1832 /// with actual values specified by ArgMap.
1833 void TreePatternNode::SubstituteFormalArguments(
1834     std::map<std::string, TreePatternNodePtr> &ArgMap) {
1835   if (isLeaf()) return;
1836 
1837   for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1838     TreePatternNode *Child = getChild(i);
1839     if (Child->isLeaf()) {
1840       Init *Val = Child->getLeafValue();
1841       // Note that, when substituting into an output pattern, Val might be an
1842       // UnsetInit.
1843       if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1844           cast<DefInit>(Val)->getDef()->getName() == "node")) {
1845         // We found a use of a formal argument, replace it with its value.
1846         TreePatternNodePtr NewChild = ArgMap[Child->getName()];
1847         assert(NewChild && "Couldn't find formal argument!");
1848         assert((Child->getPredicateFns().empty() ||
1849                 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1850                "Non-empty child predicate clobbered!");
1851         setChild(i, std::move(NewChild));
1852       }
1853     } else {
1854       getChild(i)->SubstituteFormalArguments(ArgMap);
1855     }
1856   }
1857 }
1858 
1859 
1860 /// InlinePatternFragments - If this pattern refers to any pattern
1861 /// fragments, return the set of inlined versions (this can be more than
1862 /// one if a PatFrags record has multiple alternatives).
1863 void TreePatternNode::InlinePatternFragments(
1864   TreePatternNodePtr T, TreePattern &TP,
1865   std::vector<TreePatternNodePtr> &OutAlternatives) {
1866 
1867   if (TP.hasError())
1868     return;
1869 
1870   if (isLeaf()) {
1871     OutAlternatives.push_back(T);  // nothing to do.
1872     return;
1873   }
1874 
1875   Record *Op = getOperator();
1876 
1877   if (!Op->isSubClassOf("PatFrags")) {
1878     if (getNumChildren() == 0) {
1879       OutAlternatives.push_back(T);
1880       return;
1881     }
1882 
1883     // Recursively inline children nodes.
1884     std::vector<std::vector<TreePatternNodePtr> > ChildAlternatives;
1885     ChildAlternatives.resize(getNumChildren());
1886     for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1887       TreePatternNodePtr Child = getChildShared(i);
1888       Child->InlinePatternFragments(Child, TP, ChildAlternatives[i]);
1889       // If there are no alternatives for any child, there are no
1890       // alternatives for this expression as whole.
1891       if (ChildAlternatives[i].empty())
1892         return;
1893 
1894       for (auto NewChild : ChildAlternatives[i])
1895         assert((Child->getPredicateFns().empty() ||
1896                 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1897                "Non-empty child predicate clobbered!");
1898     }
1899 
1900     // The end result is an all-pairs construction of the resultant pattern.
1901     std::vector<unsigned> Idxs;
1902     Idxs.resize(ChildAlternatives.size());
1903     bool NotDone;
1904     do {
1905       // Create the variant and add it to the output list.
1906       std::vector<TreePatternNodePtr> NewChildren;
1907       for (unsigned i = 0, e = ChildAlternatives.size(); i != e; ++i)
1908         NewChildren.push_back(ChildAlternatives[i][Idxs[i]]);
1909       TreePatternNodePtr R = std::make_shared<TreePatternNode>(
1910           getOperator(), std::move(NewChildren), getNumTypes());
1911 
1912       // Copy over properties.
1913       R->setName(getName());
1914       R->setPredicateFns(getPredicateFns());
1915       R->setTransformFn(getTransformFn());
1916       for (unsigned i = 0, e = getNumTypes(); i != e; ++i)
1917         R->setType(i, getExtType(i));
1918 
1919       // Register alternative.
1920       OutAlternatives.push_back(R);
1921 
1922       // Increment indices to the next permutation by incrementing the
1923       // indices from last index backward, e.g., generate the sequence
1924       // [0, 0], [0, 1], [1, 0], [1, 1].
1925       int IdxsIdx;
1926       for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
1927         if (++Idxs[IdxsIdx] == ChildAlternatives[IdxsIdx].size())
1928           Idxs[IdxsIdx] = 0;
1929         else
1930           break;
1931       }
1932       NotDone = (IdxsIdx >= 0);
1933     } while (NotDone);
1934 
1935     return;
1936   }
1937 
1938   // Otherwise, we found a reference to a fragment.  First, look up its
1939   // TreePattern record.
1940   TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
1941 
1942   // Verify that we are passing the right number of operands.
1943   if (Frag->getNumArgs() != Children.size()) {
1944     TP.error("'" + Op->getName() + "' fragment requires " +
1945              Twine(Frag->getNumArgs()) + " operands!");
1946     return;
1947   }
1948 
1949   // Compute the map of formal to actual arguments.
1950   std::map<std::string, TreePatternNodePtr> ArgMap;
1951   for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i) {
1952     const TreePatternNodePtr &Child = getChildShared(i);
1953     ArgMap[Frag->getArgName(i)] = Child;
1954   }
1955 
1956   // Loop over all fragment alternatives.
1957   for (auto Alternative : Frag->getTrees()) {
1958     TreePatternNodePtr FragTree = Alternative->clone();
1959 
1960     TreePredicateFn PredFn(Frag);
1961     if (!PredFn.isAlwaysTrue())
1962       FragTree->addPredicateFn(PredFn);
1963 
1964     // Resolve formal arguments to their actual value.
1965     if (Frag->getNumArgs())
1966       FragTree->SubstituteFormalArguments(ArgMap);
1967 
1968     // Transfer types.  Note that the resolved alternative may have fewer
1969     // (but not more) results than the PatFrags node.
1970     FragTree->setName(getName());
1971     for (unsigned i = 0, e = FragTree->getNumTypes(); i != e; ++i)
1972       FragTree->UpdateNodeType(i, getExtType(i), TP);
1973 
1974     // Transfer in the old predicates.
1975     for (const TreePredicateFn &Pred : getPredicateFns())
1976       FragTree->addPredicateFn(Pred);
1977 
1978     // The fragment we inlined could have recursive inlining that is needed.  See
1979     // if there are any pattern fragments in it and inline them as needed.
1980     FragTree->InlinePatternFragments(FragTree, TP, OutAlternatives);
1981   }
1982 }
1983 
1984 /// getImplicitType - Check to see if the specified record has an implicit
1985 /// type which should be applied to it.  This will infer the type of register
1986 /// references from the register file information, for example.
1987 ///
1988 /// When Unnamed is set, return the type of a DAG operand with no name, such as
1989 /// the F8RC register class argument in:
1990 ///
1991 ///   (COPY_TO_REGCLASS GPR:$src, F8RC)
1992 ///
1993 /// When Unnamed is false, return the type of a named DAG operand such as the
1994 /// GPR:$src operand above.
1995 ///
1996 static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
1997                                        bool NotRegisters,
1998                                        bool Unnamed,
1999                                        TreePattern &TP) {
2000   CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2001 
2002   // Check to see if this is a register operand.
2003   if (R->isSubClassOf("RegisterOperand")) {
2004     assert(ResNo == 0 && "Regoperand ref only has one result!");
2005     if (NotRegisters)
2006       return TypeSetByHwMode(); // Unknown.
2007     Record *RegClass = R->getValueAsDef("RegClass");
2008     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
2009     return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
2010   }
2011 
2012   // Check to see if this is a register or a register class.
2013   if (R->isSubClassOf("RegisterClass")) {
2014     assert(ResNo == 0 && "Regclass ref only has one result!");
2015     // An unnamed register class represents itself as an i32 immediate, for
2016     // example on a COPY_TO_REGCLASS instruction.
2017     if (Unnamed)
2018       return TypeSetByHwMode(MVT::i32);
2019 
2020     // In a named operand, the register class provides the possible set of
2021     // types.
2022     if (NotRegisters)
2023       return TypeSetByHwMode(); // Unknown.
2024     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
2025     return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
2026   }
2027 
2028   if (R->isSubClassOf("PatFrags")) {
2029     assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
2030     // Pattern fragment types will be resolved when they are inlined.
2031     return TypeSetByHwMode(); // Unknown.
2032   }
2033 
2034   if (R->isSubClassOf("Register")) {
2035     assert(ResNo == 0 && "Registers only produce one result!");
2036     if (NotRegisters)
2037       return TypeSetByHwMode(); // Unknown.
2038     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
2039     return TypeSetByHwMode(T.getRegisterVTs(R));
2040   }
2041 
2042   if (R->isSubClassOf("SubRegIndex")) {
2043     assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
2044     return TypeSetByHwMode(MVT::i32);
2045   }
2046 
2047   if (R->isSubClassOf("ValueType")) {
2048     assert(ResNo == 0 && "This node only has one result!");
2049     // An unnamed VTSDNode represents itself as an MVT::Other immediate.
2050     //
2051     //   (sext_inreg GPR:$src, i16)
2052     //                         ~~~
2053     if (Unnamed)
2054       return TypeSetByHwMode(MVT::Other);
2055     // With a name, the ValueType simply provides the type of the named
2056     // variable.
2057     //
2058     //   (sext_inreg i32:$src, i16)
2059     //               ~~~~~~~~
2060     if (NotRegisters)
2061       return TypeSetByHwMode(); // Unknown.
2062     const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2063     return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
2064   }
2065 
2066   if (R->isSubClassOf("CondCode")) {
2067     assert(ResNo == 0 && "This node only has one result!");
2068     // Using a CondCodeSDNode.
2069     return TypeSetByHwMode(MVT::Other);
2070   }
2071 
2072   if (R->isSubClassOf("ComplexPattern")) {
2073     assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
2074     if (NotRegisters)
2075       return TypeSetByHwMode(); // Unknown.
2076     return TypeSetByHwMode(CDP.getComplexPattern(R).getValueType());
2077   }
2078   if (R->isSubClassOf("PointerLikeRegClass")) {
2079     assert(ResNo == 0 && "Regclass can only have one result!");
2080     TypeSetByHwMode VTS(MVT::iPTR);
2081     TP.getInfer().expandOverloads(VTS);
2082     return VTS;
2083   }
2084 
2085   if (R->getName() == "node" || R->getName() == "srcvalue" ||
2086       R->getName() == "zero_reg") {
2087     // Placeholder.
2088     return TypeSetByHwMode(); // Unknown.
2089   }
2090 
2091   if (R->isSubClassOf("Operand")) {
2092     const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2093     Record *T = R->getValueAsDef("Type");
2094     return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
2095   }
2096 
2097   TP.error("Unknown node flavor used in pattern: " + R->getName());
2098   return TypeSetByHwMode(MVT::Other);
2099 }
2100 
2101 
2102 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
2103 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
2104 const CodeGenIntrinsic *TreePatternNode::
2105 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
2106   if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
2107       getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
2108       getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
2109     return nullptr;
2110 
2111   unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
2112   return &CDP.getIntrinsicInfo(IID);
2113 }
2114 
2115 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
2116 /// return the ComplexPattern information, otherwise return null.
2117 const ComplexPattern *
2118 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
2119   Record *Rec;
2120   if (isLeaf()) {
2121     DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2122     if (!DI)
2123       return nullptr;
2124     Rec = DI->getDef();
2125   } else
2126     Rec = getOperator();
2127 
2128   if (!Rec->isSubClassOf("ComplexPattern"))
2129     return nullptr;
2130   return &CGP.getComplexPattern(Rec);
2131 }
2132 
2133 unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
2134   // A ComplexPattern specifically declares how many results it fills in.
2135   if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2136     return CP->getNumOperands();
2137 
2138   // If MIOperandInfo is specified, that gives the count.
2139   if (isLeaf()) {
2140     DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2141     if (DI && DI->getDef()->isSubClassOf("Operand")) {
2142       DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
2143       if (MIOps->getNumArgs())
2144         return MIOps->getNumArgs();
2145     }
2146   }
2147 
2148   // Otherwise there is just one result.
2149   return 1;
2150 }
2151 
2152 /// NodeHasProperty - Return true if this node has the specified property.
2153 bool TreePatternNode::NodeHasProperty(SDNP Property,
2154                                       const CodeGenDAGPatterns &CGP) const {
2155   if (isLeaf()) {
2156     if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2157       return CP->hasProperty(Property);
2158 
2159     return false;
2160   }
2161 
2162   if (Property != SDNPHasChain) {
2163     // The chain proprety is already present on the different intrinsic node
2164     // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
2165     // on the intrinsic. Anything else is specific to the individual intrinsic.
2166     if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CGP))
2167       return Int->hasProperty(Property);
2168   }
2169 
2170   if (!Operator->isSubClassOf("SDPatternOperator"))
2171     return false;
2172 
2173   return CGP.getSDNodeInfo(Operator).hasProperty(Property);
2174 }
2175 
2176 
2177 
2178 
2179 /// TreeHasProperty - Return true if any node in this tree has the specified
2180 /// property.
2181 bool TreePatternNode::TreeHasProperty(SDNP Property,
2182                                       const CodeGenDAGPatterns &CGP) const {
2183   if (NodeHasProperty(Property, CGP))
2184     return true;
2185   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2186     if (getChild(i)->TreeHasProperty(Property, CGP))
2187       return true;
2188   return false;
2189 }
2190 
2191 /// isCommutativeIntrinsic - Return true if the node corresponds to a
2192 /// commutative intrinsic.
2193 bool
2194 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
2195   if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
2196     return Int->isCommutative;
2197   return false;
2198 }
2199 
2200 static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
2201   if (!N->isLeaf())
2202     return N->getOperator()->isSubClassOf(Class);
2203 
2204   DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
2205   if (DI && DI->getDef()->isSubClassOf(Class))
2206     return true;
2207 
2208   return false;
2209 }
2210 
2211 static void emitTooManyOperandsError(TreePattern &TP,
2212                                      StringRef InstName,
2213                                      unsigned Expected,
2214                                      unsigned Actual) {
2215   TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
2216            " operands but expected only " + Twine(Expected) + "!");
2217 }
2218 
2219 static void emitTooFewOperandsError(TreePattern &TP,
2220                                     StringRef InstName,
2221                                     unsigned Actual) {
2222   TP.error("Instruction '" + InstName +
2223            "' expects more than the provided " + Twine(Actual) + " operands!");
2224 }
2225 
2226 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
2227 /// this node and its children in the tree.  This returns true if it makes a
2228 /// change, false otherwise.  If a type contradiction is found, flag an error.
2229 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
2230   if (TP.hasError())
2231     return false;
2232 
2233   CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2234   if (isLeaf()) {
2235     if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
2236       // If it's a regclass or something else known, include the type.
2237       bool MadeChange = false;
2238       for (unsigned i = 0, e = Types.size(); i != e; ++i)
2239         MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
2240                                                         NotRegisters,
2241                                                         !hasName(), TP), TP);
2242       return MadeChange;
2243     }
2244 
2245     if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
2246       assert(Types.size() == 1 && "Invalid IntInit");
2247 
2248       // Int inits are always integers. :)
2249       bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
2250 
2251       if (!TP.getInfer().isConcrete(Types[0], false))
2252         return MadeChange;
2253 
2254       ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
2255       for (auto &P : VVT) {
2256         MVT::SimpleValueType VT = P.second.SimpleTy;
2257         if (VT == MVT::iPTR || VT == MVT::iPTRAny)
2258           continue;
2259         unsigned Size = MVT(VT).getSizeInBits();
2260         // Make sure that the value is representable for this type.
2261         if (Size >= 32)
2262           continue;
2263         // Check that the value doesn't use more bits than we have. It must
2264         // either be a sign- or zero-extended equivalent of the original.
2265         int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
2266         if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
2267             SignBitAndAbove == 1)
2268           continue;
2269 
2270         TP.error("Integer value '" + Twine(II->getValue()) +
2271                  "' is out of range for type '" + getEnumName(VT) + "'!");
2272         break;
2273       }
2274       return MadeChange;
2275     }
2276 
2277     return false;
2278   }
2279 
2280   if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
2281     bool MadeChange = false;
2282 
2283     // Apply the result type to the node.
2284     unsigned NumRetVTs = Int->IS.RetVTs.size();
2285     unsigned NumParamVTs = Int->IS.ParamVTs.size();
2286 
2287     for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
2288       MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
2289 
2290     if (getNumChildren() != NumParamVTs + 1) {
2291       TP.error("Intrinsic '" + Int->Name + "' expects " + Twine(NumParamVTs) +
2292                " operands, not " + Twine(getNumChildren() - 1) + " operands!");
2293       return false;
2294     }
2295 
2296     // Apply type info to the intrinsic ID.
2297     MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
2298 
2299     for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
2300       MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
2301 
2302       MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
2303       assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
2304       MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
2305     }
2306     return MadeChange;
2307   }
2308 
2309   if (getOperator()->isSubClassOf("SDNode")) {
2310     const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
2311 
2312     // Check that the number of operands is sane.  Negative operands -> varargs.
2313     if (NI.getNumOperands() >= 0 &&
2314         getNumChildren() != (unsigned)NI.getNumOperands()) {
2315       TP.error(getOperator()->getName() + " node requires exactly " +
2316                Twine(NI.getNumOperands()) + " operands!");
2317       return false;
2318     }
2319 
2320     bool MadeChange = false;
2321     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2322       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2323     MadeChange |= NI.ApplyTypeConstraints(this, TP);
2324     return MadeChange;
2325   }
2326 
2327   if (getOperator()->isSubClassOf("Instruction")) {
2328     const DAGInstruction &Inst = CDP.getInstruction(getOperator());
2329     CodeGenInstruction &InstInfo =
2330       CDP.getTargetInfo().getInstruction(getOperator());
2331 
2332     bool MadeChange = false;
2333 
2334     // Apply the result types to the node, these come from the things in the
2335     // (outs) list of the instruction.
2336     unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
2337                                         Inst.getNumResults());
2338     for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
2339       MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
2340 
2341     // If the instruction has implicit defs, we apply the first one as a result.
2342     // FIXME: This sucks, it should apply all implicit defs.
2343     if (!InstInfo.ImplicitDefs.empty()) {
2344       unsigned ResNo = NumResultsToAdd;
2345 
2346       // FIXME: Generalize to multiple possible types and multiple possible
2347       // ImplicitDefs.
2348       MVT::SimpleValueType VT =
2349         InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
2350 
2351       if (VT != MVT::Other)
2352         MadeChange |= UpdateNodeType(ResNo, VT, TP);
2353     }
2354 
2355     // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2356     // be the same.
2357     if (getOperator()->getName() == "INSERT_SUBREG") {
2358       assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
2359       MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
2360       MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
2361     } else if (getOperator()->getName() == "REG_SEQUENCE") {
2362       // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2363       // variadic.
2364 
2365       unsigned NChild = getNumChildren();
2366       if (NChild < 3) {
2367         TP.error("REG_SEQUENCE requires at least 3 operands!");
2368         return false;
2369       }
2370 
2371       if (NChild % 2 == 0) {
2372         TP.error("REG_SEQUENCE requires an odd number of operands!");
2373         return false;
2374       }
2375 
2376       if (!isOperandClass(getChild(0), "RegisterClass")) {
2377         TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2378         return false;
2379       }
2380 
2381       for (unsigned I = 1; I < NChild; I += 2) {
2382         TreePatternNode *SubIdxChild = getChild(I + 1);
2383         if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
2384           TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
2385                    Twine(I + 1) + "!");
2386           return false;
2387         }
2388       }
2389     }
2390 
2391     unsigned ChildNo = 0;
2392     for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
2393       Record *OperandNode = Inst.getOperand(i);
2394 
2395       // If the instruction expects a predicate or optional def operand, we
2396       // codegen this by setting the operand to it's default value if it has a
2397       // non-empty DefaultOps field.
2398       if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
2399           !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
2400         continue;
2401 
2402       // Verify that we didn't run out of provided operands.
2403       if (ChildNo >= getNumChildren()) {
2404         emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
2405         return false;
2406       }
2407 
2408       TreePatternNode *Child = getChild(ChildNo++);
2409       unsigned ChildResNo = 0;  // Instructions always use res #0 of their op.
2410 
2411       // If the operand has sub-operands, they may be provided by distinct
2412       // child patterns, so attempt to match each sub-operand separately.
2413       if (OperandNode->isSubClassOf("Operand")) {
2414         DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
2415         if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2416           // But don't do that if the whole operand is being provided by
2417           // a single ComplexPattern-related Operand.
2418 
2419           if (Child->getNumMIResults(CDP) < NumArgs) {
2420             // Match first sub-operand against the child we already have.
2421             Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2422             MadeChange |=
2423               Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2424 
2425             // And the remaining sub-operands against subsequent children.
2426             for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2427               if (ChildNo >= getNumChildren()) {
2428                 emitTooFewOperandsError(TP, getOperator()->getName(),
2429                                         getNumChildren());
2430                 return false;
2431               }
2432               Child = getChild(ChildNo++);
2433 
2434               SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
2435               MadeChange |=
2436                 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2437             }
2438             continue;
2439           }
2440         }
2441       }
2442 
2443       // If we didn't match by pieces above, attempt to match the whole
2444       // operand now.
2445       MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
2446     }
2447 
2448     if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
2449       emitTooManyOperandsError(TP, getOperator()->getName(),
2450                                ChildNo, getNumChildren());
2451       return false;
2452     }
2453 
2454     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2455       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2456     return MadeChange;
2457   }
2458 
2459   if (getOperator()->isSubClassOf("ComplexPattern")) {
2460     bool MadeChange = false;
2461 
2462     for (unsigned i = 0; i < getNumChildren(); ++i)
2463       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2464 
2465     return MadeChange;
2466   }
2467 
2468   assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
2469 
2470   // Node transforms always take one operand.
2471   if (getNumChildren() != 1) {
2472     TP.error("Node transform '" + getOperator()->getName() +
2473              "' requires one operand!");
2474     return false;
2475   }
2476 
2477   bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
2478   return MadeChange;
2479 }
2480 
2481 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2482 /// RHS of a commutative operation, not the on LHS.
2483 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
2484   if (!N->isLeaf() && N->getOperator()->getName() == "imm")
2485     return true;
2486   if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
2487     return true;
2488   return false;
2489 }
2490 
2491 
2492 /// canPatternMatch - If it is impossible for this pattern to match on this
2493 /// target, fill in Reason and return false.  Otherwise, return true.  This is
2494 /// used as a sanity check for .td files (to prevent people from writing stuff
2495 /// that can never possibly work), and to prevent the pattern permuter from
2496 /// generating stuff that is useless.
2497 bool TreePatternNode::canPatternMatch(std::string &Reason,
2498                                       const CodeGenDAGPatterns &CDP) {
2499   if (isLeaf()) return true;
2500 
2501   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2502     if (!getChild(i)->canPatternMatch(Reason, CDP))
2503       return false;
2504 
2505   // If this is an intrinsic, handle cases that would make it not match.  For
2506   // example, if an operand is required to be an immediate.
2507   if (getOperator()->isSubClassOf("Intrinsic")) {
2508     // TODO:
2509     return true;
2510   }
2511 
2512   if (getOperator()->isSubClassOf("ComplexPattern"))
2513     return true;
2514 
2515   // If this node is a commutative operator, check that the LHS isn't an
2516   // immediate.
2517   const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
2518   bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2519   if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2520     // Scan all of the operands of the node and make sure that only the last one
2521     // is a constant node, unless the RHS also is.
2522     if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
2523       unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
2524       for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
2525         if (OnlyOnRHSOfCommutative(getChild(i))) {
2526           Reason="Immediate value must be on the RHS of commutative operators!";
2527           return false;
2528         }
2529     }
2530   }
2531 
2532   return true;
2533 }
2534 
2535 //===----------------------------------------------------------------------===//
2536 // TreePattern implementation
2537 //
2538 
2539 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
2540                          CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2541                          isInputPattern(isInput), HasError(false),
2542                          Infer(*this) {
2543   for (Init *I : RawPat->getValues())
2544     Trees.push_back(ParseTreePattern(I, ""));
2545 }
2546 
2547 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
2548                          CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2549                          isInputPattern(isInput), HasError(false),
2550                          Infer(*this) {
2551   Trees.push_back(ParseTreePattern(Pat, ""));
2552 }
2553 
2554 TreePattern::TreePattern(Record *TheRec, TreePatternNodePtr Pat, bool isInput,
2555                          CodeGenDAGPatterns &cdp)
2556     : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2557       Infer(*this) {
2558   Trees.push_back(Pat);
2559 }
2560 
2561 void TreePattern::error(const Twine &Msg) {
2562   if (HasError)
2563     return;
2564   dump();
2565   PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2566   HasError = true;
2567 }
2568 
2569 void TreePattern::ComputeNamedNodes() {
2570   for (TreePatternNodePtr &Tree : Trees)
2571     ComputeNamedNodes(Tree.get());
2572 }
2573 
2574 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2575   if (!N->getName().empty())
2576     NamedNodes[N->getName()].push_back(N);
2577 
2578   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2579     ComputeNamedNodes(N->getChild(i));
2580 }
2581 
2582 TreePatternNodePtr TreePattern::ParseTreePattern(Init *TheInit,
2583                                                  StringRef OpName) {
2584   if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
2585     Record *R = DI->getDef();
2586 
2587     // Direct reference to a leaf DagNode or PatFrag?  Turn it into a
2588     // TreePatternNode of its own.  For example:
2589     ///   (foo GPR, imm) -> (foo GPR, (imm))
2590     if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrags"))
2591       return ParseTreePattern(
2592         DagInit::get(DI, nullptr,
2593                      std::vector<std::pair<Init*, StringInit*> >()),
2594         OpName);
2595 
2596     // Input argument?
2597     TreePatternNodePtr Res = std::make_shared<TreePatternNode>(DI, 1);
2598     if (R->getName() == "node" && !OpName.empty()) {
2599       if (OpName.empty())
2600         error("'node' argument requires a name to match with operand list");
2601       Args.push_back(OpName);
2602     }
2603 
2604     Res->setName(OpName);
2605     return Res;
2606   }
2607 
2608   // ?:$name or just $name.
2609   if (isa<UnsetInit>(TheInit)) {
2610     if (OpName.empty())
2611       error("'?' argument requires a name to match with operand list");
2612     TreePatternNodePtr Res = std::make_shared<TreePatternNode>(TheInit, 1);
2613     Args.push_back(OpName);
2614     Res->setName(OpName);
2615     return Res;
2616   }
2617 
2618   if (isa<IntInit>(TheInit) || isa<BitInit>(TheInit)) {
2619     if (!OpName.empty())
2620       error("Constant int or bit argument should not have a name!");
2621     if (isa<BitInit>(TheInit))
2622       TheInit = TheInit->convertInitializerTo(IntRecTy::get());
2623     return std::make_shared<TreePatternNode>(TheInit, 1);
2624   }
2625 
2626   if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
2627     // Turn this into an IntInit.
2628     Init *II = BI->convertInitializerTo(IntRecTy::get());
2629     if (!II || !isa<IntInit>(II))
2630       error("Bits value must be constants!");
2631     return ParseTreePattern(II, OpName);
2632   }
2633 
2634   DagInit *Dag = dyn_cast<DagInit>(TheInit);
2635   if (!Dag) {
2636     TheInit->print(errs());
2637     error("Pattern has unexpected init kind!");
2638   }
2639   DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
2640   if (!OpDef) error("Pattern has unexpected operator type!");
2641   Record *Operator = OpDef->getDef();
2642 
2643   if (Operator->isSubClassOf("ValueType")) {
2644     // If the operator is a ValueType, then this must be "type cast" of a leaf
2645     // node.
2646     if (Dag->getNumArgs() != 1)
2647       error("Type cast only takes one operand!");
2648 
2649     TreePatternNodePtr New =
2650         ParseTreePattern(Dag->getArg(0), Dag->getArgNameStr(0));
2651 
2652     // Apply the type cast.
2653     assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2654     const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
2655     New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
2656 
2657     if (!OpName.empty())
2658       error("ValueType cast should not have a name!");
2659     return New;
2660   }
2661 
2662   // Verify that this is something that makes sense for an operator.
2663   if (!Operator->isSubClassOf("PatFrags") &&
2664       !Operator->isSubClassOf("SDNode") &&
2665       !Operator->isSubClassOf("Instruction") &&
2666       !Operator->isSubClassOf("SDNodeXForm") &&
2667       !Operator->isSubClassOf("Intrinsic") &&
2668       !Operator->isSubClassOf("ComplexPattern") &&
2669       Operator->getName() != "set" &&
2670       Operator->getName() != "implicit")
2671     error("Unrecognized node '" + Operator->getName() + "'!");
2672 
2673   //  Check to see if this is something that is illegal in an input pattern.
2674   if (isInputPattern) {
2675     if (Operator->isSubClassOf("Instruction") ||
2676         Operator->isSubClassOf("SDNodeXForm"))
2677       error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2678   } else {
2679     if (Operator->isSubClassOf("Intrinsic"))
2680       error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2681 
2682     if (Operator->isSubClassOf("SDNode") &&
2683         Operator->getName() != "imm" &&
2684         Operator->getName() != "fpimm" &&
2685         Operator->getName() != "tglobaltlsaddr" &&
2686         Operator->getName() != "tconstpool" &&
2687         Operator->getName() != "tjumptable" &&
2688         Operator->getName() != "tframeindex" &&
2689         Operator->getName() != "texternalsym" &&
2690         Operator->getName() != "tblockaddress" &&
2691         Operator->getName() != "tglobaladdr" &&
2692         Operator->getName() != "bb" &&
2693         Operator->getName() != "vt" &&
2694         Operator->getName() != "mcsym")
2695       error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2696   }
2697 
2698   std::vector<TreePatternNodePtr> Children;
2699 
2700   // Parse all the operands.
2701   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
2702     Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
2703 
2704   // Get the actual number of results before Operator is converted to an intrinsic
2705   // node (which is hard-coded to have either zero or one result).
2706   unsigned NumResults = GetNumNodeResults(Operator, CDP);
2707 
2708   // If the operator is an intrinsic, then this is just syntactic sugar for
2709   // (intrinsic_* <number>, ..children..).  Pick the right intrinsic node, and
2710   // convert the intrinsic name to a number.
2711   if (Operator->isSubClassOf("Intrinsic")) {
2712     const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2713     unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2714 
2715     // If this intrinsic returns void, it must have side-effects and thus a
2716     // chain.
2717     if (Int.IS.RetVTs.empty())
2718       Operator = getDAGPatterns().get_intrinsic_void_sdnode();
2719     else if (Int.ModRef != CodeGenIntrinsic::NoMem)
2720       // Has side-effects, requires chain.
2721       Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
2722     else // Otherwise, no chain.
2723       Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
2724 
2725     Children.insert(Children.begin(),
2726                     std::make_shared<TreePatternNode>(IntInit::get(IID), 1));
2727   }
2728 
2729   if (Operator->isSubClassOf("ComplexPattern")) {
2730     for (unsigned i = 0; i < Children.size(); ++i) {
2731       TreePatternNodePtr Child = Children[i];
2732 
2733       if (Child->getName().empty())
2734         error("All arguments to a ComplexPattern must be named");
2735 
2736       // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2737       // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2738       // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2739       auto OperandId = std::make_pair(Operator, i);
2740       auto PrevOp = ComplexPatternOperands.find(Child->getName());
2741       if (PrevOp != ComplexPatternOperands.end()) {
2742         if (PrevOp->getValue() != OperandId)
2743           error("All ComplexPattern operands must appear consistently: "
2744                 "in the same order in just one ComplexPattern instance.");
2745       } else
2746         ComplexPatternOperands[Child->getName()] = OperandId;
2747     }
2748   }
2749 
2750   TreePatternNodePtr Result =
2751       std::make_shared<TreePatternNode>(Operator, std::move(Children),
2752                                         NumResults);
2753   Result->setName(OpName);
2754 
2755   if (Dag->getName()) {
2756     assert(Result->getName().empty());
2757     Result->setName(Dag->getNameStr());
2758   }
2759   return Result;
2760 }
2761 
2762 /// SimplifyTree - See if we can simplify this tree to eliminate something that
2763 /// will never match in favor of something obvious that will.  This is here
2764 /// strictly as a convenience to target authors because it allows them to write
2765 /// more type generic things and have useless type casts fold away.
2766 ///
2767 /// This returns true if any change is made.
2768 static bool SimplifyTree(TreePatternNodePtr &N) {
2769   if (N->isLeaf())
2770     return false;
2771 
2772   // If we have a bitconvert with a resolved type and if the source and
2773   // destination types are the same, then the bitconvert is useless, remove it.
2774   if (N->getOperator()->getName() == "bitconvert" &&
2775       N->getExtType(0).isValueTypeByHwMode(false) &&
2776       N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2777       N->getName().empty()) {
2778     N = N->getChildShared(0);
2779     SimplifyTree(N);
2780     return true;
2781   }
2782 
2783   // Walk all children.
2784   bool MadeChange = false;
2785   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2786     TreePatternNodePtr Child = N->getChildShared(i);
2787     MadeChange |= SimplifyTree(Child);
2788     N->setChild(i, std::move(Child));
2789   }
2790   return MadeChange;
2791 }
2792 
2793 
2794 
2795 /// InferAllTypes - Infer/propagate as many types throughout the expression
2796 /// patterns as possible.  Return true if all types are inferred, false
2797 /// otherwise.  Flags an error if a type contradiction is found.
2798 bool TreePattern::
2799 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2800   if (NamedNodes.empty())
2801     ComputeNamedNodes();
2802 
2803   bool MadeChange = true;
2804   while (MadeChange) {
2805     MadeChange = false;
2806     for (TreePatternNodePtr &Tree : Trees) {
2807       MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2808       MadeChange |= SimplifyTree(Tree);
2809     }
2810 
2811     // If there are constraints on our named nodes, apply them.
2812     for (auto &Entry : NamedNodes) {
2813       SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
2814 
2815       // If we have input named node types, propagate their types to the named
2816       // values here.
2817       if (InNamedTypes) {
2818         if (!InNamedTypes->count(Entry.getKey())) {
2819           error("Node '" + std::string(Entry.getKey()) +
2820                 "' in output pattern but not input pattern");
2821           return true;
2822         }
2823 
2824         const SmallVectorImpl<TreePatternNode*> &InNodes =
2825           InNamedTypes->find(Entry.getKey())->second;
2826 
2827         // The input types should be fully resolved by now.
2828         for (TreePatternNode *Node : Nodes) {
2829           // If this node is a register class, and it is the root of the pattern
2830           // then we're mapping something onto an input register.  We allow
2831           // changing the type of the input register in this case.  This allows
2832           // us to match things like:
2833           //  def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2834           if (Node == Trees[0].get() && Node->isLeaf()) {
2835             DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
2836             if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2837                        DI->getDef()->isSubClassOf("RegisterOperand")))
2838               continue;
2839           }
2840 
2841           assert(Node->getNumTypes() == 1 &&
2842                  InNodes[0]->getNumTypes() == 1 &&
2843                  "FIXME: cannot name multiple result nodes yet");
2844           MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2845                                              *this);
2846         }
2847       }
2848 
2849       // If there are multiple nodes with the same name, they must all have the
2850       // same type.
2851       if (Entry.second.size() > 1) {
2852         for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
2853           TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
2854           assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
2855                  "FIXME: cannot name multiple result nodes yet");
2856 
2857           MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2858           MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
2859         }
2860       }
2861     }
2862   }
2863 
2864   bool HasUnresolvedTypes = false;
2865   for (const TreePatternNodePtr &Tree : Trees)
2866     HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
2867   return !HasUnresolvedTypes;
2868 }
2869 
2870 void TreePattern::print(raw_ostream &OS) const {
2871   OS << getRecord()->getName();
2872   if (!Args.empty()) {
2873     OS << "(" << Args[0];
2874     for (unsigned i = 1, e = Args.size(); i != e; ++i)
2875       OS << ", " << Args[i];
2876     OS << ")";
2877   }
2878   OS << ": ";
2879 
2880   if (Trees.size() > 1)
2881     OS << "[\n";
2882   for (const TreePatternNodePtr &Tree : Trees) {
2883     OS << "\t";
2884     Tree->print(OS);
2885     OS << "\n";
2886   }
2887 
2888   if (Trees.size() > 1)
2889     OS << "]\n";
2890 }
2891 
2892 void TreePattern::dump() const { print(errs()); }
2893 
2894 //===----------------------------------------------------------------------===//
2895 // CodeGenDAGPatterns implementation
2896 //
2897 
2898 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R,
2899                                        PatternRewriterFn PatternRewriter)
2900     : Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()),
2901       PatternRewriter(PatternRewriter) {
2902 
2903   Intrinsics = CodeGenIntrinsicTable(Records, false);
2904   TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
2905   ParseNodeInfo();
2906   ParseNodeTransforms();
2907   ParseComplexPatterns();
2908   ParsePatternFragments();
2909   ParseDefaultOperands();
2910   ParseInstructions();
2911   ParsePatternFragments(/*OutFrags*/true);
2912   ParsePatterns();
2913 
2914   // Break patterns with parameterized types into a series of patterns,
2915   // where each one has a fixed type and is predicated on the conditions
2916   // of the associated HW mode.
2917   ExpandHwModeBasedTypes();
2918 
2919   // Generate variants.  For example, commutative patterns can match
2920   // multiple ways.  Add them to PatternsToMatch as well.
2921   GenerateVariants();
2922 
2923   // Infer instruction flags.  For example, we can detect loads,
2924   // stores, and side effects in many cases by examining an
2925   // instruction's pattern.
2926   InferInstructionFlags();
2927 
2928   // Verify that instruction flags match the patterns.
2929   VerifyInstructionFlags();
2930 }
2931 
2932 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
2933   Record *N = Records.getDef(Name);
2934   if (!N || !N->isSubClassOf("SDNode"))
2935     PrintFatalError("Error getting SDNode '" + Name + "'!");
2936 
2937   return N;
2938 }
2939 
2940 // Parse all of the SDNode definitions for the target, populating SDNodes.
2941 void CodeGenDAGPatterns::ParseNodeInfo() {
2942   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2943   const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
2944 
2945   while (!Nodes.empty()) {
2946     Record *R = Nodes.back();
2947     SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
2948     Nodes.pop_back();
2949   }
2950 
2951   // Get the builtin intrinsic nodes.
2952   intrinsic_void_sdnode     = getSDNodeNamed("intrinsic_void");
2953   intrinsic_w_chain_sdnode  = getSDNodeNamed("intrinsic_w_chain");
2954   intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2955 }
2956 
2957 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2958 /// map, and emit them to the file as functions.
2959 void CodeGenDAGPatterns::ParseNodeTransforms() {
2960   std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2961   while (!Xforms.empty()) {
2962     Record *XFormNode = Xforms.back();
2963     Record *SDNode = XFormNode->getValueAsDef("Opcode");
2964     StringRef Code = XFormNode->getValueAsString("XFormFunction");
2965     SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
2966 
2967     Xforms.pop_back();
2968   }
2969 }
2970 
2971 void CodeGenDAGPatterns::ParseComplexPatterns() {
2972   std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2973   while (!AMs.empty()) {
2974     ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2975     AMs.pop_back();
2976   }
2977 }
2978 
2979 
2980 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2981 /// file, building up the PatternFragments map.  After we've collected them all,
2982 /// inline fragments together as necessary, so that there are no references left
2983 /// inside a pattern fragment to a pattern fragment.
2984 ///
2985 void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
2986   std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrags");
2987 
2988   // First step, parse all of the fragments.
2989   for (Record *Frag : Fragments) {
2990     if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2991       continue;
2992 
2993     ListInit *LI = Frag->getValueAsListInit("Fragments");
2994     TreePattern *P =
2995         (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2996              Frag, LI, !Frag->isSubClassOf("OutPatFrag"),
2997              *this)).get();
2998 
2999     // Validate the argument list, converting it to set, to discard duplicates.
3000     std::vector<std::string> &Args = P->getArgList();
3001     // Copy the args so we can take StringRefs to them.
3002     auto ArgsCopy = Args;
3003     SmallDenseSet<StringRef, 4> OperandsSet;
3004     OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
3005 
3006     if (OperandsSet.count(""))
3007       P->error("Cannot have unnamed 'node' values in pattern fragment!");
3008 
3009     // Parse the operands list.
3010     DagInit *OpsList = Frag->getValueAsDag("Operands");
3011     DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
3012     // Special cases: ops == outs == ins. Different names are used to
3013     // improve readability.
3014     if (!OpsOp ||
3015         (OpsOp->getDef()->getName() != "ops" &&
3016          OpsOp->getDef()->getName() != "outs" &&
3017          OpsOp->getDef()->getName() != "ins"))
3018       P->error("Operands list should start with '(ops ... '!");
3019 
3020     // Copy over the arguments.
3021     Args.clear();
3022     for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
3023       if (!isa<DefInit>(OpsList->getArg(j)) ||
3024           cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
3025         P->error("Operands list should all be 'node' values.");
3026       if (!OpsList->getArgName(j))
3027         P->error("Operands list should have names for each operand!");
3028       StringRef ArgNameStr = OpsList->getArgNameStr(j);
3029       if (!OperandsSet.count(ArgNameStr))
3030         P->error("'" + ArgNameStr +
3031                  "' does not occur in pattern or was multiply specified!");
3032       OperandsSet.erase(ArgNameStr);
3033       Args.push_back(ArgNameStr);
3034     }
3035 
3036     if (!OperandsSet.empty())
3037       P->error("Operands list does not contain an entry for operand '" +
3038                *OperandsSet.begin() + "'!");
3039 
3040     // If there is a code init for this fragment, keep track of the fact that
3041     // this fragment uses it.
3042     TreePredicateFn PredFn(P);
3043     if (!PredFn.isAlwaysTrue())
3044       for (auto T : P->getTrees())
3045         T->addPredicateFn(PredFn);
3046 
3047     // If there is a node transformation corresponding to this, keep track of
3048     // it.
3049     Record *Transform = Frag->getValueAsDef("OperandTransform");
3050     if (!getSDNodeTransform(Transform).second.empty())    // not noop xform?
3051       for (auto T : P->getTrees())
3052         T->setTransformFn(Transform);
3053   }
3054 
3055   // Now that we've parsed all of the tree fragments, do a closure on them so
3056   // that there are not references to PatFrags left inside of them.
3057   for (Record *Frag : Fragments) {
3058     if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
3059       continue;
3060 
3061     TreePattern &ThePat = *PatternFragments[Frag];
3062     ThePat.InlinePatternFragments();
3063 
3064     // Infer as many types as possible.  Don't worry about it if we don't infer
3065     // all of them, some may depend on the inputs of the pattern.  Also, don't
3066     // validate type sets; validation may cause spurious failures e.g. if a
3067     // fragment needs floating-point types but the current target does not have
3068     // any (this is only an error if that fragment is ever used!).
3069     {
3070       TypeInfer::SuppressValidation SV(ThePat.getInfer());
3071       ThePat.InferAllTypes();
3072       ThePat.resetError();
3073     }
3074 
3075     // If debugging, print out the pattern fragment result.
3076     LLVM_DEBUG(ThePat.dump());
3077   }
3078 }
3079 
3080 void CodeGenDAGPatterns::ParseDefaultOperands() {
3081   std::vector<Record*> DefaultOps;
3082   DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
3083 
3084   // Find some SDNode.
3085   assert(!SDNodes.empty() && "No SDNodes parsed?");
3086   Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
3087 
3088   for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
3089     DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
3090 
3091     // Clone the DefaultInfo dag node, changing the operator from 'ops' to
3092     // SomeSDnode so that we can parse this.
3093     std::vector<std::pair<Init*, StringInit*> > Ops;
3094     for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
3095       Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
3096                                    DefaultInfo->getArgName(op)));
3097     DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
3098 
3099     // Create a TreePattern to parse this.
3100     TreePattern P(DefaultOps[i], DI, false, *this);
3101     assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
3102 
3103     // Copy the operands over into a DAGDefaultOperand.
3104     DAGDefaultOperand DefaultOpInfo;
3105 
3106     const TreePatternNodePtr &T = P.getTree(0);
3107     for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
3108       TreePatternNodePtr TPN = T->getChildShared(op);
3109       while (TPN->ApplyTypeConstraints(P, false))
3110         /* Resolve all types */;
3111 
3112       if (TPN->ContainsUnresolvedType(P)) {
3113         PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
3114                         DefaultOps[i]->getName() +
3115                         "' doesn't have a concrete type!");
3116       }
3117       DefaultOpInfo.DefaultOps.push_back(std::move(TPN));
3118     }
3119 
3120     // Insert it into the DefaultOperands map so we can find it later.
3121     DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
3122   }
3123 }
3124 
3125 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3126 /// instruction input.  Return true if this is a real use.
3127 static bool HandleUse(TreePattern &I, TreePatternNodePtr Pat,
3128                       std::map<std::string, TreePatternNodePtr> &InstInputs) {
3129   // No name -> not interesting.
3130   if (Pat->getName().empty()) {
3131     if (Pat->isLeaf()) {
3132       DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
3133       if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
3134                  DI->getDef()->isSubClassOf("RegisterOperand")))
3135         I.error("Input " + DI->getDef()->getName() + " must be named!");
3136     }
3137     return false;
3138   }
3139 
3140   Record *Rec;
3141   if (Pat->isLeaf()) {
3142     DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
3143     if (!DI)
3144       I.error("Input $" + Pat->getName() + " must be an identifier!");
3145     Rec = DI->getDef();
3146   } else {
3147     Rec = Pat->getOperator();
3148   }
3149 
3150   // SRCVALUE nodes are ignored.
3151   if (Rec->getName() == "srcvalue")
3152     return false;
3153 
3154   TreePatternNodePtr &Slot = InstInputs[Pat->getName()];
3155   if (!Slot) {
3156     Slot = Pat;
3157     return true;
3158   }
3159   Record *SlotRec;
3160   if (Slot->isLeaf()) {
3161     SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
3162   } else {
3163     assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
3164     SlotRec = Slot->getOperator();
3165   }
3166 
3167   // Ensure that the inputs agree if we've already seen this input.
3168   if (Rec != SlotRec)
3169     I.error("All $" + Pat->getName() + " inputs must agree with each other");
3170   // Ensure that the types can agree as well.
3171   Slot->UpdateNodeType(0, Pat->getExtType(0), I);
3172   Pat->UpdateNodeType(0, Slot->getExtType(0), I);
3173   if (Slot->getExtTypes() != Pat->getExtTypes())
3174     I.error("All $" + Pat->getName() + " inputs must agree with each other");
3175   return true;
3176 }
3177 
3178 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3179 /// part of "I", the instruction), computing the set of inputs and outputs of
3180 /// the pattern.  Report errors if we see anything naughty.
3181 void CodeGenDAGPatterns::FindPatternInputsAndOutputs(
3182     TreePattern &I, TreePatternNodePtr Pat,
3183     std::map<std::string, TreePatternNodePtr> &InstInputs,
3184     std::map<std::string, TreePatternNodePtr> &InstResults,
3185     std::vector<Record *> &InstImpResults) {
3186 
3187   // The instruction pattern still has unresolved fragments.  For *named*
3188   // nodes we must resolve those here.  This may not result in multiple
3189   // alternatives.
3190   if (!Pat->getName().empty()) {
3191     TreePattern SrcPattern(I.getRecord(), Pat, true, *this);
3192     SrcPattern.InlinePatternFragments();
3193     SrcPattern.InferAllTypes();
3194     Pat = SrcPattern.getOnlyTree();
3195   }
3196 
3197   if (Pat->isLeaf()) {
3198     bool isUse = HandleUse(I, Pat, InstInputs);
3199     if (!isUse && Pat->getTransformFn())
3200       I.error("Cannot specify a transform function for a non-input value!");
3201     return;
3202   }
3203 
3204   if (Pat->getOperator()->getName() == "implicit") {
3205     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
3206       TreePatternNode *Dest = Pat->getChild(i);
3207       if (!Dest->isLeaf())
3208         I.error("implicitly defined value should be a register!");
3209 
3210       DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
3211       if (!Val || !Val->getDef()->isSubClassOf("Register"))
3212         I.error("implicitly defined value should be a register!");
3213       InstImpResults.push_back(Val->getDef());
3214     }
3215     return;
3216   }
3217 
3218   if (Pat->getOperator()->getName() != "set") {
3219     // If this is not a set, verify that the children nodes are not void typed,
3220     // and recurse.
3221     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
3222       if (Pat->getChild(i)->getNumTypes() == 0)
3223         I.error("Cannot have void nodes inside of patterns!");
3224       FindPatternInputsAndOutputs(I, Pat->getChildShared(i), InstInputs,
3225                                   InstResults, InstImpResults);
3226     }
3227 
3228     // If this is a non-leaf node with no children, treat it basically as if
3229     // it were a leaf.  This handles nodes like (imm).
3230     bool isUse = HandleUse(I, Pat, InstInputs);
3231 
3232     if (!isUse && Pat->getTransformFn())
3233       I.error("Cannot specify a transform function for a non-input value!");
3234     return;
3235   }
3236 
3237   // Otherwise, this is a set, validate and collect instruction results.
3238   if (Pat->getNumChildren() == 0)
3239     I.error("set requires operands!");
3240 
3241   if (Pat->getTransformFn())
3242     I.error("Cannot specify a transform function on a set node!");
3243 
3244   // Check the set destinations.
3245   unsigned NumDests = Pat->getNumChildren()-1;
3246   for (unsigned i = 0; i != NumDests; ++i) {
3247     TreePatternNodePtr Dest = Pat->getChildShared(i);
3248     // For set destinations we also must resolve fragments here.
3249     TreePattern DestPattern(I.getRecord(), Dest, false, *this);
3250     DestPattern.InlinePatternFragments();
3251     DestPattern.InferAllTypes();
3252     Dest = DestPattern.getOnlyTree();
3253 
3254     if (!Dest->isLeaf())
3255       I.error("set destination should be a register!");
3256 
3257     DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
3258     if (!Val) {
3259       I.error("set destination should be a register!");
3260       continue;
3261     }
3262 
3263     if (Val->getDef()->isSubClassOf("RegisterClass") ||
3264         Val->getDef()->isSubClassOf("ValueType") ||
3265         Val->getDef()->isSubClassOf("RegisterOperand") ||
3266         Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
3267       if (Dest->getName().empty())
3268         I.error("set destination must have a name!");
3269       if (InstResults.count(Dest->getName()))
3270         I.error("cannot set '" + Dest->getName() + "' multiple times");
3271       InstResults[Dest->getName()] = Dest;
3272     } else if (Val->getDef()->isSubClassOf("Register")) {
3273       InstImpResults.push_back(Val->getDef());
3274     } else {
3275       I.error("set destination should be a register!");
3276     }
3277   }
3278 
3279   // Verify and collect info from the computation.
3280   FindPatternInputsAndOutputs(I, Pat->getChildShared(NumDests), InstInputs,
3281                               InstResults, InstImpResults);
3282 }
3283 
3284 //===----------------------------------------------------------------------===//
3285 // Instruction Analysis
3286 //===----------------------------------------------------------------------===//
3287 
3288 class InstAnalyzer {
3289   const CodeGenDAGPatterns &CDP;
3290 public:
3291   bool hasSideEffects;
3292   bool mayStore;
3293   bool mayLoad;
3294   bool isBitcast;
3295   bool isVariadic;
3296   bool hasChain;
3297 
3298   InstAnalyzer(const CodeGenDAGPatterns &cdp)
3299     : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
3300       isBitcast(false), isVariadic(false), hasChain(false) {}
3301 
3302   void Analyze(const PatternToMatch &Pat) {
3303     const TreePatternNode *N = Pat.getSrcPattern();
3304     AnalyzeNode(N);
3305     // These properties are detected only on the root node.
3306     isBitcast = IsNodeBitcast(N);
3307   }
3308 
3309 private:
3310   bool IsNodeBitcast(const TreePatternNode *N) const {
3311     if (hasSideEffects || mayLoad || mayStore || isVariadic)
3312       return false;
3313 
3314     if (N->isLeaf())
3315       return false;
3316     if (N->getNumChildren() != 1 || !N->getChild(0)->isLeaf())
3317       return false;
3318 
3319     const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
3320     if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
3321       return false;
3322     return OpInfo.getEnumName() == "ISD::BITCAST";
3323   }
3324 
3325 public:
3326   void AnalyzeNode(const TreePatternNode *N) {
3327     if (N->isLeaf()) {
3328       if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
3329         Record *LeafRec = DI->getDef();
3330         // Handle ComplexPattern leaves.
3331         if (LeafRec->isSubClassOf("ComplexPattern")) {
3332           const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
3333           if (CP.hasProperty(SDNPMayStore)) mayStore = true;
3334           if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
3335           if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
3336         }
3337       }
3338       return;
3339     }
3340 
3341     // Analyze children.
3342     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3343       AnalyzeNode(N->getChild(i));
3344 
3345     // Notice properties of the node.
3346     if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
3347     if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
3348     if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
3349     if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
3350     if (N->NodeHasProperty(SDNPHasChain, CDP)) hasChain = true;
3351 
3352     if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
3353       // If this is an intrinsic, analyze it.
3354       if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
3355         mayLoad = true;// These may load memory.
3356 
3357       if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
3358         mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
3359 
3360       if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
3361           IntInfo->hasSideEffects)
3362         // ReadWriteMem intrinsics can have other strange effects.
3363         hasSideEffects = true;
3364     }
3365   }
3366 
3367 };
3368 
3369 static bool InferFromPattern(CodeGenInstruction &InstInfo,
3370                              const InstAnalyzer &PatInfo,
3371                              Record *PatDef) {
3372   bool Error = false;
3373 
3374   // Remember where InstInfo got its flags.
3375   if (InstInfo.hasUndefFlags())
3376       InstInfo.InferredFrom = PatDef;
3377 
3378   // Check explicitly set flags for consistency.
3379   if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3380       !InstInfo.hasSideEffects_Unset) {
3381     // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3382     // the pattern has no side effects. That could be useful for div/rem
3383     // instructions that may trap.
3384     if (!InstInfo.hasSideEffects) {
3385       Error = true;
3386       PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
3387                  Twine(InstInfo.hasSideEffects));
3388     }
3389   }
3390 
3391   if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3392     Error = true;
3393     PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
3394                Twine(InstInfo.mayStore));
3395   }
3396 
3397   if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3398     // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
3399     // Some targets translate immediates to loads.
3400     if (!InstInfo.mayLoad) {
3401       Error = true;
3402       PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
3403                  Twine(InstInfo.mayLoad));
3404     }
3405   }
3406 
3407   // Transfer inferred flags.
3408   InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3409   InstInfo.mayStore |= PatInfo.mayStore;
3410   InstInfo.mayLoad |= PatInfo.mayLoad;
3411 
3412   // These flags are silently added without any verification.
3413   // FIXME: To match historical behavior of TableGen, for now add those flags
3414   // only when we're inferring from the primary instruction pattern.
3415   if (PatDef->isSubClassOf("Instruction")) {
3416     InstInfo.isBitcast |= PatInfo.isBitcast;
3417     InstInfo.hasChain |= PatInfo.hasChain;
3418     InstInfo.hasChain_Inferred = true;
3419   }
3420 
3421   // Don't infer isVariadic. This flag means something different on SDNodes and
3422   // instructions. For example, a CALL SDNode is variadic because it has the
3423   // call arguments as operands, but a CALL instruction is not variadic - it
3424   // has argument registers as implicit, not explicit uses.
3425 
3426   return Error;
3427 }
3428 
3429 /// hasNullFragReference - Return true if the DAG has any reference to the
3430 /// null_frag operator.
3431 static bool hasNullFragReference(DagInit *DI) {
3432   DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
3433   if (!OpDef) return false;
3434   Record *Operator = OpDef->getDef();
3435 
3436   // If this is the null fragment, return true.
3437   if (Operator->getName() == "null_frag") return true;
3438   // If any of the arguments reference the null fragment, return true.
3439   for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
3440     DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
3441     if (Arg && hasNullFragReference(Arg))
3442       return true;
3443   }
3444 
3445   return false;
3446 }
3447 
3448 /// hasNullFragReference - Return true if any DAG in the list references
3449 /// the null_frag operator.
3450 static bool hasNullFragReference(ListInit *LI) {
3451   for (Init *I : LI->getValues()) {
3452     DagInit *DI = dyn_cast<DagInit>(I);
3453     assert(DI && "non-dag in an instruction Pattern list?!");
3454     if (hasNullFragReference(DI))
3455       return true;
3456   }
3457   return false;
3458 }
3459 
3460 /// Get all the instructions in a tree.
3461 static void
3462 getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
3463   if (Tree->isLeaf())
3464     return;
3465   if (Tree->getOperator()->isSubClassOf("Instruction"))
3466     Instrs.push_back(Tree->getOperator());
3467   for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
3468     getInstructionsInTree(Tree->getChild(i), Instrs);
3469 }
3470 
3471 /// Check the class of a pattern leaf node against the instruction operand it
3472 /// represents.
3473 static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
3474                               Record *Leaf) {
3475   if (OI.Rec == Leaf)
3476     return true;
3477 
3478   // Allow direct value types to be used in instruction set patterns.
3479   // The type will be checked later.
3480   if (Leaf->isSubClassOf("ValueType"))
3481     return true;
3482 
3483   // Patterns can also be ComplexPattern instances.
3484   if (Leaf->isSubClassOf("ComplexPattern"))
3485     return true;
3486 
3487   return false;
3488 }
3489 
3490 void CodeGenDAGPatterns::parseInstructionPattern(
3491     CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
3492 
3493   assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
3494 
3495   // Parse the instruction.
3496   TreePattern I(CGI.TheDef, Pat, true, *this);
3497 
3498   // InstInputs - Keep track of all of the inputs of the instruction, along
3499   // with the record they are declared as.
3500   std::map<std::string, TreePatternNodePtr> InstInputs;
3501 
3502   // InstResults - Keep track of all the virtual registers that are 'set'
3503   // in the instruction, including what reg class they are.
3504   std::map<std::string, TreePatternNodePtr> InstResults;
3505 
3506   std::vector<Record*> InstImpResults;
3507 
3508   // Verify that the top-level forms in the instruction are of void type, and
3509   // fill in the InstResults map.
3510   SmallString<32> TypesString;
3511   for (unsigned j = 0, e = I.getNumTrees(); j != e; ++j) {
3512     TypesString.clear();
3513     TreePatternNodePtr Pat = I.getTree(j);
3514     if (Pat->getNumTypes() != 0) {
3515       raw_svector_ostream OS(TypesString);
3516       for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3517         if (k > 0)
3518           OS << ", ";
3519         Pat->getExtType(k).writeToStream(OS);
3520       }
3521       I.error("Top-level forms in instruction pattern should have"
3522                " void types, has types " +
3523                OS.str());
3524     }
3525 
3526     // Find inputs and outputs, and verify the structure of the uses/defs.
3527     FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
3528                                 InstImpResults);
3529   }
3530 
3531   // Now that we have inputs and outputs of the pattern, inspect the operands
3532   // list for the instruction.  This determines the order that operands are
3533   // added to the machine instruction the node corresponds to.
3534   unsigned NumResults = InstResults.size();
3535 
3536   // Parse the operands list from the (ops) list, validating it.
3537   assert(I.getArgList().empty() && "Args list should still be empty here!");
3538 
3539   // Check that all of the results occur first in the list.
3540   std::vector<Record*> Results;
3541   SmallVector<TreePatternNodePtr, 2> ResNodes;
3542   for (unsigned i = 0; i != NumResults; ++i) {
3543     if (i == CGI.Operands.size())
3544       I.error("'" + InstResults.begin()->first +
3545                "' set but does not appear in operand list!");
3546     const std::string &OpName = CGI.Operands[i].Name;
3547 
3548     // Check that it exists in InstResults.
3549     TreePatternNodePtr RNode = InstResults[OpName];
3550     if (!RNode)
3551       I.error("Operand $" + OpName + " does not exist in operand list!");
3552 
3553 
3554     Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
3555     ResNodes.push_back(std::move(RNode));
3556     if (!R)
3557       I.error("Operand $" + OpName + " should be a set destination: all "
3558                "outputs must occur before inputs in operand list!");
3559 
3560     if (!checkOperandClass(CGI.Operands[i], R))
3561       I.error("Operand $" + OpName + " class mismatch!");
3562 
3563     // Remember the return type.
3564     Results.push_back(CGI.Operands[i].Rec);
3565 
3566     // Okay, this one checks out.
3567     InstResults.erase(OpName);
3568   }
3569 
3570   // Loop over the inputs next.
3571   std::vector<TreePatternNodePtr> ResultNodeOperands;
3572   std::vector<Record*> Operands;
3573   for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3574     CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3575     const std::string &OpName = Op.Name;
3576     if (OpName.empty())
3577       I.error("Operand #" + Twine(i) + " in operands list has no name!");
3578 
3579     if (!InstInputs.count(OpName)) {
3580       // If this is an operand with a DefaultOps set filled in, we can ignore
3581       // this.  When we codegen it, we will do so as always executed.
3582       if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3583         // Does it have a non-empty DefaultOps field?  If so, ignore this
3584         // operand.
3585         if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3586           continue;
3587       }
3588       I.error("Operand $" + OpName +
3589                " does not appear in the instruction pattern");
3590     }
3591     TreePatternNodePtr InVal = InstInputs[OpName];
3592     InstInputs.erase(OpName);   // It occurred, remove from map.
3593 
3594     if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3595       Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3596       if (!checkOperandClass(Op, InRec))
3597         I.error("Operand $" + OpName + "'s register class disagrees"
3598                  " between the operand and pattern");
3599     }
3600     Operands.push_back(Op.Rec);
3601 
3602     // Construct the result for the dest-pattern operand list.
3603     TreePatternNodePtr OpNode = InVal->clone();
3604 
3605     // No predicate is useful on the result.
3606     OpNode->clearPredicateFns();
3607 
3608     // Promote the xform function to be an explicit node if set.
3609     if (Record *Xform = OpNode->getTransformFn()) {
3610       OpNode->setTransformFn(nullptr);
3611       std::vector<TreePatternNodePtr> Children;
3612       Children.push_back(OpNode);
3613       OpNode = std::make_shared<TreePatternNode>(Xform, std::move(Children),
3614                                                  OpNode->getNumTypes());
3615     }
3616 
3617     ResultNodeOperands.push_back(std::move(OpNode));
3618   }
3619 
3620   if (!InstInputs.empty())
3621     I.error("Input operand $" + InstInputs.begin()->first +
3622             " occurs in pattern but not in operands list!");
3623 
3624   TreePatternNodePtr ResultPattern = std::make_shared<TreePatternNode>(
3625       I.getRecord(), std::move(ResultNodeOperands),
3626       GetNumNodeResults(I.getRecord(), *this));
3627   // Copy fully inferred output node types to instruction result pattern.
3628   for (unsigned i = 0; i != NumResults; ++i) {
3629     assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3630     ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3631   }
3632 
3633   // FIXME: Assume only the first tree is the pattern. The others are clobber
3634   // nodes.
3635   TreePatternNodePtr Pattern = I.getTree(0);
3636   TreePatternNodePtr SrcPattern;
3637   if (Pattern->getOperator()->getName() == "set") {
3638     SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3639   } else{
3640     // Not a set (store or something?)
3641     SrcPattern = Pattern;
3642   }
3643 
3644   // Create and insert the instruction.
3645   // FIXME: InstImpResults should not be part of DAGInstruction.
3646   Record *R = I.getRecord();
3647   DAGInsts.emplace(std::piecewise_construct, std::forward_as_tuple(R),
3648                    std::forward_as_tuple(Results, Operands, InstImpResults,
3649                                          SrcPattern, ResultPattern));
3650 
3651   LLVM_DEBUG(I.dump());
3652 }
3653 
3654 /// ParseInstructions - Parse all of the instructions, inlining and resolving
3655 /// any fragments involved.  This populates the Instructions list with fully
3656 /// resolved instructions.
3657 void CodeGenDAGPatterns::ParseInstructions() {
3658   std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3659 
3660   for (Record *Instr : Instrs) {
3661     ListInit *LI = nullptr;
3662 
3663     if (isa<ListInit>(Instr->getValueInit("Pattern")))
3664       LI = Instr->getValueAsListInit("Pattern");
3665 
3666     // If there is no pattern, only collect minimal information about the
3667     // instruction for its operand list.  We have to assume that there is one
3668     // result, as we have no detailed info. A pattern which references the
3669     // null_frag operator is as-if no pattern were specified. Normally this
3670     // is from a multiclass expansion w/ a SDPatternOperator passed in as
3671     // null_frag.
3672     if (!LI || LI->empty() || hasNullFragReference(LI)) {
3673       std::vector<Record*> Results;
3674       std::vector<Record*> Operands;
3675 
3676       CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3677 
3678       if (InstInfo.Operands.size() != 0) {
3679         for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3680           Results.push_back(InstInfo.Operands[j].Rec);
3681 
3682         // The rest are inputs.
3683         for (unsigned j = InstInfo.Operands.NumDefs,
3684                e = InstInfo.Operands.size(); j < e; ++j)
3685           Operands.push_back(InstInfo.Operands[j].Rec);
3686       }
3687 
3688       // Create and insert the instruction.
3689       std::vector<Record*> ImpResults;
3690       Instructions.insert(std::make_pair(Instr,
3691                             DAGInstruction(Results, Operands, ImpResults)));
3692       continue;  // no pattern.
3693     }
3694 
3695     CodeGenInstruction &CGI = Target.getInstruction(Instr);
3696     parseInstructionPattern(CGI, LI, Instructions);
3697   }
3698 
3699   // If we can, convert the instructions to be patterns that are matched!
3700   for (auto &Entry : Instructions) {
3701     Record *Instr = Entry.first;
3702     DAGInstruction &TheInst = Entry.second;
3703     TreePatternNodePtr SrcPattern = TheInst.getSrcPattern();
3704     TreePatternNodePtr ResultPattern = TheInst.getResultPattern();
3705 
3706     if (SrcPattern && ResultPattern) {
3707       TreePattern Pattern(Instr, SrcPattern, true, *this);
3708       TreePattern Result(Instr, ResultPattern, false, *this);
3709       ParseOnePattern(Instr, Pattern, Result, TheInst.getImpResults());
3710     }
3711   }
3712 }
3713 
3714 typedef std::pair<TreePatternNode *, unsigned> NameRecord;
3715 
3716 static void FindNames(TreePatternNode *P,
3717                       std::map<std::string, NameRecord> &Names,
3718                       TreePattern *PatternTop) {
3719   if (!P->getName().empty()) {
3720     NameRecord &Rec = Names[P->getName()];
3721     // If this is the first instance of the name, remember the node.
3722     if (Rec.second++ == 0)
3723       Rec.first = P;
3724     else if (Rec.first->getExtTypes() != P->getExtTypes())
3725       PatternTop->error("repetition of value: $" + P->getName() +
3726                         " where different uses have different types!");
3727   }
3728 
3729   if (!P->isLeaf()) {
3730     for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3731       FindNames(P->getChild(i), Names, PatternTop);
3732   }
3733 }
3734 
3735 std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) {
3736   std::vector<Predicate> Preds;
3737   for (Init *I : L->getValues()) {
3738     if (DefInit *Pred = dyn_cast<DefInit>(I))
3739       Preds.push_back(Pred->getDef());
3740     else
3741       llvm_unreachable("Non-def on the list");
3742   }
3743 
3744   // Sort so that different orders get canonicalized to the same string.
3745   llvm::sort(Preds.begin(), Preds.end());
3746   return Preds;
3747 }
3748 
3749 void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
3750                                            PatternToMatch &&PTM) {
3751   // Do some sanity checking on the pattern we're about to match.
3752   std::string Reason;
3753   if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3754     PrintWarning(Pattern->getRecord()->getLoc(),
3755       Twine("Pattern can never match: ") + Reason);
3756     return;
3757   }
3758 
3759   // If the source pattern's root is a complex pattern, that complex pattern
3760   // must specify the nodes it can potentially match.
3761   if (const ComplexPattern *CP =
3762         PTM.getSrcPattern()->getComplexPatternInfo(*this))
3763     if (CP->getRootNodes().empty())
3764       Pattern->error("ComplexPattern at root must specify list of opcodes it"
3765                      " could match");
3766 
3767 
3768   // Find all of the named values in the input and output, ensure they have the
3769   // same type.
3770   std::map<std::string, NameRecord> SrcNames, DstNames;
3771   FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3772   FindNames(PTM.getDstPattern(), DstNames, Pattern);
3773 
3774   // Scan all of the named values in the destination pattern, rejecting them if
3775   // they don't exist in the input pattern.
3776   for (const auto &Entry : DstNames) {
3777     if (SrcNames[Entry.first].first == nullptr)
3778       Pattern->error("Pattern has input without matching name in output: $" +
3779                      Entry.first);
3780   }
3781 
3782   // Scan all of the named values in the source pattern, rejecting them if the
3783   // name isn't used in the dest, and isn't used to tie two values together.
3784   for (const auto &Entry : SrcNames)
3785     if (DstNames[Entry.first].first == nullptr &&
3786         SrcNames[Entry.first].second == 1)
3787       Pattern->error("Pattern has dead named input: $" + Entry.first);
3788 
3789   PatternsToMatch.push_back(PTM);
3790 }
3791 
3792 void CodeGenDAGPatterns::InferInstructionFlags() {
3793   ArrayRef<const CodeGenInstruction*> Instructions =
3794     Target.getInstructionsByEnumValue();
3795 
3796   unsigned Errors = 0;
3797 
3798   // Try to infer flags from all patterns in PatternToMatch.  These include
3799   // both the primary instruction patterns (which always come first) and
3800   // patterns defined outside the instruction.
3801   for (const PatternToMatch &PTM : ptms()) {
3802     // We can only infer from single-instruction patterns, otherwise we won't
3803     // know which instruction should get the flags.
3804     SmallVector<Record*, 8> PatInstrs;
3805     getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3806     if (PatInstrs.size() != 1)
3807       continue;
3808 
3809     // Get the single instruction.
3810     CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3811 
3812     // Only infer properties from the first pattern. We'll verify the others.
3813     if (InstInfo.InferredFrom)
3814       continue;
3815 
3816     InstAnalyzer PatInfo(*this);
3817     PatInfo.Analyze(PTM);
3818     Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3819   }
3820 
3821   if (Errors)
3822     PrintFatalError("pattern conflicts");
3823 
3824   // If requested by the target, guess any undefined properties.
3825   if (Target.guessInstructionProperties()) {
3826     for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3827       CodeGenInstruction *InstInfo =
3828         const_cast<CodeGenInstruction *>(Instructions[i]);
3829       if (InstInfo->InferredFrom)
3830         continue;
3831       // The mayLoad and mayStore flags default to false.
3832       // Conservatively assume hasSideEffects if it wasn't explicit.
3833       if (InstInfo->hasSideEffects_Unset)
3834         InstInfo->hasSideEffects = true;
3835     }
3836     return;
3837   }
3838 
3839   // Complain about any flags that are still undefined.
3840   for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3841     CodeGenInstruction *InstInfo =
3842       const_cast<CodeGenInstruction *>(Instructions[i]);
3843     if (InstInfo->InferredFrom)
3844       continue;
3845     if (InstInfo->hasSideEffects_Unset)
3846       PrintError(InstInfo->TheDef->getLoc(),
3847                  "Can't infer hasSideEffects from patterns");
3848     if (InstInfo->mayStore_Unset)
3849       PrintError(InstInfo->TheDef->getLoc(),
3850                  "Can't infer mayStore from patterns");
3851     if (InstInfo->mayLoad_Unset)
3852       PrintError(InstInfo->TheDef->getLoc(),
3853                  "Can't infer mayLoad from patterns");
3854   }
3855 }
3856 
3857 
3858 /// Verify instruction flags against pattern node properties.
3859 void CodeGenDAGPatterns::VerifyInstructionFlags() {
3860   unsigned Errors = 0;
3861   for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3862     const PatternToMatch &PTM = *I;
3863     SmallVector<Record*, 8> Instrs;
3864     getInstructionsInTree(PTM.getDstPattern(), Instrs);
3865     if (Instrs.empty())
3866       continue;
3867 
3868     // Count the number of instructions with each flag set.
3869     unsigned NumSideEffects = 0;
3870     unsigned NumStores = 0;
3871     unsigned NumLoads = 0;
3872     for (const Record *Instr : Instrs) {
3873       const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3874       NumSideEffects += InstInfo.hasSideEffects;
3875       NumStores += InstInfo.mayStore;
3876       NumLoads += InstInfo.mayLoad;
3877     }
3878 
3879     // Analyze the source pattern.
3880     InstAnalyzer PatInfo(*this);
3881     PatInfo.Analyze(PTM);
3882 
3883     // Collect error messages.
3884     SmallVector<std::string, 4> Msgs;
3885 
3886     // Check for missing flags in the output.
3887     // Permit extra flags for now at least.
3888     if (PatInfo.hasSideEffects && !NumSideEffects)
3889       Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3890 
3891     // Don't verify store flags on instructions with side effects. At least for
3892     // intrinsics, side effects implies mayStore.
3893     if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3894       Msgs.push_back("pattern may store, but mayStore isn't set");
3895 
3896     // Similarly, mayStore implies mayLoad on intrinsics.
3897     if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3898       Msgs.push_back("pattern may load, but mayLoad isn't set");
3899 
3900     // Print error messages.
3901     if (Msgs.empty())
3902       continue;
3903     ++Errors;
3904 
3905     for (const std::string &Msg : Msgs)
3906       PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
3907                  (Instrs.size() == 1 ?
3908                   "instruction" : "output instructions"));
3909     // Provide the location of the relevant instruction definitions.
3910     for (const Record *Instr : Instrs) {
3911       if (Instr != PTM.getSrcRecord())
3912         PrintError(Instr->getLoc(), "defined here");
3913       const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3914       if (InstInfo.InferredFrom &&
3915           InstInfo.InferredFrom != InstInfo.TheDef &&
3916           InstInfo.InferredFrom != PTM.getSrcRecord())
3917         PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
3918     }
3919   }
3920   if (Errors)
3921     PrintFatalError("Errors in DAG patterns");
3922 }
3923 
3924 /// Given a pattern result with an unresolved type, see if we can find one
3925 /// instruction with an unresolved result type.  Force this result type to an
3926 /// arbitrary element if it's possible types to converge results.
3927 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3928   if (N->isLeaf())
3929     return false;
3930 
3931   // Analyze children.
3932   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3933     if (ForceArbitraryInstResultType(N->getChild(i), TP))
3934       return true;
3935 
3936   if (!N->getOperator()->isSubClassOf("Instruction"))
3937     return false;
3938 
3939   // If this type is already concrete or completely unknown we can't do
3940   // anything.
3941   TypeInfer &TI = TP.getInfer();
3942   for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3943     if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
3944       continue;
3945 
3946     // Otherwise, force its type to an arbitrary choice.
3947     if (TI.forceArbitrary(N->getExtType(i)))
3948       return true;
3949   }
3950 
3951   return false;
3952 }
3953 
3954 // Promote xform function to be an explicit node wherever set.
3955 static TreePatternNodePtr PromoteXForms(TreePatternNodePtr N) {
3956   if (Record *Xform = N->getTransformFn()) {
3957       N->setTransformFn(nullptr);
3958       std::vector<TreePatternNodePtr> Children;
3959       Children.push_back(PromoteXForms(N));
3960       return std::make_shared<TreePatternNode>(Xform, std::move(Children),
3961                                                N->getNumTypes());
3962   }
3963 
3964   if (!N->isLeaf())
3965     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3966       TreePatternNodePtr Child = N->getChildShared(i);
3967       N->setChild(i, PromoteXForms(Child));
3968     }
3969   return N;
3970 }
3971 
3972 void CodeGenDAGPatterns::ParseOnePattern(Record *TheDef,
3973        TreePattern &Pattern, TreePattern &Result,
3974        const std::vector<Record *> &InstImpResults) {
3975 
3976   // Inline pattern fragments and expand multiple alternatives.
3977   Pattern.InlinePatternFragments();
3978   Result.InlinePatternFragments();
3979 
3980   if (Result.getNumTrees() != 1)
3981     Result.error("Cannot use multi-alternative fragments in result pattern!");
3982 
3983   // Infer types.
3984   bool IterateInference;
3985   bool InferredAllPatternTypes, InferredAllResultTypes;
3986   do {
3987     // Infer as many types as possible.  If we cannot infer all of them, we
3988     // can never do anything with this pattern: report it to the user.
3989     InferredAllPatternTypes =
3990         Pattern.InferAllTypes(&Pattern.getNamedNodesMap());
3991 
3992     // Infer as many types as possible.  If we cannot infer all of them, we
3993     // can never do anything with this pattern: report it to the user.
3994     InferredAllResultTypes =
3995         Result.InferAllTypes(&Pattern.getNamedNodesMap());
3996 
3997     IterateInference = false;
3998 
3999     // Apply the type of the result to the source pattern.  This helps us
4000     // resolve cases where the input type is known to be a pointer type (which
4001     // is considered resolved), but the result knows it needs to be 32- or
4002     // 64-bits.  Infer the other way for good measure.
4003     for (auto T : Pattern.getTrees())
4004       for (unsigned i = 0, e = std::min(Result.getOnlyTree()->getNumTypes(),
4005                                         T->getNumTypes());
4006          i != e; ++i) {
4007         IterateInference |= T->UpdateNodeType(
4008             i, Result.getOnlyTree()->getExtType(i), Result);
4009         IterateInference |= Result.getOnlyTree()->UpdateNodeType(
4010             i, T->getExtType(i), Result);
4011       }
4012 
4013     // If our iteration has converged and the input pattern's types are fully
4014     // resolved but the result pattern is not fully resolved, we may have a
4015     // situation where we have two instructions in the result pattern and
4016     // the instructions require a common register class, but don't care about
4017     // what actual MVT is used.  This is actually a bug in our modelling:
4018     // output patterns should have register classes, not MVTs.
4019     //
4020     // In any case, to handle this, we just go through and disambiguate some
4021     // arbitrary types to the result pattern's nodes.
4022     if (!IterateInference && InferredAllPatternTypes &&
4023         !InferredAllResultTypes)
4024       IterateInference =
4025           ForceArbitraryInstResultType(Result.getTree(0).get(), Result);
4026   } while (IterateInference);
4027 
4028   // Verify that we inferred enough types that we can do something with the
4029   // pattern and result.  If these fire the user has to add type casts.
4030   if (!InferredAllPatternTypes)
4031     Pattern.error("Could not infer all types in pattern!");
4032   if (!InferredAllResultTypes) {
4033     Pattern.dump();
4034     Result.error("Could not infer all types in pattern result!");
4035   }
4036 
4037   // Promote xform function to be an explicit node wherever set.
4038   TreePatternNodePtr DstShared = PromoteXForms(Result.getOnlyTree());
4039 
4040   TreePattern Temp(Result.getRecord(), DstShared, false, *this);
4041   Temp.InferAllTypes();
4042 
4043   ListInit *Preds = TheDef->getValueAsListInit("Predicates");
4044   int Complexity = TheDef->getValueAsInt("AddedComplexity");
4045 
4046   if (PatternRewriter)
4047     PatternRewriter(&Pattern);
4048 
4049   // A pattern may end up with an "impossible" type, i.e. a situation
4050   // where all types have been eliminated for some node in this pattern.
4051   // This could occur for intrinsics that only make sense for a specific
4052   // value type, and use a specific register class. If, for some mode,
4053   // that register class does not accept that type, the type inference
4054   // will lead to a contradiction, which is not an error however, but
4055   // a sign that this pattern will simply never match.
4056   if (Temp.getOnlyTree()->hasPossibleType())
4057     for (auto T : Pattern.getTrees())
4058       if (T->hasPossibleType())
4059         AddPatternToMatch(&Pattern,
4060                           PatternToMatch(TheDef, makePredList(Preds),
4061                                          T, Temp.getOnlyTree(),
4062                                          InstImpResults, Complexity,
4063                                          TheDef->getID()));
4064 }
4065 
4066 void CodeGenDAGPatterns::ParsePatterns() {
4067   std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
4068 
4069   for (Record *CurPattern : Patterns) {
4070     DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
4071 
4072     // If the pattern references the null_frag, there's nothing to do.
4073     if (hasNullFragReference(Tree))
4074       continue;
4075 
4076     TreePattern Pattern(CurPattern, Tree, true, *this);
4077 
4078     ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
4079     if (LI->empty()) continue;  // no pattern.
4080 
4081     // Parse the instruction.
4082     TreePattern Result(CurPattern, LI, false, *this);
4083 
4084     if (Result.getNumTrees() != 1)
4085       Result.error("Cannot handle instructions producing instructions "
4086                    "with temporaries yet!");
4087 
4088     // Validate that the input pattern is correct.
4089     std::map<std::string, TreePatternNodePtr> InstInputs;
4090     std::map<std::string, TreePatternNodePtr> InstResults;
4091     std::vector<Record*> InstImpResults;
4092     for (unsigned j = 0, ee = Pattern.getNumTrees(); j != ee; ++j)
4093       FindPatternInputsAndOutputs(Pattern, Pattern.getTree(j), InstInputs,
4094                                   InstResults, InstImpResults);
4095 
4096     ParseOnePattern(CurPattern, Pattern, Result, InstImpResults);
4097   }
4098 }
4099 
4100 static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
4101   for (const TypeSetByHwMode &VTS : N->getExtTypes())
4102     for (const auto &I : VTS)
4103       Modes.insert(I.first);
4104 
4105   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
4106     collectModes(Modes, N->getChild(i));
4107 }
4108 
4109 void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
4110   const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
4111   std::map<unsigned,std::vector<Predicate>> ModeChecks;
4112   std::vector<PatternToMatch> Copy = PatternsToMatch;
4113   PatternsToMatch.clear();
4114 
4115   auto AppendPattern = [this, &ModeChecks](PatternToMatch &P, unsigned Mode) {
4116     TreePatternNodePtr NewSrc = P.SrcPattern->clone();
4117     TreePatternNodePtr NewDst = P.DstPattern->clone();
4118     if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
4119       return;
4120     }
4121 
4122     std::vector<Predicate> Preds = P.Predicates;
4123     const std::vector<Predicate> &MC = ModeChecks[Mode];
4124     Preds.insert(Preds.end(), MC.begin(), MC.end());
4125     PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, std::move(NewSrc),
4126                                  std::move(NewDst), P.getDstRegs(),
4127                                  P.getAddedComplexity(), Record::getNewUID(),
4128                                  Mode);
4129   };
4130 
4131   for (PatternToMatch &P : Copy) {
4132     TreePatternNodePtr SrcP = nullptr, DstP = nullptr;
4133     if (P.SrcPattern->hasProperTypeByHwMode())
4134       SrcP = P.SrcPattern;
4135     if (P.DstPattern->hasProperTypeByHwMode())
4136       DstP = P.DstPattern;
4137     if (!SrcP && !DstP) {
4138       PatternsToMatch.push_back(P);
4139       continue;
4140     }
4141 
4142     std::set<unsigned> Modes;
4143     if (SrcP)
4144       collectModes(Modes, SrcP.get());
4145     if (DstP)
4146       collectModes(Modes, DstP.get());
4147 
4148     // The predicate for the default mode needs to be constructed for each
4149     // pattern separately.
4150     // Since not all modes must be present in each pattern, if a mode m is
4151     // absent, then there is no point in constructing a check for m. If such
4152     // a check was created, it would be equivalent to checking the default
4153     // mode, except not all modes' predicates would be a part of the checking
4154     // code. The subsequently generated check for the default mode would then
4155     // have the exact same patterns, but a different predicate code. To avoid
4156     // duplicated patterns with different predicate checks, construct the
4157     // default check as a negation of all predicates that are actually present
4158     // in the source/destination patterns.
4159     std::vector<Predicate> DefaultPred;
4160 
4161     for (unsigned M : Modes) {
4162       if (M == DefaultMode)
4163         continue;
4164       if (ModeChecks.find(M) != ModeChecks.end())
4165         continue;
4166 
4167       // Fill the map entry for this mode.
4168       const HwMode &HM = CGH.getMode(M);
4169       ModeChecks[M].emplace_back(Predicate(HM.Features, true));
4170 
4171       // Add negations of the HM's predicates to the default predicate.
4172       DefaultPred.emplace_back(Predicate(HM.Features, false));
4173     }
4174 
4175     for (unsigned M : Modes) {
4176       if (M == DefaultMode)
4177         continue;
4178       AppendPattern(P, M);
4179     }
4180 
4181     bool HasDefault = Modes.count(DefaultMode);
4182     if (HasDefault)
4183       AppendPattern(P, DefaultMode);
4184   }
4185 }
4186 
4187 /// Dependent variable map for CodeGenDAGPattern variant generation
4188 typedef StringMap<int> DepVarMap;
4189 
4190 static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
4191   if (N->isLeaf()) {
4192     if (N->hasName() && isa<DefInit>(N->getLeafValue()))
4193       DepMap[N->getName()]++;
4194   } else {
4195     for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
4196       FindDepVarsOf(N->getChild(i), DepMap);
4197   }
4198 }
4199 
4200 /// Find dependent variables within child patterns
4201 static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
4202   DepVarMap depcounts;
4203   FindDepVarsOf(N, depcounts);
4204   for (const auto &Pair : depcounts) {
4205     if (Pair.getValue() > 1)
4206       DepVars.insert(Pair.getKey());
4207   }
4208 }
4209 
4210 #ifndef NDEBUG
4211 /// Dump the dependent variable set:
4212 static void DumpDepVars(MultipleUseVarSet &DepVars) {
4213   if (DepVars.empty()) {
4214     LLVM_DEBUG(errs() << "<empty set>");
4215   } else {
4216     LLVM_DEBUG(errs() << "[ ");
4217     for (const auto &DepVar : DepVars) {
4218       LLVM_DEBUG(errs() << DepVar.getKey() << " ");
4219     }
4220     LLVM_DEBUG(errs() << "]");
4221   }
4222 }
4223 #endif
4224 
4225 
4226 /// CombineChildVariants - Given a bunch of permutations of each child of the
4227 /// 'operator' node, put them together in all possible ways.
4228 static void CombineChildVariants(
4229     TreePatternNodePtr Orig,
4230     const std::vector<std::vector<TreePatternNodePtr>> &ChildVariants,
4231     std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP,
4232     const MultipleUseVarSet &DepVars) {
4233   // Make sure that each operand has at least one variant to choose from.
4234   for (const auto &Variants : ChildVariants)
4235     if (Variants.empty())
4236       return;
4237 
4238   // The end result is an all-pairs construction of the resultant pattern.
4239   std::vector<unsigned> Idxs;
4240   Idxs.resize(ChildVariants.size());
4241   bool NotDone;
4242   do {
4243 #ifndef NDEBUG
4244     LLVM_DEBUG(if (!Idxs.empty()) {
4245       errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
4246       for (unsigned Idx : Idxs) {
4247         errs() << Idx << " ";
4248       }
4249       errs() << "]\n";
4250     });
4251 #endif
4252     // Create the variant and add it to the output list.
4253     std::vector<TreePatternNodePtr> NewChildren;
4254     for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
4255       NewChildren.push_back(ChildVariants[i][Idxs[i]]);
4256     TreePatternNodePtr R = std::make_shared<TreePatternNode>(
4257         Orig->getOperator(), std::move(NewChildren), Orig->getNumTypes());
4258 
4259     // Copy over properties.
4260     R->setName(Orig->getName());
4261     R->setPredicateFns(Orig->getPredicateFns());
4262     R->setTransformFn(Orig->getTransformFn());
4263     for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
4264       R->setType(i, Orig->getExtType(i));
4265 
4266     // If this pattern cannot match, do not include it as a variant.
4267     std::string ErrString;
4268     // Scan to see if this pattern has already been emitted.  We can get
4269     // duplication due to things like commuting:
4270     //   (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4271     // which are the same pattern.  Ignore the dups.
4272     if (R->canPatternMatch(ErrString, CDP) &&
4273         none_of(OutVariants, [&](TreePatternNodePtr Variant) {
4274           return R->isIsomorphicTo(Variant.get(), DepVars);
4275         }))
4276       OutVariants.push_back(R);
4277 
4278     // Increment indices to the next permutation by incrementing the
4279     // indices from last index backward, e.g., generate the sequence
4280     // [0, 0], [0, 1], [1, 0], [1, 1].
4281     int IdxsIdx;
4282     for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
4283       if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
4284         Idxs[IdxsIdx] = 0;
4285       else
4286         break;
4287     }
4288     NotDone = (IdxsIdx >= 0);
4289   } while (NotDone);
4290 }
4291 
4292 /// CombineChildVariants - A helper function for binary operators.
4293 ///
4294 static void CombineChildVariants(TreePatternNodePtr Orig,
4295                                  const std::vector<TreePatternNodePtr> &LHS,
4296                                  const std::vector<TreePatternNodePtr> &RHS,
4297                                  std::vector<TreePatternNodePtr> &OutVariants,
4298                                  CodeGenDAGPatterns &CDP,
4299                                  const MultipleUseVarSet &DepVars) {
4300   std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
4301   ChildVariants.push_back(LHS);
4302   ChildVariants.push_back(RHS);
4303   CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
4304 }
4305 
4306 static void
4307 GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N,
4308                                   std::vector<TreePatternNodePtr> &Children) {
4309   assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
4310   Record *Operator = N->getOperator();
4311 
4312   // Only permit raw nodes.
4313   if (!N->getName().empty() || !N->getPredicateFns().empty() ||
4314       N->getTransformFn()) {
4315     Children.push_back(N);
4316     return;
4317   }
4318 
4319   if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
4320     Children.push_back(N->getChildShared(0));
4321   else
4322     GatherChildrenOfAssociativeOpcode(N->getChildShared(0), Children);
4323 
4324   if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
4325     Children.push_back(N->getChildShared(1));
4326   else
4327     GatherChildrenOfAssociativeOpcode(N->getChildShared(1), Children);
4328 }
4329 
4330 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4331 /// the (potentially recursive) pattern by using algebraic laws.
4332 ///
4333 static void GenerateVariantsOf(TreePatternNodePtr N,
4334                                std::vector<TreePatternNodePtr> &OutVariants,
4335                                CodeGenDAGPatterns &CDP,
4336                                const MultipleUseVarSet &DepVars) {
4337   // We cannot permute leaves or ComplexPattern uses.
4338   if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
4339     OutVariants.push_back(N);
4340     return;
4341   }
4342 
4343   // Look up interesting info about the node.
4344   const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
4345 
4346   // If this node is associative, re-associate.
4347   if (NodeInfo.hasProperty(SDNPAssociative)) {
4348     // Re-associate by pulling together all of the linked operators
4349     std::vector<TreePatternNodePtr> MaximalChildren;
4350     GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
4351 
4352     // Only handle child sizes of 3.  Otherwise we'll end up trying too many
4353     // permutations.
4354     if (MaximalChildren.size() == 3) {
4355       // Find the variants of all of our maximal children.
4356       std::vector<TreePatternNodePtr> AVariants, BVariants, CVariants;
4357       GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
4358       GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
4359       GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
4360 
4361       // There are only two ways we can permute the tree:
4362       //   (A op B) op C    and    A op (B op C)
4363       // Within these forms, we can also permute A/B/C.
4364 
4365       // Generate legal pair permutations of A/B/C.
4366       std::vector<TreePatternNodePtr> ABVariants;
4367       std::vector<TreePatternNodePtr> BAVariants;
4368       std::vector<TreePatternNodePtr> ACVariants;
4369       std::vector<TreePatternNodePtr> CAVariants;
4370       std::vector<TreePatternNodePtr> BCVariants;
4371       std::vector<TreePatternNodePtr> CBVariants;
4372       CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4373       CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4374       CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4375       CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4376       CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4377       CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
4378 
4379       // Combine those into the result: (x op x) op x
4380       CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4381       CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4382       CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4383       CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4384       CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4385       CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
4386 
4387       // Combine those into the result: x op (x op x)
4388       CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4389       CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4390       CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4391       CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4392       CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4393       CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
4394       return;
4395     }
4396   }
4397 
4398   // Compute permutations of all children.
4399   std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
4400   ChildVariants.resize(N->getNumChildren());
4401   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
4402     GenerateVariantsOf(N->getChildShared(i), ChildVariants[i], CDP, DepVars);
4403 
4404   // Build all permutations based on how the children were formed.
4405   CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
4406 
4407   // If this node is commutative, consider the commuted order.
4408   bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4409   if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
4410     assert((N->getNumChildren()>=2 || isCommIntrinsic) &&
4411            "Commutative but doesn't have 2 children!");
4412     // Don't count children which are actually register references.
4413     unsigned NC = 0;
4414     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4415       TreePatternNode *Child = N->getChild(i);
4416       if (Child->isLeaf())
4417         if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
4418           Record *RR = DI->getDef();
4419           if (RR->isSubClassOf("Register"))
4420             continue;
4421         }
4422       NC++;
4423     }
4424     // Consider the commuted order.
4425     if (isCommIntrinsic) {
4426       // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4427       // operands are the commutative operands, and there might be more operands
4428       // after those.
4429       assert(NC >= 3 &&
4430              "Commutative intrinsic should have at least 3 children!");
4431       std::vector<std::vector<TreePatternNodePtr>> Variants;
4432       Variants.push_back(std::move(ChildVariants[0])); // Intrinsic id.
4433       Variants.push_back(std::move(ChildVariants[2]));
4434       Variants.push_back(std::move(ChildVariants[1]));
4435       for (unsigned i = 3; i != NC; ++i)
4436         Variants.push_back(std::move(ChildVariants[i]));
4437       CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
4438     } else if (NC == N->getNumChildren()) {
4439       std::vector<std::vector<TreePatternNodePtr>> Variants;
4440       Variants.push_back(std::move(ChildVariants[1]));
4441       Variants.push_back(std::move(ChildVariants[0]));
4442       for (unsigned i = 2; i != NC; ++i)
4443         Variants.push_back(std::move(ChildVariants[i]));
4444       CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
4445     }
4446   }
4447 }
4448 
4449 
4450 // GenerateVariants - Generate variants.  For example, commutative patterns can
4451 // match multiple ways.  Add them to PatternsToMatch as well.
4452 void CodeGenDAGPatterns::GenerateVariants() {
4453   LLVM_DEBUG(errs() << "Generating instruction variants.\n");
4454 
4455   // Loop over all of the patterns we've collected, checking to see if we can
4456   // generate variants of the instruction, through the exploitation of
4457   // identities.  This permits the target to provide aggressive matching without
4458   // the .td file having to contain tons of variants of instructions.
4459   //
4460   // Note that this loop adds new patterns to the PatternsToMatch list, but we
4461   // intentionally do not reconsider these.  Any variants of added patterns have
4462   // already been added.
4463   //
4464   const unsigned NumOriginalPatterns = PatternsToMatch.size();
4465   BitVector MatchedPatterns(NumOriginalPatterns);
4466   std::vector<BitVector> MatchedPredicates(NumOriginalPatterns,
4467                                            BitVector(NumOriginalPatterns));
4468 
4469   typedef std::pair<MultipleUseVarSet, std::vector<TreePatternNodePtr>>
4470       DepsAndVariants;
4471   std::map<unsigned, DepsAndVariants> PatternsWithVariants;
4472 
4473   // Collect patterns with more than one variant.
4474   for (unsigned i = 0; i != NumOriginalPatterns; ++i) {
4475     MultipleUseVarSet DepVars;
4476     std::vector<TreePatternNodePtr> Variants;
4477     FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
4478     LLVM_DEBUG(errs() << "Dependent/multiply used variables: ");
4479     LLVM_DEBUG(DumpDepVars(DepVars));
4480     LLVM_DEBUG(errs() << "\n");
4481     GenerateVariantsOf(PatternsToMatch[i].getSrcPatternShared(), Variants,
4482                        *this, DepVars);
4483 
4484     assert(!Variants.empty() && "Must create at least original variant!");
4485     if (Variants.size() == 1) // No additional variants for this pattern.
4486       continue;
4487 
4488     LLVM_DEBUG(errs() << "FOUND VARIANTS OF: ";
4489                PatternsToMatch[i].getSrcPattern()->dump(); errs() << "\n");
4490 
4491     PatternsWithVariants[i] = std::make_pair(DepVars, Variants);
4492 
4493     // Cache matching predicates.
4494     if (MatchedPatterns[i])
4495       continue;
4496 
4497     const std::vector<Predicate> &Predicates =
4498         PatternsToMatch[i].getPredicates();
4499 
4500     BitVector &Matches = MatchedPredicates[i];
4501     MatchedPatterns.set(i);
4502     Matches.set(i);
4503 
4504     // Don't test patterns that have already been cached - it won't match.
4505     for (unsigned p = 0; p != NumOriginalPatterns; ++p)
4506       if (!MatchedPatterns[p])
4507         Matches[p] = (Predicates == PatternsToMatch[p].getPredicates());
4508 
4509     // Copy this to all the matching patterns.
4510     for (int p = Matches.find_first(); p != -1; p = Matches.find_next(p))
4511       if (p != (int)i) {
4512         MatchedPatterns.set(p);
4513         MatchedPredicates[p] = Matches;
4514       }
4515   }
4516 
4517   for (auto it : PatternsWithVariants) {
4518     unsigned i = it.first;
4519     const MultipleUseVarSet &DepVars = it.second.first;
4520     const std::vector<TreePatternNodePtr> &Variants = it.second.second;
4521 
4522     for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
4523       TreePatternNodePtr Variant = Variants[v];
4524       BitVector &Matches = MatchedPredicates[i];
4525 
4526       LLVM_DEBUG(errs() << "  VAR#" << v << ": "; Variant->dump();
4527                  errs() << "\n");
4528 
4529       // Scan to see if an instruction or explicit pattern already matches this.
4530       bool AlreadyExists = false;
4531       for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
4532         // Skip if the top level predicates do not match.
4533         if (!Matches[p])
4534           continue;
4535         // Check to see if this variant already exists.
4536         if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
4537                                     DepVars)) {
4538           LLVM_DEBUG(errs() << "  *** ALREADY EXISTS, ignoring variant.\n");
4539           AlreadyExists = true;
4540           break;
4541         }
4542       }
4543       // If we already have it, ignore the variant.
4544       if (AlreadyExists) continue;
4545 
4546       // Otherwise, add it to the list of patterns we have.
4547       PatternsToMatch.push_back(PatternToMatch(
4548           PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
4549           Variant, PatternsToMatch[i].getDstPatternShared(),
4550           PatternsToMatch[i].getDstRegs(),
4551           PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
4552       MatchedPredicates.push_back(Matches);
4553 
4554       // Add a new match the same as this pattern.
4555       for (auto &P : MatchedPredicates)
4556         P.push_back(P[i]);
4557     }
4558 
4559     LLVM_DEBUG(errs() << "\n");
4560   }
4561 }
4562