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