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