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