xref: /llvm-project/llvm/utils/TableGen/Common/CodeGenDAGPatterns.cpp (revision d0dc29c2084a18c33b1b5b1cad9fd42215869746)
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() || hasOneUse() ||
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   if (hasOneUse())
1144     Code += "if (!SDValue(N, 0).hasOneUse()) return false;\n";
1145 
1146   std::string PredicateCode =
1147       std::string(PatFragRec->getRecord()->getValueAsString("PredicateCode"));
1148 
1149   Code += PredicateCode;
1150 
1151   if (PredicateCode.empty() && !Code.empty())
1152     Code += "return true;\n";
1153 
1154   return Code;
1155 }
1156 
1157 bool TreePredicateFn::hasImmCode() const {
1158   return !PatFragRec->getRecord()->getValueAsString("ImmediateCode").empty();
1159 }
1160 
1161 std::string TreePredicateFn::getImmCode() const {
1162   return std::string(
1163       PatFragRec->getRecord()->getValueAsString("ImmediateCode"));
1164 }
1165 
1166 bool TreePredicateFn::immCodeUsesAPInt() const {
1167   return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
1168 }
1169 
1170 bool TreePredicateFn::immCodeUsesAPFloat() const {
1171   bool Unset;
1172   // The return value will be false when IsAPFloat is unset.
1173   return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
1174                                                                    Unset);
1175 }
1176 
1177 bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,
1178                                                    bool Value) const {
1179   bool Unset;
1180   bool Result =
1181       getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field, Unset);
1182   if (Unset)
1183     return false;
1184   return Result == Value;
1185 }
1186 bool TreePredicateFn::usesOperands() const {
1187   return isPredefinedPredicateEqualTo("PredicateCodeUsesOperands", true);
1188 }
1189 bool TreePredicateFn::hasNoUse() const {
1190   return isPredefinedPredicateEqualTo("HasNoUse", true);
1191 }
1192 bool TreePredicateFn::hasOneUse() const {
1193   return isPredefinedPredicateEqualTo("HasOneUse", true);
1194 }
1195 bool TreePredicateFn::isLoad() const {
1196   return isPredefinedPredicateEqualTo("IsLoad", true);
1197 }
1198 bool TreePredicateFn::isStore() const {
1199   return isPredefinedPredicateEqualTo("IsStore", true);
1200 }
1201 bool TreePredicateFn::isAtomic() const {
1202   return isPredefinedPredicateEqualTo("IsAtomic", true);
1203 }
1204 bool TreePredicateFn::isUnindexed() const {
1205   return isPredefinedPredicateEqualTo("IsUnindexed", true);
1206 }
1207 bool TreePredicateFn::isNonExtLoad() const {
1208   return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
1209 }
1210 bool TreePredicateFn::isAnyExtLoad() const {
1211   return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
1212 }
1213 bool TreePredicateFn::isSignExtLoad() const {
1214   return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
1215 }
1216 bool TreePredicateFn::isZeroExtLoad() const {
1217   return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
1218 }
1219 bool TreePredicateFn::isNonTruncStore() const {
1220   return isPredefinedPredicateEqualTo("IsTruncStore", false);
1221 }
1222 bool TreePredicateFn::isTruncStore() const {
1223   return isPredefinedPredicateEqualTo("IsTruncStore", true);
1224 }
1225 bool TreePredicateFn::isAtomicOrderingMonotonic() const {
1226   return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true);
1227 }
1228 bool TreePredicateFn::isAtomicOrderingAcquire() const {
1229   return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true);
1230 }
1231 bool TreePredicateFn::isAtomicOrderingRelease() const {
1232   return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true);
1233 }
1234 bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
1235   return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true);
1236 }
1237 bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
1238   return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent",
1239                                       true);
1240 }
1241 bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {
1242   return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger",
1243                                       true);
1244 }
1245 bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {
1246   return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger",
1247                                       false);
1248 }
1249 bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {
1250   return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger",
1251                                       true);
1252 }
1253 bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {
1254   return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger",
1255                                       false);
1256 }
1257 Record *TreePredicateFn::getMemoryVT() const {
1258   Record *R = getOrigPatFragRecord()->getRecord();
1259   if (R->isValueUnset("MemoryVT"))
1260     return nullptr;
1261   return R->getValueAsDef("MemoryVT");
1262 }
1263 
1264 ListInit *TreePredicateFn::getAddressSpaces() const {
1265   Record *R = getOrigPatFragRecord()->getRecord();
1266   if (R->isValueUnset("AddressSpaces"))
1267     return nullptr;
1268   return R->getValueAsListInit("AddressSpaces");
1269 }
1270 
1271 int64_t TreePredicateFn::getMinAlignment() const {
1272   Record *R = getOrigPatFragRecord()->getRecord();
1273   if (R->isValueUnset("MinAlignment"))
1274     return 0;
1275   return R->getValueAsInt("MinAlignment");
1276 }
1277 
1278 Record *TreePredicateFn::getScalarMemoryVT() const {
1279   Record *R = getOrigPatFragRecord()->getRecord();
1280   if (R->isValueUnset("ScalarMemoryVT"))
1281     return nullptr;
1282   return R->getValueAsDef("ScalarMemoryVT");
1283 }
1284 bool TreePredicateFn::hasGISelPredicateCode() const {
1285   return !PatFragRec->getRecord()
1286               ->getValueAsString("GISelPredicateCode")
1287               .empty();
1288 }
1289 std::string TreePredicateFn::getGISelPredicateCode() const {
1290   return std::string(
1291       PatFragRec->getRecord()->getValueAsString("GISelPredicateCode"));
1292 }
1293 
1294 StringRef TreePredicateFn::getImmType() const {
1295   if (immCodeUsesAPInt())
1296     return "const APInt &";
1297   if (immCodeUsesAPFloat())
1298     return "const APFloat &";
1299   return "int64_t";
1300 }
1301 
1302 StringRef TreePredicateFn::getImmTypeIdentifier() const {
1303   if (immCodeUsesAPInt())
1304     return "APInt";
1305   if (immCodeUsesAPFloat())
1306     return "APFloat";
1307   return "I64";
1308 }
1309 
1310 /// isAlwaysTrue - Return true if this is a noop predicate.
1311 bool TreePredicateFn::isAlwaysTrue() const {
1312   return !hasPredCode() && !hasImmCode();
1313 }
1314 
1315 /// Return the name to use in the generated code to reference this, this is
1316 /// "Predicate_foo" if from a pattern fragment "foo".
1317 std::string TreePredicateFn::getFnName() const {
1318   return "Predicate_" + PatFragRec->getRecord()->getName().str();
1319 }
1320 
1321 /// getCodeToRunOnSDNode - Return the code for the function body that
1322 /// evaluates this predicate.  The argument is expected to be in "Node",
1323 /// not N.  This handles casting and conversion to a concrete node type as
1324 /// appropriate.
1325 std::string TreePredicateFn::getCodeToRunOnSDNode() const {
1326   // Handle immediate predicates first.
1327   std::string ImmCode = getImmCode();
1328   if (!ImmCode.empty()) {
1329     if (isLoad())
1330       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1331                       "IsLoad cannot be used with ImmLeaf or its subclasses");
1332     if (isStore())
1333       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1334                       "IsStore cannot be used with ImmLeaf or its subclasses");
1335     if (isUnindexed())
1336       PrintFatalError(
1337           getOrigPatFragRecord()->getRecord()->getLoc(),
1338           "IsUnindexed cannot be used with ImmLeaf or its subclasses");
1339     if (isNonExtLoad())
1340       PrintFatalError(
1341           getOrigPatFragRecord()->getRecord()->getLoc(),
1342           "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
1343     if (isAnyExtLoad())
1344       PrintFatalError(
1345           getOrigPatFragRecord()->getRecord()->getLoc(),
1346           "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
1347     if (isSignExtLoad())
1348       PrintFatalError(
1349           getOrigPatFragRecord()->getRecord()->getLoc(),
1350           "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
1351     if (isZeroExtLoad())
1352       PrintFatalError(
1353           getOrigPatFragRecord()->getRecord()->getLoc(),
1354           "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
1355     if (isNonTruncStore())
1356       PrintFatalError(
1357           getOrigPatFragRecord()->getRecord()->getLoc(),
1358           "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
1359     if (isTruncStore())
1360       PrintFatalError(
1361           getOrigPatFragRecord()->getRecord()->getLoc(),
1362           "IsTruncStore cannot be used with ImmLeaf or its subclasses");
1363     if (getMemoryVT())
1364       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1365                       "MemoryVT cannot be used with ImmLeaf or its subclasses");
1366     if (getScalarMemoryVT())
1367       PrintFatalError(
1368           getOrigPatFragRecord()->getRecord()->getLoc(),
1369           "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
1370 
1371     std::string Result = ("    " + getImmType() + " Imm = ").str();
1372     if (immCodeUsesAPFloat())
1373       Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
1374     else if (immCodeUsesAPInt())
1375       Result += "Node->getAsAPIntVal();\n";
1376     else
1377       Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n";
1378     return Result + ImmCode;
1379   }
1380 
1381   // Handle arbitrary node predicates.
1382   assert(hasPredCode() && "Don't have any predicate code!");
1383 
1384   // If this is using PatFrags, there are multiple trees to search. They should
1385   // all have the same class.  FIXME: Is there a way to find a common
1386   // superclass?
1387   StringRef ClassName;
1388   for (const auto &Tree : PatFragRec->getTrees()) {
1389     StringRef TreeClassName;
1390     if (Tree->isLeaf())
1391       TreeClassName = "SDNode";
1392     else {
1393       Record *Op = Tree->getOperator();
1394       const SDNodeInfo &Info = PatFragRec->getDAGPatterns().getSDNodeInfo(Op);
1395       TreeClassName = Info.getSDClassName();
1396     }
1397 
1398     if (ClassName.empty())
1399       ClassName = TreeClassName;
1400     else if (ClassName != TreeClassName) {
1401       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1402                       "PatFrags trees do not have consistent class");
1403     }
1404   }
1405 
1406   std::string Result;
1407   if (ClassName == "SDNode")
1408     Result = "    SDNode *N = Node;\n";
1409   else
1410     Result = "    auto *N = cast<" + ClassName.str() + ">(Node);\n";
1411 
1412   return (Twine(Result) + "    (void)N;\n" + getPredCode()).str();
1413 }
1414 
1415 //===----------------------------------------------------------------------===//
1416 // PatternToMatch implementation
1417 //
1418 
1419 static bool isImmAllOnesAllZerosMatch(const TreePatternNode &P) {
1420   if (!P.isLeaf())
1421     return false;
1422   DefInit *DI = dyn_cast<DefInit>(P.getLeafValue());
1423   if (!DI)
1424     return false;
1425 
1426   Record *R = DI->getDef();
1427   return R->getName() == "immAllOnesV" || R->getName() == "immAllZerosV";
1428 }
1429 
1430 /// getPatternSize - Return the 'size' of this pattern.  We want to match large
1431 /// patterns before small ones.  This is used to determine the size of a
1432 /// pattern.
1433 static unsigned getPatternSize(const TreePatternNode &P,
1434                                const CodeGenDAGPatterns &CGP) {
1435   unsigned Size = 3; // The node itself.
1436   // If the root node is a ConstantSDNode, increases its size.
1437   // e.g. (set R32:$dst, 0).
1438   if (P.isLeaf() && isa<IntInit>(P.getLeafValue()))
1439     Size += 2;
1440 
1441   if (const ComplexPattern *AM = P.getComplexPatternInfo(CGP)) {
1442     Size += AM->getComplexity();
1443     // We don't want to count any children twice, so return early.
1444     return Size;
1445   }
1446 
1447   // If this node has some predicate function that must match, it adds to the
1448   // complexity of this node.
1449   if (!P.getPredicateCalls().empty())
1450     ++Size;
1451 
1452   // Count children in the count if they are also nodes.
1453   for (unsigned i = 0, e = P.getNumChildren(); i != e; ++i) {
1454     const TreePatternNode &Child = P.getChild(i);
1455     if (!Child.isLeaf() && Child.getNumTypes()) {
1456       const TypeSetByHwMode &T0 = Child.getExtType(0);
1457       // At this point, all variable type sets should be simple, i.e. only
1458       // have a default mode.
1459       if (T0.getMachineValueType() != MVT::Other) {
1460         Size += getPatternSize(Child, CGP);
1461         continue;
1462       }
1463     }
1464     if (Child.isLeaf()) {
1465       if (isa<IntInit>(Child.getLeafValue()))
1466         Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
1467       else if (Child.getComplexPatternInfo(CGP))
1468         Size += getPatternSize(Child, CGP);
1469       else if (isImmAllOnesAllZerosMatch(Child))
1470         Size += 4; // Matches a build_vector(+3) and a predicate (+1).
1471       else if (!Child.getPredicateCalls().empty())
1472         ++Size;
1473     }
1474   }
1475 
1476   return Size;
1477 }
1478 
1479 /// Compute the complexity metric for the input pattern.  This roughly
1480 /// corresponds to the number of nodes that are covered.
1481 int PatternToMatch::getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
1482   return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
1483 }
1484 
1485 void PatternToMatch::getPredicateRecords(
1486     SmallVectorImpl<Record *> &PredicateRecs) const {
1487   for (Init *I : Predicates->getValues()) {
1488     if (DefInit *Pred = dyn_cast<DefInit>(I)) {
1489       Record *Def = Pred->getDef();
1490       if (!Def->isSubClassOf("Predicate")) {
1491 #ifndef NDEBUG
1492         Def->dump();
1493 #endif
1494         llvm_unreachable("Unknown predicate type!");
1495       }
1496       PredicateRecs.push_back(Def);
1497     }
1498   }
1499   // Sort so that different orders get canonicalized to the same string.
1500   llvm::sort(PredicateRecs, LessRecord());
1501   // Remove duplicate predicates.
1502   PredicateRecs.erase(std::unique(PredicateRecs.begin(), PredicateRecs.end()),
1503                       PredicateRecs.end());
1504 }
1505 
1506 /// getPredicateCheck - Return a single string containing all of this
1507 /// pattern's predicates concatenated with "&&" operators.
1508 ///
1509 std::string PatternToMatch::getPredicateCheck() const {
1510   SmallVector<Record *, 4> PredicateRecs;
1511   getPredicateRecords(PredicateRecs);
1512 
1513   SmallString<128> PredicateCheck;
1514   raw_svector_ostream OS(PredicateCheck);
1515   ListSeparator LS(" && ");
1516   for (Record *Pred : PredicateRecs) {
1517     StringRef CondString = Pred->getValueAsString("CondString");
1518     if (CondString.empty())
1519       continue;
1520     OS << LS << '(' << CondString << ')';
1521   }
1522 
1523   if (!HwModeFeatures.empty())
1524     OS << LS << HwModeFeatures;
1525 
1526   return std::string(PredicateCheck);
1527 }
1528 
1529 //===----------------------------------------------------------------------===//
1530 // SDTypeConstraint implementation
1531 //
1532 
1533 SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
1534   OperandNo = R->getValueAsInt("OperandNum");
1535 
1536   if (R->isSubClassOf("SDTCisVT")) {
1537     ConstraintType = SDTCisVT;
1538     VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1539     for (const auto &P : VVT)
1540       if (P.second == MVT::isVoid)
1541         PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
1542   } else if (R->isSubClassOf("SDTCisPtrTy")) {
1543     ConstraintType = SDTCisPtrTy;
1544   } else if (R->isSubClassOf("SDTCisInt")) {
1545     ConstraintType = SDTCisInt;
1546   } else if (R->isSubClassOf("SDTCisFP")) {
1547     ConstraintType = SDTCisFP;
1548   } else if (R->isSubClassOf("SDTCisVec")) {
1549     ConstraintType = SDTCisVec;
1550   } else if (R->isSubClassOf("SDTCisSameAs")) {
1551     ConstraintType = SDTCisSameAs;
1552     x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
1553   } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
1554     ConstraintType = SDTCisVTSmallerThanOp;
1555     x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
1556         R->getValueAsInt("OtherOperandNum");
1557   } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
1558     ConstraintType = SDTCisOpSmallerThanOp;
1559     x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
1560         R->getValueAsInt("BigOperandNum");
1561   } else if (R->isSubClassOf("SDTCisEltOfVec")) {
1562     ConstraintType = SDTCisEltOfVec;
1563     x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
1564   } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
1565     ConstraintType = SDTCisSubVecOfVec;
1566     x.SDTCisSubVecOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
1567   } else if (R->isSubClassOf("SDTCVecEltisVT")) {
1568     ConstraintType = SDTCVecEltisVT;
1569     VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1570     for (const auto &P : VVT) {
1571       MVT T = P.second;
1572       if (T.isVector())
1573         PrintFatalError(R->getLoc(),
1574                         "Cannot use vector type as SDTCVecEltisVT");
1575       if (!T.isInteger() && !T.isFloatingPoint())
1576         PrintFatalError(R->getLoc(), "Must use integer or floating point type "
1577                                      "as SDTCVecEltisVT");
1578     }
1579   } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
1580     ConstraintType = SDTCisSameNumEltsAs;
1581     x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
1582         R->getValueAsInt("OtherOperandNum");
1583   } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
1584     ConstraintType = SDTCisSameSizeAs;
1585     x.SDTCisSameSizeAs_Info.OtherOperandNum =
1586         R->getValueAsInt("OtherOperandNum");
1587   } else {
1588     PrintFatalError(R->getLoc(),
1589                     "Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
1590   }
1591 }
1592 
1593 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
1594 /// N, and the result number in ResNo.
1595 static TreePatternNode &getOperandNum(unsigned OpNo, TreePatternNode &N,
1596                                       const SDNodeInfo &NodeInfo,
1597                                       unsigned &ResNo) {
1598   unsigned NumResults = NodeInfo.getNumResults();
1599   if (OpNo < NumResults) {
1600     ResNo = OpNo;
1601     return N;
1602   }
1603 
1604   OpNo -= NumResults;
1605 
1606   if (OpNo >= N.getNumChildren()) {
1607     std::string S;
1608     raw_string_ostream OS(S);
1609     OS << "Invalid operand number in type constraint " << (OpNo + NumResults)
1610        << " ";
1611     N.print(OS);
1612     PrintFatalError(S);
1613   }
1614 
1615   return N.getChild(OpNo);
1616 }
1617 
1618 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
1619 /// constraint to the nodes operands.  This returns true if it makes a
1620 /// change, false otherwise.  If a type contradiction is found, flag an error.
1621 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode &N,
1622                                            const SDNodeInfo &NodeInfo,
1623                                            TreePattern &TP) const {
1624   if (TP.hasError())
1625     return false;
1626 
1627   unsigned ResNo = 0; // The result number being referenced.
1628   TreePatternNode &NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
1629   TypeInfer &TI = TP.getInfer();
1630 
1631   switch (ConstraintType) {
1632   case SDTCisVT:
1633     // Operand must be a particular type.
1634     return NodeToApply.UpdateNodeType(ResNo, VVT, TP);
1635   case SDTCisPtrTy:
1636     // Operand must be same as target pointer type.
1637     return NodeToApply.UpdateNodeType(ResNo, MVT::iPTR, TP);
1638   case SDTCisInt:
1639     // Require it to be one of the legal integer VTs.
1640     return TI.EnforceInteger(NodeToApply.getExtType(ResNo));
1641   case SDTCisFP:
1642     // Require it to be one of the legal fp VTs.
1643     return TI.EnforceFloatingPoint(NodeToApply.getExtType(ResNo));
1644   case SDTCisVec:
1645     // Require it to be one of the legal vector VTs.
1646     return TI.EnforceVector(NodeToApply.getExtType(ResNo));
1647   case SDTCisSameAs: {
1648     unsigned OResNo = 0;
1649     TreePatternNode &OtherNode =
1650         getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
1651     return (int)NodeToApply.UpdateNodeType(ResNo, OtherNode.getExtType(OResNo),
1652                                            TP) |
1653            (int)OtherNode.UpdateNodeType(OResNo, NodeToApply.getExtType(ResNo),
1654                                          TP);
1655   }
1656   case SDTCisVTSmallerThanOp: {
1657     // The NodeToApply must be a leaf node that is a VT.  OtherOperandNum must
1658     // have an integer type that is smaller than the VT.
1659     if (!NodeToApply.isLeaf() || !isa<DefInit>(NodeToApply.getLeafValue()) ||
1660         !cast<DefInit>(NodeToApply.getLeafValue())
1661              ->getDef()
1662              ->isSubClassOf("ValueType")) {
1663       TP.error(N.getOperator()->getName() + " expects a VT operand!");
1664       return false;
1665     }
1666     DefInit *DI = cast<DefInit>(NodeToApply.getLeafValue());
1667     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1668     auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
1669     TypeSetByHwMode TypeListTmp(VVT);
1670 
1671     unsigned OResNo = 0;
1672     TreePatternNode &OtherNode = getOperandNum(
1673         x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo, OResNo);
1674 
1675     return TI.EnforceSmallerThan(TypeListTmp, OtherNode.getExtType(OResNo),
1676                                  /*SmallIsVT*/ true);
1677   }
1678   case SDTCisOpSmallerThanOp: {
1679     unsigned BResNo = 0;
1680     TreePatternNode &BigOperand = getOperandNum(
1681         x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo, BResNo);
1682     return TI.EnforceSmallerThan(NodeToApply.getExtType(ResNo),
1683                                  BigOperand.getExtType(BResNo));
1684   }
1685   case SDTCisEltOfVec: {
1686     unsigned VResNo = 0;
1687     TreePatternNode &VecOperand = getOperandNum(
1688         x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo, VResNo);
1689     // Filter vector types out of VecOperand that don't have the right element
1690     // type.
1691     return TI.EnforceVectorEltTypeIs(VecOperand.getExtType(VResNo),
1692                                      NodeToApply.getExtType(ResNo));
1693   }
1694   case SDTCisSubVecOfVec: {
1695     unsigned VResNo = 0;
1696     TreePatternNode &BigVecOperand = getOperandNum(
1697         x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo, VResNo);
1698 
1699     // Filter vector types out of BigVecOperand that don't have the
1700     // right subvector type.
1701     return TI.EnforceVectorSubVectorTypeIs(BigVecOperand.getExtType(VResNo),
1702                                            NodeToApply.getExtType(ResNo));
1703   }
1704   case SDTCVecEltisVT: {
1705     return TI.EnforceVectorEltTypeIs(NodeToApply.getExtType(ResNo), VVT);
1706   }
1707   case SDTCisSameNumEltsAs: {
1708     unsigned OResNo = 0;
1709     TreePatternNode &OtherNode = getOperandNum(
1710         x.SDTCisSameNumEltsAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
1711     return TI.EnforceSameNumElts(OtherNode.getExtType(OResNo),
1712                                  NodeToApply.getExtType(ResNo));
1713   }
1714   case SDTCisSameSizeAs: {
1715     unsigned OResNo = 0;
1716     TreePatternNode &OtherNode = getOperandNum(
1717         x.SDTCisSameSizeAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
1718     return TI.EnforceSameSize(OtherNode.getExtType(OResNo),
1719                               NodeToApply.getExtType(ResNo));
1720   }
1721   }
1722   llvm_unreachable("Invalid ConstraintType!");
1723 }
1724 
1725 // Update the node type to match an instruction operand or result as specified
1726 // in the ins or outs lists on the instruction definition. Return true if the
1727 // type was actually changed.
1728 bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo, Record *Operand,
1729                                              TreePattern &TP) {
1730   // The 'unknown' operand indicates that types should be inferred from the
1731   // context.
1732   if (Operand->isSubClassOf("unknown_class"))
1733     return false;
1734 
1735   // The Operand class specifies a type directly.
1736   if (Operand->isSubClassOf("Operand")) {
1737     Record *R = Operand->getValueAsDef("Type");
1738     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1739     return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
1740   }
1741 
1742   // PointerLikeRegClass has a type that is determined at runtime.
1743   if (Operand->isSubClassOf("PointerLikeRegClass"))
1744     return UpdateNodeType(ResNo, MVT::iPTR, TP);
1745 
1746   // Both RegisterClass and RegisterOperand operands derive their types from a
1747   // register class def.
1748   Record *RC = nullptr;
1749   if (Operand->isSubClassOf("RegisterClass"))
1750     RC = Operand;
1751   else if (Operand->isSubClassOf("RegisterOperand"))
1752     RC = Operand->getValueAsDef("RegClass");
1753 
1754   assert(RC && "Unknown operand type");
1755   CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1756   return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1757 }
1758 
1759 bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1760   for (unsigned i = 0, e = Types.size(); i != e; ++i)
1761     if (!TP.getInfer().isConcrete(Types[i], true))
1762       return true;
1763   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1764     if (getChild(i).ContainsUnresolvedType(TP))
1765       return true;
1766   return false;
1767 }
1768 
1769 bool TreePatternNode::hasProperTypeByHwMode() const {
1770   for (const TypeSetByHwMode &S : Types)
1771     if (!S.isSimple())
1772       return true;
1773   for (const TreePatternNodePtr &C : Children)
1774     if (C->hasProperTypeByHwMode())
1775       return true;
1776   return false;
1777 }
1778 
1779 bool TreePatternNode::hasPossibleType() const {
1780   for (const TypeSetByHwMode &S : Types)
1781     if (!S.isPossible())
1782       return false;
1783   for (const TreePatternNodePtr &C : Children)
1784     if (!C->hasPossibleType())
1785       return false;
1786   return true;
1787 }
1788 
1789 bool TreePatternNode::setDefaultMode(unsigned Mode) {
1790   for (TypeSetByHwMode &S : Types) {
1791     S.makeSimple(Mode);
1792     // Check if the selected mode had a type conflict.
1793     if (S.get(DefaultMode).empty())
1794       return false;
1795   }
1796   for (const TreePatternNodePtr &C : Children)
1797     if (!C->setDefaultMode(Mode))
1798       return false;
1799   return true;
1800 }
1801 
1802 //===----------------------------------------------------------------------===//
1803 // SDNodeInfo implementation
1804 //
1805 SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
1806   EnumName = R->getValueAsString("Opcode");
1807   SDClassName = R->getValueAsString("SDClass");
1808   Record *TypeProfile = R->getValueAsDef("TypeProfile");
1809   NumResults = TypeProfile->getValueAsInt("NumResults");
1810   NumOperands = TypeProfile->getValueAsInt("NumOperands");
1811 
1812   // Parse the properties.
1813   Properties = parseSDPatternOperatorProperties(R);
1814 
1815   // Parse the type constraints.
1816   std::vector<Record *> ConstraintList =
1817       TypeProfile->getValueAsListOfDefs("Constraints");
1818   for (Record *R : ConstraintList)
1819     TypeConstraints.emplace_back(R, CGH);
1820 }
1821 
1822 /// getKnownType - If the type constraints on this node imply a fixed type
1823 /// (e.g. all stores return void, etc), then return it as an
1824 /// MVT::SimpleValueType.  Otherwise, return EEVT::Other.
1825 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
1826   unsigned NumResults = getNumResults();
1827   assert(NumResults <= 1 &&
1828          "We only work with nodes with zero or one result so far!");
1829   assert(ResNo == 0 && "Only handles single result nodes so far");
1830 
1831   for (const SDTypeConstraint &Constraint : TypeConstraints) {
1832     // Make sure that this applies to the correct node result.
1833     if (Constraint.OperandNo >= NumResults) // FIXME: need value #
1834       continue;
1835 
1836     switch (Constraint.ConstraintType) {
1837     default:
1838       break;
1839     case SDTypeConstraint::SDTCisVT:
1840       if (Constraint.VVT.isSimple())
1841         return Constraint.VVT.getSimple().SimpleTy;
1842       break;
1843     case SDTypeConstraint::SDTCisPtrTy:
1844       return MVT::iPTR;
1845     }
1846   }
1847   return MVT::Other;
1848 }
1849 
1850 //===----------------------------------------------------------------------===//
1851 // TreePatternNode implementation
1852 //
1853 
1854 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1855   if (Operator->getName() == "set" || Operator->getName() == "implicit")
1856     return 0; // All return nothing.
1857 
1858   if (Operator->isSubClassOf("Intrinsic"))
1859     return CDP.getIntrinsic(Operator).IS.RetTys.size();
1860 
1861   if (Operator->isSubClassOf("SDNode"))
1862     return CDP.getSDNodeInfo(Operator).getNumResults();
1863 
1864   if (Operator->isSubClassOf("PatFrags")) {
1865     // If we've already parsed this pattern fragment, get it.  Otherwise, handle
1866     // the forward reference case where one pattern fragment references another
1867     // before it is processed.
1868     if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator)) {
1869       // The number of results of a fragment with alternative records is the
1870       // maximum number of results across all alternatives.
1871       unsigned NumResults = 0;
1872       for (const auto &T : PFRec->getTrees())
1873         NumResults = std::max(NumResults, T->getNumTypes());
1874       return NumResults;
1875     }
1876 
1877     ListInit *LI = Operator->getValueAsListInit("Fragments");
1878     assert(LI && "Invalid Fragment");
1879     unsigned NumResults = 0;
1880     for (Init *I : LI->getValues()) {
1881       Record *Op = nullptr;
1882       if (DagInit *Dag = dyn_cast<DagInit>(I))
1883         if (DefInit *DI = dyn_cast<DefInit>(Dag->getOperator()))
1884           Op = DI->getDef();
1885       assert(Op && "Invalid Fragment");
1886       NumResults = std::max(NumResults, GetNumNodeResults(Op, CDP));
1887     }
1888     return NumResults;
1889   }
1890 
1891   if (Operator->isSubClassOf("Instruction")) {
1892     CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
1893 
1894     unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1895 
1896     // Subtract any defaulted outputs.
1897     for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1898       Record *OperandNode = InstInfo.Operands[i].Rec;
1899 
1900       if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1901           !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1902         --NumDefsToAdd;
1903     }
1904 
1905     // Add on one implicit def if it has a resolvable type.
1906     if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=
1907         MVT::Other)
1908       ++NumDefsToAdd;
1909     return NumDefsToAdd;
1910   }
1911 
1912   if (Operator->isSubClassOf("SDNodeXForm"))
1913     return 1; // FIXME: Generalize SDNodeXForm
1914 
1915   if (Operator->isSubClassOf("ValueType"))
1916     return 1; // A type-cast of one result.
1917 
1918   if (Operator->isSubClassOf("ComplexPattern"))
1919     return 1;
1920 
1921   errs() << *Operator;
1922   PrintFatalError("Unhandled node in GetNumNodeResults");
1923 }
1924 
1925 void TreePatternNode::print(raw_ostream &OS) const {
1926   if (isLeaf())
1927     OS << *getLeafValue();
1928   else
1929     OS << '(' << getOperator()->getName();
1930 
1931   for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1932     OS << ':';
1933     getExtType(i).writeToStream(OS);
1934   }
1935 
1936   if (!isLeaf()) {
1937     if (getNumChildren() != 0) {
1938       OS << " ";
1939       ListSeparator LS;
1940       for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1941         OS << LS;
1942         getChild(i).print(OS);
1943       }
1944     }
1945     OS << ")";
1946   }
1947 
1948   for (const TreePredicateCall &Pred : PredicateCalls) {
1949     OS << "<<P:";
1950     if (Pred.Scope)
1951       OS << Pred.Scope << ":";
1952     OS << Pred.Fn.getFnName() << ">>";
1953   }
1954   if (TransformFn)
1955     OS << "<<X:" << TransformFn->getName() << ">>";
1956   if (!getName().empty())
1957     OS << ":$" << getName();
1958 
1959   for (const ScopedName &Name : NamesAsPredicateArg)
1960     OS << ":$pred:" << Name.getScope() << ":" << Name.getIdentifier();
1961 }
1962 void TreePatternNode::dump() const { print(errs()); }
1963 
1964 /// isIsomorphicTo - Return true if this node is recursively
1965 /// isomorphic to the specified node.  For this comparison, the node's
1966 /// entire state is considered. The assigned name is ignored, since
1967 /// nodes with differing names are considered isomorphic. However, if
1968 /// the assigned name is present in the dependent variable set, then
1969 /// the assigned name is considered significant and the node is
1970 /// isomorphic if the names match.
1971 bool TreePatternNode::isIsomorphicTo(const TreePatternNode &N,
1972                                      const MultipleUseVarSet &DepVars) const {
1973   if (&N == this)
1974     return true;
1975   if (N.isLeaf() != isLeaf())
1976     return false;
1977 
1978   // Check operator of non-leaves early since it can be cheaper than checking
1979   // types.
1980   if (!isLeaf())
1981     if (N.getOperator() != getOperator() ||
1982         N.getNumChildren() != getNumChildren())
1983       return false;
1984 
1985   if (getExtTypes() != N.getExtTypes() ||
1986       getPredicateCalls() != N.getPredicateCalls() ||
1987       getTransformFn() != N.getTransformFn())
1988     return false;
1989 
1990   if (isLeaf()) {
1991     if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1992       if (DefInit *NDI = dyn_cast<DefInit>(N.getLeafValue())) {
1993         return ((DI->getDef() == NDI->getDef()) &&
1994                 (!DepVars.contains(getName()) || getName() == N.getName()));
1995       }
1996     }
1997     return getLeafValue() == N.getLeafValue();
1998   }
1999 
2000   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2001     if (!getChild(i).isIsomorphicTo(N.getChild(i), DepVars))
2002       return false;
2003   return true;
2004 }
2005 
2006 /// clone - Make a copy of this tree and all of its children.
2007 ///
2008 TreePatternNodePtr TreePatternNode::clone() const {
2009   TreePatternNodePtr New;
2010   if (isLeaf()) {
2011     New = makeIntrusiveRefCnt<TreePatternNode>(getLeafValue(), getNumTypes());
2012   } else {
2013     std::vector<TreePatternNodePtr> CChildren;
2014     CChildren.reserve(Children.size());
2015     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2016       CChildren.push_back(getChild(i).clone());
2017     New = makeIntrusiveRefCnt<TreePatternNode>(
2018         getOperator(), std::move(CChildren), getNumTypes());
2019   }
2020   New->setName(getName());
2021   New->setNamesAsPredicateArg(getNamesAsPredicateArg());
2022   New->Types = Types;
2023   New->setPredicateCalls(getPredicateCalls());
2024   New->setGISelFlagsRecord(getGISelFlagsRecord());
2025   New->setTransformFn(getTransformFn());
2026   return New;
2027 }
2028 
2029 /// RemoveAllTypes - Recursively strip all the types of this tree.
2030 void TreePatternNode::RemoveAllTypes() {
2031   // Reset to unknown type.
2032   std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
2033   if (isLeaf())
2034     return;
2035   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2036     getChild(i).RemoveAllTypes();
2037 }
2038 
2039 /// SubstituteFormalArguments - Replace the formal arguments in this tree
2040 /// with actual values specified by ArgMap.
2041 void TreePatternNode::SubstituteFormalArguments(
2042     std::map<std::string, TreePatternNodePtr> &ArgMap) {
2043   if (isLeaf())
2044     return;
2045 
2046   for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
2047     TreePatternNode &Child = getChild(i);
2048     if (Child.isLeaf()) {
2049       Init *Val = Child.getLeafValue();
2050       // Note that, when substituting into an output pattern, Val might be an
2051       // UnsetInit.
2052       if (isa<UnsetInit>(Val) ||
2053           (isa<DefInit>(Val) &&
2054            cast<DefInit>(Val)->getDef()->getName() == "node")) {
2055         // We found a use of a formal argument, replace it with its value.
2056         TreePatternNodePtr NewChild = ArgMap[Child.getName()];
2057         assert(NewChild && "Couldn't find formal argument!");
2058         assert((Child.getPredicateCalls().empty() ||
2059                 NewChild->getPredicateCalls() == Child.getPredicateCalls()) &&
2060                "Non-empty child predicate clobbered!");
2061         setChild(i, std::move(NewChild));
2062       }
2063     } else {
2064       getChild(i).SubstituteFormalArguments(ArgMap);
2065     }
2066   }
2067 }
2068 
2069 /// InlinePatternFragments - If this pattern refers to any pattern
2070 /// fragments, return the set of inlined versions (this can be more than
2071 /// one if a PatFrags record has multiple alternatives).
2072 void TreePatternNode::InlinePatternFragments(
2073     TreePattern &TP, std::vector<TreePatternNodePtr> &OutAlternatives) {
2074 
2075   if (TP.hasError())
2076     return;
2077 
2078   if (isLeaf()) {
2079     OutAlternatives.push_back(this); // nothing to do.
2080     return;
2081   }
2082 
2083   Record *Op = getOperator();
2084 
2085   if (!Op->isSubClassOf("PatFrags")) {
2086     if (getNumChildren() == 0) {
2087       OutAlternatives.push_back(this);
2088       return;
2089     }
2090 
2091     // Recursively inline children nodes.
2092     std::vector<std::vector<TreePatternNodePtr>> ChildAlternatives(
2093         getNumChildren());
2094     for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
2095       TreePatternNodePtr Child = getChildShared(i);
2096       Child->InlinePatternFragments(TP, ChildAlternatives[i]);
2097       // If there are no alternatives for any child, there are no
2098       // alternatives for this expression as whole.
2099       if (ChildAlternatives[i].empty())
2100         return;
2101 
2102       assert((Child->getPredicateCalls().empty() ||
2103               llvm::all_of(ChildAlternatives[i],
2104                            [&](const TreePatternNodePtr &NewChild) {
2105                              return NewChild->getPredicateCalls() ==
2106                                     Child->getPredicateCalls();
2107                            })) &&
2108              "Non-empty child predicate clobbered!");
2109     }
2110 
2111     // The end result is an all-pairs construction of the resultant pattern.
2112     std::vector<unsigned> Idxs(ChildAlternatives.size());
2113     bool NotDone;
2114     do {
2115       // Create the variant and add it to the output list.
2116       std::vector<TreePatternNodePtr> NewChildren;
2117       NewChildren.reserve(ChildAlternatives.size());
2118       for (unsigned i = 0, e = ChildAlternatives.size(); i != e; ++i)
2119         NewChildren.push_back(ChildAlternatives[i][Idxs[i]]);
2120       TreePatternNodePtr R = makeIntrusiveRefCnt<TreePatternNode>(
2121           getOperator(), std::move(NewChildren), getNumTypes());
2122 
2123       // Copy over properties.
2124       R->setName(getName());
2125       R->setNamesAsPredicateArg(getNamesAsPredicateArg());
2126       R->setPredicateCalls(getPredicateCalls());
2127       R->setGISelFlagsRecord(getGISelFlagsRecord());
2128       R->setTransformFn(getTransformFn());
2129       for (unsigned i = 0, e = getNumTypes(); i != e; ++i)
2130         R->setType(i, getExtType(i));
2131       for (unsigned i = 0, e = getNumResults(); i != e; ++i)
2132         R->setResultIndex(i, getResultIndex(i));
2133 
2134       // Register alternative.
2135       OutAlternatives.push_back(R);
2136 
2137       // Increment indices to the next permutation by incrementing the
2138       // indices from last index backward, e.g., generate the sequence
2139       // [0, 0], [0, 1], [1, 0], [1, 1].
2140       int IdxsIdx;
2141       for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2142         if (++Idxs[IdxsIdx] == ChildAlternatives[IdxsIdx].size())
2143           Idxs[IdxsIdx] = 0;
2144         else
2145           break;
2146       }
2147       NotDone = (IdxsIdx >= 0);
2148     } while (NotDone);
2149 
2150     return;
2151   }
2152 
2153   // Otherwise, we found a reference to a fragment.  First, look up its
2154   // TreePattern record.
2155   TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
2156 
2157   // Verify that we are passing the right number of operands.
2158   if (Frag->getNumArgs() != getNumChildren()) {
2159     TP.error("'" + Op->getName() + "' fragment requires " +
2160              Twine(Frag->getNumArgs()) + " operands!");
2161     return;
2162   }
2163 
2164   TreePredicateFn PredFn(Frag);
2165   unsigned Scope = 0;
2166   if (TreePredicateFn(Frag).usesOperands())
2167     Scope = TP.getDAGPatterns().allocateScope();
2168 
2169   // Compute the map of formal to actual arguments.
2170   std::map<std::string, TreePatternNodePtr> ArgMap;
2171   for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i) {
2172     TreePatternNodePtr Child = getChildShared(i);
2173     if (Scope != 0) {
2174       Child = Child->clone();
2175       Child->addNameAsPredicateArg(ScopedName(Scope, Frag->getArgName(i)));
2176     }
2177     ArgMap[Frag->getArgName(i)] = Child;
2178   }
2179 
2180   // Loop over all fragment alternatives.
2181   for (const auto &Alternative : Frag->getTrees()) {
2182     TreePatternNodePtr FragTree = Alternative->clone();
2183 
2184     if (!PredFn.isAlwaysTrue())
2185       FragTree->addPredicateCall(PredFn, Scope);
2186 
2187     // Resolve formal arguments to their actual value.
2188     if (Frag->getNumArgs())
2189       FragTree->SubstituteFormalArguments(ArgMap);
2190 
2191     // Transfer types.  Note that the resolved alternative may have fewer
2192     // (but not more) results than the PatFrags node.
2193     FragTree->setName(getName());
2194     for (unsigned i = 0, e = FragTree->getNumTypes(); i != e; ++i)
2195       FragTree->UpdateNodeType(i, getExtType(i), TP);
2196 
2197     if (Op->isSubClassOf("GISelFlags"))
2198       FragTree->setGISelFlagsRecord(Op);
2199 
2200     // Transfer in the old predicates.
2201     for (const TreePredicateCall &Pred : getPredicateCalls())
2202       FragTree->addPredicateCall(Pred);
2203 
2204     // The fragment we inlined could have recursive inlining that is needed. See
2205     // if there are any pattern fragments in it and inline them as needed.
2206     FragTree->InlinePatternFragments(TP, OutAlternatives);
2207   }
2208 }
2209 
2210 /// getImplicitType - Check to see if the specified record has an implicit
2211 /// type which should be applied to it.  This will infer the type of register
2212 /// references from the register file information, for example.
2213 ///
2214 /// When Unnamed is set, return the type of a DAG operand with no name, such as
2215 /// the F8RC register class argument in:
2216 ///
2217 ///   (COPY_TO_REGCLASS GPR:$src, F8RC)
2218 ///
2219 /// When Unnamed is false, return the type of a named DAG operand such as the
2220 /// GPR:$src operand above.
2221 ///
2222 static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
2223                                        bool NotRegisters, bool Unnamed,
2224                                        TreePattern &TP) {
2225   CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2226 
2227   // Check to see if this is a register operand.
2228   if (R->isSubClassOf("RegisterOperand")) {
2229     assert(ResNo == 0 && "Regoperand ref only has one result!");
2230     if (NotRegisters)
2231       return TypeSetByHwMode(); // Unknown.
2232     Record *RegClass = R->getValueAsDef("RegClass");
2233     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
2234     return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
2235   }
2236 
2237   // Check to see if this is a register or a register class.
2238   if (R->isSubClassOf("RegisterClass")) {
2239     assert(ResNo == 0 && "Regclass ref only has one result!");
2240     // An unnamed register class represents itself as an i32 immediate, for
2241     // example on a COPY_TO_REGCLASS instruction.
2242     if (Unnamed)
2243       return TypeSetByHwMode(MVT::i32);
2244 
2245     // In a named operand, the register class provides the possible set of
2246     // types.
2247     if (NotRegisters)
2248       return TypeSetByHwMode(); // Unknown.
2249     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
2250     return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
2251   }
2252 
2253   if (R->isSubClassOf("PatFrags")) {
2254     assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
2255     // Pattern fragment types will be resolved when they are inlined.
2256     return TypeSetByHwMode(); // Unknown.
2257   }
2258 
2259   if (R->isSubClassOf("Register")) {
2260     assert(ResNo == 0 && "Registers only produce one result!");
2261     if (NotRegisters)
2262       return TypeSetByHwMode(); // Unknown.
2263     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
2264     return TypeSetByHwMode(T.getRegisterVTs(R));
2265   }
2266 
2267   if (R->isSubClassOf("SubRegIndex")) {
2268     assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
2269     return TypeSetByHwMode(MVT::i32);
2270   }
2271 
2272   if (R->isSubClassOf("ValueType")) {
2273     assert(ResNo == 0 && "This node only has one result!");
2274     // An unnamed VTSDNode represents itself as an MVT::Other immediate.
2275     //
2276     //   (sext_inreg GPR:$src, i16)
2277     //                         ~~~
2278     if (Unnamed)
2279       return TypeSetByHwMode(MVT::Other);
2280     // With a name, the ValueType simply provides the type of the named
2281     // variable.
2282     //
2283     //   (sext_inreg i32:$src, i16)
2284     //               ~~~~~~~~
2285     if (NotRegisters)
2286       return TypeSetByHwMode(); // Unknown.
2287     const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2288     return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
2289   }
2290 
2291   if (R->isSubClassOf("CondCode")) {
2292     assert(ResNo == 0 && "This node only has one result!");
2293     // Using a CondCodeSDNode.
2294     return TypeSetByHwMode(MVT::Other);
2295   }
2296 
2297   if (R->isSubClassOf("ComplexPattern")) {
2298     assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
2299     if (NotRegisters)
2300       return TypeSetByHwMode(); // Unknown.
2301     Record *T = CDP.getComplexPattern(R).getValueType();
2302     const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2303     return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
2304   }
2305   if (R->isSubClassOf("PointerLikeRegClass")) {
2306     assert(ResNo == 0 && "Regclass can only have one result!");
2307     TypeSetByHwMode VTS(MVT::iPTR);
2308     TP.getInfer().expandOverloads(VTS);
2309     return VTS;
2310   }
2311 
2312   if (R->getName() == "node" || R->getName() == "srcvalue" ||
2313       R->getName() == "zero_reg" || R->getName() == "immAllOnesV" ||
2314       R->getName() == "immAllZerosV" || R->getName() == "undef_tied_input") {
2315     // Placeholder.
2316     return TypeSetByHwMode(); // Unknown.
2317   }
2318 
2319   if (R->isSubClassOf("Operand")) {
2320     const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2321     Record *T = R->getValueAsDef("Type");
2322     return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
2323   }
2324 
2325   TP.error("Unknown node flavor used in pattern: " + R->getName());
2326   return TypeSetByHwMode(MVT::Other);
2327 }
2328 
2329 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
2330 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
2331 const CodeGenIntrinsic *
2332 TreePatternNode::getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
2333   if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
2334       getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
2335       getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
2336     return nullptr;
2337 
2338   unsigned IID = cast<IntInit>(getChild(0).getLeafValue())->getValue();
2339   return &CDP.getIntrinsicInfo(IID);
2340 }
2341 
2342 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
2343 /// return the ComplexPattern information, otherwise return null.
2344 const ComplexPattern *
2345 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
2346   Record *Rec;
2347   if (isLeaf()) {
2348     DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2349     if (!DI)
2350       return nullptr;
2351     Rec = DI->getDef();
2352   } else
2353     Rec = getOperator();
2354 
2355   if (!Rec->isSubClassOf("ComplexPattern"))
2356     return nullptr;
2357   return &CGP.getComplexPattern(Rec);
2358 }
2359 
2360 unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
2361   // A ComplexPattern specifically declares how many results it fills in.
2362   if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2363     return CP->getNumOperands();
2364 
2365   // If MIOperandInfo is specified, that gives the count.
2366   if (isLeaf()) {
2367     DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2368     if (DI && DI->getDef()->isSubClassOf("Operand")) {
2369       DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
2370       if (MIOps->getNumArgs())
2371         return MIOps->getNumArgs();
2372     }
2373   }
2374 
2375   // Otherwise there is just one result.
2376   return 1;
2377 }
2378 
2379 /// NodeHasProperty - Return true if this node has the specified property.
2380 bool TreePatternNode::NodeHasProperty(SDNP Property,
2381                                       const CodeGenDAGPatterns &CGP) const {
2382   if (isLeaf()) {
2383     if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2384       return CP->hasProperty(Property);
2385 
2386     return false;
2387   }
2388 
2389   if (Property != SDNPHasChain) {
2390     // The chain proprety is already present on the different intrinsic node
2391     // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
2392     // on the intrinsic. Anything else is specific to the individual intrinsic.
2393     if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CGP))
2394       return Int->hasProperty(Property);
2395   }
2396 
2397   if (!getOperator()->isSubClassOf("SDPatternOperator"))
2398     return false;
2399 
2400   return CGP.getSDNodeInfo(getOperator()).hasProperty(Property);
2401 }
2402 
2403 /// TreeHasProperty - Return true if any node in this tree has the specified
2404 /// property.
2405 bool TreePatternNode::TreeHasProperty(SDNP Property,
2406                                       const CodeGenDAGPatterns &CGP) const {
2407   if (NodeHasProperty(Property, CGP))
2408     return true;
2409   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2410     if (getChild(i).TreeHasProperty(Property, CGP))
2411       return true;
2412   return false;
2413 }
2414 
2415 /// isCommutativeIntrinsic - Return true if the node corresponds to a
2416 /// commutative intrinsic.
2417 bool TreePatternNode::isCommutativeIntrinsic(
2418     const CodeGenDAGPatterns &CDP) const {
2419   if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
2420     return Int->isCommutative;
2421   return false;
2422 }
2423 
2424 static bool isOperandClass(const TreePatternNode &N, StringRef Class) {
2425   if (!N.isLeaf())
2426     return N.getOperator()->isSubClassOf(Class);
2427 
2428   DefInit *DI = dyn_cast<DefInit>(N.getLeafValue());
2429   if (DI && DI->getDef()->isSubClassOf(Class))
2430     return true;
2431 
2432   return false;
2433 }
2434 
2435 static void emitTooManyOperandsError(TreePattern &TP, StringRef InstName,
2436                                      unsigned Expected, unsigned Actual) {
2437   TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
2438            " operands but expected only " + Twine(Expected) + "!");
2439 }
2440 
2441 static void emitTooFewOperandsError(TreePattern &TP, StringRef InstName,
2442                                     unsigned Actual) {
2443   TP.error("Instruction '" + InstName + "' expects more than the provided " +
2444            Twine(Actual) + " operands!");
2445 }
2446 
2447 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
2448 /// this node and its children in the tree.  This returns true if it makes a
2449 /// change, false otherwise.  If a type contradiction is found, flag an error.
2450 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
2451   if (TP.hasError())
2452     return false;
2453 
2454   CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2455   if (isLeaf()) {
2456     if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
2457       // If it's a regclass or something else known, include the type.
2458       bool MadeChange = false;
2459       for (unsigned i = 0, e = Types.size(); i != e; ++i)
2460         MadeChange |= UpdateNodeType(
2461             i, getImplicitType(DI->getDef(), i, NotRegisters, !hasName(), TP),
2462             TP);
2463       return MadeChange;
2464     }
2465 
2466     if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
2467       assert(Types.size() == 1 && "Invalid IntInit");
2468 
2469       // Int inits are always integers. :)
2470       bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
2471 
2472       if (!TP.getInfer().isConcrete(Types[0], false))
2473         return MadeChange;
2474 
2475       ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
2476       for (auto &P : VVT) {
2477         MVT::SimpleValueType VT = P.second.SimpleTy;
2478         if (VT == MVT::iPTR || VT == MVT::iPTRAny)
2479           continue;
2480         unsigned Size = MVT(VT).getFixedSizeInBits();
2481         // Make sure that the value is representable for this type.
2482         if (Size >= 32)
2483           continue;
2484         // Check that the value doesn't use more bits than we have. It must
2485         // either be a sign- or zero-extended equivalent of the original.
2486         int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
2487         if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
2488             SignBitAndAbove == 1)
2489           continue;
2490 
2491         TP.error("Integer value '" + Twine(II->getValue()) +
2492                  "' is out of range for type '" + getEnumName(VT) + "'!");
2493         break;
2494       }
2495       return MadeChange;
2496     }
2497 
2498     return false;
2499   }
2500 
2501   if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
2502     bool MadeChange = false;
2503 
2504     // Apply the result type to the node.
2505     unsigned NumRetVTs = Int->IS.RetTys.size();
2506     unsigned NumParamVTs = Int->IS.ParamTys.size();
2507 
2508     for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
2509       MadeChange |= UpdateNodeType(
2510           i, getValueType(Int->IS.RetTys[i]->getValueAsDef("VT")), TP);
2511 
2512     if (getNumChildren() != NumParamVTs + 1) {
2513       TP.error("Intrinsic '" + Int->Name + "' expects " + Twine(NumParamVTs) +
2514                " operands, not " + Twine(getNumChildren() - 1) + " operands!");
2515       return false;
2516     }
2517 
2518     // Apply type info to the intrinsic ID.
2519     MadeChange |= getChild(0).UpdateNodeType(0, MVT::iPTR, TP);
2520 
2521     for (unsigned i = 0, e = getNumChildren() - 1; i != e; ++i) {
2522       MadeChange |= getChild(i + 1).ApplyTypeConstraints(TP, NotRegisters);
2523 
2524       MVT::SimpleValueType OpVT =
2525           getValueType(Int->IS.ParamTys[i]->getValueAsDef("VT"));
2526       assert(getChild(i + 1).getNumTypes() == 1 && "Unhandled case");
2527       MadeChange |= getChild(i + 1).UpdateNodeType(0, OpVT, TP);
2528     }
2529     return MadeChange;
2530   }
2531 
2532   if (getOperator()->isSubClassOf("SDNode")) {
2533     const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
2534 
2535     // Check that the number of operands is sane.  Negative operands -> varargs.
2536     if (NI.getNumOperands() >= 0 &&
2537         getNumChildren() != (unsigned)NI.getNumOperands()) {
2538       TP.error(getOperator()->getName() + " node requires exactly " +
2539                Twine(NI.getNumOperands()) + " operands!");
2540       return false;
2541     }
2542 
2543     bool MadeChange = false;
2544     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2545       MadeChange |= getChild(i).ApplyTypeConstraints(TP, NotRegisters);
2546     MadeChange |= NI.ApplyTypeConstraints(*this, TP);
2547     return MadeChange;
2548   }
2549 
2550   if (getOperator()->isSubClassOf("Instruction")) {
2551     const DAGInstruction &Inst = CDP.getInstruction(getOperator());
2552     CodeGenInstruction &InstInfo =
2553         CDP.getTargetInfo().getInstruction(getOperator());
2554 
2555     bool MadeChange = false;
2556 
2557     // Apply the result types to the node, these come from the things in the
2558     // (outs) list of the instruction.
2559     unsigned NumResultsToAdd =
2560         std::min(InstInfo.Operands.NumDefs, Inst.getNumResults());
2561     for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
2562       MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
2563 
2564     // If the instruction has implicit defs, we apply the first one as a result.
2565     // FIXME: This sucks, it should apply all implicit defs.
2566     if (!InstInfo.ImplicitDefs.empty()) {
2567       unsigned ResNo = NumResultsToAdd;
2568 
2569       // FIXME: Generalize to multiple possible types and multiple possible
2570       // ImplicitDefs.
2571       MVT::SimpleValueType VT =
2572           InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
2573 
2574       if (VT != MVT::Other)
2575         MadeChange |= UpdateNodeType(ResNo, VT, TP);
2576     }
2577 
2578     // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2579     // be the same.
2580     if (getOperator()->getName() == "INSERT_SUBREG") {
2581       assert(getChild(0).getNumTypes() == 1 && "FIXME: Unhandled");
2582       MadeChange |= UpdateNodeType(0, getChild(0).getExtType(0), TP);
2583       MadeChange |= getChild(0).UpdateNodeType(0, getExtType(0), TP);
2584     } else if (getOperator()->getName() == "REG_SEQUENCE") {
2585       // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2586       // variadic.
2587 
2588       unsigned NChild = getNumChildren();
2589       if (NChild < 3) {
2590         TP.error("REG_SEQUENCE requires at least 3 operands!");
2591         return false;
2592       }
2593 
2594       if (NChild % 2 == 0) {
2595         TP.error("REG_SEQUENCE requires an odd number of operands!");
2596         return false;
2597       }
2598 
2599       if (!isOperandClass(getChild(0), "RegisterClass")) {
2600         TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2601         return false;
2602       }
2603 
2604       for (unsigned I = 1; I < NChild; I += 2) {
2605         TreePatternNode &SubIdxChild = getChild(I + 1);
2606         if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
2607           TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
2608                    Twine(I + 1) + "!");
2609           return false;
2610         }
2611       }
2612     }
2613 
2614     unsigned NumResults = Inst.getNumResults();
2615     unsigned NumFixedOperands = InstInfo.Operands.size();
2616 
2617     // If one or more operands with a default value appear at the end of the
2618     // formal operand list for an instruction, we allow them to be overridden
2619     // by optional operands provided in the pattern.
2620     //
2621     // But if an operand B without a default appears at any point after an
2622     // operand A with a default, then we don't allow A to be overridden,
2623     // because there would be no way to specify whether the next operand in
2624     // the pattern was intended to override A or skip it.
2625     unsigned NonOverridableOperands = NumFixedOperands;
2626     while (NonOverridableOperands > NumResults &&
2627            CDP.operandHasDefault(
2628                InstInfo.Operands[NonOverridableOperands - 1].Rec))
2629       --NonOverridableOperands;
2630 
2631     unsigned ChildNo = 0;
2632     assert(NumResults <= NumFixedOperands);
2633     for (unsigned i = NumResults, e = NumFixedOperands; i != e; ++i) {
2634       Record *OperandNode = InstInfo.Operands[i].Rec;
2635 
2636       // If the operand has a default value, do we use it? We must use the
2637       // default if we've run out of children of the pattern DAG to consume,
2638       // or if the operand is followed by a non-defaulted one.
2639       if (CDP.operandHasDefault(OperandNode) &&
2640           (i < NonOverridableOperands || ChildNo >= getNumChildren()))
2641         continue;
2642 
2643       // If we have run out of child nodes and there _isn't_ a default
2644       // value we can use for the next operand, give an error.
2645       if (ChildNo >= getNumChildren()) {
2646         emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
2647         return false;
2648       }
2649 
2650       TreePatternNode *Child = &getChild(ChildNo++);
2651       unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
2652 
2653       // If the operand has sub-operands, they may be provided by distinct
2654       // child patterns, so attempt to match each sub-operand separately.
2655       if (OperandNode->isSubClassOf("Operand")) {
2656         DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
2657         if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2658           // But don't do that if the whole operand is being provided by
2659           // a single ComplexPattern-related Operand.
2660 
2661           if (Child->getNumMIResults(CDP) < NumArgs) {
2662             // Match first sub-operand against the child we already have.
2663             Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2664             MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2665 
2666             // And the remaining sub-operands against subsequent children.
2667             for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2668               if (ChildNo >= getNumChildren()) {
2669                 emitTooFewOperandsError(TP, getOperator()->getName(),
2670                                         getNumChildren());
2671                 return false;
2672               }
2673               Child = &getChild(ChildNo++);
2674 
2675               SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
2676               MadeChange |=
2677                   Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2678             }
2679             continue;
2680           }
2681         }
2682       }
2683 
2684       // If we didn't match by pieces above, attempt to match the whole
2685       // operand now.
2686       MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
2687     }
2688 
2689     if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
2690       emitTooManyOperandsError(TP, getOperator()->getName(), ChildNo,
2691                                getNumChildren());
2692       return false;
2693     }
2694 
2695     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2696       MadeChange |= getChild(i).ApplyTypeConstraints(TP, NotRegisters);
2697     return MadeChange;
2698   }
2699 
2700   if (getOperator()->isSubClassOf("ComplexPattern")) {
2701     bool MadeChange = false;
2702 
2703     if (!NotRegisters) {
2704       assert(Types.size() == 1 && "ComplexPatterns only produce one result!");
2705       Record *T = CDP.getComplexPattern(getOperator()).getValueType();
2706       const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2707       const ValueTypeByHwMode VVT = getValueTypeByHwMode(T, CGH);
2708       // TODO: AArch64 and AMDGPU use ComplexPattern<untyped, ...> and then
2709       // exclusively use those as non-leaf nodes with explicit type casts, so
2710       // for backwards compatibility we do no inference in that case. This is
2711       // not supported when the ComplexPattern is used as a leaf value,
2712       // however; this inconsistency should be resolved, either by adding this
2713       // case there or by altering the backends to not do this (e.g. using Any
2714       // instead may work).
2715       if (!VVT.isSimple() || VVT.getSimple() != MVT::Untyped)
2716         MadeChange |= UpdateNodeType(0, VVT, TP);
2717     }
2718 
2719     for (unsigned i = 0; i < getNumChildren(); ++i)
2720       MadeChange |= getChild(i).ApplyTypeConstraints(TP, NotRegisters);
2721 
2722     return MadeChange;
2723   }
2724 
2725   assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
2726 
2727   // Node transforms always take one operand.
2728   if (getNumChildren() != 1) {
2729     TP.error("Node transform '" + getOperator()->getName() +
2730              "' requires one operand!");
2731     return false;
2732   }
2733 
2734   bool MadeChange = getChild(0).ApplyTypeConstraints(TP, NotRegisters);
2735   return MadeChange;
2736 }
2737 
2738 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2739 /// RHS of a commutative operation, not the on LHS.
2740 static bool OnlyOnRHSOfCommutative(TreePatternNode &N) {
2741   if (!N.isLeaf() && N.getOperator()->getName() == "imm")
2742     return true;
2743   if (N.isLeaf() && isa<IntInit>(N.getLeafValue()))
2744     return true;
2745   if (isImmAllOnesAllZerosMatch(N))
2746     return true;
2747   return false;
2748 }
2749 
2750 /// canPatternMatch - If it is impossible for this pattern to match on this
2751 /// target, fill in Reason and return false.  Otherwise, return true.  This is
2752 /// used as a sanity check for .td files (to prevent people from writing stuff
2753 /// that can never possibly work), and to prevent the pattern permuter from
2754 /// generating stuff that is useless.
2755 bool TreePatternNode::canPatternMatch(std::string &Reason,
2756                                       const CodeGenDAGPatterns &CDP) {
2757   if (isLeaf())
2758     return true;
2759 
2760   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2761     if (!getChild(i).canPatternMatch(Reason, CDP))
2762       return false;
2763 
2764   // If this is an intrinsic, handle cases that would make it not match.  For
2765   // example, if an operand is required to be an immediate.
2766   if (getOperator()->isSubClassOf("Intrinsic")) {
2767     // TODO:
2768     return true;
2769   }
2770 
2771   if (getOperator()->isSubClassOf("ComplexPattern"))
2772     return true;
2773 
2774   // If this node is a commutative operator, check that the LHS isn't an
2775   // immediate.
2776   const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
2777   bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2778   if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2779     // Scan all of the operands of the node and make sure that only the last one
2780     // is a constant node, unless the RHS also is.
2781     if (!OnlyOnRHSOfCommutative(getChild(getNumChildren() - 1))) {
2782       unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
2783       for (unsigned i = Skip, e = getNumChildren() - 1; i != e; ++i)
2784         if (OnlyOnRHSOfCommutative(getChild(i))) {
2785           Reason =
2786               "Immediate value must be on the RHS of commutative operators!";
2787           return false;
2788         }
2789     }
2790   }
2791 
2792   return true;
2793 }
2794 
2795 //===----------------------------------------------------------------------===//
2796 // TreePattern implementation
2797 //
2798 
2799 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
2800                          CodeGenDAGPatterns &cdp)
2801     : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2802       Infer(*this) {
2803   for (Init *I : RawPat->getValues())
2804     Trees.push_back(ParseTreePattern(I, ""));
2805 }
2806 
2807 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
2808                          CodeGenDAGPatterns &cdp)
2809     : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2810       Infer(*this) {
2811   Trees.push_back(ParseTreePattern(Pat, ""));
2812 }
2813 
2814 TreePattern::TreePattern(Record *TheRec, TreePatternNodePtr Pat, bool isInput,
2815                          CodeGenDAGPatterns &cdp)
2816     : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2817       Infer(*this) {
2818   Trees.push_back(Pat);
2819 }
2820 
2821 void TreePattern::error(const Twine &Msg) {
2822   if (HasError)
2823     return;
2824   dump();
2825   PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2826   HasError = true;
2827 }
2828 
2829 void TreePattern::ComputeNamedNodes() {
2830   for (TreePatternNodePtr &Tree : Trees)
2831     ComputeNamedNodes(*Tree);
2832 }
2833 
2834 void TreePattern::ComputeNamedNodes(TreePatternNode &N) {
2835   if (!N.getName().empty())
2836     NamedNodes[N.getName()].push_back(&N);
2837 
2838   for (unsigned i = 0, e = N.getNumChildren(); i != e; ++i)
2839     ComputeNamedNodes(N.getChild(i));
2840 }
2841 
2842 TreePatternNodePtr TreePattern::ParseTreePattern(Init *TheInit,
2843                                                  StringRef OpName) {
2844   RecordKeeper &RK = TheInit->getRecordKeeper();
2845   if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
2846     Record *R = DI->getDef();
2847 
2848     // Direct reference to a leaf DagNode or PatFrag?  Turn it into a
2849     // TreePatternNode of its own.  For example:
2850     ///   (foo GPR, imm) -> (foo GPR, (imm))
2851     if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrags"))
2852       return ParseTreePattern(
2853           DagInit::get(DI, nullptr,
2854                        std::vector<std::pair<Init *, StringInit *>>()),
2855           OpName);
2856 
2857     // Input argument?
2858     TreePatternNodePtr Res = makeIntrusiveRefCnt<TreePatternNode>(DI, 1);
2859     if (R->getName() == "node" && !OpName.empty()) {
2860       if (OpName.empty())
2861         error("'node' argument requires a name to match with operand list");
2862       Args.push_back(std::string(OpName));
2863     }
2864 
2865     Res->setName(OpName);
2866     return Res;
2867   }
2868 
2869   // ?:$name or just $name.
2870   if (isa<UnsetInit>(TheInit)) {
2871     if (OpName.empty())
2872       error("'?' argument requires a name to match with operand list");
2873     TreePatternNodePtr Res = makeIntrusiveRefCnt<TreePatternNode>(TheInit, 1);
2874     Args.push_back(std::string(OpName));
2875     Res->setName(OpName);
2876     return Res;
2877   }
2878 
2879   if (isa<IntInit>(TheInit) || isa<BitInit>(TheInit)) {
2880     if (!OpName.empty())
2881       error("Constant int or bit argument should not have a name!");
2882     if (isa<BitInit>(TheInit))
2883       TheInit = TheInit->convertInitializerTo(IntRecTy::get(RK));
2884     return makeIntrusiveRefCnt<TreePatternNode>(TheInit, 1);
2885   }
2886 
2887   if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
2888     // Turn this into an IntInit.
2889     Init *II = BI->convertInitializerTo(IntRecTy::get(RK));
2890     if (!II || !isa<IntInit>(II))
2891       error("Bits value must be constants!");
2892     return II ? ParseTreePattern(II, OpName) : nullptr;
2893   }
2894 
2895   DagInit *Dag = dyn_cast<DagInit>(TheInit);
2896   if (!Dag) {
2897     TheInit->print(errs());
2898     error("Pattern has unexpected init kind!");
2899     return nullptr;
2900   }
2901   DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
2902   if (!OpDef) {
2903     error("Pattern has unexpected operator type!");
2904     return nullptr;
2905   }
2906   Record *Operator = OpDef->getDef();
2907 
2908   if (Operator->isSubClassOf("ValueType")) {
2909     // If the operator is a ValueType, then this must be "type cast" of a leaf
2910     // node.
2911     if (Dag->getNumArgs() != 1)
2912       error("Type cast only takes one operand!");
2913 
2914     TreePatternNodePtr New =
2915         ParseTreePattern(Dag->getArg(0), Dag->getArgNameStr(0));
2916 
2917     // Apply the type cast.
2918     if (New->getNumTypes() != 1)
2919       error("Type cast can only have one type!");
2920     const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
2921     New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
2922 
2923     if (!OpName.empty())
2924       error("ValueType cast should not have a name!");
2925     return New;
2926   }
2927 
2928   // Verify that this is something that makes sense for an operator.
2929   if (!Operator->isSubClassOf("PatFrags") &&
2930       !Operator->isSubClassOf("SDNode") &&
2931       !Operator->isSubClassOf("Instruction") &&
2932       !Operator->isSubClassOf("SDNodeXForm") &&
2933       !Operator->isSubClassOf("Intrinsic") &&
2934       !Operator->isSubClassOf("ComplexPattern") &&
2935       Operator->getName() != "set" && Operator->getName() != "implicit")
2936     error("Unrecognized node '" + Operator->getName() + "'!");
2937 
2938   //  Check to see if this is something that is illegal in an input pattern.
2939   if (isInputPattern) {
2940     if (Operator->isSubClassOf("Instruction") ||
2941         Operator->isSubClassOf("SDNodeXForm"))
2942       error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2943   } else {
2944     if (Operator->isSubClassOf("Intrinsic"))
2945       error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2946 
2947     if (Operator->isSubClassOf("SDNode") && Operator->getName() != "imm" &&
2948         Operator->getName() != "timm" && Operator->getName() != "fpimm" &&
2949         Operator->getName() != "tglobaltlsaddr" &&
2950         Operator->getName() != "tconstpool" &&
2951         Operator->getName() != "tjumptable" &&
2952         Operator->getName() != "tframeindex" &&
2953         Operator->getName() != "texternalsym" &&
2954         Operator->getName() != "tblockaddress" &&
2955         Operator->getName() != "tglobaladdr" && Operator->getName() != "bb" &&
2956         Operator->getName() != "vt" && Operator->getName() != "mcsym")
2957       error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2958   }
2959 
2960   std::vector<TreePatternNodePtr> Children;
2961 
2962   // Parse all the operands.
2963   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
2964     Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
2965 
2966   // Get the actual number of results before Operator is converted to an
2967   // intrinsic node (which is hard-coded to have either zero or one result).
2968   unsigned NumResults = GetNumNodeResults(Operator, CDP);
2969 
2970   // If the operator is an intrinsic, then this is just syntactic sugar for
2971   // (intrinsic_* <number>, ..children..).  Pick the right intrinsic node, and
2972   // convert the intrinsic name to a number.
2973   if (Operator->isSubClassOf("Intrinsic")) {
2974     const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2975     unsigned IID = getDAGPatterns().getIntrinsicID(Operator) + 1;
2976 
2977     // If this intrinsic returns void, it must have side-effects and thus a
2978     // chain.
2979     if (Int.IS.RetTys.empty())
2980       Operator = getDAGPatterns().get_intrinsic_void_sdnode();
2981     else if (!Int.ME.doesNotAccessMemory() || Int.hasSideEffects)
2982       // Has side-effects, requires chain.
2983       Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
2984     else // Otherwise, no chain.
2985       Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
2986 
2987     Children.insert(Children.begin(), makeIntrusiveRefCnt<TreePatternNode>(
2988                                           IntInit::get(RK, IID), 1));
2989   }
2990 
2991   if (Operator->isSubClassOf("ComplexPattern")) {
2992     for (unsigned i = 0; i < Children.size(); ++i) {
2993       TreePatternNodePtr Child = Children[i];
2994 
2995       if (Child->getName().empty())
2996         error("All arguments to a ComplexPattern must be named");
2997 
2998       // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2999       // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
3000       // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
3001       auto OperandId = std::pair(Operator, i);
3002       auto PrevOp = ComplexPatternOperands.find(Child->getName());
3003       if (PrevOp != ComplexPatternOperands.end()) {
3004         if (PrevOp->getValue() != OperandId)
3005           error("All ComplexPattern operands must appear consistently: "
3006                 "in the same order in just one ComplexPattern instance.");
3007       } else
3008         ComplexPatternOperands[Child->getName()] = OperandId;
3009     }
3010   }
3011 
3012   TreePatternNodePtr Result = makeIntrusiveRefCnt<TreePatternNode>(
3013       Operator, std::move(Children), NumResults);
3014   Result->setName(OpName);
3015 
3016   if (Dag->getName()) {
3017     assert(Result->getName().empty());
3018     Result->setName(Dag->getNameStr());
3019   }
3020   return Result;
3021 }
3022 
3023 /// SimplifyTree - See if we can simplify this tree to eliminate something that
3024 /// will never match in favor of something obvious that will.  This is here
3025 /// strictly as a convenience to target authors because it allows them to write
3026 /// more type generic things and have useless type casts fold away.
3027 ///
3028 /// This returns true if any change is made.
3029 static bool SimplifyTree(TreePatternNodePtr &N) {
3030   if (N->isLeaf())
3031     return false;
3032 
3033   // If we have a bitconvert with a resolved type and if the source and
3034   // destination types are the same, then the bitconvert is useless, remove it.
3035   //
3036   // We make an exception if the types are completely empty. This can come up
3037   // when the pattern being simplified is in the Fragments list of a PatFrags,
3038   // so that the operand is just an untyped "node". In that situation we leave
3039   // bitconverts unsimplified, and simplify them later once the fragment is
3040   // expanded into its true context.
3041   if (N->getOperator()->getName() == "bitconvert" &&
3042       N->getExtType(0).isValueTypeByHwMode(false) &&
3043       !N->getExtType(0).empty() &&
3044       N->getExtType(0) == N->getChild(0).getExtType(0) &&
3045       N->getName().empty()) {
3046     N = N->getChildShared(0);
3047     SimplifyTree(N);
3048     return true;
3049   }
3050 
3051   // Walk all children.
3052   bool MadeChange = false;
3053   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3054     MadeChange |= SimplifyTree(N->getChildSharedPtr(i));
3055 
3056   return MadeChange;
3057 }
3058 
3059 /// InferAllTypes - Infer/propagate as many types throughout the expression
3060 /// patterns as possible.  Return true if all types are inferred, false
3061 /// otherwise.  Flags an error if a type contradiction is found.
3062 bool TreePattern::InferAllTypes(
3063     const StringMap<SmallVector<TreePatternNode *, 1>> *InNamedTypes) {
3064   if (NamedNodes.empty())
3065     ComputeNamedNodes();
3066 
3067   bool MadeChange = true;
3068   while (MadeChange) {
3069     MadeChange = false;
3070     for (TreePatternNodePtr &Tree : Trees) {
3071       MadeChange |= Tree->ApplyTypeConstraints(*this, false);
3072       MadeChange |= SimplifyTree(Tree);
3073     }
3074 
3075     // If there are constraints on our named nodes, apply them.
3076     for (auto &Entry : NamedNodes) {
3077       SmallVectorImpl<TreePatternNode *> &Nodes = Entry.second;
3078 
3079       // If we have input named node types, propagate their types to the named
3080       // values here.
3081       if (InNamedTypes) {
3082         if (!InNamedTypes->count(Entry.getKey())) {
3083           error("Node '" + std::string(Entry.getKey()) +
3084                 "' in output pattern but not input pattern");
3085           return true;
3086         }
3087 
3088         const SmallVectorImpl<TreePatternNode *> &InNodes =
3089             InNamedTypes->find(Entry.getKey())->second;
3090 
3091         // The input types should be fully resolved by now.
3092         for (TreePatternNode *Node : Nodes) {
3093           // If this node is a register class, and it is the root of the pattern
3094           // then we're mapping something onto an input register.  We allow
3095           // changing the type of the input register in this case.  This allows
3096           // us to match things like:
3097           //  def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
3098           if (Node == Trees[0].get() && Node->isLeaf()) {
3099             DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
3100             if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
3101                        DI->getDef()->isSubClassOf("RegisterOperand")))
3102               continue;
3103           }
3104 
3105           assert(Node->getNumTypes() == 1 && InNodes[0]->getNumTypes() == 1 &&
3106                  "FIXME: cannot name multiple result nodes yet");
3107           MadeChange |=
3108               Node->UpdateNodeType(0, InNodes[0]->getExtType(0), *this);
3109         }
3110       }
3111 
3112       // If there are multiple nodes with the same name, they must all have the
3113       // same type.
3114       if (Entry.second.size() > 1) {
3115         for (unsigned i = 0, e = Nodes.size() - 1; i != e; ++i) {
3116           TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i + 1];
3117           assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
3118                  "FIXME: cannot name multiple result nodes yet");
3119 
3120           MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
3121           MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
3122         }
3123       }
3124     }
3125   }
3126 
3127   bool HasUnresolvedTypes = false;
3128   for (const TreePatternNodePtr &Tree : Trees)
3129     HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
3130   return !HasUnresolvedTypes;
3131 }
3132 
3133 void TreePattern::print(raw_ostream &OS) const {
3134   OS << getRecord()->getName();
3135   if (!Args.empty()) {
3136     OS << "(";
3137     ListSeparator LS;
3138     for (const std::string &Arg : Args)
3139       OS << LS << Arg;
3140     OS << ")";
3141   }
3142   OS << ": ";
3143 
3144   if (Trees.size() > 1)
3145     OS << "[\n";
3146   for (const TreePatternNodePtr &Tree : Trees) {
3147     OS << "\t";
3148     Tree->print(OS);
3149     OS << "\n";
3150   }
3151 
3152   if (Trees.size() > 1)
3153     OS << "]\n";
3154 }
3155 
3156 void TreePattern::dump() const { print(errs()); }
3157 
3158 //===----------------------------------------------------------------------===//
3159 // CodeGenDAGPatterns implementation
3160 //
3161 
3162 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R,
3163                                        PatternRewriterFn PatternRewriter)
3164     : Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()),
3165       PatternRewriter(PatternRewriter) {
3166 
3167   Intrinsics = CodeGenIntrinsicTable(Records);
3168   ParseNodeInfo();
3169   ParseNodeTransforms();
3170   ParseComplexPatterns();
3171   ParsePatternFragments();
3172   ParseDefaultOperands();
3173   ParseInstructions();
3174   ParsePatternFragments(/*OutFrags*/ true);
3175   ParsePatterns();
3176 
3177   // Generate variants.  For example, commutative patterns can match
3178   // multiple ways.  Add them to PatternsToMatch as well.
3179   GenerateVariants();
3180 
3181   // Break patterns with parameterized types into a series of patterns,
3182   // where each one has a fixed type and is predicated on the conditions
3183   // of the associated HW mode.
3184   ExpandHwModeBasedTypes();
3185 
3186   // Infer instruction flags.  For example, we can detect loads,
3187   // stores, and side effects in many cases by examining an
3188   // instruction's pattern.
3189   InferInstructionFlags();
3190 
3191   // Verify that instruction flags match the patterns.
3192   VerifyInstructionFlags();
3193 }
3194 
3195 Record *CodeGenDAGPatterns::getSDNodeNamed(StringRef Name) const {
3196   Record *N = Records.getDef(Name);
3197   if (!N || !N->isSubClassOf("SDNode"))
3198     PrintFatalError("Error getting SDNode '" + Name + "'!");
3199 
3200   return N;
3201 }
3202 
3203 // Parse all of the SDNode definitions for the target, populating SDNodes.
3204 void CodeGenDAGPatterns::ParseNodeInfo() {
3205   std::vector<Record *> Nodes = Records.getAllDerivedDefinitions("SDNode");
3206   const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
3207 
3208   while (!Nodes.empty()) {
3209     Record *R = Nodes.back();
3210     SDNodes.insert(std::pair(R, SDNodeInfo(R, CGH)));
3211     Nodes.pop_back();
3212   }
3213 
3214   // Get the builtin intrinsic nodes.
3215   intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
3216   intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
3217   intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
3218 }
3219 
3220 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
3221 /// map, and emit them to the file as functions.
3222 void CodeGenDAGPatterns::ParseNodeTransforms() {
3223   std::vector<Record *> Xforms =
3224       Records.getAllDerivedDefinitions("SDNodeXForm");
3225   while (!Xforms.empty()) {
3226     Record *XFormNode = Xforms.back();
3227     Record *SDNode = XFormNode->getValueAsDef("Opcode");
3228     StringRef Code = XFormNode->getValueAsString("XFormFunction");
3229     SDNodeXForms.insert(
3230         std::pair(XFormNode, NodeXForm(SDNode, std::string(Code))));
3231 
3232     Xforms.pop_back();
3233   }
3234 }
3235 
3236 void CodeGenDAGPatterns::ParseComplexPatterns() {
3237   std::vector<Record *> AMs =
3238       Records.getAllDerivedDefinitions("ComplexPattern");
3239   while (!AMs.empty()) {
3240     ComplexPatterns.insert(std::pair(AMs.back(), AMs.back()));
3241     AMs.pop_back();
3242   }
3243 }
3244 
3245 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
3246 /// file, building up the PatternFragments map.  After we've collected them all,
3247 /// inline fragments together as necessary, so that there are no references left
3248 /// inside a pattern fragment to a pattern fragment.
3249 ///
3250 void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
3251   std::vector<Record *> Fragments =
3252       Records.getAllDerivedDefinitions("PatFrags");
3253 
3254   // First step, parse all of the fragments.
3255   for (Record *Frag : Fragments) {
3256     if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
3257       continue;
3258 
3259     ListInit *LI = Frag->getValueAsListInit("Fragments");
3260     TreePattern *P = (PatternFragments[Frag] = std::make_unique<TreePattern>(
3261                           Frag, LI, !Frag->isSubClassOf("OutPatFrag"), *this))
3262                          .get();
3263 
3264     // Validate the argument list, converting it to set, to discard duplicates.
3265     std::vector<std::string> &Args = P->getArgList();
3266     // Copy the args so we can take StringRefs to them.
3267     auto ArgsCopy = Args;
3268     SmallDenseSet<StringRef, 4> OperandsSet;
3269     OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
3270 
3271     if (OperandsSet.count(""))
3272       P->error("Cannot have unnamed 'node' values in pattern fragment!");
3273 
3274     // Parse the operands list.
3275     DagInit *OpsList = Frag->getValueAsDag("Operands");
3276     DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
3277     // Special cases: ops == outs == ins. Different names are used to
3278     // improve readability.
3279     if (!OpsOp || (OpsOp->getDef()->getName() != "ops" &&
3280                    OpsOp->getDef()->getName() != "outs" &&
3281                    OpsOp->getDef()->getName() != "ins"))
3282       P->error("Operands list should start with '(ops ... '!");
3283 
3284     // Copy over the arguments.
3285     Args.clear();
3286     for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
3287       if (!isa<DefInit>(OpsList->getArg(j)) ||
3288           cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
3289         P->error("Operands list should all be 'node' values.");
3290       if (!OpsList->getArgName(j))
3291         P->error("Operands list should have names for each operand!");
3292       StringRef ArgNameStr = OpsList->getArgNameStr(j);
3293       if (!OperandsSet.count(ArgNameStr))
3294         P->error("'" + ArgNameStr +
3295                  "' does not occur in pattern or was multiply specified!");
3296       OperandsSet.erase(ArgNameStr);
3297       Args.push_back(std::string(ArgNameStr));
3298     }
3299 
3300     if (!OperandsSet.empty())
3301       P->error("Operands list does not contain an entry for operand '" +
3302                *OperandsSet.begin() + "'!");
3303 
3304     // If there is a node transformation corresponding to this, keep track of
3305     // it.
3306     Record *Transform = Frag->getValueAsDef("OperandTransform");
3307     if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
3308       for (const auto &T : P->getTrees())
3309         T->setTransformFn(Transform);
3310   }
3311 
3312   // Now that we've parsed all of the tree fragments, do a closure on them so
3313   // that there are not references to PatFrags left inside of them.
3314   for (Record *Frag : Fragments) {
3315     if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
3316       continue;
3317 
3318     TreePattern &ThePat = *PatternFragments[Frag];
3319     ThePat.InlinePatternFragments();
3320 
3321     // Infer as many types as possible.  Don't worry about it if we don't infer
3322     // all of them, some may depend on the inputs of the pattern.  Also, don't
3323     // validate type sets; validation may cause spurious failures e.g. if a
3324     // fragment needs floating-point types but the current target does not have
3325     // any (this is only an error if that fragment is ever used!).
3326     {
3327       TypeInfer::SuppressValidation SV(ThePat.getInfer());
3328       ThePat.InferAllTypes();
3329       ThePat.resetError();
3330     }
3331 
3332     // If debugging, print out the pattern fragment result.
3333     LLVM_DEBUG(ThePat.dump());
3334   }
3335 }
3336 
3337 void CodeGenDAGPatterns::ParseDefaultOperands() {
3338   std::vector<Record *> DefaultOps;
3339   DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
3340 
3341   // Find some SDNode.
3342   assert(!SDNodes.empty() && "No SDNodes parsed?");
3343   Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
3344 
3345   for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
3346     DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
3347 
3348     // Clone the DefaultInfo dag node, changing the operator from 'ops' to
3349     // SomeSDnode so that we can parse this.
3350     std::vector<std::pair<Init *, StringInit *>> Ops;
3351     for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
3352       Ops.push_back(
3353           std::pair(DefaultInfo->getArg(op), DefaultInfo->getArgName(op)));
3354     DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
3355 
3356     // Create a TreePattern to parse this.
3357     TreePattern P(DefaultOps[i], DI, false, *this);
3358     assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
3359 
3360     // Copy the operands over into a DAGDefaultOperand.
3361     DAGDefaultOperand DefaultOpInfo;
3362 
3363     const TreePatternNodePtr &T = P.getTree(0);
3364     for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
3365       TreePatternNodePtr TPN = T->getChildShared(op);
3366       while (TPN->ApplyTypeConstraints(P, false))
3367         /* Resolve all types */;
3368 
3369       if (TPN->ContainsUnresolvedType(P)) {
3370         PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
3371                         DefaultOps[i]->getName() +
3372                         "' doesn't have a concrete type!");
3373       }
3374       DefaultOpInfo.DefaultOps.push_back(std::move(TPN));
3375     }
3376 
3377     // Insert it into the DefaultOperands map so we can find it later.
3378     DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
3379   }
3380 }
3381 
3382 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3383 /// instruction input.  Return true if this is a real use.
3384 static bool HandleUse(TreePattern &I, TreePatternNodePtr Pat,
3385                       std::map<std::string, TreePatternNodePtr> &InstInputs) {
3386   // No name -> not interesting.
3387   if (Pat->getName().empty()) {
3388     if (Pat->isLeaf()) {
3389       DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
3390       if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
3391                  DI->getDef()->isSubClassOf("RegisterOperand")))
3392         I.error("Input " + DI->getDef()->getName() + " must be named!");
3393     }
3394     return false;
3395   }
3396 
3397   Record *Rec;
3398   if (Pat->isLeaf()) {
3399     DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
3400     if (!DI)
3401       I.error("Input $" + Pat->getName() + " must be an identifier!");
3402     Rec = DI->getDef();
3403   } else {
3404     Rec = Pat->getOperator();
3405   }
3406 
3407   // SRCVALUE nodes are ignored.
3408   if (Rec->getName() == "srcvalue")
3409     return false;
3410 
3411   TreePatternNodePtr &Slot = InstInputs[Pat->getName()];
3412   if (!Slot) {
3413     Slot = Pat;
3414     return true;
3415   }
3416   Record *SlotRec;
3417   if (Slot->isLeaf()) {
3418     SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
3419   } else {
3420     assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
3421     SlotRec = Slot->getOperator();
3422   }
3423 
3424   // Ensure that the inputs agree if we've already seen this input.
3425   if (Rec != SlotRec)
3426     I.error("All $" + Pat->getName() + " inputs must agree with each other");
3427   // Ensure that the types can agree as well.
3428   Slot->UpdateNodeType(0, Pat->getExtType(0), I);
3429   Pat->UpdateNodeType(0, Slot->getExtType(0), I);
3430   if (Slot->getExtTypes() != Pat->getExtTypes())
3431     I.error("All $" + Pat->getName() + " inputs must agree with each other");
3432   return true;
3433 }
3434 
3435 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3436 /// part of "I", the instruction), computing the set of inputs and outputs of
3437 /// the pattern.  Report errors if we see anything naughty.
3438 void CodeGenDAGPatterns::FindPatternInputsAndOutputs(
3439     TreePattern &I, TreePatternNodePtr Pat,
3440     std::map<std::string, TreePatternNodePtr> &InstInputs,
3441     MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
3442         &InstResults,
3443     std::vector<Record *> &InstImpResults) {
3444 
3445   // The instruction pattern still has unresolved fragments.  For *named*
3446   // nodes we must resolve those here.  This may not result in multiple
3447   // alternatives.
3448   if (!Pat->getName().empty()) {
3449     TreePattern SrcPattern(I.getRecord(), Pat, true, *this);
3450     SrcPattern.InlinePatternFragments();
3451     SrcPattern.InferAllTypes();
3452     Pat = SrcPattern.getOnlyTree();
3453   }
3454 
3455   if (Pat->isLeaf()) {
3456     bool isUse = HandleUse(I, Pat, InstInputs);
3457     if (!isUse && Pat->getTransformFn())
3458       I.error("Cannot specify a transform function for a non-input value!");
3459     return;
3460   }
3461 
3462   if (Pat->getOperator()->getName() == "implicit") {
3463     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
3464       TreePatternNode &Dest = Pat->getChild(i);
3465       if (!Dest.isLeaf())
3466         I.error("implicitly defined value should be a register!");
3467 
3468       DefInit *Val = dyn_cast<DefInit>(Dest.getLeafValue());
3469       if (!Val || !Val->getDef()->isSubClassOf("Register"))
3470         I.error("implicitly defined value should be a register!");
3471       if (Val)
3472         InstImpResults.push_back(Val->getDef());
3473     }
3474     return;
3475   }
3476 
3477   if (Pat->getOperator()->getName() != "set") {
3478     // If this is not a set, verify that the children nodes are not void typed,
3479     // and recurse.
3480     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
3481       if (Pat->getChild(i).getNumTypes() == 0)
3482         I.error("Cannot have void nodes inside of patterns!");
3483       FindPatternInputsAndOutputs(I, Pat->getChildShared(i), InstInputs,
3484                                   InstResults, InstImpResults);
3485     }
3486 
3487     // If this is a non-leaf node with no children, treat it basically as if
3488     // it were a leaf.  This handles nodes like (imm).
3489     bool isUse = HandleUse(I, Pat, InstInputs);
3490 
3491     if (!isUse && Pat->getTransformFn())
3492       I.error("Cannot specify a transform function for a non-input value!");
3493     return;
3494   }
3495 
3496   // Otherwise, this is a set, validate and collect instruction results.
3497   if (Pat->getNumChildren() == 0)
3498     I.error("set requires operands!");
3499 
3500   if (Pat->getTransformFn())
3501     I.error("Cannot specify a transform function on a set node!");
3502 
3503   // Check the set destinations.
3504   unsigned NumDests = Pat->getNumChildren() - 1;
3505   for (unsigned i = 0; i != NumDests; ++i) {
3506     TreePatternNodePtr Dest = Pat->getChildShared(i);
3507     // For set destinations we also must resolve fragments here.
3508     TreePattern DestPattern(I.getRecord(), Dest, false, *this);
3509     DestPattern.InlinePatternFragments();
3510     DestPattern.InferAllTypes();
3511     Dest = DestPattern.getOnlyTree();
3512 
3513     if (!Dest->isLeaf())
3514       I.error("set destination should be a register!");
3515 
3516     DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
3517     if (!Val) {
3518       I.error("set destination should be a register!");
3519       continue;
3520     }
3521 
3522     if (Val->getDef()->isSubClassOf("RegisterClass") ||
3523         Val->getDef()->isSubClassOf("ValueType") ||
3524         Val->getDef()->isSubClassOf("RegisterOperand") ||
3525         Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
3526       if (Dest->getName().empty())
3527         I.error("set destination must have a name!");
3528       if (InstResults.count(Dest->getName()))
3529         I.error("cannot set '" + Dest->getName() + "' multiple times");
3530       InstResults[Dest->getName()] = Dest;
3531     } else if (Val->getDef()->isSubClassOf("Register")) {
3532       InstImpResults.push_back(Val->getDef());
3533     } else {
3534       I.error("set destination should be a register!");
3535     }
3536   }
3537 
3538   // Verify and collect info from the computation.
3539   FindPatternInputsAndOutputs(I, Pat->getChildShared(NumDests), InstInputs,
3540                               InstResults, InstImpResults);
3541 }
3542 
3543 //===----------------------------------------------------------------------===//
3544 // Instruction Analysis
3545 //===----------------------------------------------------------------------===//
3546 
3547 class InstAnalyzer {
3548   const CodeGenDAGPatterns &CDP;
3549 
3550 public:
3551   bool hasSideEffects;
3552   bool mayStore;
3553   bool mayLoad;
3554   bool isBitcast;
3555   bool isVariadic;
3556   bool hasChain;
3557 
3558   InstAnalyzer(const CodeGenDAGPatterns &cdp)
3559       : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
3560         isBitcast(false), isVariadic(false), hasChain(false) {}
3561 
3562   void Analyze(const PatternToMatch &Pat) {
3563     const TreePatternNode &N = Pat.getSrcPattern();
3564     AnalyzeNode(N);
3565     // These properties are detected only on the root node.
3566     isBitcast = IsNodeBitcast(N);
3567   }
3568 
3569 private:
3570   bool IsNodeBitcast(const TreePatternNode &N) const {
3571     if (hasSideEffects || mayLoad || mayStore || isVariadic)
3572       return false;
3573 
3574     if (N.isLeaf())
3575       return false;
3576     if (N.getNumChildren() != 1 || !N.getChild(0).isLeaf())
3577       return false;
3578 
3579     if (N.getOperator()->isSubClassOf("ComplexPattern"))
3580       return false;
3581 
3582     const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N.getOperator());
3583     if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
3584       return false;
3585     return OpInfo.getEnumName() == "ISD::BITCAST";
3586   }
3587 
3588 public:
3589   void AnalyzeNode(const TreePatternNode &N) {
3590     if (N.isLeaf()) {
3591       if (DefInit *DI = dyn_cast<DefInit>(N.getLeafValue())) {
3592         Record *LeafRec = DI->getDef();
3593         // Handle ComplexPattern leaves.
3594         if (LeafRec->isSubClassOf("ComplexPattern")) {
3595           const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
3596           if (CP.hasProperty(SDNPMayStore))
3597             mayStore = true;
3598           if (CP.hasProperty(SDNPMayLoad))
3599             mayLoad = true;
3600           if (CP.hasProperty(SDNPSideEffect))
3601             hasSideEffects = true;
3602         }
3603       }
3604       return;
3605     }
3606 
3607     // Analyze children.
3608     for (unsigned i = 0, e = N.getNumChildren(); i != e; ++i)
3609       AnalyzeNode(N.getChild(i));
3610 
3611     // Notice properties of the node.
3612     if (N.NodeHasProperty(SDNPMayStore, CDP))
3613       mayStore = true;
3614     if (N.NodeHasProperty(SDNPMayLoad, CDP))
3615       mayLoad = true;
3616     if (N.NodeHasProperty(SDNPSideEffect, CDP))
3617       hasSideEffects = true;
3618     if (N.NodeHasProperty(SDNPVariadic, CDP))
3619       isVariadic = true;
3620     if (N.NodeHasProperty(SDNPHasChain, CDP))
3621       hasChain = true;
3622 
3623     if (const CodeGenIntrinsic *IntInfo = N.getIntrinsicInfo(CDP)) {
3624       ModRefInfo MR = IntInfo->ME.getModRef();
3625       // If this is an intrinsic, analyze it.
3626       if (isRefSet(MR))
3627         mayLoad = true; // These may load memory.
3628 
3629       if (isModSet(MR))
3630         mayStore = true; // Intrinsics that can write to memory are 'mayStore'.
3631 
3632       // Consider intrinsics that don't specify any restrictions on memory
3633       // effects as having a side-effect.
3634       if (IntInfo->ME == MemoryEffects::unknown() || IntInfo->hasSideEffects)
3635         hasSideEffects = true;
3636     }
3637   }
3638 };
3639 
3640 static bool InferFromPattern(CodeGenInstruction &InstInfo,
3641                              const InstAnalyzer &PatInfo, Record *PatDef) {
3642   bool Error = false;
3643 
3644   // Remember where InstInfo got its flags.
3645   if (InstInfo.hasUndefFlags())
3646     InstInfo.InferredFrom = PatDef;
3647 
3648   // Check explicitly set flags for consistency.
3649   if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3650       !InstInfo.hasSideEffects_Unset) {
3651     // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3652     // the pattern has no side effects. That could be useful for div/rem
3653     // instructions that may trap.
3654     if (!InstInfo.hasSideEffects) {
3655       Error = true;
3656       PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
3657                                        Twine(InstInfo.hasSideEffects));
3658     }
3659   }
3660 
3661   if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3662     Error = true;
3663     PrintError(PatDef->getLoc(),
3664                "Pattern doesn't match mayStore = " + Twine(InstInfo.mayStore));
3665   }
3666 
3667   if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3668     // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
3669     // Some targets translate immediates to loads.
3670     if (!InstInfo.mayLoad) {
3671       Error = true;
3672       PrintError(PatDef->getLoc(),
3673                  "Pattern doesn't match mayLoad = " + Twine(InstInfo.mayLoad));
3674     }
3675   }
3676 
3677   // Transfer inferred flags.
3678   InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3679   InstInfo.mayStore |= PatInfo.mayStore;
3680   InstInfo.mayLoad |= PatInfo.mayLoad;
3681 
3682   // These flags are silently added without any verification.
3683   // FIXME: To match historical behavior of TableGen, for now add those flags
3684   // only when we're inferring from the primary instruction pattern.
3685   if (PatDef->isSubClassOf("Instruction")) {
3686     InstInfo.isBitcast |= PatInfo.isBitcast;
3687     InstInfo.hasChain |= PatInfo.hasChain;
3688     InstInfo.hasChain_Inferred = true;
3689   }
3690 
3691   // Don't infer isVariadic. This flag means something different on SDNodes and
3692   // instructions. For example, a CALL SDNode is variadic because it has the
3693   // call arguments as operands, but a CALL instruction is not variadic - it
3694   // has argument registers as implicit, not explicit uses.
3695 
3696   return Error;
3697 }
3698 
3699 /// hasNullFragReference - Return true if the DAG has any reference to the
3700 /// null_frag operator.
3701 static bool hasNullFragReference(DagInit *DI) {
3702   DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
3703   if (!OpDef)
3704     return false;
3705   Record *Operator = OpDef->getDef();
3706 
3707   // If this is the null fragment, return true.
3708   if (Operator->getName() == "null_frag")
3709     return true;
3710   // If any of the arguments reference the null fragment, return true.
3711   for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
3712     if (auto Arg = dyn_cast<DefInit>(DI->getArg(i)))
3713       if (Arg->getDef()->getName() == "null_frag")
3714         return true;
3715     DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
3716     if (Arg && hasNullFragReference(Arg))
3717       return true;
3718   }
3719 
3720   return false;
3721 }
3722 
3723 /// hasNullFragReference - Return true if any DAG in the list references
3724 /// the null_frag operator.
3725 static bool hasNullFragReference(ListInit *LI) {
3726   for (Init *I : LI->getValues()) {
3727     DagInit *DI = dyn_cast<DagInit>(I);
3728     assert(DI && "non-dag in an instruction Pattern list?!");
3729     if (hasNullFragReference(DI))
3730       return true;
3731   }
3732   return false;
3733 }
3734 
3735 /// Get all the instructions in a tree.
3736 static void getInstructionsInTree(TreePatternNode &Tree,
3737                                   SmallVectorImpl<Record *> &Instrs) {
3738   if (Tree.isLeaf())
3739     return;
3740   if (Tree.getOperator()->isSubClassOf("Instruction"))
3741     Instrs.push_back(Tree.getOperator());
3742   for (unsigned i = 0, e = Tree.getNumChildren(); i != e; ++i)
3743     getInstructionsInTree(Tree.getChild(i), Instrs);
3744 }
3745 
3746 /// Check the class of a pattern leaf node against the instruction operand it
3747 /// represents.
3748 static bool checkOperandClass(CGIOperandList::OperandInfo &OI, Record *Leaf) {
3749   if (OI.Rec == Leaf)
3750     return true;
3751 
3752   // Allow direct value types to be used in instruction set patterns.
3753   // The type will be checked later.
3754   if (Leaf->isSubClassOf("ValueType"))
3755     return true;
3756 
3757   // Patterns can also be ComplexPattern instances.
3758   if (Leaf->isSubClassOf("ComplexPattern"))
3759     return true;
3760 
3761   return false;
3762 }
3763 
3764 void CodeGenDAGPatterns::parseInstructionPattern(CodeGenInstruction &CGI,
3765                                                  ListInit *Pat,
3766                                                  DAGInstMap &DAGInsts) {
3767 
3768   assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
3769 
3770   // Parse the instruction.
3771   TreePattern I(CGI.TheDef, Pat, true, *this);
3772 
3773   // InstInputs - Keep track of all of the inputs of the instruction, along
3774   // with the record they are declared as.
3775   std::map<std::string, TreePatternNodePtr> InstInputs;
3776 
3777   // InstResults - Keep track of all the virtual registers that are 'set'
3778   // in the instruction, including what reg class they are.
3779   MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
3780       InstResults;
3781 
3782   std::vector<Record *> InstImpResults;
3783 
3784   // Verify that the top-level forms in the instruction are of void type, and
3785   // fill in the InstResults map.
3786   SmallString<32> TypesString;
3787   for (unsigned j = 0, e = I.getNumTrees(); j != e; ++j) {
3788     TypesString.clear();
3789     TreePatternNodePtr Pat = I.getTree(j);
3790     if (Pat->getNumTypes() != 0) {
3791       raw_svector_ostream OS(TypesString);
3792       ListSeparator LS;
3793       for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3794         OS << LS;
3795         Pat->getExtType(k).writeToStream(OS);
3796       }
3797       I.error("Top-level forms in instruction pattern should have"
3798               " void types, has types " +
3799               OS.str());
3800     }
3801 
3802     // Find inputs and outputs, and verify the structure of the uses/defs.
3803     FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
3804                                 InstImpResults);
3805   }
3806 
3807   // Now that we have inputs and outputs of the pattern, inspect the operands
3808   // list for the instruction.  This determines the order that operands are
3809   // added to the machine instruction the node corresponds to.
3810   unsigned NumResults = InstResults.size();
3811 
3812   // Parse the operands list from the (ops) list, validating it.
3813   assert(I.getArgList().empty() && "Args list should still be empty here!");
3814 
3815   // Check that all of the results occur first in the list.
3816   std::vector<Record *> Results;
3817   std::vector<unsigned> ResultIndices;
3818   SmallVector<TreePatternNodePtr, 2> ResNodes;
3819   for (unsigned i = 0; i != NumResults; ++i) {
3820     if (i == CGI.Operands.size()) {
3821       const std::string &OpName =
3822           llvm::find_if(
3823               InstResults,
3824               [](const std::pair<std::string, TreePatternNodePtr> &P) {
3825                 return P.second;
3826               })
3827               ->first;
3828 
3829       I.error("'" + OpName + "' set but does not appear in operand list!");
3830     }
3831 
3832     const std::string &OpName = CGI.Operands[i].Name;
3833 
3834     // Check that it exists in InstResults.
3835     auto InstResultIter = InstResults.find(OpName);
3836     if (InstResultIter == InstResults.end() || !InstResultIter->second)
3837       I.error("Operand $" + OpName + " does not exist in operand list!");
3838 
3839     TreePatternNodePtr RNode = InstResultIter->second;
3840     Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
3841     ResNodes.push_back(std::move(RNode));
3842     if (!R)
3843       I.error("Operand $" + OpName +
3844               " should be a set destination: all "
3845               "outputs must occur before inputs in operand list!");
3846 
3847     if (!checkOperandClass(CGI.Operands[i], R))
3848       I.error("Operand $" + OpName + " class mismatch!");
3849 
3850     // Remember the return type.
3851     Results.push_back(CGI.Operands[i].Rec);
3852 
3853     // Remember the result index.
3854     ResultIndices.push_back(std::distance(InstResults.begin(), InstResultIter));
3855 
3856     // Okay, this one checks out.
3857     InstResultIter->second = nullptr;
3858   }
3859 
3860   // Loop over the inputs next.
3861   std::vector<TreePatternNodePtr> ResultNodeOperands;
3862   std::vector<Record *> Operands;
3863   for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3864     CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3865     const std::string &OpName = Op.Name;
3866     if (OpName.empty()) {
3867       I.error("Operand #" + Twine(i) + " in operands list has no name!");
3868       continue;
3869     }
3870 
3871     if (!InstInputs.count(OpName)) {
3872       // If this is an operand with a DefaultOps set filled in, we can ignore
3873       // this.  When we codegen it, we will do so as always executed.
3874       if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3875         // Does it have a non-empty DefaultOps field?  If so, ignore this
3876         // operand.
3877         if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3878           continue;
3879       }
3880       I.error("Operand $" + OpName +
3881               " does not appear in the instruction pattern");
3882       continue;
3883     }
3884     TreePatternNodePtr InVal = InstInputs[OpName];
3885     InstInputs.erase(OpName); // It occurred, remove from map.
3886 
3887     if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3888       Record *InRec = cast<DefInit>(InVal->getLeafValue())->getDef();
3889       if (!checkOperandClass(Op, InRec)) {
3890         I.error("Operand $" + OpName +
3891                 "'s register class disagrees"
3892                 " between the operand and pattern");
3893         continue;
3894       }
3895     }
3896     Operands.push_back(Op.Rec);
3897 
3898     // Construct the result for the dest-pattern operand list.
3899     TreePatternNodePtr OpNode = InVal->clone();
3900 
3901     // No predicate is useful on the result.
3902     OpNode->clearPredicateCalls();
3903 
3904     // Promote the xform function to be an explicit node if set.
3905     if (Record *Xform = OpNode->getTransformFn()) {
3906       OpNode->setTransformFn(nullptr);
3907       std::vector<TreePatternNodePtr> Children;
3908       Children.push_back(OpNode);
3909       OpNode = makeIntrusiveRefCnt<TreePatternNode>(Xform, std::move(Children),
3910                                                     OpNode->getNumTypes());
3911     }
3912 
3913     ResultNodeOperands.push_back(std::move(OpNode));
3914   }
3915 
3916   if (!InstInputs.empty())
3917     I.error("Input operand $" + InstInputs.begin()->first +
3918             " occurs in pattern but not in operands list!");
3919 
3920   TreePatternNodePtr ResultPattern = makeIntrusiveRefCnt<TreePatternNode>(
3921       I.getRecord(), std::move(ResultNodeOperands),
3922       GetNumNodeResults(I.getRecord(), *this));
3923   // Copy fully inferred output node types to instruction result pattern.
3924   for (unsigned i = 0; i != NumResults; ++i) {
3925     assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3926     ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3927     ResultPattern->setResultIndex(i, ResultIndices[i]);
3928   }
3929 
3930   // FIXME: Assume only the first tree is the pattern. The others are clobber
3931   // nodes.
3932   TreePatternNodePtr Pattern = I.getTree(0);
3933   TreePatternNodePtr SrcPattern;
3934   if (Pattern->getOperator()->getName() == "set") {
3935     SrcPattern = Pattern->getChild(Pattern->getNumChildren() - 1).clone();
3936   } else {
3937     // Not a set (store or something?)
3938     SrcPattern = Pattern;
3939   }
3940 
3941   // Create and insert the instruction.
3942   // FIXME: InstImpResults should not be part of DAGInstruction.
3943   Record *R = I.getRecord();
3944   DAGInsts.try_emplace(R, std::move(Results), std::move(Operands),
3945                        std::move(InstImpResults), SrcPattern, ResultPattern);
3946 
3947   LLVM_DEBUG(I.dump());
3948 }
3949 
3950 /// ParseInstructions - Parse all of the instructions, inlining and resolving
3951 /// any fragments involved.  This populates the Instructions list with fully
3952 /// resolved instructions.
3953 void CodeGenDAGPatterns::ParseInstructions() {
3954   std::vector<Record *> Instrs =
3955       Records.getAllDerivedDefinitions("Instruction");
3956 
3957   for (Record *Instr : Instrs) {
3958     ListInit *LI = nullptr;
3959 
3960     if (isa<ListInit>(Instr->getValueInit("Pattern")))
3961       LI = Instr->getValueAsListInit("Pattern");
3962 
3963     // If there is no pattern, only collect minimal information about the
3964     // instruction for its operand list.  We have to assume that there is one
3965     // result, as we have no detailed info. A pattern which references the
3966     // null_frag operator is as-if no pattern were specified. Normally this
3967     // is from a multiclass expansion w/ a SDPatternOperator passed in as
3968     // null_frag.
3969     if (!LI || LI->empty() || hasNullFragReference(LI)) {
3970       std::vector<Record *> Results;
3971       std::vector<Record *> Operands;
3972 
3973       CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3974 
3975       if (InstInfo.Operands.size() != 0) {
3976         for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3977           Results.push_back(InstInfo.Operands[j].Rec);
3978 
3979         // The rest are inputs.
3980         for (unsigned j = InstInfo.Operands.NumDefs,
3981                       e = InstInfo.Operands.size();
3982              j < e; ++j)
3983           Operands.push_back(InstInfo.Operands[j].Rec);
3984       }
3985 
3986       // Create and insert the instruction.
3987       Instructions.try_emplace(Instr, std::move(Results), std::move(Operands),
3988                                std::vector<Record *>());
3989       continue; // no pattern.
3990     }
3991 
3992     CodeGenInstruction &CGI = Target.getInstruction(Instr);
3993     parseInstructionPattern(CGI, LI, Instructions);
3994   }
3995 
3996   // If we can, convert the instructions to be patterns that are matched!
3997   for (auto &Entry : Instructions) {
3998     Record *Instr = Entry.first;
3999     DAGInstruction &TheInst = Entry.second;
4000     TreePatternNodePtr SrcPattern = TheInst.getSrcPattern();
4001     TreePatternNodePtr ResultPattern = TheInst.getResultPattern();
4002 
4003     if (SrcPattern && ResultPattern) {
4004       TreePattern Pattern(Instr, SrcPattern, true, *this);
4005       TreePattern Result(Instr, ResultPattern, false, *this);
4006       ParseOnePattern(Instr, Pattern, Result, TheInst.getImpResults());
4007     }
4008   }
4009 }
4010 
4011 typedef std::pair<TreePatternNode *, unsigned> NameRecord;
4012 
4013 static void FindNames(TreePatternNode &P,
4014                       std::map<std::string, NameRecord> &Names,
4015                       TreePattern *PatternTop) {
4016   if (!P.getName().empty()) {
4017     NameRecord &Rec = Names[P.getName()];
4018     // If this is the first instance of the name, remember the node.
4019     if (Rec.second++ == 0)
4020       Rec.first = &P;
4021     else if (Rec.first->getExtTypes() != P.getExtTypes())
4022       PatternTop->error("repetition of value: $" + P.getName() +
4023                         " where different uses have different types!");
4024   }
4025 
4026   if (!P.isLeaf()) {
4027     for (unsigned i = 0, e = P.getNumChildren(); i != e; ++i)
4028       FindNames(P.getChild(i), Names, PatternTop);
4029   }
4030 }
4031 
4032 void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
4033                                            PatternToMatch &&PTM) {
4034   // Do some sanity checking on the pattern we're about to match.
4035   std::string Reason;
4036   if (!PTM.getSrcPattern().canPatternMatch(Reason, *this)) {
4037     PrintWarning(Pattern->getRecord()->getLoc(),
4038                  Twine("Pattern can never match: ") + Reason);
4039     return;
4040   }
4041 
4042   // If the source pattern's root is a complex pattern, that complex pattern
4043   // must specify the nodes it can potentially match.
4044   if (const ComplexPattern *CP =
4045           PTM.getSrcPattern().getComplexPatternInfo(*this))
4046     if (CP->getRootNodes().empty())
4047       Pattern->error("ComplexPattern at root must specify list of opcodes it"
4048                      " could match");
4049 
4050   // Find all of the named values in the input and output, ensure they have the
4051   // same type.
4052   std::map<std::string, NameRecord> SrcNames, DstNames;
4053   FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
4054   FindNames(PTM.getDstPattern(), DstNames, Pattern);
4055 
4056   // Scan all of the named values in the destination pattern, rejecting them if
4057   // they don't exist in the input pattern.
4058   for (const auto &Entry : DstNames) {
4059     if (SrcNames[Entry.first].first == nullptr)
4060       Pattern->error("Pattern has input without matching name in output: $" +
4061                      Entry.first);
4062   }
4063 
4064   // Scan all of the named values in the source pattern, rejecting them if the
4065   // name isn't used in the dest, and isn't used to tie two values together.
4066   for (const auto &Entry : SrcNames)
4067     if (DstNames[Entry.first].first == nullptr &&
4068         SrcNames[Entry.first].second == 1)
4069       Pattern->error("Pattern has dead named input: $" + Entry.first);
4070 
4071   PatternsToMatch.push_back(std::move(PTM));
4072 }
4073 
4074 void CodeGenDAGPatterns::InferInstructionFlags() {
4075   ArrayRef<const CodeGenInstruction *> Instructions =
4076       Target.getInstructionsByEnumValue();
4077 
4078   unsigned Errors = 0;
4079 
4080   // Try to infer flags from all patterns in PatternToMatch.  These include
4081   // both the primary instruction patterns (which always come first) and
4082   // patterns defined outside the instruction.
4083   for (const PatternToMatch &PTM : ptms()) {
4084     // We can only infer from single-instruction patterns, otherwise we won't
4085     // know which instruction should get the flags.
4086     SmallVector<Record *, 8> PatInstrs;
4087     getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
4088     if (PatInstrs.size() != 1)
4089       continue;
4090 
4091     // Get the single instruction.
4092     CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
4093 
4094     // Only infer properties from the first pattern. We'll verify the others.
4095     if (InstInfo.InferredFrom)
4096       continue;
4097 
4098     InstAnalyzer PatInfo(*this);
4099     PatInfo.Analyze(PTM);
4100     Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
4101   }
4102 
4103   if (Errors)
4104     PrintFatalError("pattern conflicts");
4105 
4106   // If requested by the target, guess any undefined properties.
4107   if (Target.guessInstructionProperties()) {
4108     for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
4109       CodeGenInstruction *InstInfo =
4110           const_cast<CodeGenInstruction *>(Instructions[i]);
4111       if (InstInfo->InferredFrom)
4112         continue;
4113       // The mayLoad and mayStore flags default to false.
4114       // Conservatively assume hasSideEffects if it wasn't explicit.
4115       if (InstInfo->hasSideEffects_Unset)
4116         InstInfo->hasSideEffects = true;
4117     }
4118     return;
4119   }
4120 
4121   // Complain about any flags that are still undefined.
4122   for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
4123     CodeGenInstruction *InstInfo =
4124         const_cast<CodeGenInstruction *>(Instructions[i]);
4125     if (InstInfo->InferredFrom)
4126       continue;
4127     if (InstInfo->hasSideEffects_Unset)
4128       PrintError(InstInfo->TheDef->getLoc(),
4129                  "Can't infer hasSideEffects from patterns");
4130     if (InstInfo->mayStore_Unset)
4131       PrintError(InstInfo->TheDef->getLoc(),
4132                  "Can't infer mayStore from patterns");
4133     if (InstInfo->mayLoad_Unset)
4134       PrintError(InstInfo->TheDef->getLoc(),
4135                  "Can't infer mayLoad from patterns");
4136   }
4137 }
4138 
4139 /// Verify instruction flags against pattern node properties.
4140 void CodeGenDAGPatterns::VerifyInstructionFlags() {
4141   unsigned Errors = 0;
4142   for (const PatternToMatch &PTM : ptms()) {
4143     SmallVector<Record *, 8> Instrs;
4144     getInstructionsInTree(PTM.getDstPattern(), Instrs);
4145     if (Instrs.empty())
4146       continue;
4147 
4148     // Count the number of instructions with each flag set.
4149     unsigned NumSideEffects = 0;
4150     unsigned NumStores = 0;
4151     unsigned NumLoads = 0;
4152     for (const Record *Instr : Instrs) {
4153       const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
4154       NumSideEffects += InstInfo.hasSideEffects;
4155       NumStores += InstInfo.mayStore;
4156       NumLoads += InstInfo.mayLoad;
4157     }
4158 
4159     // Analyze the source pattern.
4160     InstAnalyzer PatInfo(*this);
4161     PatInfo.Analyze(PTM);
4162 
4163     // Collect error messages.
4164     SmallVector<std::string, 4> Msgs;
4165 
4166     // Check for missing flags in the output.
4167     // Permit extra flags for now at least.
4168     if (PatInfo.hasSideEffects && !NumSideEffects)
4169       Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
4170 
4171     // Don't verify store flags on instructions with side effects. At least for
4172     // intrinsics, side effects implies mayStore.
4173     if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
4174       Msgs.push_back("pattern may store, but mayStore isn't set");
4175 
4176     // Similarly, mayStore implies mayLoad on intrinsics.
4177     if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
4178       Msgs.push_back("pattern may load, but mayLoad isn't set");
4179 
4180     // Print error messages.
4181     if (Msgs.empty())
4182       continue;
4183     ++Errors;
4184 
4185     for (const std::string &Msg : Msgs)
4186       PrintError(
4187           PTM.getSrcRecord()->getLoc(),
4188           Twine(Msg) + " on the " +
4189               (Instrs.size() == 1 ? "instruction" : "output instructions"));
4190     // Provide the location of the relevant instruction definitions.
4191     for (const Record *Instr : Instrs) {
4192       if (Instr != PTM.getSrcRecord())
4193         PrintError(Instr->getLoc(), "defined here");
4194       const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
4195       if (InstInfo.InferredFrom && InstInfo.InferredFrom != InstInfo.TheDef &&
4196           InstInfo.InferredFrom != PTM.getSrcRecord())
4197         PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
4198     }
4199   }
4200   if (Errors)
4201     PrintFatalError("Errors in DAG patterns");
4202 }
4203 
4204 /// Given a pattern result with an unresolved type, see if we can find one
4205 /// instruction with an unresolved result type.  Force this result type to an
4206 /// arbitrary element if it's possible types to converge results.
4207 static bool ForceArbitraryInstResultType(TreePatternNode &N, TreePattern &TP) {
4208   if (N.isLeaf())
4209     return false;
4210 
4211   // Analyze children.
4212   for (unsigned i = 0, e = N.getNumChildren(); i != e; ++i)
4213     if (ForceArbitraryInstResultType(N.getChild(i), TP))
4214       return true;
4215 
4216   if (!N.getOperator()->isSubClassOf("Instruction"))
4217     return false;
4218 
4219   // If this type is already concrete or completely unknown we can't do
4220   // anything.
4221   TypeInfer &TI = TP.getInfer();
4222   for (unsigned i = 0, e = N.getNumTypes(); i != e; ++i) {
4223     if (N.getExtType(i).empty() || TI.isConcrete(N.getExtType(i), false))
4224       continue;
4225 
4226     // Otherwise, force its type to an arbitrary choice.
4227     if (TI.forceArbitrary(N.getExtType(i)))
4228       return true;
4229   }
4230 
4231   return false;
4232 }
4233 
4234 // Promote xform function to be an explicit node wherever set.
4235 static TreePatternNodePtr PromoteXForms(TreePatternNodePtr N) {
4236   if (Record *Xform = N->getTransformFn()) {
4237     N->setTransformFn(nullptr);
4238     std::vector<TreePatternNodePtr> Children;
4239     Children.push_back(PromoteXForms(N));
4240     return makeIntrusiveRefCnt<TreePatternNode>(Xform, std::move(Children),
4241                                                 N->getNumTypes());
4242   }
4243 
4244   if (!N->isLeaf())
4245     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4246       TreePatternNodePtr Child = N->getChildShared(i);
4247       N->setChild(i, PromoteXForms(Child));
4248     }
4249   return N;
4250 }
4251 
4252 void CodeGenDAGPatterns::ParseOnePattern(
4253     Record *TheDef, TreePattern &Pattern, TreePattern &Result,
4254     const std::vector<Record *> &InstImpResults, bool ShouldIgnore) {
4255 
4256   // Inline pattern fragments and expand multiple alternatives.
4257   Pattern.InlinePatternFragments();
4258   Result.InlinePatternFragments();
4259 
4260   if (Result.getNumTrees() != 1)
4261     Result.error("Cannot use multi-alternative fragments in result pattern!");
4262 
4263   // Infer types.
4264   bool IterateInference;
4265   bool InferredAllPatternTypes, InferredAllResultTypes;
4266   do {
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     InferredAllPatternTypes =
4270         Pattern.InferAllTypes(&Pattern.getNamedNodesMap());
4271 
4272     // Infer as many types as possible.  If we cannot infer all of them, we
4273     // can never do anything with this pattern: report it to the user.
4274     InferredAllResultTypes = Result.InferAllTypes(&Pattern.getNamedNodesMap());
4275 
4276     IterateInference = false;
4277 
4278     // Apply the type of the result to the source pattern.  This helps us
4279     // resolve cases where the input type is known to be a pointer type (which
4280     // is considered resolved), but the result knows it needs to be 32- or
4281     // 64-bits.  Infer the other way for good measure.
4282     for (const auto &T : Pattern.getTrees())
4283       for (unsigned i = 0, e = std::min(Result.getOnlyTree()->getNumTypes(),
4284                                         T->getNumTypes());
4285            i != e; ++i) {
4286         IterateInference |=
4287             T->UpdateNodeType(i, Result.getOnlyTree()->getExtType(i), Result);
4288         IterateInference |=
4289             Result.getOnlyTree()->UpdateNodeType(i, T->getExtType(i), Result);
4290       }
4291 
4292     // If our iteration has converged and the input pattern's types are fully
4293     // resolved but the result pattern is not fully resolved, we may have a
4294     // situation where we have two instructions in the result pattern and
4295     // the instructions require a common register class, but don't care about
4296     // what actual MVT is used.  This is actually a bug in our modelling:
4297     // output patterns should have register classes, not MVTs.
4298     //
4299     // In any case, to handle this, we just go through and disambiguate some
4300     // arbitrary types to the result pattern's nodes.
4301     if (!IterateInference && InferredAllPatternTypes && !InferredAllResultTypes)
4302       IterateInference =
4303           ForceArbitraryInstResultType(*Result.getTree(0), Result);
4304   } while (IterateInference);
4305 
4306   // Verify that we inferred enough types that we can do something with the
4307   // pattern and result.  If these fire the user has to add type casts.
4308   if (!InferredAllPatternTypes)
4309     Pattern.error("Could not infer all types in pattern!");
4310   if (!InferredAllResultTypes) {
4311     Pattern.dump();
4312     Result.error("Could not infer all types in pattern result!");
4313   }
4314 
4315   // Promote xform function to be an explicit node wherever set.
4316   TreePatternNodePtr DstShared = PromoteXForms(Result.getOnlyTree());
4317 
4318   TreePattern Temp(Result.getRecord(), DstShared, false, *this);
4319   Temp.InferAllTypes();
4320 
4321   ListInit *Preds = TheDef->getValueAsListInit("Predicates");
4322   int Complexity = TheDef->getValueAsInt("AddedComplexity");
4323 
4324   if (PatternRewriter)
4325     PatternRewriter(&Pattern);
4326 
4327   // A pattern may end up with an "impossible" type, i.e. a situation
4328   // where all types have been eliminated for some node in this pattern.
4329   // This could occur for intrinsics that only make sense for a specific
4330   // value type, and use a specific register class. If, for some mode,
4331   // that register class does not accept that type, the type inference
4332   // will lead to a contradiction, which is not an error however, but
4333   // a sign that this pattern will simply never match.
4334   if (Temp.getOnlyTree()->hasPossibleType()) {
4335     for (const auto &T : Pattern.getTrees()) {
4336       if (T->hasPossibleType())
4337         AddPatternToMatch(&Pattern,
4338                           PatternToMatch(TheDef, Preds, T, Temp.getOnlyTree(),
4339                                          InstImpResults, Complexity,
4340                                          TheDef->getID(), ShouldIgnore));
4341     }
4342   } else {
4343     // Show a message about a dropped pattern with some info to make it
4344     // easier to identify it in the .td files.
4345     LLVM_DEBUG({
4346       dbgs() << "Dropping: ";
4347       Pattern.dump();
4348       Temp.getOnlyTree()->dump();
4349       dbgs() << "\n";
4350     });
4351   }
4352 }
4353 
4354 void CodeGenDAGPatterns::ParsePatterns() {
4355   std::vector<Record *> Patterns = Records.getAllDerivedDefinitions("Pattern");
4356 
4357   for (Record *CurPattern : Patterns) {
4358     DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
4359 
4360     // If the pattern references the null_frag, there's nothing to do.
4361     if (hasNullFragReference(Tree))
4362       continue;
4363 
4364     TreePattern Pattern(CurPattern, Tree, true, *this);
4365 
4366     ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
4367     if (LI->empty())
4368       continue; // no pattern.
4369 
4370     // Parse the instruction.
4371     TreePattern Result(CurPattern, LI, false, *this);
4372 
4373     if (Result.getNumTrees() != 1)
4374       Result.error("Cannot handle instructions producing instructions "
4375                    "with temporaries yet!");
4376 
4377     // Validate that the input pattern is correct.
4378     std::map<std::string, TreePatternNodePtr> InstInputs;
4379     MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
4380         InstResults;
4381     std::vector<Record *> InstImpResults;
4382     for (unsigned j = 0, ee = Pattern.getNumTrees(); j != ee; ++j)
4383       FindPatternInputsAndOutputs(Pattern, Pattern.getTree(j), InstInputs,
4384                                   InstResults, InstImpResults);
4385 
4386     ParseOnePattern(CurPattern, Pattern, Result, InstImpResults,
4387                     CurPattern->getValueAsBit("GISelShouldIgnore"));
4388   }
4389 }
4390 
4391 static void collectModes(std::set<unsigned> &Modes, const TreePatternNode &N) {
4392   for (const TypeSetByHwMode &VTS : N.getExtTypes())
4393     for (const auto &I : VTS)
4394       Modes.insert(I.first);
4395 
4396   for (unsigned i = 0, e = N.getNumChildren(); i != e; ++i)
4397     collectModes(Modes, N.getChild(i));
4398 }
4399 
4400 void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
4401   const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
4402   if (CGH.getNumModeIds() == 1)
4403     return;
4404 
4405   std::vector<PatternToMatch> Copy;
4406   PatternsToMatch.swap(Copy);
4407 
4408   auto AppendPattern = [this](PatternToMatch &P, unsigned Mode,
4409                               StringRef Check) {
4410     TreePatternNodePtr NewSrc = P.getSrcPattern().clone();
4411     TreePatternNodePtr NewDst = P.getDstPattern().clone();
4412     if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
4413       return;
4414     }
4415 
4416     PatternsToMatch.emplace_back(
4417         P.getSrcRecord(), P.getPredicates(), std::move(NewSrc),
4418         std::move(NewDst), P.getDstRegs(), P.getAddedComplexity(),
4419         Record::getNewUID(Records), P.getGISelShouldIgnore(), Check);
4420   };
4421 
4422   for (PatternToMatch &P : Copy) {
4423     const TreePatternNode *SrcP = nullptr, *DstP = nullptr;
4424     if (P.getSrcPattern().hasProperTypeByHwMode())
4425       SrcP = &P.getSrcPattern();
4426     if (P.getDstPattern().hasProperTypeByHwMode())
4427       DstP = &P.getDstPattern();
4428     if (!SrcP && !DstP) {
4429       PatternsToMatch.push_back(P);
4430       continue;
4431     }
4432 
4433     std::set<unsigned> Modes;
4434     if (SrcP)
4435       collectModes(Modes, *SrcP);
4436     if (DstP)
4437       collectModes(Modes, *DstP);
4438 
4439     // The predicate for the default mode needs to be constructed for each
4440     // pattern separately.
4441     // Since not all modes must be present in each pattern, if a mode m is
4442     // absent, then there is no point in constructing a check for m. If such
4443     // a check was created, it would be equivalent to checking the default
4444     // mode, except not all modes' predicates would be a part of the checking
4445     // code. The subsequently generated check for the default mode would then
4446     // have the exact same patterns, but a different predicate code. To avoid
4447     // duplicated patterns with different predicate checks, construct the
4448     // default check as a negation of all predicates that are actually present
4449     // in the source/destination patterns.
4450     SmallString<128> DefaultCheck;
4451 
4452     for (unsigned M : Modes) {
4453       if (M == DefaultMode)
4454         continue;
4455 
4456       // Fill the map entry for this mode.
4457       const HwMode &HM = CGH.getMode(M);
4458       AppendPattern(P, M, HM.Predicates);
4459 
4460       // Add negations of the HM's predicates to the default predicate.
4461       if (!DefaultCheck.empty())
4462         DefaultCheck += " && ";
4463       DefaultCheck += "!(";
4464       DefaultCheck += HM.Predicates;
4465       DefaultCheck += ")";
4466     }
4467 
4468     bool HasDefault = Modes.count(DefaultMode);
4469     if (HasDefault)
4470       AppendPattern(P, DefaultMode, DefaultCheck);
4471   }
4472 }
4473 
4474 /// Dependent variable map for CodeGenDAGPattern variant generation
4475 typedef StringMap<int> DepVarMap;
4476 
4477 static void FindDepVarsOf(TreePatternNode &N, DepVarMap &DepMap) {
4478   if (N.isLeaf()) {
4479     if (N.hasName() && isa<DefInit>(N.getLeafValue()))
4480       DepMap[N.getName()]++;
4481   } else {
4482     for (size_t i = 0, e = N.getNumChildren(); i != e; ++i)
4483       FindDepVarsOf(N.getChild(i), DepMap);
4484   }
4485 }
4486 
4487 /// Find dependent variables within child patterns
4488 static void FindDepVars(TreePatternNode &N, MultipleUseVarSet &DepVars) {
4489   DepVarMap depcounts;
4490   FindDepVarsOf(N, depcounts);
4491   for (const auto &Pair : depcounts) {
4492     if (Pair.getValue() > 1)
4493       DepVars.insert(Pair.getKey());
4494   }
4495 }
4496 
4497 #ifndef NDEBUG
4498 /// Dump the dependent variable set:
4499 static void DumpDepVars(MultipleUseVarSet &DepVars) {
4500   if (DepVars.empty()) {
4501     LLVM_DEBUG(errs() << "<empty set>");
4502   } else {
4503     LLVM_DEBUG(errs() << "[ ");
4504     for (const auto &DepVar : DepVars) {
4505       LLVM_DEBUG(errs() << DepVar.getKey() << " ");
4506     }
4507     LLVM_DEBUG(errs() << "]");
4508   }
4509 }
4510 #endif
4511 
4512 /// CombineChildVariants - Given a bunch of permutations of each child of the
4513 /// 'operator' node, put them together in all possible ways.
4514 static void CombineChildVariants(
4515     TreePatternNodePtr Orig,
4516     const std::vector<std::vector<TreePatternNodePtr>> &ChildVariants,
4517     std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP,
4518     const MultipleUseVarSet &DepVars) {
4519   // Make sure that each operand has at least one variant to choose from.
4520   for (const auto &Variants : ChildVariants)
4521     if (Variants.empty())
4522       return;
4523 
4524   // The end result is an all-pairs construction of the resultant pattern.
4525   std::vector<unsigned> Idxs(ChildVariants.size());
4526   bool NotDone;
4527   do {
4528 #ifndef NDEBUG
4529     LLVM_DEBUG(if (!Idxs.empty()) {
4530       errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
4531       for (unsigned Idx : Idxs) {
4532         errs() << Idx << " ";
4533       }
4534       errs() << "]\n";
4535     });
4536 #endif
4537     // Create the variant and add it to the output list.
4538     std::vector<TreePatternNodePtr> NewChildren;
4539     NewChildren.reserve(ChildVariants.size());
4540     for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
4541       NewChildren.push_back(ChildVariants[i][Idxs[i]]);
4542     TreePatternNodePtr R = makeIntrusiveRefCnt<TreePatternNode>(
4543         Orig->getOperator(), std::move(NewChildren), Orig->getNumTypes());
4544 
4545     // Copy over properties.
4546     R->setName(Orig->getName());
4547     R->setNamesAsPredicateArg(Orig->getNamesAsPredicateArg());
4548     R->setPredicateCalls(Orig->getPredicateCalls());
4549     R->setGISelFlagsRecord(Orig->getGISelFlagsRecord());
4550     R->setTransformFn(Orig->getTransformFn());
4551     for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
4552       R->setType(i, Orig->getExtType(i));
4553 
4554     // If this pattern cannot match, do not include it as a variant.
4555     std::string ErrString;
4556     // Scan to see if this pattern has already been emitted.  We can get
4557     // duplication due to things like commuting:
4558     //   (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4559     // which are the same pattern.  Ignore the dups.
4560     if (R->canPatternMatch(ErrString, CDP) &&
4561         none_of(OutVariants, [&](TreePatternNodePtr Variant) {
4562           return R->isIsomorphicTo(*Variant, DepVars);
4563         }))
4564       OutVariants.push_back(R);
4565 
4566     // Increment indices to the next permutation by incrementing the
4567     // indices from last index backward, e.g., generate the sequence
4568     // [0, 0], [0, 1], [1, 0], [1, 1].
4569     int IdxsIdx;
4570     for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
4571       if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
4572         Idxs[IdxsIdx] = 0;
4573       else
4574         break;
4575     }
4576     NotDone = (IdxsIdx >= 0);
4577   } while (NotDone);
4578 }
4579 
4580 /// CombineChildVariants - A helper function for binary operators.
4581 ///
4582 static void CombineChildVariants(TreePatternNodePtr Orig,
4583                                  const std::vector<TreePatternNodePtr> &LHS,
4584                                  const std::vector<TreePatternNodePtr> &RHS,
4585                                  std::vector<TreePatternNodePtr> &OutVariants,
4586                                  CodeGenDAGPatterns &CDP,
4587                                  const MultipleUseVarSet &DepVars) {
4588   std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
4589   ChildVariants.push_back(LHS);
4590   ChildVariants.push_back(RHS);
4591   CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
4592 }
4593 
4594 static void
4595 GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N,
4596                                   std::vector<TreePatternNodePtr> &Children) {
4597   assert(N->getNumChildren() == 2 &&
4598          "Associative but doesn't have 2 children!");
4599   Record *Operator = N->getOperator();
4600 
4601   // Only permit raw nodes.
4602   if (!N->getName().empty() || !N->getPredicateCalls().empty() ||
4603       N->getTransformFn()) {
4604     Children.push_back(N);
4605     return;
4606   }
4607 
4608   if (N->getChild(0).isLeaf() || N->getChild(0).getOperator() != Operator)
4609     Children.push_back(N->getChildShared(0));
4610   else
4611     GatherChildrenOfAssociativeOpcode(N->getChildShared(0), Children);
4612 
4613   if (N->getChild(1).isLeaf() || N->getChild(1).getOperator() != Operator)
4614     Children.push_back(N->getChildShared(1));
4615   else
4616     GatherChildrenOfAssociativeOpcode(N->getChildShared(1), Children);
4617 }
4618 
4619 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4620 /// the (potentially recursive) pattern by using algebraic laws.
4621 ///
4622 static void GenerateVariantsOf(TreePatternNodePtr N,
4623                                std::vector<TreePatternNodePtr> &OutVariants,
4624                                CodeGenDAGPatterns &CDP,
4625                                const MultipleUseVarSet &DepVars) {
4626   // We cannot permute leaves or ComplexPattern uses.
4627   if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
4628     OutVariants.push_back(N);
4629     return;
4630   }
4631 
4632   // Look up interesting info about the node.
4633   const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
4634 
4635   // If this node is associative, re-associate.
4636   if (NodeInfo.hasProperty(SDNPAssociative)) {
4637     // Re-associate by pulling together all of the linked operators
4638     std::vector<TreePatternNodePtr> MaximalChildren;
4639     GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
4640 
4641     // Only handle child sizes of 3.  Otherwise we'll end up trying too many
4642     // permutations.
4643     if (MaximalChildren.size() == 3) {
4644       // Find the variants of all of our maximal children.
4645       std::vector<TreePatternNodePtr> AVariants, BVariants, CVariants;
4646       GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
4647       GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
4648       GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
4649 
4650       // There are only two ways we can permute the tree:
4651       //   (A op B) op C    and    A op (B op C)
4652       // Within these forms, we can also permute A/B/C.
4653 
4654       // Generate legal pair permutations of A/B/C.
4655       std::vector<TreePatternNodePtr> ABVariants;
4656       std::vector<TreePatternNodePtr> BAVariants;
4657       std::vector<TreePatternNodePtr> ACVariants;
4658       std::vector<TreePatternNodePtr> CAVariants;
4659       std::vector<TreePatternNodePtr> BCVariants;
4660       std::vector<TreePatternNodePtr> CBVariants;
4661       CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4662       CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4663       CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4664       CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4665       CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4666       CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
4667 
4668       // Combine those into the result: (x op x) op x
4669       CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4670       CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4671       CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4672       CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4673       CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4674       CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
4675 
4676       // Combine those into the result: x op (x op x)
4677       CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4678       CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4679       CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4680       CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4681       CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4682       CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
4683       return;
4684     }
4685   }
4686 
4687   // Compute permutations of all children.
4688   std::vector<std::vector<TreePatternNodePtr>> ChildVariants(
4689       N->getNumChildren());
4690   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
4691     GenerateVariantsOf(N->getChildShared(i), ChildVariants[i], CDP, DepVars);
4692 
4693   // Build all permutations based on how the children were formed.
4694   CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
4695 
4696   // If this node is commutative, consider the commuted order.
4697   bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4698   if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
4699     unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
4700     assert(N->getNumChildren() >= (2 + Skip) &&
4701            "Commutative but doesn't have 2 children!");
4702     // Don't allow commuting children which are actually register references.
4703     bool NoRegisters = true;
4704     unsigned i = 0 + Skip;
4705     unsigned e = 2 + Skip;
4706     for (; i != e; ++i) {
4707       TreePatternNode &Child = N->getChild(i);
4708       if (Child.isLeaf())
4709         if (DefInit *DI = dyn_cast<DefInit>(Child.getLeafValue())) {
4710           Record *RR = DI->getDef();
4711           if (RR->isSubClassOf("Register"))
4712             NoRegisters = false;
4713         }
4714     }
4715     // Consider the commuted order.
4716     if (NoRegisters) {
4717       // Swap the first two operands after the intrinsic id, if present.
4718       unsigned i = isCommIntrinsic ? 1 : 0;
4719       std::swap(ChildVariants[i], ChildVariants[i + 1]);
4720       CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
4721     }
4722   }
4723 }
4724 
4725 // GenerateVariants - Generate variants.  For example, commutative patterns can
4726 // match multiple ways.  Add them to PatternsToMatch as well.
4727 void CodeGenDAGPatterns::GenerateVariants() {
4728   LLVM_DEBUG(errs() << "Generating instruction variants.\n");
4729 
4730   // Loop over all of the patterns we've collected, checking to see if we can
4731   // generate variants of the instruction, through the exploitation of
4732   // identities.  This permits the target to provide aggressive matching without
4733   // the .td file having to contain tons of variants of instructions.
4734   //
4735   // Note that this loop adds new patterns to the PatternsToMatch list, but we
4736   // intentionally do not reconsider these.  Any variants of added patterns have
4737   // already been added.
4738   //
4739   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
4740     MultipleUseVarSet DepVars;
4741     std::vector<TreePatternNodePtr> Variants;
4742     FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
4743     LLVM_DEBUG(errs() << "Dependent/multiply used variables: ");
4744     LLVM_DEBUG(DumpDepVars(DepVars));
4745     LLVM_DEBUG(errs() << "\n");
4746     GenerateVariantsOf(PatternsToMatch[i].getSrcPatternShared(), Variants,
4747                        *this, DepVars);
4748 
4749     assert(PatternsToMatch[i].getHwModeFeatures().empty() &&
4750            "HwModes should not have been expanded yet!");
4751 
4752     assert(!Variants.empty() && "Must create at least original variant!");
4753     if (Variants.size() == 1) // No additional variants for this pattern.
4754       continue;
4755 
4756     LLVM_DEBUG(errs() << "FOUND VARIANTS OF: ";
4757                PatternsToMatch[i].getSrcPattern().dump(); errs() << "\n");
4758 
4759     for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
4760       TreePatternNodePtr Variant = Variants[v];
4761 
4762       LLVM_DEBUG(errs() << "  VAR#" << v << ": "; Variant->dump();
4763                  errs() << "\n");
4764 
4765       // Scan to see if an instruction or explicit pattern already matches this.
4766       bool AlreadyExists = false;
4767       for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
4768         // Skip if the top level predicates do not match.
4769         if ((i != p) && (PatternsToMatch[i].getPredicates() !=
4770                          PatternsToMatch[p].getPredicates()))
4771           continue;
4772         // Check to see if this variant already exists.
4773         if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
4774                                     DepVars)) {
4775           LLVM_DEBUG(errs() << "  *** ALREADY EXISTS, ignoring variant.\n");
4776           AlreadyExists = true;
4777           break;
4778         }
4779       }
4780       // If we already have it, ignore the variant.
4781       if (AlreadyExists)
4782         continue;
4783 
4784       // Otherwise, add it to the list of patterns we have.
4785       PatternsToMatch.emplace_back(
4786           PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
4787           Variant, PatternsToMatch[i].getDstPatternShared(),
4788           PatternsToMatch[i].getDstRegs(),
4789           PatternsToMatch[i].getAddedComplexity(), Record::getNewUID(Records),
4790           PatternsToMatch[i].getGISelShouldIgnore(),
4791           PatternsToMatch[i].getHwModeFeatures());
4792     }
4793 
4794     LLVM_DEBUG(errs() << "\n");
4795   }
4796 }
4797