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