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