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, 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 node transformation corresponding to this, keep track of
3041     // it.
3042     Record *Transform = Frag->getValueAsDef("OperandTransform");
3043     if (!getSDNodeTransform(Transform).second.empty())    // not noop xform?
3044       for (auto T : P->getTrees())
3045         T->setTransformFn(Transform);
3046   }
3047 
3048   // Now that we've parsed all of the tree fragments, do a closure on them so
3049   // that there are not references to PatFrags left inside of them.
3050   for (Record *Frag : Fragments) {
3051     if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
3052       continue;
3053 
3054     TreePattern &ThePat = *PatternFragments[Frag];
3055     ThePat.InlinePatternFragments();
3056 
3057     // Infer as many types as possible.  Don't worry about it if we don't infer
3058     // all of them, some may depend on the inputs of the pattern.  Also, don't
3059     // validate type sets; validation may cause spurious failures e.g. if a
3060     // fragment needs floating-point types but the current target does not have
3061     // any (this is only an error if that fragment is ever used!).
3062     {
3063       TypeInfer::SuppressValidation SV(ThePat.getInfer());
3064       ThePat.InferAllTypes();
3065       ThePat.resetError();
3066     }
3067 
3068     // If debugging, print out the pattern fragment result.
3069     LLVM_DEBUG(ThePat.dump());
3070   }
3071 }
3072 
3073 void CodeGenDAGPatterns::ParseDefaultOperands() {
3074   std::vector<Record*> DefaultOps;
3075   DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
3076 
3077   // Find some SDNode.
3078   assert(!SDNodes.empty() && "No SDNodes parsed?");
3079   Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
3080 
3081   for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
3082     DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
3083 
3084     // Clone the DefaultInfo dag node, changing the operator from 'ops' to
3085     // SomeSDnode so that we can parse this.
3086     std::vector<std::pair<Init*, StringInit*> > Ops;
3087     for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
3088       Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
3089                                    DefaultInfo->getArgName(op)));
3090     DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
3091 
3092     // Create a TreePattern to parse this.
3093     TreePattern P(DefaultOps[i], DI, false, *this);
3094     assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
3095 
3096     // Copy the operands over into a DAGDefaultOperand.
3097     DAGDefaultOperand DefaultOpInfo;
3098 
3099     const TreePatternNodePtr &T = P.getTree(0);
3100     for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
3101       TreePatternNodePtr TPN = T->getChildShared(op);
3102       while (TPN->ApplyTypeConstraints(P, false))
3103         /* Resolve all types */;
3104 
3105       if (TPN->ContainsUnresolvedType(P)) {
3106         PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
3107                         DefaultOps[i]->getName() +
3108                         "' doesn't have a concrete type!");
3109       }
3110       DefaultOpInfo.DefaultOps.push_back(std::move(TPN));
3111     }
3112 
3113     // Insert it into the DefaultOperands map so we can find it later.
3114     DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
3115   }
3116 }
3117 
3118 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3119 /// instruction input.  Return true if this is a real use.
3120 static bool HandleUse(TreePattern &I, TreePatternNodePtr Pat,
3121                       std::map<std::string, TreePatternNodePtr> &InstInputs) {
3122   // No name -> not interesting.
3123   if (Pat->getName().empty()) {
3124     if (Pat->isLeaf()) {
3125       DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
3126       if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
3127                  DI->getDef()->isSubClassOf("RegisterOperand")))
3128         I.error("Input " + DI->getDef()->getName() + " must be named!");
3129     }
3130     return false;
3131   }
3132 
3133   Record *Rec;
3134   if (Pat->isLeaf()) {
3135     DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
3136     if (!DI)
3137       I.error("Input $" + Pat->getName() + " must be an identifier!");
3138     Rec = DI->getDef();
3139   } else {
3140     Rec = Pat->getOperator();
3141   }
3142 
3143   // SRCVALUE nodes are ignored.
3144   if (Rec->getName() == "srcvalue")
3145     return false;
3146 
3147   TreePatternNodePtr &Slot = InstInputs[Pat->getName()];
3148   if (!Slot) {
3149     Slot = Pat;
3150     return true;
3151   }
3152   Record *SlotRec;
3153   if (Slot->isLeaf()) {
3154     SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
3155   } else {
3156     assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
3157     SlotRec = Slot->getOperator();
3158   }
3159 
3160   // Ensure that the inputs agree if we've already seen this input.
3161   if (Rec != SlotRec)
3162     I.error("All $" + Pat->getName() + " inputs must agree with each other");
3163   // Ensure that the types can agree as well.
3164   Slot->UpdateNodeType(0, Pat->getExtType(0), I);
3165   Pat->UpdateNodeType(0, Slot->getExtType(0), I);
3166   if (Slot->getExtTypes() != Pat->getExtTypes())
3167     I.error("All $" + Pat->getName() + " inputs must agree with each other");
3168   return true;
3169 }
3170 
3171 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3172 /// part of "I", the instruction), computing the set of inputs and outputs of
3173 /// the pattern.  Report errors if we see anything naughty.
3174 void CodeGenDAGPatterns::FindPatternInputsAndOutputs(
3175     TreePattern &I, TreePatternNodePtr Pat,
3176     std::map<std::string, TreePatternNodePtr> &InstInputs,
3177     std::map<std::string, TreePatternNodePtr> &InstResults,
3178     std::vector<Record *> &InstImpResults) {
3179 
3180   // The instruction pattern still has unresolved fragments.  For *named*
3181   // nodes we must resolve those here.  This may not result in multiple
3182   // alternatives.
3183   if (!Pat->getName().empty()) {
3184     TreePattern SrcPattern(I.getRecord(), Pat, true, *this);
3185     SrcPattern.InlinePatternFragments();
3186     SrcPattern.InferAllTypes();
3187     Pat = SrcPattern.getOnlyTree();
3188   }
3189 
3190   if (Pat->isLeaf()) {
3191     bool isUse = HandleUse(I, Pat, InstInputs);
3192     if (!isUse && Pat->getTransformFn())
3193       I.error("Cannot specify a transform function for a non-input value!");
3194     return;
3195   }
3196 
3197   if (Pat->getOperator()->getName() == "implicit") {
3198     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
3199       TreePatternNode *Dest = Pat->getChild(i);
3200       if (!Dest->isLeaf())
3201         I.error("implicitly defined value should be a register!");
3202 
3203       DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
3204       if (!Val || !Val->getDef()->isSubClassOf("Register"))
3205         I.error("implicitly defined value should be a register!");
3206       InstImpResults.push_back(Val->getDef());
3207     }
3208     return;
3209   }
3210 
3211   if (Pat->getOperator()->getName() != "set") {
3212     // If this is not a set, verify that the children nodes are not void typed,
3213     // and recurse.
3214     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
3215       if (Pat->getChild(i)->getNumTypes() == 0)
3216         I.error("Cannot have void nodes inside of patterns!");
3217       FindPatternInputsAndOutputs(I, Pat->getChildShared(i), InstInputs,
3218                                   InstResults, InstImpResults);
3219     }
3220 
3221     // If this is a non-leaf node with no children, treat it basically as if
3222     // it were a leaf.  This handles nodes like (imm).
3223     bool isUse = HandleUse(I, Pat, InstInputs);
3224 
3225     if (!isUse && Pat->getTransformFn())
3226       I.error("Cannot specify a transform function for a non-input value!");
3227     return;
3228   }
3229 
3230   // Otherwise, this is a set, validate and collect instruction results.
3231   if (Pat->getNumChildren() == 0)
3232     I.error("set requires operands!");
3233 
3234   if (Pat->getTransformFn())
3235     I.error("Cannot specify a transform function on a set node!");
3236 
3237   // Check the set destinations.
3238   unsigned NumDests = Pat->getNumChildren()-1;
3239   for (unsigned i = 0; i != NumDests; ++i) {
3240     TreePatternNodePtr Dest = Pat->getChildShared(i);
3241     // For set destinations we also must resolve fragments here.
3242     TreePattern DestPattern(I.getRecord(), Dest, false, *this);
3243     DestPattern.InlinePatternFragments();
3244     DestPattern.InferAllTypes();
3245     Dest = DestPattern.getOnlyTree();
3246 
3247     if (!Dest->isLeaf())
3248       I.error("set destination should be a register!");
3249 
3250     DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
3251     if (!Val) {
3252       I.error("set destination should be a register!");
3253       continue;
3254     }
3255 
3256     if (Val->getDef()->isSubClassOf("RegisterClass") ||
3257         Val->getDef()->isSubClassOf("ValueType") ||
3258         Val->getDef()->isSubClassOf("RegisterOperand") ||
3259         Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
3260       if (Dest->getName().empty())
3261         I.error("set destination must have a name!");
3262       if (InstResults.count(Dest->getName()))
3263         I.error("cannot set '" + Dest->getName() + "' multiple times");
3264       InstResults[Dest->getName()] = Dest;
3265     } else if (Val->getDef()->isSubClassOf("Register")) {
3266       InstImpResults.push_back(Val->getDef());
3267     } else {
3268       I.error("set destination should be a register!");
3269     }
3270   }
3271 
3272   // Verify and collect info from the computation.
3273   FindPatternInputsAndOutputs(I, Pat->getChildShared(NumDests), InstInputs,
3274                               InstResults, InstImpResults);
3275 }
3276 
3277 //===----------------------------------------------------------------------===//
3278 // Instruction Analysis
3279 //===----------------------------------------------------------------------===//
3280 
3281 class InstAnalyzer {
3282   const CodeGenDAGPatterns &CDP;
3283 public:
3284   bool hasSideEffects;
3285   bool mayStore;
3286   bool mayLoad;
3287   bool isBitcast;
3288   bool isVariadic;
3289   bool hasChain;
3290 
3291   InstAnalyzer(const CodeGenDAGPatterns &cdp)
3292     : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
3293       isBitcast(false), isVariadic(false), hasChain(false) {}
3294 
3295   void Analyze(const PatternToMatch &Pat) {
3296     const TreePatternNode *N = Pat.getSrcPattern();
3297     AnalyzeNode(N);
3298     // These properties are detected only on the root node.
3299     isBitcast = IsNodeBitcast(N);
3300   }
3301 
3302 private:
3303   bool IsNodeBitcast(const TreePatternNode *N) const {
3304     if (hasSideEffects || mayLoad || mayStore || isVariadic)
3305       return false;
3306 
3307     if (N->isLeaf())
3308       return false;
3309     if (N->getNumChildren() != 1 || !N->getChild(0)->isLeaf())
3310       return false;
3311 
3312     const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
3313     if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
3314       return false;
3315     return OpInfo.getEnumName() == "ISD::BITCAST";
3316   }
3317 
3318 public:
3319   void AnalyzeNode(const TreePatternNode *N) {
3320     if (N->isLeaf()) {
3321       if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
3322         Record *LeafRec = DI->getDef();
3323         // Handle ComplexPattern leaves.
3324         if (LeafRec->isSubClassOf("ComplexPattern")) {
3325           const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
3326           if (CP.hasProperty(SDNPMayStore)) mayStore = true;
3327           if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
3328           if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
3329         }
3330       }
3331       return;
3332     }
3333 
3334     // Analyze children.
3335     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3336       AnalyzeNode(N->getChild(i));
3337 
3338     // Notice properties of the node.
3339     if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
3340     if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
3341     if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
3342     if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
3343     if (N->NodeHasProperty(SDNPHasChain, CDP)) hasChain = true;
3344 
3345     if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
3346       // If this is an intrinsic, analyze it.
3347       if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
3348         mayLoad = true;// These may load memory.
3349 
3350       if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
3351         mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
3352 
3353       if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
3354           IntInfo->hasSideEffects)
3355         // ReadWriteMem intrinsics can have other strange effects.
3356         hasSideEffects = true;
3357     }
3358   }
3359 
3360 };
3361 
3362 static bool InferFromPattern(CodeGenInstruction &InstInfo,
3363                              const InstAnalyzer &PatInfo,
3364                              Record *PatDef) {
3365   bool Error = false;
3366 
3367   // Remember where InstInfo got its flags.
3368   if (InstInfo.hasUndefFlags())
3369       InstInfo.InferredFrom = PatDef;
3370 
3371   // Check explicitly set flags for consistency.
3372   if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3373       !InstInfo.hasSideEffects_Unset) {
3374     // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3375     // the pattern has no side effects. That could be useful for div/rem
3376     // instructions that may trap.
3377     if (!InstInfo.hasSideEffects) {
3378       Error = true;
3379       PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
3380                  Twine(InstInfo.hasSideEffects));
3381     }
3382   }
3383 
3384   if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3385     Error = true;
3386     PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
3387                Twine(InstInfo.mayStore));
3388   }
3389 
3390   if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3391     // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
3392     // Some targets translate immediates to loads.
3393     if (!InstInfo.mayLoad) {
3394       Error = true;
3395       PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
3396                  Twine(InstInfo.mayLoad));
3397     }
3398   }
3399 
3400   // Transfer inferred flags.
3401   InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3402   InstInfo.mayStore |= PatInfo.mayStore;
3403   InstInfo.mayLoad |= PatInfo.mayLoad;
3404 
3405   // These flags are silently added without any verification.
3406   // FIXME: To match historical behavior of TableGen, for now add those flags
3407   // only when we're inferring from the primary instruction pattern.
3408   if (PatDef->isSubClassOf("Instruction")) {
3409     InstInfo.isBitcast |= PatInfo.isBitcast;
3410     InstInfo.hasChain |= PatInfo.hasChain;
3411     InstInfo.hasChain_Inferred = true;
3412   }
3413 
3414   // Don't infer isVariadic. This flag means something different on SDNodes and
3415   // instructions. For example, a CALL SDNode is variadic because it has the
3416   // call arguments as operands, but a CALL instruction is not variadic - it
3417   // has argument registers as implicit, not explicit uses.
3418 
3419   return Error;
3420 }
3421 
3422 /// hasNullFragReference - Return true if the DAG has any reference to the
3423 /// null_frag operator.
3424 static bool hasNullFragReference(DagInit *DI) {
3425   DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
3426   if (!OpDef) return false;
3427   Record *Operator = OpDef->getDef();
3428 
3429   // If this is the null fragment, return true.
3430   if (Operator->getName() == "null_frag") return true;
3431   // If any of the arguments reference the null fragment, return true.
3432   for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
3433     DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
3434     if (Arg && hasNullFragReference(Arg))
3435       return true;
3436   }
3437 
3438   return false;
3439 }
3440 
3441 /// hasNullFragReference - Return true if any DAG in the list references
3442 /// the null_frag operator.
3443 static bool hasNullFragReference(ListInit *LI) {
3444   for (Init *I : LI->getValues()) {
3445     DagInit *DI = dyn_cast<DagInit>(I);
3446     assert(DI && "non-dag in an instruction Pattern list?!");
3447     if (hasNullFragReference(DI))
3448       return true;
3449   }
3450   return false;
3451 }
3452 
3453 /// Get all the instructions in a tree.
3454 static void
3455 getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
3456   if (Tree->isLeaf())
3457     return;
3458   if (Tree->getOperator()->isSubClassOf("Instruction"))
3459     Instrs.push_back(Tree->getOperator());
3460   for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
3461     getInstructionsInTree(Tree->getChild(i), Instrs);
3462 }
3463 
3464 /// Check the class of a pattern leaf node against the instruction operand it
3465 /// represents.
3466 static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
3467                               Record *Leaf) {
3468   if (OI.Rec == Leaf)
3469     return true;
3470 
3471   // Allow direct value types to be used in instruction set patterns.
3472   // The type will be checked later.
3473   if (Leaf->isSubClassOf("ValueType"))
3474     return true;
3475 
3476   // Patterns can also be ComplexPattern instances.
3477   if (Leaf->isSubClassOf("ComplexPattern"))
3478     return true;
3479 
3480   return false;
3481 }
3482 
3483 void CodeGenDAGPatterns::parseInstructionPattern(
3484     CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
3485 
3486   assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
3487 
3488   // Parse the instruction.
3489   TreePattern I(CGI.TheDef, Pat, true, *this);
3490 
3491   // InstInputs - Keep track of all of the inputs of the instruction, along
3492   // with the record they are declared as.
3493   std::map<std::string, TreePatternNodePtr> InstInputs;
3494 
3495   // InstResults - Keep track of all the virtual registers that are 'set'
3496   // in the instruction, including what reg class they are.
3497   std::map<std::string, TreePatternNodePtr> InstResults;
3498 
3499   std::vector<Record*> InstImpResults;
3500 
3501   // Verify that the top-level forms in the instruction are of void type, and
3502   // fill in the InstResults map.
3503   SmallString<32> TypesString;
3504   for (unsigned j = 0, e = I.getNumTrees(); j != e; ++j) {
3505     TypesString.clear();
3506     TreePatternNodePtr Pat = I.getTree(j);
3507     if (Pat->getNumTypes() != 0) {
3508       raw_svector_ostream OS(TypesString);
3509       for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3510         if (k > 0)
3511           OS << ", ";
3512         Pat->getExtType(k).writeToStream(OS);
3513       }
3514       I.error("Top-level forms in instruction pattern should have"
3515                " void types, has types " +
3516                OS.str());
3517     }
3518 
3519     // Find inputs and outputs, and verify the structure of the uses/defs.
3520     FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
3521                                 InstImpResults);
3522   }
3523 
3524   // Now that we have inputs and outputs of the pattern, inspect the operands
3525   // list for the instruction.  This determines the order that operands are
3526   // added to the machine instruction the node corresponds to.
3527   unsigned NumResults = InstResults.size();
3528 
3529   // Parse the operands list from the (ops) list, validating it.
3530   assert(I.getArgList().empty() && "Args list should still be empty here!");
3531 
3532   // Check that all of the results occur first in the list.
3533   std::vector<Record*> Results;
3534   SmallVector<TreePatternNodePtr, 2> ResNodes;
3535   for (unsigned i = 0; i != NumResults; ++i) {
3536     if (i == CGI.Operands.size())
3537       I.error("'" + InstResults.begin()->first +
3538                "' set but does not appear in operand list!");
3539     const std::string &OpName = CGI.Operands[i].Name;
3540 
3541     // Check that it exists in InstResults.
3542     TreePatternNodePtr RNode = InstResults[OpName];
3543     if (!RNode)
3544       I.error("Operand $" + OpName + " does not exist in operand list!");
3545 
3546 
3547     Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
3548     ResNodes.push_back(std::move(RNode));
3549     if (!R)
3550       I.error("Operand $" + OpName + " should be a set destination: all "
3551                "outputs must occur before inputs in operand list!");
3552 
3553     if (!checkOperandClass(CGI.Operands[i], R))
3554       I.error("Operand $" + OpName + " class mismatch!");
3555 
3556     // Remember the return type.
3557     Results.push_back(CGI.Operands[i].Rec);
3558 
3559     // Okay, this one checks out.
3560     InstResults.erase(OpName);
3561   }
3562 
3563   // Loop over the inputs next.
3564   std::vector<TreePatternNodePtr> ResultNodeOperands;
3565   std::vector<Record*> Operands;
3566   for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3567     CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3568     const std::string &OpName = Op.Name;
3569     if (OpName.empty())
3570       I.error("Operand #" + Twine(i) + " in operands list has no name!");
3571 
3572     if (!InstInputs.count(OpName)) {
3573       // If this is an operand with a DefaultOps set filled in, we can ignore
3574       // this.  When we codegen it, we will do so as always executed.
3575       if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3576         // Does it have a non-empty DefaultOps field?  If so, ignore this
3577         // operand.
3578         if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3579           continue;
3580       }
3581       I.error("Operand $" + OpName +
3582                " does not appear in the instruction pattern");
3583     }
3584     TreePatternNodePtr InVal = InstInputs[OpName];
3585     InstInputs.erase(OpName);   // It occurred, remove from map.
3586 
3587     if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3588       Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3589       if (!checkOperandClass(Op, InRec))
3590         I.error("Operand $" + OpName + "'s register class disagrees"
3591                  " between the operand and pattern");
3592     }
3593     Operands.push_back(Op.Rec);
3594 
3595     // Construct the result for the dest-pattern operand list.
3596     TreePatternNodePtr OpNode = InVal->clone();
3597 
3598     // No predicate is useful on the result.
3599     OpNode->clearPredicateFns();
3600 
3601     // Promote the xform function to be an explicit node if set.
3602     if (Record *Xform = OpNode->getTransformFn()) {
3603       OpNode->setTransformFn(nullptr);
3604       std::vector<TreePatternNodePtr> Children;
3605       Children.push_back(OpNode);
3606       OpNode = std::make_shared<TreePatternNode>(Xform, std::move(Children),
3607                                                  OpNode->getNumTypes());
3608     }
3609 
3610     ResultNodeOperands.push_back(std::move(OpNode));
3611   }
3612 
3613   if (!InstInputs.empty())
3614     I.error("Input operand $" + InstInputs.begin()->first +
3615             " occurs in pattern but not in operands list!");
3616 
3617   TreePatternNodePtr ResultPattern = std::make_shared<TreePatternNode>(
3618       I.getRecord(), std::move(ResultNodeOperands),
3619       GetNumNodeResults(I.getRecord(), *this));
3620   // Copy fully inferred output node types to instruction result pattern.
3621   for (unsigned i = 0; i != NumResults; ++i) {
3622     assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3623     ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3624   }
3625 
3626   // FIXME: Assume only the first tree is the pattern. The others are clobber
3627   // nodes.
3628   TreePatternNodePtr Pattern = I.getTree(0);
3629   TreePatternNodePtr SrcPattern;
3630   if (Pattern->getOperator()->getName() == "set") {
3631     SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3632   } else{
3633     // Not a set (store or something?)
3634     SrcPattern = Pattern;
3635   }
3636 
3637   // Create and insert the instruction.
3638   // FIXME: InstImpResults should not be part of DAGInstruction.
3639   Record *R = I.getRecord();
3640   DAGInsts.emplace(std::piecewise_construct, std::forward_as_tuple(R),
3641                    std::forward_as_tuple(Results, Operands, InstImpResults,
3642                                          SrcPattern, ResultPattern));
3643 
3644   LLVM_DEBUG(I.dump());
3645 }
3646 
3647 /// ParseInstructions - Parse all of the instructions, inlining and resolving
3648 /// any fragments involved.  This populates the Instructions list with fully
3649 /// resolved instructions.
3650 void CodeGenDAGPatterns::ParseInstructions() {
3651   std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3652 
3653   for (Record *Instr : Instrs) {
3654     ListInit *LI = nullptr;
3655 
3656     if (isa<ListInit>(Instr->getValueInit("Pattern")))
3657       LI = Instr->getValueAsListInit("Pattern");
3658 
3659     // If there is no pattern, only collect minimal information about the
3660     // instruction for its operand list.  We have to assume that there is one
3661     // result, as we have no detailed info. A pattern which references the
3662     // null_frag operator is as-if no pattern were specified. Normally this
3663     // is from a multiclass expansion w/ a SDPatternOperator passed in as
3664     // null_frag.
3665     if (!LI || LI->empty() || hasNullFragReference(LI)) {
3666       std::vector<Record*> Results;
3667       std::vector<Record*> Operands;
3668 
3669       CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3670 
3671       if (InstInfo.Operands.size() != 0) {
3672         for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3673           Results.push_back(InstInfo.Operands[j].Rec);
3674 
3675         // The rest are inputs.
3676         for (unsigned j = InstInfo.Operands.NumDefs,
3677                e = InstInfo.Operands.size(); j < e; ++j)
3678           Operands.push_back(InstInfo.Operands[j].Rec);
3679       }
3680 
3681       // Create and insert the instruction.
3682       std::vector<Record*> ImpResults;
3683       Instructions.insert(std::make_pair(Instr,
3684                             DAGInstruction(Results, Operands, ImpResults)));
3685       continue;  // no pattern.
3686     }
3687 
3688     CodeGenInstruction &CGI = Target.getInstruction(Instr);
3689     parseInstructionPattern(CGI, LI, Instructions);
3690   }
3691 
3692   // If we can, convert the instructions to be patterns that are matched!
3693   for (auto &Entry : Instructions) {
3694     Record *Instr = Entry.first;
3695     DAGInstruction &TheInst = Entry.second;
3696     TreePatternNodePtr SrcPattern = TheInst.getSrcPattern();
3697     TreePatternNodePtr ResultPattern = TheInst.getResultPattern();
3698 
3699     if (SrcPattern && ResultPattern) {
3700       TreePattern Pattern(Instr, SrcPattern, true, *this);
3701       TreePattern Result(Instr, ResultPattern, false, *this);
3702       ParseOnePattern(Instr, Pattern, Result, TheInst.getImpResults());
3703     }
3704   }
3705 }
3706 
3707 typedef std::pair<TreePatternNode *, unsigned> NameRecord;
3708 
3709 static void FindNames(TreePatternNode *P,
3710                       std::map<std::string, NameRecord> &Names,
3711                       TreePattern *PatternTop) {
3712   if (!P->getName().empty()) {
3713     NameRecord &Rec = Names[P->getName()];
3714     // If this is the first instance of the name, remember the node.
3715     if (Rec.second++ == 0)
3716       Rec.first = P;
3717     else if (Rec.first->getExtTypes() != P->getExtTypes())
3718       PatternTop->error("repetition of value: $" + P->getName() +
3719                         " where different uses have different types!");
3720   }
3721 
3722   if (!P->isLeaf()) {
3723     for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3724       FindNames(P->getChild(i), Names, PatternTop);
3725   }
3726 }
3727 
3728 std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) {
3729   std::vector<Predicate> Preds;
3730   for (Init *I : L->getValues()) {
3731     if (DefInit *Pred = dyn_cast<DefInit>(I))
3732       Preds.push_back(Pred->getDef());
3733     else
3734       llvm_unreachable("Non-def on the list");
3735   }
3736 
3737   // Sort so that different orders get canonicalized to the same string.
3738   llvm::sort(Preds);
3739   return Preds;
3740 }
3741 
3742 void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
3743                                            PatternToMatch &&PTM) {
3744   // Do some sanity checking on the pattern we're about to match.
3745   std::string Reason;
3746   if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3747     PrintWarning(Pattern->getRecord()->getLoc(),
3748       Twine("Pattern can never match: ") + Reason);
3749     return;
3750   }
3751 
3752   // If the source pattern's root is a complex pattern, that complex pattern
3753   // must specify the nodes it can potentially match.
3754   if (const ComplexPattern *CP =
3755         PTM.getSrcPattern()->getComplexPatternInfo(*this))
3756     if (CP->getRootNodes().empty())
3757       Pattern->error("ComplexPattern at root must specify list of opcodes it"
3758                      " could match");
3759 
3760 
3761   // Find all of the named values in the input and output, ensure they have the
3762   // same type.
3763   std::map<std::string, NameRecord> SrcNames, DstNames;
3764   FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3765   FindNames(PTM.getDstPattern(), DstNames, Pattern);
3766 
3767   // Scan all of the named values in the destination pattern, rejecting them if
3768   // they don't exist in the input pattern.
3769   for (const auto &Entry : DstNames) {
3770     if (SrcNames[Entry.first].first == nullptr)
3771       Pattern->error("Pattern has input without matching name in output: $" +
3772                      Entry.first);
3773   }
3774 
3775   // Scan all of the named values in the source pattern, rejecting them if the
3776   // name isn't used in the dest, and isn't used to tie two values together.
3777   for (const auto &Entry : SrcNames)
3778     if (DstNames[Entry.first].first == nullptr &&
3779         SrcNames[Entry.first].second == 1)
3780       Pattern->error("Pattern has dead named input: $" + Entry.first);
3781 
3782   PatternsToMatch.push_back(PTM);
3783 }
3784 
3785 void CodeGenDAGPatterns::InferInstructionFlags() {
3786   ArrayRef<const CodeGenInstruction*> Instructions =
3787     Target.getInstructionsByEnumValue();
3788 
3789   unsigned Errors = 0;
3790 
3791   // Try to infer flags from all patterns in PatternToMatch.  These include
3792   // both the primary instruction patterns (which always come first) and
3793   // patterns defined outside the instruction.
3794   for (const PatternToMatch &PTM : ptms()) {
3795     // We can only infer from single-instruction patterns, otherwise we won't
3796     // know which instruction should get the flags.
3797     SmallVector<Record*, 8> PatInstrs;
3798     getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3799     if (PatInstrs.size() != 1)
3800       continue;
3801 
3802     // Get the single instruction.
3803     CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3804 
3805     // Only infer properties from the first pattern. We'll verify the others.
3806     if (InstInfo.InferredFrom)
3807       continue;
3808 
3809     InstAnalyzer PatInfo(*this);
3810     PatInfo.Analyze(PTM);
3811     Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3812   }
3813 
3814   if (Errors)
3815     PrintFatalError("pattern conflicts");
3816 
3817   // If requested by the target, guess any undefined properties.
3818   if (Target.guessInstructionProperties()) {
3819     for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3820       CodeGenInstruction *InstInfo =
3821         const_cast<CodeGenInstruction *>(Instructions[i]);
3822       if (InstInfo->InferredFrom)
3823         continue;
3824       // The mayLoad and mayStore flags default to false.
3825       // Conservatively assume hasSideEffects if it wasn't explicit.
3826       if (InstInfo->hasSideEffects_Unset)
3827         InstInfo->hasSideEffects = true;
3828     }
3829     return;
3830   }
3831 
3832   // Complain about any flags that are still undefined.
3833   for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3834     CodeGenInstruction *InstInfo =
3835       const_cast<CodeGenInstruction *>(Instructions[i]);
3836     if (InstInfo->InferredFrom)
3837       continue;
3838     if (InstInfo->hasSideEffects_Unset)
3839       PrintError(InstInfo->TheDef->getLoc(),
3840                  "Can't infer hasSideEffects from patterns");
3841     if (InstInfo->mayStore_Unset)
3842       PrintError(InstInfo->TheDef->getLoc(),
3843                  "Can't infer mayStore from patterns");
3844     if (InstInfo->mayLoad_Unset)
3845       PrintError(InstInfo->TheDef->getLoc(),
3846                  "Can't infer mayLoad from patterns");
3847   }
3848 }
3849 
3850 
3851 /// Verify instruction flags against pattern node properties.
3852 void CodeGenDAGPatterns::VerifyInstructionFlags() {
3853   unsigned Errors = 0;
3854   for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3855     const PatternToMatch &PTM = *I;
3856     SmallVector<Record*, 8> Instrs;
3857     getInstructionsInTree(PTM.getDstPattern(), Instrs);
3858     if (Instrs.empty())
3859       continue;
3860 
3861     // Count the number of instructions with each flag set.
3862     unsigned NumSideEffects = 0;
3863     unsigned NumStores = 0;
3864     unsigned NumLoads = 0;
3865     for (const Record *Instr : Instrs) {
3866       const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3867       NumSideEffects += InstInfo.hasSideEffects;
3868       NumStores += InstInfo.mayStore;
3869       NumLoads += InstInfo.mayLoad;
3870     }
3871 
3872     // Analyze the source pattern.
3873     InstAnalyzer PatInfo(*this);
3874     PatInfo.Analyze(PTM);
3875 
3876     // Collect error messages.
3877     SmallVector<std::string, 4> Msgs;
3878 
3879     // Check for missing flags in the output.
3880     // Permit extra flags for now at least.
3881     if (PatInfo.hasSideEffects && !NumSideEffects)
3882       Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3883 
3884     // Don't verify store flags on instructions with side effects. At least for
3885     // intrinsics, side effects implies mayStore.
3886     if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3887       Msgs.push_back("pattern may store, but mayStore isn't set");
3888 
3889     // Similarly, mayStore implies mayLoad on intrinsics.
3890     if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3891       Msgs.push_back("pattern may load, but mayLoad isn't set");
3892 
3893     // Print error messages.
3894     if (Msgs.empty())
3895       continue;
3896     ++Errors;
3897 
3898     for (const std::string &Msg : Msgs)
3899       PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
3900                  (Instrs.size() == 1 ?
3901                   "instruction" : "output instructions"));
3902     // Provide the location of the relevant instruction definitions.
3903     for (const Record *Instr : Instrs) {
3904       if (Instr != PTM.getSrcRecord())
3905         PrintError(Instr->getLoc(), "defined here");
3906       const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3907       if (InstInfo.InferredFrom &&
3908           InstInfo.InferredFrom != InstInfo.TheDef &&
3909           InstInfo.InferredFrom != PTM.getSrcRecord())
3910         PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
3911     }
3912   }
3913   if (Errors)
3914     PrintFatalError("Errors in DAG patterns");
3915 }
3916 
3917 /// Given a pattern result with an unresolved type, see if we can find one
3918 /// instruction with an unresolved result type.  Force this result type to an
3919 /// arbitrary element if it's possible types to converge results.
3920 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3921   if (N->isLeaf())
3922     return false;
3923 
3924   // Analyze children.
3925   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3926     if (ForceArbitraryInstResultType(N->getChild(i), TP))
3927       return true;
3928 
3929   if (!N->getOperator()->isSubClassOf("Instruction"))
3930     return false;
3931 
3932   // If this type is already concrete or completely unknown we can't do
3933   // anything.
3934   TypeInfer &TI = TP.getInfer();
3935   for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3936     if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
3937       continue;
3938 
3939     // Otherwise, force its type to an arbitrary choice.
3940     if (TI.forceArbitrary(N->getExtType(i)))
3941       return true;
3942   }
3943 
3944   return false;
3945 }
3946 
3947 // Promote xform function to be an explicit node wherever set.
3948 static TreePatternNodePtr PromoteXForms(TreePatternNodePtr N) {
3949   if (Record *Xform = N->getTransformFn()) {
3950       N->setTransformFn(nullptr);
3951       std::vector<TreePatternNodePtr> Children;
3952       Children.push_back(PromoteXForms(N));
3953       return std::make_shared<TreePatternNode>(Xform, std::move(Children),
3954                                                N->getNumTypes());
3955   }
3956 
3957   if (!N->isLeaf())
3958     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3959       TreePatternNodePtr Child = N->getChildShared(i);
3960       N->setChild(i, PromoteXForms(Child));
3961     }
3962   return N;
3963 }
3964 
3965 void CodeGenDAGPatterns::ParseOnePattern(Record *TheDef,
3966        TreePattern &Pattern, TreePattern &Result,
3967        const std::vector<Record *> &InstImpResults) {
3968 
3969   // Inline pattern fragments and expand multiple alternatives.
3970   Pattern.InlinePatternFragments();
3971   Result.InlinePatternFragments();
3972 
3973   if (Result.getNumTrees() != 1)
3974     Result.error("Cannot use multi-alternative fragments in result pattern!");
3975 
3976   // Infer types.
3977   bool IterateInference;
3978   bool InferredAllPatternTypes, InferredAllResultTypes;
3979   do {
3980     // Infer as many types as possible.  If we cannot infer all of them, we
3981     // can never do anything with this pattern: report it to the user.
3982     InferredAllPatternTypes =
3983         Pattern.InferAllTypes(&Pattern.getNamedNodesMap());
3984 
3985     // Infer as many types as possible.  If we cannot infer all of them, we
3986     // can never do anything with this pattern: report it to the user.
3987     InferredAllResultTypes =
3988         Result.InferAllTypes(&Pattern.getNamedNodesMap());
3989 
3990     IterateInference = false;
3991 
3992     // Apply the type of the result to the source pattern.  This helps us
3993     // resolve cases where the input type is known to be a pointer type (which
3994     // is considered resolved), but the result knows it needs to be 32- or
3995     // 64-bits.  Infer the other way for good measure.
3996     for (auto T : Pattern.getTrees())
3997       for (unsigned i = 0, e = std::min(Result.getOnlyTree()->getNumTypes(),
3998                                         T->getNumTypes());
3999          i != e; ++i) {
4000         IterateInference |= T->UpdateNodeType(
4001             i, Result.getOnlyTree()->getExtType(i), Result);
4002         IterateInference |= Result.getOnlyTree()->UpdateNodeType(
4003             i, T->getExtType(i), Result);
4004       }
4005 
4006     // If our iteration has converged and the input pattern's types are fully
4007     // resolved but the result pattern is not fully resolved, we may have a
4008     // situation where we have two instructions in the result pattern and
4009     // the instructions require a common register class, but don't care about
4010     // what actual MVT is used.  This is actually a bug in our modelling:
4011     // output patterns should have register classes, not MVTs.
4012     //
4013     // In any case, to handle this, we just go through and disambiguate some
4014     // arbitrary types to the result pattern's nodes.
4015     if (!IterateInference && InferredAllPatternTypes &&
4016         !InferredAllResultTypes)
4017       IterateInference =
4018           ForceArbitraryInstResultType(Result.getTree(0).get(), Result);
4019   } while (IterateInference);
4020 
4021   // Verify that we inferred enough types that we can do something with the
4022   // pattern and result.  If these fire the user has to add type casts.
4023   if (!InferredAllPatternTypes)
4024     Pattern.error("Could not infer all types in pattern!");
4025   if (!InferredAllResultTypes) {
4026     Pattern.dump();
4027     Result.error("Could not infer all types in pattern result!");
4028   }
4029 
4030   // Promote xform function to be an explicit node wherever set.
4031   TreePatternNodePtr DstShared = PromoteXForms(Result.getOnlyTree());
4032 
4033   TreePattern Temp(Result.getRecord(), DstShared, false, *this);
4034   Temp.InferAllTypes();
4035 
4036   ListInit *Preds = TheDef->getValueAsListInit("Predicates");
4037   int Complexity = TheDef->getValueAsInt("AddedComplexity");
4038 
4039   if (PatternRewriter)
4040     PatternRewriter(&Pattern);
4041 
4042   // A pattern may end up with an "impossible" type, i.e. a situation
4043   // where all types have been eliminated for some node in this pattern.
4044   // This could occur for intrinsics that only make sense for a specific
4045   // value type, and use a specific register class. If, for some mode,
4046   // that register class does not accept that type, the type inference
4047   // will lead to a contradiction, which is not an error however, but
4048   // a sign that this pattern will simply never match.
4049   if (Temp.getOnlyTree()->hasPossibleType())
4050     for (auto T : Pattern.getTrees())
4051       if (T->hasPossibleType())
4052         AddPatternToMatch(&Pattern,
4053                           PatternToMatch(TheDef, makePredList(Preds),
4054                                          T, Temp.getOnlyTree(),
4055                                          InstImpResults, Complexity,
4056                                          TheDef->getID()));
4057 }
4058 
4059 void CodeGenDAGPatterns::ParsePatterns() {
4060   std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
4061 
4062   for (Record *CurPattern : Patterns) {
4063     DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
4064 
4065     // If the pattern references the null_frag, there's nothing to do.
4066     if (hasNullFragReference(Tree))
4067       continue;
4068 
4069     TreePattern Pattern(CurPattern, Tree, true, *this);
4070 
4071     ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
4072     if (LI->empty()) continue;  // no pattern.
4073 
4074     // Parse the instruction.
4075     TreePattern Result(CurPattern, LI, false, *this);
4076 
4077     if (Result.getNumTrees() != 1)
4078       Result.error("Cannot handle instructions producing instructions "
4079                    "with temporaries yet!");
4080 
4081     // Validate that the input pattern is correct.
4082     std::map<std::string, TreePatternNodePtr> InstInputs;
4083     std::map<std::string, TreePatternNodePtr> InstResults;
4084     std::vector<Record*> InstImpResults;
4085     for (unsigned j = 0, ee = Pattern.getNumTrees(); j != ee; ++j)
4086       FindPatternInputsAndOutputs(Pattern, Pattern.getTree(j), InstInputs,
4087                                   InstResults, InstImpResults);
4088 
4089     ParseOnePattern(CurPattern, Pattern, Result, InstImpResults);
4090   }
4091 }
4092 
4093 static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
4094   for (const TypeSetByHwMode &VTS : N->getExtTypes())
4095     for (const auto &I : VTS)
4096       Modes.insert(I.first);
4097 
4098   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
4099     collectModes(Modes, N->getChild(i));
4100 }
4101 
4102 void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
4103   const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
4104   std::map<unsigned,std::vector<Predicate>> ModeChecks;
4105   std::vector<PatternToMatch> Copy = PatternsToMatch;
4106   PatternsToMatch.clear();
4107 
4108   auto AppendPattern = [this, &ModeChecks](PatternToMatch &P, unsigned Mode) {
4109     TreePatternNodePtr NewSrc = P.SrcPattern->clone();
4110     TreePatternNodePtr NewDst = P.DstPattern->clone();
4111     if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
4112       return;
4113     }
4114 
4115     std::vector<Predicate> Preds = P.Predicates;
4116     const std::vector<Predicate> &MC = ModeChecks[Mode];
4117     Preds.insert(Preds.end(), MC.begin(), MC.end());
4118     PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, std::move(NewSrc),
4119                                  std::move(NewDst), P.getDstRegs(),
4120                                  P.getAddedComplexity(), Record::getNewUID(),
4121                                  Mode);
4122   };
4123 
4124   for (PatternToMatch &P : Copy) {
4125     TreePatternNodePtr SrcP = nullptr, DstP = nullptr;
4126     if (P.SrcPattern->hasProperTypeByHwMode())
4127       SrcP = P.SrcPattern;
4128     if (P.DstPattern->hasProperTypeByHwMode())
4129       DstP = P.DstPattern;
4130     if (!SrcP && !DstP) {
4131       PatternsToMatch.push_back(P);
4132       continue;
4133     }
4134 
4135     std::set<unsigned> Modes;
4136     if (SrcP)
4137       collectModes(Modes, SrcP.get());
4138     if (DstP)
4139       collectModes(Modes, DstP.get());
4140 
4141     // The predicate for the default mode needs to be constructed for each
4142     // pattern separately.
4143     // Since not all modes must be present in each pattern, if a mode m is
4144     // absent, then there is no point in constructing a check for m. If such
4145     // a check was created, it would be equivalent to checking the default
4146     // mode, except not all modes' predicates would be a part of the checking
4147     // code. The subsequently generated check for the default mode would then
4148     // have the exact same patterns, but a different predicate code. To avoid
4149     // duplicated patterns with different predicate checks, construct the
4150     // default check as a negation of all predicates that are actually present
4151     // in the source/destination patterns.
4152     std::vector<Predicate> DefaultPred;
4153 
4154     for (unsigned M : Modes) {
4155       if (M == DefaultMode)
4156         continue;
4157       if (ModeChecks.find(M) != ModeChecks.end())
4158         continue;
4159 
4160       // Fill the map entry for this mode.
4161       const HwMode &HM = CGH.getMode(M);
4162       ModeChecks[M].emplace_back(Predicate(HM.Features, true));
4163 
4164       // Add negations of the HM's predicates to the default predicate.
4165       DefaultPred.emplace_back(Predicate(HM.Features, false));
4166     }
4167 
4168     for (unsigned M : Modes) {
4169       if (M == DefaultMode)
4170         continue;
4171       AppendPattern(P, M);
4172     }
4173 
4174     bool HasDefault = Modes.count(DefaultMode);
4175     if (HasDefault)
4176       AppendPattern(P, DefaultMode);
4177   }
4178 }
4179 
4180 /// Dependent variable map for CodeGenDAGPattern variant generation
4181 typedef StringMap<int> DepVarMap;
4182 
4183 static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
4184   if (N->isLeaf()) {
4185     if (N->hasName() && isa<DefInit>(N->getLeafValue()))
4186       DepMap[N->getName()]++;
4187   } else {
4188     for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
4189       FindDepVarsOf(N->getChild(i), DepMap);
4190   }
4191 }
4192 
4193 /// Find dependent variables within child patterns
4194 static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
4195   DepVarMap depcounts;
4196   FindDepVarsOf(N, depcounts);
4197   for (const auto &Pair : depcounts) {
4198     if (Pair.getValue() > 1)
4199       DepVars.insert(Pair.getKey());
4200   }
4201 }
4202 
4203 #ifndef NDEBUG
4204 /// Dump the dependent variable set:
4205 static void DumpDepVars(MultipleUseVarSet &DepVars) {
4206   if (DepVars.empty()) {
4207     LLVM_DEBUG(errs() << "<empty set>");
4208   } else {
4209     LLVM_DEBUG(errs() << "[ ");
4210     for (const auto &DepVar : DepVars) {
4211       LLVM_DEBUG(errs() << DepVar.getKey() << " ");
4212     }
4213     LLVM_DEBUG(errs() << "]");
4214   }
4215 }
4216 #endif
4217 
4218 
4219 /// CombineChildVariants - Given a bunch of permutations of each child of the
4220 /// 'operator' node, put them together in all possible ways.
4221 static void CombineChildVariants(
4222     TreePatternNodePtr Orig,
4223     const std::vector<std::vector<TreePatternNodePtr>> &ChildVariants,
4224     std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP,
4225     const MultipleUseVarSet &DepVars) {
4226   // Make sure that each operand has at least one variant to choose from.
4227   for (const auto &Variants : ChildVariants)
4228     if (Variants.empty())
4229       return;
4230 
4231   // The end result is an all-pairs construction of the resultant pattern.
4232   std::vector<unsigned> Idxs;
4233   Idxs.resize(ChildVariants.size());
4234   bool NotDone;
4235   do {
4236 #ifndef NDEBUG
4237     LLVM_DEBUG(if (!Idxs.empty()) {
4238       errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
4239       for (unsigned Idx : Idxs) {
4240         errs() << Idx << " ";
4241       }
4242       errs() << "]\n";
4243     });
4244 #endif
4245     // Create the variant and add it to the output list.
4246     std::vector<TreePatternNodePtr> NewChildren;
4247     for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
4248       NewChildren.push_back(ChildVariants[i][Idxs[i]]);
4249     TreePatternNodePtr R = std::make_shared<TreePatternNode>(
4250         Orig->getOperator(), std::move(NewChildren), Orig->getNumTypes());
4251 
4252     // Copy over properties.
4253     R->setName(Orig->getName());
4254     R->setPredicateFns(Orig->getPredicateFns());
4255     R->setTransformFn(Orig->getTransformFn());
4256     for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
4257       R->setType(i, Orig->getExtType(i));
4258 
4259     // If this pattern cannot match, do not include it as a variant.
4260     std::string ErrString;
4261     // Scan to see if this pattern has already been emitted.  We can get
4262     // duplication due to things like commuting:
4263     //   (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4264     // which are the same pattern.  Ignore the dups.
4265     if (R->canPatternMatch(ErrString, CDP) &&
4266         none_of(OutVariants, [&](TreePatternNodePtr Variant) {
4267           return R->isIsomorphicTo(Variant.get(), DepVars);
4268         }))
4269       OutVariants.push_back(R);
4270 
4271     // Increment indices to the next permutation by incrementing the
4272     // indices from last index backward, e.g., generate the sequence
4273     // [0, 0], [0, 1], [1, 0], [1, 1].
4274     int IdxsIdx;
4275     for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
4276       if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
4277         Idxs[IdxsIdx] = 0;
4278       else
4279         break;
4280     }
4281     NotDone = (IdxsIdx >= 0);
4282   } while (NotDone);
4283 }
4284 
4285 /// CombineChildVariants - A helper function for binary operators.
4286 ///
4287 static void CombineChildVariants(TreePatternNodePtr Orig,
4288                                  const std::vector<TreePatternNodePtr> &LHS,
4289                                  const std::vector<TreePatternNodePtr> &RHS,
4290                                  std::vector<TreePatternNodePtr> &OutVariants,
4291                                  CodeGenDAGPatterns &CDP,
4292                                  const MultipleUseVarSet &DepVars) {
4293   std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
4294   ChildVariants.push_back(LHS);
4295   ChildVariants.push_back(RHS);
4296   CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
4297 }
4298 
4299 static void
4300 GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N,
4301                                   std::vector<TreePatternNodePtr> &Children) {
4302   assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
4303   Record *Operator = N->getOperator();
4304 
4305   // Only permit raw nodes.
4306   if (!N->getName().empty() || !N->getPredicateFns().empty() ||
4307       N->getTransformFn()) {
4308     Children.push_back(N);
4309     return;
4310   }
4311 
4312   if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
4313     Children.push_back(N->getChildShared(0));
4314   else
4315     GatherChildrenOfAssociativeOpcode(N->getChildShared(0), Children);
4316 
4317   if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
4318     Children.push_back(N->getChildShared(1));
4319   else
4320     GatherChildrenOfAssociativeOpcode(N->getChildShared(1), Children);
4321 }
4322 
4323 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4324 /// the (potentially recursive) pattern by using algebraic laws.
4325 ///
4326 static void GenerateVariantsOf(TreePatternNodePtr N,
4327                                std::vector<TreePatternNodePtr> &OutVariants,
4328                                CodeGenDAGPatterns &CDP,
4329                                const MultipleUseVarSet &DepVars) {
4330   // We cannot permute leaves or ComplexPattern uses.
4331   if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
4332     OutVariants.push_back(N);
4333     return;
4334   }
4335 
4336   // Look up interesting info about the node.
4337   const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
4338 
4339   // If this node is associative, re-associate.
4340   if (NodeInfo.hasProperty(SDNPAssociative)) {
4341     // Re-associate by pulling together all of the linked operators
4342     std::vector<TreePatternNodePtr> MaximalChildren;
4343     GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
4344 
4345     // Only handle child sizes of 3.  Otherwise we'll end up trying too many
4346     // permutations.
4347     if (MaximalChildren.size() == 3) {
4348       // Find the variants of all of our maximal children.
4349       std::vector<TreePatternNodePtr> AVariants, BVariants, CVariants;
4350       GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
4351       GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
4352       GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
4353 
4354       // There are only two ways we can permute the tree:
4355       //   (A op B) op C    and    A op (B op C)
4356       // Within these forms, we can also permute A/B/C.
4357 
4358       // Generate legal pair permutations of A/B/C.
4359       std::vector<TreePatternNodePtr> ABVariants;
4360       std::vector<TreePatternNodePtr> BAVariants;
4361       std::vector<TreePatternNodePtr> ACVariants;
4362       std::vector<TreePatternNodePtr> CAVariants;
4363       std::vector<TreePatternNodePtr> BCVariants;
4364       std::vector<TreePatternNodePtr> CBVariants;
4365       CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4366       CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4367       CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4368       CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4369       CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4370       CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
4371 
4372       // Combine those into the result: (x op x) op x
4373       CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4374       CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4375       CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4376       CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4377       CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4378       CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
4379 
4380       // Combine those into the result: x op (x op x)
4381       CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4382       CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4383       CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4384       CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4385       CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4386       CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
4387       return;
4388     }
4389   }
4390 
4391   // Compute permutations of all children.
4392   std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
4393   ChildVariants.resize(N->getNumChildren());
4394   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
4395     GenerateVariantsOf(N->getChildShared(i), ChildVariants[i], CDP, DepVars);
4396 
4397   // Build all permutations based on how the children were formed.
4398   CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
4399 
4400   // If this node is commutative, consider the commuted order.
4401   bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4402   if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
4403     assert((N->getNumChildren()>=2 || isCommIntrinsic) &&
4404            "Commutative but doesn't have 2 children!");
4405     // Don't count children which are actually register references.
4406     unsigned NC = 0;
4407     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4408       TreePatternNode *Child = N->getChild(i);
4409       if (Child->isLeaf())
4410         if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
4411           Record *RR = DI->getDef();
4412           if (RR->isSubClassOf("Register"))
4413             continue;
4414         }
4415       NC++;
4416     }
4417     // Consider the commuted order.
4418     if (isCommIntrinsic) {
4419       // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4420       // operands are the commutative operands, and there might be more operands
4421       // after those.
4422       assert(NC >= 3 &&
4423              "Commutative intrinsic should have at least 3 children!");
4424       std::vector<std::vector<TreePatternNodePtr>> Variants;
4425       Variants.push_back(std::move(ChildVariants[0])); // Intrinsic id.
4426       Variants.push_back(std::move(ChildVariants[2]));
4427       Variants.push_back(std::move(ChildVariants[1]));
4428       for (unsigned i = 3; i != NC; ++i)
4429         Variants.push_back(std::move(ChildVariants[i]));
4430       CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
4431     } else if (NC == N->getNumChildren()) {
4432       std::vector<std::vector<TreePatternNodePtr>> Variants;
4433       Variants.push_back(std::move(ChildVariants[1]));
4434       Variants.push_back(std::move(ChildVariants[0]));
4435       for (unsigned i = 2; i != NC; ++i)
4436         Variants.push_back(std::move(ChildVariants[i]));
4437       CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
4438     }
4439   }
4440 }
4441 
4442 
4443 // GenerateVariants - Generate variants.  For example, commutative patterns can
4444 // match multiple ways.  Add them to PatternsToMatch as well.
4445 void CodeGenDAGPatterns::GenerateVariants() {
4446   LLVM_DEBUG(errs() << "Generating instruction variants.\n");
4447 
4448   // Loop over all of the patterns we've collected, checking to see if we can
4449   // generate variants of the instruction, through the exploitation of
4450   // identities.  This permits the target to provide aggressive matching without
4451   // the .td file having to contain tons of variants of instructions.
4452   //
4453   // Note that this loop adds new patterns to the PatternsToMatch list, but we
4454   // intentionally do not reconsider these.  Any variants of added patterns have
4455   // already been added.
4456   //
4457   const unsigned NumOriginalPatterns = PatternsToMatch.size();
4458   BitVector MatchedPatterns(NumOriginalPatterns);
4459   std::vector<BitVector> MatchedPredicates(NumOriginalPatterns,
4460                                            BitVector(NumOriginalPatterns));
4461 
4462   typedef std::pair<MultipleUseVarSet, std::vector<TreePatternNodePtr>>
4463       DepsAndVariants;
4464   std::map<unsigned, DepsAndVariants> PatternsWithVariants;
4465 
4466   // Collect patterns with more than one variant.
4467   for (unsigned i = 0; i != NumOriginalPatterns; ++i) {
4468     MultipleUseVarSet DepVars;
4469     std::vector<TreePatternNodePtr> Variants;
4470     FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
4471     LLVM_DEBUG(errs() << "Dependent/multiply used variables: ");
4472     LLVM_DEBUG(DumpDepVars(DepVars));
4473     LLVM_DEBUG(errs() << "\n");
4474     GenerateVariantsOf(PatternsToMatch[i].getSrcPatternShared(), Variants,
4475                        *this, DepVars);
4476 
4477     assert(!Variants.empty() && "Must create at least original variant!");
4478     if (Variants.size() == 1) // No additional variants for this pattern.
4479       continue;
4480 
4481     LLVM_DEBUG(errs() << "FOUND VARIANTS OF: ";
4482                PatternsToMatch[i].getSrcPattern()->dump(); errs() << "\n");
4483 
4484     PatternsWithVariants[i] = std::make_pair(DepVars, Variants);
4485 
4486     // Cache matching predicates.
4487     if (MatchedPatterns[i])
4488       continue;
4489 
4490     const std::vector<Predicate> &Predicates =
4491         PatternsToMatch[i].getPredicates();
4492 
4493     BitVector &Matches = MatchedPredicates[i];
4494     MatchedPatterns.set(i);
4495     Matches.set(i);
4496 
4497     // Don't test patterns that have already been cached - it won't match.
4498     for (unsigned p = 0; p != NumOriginalPatterns; ++p)
4499       if (!MatchedPatterns[p])
4500         Matches[p] = (Predicates == PatternsToMatch[p].getPredicates());
4501 
4502     // Copy this to all the matching patterns.
4503     for (int p = Matches.find_first(); p != -1; p = Matches.find_next(p))
4504       if (p != (int)i) {
4505         MatchedPatterns.set(p);
4506         MatchedPredicates[p] = Matches;
4507       }
4508   }
4509 
4510   for (auto it : PatternsWithVariants) {
4511     unsigned i = it.first;
4512     const MultipleUseVarSet &DepVars = it.second.first;
4513     const std::vector<TreePatternNodePtr> &Variants = it.second.second;
4514 
4515     for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
4516       TreePatternNodePtr Variant = Variants[v];
4517       BitVector &Matches = MatchedPredicates[i];
4518 
4519       LLVM_DEBUG(errs() << "  VAR#" << v << ": "; Variant->dump();
4520                  errs() << "\n");
4521 
4522       // Scan to see if an instruction or explicit pattern already matches this.
4523       bool AlreadyExists = false;
4524       for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
4525         // Skip if the top level predicates do not match.
4526         if (!Matches[p])
4527           continue;
4528         // Check to see if this variant already exists.
4529         if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
4530                                     DepVars)) {
4531           LLVM_DEBUG(errs() << "  *** ALREADY EXISTS, ignoring variant.\n");
4532           AlreadyExists = true;
4533           break;
4534         }
4535       }
4536       // If we already have it, ignore the variant.
4537       if (AlreadyExists) continue;
4538 
4539       // Otherwise, add it to the list of patterns we have.
4540       PatternsToMatch.push_back(PatternToMatch(
4541           PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
4542           Variant, PatternsToMatch[i].getDstPatternShared(),
4543           PatternsToMatch[i].getDstRegs(),
4544           PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
4545       MatchedPredicates.push_back(Matches);
4546 
4547       // Add a new match the same as this pattern.
4548       for (auto &P : MatchedPredicates)
4549         P.push_back(P[i]);
4550     }
4551 
4552     LLVM_DEBUG(errs() << "\n");
4553   }
4554 }
4555