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