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