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