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