1 //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the CodeGenDAGPatterns class, which is used to read and
11 // represent the patterns present in a .td file for instructions.
13 //===----------------------------------------------------------------------===//
15 #include "CodeGenDAGPatterns.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/TableGen/Error.h"
26 #include "llvm/TableGen/Record.h"
32 #define DEBUG_TYPE "dag-patterns"
34 static inline bool isIntegerOrPtr(MVT VT) {
35 return VT.isInteger() || VT == MVT::iPTR;
37 static inline bool isFloatingPoint(MVT VT) {
38 return VT.isFloatingPoint();
40 static inline bool isVector(MVT VT) {
43 static inline bool isScalar(MVT VT) {
44 return !VT.isVector();
47 template <typename Predicate>
48 static bool berase_if(MachineValueTypeSet &S, Predicate P) {
50 // It is ok to iterate over MachineValueTypeSet and remove elements from it
61 // --- TypeSetByHwMode
63 // This is a parameterized type-set class. For each mode there is a list
64 // of types that are currently possible for a given tree node. Type
65 // inference will apply to each mode separately.
67 TypeSetByHwMode::TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList) {
68 for (const ValueTypeByHwMode &VVT : VTList)
72 bool TypeSetByHwMode::isValueTypeByHwMode(bool AllowEmpty) const {
73 for (const auto &I : *this) {
74 if (I.second.size() > 1)
76 if (!AllowEmpty && I.second.empty())
82 ValueTypeByHwMode TypeSetByHwMode::getValueTypeByHwMode() const {
83 assert(isValueTypeByHwMode(true) &&
84 "The type set has multiple types for at least one HW mode");
85 ValueTypeByHwMode VVT;
86 for (const auto &I : *this) {
87 MVT T = I.second.empty() ? MVT::Other : *I.second.begin();
88 VVT.getOrCreateTypeForMode(I.first, T);
93 bool TypeSetByHwMode::isPossible() const {
94 for (const auto &I : *this)
95 if (!I.second.empty())
100 bool TypeSetByHwMode::insert(const ValueTypeByHwMode &VVT) {
101 bool Changed = false;
102 SmallDenseSet<unsigned, 4> Modes;
103 for (const auto &P : VVT) {
104 unsigned M = P.first;
106 // Make sure there exists a set for each specific mode from VVT.
107 Changed |= getOrCreate(M).insert(P.second).second;
110 // If VVT has a default mode, add the corresponding type to all
111 // modes in "this" that do not exist in VVT.
112 if (Modes.count(DefaultMode)) {
113 MVT DT = VVT.getType(DefaultMode);
114 for (auto &I : *this)
115 if (!Modes.count(I.first))
116 Changed |= I.second.insert(DT).second;
121 // Constrain the type set to be the intersection with VTS.
122 bool TypeSetByHwMode::constrain(const TypeSetByHwMode &VTS) {
123 bool Changed = false;
125 for (const auto &I : VTS) {
126 unsigned M = I.first;
127 if (M == DefaultMode || hasMode(M))
129 Map.insert({M, Map.at(DefaultMode)});
134 for (auto &I : *this) {
135 unsigned M = I.first;
136 SetType &S = I.second;
137 if (VTS.hasMode(M) || VTS.hasDefault()) {
138 Changed |= intersect(I.second, VTS.get(M));
139 } else if (!S.empty()) {
147 template <typename Predicate>
148 bool TypeSetByHwMode::constrain(Predicate P) {
149 bool Changed = false;
150 for (auto &I : *this)
151 Changed |= berase_if(I.second, [&P](MVT VT) { return !P(VT); });
155 template <typename Predicate>
156 bool TypeSetByHwMode::assign_if(const TypeSetByHwMode &VTS, Predicate P) {
158 for (const auto &I : VTS) {
159 SetType &S = getOrCreate(I.first);
160 for (auto J : I.second)
167 void TypeSetByHwMode::writeToStream(raw_ostream &OS) const {
168 SmallVector<unsigned, 4> Modes;
169 Modes.reserve(Map.size());
171 for (const auto &I : *this)
172 Modes.push_back(I.first);
177 array_pod_sort(Modes.begin(), Modes.end());
180 for (unsigned M : Modes) {
181 OS << ' ' << getModeName(M) << ':';
182 writeToStream(get(M), OS);
187 void TypeSetByHwMode::writeToStream(const SetType &S, raw_ostream &OS) {
188 SmallVector<MVT, 4> Types(S.begin(), S.end());
189 array_pod_sort(Types.begin(), Types.end());
192 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
193 OS << ValueTypeByHwMode::getMVTName(Types[i]);
200 bool TypeSetByHwMode::operator==(const TypeSetByHwMode &VTS) const {
201 bool HaveDefault = hasDefault();
202 if (HaveDefault != VTS.hasDefault())
207 return *begin() == *VTS.begin();
211 SmallDenseSet<unsigned, 4> Modes;
212 for (auto &I : *this)
213 Modes.insert(I.first);
214 for (const auto &I : VTS)
215 Modes.insert(I.first);
218 // Both sets have default mode.
219 for (unsigned M : Modes) {
220 if (get(M) != VTS.get(M))
224 // Neither set has default mode.
225 for (unsigned M : Modes) {
226 // If there is no default mode, an empty set is equivalent to not having
227 // the corresponding mode.
228 bool NoModeThis = !hasMode(M) || get(M).empty();
229 bool NoModeVTS = !VTS.hasMode(M) || VTS.get(M).empty();
230 if (NoModeThis != NoModeVTS)
233 if (get(M) != VTS.get(M))
242 raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T) {
249 void TypeSetByHwMode::dump() const {
250 dbgs() << *this << '\n';
253 bool TypeSetByHwMode::intersect(SetType &Out, const SetType &In) {
254 bool OutP = Out.count(MVT::iPTR), InP = In.count(MVT::iPTR);
255 auto Int = [&In](MVT T) -> bool { return !In.count(T); };
258 return berase_if(Out, Int);
260 // Compute the intersection of scalars separately to account for only
261 // one set containing iPTR.
262 // The itersection of iPTR with a set of integer scalar types that does not
263 // include iPTR will result in the most specific scalar type:
264 // - iPTR is more specific than any set with two elements or more
265 // - iPTR is less specific than any single integer scalar type.
267 // { iPTR } * { i32 } -> { i32 }
268 // { iPTR } * { i32 i64 } -> { iPTR }
270 // { iPTR i32 } * { i32 } -> { i32 }
271 // { iPTR i32 } * { i32 i64 } -> { i32 i64 }
272 // { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 }
274 // Compute the difference between the two sets in such a way that the
275 // iPTR is in the set that is being subtracted. This is to see if there
276 // are any extra scalars in the set without iPTR that are not in the
277 // set containing iPTR. Then the iPTR could be considered a "wildcard"
278 // matching these scalars. If there is only one such scalar, it would
279 // replace the iPTR, if there are more, the iPTR would be retained.
283 berase_if(Diff, [&In](MVT T) { return In.count(T); });
284 // Pre-remove these elements and rely only on InP/OutP to determine
285 // whether a change has been made.
286 berase_if(Out, [&Diff](MVT T) { return Diff.count(T); });
289 berase_if(Diff, [&Out](MVT T) { return Out.count(T); });
290 Out.erase(MVT::iPTR);
293 // The actual intersection.
294 bool Changed = berase_if(Out, Int);
295 unsigned NumD = Diff.size();
300 Out.insert(*Diff.begin());
301 // This is a change only if Out was the one with iPTR (which is now
305 // Multiple elements from Out are now replaced with iPTR.
306 Out.insert(MVT::iPTR);
312 bool TypeSetByHwMode::validate() const {
316 bool AllEmpty = true;
317 for (const auto &I : *this)
318 AllEmpty &= I.second.empty();
326 bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,
327 const TypeSetByHwMode &In) {
328 ValidateOnExit _1(Out, *this);
330 if (In.empty() || Out == In || TP.hasError())
337 bool Changed = Out.constrain(In);
338 if (Changed && Out.empty())
339 TP.error("Type contradiction");
344 bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) {
345 ValidateOnExit _1(Out, *this);
348 assert(!Out.empty() && "cannot pick from an empty set");
350 bool Changed = false;
351 for (auto &I : Out) {
352 TypeSetByHwMode::SetType &S = I.second;
355 MVT T = *S.begin(); // Pick the first element.
363 bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) {
364 ValidateOnExit _1(Out, *this);
368 return Out.constrain(isIntegerOrPtr);
370 return Out.assign_if(getLegalTypes(), isIntegerOrPtr);
373 bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode &Out) {
374 ValidateOnExit _1(Out, *this);
378 return Out.constrain(isFloatingPoint);
380 return Out.assign_if(getLegalTypes(), isFloatingPoint);
383 bool TypeInfer::EnforceScalar(TypeSetByHwMode &Out) {
384 ValidateOnExit _1(Out, *this);
388 return Out.constrain(isScalar);
390 return Out.assign_if(getLegalTypes(), isScalar);
393 bool TypeInfer::EnforceVector(TypeSetByHwMode &Out) {
394 ValidateOnExit _1(Out, *this);
398 return Out.constrain(isVector);
400 return Out.assign_if(getLegalTypes(), isVector);
403 bool TypeInfer::EnforceAny(TypeSetByHwMode &Out) {
404 ValidateOnExit _1(Out, *this);
405 if (TP.hasError() || !Out.empty())
408 Out = getLegalTypes();
412 template <typename Iter, typename Pred, typename Less>
413 static Iter min_if(Iter B, Iter E, Pred P, Less L) {
417 for (Iter I = B; I != E; ++I) {
420 if (Min == E || L(*I, *Min))
426 template <typename Iter, typename Pred, typename Less>
427 static Iter max_if(Iter B, Iter E, Pred P, Less L) {
431 for (Iter I = B; I != E; ++I) {
434 if (Max == E || L(*Max, *I))
440 /// Make sure that for each type in Small, there exists a larger type in Big.
441 bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode &Small,
442 TypeSetByHwMode &Big) {
443 ValidateOnExit _1(Small, *this), _2(Big, *this);
446 bool Changed = false;
449 Changed |= EnforceAny(Small);
451 Changed |= EnforceAny(Big);
453 assert(Small.hasDefault() && Big.hasDefault());
455 std::vector<unsigned> Modes = union_modes(Small, Big);
457 // 1. Only allow integer or floating point types and make sure that
458 // both sides are both integer or both floating point.
459 // 2. Make sure that either both sides have vector types, or neither
461 for (unsigned M : Modes) {
462 TypeSetByHwMode::SetType &S = Small.get(M);
463 TypeSetByHwMode::SetType &B = Big.get(M);
465 if (any_of(S, isIntegerOrPtr) && any_of(S, isIntegerOrPtr)) {
466 auto NotInt = [](MVT VT) { return !isIntegerOrPtr(VT); };
467 Changed |= berase_if(S, NotInt) |
468 berase_if(B, NotInt);
469 } else if (any_of(S, isFloatingPoint) && any_of(B, isFloatingPoint)) {
470 auto NotFP = [](MVT VT) { return !isFloatingPoint(VT); };
471 Changed |= berase_if(S, NotFP) |
473 } else if (S.empty() || B.empty()) {
474 Changed = !S.empty() || !B.empty();
478 TP.error("Incompatible types");
482 if (none_of(S, isVector) || none_of(B, isVector)) {
483 Changed |= berase_if(S, isVector) |
484 berase_if(B, isVector);
488 auto LT = [](MVT A, MVT B) -> bool {
489 return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
490 (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
491 A.getSizeInBits() < B.getSizeInBits());
493 auto LE = [](MVT A, MVT B) -> bool {
494 // This function is used when removing elements: when a vector is compared
495 // to a non-vector, it should return false (to avoid removal).
496 if (A.isVector() != B.isVector())
499 // Note on the < comparison below:
500 // X86 has patterns like
501 // (set VR128X:$dst, (v16i8 (X86vtrunc (v4i32 VR128X:$src1)))),
502 // where the truncated vector is given a type v16i8, while the source
503 // vector has type v4i32. They both have the same size in bits.
504 // The minimal type in the result is obviously v16i8, and when we remove
505 // all types from the source that are smaller-or-equal than v8i16, the
506 // only source type would also be removed (since it's equal in size).
507 return A.getScalarSizeInBits() <= B.getScalarSizeInBits() ||
508 A.getSizeInBits() < B.getSizeInBits();
511 for (unsigned M : Modes) {
512 TypeSetByHwMode::SetType &S = Small.get(M);
513 TypeSetByHwMode::SetType &B = Big.get(M);
514 // MinS = min scalar in Small, remove all scalars from Big that are
515 // smaller-or-equal than MinS.
516 auto MinS = min_if(S.begin(), S.end(), isScalar, LT);
518 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinS));
520 // MaxS = max scalar in Big, remove all scalars from Small that are
522 auto MaxS = max_if(B.begin(), B.end(), isScalar, LT);
524 Changed |= berase_if(S, std::bind(LE, *MaxS, std::placeholders::_1));
526 // MinV = min vector in Small, remove all vectors from Big that are
527 // smaller-or-equal than MinV.
528 auto MinV = min_if(S.begin(), S.end(), isVector, LT);
530 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinV));
532 // MaxV = max vector in Big, remove all vectors from Small that are
534 auto MaxV = max_if(B.begin(), B.end(), isVector, LT);
536 Changed |= berase_if(S, std::bind(LE, *MaxV, std::placeholders::_1));
542 /// 1. Ensure that for each type T in Vec, T is a vector type, and that
543 /// for each type U in Elem, U is a scalar type.
544 /// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)
545 /// type T in Vec, such that U is the element type of T.
546 bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
547 TypeSetByHwMode &Elem) {
548 ValidateOnExit _1(Vec, *this), _2(Elem, *this);
551 bool Changed = false;
554 Changed |= EnforceVector(Vec);
556 Changed |= EnforceScalar(Elem);
558 for (unsigned M : union_modes(Vec, Elem)) {
559 TypeSetByHwMode::SetType &V = Vec.get(M);
560 TypeSetByHwMode::SetType &E = Elem.get(M);
562 Changed |= berase_if(V, isScalar); // Scalar = !vector
563 Changed |= berase_if(E, isVector); // Vector = !scalar
564 assert(!V.empty() && !E.empty());
566 SmallSet<MVT,4> VT, ST;
567 // Collect element types from the "vector" set.
569 VT.insert(T.getVectorElementType());
570 // Collect scalar types from the "element" set.
574 // Remove from V all (vector) types whose element type is not in S.
575 Changed |= berase_if(V, [&ST](MVT T) -> bool {
576 return !ST.count(T.getVectorElementType());
578 // Remove from E all (scalar) types, for which there is no corresponding
580 Changed |= berase_if(E, [&VT](MVT T) -> bool { return !VT.count(T); });
586 bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
587 const ValueTypeByHwMode &VVT) {
588 TypeSetByHwMode Tmp(VVT);
589 ValidateOnExit _1(Vec, *this), _2(Tmp, *this);
590 return EnforceVectorEltTypeIs(Vec, Tmp);
593 /// Ensure that for each type T in Sub, T is a vector type, and there
594 /// exists a type U in Vec such that U is a vector type with the same
595 /// element type as T and at least as many elements as T.
596 bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
597 TypeSetByHwMode &Sub) {
598 ValidateOnExit _1(Vec, *this), _2(Sub, *this);
602 /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.
603 auto IsSubVec = [](MVT B, MVT P) -> bool {
604 if (!B.isVector() || !P.isVector())
606 // Logically a <4 x i32> is a valid subvector of <n x 4 x i32>
607 // but until there are obvious use-cases for this, keep the
609 if (B.isScalableVector() != P.isScalableVector())
611 if (B.getVectorElementType() != P.getVectorElementType())
613 return B.getVectorNumElements() < P.getVectorNumElements();
616 /// Return true if S has no element (vector type) that T is a sub-vector of,
617 /// i.e. has the same element type as T and more elements.
618 auto NoSubV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
619 for (const auto &I : S)
625 /// Return true if S has no element (vector type) that T is a super-vector
626 /// of, i.e. has the same element type as T and fewer elements.
627 auto NoSupV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
628 for (const auto &I : S)
634 bool Changed = false;
637 Changed |= EnforceVector(Vec);
639 Changed |= EnforceVector(Sub);
641 for (unsigned M : union_modes(Vec, Sub)) {
642 TypeSetByHwMode::SetType &S = Sub.get(M);
643 TypeSetByHwMode::SetType &V = Vec.get(M);
645 Changed |= berase_if(S, isScalar);
647 // Erase all types from S that are not sub-vectors of a type in V.
648 Changed |= berase_if(S, std::bind(NoSubV, V, std::placeholders::_1));
650 // Erase all types from V that are not super-vectors of a type in S.
651 Changed |= berase_if(V, std::bind(NoSupV, S, std::placeholders::_1));
657 /// 1. Ensure that V has a scalar type iff W has a scalar type.
658 /// 2. Ensure that for each vector type T in V, there exists a vector
659 /// type U in W, such that T and U have the same number of elements.
660 /// 3. Ensure that for each vector type U in W, there exists a vector
661 /// type T in V, such that T and U have the same number of elements
663 bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) {
664 ValidateOnExit _1(V, *this), _2(W, *this);
668 bool Changed = false;
670 Changed |= EnforceAny(V);
672 Changed |= EnforceAny(W);
674 // An actual vector type cannot have 0 elements, so we can treat scalars
675 // as zero-length vectors. This way both vectors and scalars can be
676 // processed identically.
677 auto NoLength = [](const SmallSet<unsigned,2> &Lengths, MVT T) -> bool {
678 return !Lengths.count(T.isVector() ? T.getVectorNumElements() : 0);
681 for (unsigned M : union_modes(V, W)) {
682 TypeSetByHwMode::SetType &VS = V.get(M);
683 TypeSetByHwMode::SetType &WS = W.get(M);
685 SmallSet<unsigned,2> VN, WN;
687 VN.insert(T.isVector() ? T.getVectorNumElements() : 0);
689 WN.insert(T.isVector() ? T.getVectorNumElements() : 0);
691 Changed |= berase_if(VS, std::bind(NoLength, WN, std::placeholders::_1));
692 Changed |= berase_if(WS, std::bind(NoLength, VN, std::placeholders::_1));
697 /// 1. Ensure that for each type T in A, there exists a type U in B,
698 /// such that T and U have equal size in bits.
699 /// 2. Ensure that for each type U in B, there exists a type T in A
700 /// such that T and U have equal size in bits (reverse of 1).
701 bool TypeInfer::EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B) {
702 ValidateOnExit _1(A, *this), _2(B, *this);
705 bool Changed = false;
707 Changed |= EnforceAny(A);
709 Changed |= EnforceAny(B);
711 auto NoSize = [](const SmallSet<unsigned,2> &Sizes, MVT T) -> bool {
712 return !Sizes.count(T.getSizeInBits());
715 for (unsigned M : union_modes(A, B)) {
716 TypeSetByHwMode::SetType &AS = A.get(M);
717 TypeSetByHwMode::SetType &BS = B.get(M);
718 SmallSet<unsigned,2> AN, BN;
721 AN.insert(T.getSizeInBits());
723 BN.insert(T.getSizeInBits());
725 Changed |= berase_if(AS, std::bind(NoSize, BN, std::placeholders::_1));
726 Changed |= berase_if(BS, std::bind(NoSize, AN, std::placeholders::_1));
732 void TypeInfer::expandOverloads(TypeSetByHwMode &VTS) {
733 ValidateOnExit _1(VTS, *this);
734 TypeSetByHwMode Legal = getLegalTypes();
735 bool HaveLegalDef = Legal.hasDefault();
737 for (auto &I : VTS) {
738 unsigned M = I.first;
739 if (!Legal.hasMode(M) && !HaveLegalDef) {
740 TP.error("Invalid mode " + Twine(M));
743 expandOverloads(I.second, Legal.get(M));
747 void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out,
748 const TypeSetByHwMode::SetType &Legal) {
751 if (!T.isOverloaded())
755 // MachineValueTypeSet allows iteration and erasing.
760 switch (Ov.SimpleTy) {
762 Out.insert(MVT::iPTR);
765 for (MVT T : MVT::integer_valuetypes())
768 for (MVT T : MVT::integer_vector_valuetypes())
773 for (MVT T : MVT::fp_valuetypes())
776 for (MVT T : MVT::fp_vector_valuetypes())
781 for (MVT T : MVT::vector_valuetypes())
786 for (MVT T : MVT::all_valuetypes())
796 TypeSetByHwMode TypeInfer::getLegalTypes() {
797 if (!LegalTypesCached) {
798 // Stuff all types from all modes into the default mode.
799 const TypeSetByHwMode <S = TP.getDAGPatterns().getLegalTypes();
800 for (const auto &I : LTS)
801 LegalCache.insert(I.second);
802 LegalTypesCached = true;
805 VTS.getOrCreate(DefaultMode) = LegalCache;
810 TypeInfer::ValidateOnExit::~ValidateOnExit() {
811 if (!VTS.validate()) {
812 dbgs() << "Type set is empty for each HW mode:\n"
813 "possible type contradiction in the pattern below "
814 "(use -print-records with llvm-tblgen to see all "
815 "expanded records).\n";
817 llvm_unreachable(nullptr);
822 //===----------------------------------------------------------------------===//
823 // TreePredicateFn Implementation
824 //===----------------------------------------------------------------------===//
826 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
827 TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
829 (!hasPredCode() || !hasImmCode()) &&
830 ".td file corrupt: can't have a node predicate *and* an imm predicate");
833 bool TreePredicateFn::hasPredCode() const {
834 return isLoad() || isStore() || isAtomic() ||
835 !PatFragRec->getRecord()->getValueAsString("PredicateCode").empty();
838 std::string TreePredicateFn::getPredCode() const {
839 std::string Code = "";
841 if (!isLoad() && !isStore() && !isAtomic()) {
842 Record *MemoryVT = getMemoryVT();
845 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
846 "MemoryVT requires IsLoad or IsStore");
849 if (!isLoad() && !isStore()) {
851 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
852 "IsUnindexed requires IsLoad or IsStore");
854 Record *ScalarMemoryVT = getScalarMemoryVT();
857 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
858 "ScalarMemoryVT requires IsLoad or IsStore");
861 if (isLoad() + isStore() + isAtomic() > 1)
862 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
863 "IsLoad, IsStore, and IsAtomic are mutually exclusive");
866 if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&
867 !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&
868 getScalarMemoryVT() == nullptr)
869 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
870 "IsLoad cannot be used by itself");
873 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
874 "IsNonExtLoad requires IsLoad");
876 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
877 "IsAnyExtLoad requires IsLoad");
879 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
880 "IsSignExtLoad requires IsLoad");
882 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
883 "IsZeroExtLoad requires IsLoad");
887 if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&
888 getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr)
889 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
890 "IsStore cannot be used by itself");
892 if (isNonTruncStore())
893 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
894 "IsNonTruncStore requires IsStore");
896 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
897 "IsTruncStore requires IsStore");
901 if (getMemoryVT() == nullptr && !isAtomicOrderingMonotonic() &&
902 !isAtomicOrderingAcquire() && !isAtomicOrderingRelease() &&
903 !isAtomicOrderingAcquireRelease() &&
904 !isAtomicOrderingSequentiallyConsistent() &&
905 !isAtomicOrderingAcquireOrStronger() &&
906 !isAtomicOrderingReleaseOrStronger() &&
907 !isAtomicOrderingWeakerThanAcquire() &&
908 !isAtomicOrderingWeakerThanRelease())
909 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
910 "IsAtomic cannot be used by itself");
912 if (isAtomicOrderingMonotonic())
913 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
914 "IsAtomicOrderingMonotonic requires IsAtomic");
915 if (isAtomicOrderingAcquire())
916 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
917 "IsAtomicOrderingAcquire requires IsAtomic");
918 if (isAtomicOrderingRelease())
919 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
920 "IsAtomicOrderingRelease requires IsAtomic");
921 if (isAtomicOrderingAcquireRelease())
922 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
923 "IsAtomicOrderingAcquireRelease requires IsAtomic");
924 if (isAtomicOrderingSequentiallyConsistent())
925 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
926 "IsAtomicOrderingSequentiallyConsistent requires IsAtomic");
927 if (isAtomicOrderingAcquireOrStronger())
928 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
929 "IsAtomicOrderingAcquireOrStronger requires IsAtomic");
930 if (isAtomicOrderingReleaseOrStronger())
931 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
932 "IsAtomicOrderingReleaseOrStronger requires IsAtomic");
933 if (isAtomicOrderingWeakerThanAcquire())
934 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
935 "IsAtomicOrderingWeakerThanAcquire requires IsAtomic");
938 if (isLoad() || isStore() || isAtomic()) {
939 StringRef SDNodeName =
940 isLoad() ? "LoadSDNode" : isStore() ? "StoreSDNode" : "AtomicSDNode";
942 Record *MemoryVT = getMemoryVT();
945 Code += ("if (cast<" + SDNodeName + ">(N)->getMemoryVT() != MVT::" +
946 MemoryVT->getName() + ") return false;\n")
950 if (isAtomic() && isAtomicOrderingMonotonic())
951 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
952 "AtomicOrdering::Monotonic) return false;\n";
953 if (isAtomic() && isAtomicOrderingAcquire())
954 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
955 "AtomicOrdering::Acquire) return false;\n";
956 if (isAtomic() && isAtomicOrderingRelease())
957 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
958 "AtomicOrdering::Release) return false;\n";
959 if (isAtomic() && isAtomicOrderingAcquireRelease())
960 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
961 "AtomicOrdering::AcquireRelease) return false;\n";
962 if (isAtomic() && isAtomicOrderingSequentiallyConsistent())
963 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
964 "AtomicOrdering::SequentiallyConsistent) return false;\n";
966 if (isAtomic() && isAtomicOrderingAcquireOrStronger())
967 Code += "if (!isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
969 if (isAtomic() && isAtomicOrderingWeakerThanAcquire())
970 Code += "if (isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
973 if (isAtomic() && isAtomicOrderingReleaseOrStronger())
974 Code += "if (!isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
976 if (isAtomic() && isAtomicOrderingWeakerThanRelease())
977 Code += "if (isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
980 if (isLoad() || isStore()) {
981 StringRef SDNodeName = isLoad() ? "LoadSDNode" : "StoreSDNode";
984 Code += ("if (cast<" + SDNodeName +
985 ">(N)->getAddressingMode() != ISD::UNINDEXED) "
990 if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
991 isZeroExtLoad()) > 1)
992 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
993 "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
994 "IsZeroExtLoad are mutually exclusive");
996 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != "
997 "ISD::NON_EXTLOAD) return false;\n";
999 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
1001 if (isSignExtLoad())
1002 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
1004 if (isZeroExtLoad())
1005 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
1008 if ((isNonTruncStore() + isTruncStore()) > 1)
1010 getOrigPatFragRecord()->getRecord()->getLoc(),
1011 "IsNonTruncStore, and IsTruncStore are mutually exclusive");
1012 if (isNonTruncStore())
1014 " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1017 " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1020 Record *ScalarMemoryVT = getScalarMemoryVT();
1023 Code += ("if (cast<" + SDNodeName +
1024 ">(N)->getMemoryVT().getScalarType() != MVT::" +
1025 ScalarMemoryVT->getName() + ") return false;\n")
1029 std::string PredicateCode = PatFragRec->getRecord()->getValueAsString("PredicateCode");
1031 Code += PredicateCode;
1033 if (PredicateCode.empty() && !Code.empty())
1034 Code += "return true;\n";
1039 bool TreePredicateFn::hasImmCode() const {
1040 return !PatFragRec->getRecord()->getValueAsString("ImmediateCode").empty();
1043 std::string TreePredicateFn::getImmCode() const {
1044 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
1047 bool TreePredicateFn::immCodeUsesAPInt() const {
1048 return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
1051 bool TreePredicateFn::immCodeUsesAPFloat() const {
1053 // The return value will be false when IsAPFloat is unset.
1054 return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
1058 bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,
1062 getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field, Unset);
1065 return Result == Value;
1067 bool TreePredicateFn::isLoad() const {
1068 return isPredefinedPredicateEqualTo("IsLoad", true);
1070 bool TreePredicateFn::isStore() const {
1071 return isPredefinedPredicateEqualTo("IsStore", true);
1073 bool TreePredicateFn::isAtomic() const {
1074 return isPredefinedPredicateEqualTo("IsAtomic", true);
1076 bool TreePredicateFn::isUnindexed() const {
1077 return isPredefinedPredicateEqualTo("IsUnindexed", true);
1079 bool TreePredicateFn::isNonExtLoad() const {
1080 return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
1082 bool TreePredicateFn::isAnyExtLoad() const {
1083 return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
1085 bool TreePredicateFn::isSignExtLoad() const {
1086 return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
1088 bool TreePredicateFn::isZeroExtLoad() const {
1089 return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
1091 bool TreePredicateFn::isNonTruncStore() const {
1092 return isPredefinedPredicateEqualTo("IsTruncStore", false);
1094 bool TreePredicateFn::isTruncStore() const {
1095 return isPredefinedPredicateEqualTo("IsTruncStore", true);
1097 bool TreePredicateFn::isAtomicOrderingMonotonic() const {
1098 return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true);
1100 bool TreePredicateFn::isAtomicOrderingAcquire() const {
1101 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true);
1103 bool TreePredicateFn::isAtomicOrderingRelease() const {
1104 return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true);
1106 bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
1107 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true);
1109 bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
1110 return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent",
1113 bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {
1114 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", true);
1116 bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {
1117 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", false);
1119 bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {
1120 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", true);
1122 bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {
1123 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", false);
1125 Record *TreePredicateFn::getMemoryVT() const {
1126 Record *R = getOrigPatFragRecord()->getRecord();
1127 if (R->isValueUnset("MemoryVT"))
1129 return R->getValueAsDef("MemoryVT");
1131 Record *TreePredicateFn::getScalarMemoryVT() const {
1132 Record *R = getOrigPatFragRecord()->getRecord();
1133 if (R->isValueUnset("ScalarMemoryVT"))
1135 return R->getValueAsDef("ScalarMemoryVT");
1138 StringRef TreePredicateFn::getImmType() const {
1139 if (immCodeUsesAPInt())
1140 return "const APInt &";
1141 if (immCodeUsesAPFloat())
1142 return "const APFloat &";
1146 StringRef TreePredicateFn::getImmTypeIdentifier() const {
1147 if (immCodeUsesAPInt())
1149 else if (immCodeUsesAPFloat())
1154 /// isAlwaysTrue - Return true if this is a noop predicate.
1155 bool TreePredicateFn::isAlwaysTrue() const {
1156 return !hasPredCode() && !hasImmCode();
1159 /// Return the name to use in the generated code to reference this, this is
1160 /// "Predicate_foo" if from a pattern fragment "foo".
1161 std::string TreePredicateFn::getFnName() const {
1162 return "Predicate_" + PatFragRec->getRecord()->getName().str();
1165 /// getCodeToRunOnSDNode - Return the code for the function body that
1166 /// evaluates this predicate. The argument is expected to be in "Node",
1167 /// not N. This handles casting and conversion to a concrete node type as
1169 std::string TreePredicateFn::getCodeToRunOnSDNode() const {
1170 // Handle immediate predicates first.
1171 std::string ImmCode = getImmCode();
1172 if (!ImmCode.empty()) {
1174 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1175 "IsLoad cannot be used with ImmLeaf or its subclasses");
1177 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1178 "IsStore cannot be used with ImmLeaf or its subclasses");
1181 getOrigPatFragRecord()->getRecord()->getLoc(),
1182 "IsUnindexed cannot be used with ImmLeaf or its subclasses");
1185 getOrigPatFragRecord()->getRecord()->getLoc(),
1186 "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
1189 getOrigPatFragRecord()->getRecord()->getLoc(),
1190 "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
1191 if (isSignExtLoad())
1193 getOrigPatFragRecord()->getRecord()->getLoc(),
1194 "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
1195 if (isZeroExtLoad())
1197 getOrigPatFragRecord()->getRecord()->getLoc(),
1198 "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
1199 if (isNonTruncStore())
1201 getOrigPatFragRecord()->getRecord()->getLoc(),
1202 "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
1205 getOrigPatFragRecord()->getRecord()->getLoc(),
1206 "IsTruncStore cannot be used with ImmLeaf or its subclasses");
1208 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1209 "MemoryVT cannot be used with ImmLeaf or its subclasses");
1210 if (getScalarMemoryVT())
1212 getOrigPatFragRecord()->getRecord()->getLoc(),
1213 "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
1215 std::string Result = (" " + getImmType() + " Imm = ").str();
1216 if (immCodeUsesAPFloat())
1217 Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
1218 else if (immCodeUsesAPInt())
1219 Result += "cast<ConstantSDNode>(Node)->getAPIntValue();\n";
1221 Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n";
1222 return Result + ImmCode;
1225 // Handle arbitrary node predicates.
1226 assert(hasPredCode() && "Don't have any predicate code!");
1227 StringRef ClassName;
1228 if (PatFragRec->getOnlyTree()->isLeaf())
1229 ClassName = "SDNode";
1231 Record *Op = PatFragRec->getOnlyTree()->getOperator();
1232 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
1235 if (ClassName == "SDNode")
1236 Result = " SDNode *N = Node;\n";
1238 Result = " auto *N = cast<" + ClassName.str() + ">(Node);\n";
1240 return Result + getPredCode();
1243 //===----------------------------------------------------------------------===//
1244 // PatternToMatch implementation
1247 /// getPatternSize - Return the 'size' of this pattern. We want to match large
1248 /// patterns before small ones. This is used to determine the size of a
1250 static unsigned getPatternSize(const TreePatternNode *P,
1251 const CodeGenDAGPatterns &CGP) {
1252 unsigned Size = 3; // The node itself.
1253 // If the root node is a ConstantSDNode, increases its size.
1254 // e.g. (set R32:$dst, 0).
1255 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
1258 if (const ComplexPattern *AM = P->getComplexPatternInfo(CGP)) {
1259 Size += AM->getComplexity();
1260 // We don't want to count any children twice, so return early.
1264 // If this node has some predicate function that must match, it adds to the
1265 // complexity of this node.
1266 if (!P->getPredicateFns().empty())
1269 // Count children in the count if they are also nodes.
1270 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1271 const TreePatternNode *Child = P->getChild(i);
1272 if (!Child->isLeaf() && Child->getNumTypes()) {
1273 const TypeSetByHwMode &T0 = Child->getType(0);
1274 // At this point, all variable type sets should be simple, i.e. only
1275 // have a default mode.
1276 if (T0.getMachineValueType() != MVT::Other) {
1277 Size += getPatternSize(Child, CGP);
1281 if (Child->isLeaf()) {
1282 if (isa<IntInit>(Child->getLeafValue()))
1283 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
1284 else if (Child->getComplexPatternInfo(CGP))
1285 Size += getPatternSize(Child, CGP);
1286 else if (!Child->getPredicateFns().empty())
1294 /// Compute the complexity metric for the input pattern. This roughly
1295 /// corresponds to the number of nodes that are covered.
1296 int PatternToMatch::
1297 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
1298 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
1301 /// getPredicateCheck - Return a single string containing all of this
1302 /// pattern's predicates concatenated with "&&" operators.
1304 std::string PatternToMatch::getPredicateCheck() const {
1305 SmallVector<const Predicate*,4> PredList;
1306 for (const Predicate &P : Predicates)
1307 PredList.push_back(&P);
1308 std::sort(PredList.begin(), PredList.end(), deref<llvm::less>());
1311 for (unsigned i = 0, e = PredList.size(); i != e; ++i) {
1314 Check += '(' + PredList[i]->getCondString() + ')';
1319 //===----------------------------------------------------------------------===//
1320 // SDTypeConstraint implementation
1323 SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
1324 OperandNo = R->getValueAsInt("OperandNum");
1326 if (R->isSubClassOf("SDTCisVT")) {
1327 ConstraintType = SDTCisVT;
1328 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1329 for (const auto &P : VVT)
1330 if (P.second == MVT::isVoid)
1331 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
1332 } else if (R->isSubClassOf("SDTCisPtrTy")) {
1333 ConstraintType = SDTCisPtrTy;
1334 } else if (R->isSubClassOf("SDTCisInt")) {
1335 ConstraintType = SDTCisInt;
1336 } else if (R->isSubClassOf("SDTCisFP")) {
1337 ConstraintType = SDTCisFP;
1338 } else if (R->isSubClassOf("SDTCisVec")) {
1339 ConstraintType = SDTCisVec;
1340 } else if (R->isSubClassOf("SDTCisSameAs")) {
1341 ConstraintType = SDTCisSameAs;
1342 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
1343 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
1344 ConstraintType = SDTCisVTSmallerThanOp;
1345 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
1346 R->getValueAsInt("OtherOperandNum");
1347 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
1348 ConstraintType = SDTCisOpSmallerThanOp;
1349 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
1350 R->getValueAsInt("BigOperandNum");
1351 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
1352 ConstraintType = SDTCisEltOfVec;
1353 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
1354 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
1355 ConstraintType = SDTCisSubVecOfVec;
1356 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
1357 R->getValueAsInt("OtherOpNum");
1358 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
1359 ConstraintType = SDTCVecEltisVT;
1360 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1361 for (const auto &P : VVT) {
1364 PrintFatalError(R->getLoc(),
1365 "Cannot use vector type as SDTCVecEltisVT");
1366 if (!T.isInteger() && !T.isFloatingPoint())
1367 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
1368 "as SDTCVecEltisVT");
1370 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
1371 ConstraintType = SDTCisSameNumEltsAs;
1372 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
1373 R->getValueAsInt("OtherOperandNum");
1374 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
1375 ConstraintType = SDTCisSameSizeAs;
1376 x.SDTCisSameSizeAs_Info.OtherOperandNum =
1377 R->getValueAsInt("OtherOperandNum");
1379 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
1383 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
1384 /// N, and the result number in ResNo.
1385 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
1386 const SDNodeInfo &NodeInfo,
1388 unsigned NumResults = NodeInfo.getNumResults();
1389 if (OpNo < NumResults) {
1396 if (OpNo >= N->getNumChildren()) {
1398 raw_string_ostream OS(S);
1399 OS << "Invalid operand number in type constraint "
1400 << (OpNo+NumResults) << " ";
1402 PrintFatalError(OS.str());
1405 return N->getChild(OpNo);
1408 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
1409 /// constraint to the nodes operands. This returns true if it makes a
1410 /// change, false otherwise. If a type contradiction is found, flag an error.
1411 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
1412 const SDNodeInfo &NodeInfo,
1413 TreePattern &TP) const {
1417 unsigned ResNo = 0; // The result number being referenced.
1418 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
1419 TypeInfer &TI = TP.getInfer();
1421 switch (ConstraintType) {
1423 // Operand must be a particular type.
1424 return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
1426 // Operand must be same as target pointer type.
1427 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
1429 // Require it to be one of the legal integer VTs.
1430 return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
1432 // Require it to be one of the legal fp VTs.
1433 return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
1435 // Require it to be one of the legal vector VTs.
1436 return TI.EnforceVector(NodeToApply->getExtType(ResNo));
1437 case SDTCisSameAs: {
1438 unsigned OResNo = 0;
1439 TreePatternNode *OtherNode =
1440 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
1441 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1442 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
1444 case SDTCisVTSmallerThanOp: {
1445 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1446 // have an integer type that is smaller than the VT.
1447 if (!NodeToApply->isLeaf() ||
1448 !isa<DefInit>(NodeToApply->getLeafValue()) ||
1449 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
1450 ->isSubClassOf("ValueType")) {
1451 TP.error(N->getOperator()->getName() + " expects a VT operand!");
1454 DefInit *DI = static_cast<DefInit*>(NodeToApply->getLeafValue());
1455 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1456 auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
1457 TypeSetByHwMode TypeListTmp(VVT);
1459 unsigned OResNo = 0;
1460 TreePatternNode *OtherNode =
1461 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1464 return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo));
1466 case SDTCisOpSmallerThanOp: {
1467 unsigned BResNo = 0;
1468 TreePatternNode *BigOperand =
1469 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1471 return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
1472 BigOperand->getExtType(BResNo));
1474 case SDTCisEltOfVec: {
1475 unsigned VResNo = 0;
1476 TreePatternNode *VecOperand =
1477 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1479 // Filter vector types out of VecOperand that don't have the right element
1481 return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
1482 NodeToApply->getExtType(ResNo));
1484 case SDTCisSubVecOfVec: {
1485 unsigned VResNo = 0;
1486 TreePatternNode *BigVecOperand =
1487 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1490 // Filter vector types out of BigVecOperand that don't have the
1491 // right subvector type.
1492 return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
1493 NodeToApply->getExtType(ResNo));
1495 case SDTCVecEltisVT: {
1496 return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
1498 case SDTCisSameNumEltsAs: {
1499 unsigned OResNo = 0;
1500 TreePatternNode *OtherNode =
1501 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1502 N, NodeInfo, OResNo);
1503 return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
1504 NodeToApply->getExtType(ResNo));
1506 case SDTCisSameSizeAs: {
1507 unsigned OResNo = 0;
1508 TreePatternNode *OtherNode =
1509 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1510 N, NodeInfo, OResNo);
1511 return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
1512 NodeToApply->getExtType(ResNo));
1515 llvm_unreachable("Invalid ConstraintType!");
1518 // Update the node type to match an instruction operand or result as specified
1519 // in the ins or outs lists on the instruction definition. Return true if the
1520 // type was actually changed.
1521 bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1524 // The 'unknown' operand indicates that types should be inferred from the
1526 if (Operand->isSubClassOf("unknown_class"))
1529 // The Operand class specifies a type directly.
1530 if (Operand->isSubClassOf("Operand")) {
1531 Record *R = Operand->getValueAsDef("Type");
1532 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1533 return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
1536 // PointerLikeRegClass has a type that is determined at runtime.
1537 if (Operand->isSubClassOf("PointerLikeRegClass"))
1538 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1540 // Both RegisterClass and RegisterOperand operands derive their types from a
1541 // register class def.
1542 Record *RC = nullptr;
1543 if (Operand->isSubClassOf("RegisterClass"))
1545 else if (Operand->isSubClassOf("RegisterOperand"))
1546 RC = Operand->getValueAsDef("RegClass");
1548 assert(RC && "Unknown operand type");
1549 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1550 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1553 bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1554 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1555 if (!TP.getInfer().isConcrete(Types[i], true))
1557 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1558 if (getChild(i)->ContainsUnresolvedType(TP))
1563 bool TreePatternNode::hasProperTypeByHwMode() const {
1564 for (const TypeSetByHwMode &S : Types)
1565 if (!S.isDefaultOnly())
1567 for (TreePatternNode *C : Children)
1568 if (C->hasProperTypeByHwMode())
1573 bool TreePatternNode::hasPossibleType() const {
1574 for (const TypeSetByHwMode &S : Types)
1575 if (!S.isPossible())
1577 for (TreePatternNode *C : Children)
1578 if (!C->hasPossibleType())
1583 bool TreePatternNode::setDefaultMode(unsigned Mode) {
1584 for (TypeSetByHwMode &S : Types) {
1586 // Check if the selected mode had a type conflict.
1587 if (S.get(DefaultMode).empty())
1590 for (TreePatternNode *C : Children)
1591 if (!C->setDefaultMode(Mode))
1596 //===----------------------------------------------------------------------===//
1597 // SDNodeInfo implementation
1599 SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
1600 EnumName = R->getValueAsString("Opcode");
1601 SDClassName = R->getValueAsString("SDClass");
1602 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1603 NumResults = TypeProfile->getValueAsInt("NumResults");
1604 NumOperands = TypeProfile->getValueAsInt("NumOperands");
1606 // Parse the properties.
1607 Properties = parseSDPatternOperatorProperties(R);
1609 // Parse the type constraints.
1610 std::vector<Record*> ConstraintList =
1611 TypeProfile->getValueAsListOfDefs("Constraints");
1612 for (Record *R : ConstraintList)
1613 TypeConstraints.emplace_back(R, CGH);
1616 /// getKnownType - If the type constraints on this node imply a fixed type
1617 /// (e.g. all stores return void, etc), then return it as an
1618 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
1619 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
1620 unsigned NumResults = getNumResults();
1621 assert(NumResults <= 1 &&
1622 "We only work with nodes with zero or one result so far!");
1623 assert(ResNo == 0 && "Only handles single result nodes so far");
1625 for (const SDTypeConstraint &Constraint : TypeConstraints) {
1626 // Make sure that this applies to the correct node result.
1627 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
1630 switch (Constraint.ConstraintType) {
1632 case SDTypeConstraint::SDTCisVT:
1633 if (Constraint.VVT.isSimple())
1634 return Constraint.VVT.getSimple().SimpleTy;
1636 case SDTypeConstraint::SDTCisPtrTy:
1643 //===----------------------------------------------------------------------===//
1644 // TreePatternNode implementation
1647 TreePatternNode::~TreePatternNode() {
1648 #if 0 // FIXME: implement refcounted tree nodes!
1649 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1654 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1655 if (Operator->getName() == "set" ||
1656 Operator->getName() == "implicit")
1657 return 0; // All return nothing.
1659 if (Operator->isSubClassOf("Intrinsic"))
1660 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
1662 if (Operator->isSubClassOf("SDNode"))
1663 return CDP.getSDNodeInfo(Operator).getNumResults();
1665 if (Operator->isSubClassOf("PatFrag")) {
1666 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1667 // the forward reference case where one pattern fragment references another
1668 // before it is processed.
1669 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1670 return PFRec->getOnlyTree()->getNumTypes();
1672 // Get the result tree.
1673 DagInit *Tree = Operator->getValueAsDag("Fragment");
1674 Record *Op = nullptr;
1676 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1678 assert(Op && "Invalid Fragment");
1679 return GetNumNodeResults(Op, CDP);
1682 if (Operator->isSubClassOf("Instruction")) {
1683 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
1685 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1687 // Subtract any defaulted outputs.
1688 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1689 Record *OperandNode = InstInfo.Operands[i].Rec;
1691 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1692 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1696 // Add on one implicit def if it has a resolvable type.
1697 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1699 return NumDefsToAdd;
1702 if (Operator->isSubClassOf("SDNodeXForm"))
1703 return 1; // FIXME: Generalize SDNodeXForm
1705 if (Operator->isSubClassOf("ValueType"))
1706 return 1; // A type-cast of one result.
1708 if (Operator->isSubClassOf("ComplexPattern"))
1711 errs() << *Operator;
1712 PrintFatalError("Unhandled node in GetNumNodeResults");
1715 void TreePatternNode::print(raw_ostream &OS) const {
1717 OS << *getLeafValue();
1719 OS << '(' << getOperator()->getName();
1721 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1723 getExtType(i).writeToStream(OS);
1727 if (getNumChildren() != 0) {
1729 getChild(0)->print(OS);
1730 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1732 getChild(i)->print(OS);
1738 for (const TreePredicateFn &Pred : PredicateFns)
1739 OS << "<<P:" << Pred.getFnName() << ">>";
1741 OS << "<<X:" << TransformFn->getName() << ">>";
1742 if (!getName().empty())
1743 OS << ":$" << getName();
1746 void TreePatternNode::dump() const {
1750 /// isIsomorphicTo - Return true if this node is recursively
1751 /// isomorphic to the specified node. For this comparison, the node's
1752 /// entire state is considered. The assigned name is ignored, since
1753 /// nodes with differing names are considered isomorphic. However, if
1754 /// the assigned name is present in the dependent variable set, then
1755 /// the assigned name is considered significant and the node is
1756 /// isomorphic if the names match.
1757 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1758 const MultipleUseVarSet &DepVars) const {
1759 if (N == this) return true;
1760 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1761 getPredicateFns() != N->getPredicateFns() ||
1762 getTransformFn() != N->getTransformFn())
1766 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1767 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
1768 return ((DI->getDef() == NDI->getDef())
1769 && (DepVars.find(getName()) == DepVars.end()
1770 || getName() == N->getName()));
1773 return getLeafValue() == N->getLeafValue();
1776 if (N->getOperator() != getOperator() ||
1777 N->getNumChildren() != getNumChildren()) return false;
1778 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1779 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
1784 /// clone - Make a copy of this tree and all of its children.
1786 TreePatternNode *TreePatternNode::clone() const {
1787 TreePatternNode *New;
1789 New = new TreePatternNode(getLeafValue(), getNumTypes());
1791 std::vector<TreePatternNode*> CChildren;
1792 CChildren.reserve(Children.size());
1793 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1794 CChildren.push_back(getChild(i)->clone());
1795 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
1797 New->setName(getName());
1799 New->setPredicateFns(getPredicateFns());
1800 New->setTransformFn(getTransformFn());
1804 /// RemoveAllTypes - Recursively strip all the types of this tree.
1805 void TreePatternNode::RemoveAllTypes() {
1806 // Reset to unknown type.
1807 std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
1808 if (isLeaf()) return;
1809 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1810 getChild(i)->RemoveAllTypes();
1814 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1815 /// with actual values specified by ArgMap.
1816 void TreePatternNode::
1817 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1818 if (isLeaf()) return;
1820 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1821 TreePatternNode *Child = getChild(i);
1822 if (Child->isLeaf()) {
1823 Init *Val = Child->getLeafValue();
1824 // Note that, when substituting into an output pattern, Val might be an
1826 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1827 cast<DefInit>(Val)->getDef()->getName() == "node")) {
1828 // We found a use of a formal argument, replace it with its value.
1829 TreePatternNode *NewChild = ArgMap[Child->getName()];
1830 assert(NewChild && "Couldn't find formal argument!");
1831 assert((Child->getPredicateFns().empty() ||
1832 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1833 "Non-empty child predicate clobbered!");
1834 setChild(i, NewChild);
1837 getChild(i)->SubstituteFormalArguments(ArgMap);
1843 /// InlinePatternFragments - If this pattern refers to any pattern
1844 /// fragments, inline them into place, giving us a pattern without any
1845 /// PatFrag references.
1846 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1851 return this; // nothing to do.
1852 Record *Op = getOperator();
1854 if (!Op->isSubClassOf("PatFrag")) {
1855 // Just recursively inline children nodes.
1856 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1857 TreePatternNode *Child = getChild(i);
1858 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1860 assert((Child->getPredicateFns().empty() ||
1861 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1862 "Non-empty child predicate clobbered!");
1864 setChild(i, NewChild);
1869 // Otherwise, we found a reference to a fragment. First, look up its
1870 // TreePattern record.
1871 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
1873 // Verify that we are passing the right number of operands.
1874 if (Frag->getNumArgs() != Children.size()) {
1875 TP.error("'" + Op->getName() + "' fragment requires " +
1876 utostr(Frag->getNumArgs()) + " operands!");
1880 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1882 TreePredicateFn PredFn(Frag);
1883 if (!PredFn.isAlwaysTrue())
1884 FragTree->addPredicateFn(PredFn);
1886 // Resolve formal arguments to their actual value.
1887 if (Frag->getNumArgs()) {
1888 // Compute the map of formal to actual arguments.
1889 std::map<std::string, TreePatternNode*> ArgMap;
1890 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1891 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
1893 FragTree->SubstituteFormalArguments(ArgMap);
1896 FragTree->setName(getName());
1897 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1898 FragTree->UpdateNodeType(i, getExtType(i), TP);
1900 // Transfer in the old predicates.
1901 for (const TreePredicateFn &Pred : getPredicateFns())
1902 FragTree->addPredicateFn(Pred);
1904 // Get a new copy of this fragment to stitch into here.
1905 //delete this; // FIXME: implement refcounting!
1907 // The fragment we inlined could have recursive inlining that is needed. See
1908 // if there are any pattern fragments in it and inline them as needed.
1909 return FragTree->InlinePatternFragments(TP);
1912 /// getImplicitType - Check to see if the specified record has an implicit
1913 /// type which should be applied to it. This will infer the type of register
1914 /// references from the register file information, for example.
1916 /// When Unnamed is set, return the type of a DAG operand with no name, such as
1917 /// the F8RC register class argument in:
1919 /// (COPY_TO_REGCLASS GPR:$src, F8RC)
1921 /// When Unnamed is false, return the type of a named DAG operand such as the
1922 /// GPR:$src operand above.
1924 static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
1928 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1930 // Check to see if this is a register operand.
1931 if (R->isSubClassOf("RegisterOperand")) {
1932 assert(ResNo == 0 && "Regoperand ref only has one result!");
1934 return TypeSetByHwMode(); // Unknown.
1935 Record *RegClass = R->getValueAsDef("RegClass");
1936 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1937 return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
1940 // Check to see if this is a register or a register class.
1941 if (R->isSubClassOf("RegisterClass")) {
1942 assert(ResNo == 0 && "Regclass ref only has one result!");
1943 // An unnamed register class represents itself as an i32 immediate, for
1944 // example on a COPY_TO_REGCLASS instruction.
1946 return TypeSetByHwMode(MVT::i32);
1948 // In a named operand, the register class provides the possible set of
1951 return TypeSetByHwMode(); // Unknown.
1952 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1953 return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
1956 if (R->isSubClassOf("PatFrag")) {
1957 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
1958 // Pattern fragment types will be resolved when they are inlined.
1959 return TypeSetByHwMode(); // Unknown.
1962 if (R->isSubClassOf("Register")) {
1963 assert(ResNo == 0 && "Registers only produce one result!");
1965 return TypeSetByHwMode(); // Unknown.
1966 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1967 return TypeSetByHwMode(T.getRegisterVTs(R));
1970 if (R->isSubClassOf("SubRegIndex")) {
1971 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1972 return TypeSetByHwMode(MVT::i32);
1975 if (R->isSubClassOf("ValueType")) {
1976 assert(ResNo == 0 && "This node only has one result!");
1977 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1979 // (sext_inreg GPR:$src, i16)
1982 return TypeSetByHwMode(MVT::Other);
1983 // With a name, the ValueType simply provides the type of the named
1986 // (sext_inreg i32:$src, i16)
1989 return TypeSetByHwMode(); // Unknown.
1990 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
1991 return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
1994 if (R->isSubClassOf("CondCode")) {
1995 assert(ResNo == 0 && "This node only has one result!");
1996 // Using a CondCodeSDNode.
1997 return TypeSetByHwMode(MVT::Other);
2000 if (R->isSubClassOf("ComplexPattern")) {
2001 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
2003 return TypeSetByHwMode(); // Unknown.
2004 return TypeSetByHwMode(CDP.getComplexPattern(R).getValueType());
2006 if (R->isSubClassOf("PointerLikeRegClass")) {
2007 assert(ResNo == 0 && "Regclass can only have one result!");
2008 TypeSetByHwMode VTS(MVT::iPTR);
2009 TP.getInfer().expandOverloads(VTS);
2013 if (R->getName() == "node" || R->getName() == "srcvalue" ||
2014 R->getName() == "zero_reg") {
2016 return TypeSetByHwMode(); // Unknown.
2019 if (R->isSubClassOf("Operand")) {
2020 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2021 Record *T = R->getValueAsDef("Type");
2022 return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
2025 TP.error("Unknown node flavor used in pattern: " + R->getName());
2026 return TypeSetByHwMode(MVT::Other);
2030 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
2031 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
2032 const CodeGenIntrinsic *TreePatternNode::
2033 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
2034 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
2035 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
2036 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
2039 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
2040 return &CDP.getIntrinsicInfo(IID);
2043 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
2044 /// return the ComplexPattern information, otherwise return null.
2045 const ComplexPattern *
2046 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
2049 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2054 Rec = getOperator();
2056 if (!Rec->isSubClassOf("ComplexPattern"))
2058 return &CGP.getComplexPattern(Rec);
2061 unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
2062 // A ComplexPattern specifically declares how many results it fills in.
2063 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2064 return CP->getNumOperands();
2066 // If MIOperandInfo is specified, that gives the count.
2068 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2069 if (DI && DI->getDef()->isSubClassOf("Operand")) {
2070 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
2071 if (MIOps->getNumArgs())
2072 return MIOps->getNumArgs();
2076 // Otherwise there is just one result.
2080 /// NodeHasProperty - Return true if this node has the specified property.
2081 bool TreePatternNode::NodeHasProperty(SDNP Property,
2082 const CodeGenDAGPatterns &CGP) const {
2084 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2085 return CP->hasProperty(Property);
2090 if (Property != SDNPHasChain) {
2091 // The chain proprety is already present on the different intrinsic node
2092 // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
2093 // on the intrinsic. Anything else is specific to the individual intrinsic.
2094 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CGP))
2095 return Int->hasProperty(Property);
2098 if (!Operator->isSubClassOf("SDPatternOperator"))
2101 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
2107 /// TreeHasProperty - Return true if any node in this tree has the specified
2109 bool TreePatternNode::TreeHasProperty(SDNP Property,
2110 const CodeGenDAGPatterns &CGP) const {
2111 if (NodeHasProperty(Property, CGP))
2113 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2114 if (getChild(i)->TreeHasProperty(Property, CGP))
2119 /// isCommutativeIntrinsic - Return true if the node corresponds to a
2120 /// commutative intrinsic.
2122 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
2123 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
2124 return Int->isCommutative;
2128 static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
2130 return N->getOperator()->isSubClassOf(Class);
2132 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
2133 if (DI && DI->getDef()->isSubClassOf(Class))
2139 static void emitTooManyOperandsError(TreePattern &TP,
2143 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
2144 " operands but expected only " + Twine(Expected) + "!");
2147 static void emitTooFewOperandsError(TreePattern &TP,
2150 TP.error("Instruction '" + InstName +
2151 "' expects more than the provided " + Twine(Actual) + " operands!");
2154 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
2155 /// this node and its children in the tree. This returns true if it makes a
2156 /// change, false otherwise. If a type contradiction is found, flag an error.
2157 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
2161 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2163 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
2164 // If it's a regclass or something else known, include the type.
2165 bool MadeChange = false;
2166 for (unsigned i = 0, e = Types.size(); i != e; ++i)
2167 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
2169 !hasName(), TP), TP);
2173 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
2174 assert(Types.size() == 1 && "Invalid IntInit");
2176 // Int inits are always integers. :)
2177 bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
2179 if (!TP.getInfer().isConcrete(Types[0], false))
2182 ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
2183 for (auto &P : VVT) {
2184 MVT::SimpleValueType VT = P.second.SimpleTy;
2185 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
2187 unsigned Size = MVT(VT).getSizeInBits();
2188 // Make sure that the value is representable for this type.
2191 // Check that the value doesn't use more bits than we have. It must
2192 // either be a sign- or zero-extended equivalent of the original.
2193 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
2194 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
2195 SignBitAndAbove == 1)
2198 TP.error("Integer value '" + itostr(II->getValue()) +
2199 "' is out of range for type '" + getEnumName(VT) + "'!");
2208 // special handling for set, which isn't really an SDNode.
2209 if (getOperator()->getName() == "set") {
2210 assert(getNumTypes() == 0 && "Set doesn't produce a value");
2211 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
2212 unsigned NC = getNumChildren();
2214 TreePatternNode *SetVal = getChild(NC-1);
2215 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
2217 for (unsigned i = 0; i < NC-1; ++i) {
2218 TreePatternNode *Child = getChild(i);
2219 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
2221 // Types of operands must match.
2222 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
2223 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
2228 if (getOperator()->getName() == "implicit") {
2229 assert(getNumTypes() == 0 && "Node doesn't produce a value");
2231 bool MadeChange = false;
2232 for (unsigned i = 0; i < getNumChildren(); ++i)
2233 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2237 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
2238 bool MadeChange = false;
2240 // Apply the result type to the node.
2241 unsigned NumRetVTs = Int->IS.RetVTs.size();
2242 unsigned NumParamVTs = Int->IS.ParamVTs.size();
2244 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
2245 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
2247 if (getNumChildren() != NumParamVTs + 1) {
2248 TP.error("Intrinsic '" + Int->Name + "' expects " +
2249 utostr(NumParamVTs) + " operands, not " +
2250 utostr(getNumChildren() - 1) + " operands!");
2254 // Apply type info to the intrinsic ID.
2255 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
2257 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
2258 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
2260 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
2261 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
2262 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
2267 if (getOperator()->isSubClassOf("SDNode")) {
2268 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
2270 // Check that the number of operands is sane. Negative operands -> varargs.
2271 if (NI.getNumOperands() >= 0 &&
2272 getNumChildren() != (unsigned)NI.getNumOperands()) {
2273 TP.error(getOperator()->getName() + " node requires exactly " +
2274 itostr(NI.getNumOperands()) + " operands!");
2278 bool MadeChange = false;
2279 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2280 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2281 MadeChange |= NI.ApplyTypeConstraints(this, TP);
2285 if (getOperator()->isSubClassOf("Instruction")) {
2286 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
2287 CodeGenInstruction &InstInfo =
2288 CDP.getTargetInfo().getInstruction(getOperator());
2290 bool MadeChange = false;
2292 // Apply the result types to the node, these come from the things in the
2293 // (outs) list of the instruction.
2294 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
2295 Inst.getNumResults());
2296 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
2297 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
2299 // If the instruction has implicit defs, we apply the first one as a result.
2300 // FIXME: This sucks, it should apply all implicit defs.
2301 if (!InstInfo.ImplicitDefs.empty()) {
2302 unsigned ResNo = NumResultsToAdd;
2304 // FIXME: Generalize to multiple possible types and multiple possible
2306 MVT::SimpleValueType VT =
2307 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
2309 if (VT != MVT::Other)
2310 MadeChange |= UpdateNodeType(ResNo, VT, TP);
2313 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2315 if (getOperator()->getName() == "INSERT_SUBREG") {
2316 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
2317 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
2318 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
2319 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2320 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2323 unsigned NChild = getNumChildren();
2325 TP.error("REG_SEQUENCE requires at least 3 operands!");
2329 if (NChild % 2 == 0) {
2330 TP.error("REG_SEQUENCE requires an odd number of operands!");
2334 if (!isOperandClass(getChild(0), "RegisterClass")) {
2335 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2339 for (unsigned I = 1; I < NChild; I += 2) {
2340 TreePatternNode *SubIdxChild = getChild(I + 1);
2341 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
2342 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
2343 itostr(I + 1) + "!");
2349 unsigned ChildNo = 0;
2350 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
2351 Record *OperandNode = Inst.getOperand(i);
2353 // If the instruction expects a predicate or optional def operand, we
2354 // codegen this by setting the operand to it's default value if it has a
2355 // non-empty DefaultOps field.
2356 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
2357 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
2360 // Verify that we didn't run out of provided operands.
2361 if (ChildNo >= getNumChildren()) {
2362 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
2366 TreePatternNode *Child = getChild(ChildNo++);
2367 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
2369 // If the operand has sub-operands, they may be provided by distinct
2370 // child patterns, so attempt to match each sub-operand separately.
2371 if (OperandNode->isSubClassOf("Operand")) {
2372 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
2373 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2374 // But don't do that if the whole operand is being provided by
2375 // a single ComplexPattern-related Operand.
2377 if (Child->getNumMIResults(CDP) < NumArgs) {
2378 // Match first sub-operand against the child we already have.
2379 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2381 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2383 // And the remaining sub-operands against subsequent children.
2384 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2385 if (ChildNo >= getNumChildren()) {
2386 emitTooFewOperandsError(TP, getOperator()->getName(),
2390 Child = getChild(ChildNo++);
2392 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
2394 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2401 // If we didn't match by pieces above, attempt to match the whole
2403 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
2406 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
2407 emitTooManyOperandsError(TP, getOperator()->getName(),
2408 ChildNo, getNumChildren());
2412 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2413 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2417 if (getOperator()->isSubClassOf("ComplexPattern")) {
2418 bool MadeChange = false;
2420 for (unsigned i = 0; i < getNumChildren(); ++i)
2421 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2426 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
2428 // Node transforms always take one operand.
2429 if (getNumChildren() != 1) {
2430 TP.error("Node transform '" + getOperator()->getName() +
2431 "' requires one operand!");
2435 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
2439 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2440 /// RHS of a commutative operation, not the on LHS.
2441 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
2442 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
2444 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
2450 /// canPatternMatch - If it is impossible for this pattern to match on this
2451 /// target, fill in Reason and return false. Otherwise, return true. This is
2452 /// used as a sanity check for .td files (to prevent people from writing stuff
2453 /// that can never possibly work), and to prevent the pattern permuter from
2454 /// generating stuff that is useless.
2455 bool TreePatternNode::canPatternMatch(std::string &Reason,
2456 const CodeGenDAGPatterns &CDP) {
2457 if (isLeaf()) return true;
2459 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2460 if (!getChild(i)->canPatternMatch(Reason, CDP))
2463 // If this is an intrinsic, handle cases that would make it not match. For
2464 // example, if an operand is required to be an immediate.
2465 if (getOperator()->isSubClassOf("Intrinsic")) {
2470 if (getOperator()->isSubClassOf("ComplexPattern"))
2473 // If this node is a commutative operator, check that the LHS isn't an
2475 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
2476 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2477 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2478 // Scan all of the operands of the node and make sure that only the last one
2479 // is a constant node, unless the RHS also is.
2480 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
2481 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
2482 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
2483 if (OnlyOnRHSOfCommutative(getChild(i))) {
2484 Reason="Immediate value must be on the RHS of commutative operators!";
2493 //===----------------------------------------------------------------------===//
2494 // TreePattern implementation
2497 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
2498 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2499 isInputPattern(isInput), HasError(false),
2501 for (Init *I : RawPat->getValues())
2502 Trees.push_back(ParseTreePattern(I, ""));
2505 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
2506 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2507 isInputPattern(isInput), HasError(false),
2509 Trees.push_back(ParseTreePattern(Pat, ""));
2512 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
2513 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2514 isInputPattern(isInput), HasError(false),
2516 Trees.push_back(Pat);
2519 void TreePattern::error(const Twine &Msg) {
2523 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2527 void TreePattern::ComputeNamedNodes() {
2528 for (TreePatternNode *Tree : Trees)
2529 ComputeNamedNodes(Tree);
2532 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2533 if (!N->getName().empty())
2534 NamedNodes[N->getName()].push_back(N);
2536 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2537 ComputeNamedNodes(N->getChild(i));
2541 TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
2542 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
2543 Record *R = DI->getDef();
2545 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
2546 // TreePatternNode of its own. For example:
2547 /// (foo GPR, imm) -> (foo GPR, (imm))
2548 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
2549 return ParseTreePattern(
2550 DagInit::get(DI, nullptr,
2551 std::vector<std::pair<Init*, StringInit*> >()),
2555 TreePatternNode *Res = new TreePatternNode(DI, 1);
2556 if (R->getName() == "node" && !OpName.empty()) {
2558 error("'node' argument requires a name to match with operand list");
2559 Args.push_back(OpName);
2562 Res->setName(OpName);
2566 // ?:$name or just $name.
2567 if (isa<UnsetInit>(TheInit)) {
2569 error("'?' argument requires a name to match with operand list");
2570 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
2571 Args.push_back(OpName);
2572 Res->setName(OpName);
2576 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
2577 if (!OpName.empty())
2578 error("Constant int argument should not have a name!");
2579 return new TreePatternNode(II, 1);
2582 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
2583 // Turn this into an IntInit.
2584 Init *II = BI->convertInitializerTo(IntRecTy::get());
2585 if (!II || !isa<IntInit>(II))
2586 error("Bits value must be constants!");
2587 return ParseTreePattern(II, OpName);
2590 DagInit *Dag = dyn_cast<DagInit>(TheInit);
2592 TheInit->print(errs());
2593 error("Pattern has unexpected init kind!");
2595 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
2596 if (!OpDef) error("Pattern has unexpected operator type!");
2597 Record *Operator = OpDef->getDef();
2599 if (Operator->isSubClassOf("ValueType")) {
2600 // If the operator is a ValueType, then this must be "type cast" of a leaf
2602 if (Dag->getNumArgs() != 1)
2603 error("Type cast only takes one operand!");
2605 TreePatternNode *New = ParseTreePattern(Dag->getArg(0),
2606 Dag->getArgNameStr(0));
2608 // Apply the type cast.
2609 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2610 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
2611 New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
2613 if (!OpName.empty())
2614 error("ValueType cast should not have a name!");
2618 // Verify that this is something that makes sense for an operator.
2619 if (!Operator->isSubClassOf("PatFrag") &&
2620 !Operator->isSubClassOf("SDNode") &&
2621 !Operator->isSubClassOf("Instruction") &&
2622 !Operator->isSubClassOf("SDNodeXForm") &&
2623 !Operator->isSubClassOf("Intrinsic") &&
2624 !Operator->isSubClassOf("ComplexPattern") &&
2625 Operator->getName() != "set" &&
2626 Operator->getName() != "implicit")
2627 error("Unrecognized node '" + Operator->getName() + "'!");
2629 // Check to see if this is something that is illegal in an input pattern.
2630 if (isInputPattern) {
2631 if (Operator->isSubClassOf("Instruction") ||
2632 Operator->isSubClassOf("SDNodeXForm"))
2633 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2635 if (Operator->isSubClassOf("Intrinsic"))
2636 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2638 if (Operator->isSubClassOf("SDNode") &&
2639 Operator->getName() != "imm" &&
2640 Operator->getName() != "fpimm" &&
2641 Operator->getName() != "tglobaltlsaddr" &&
2642 Operator->getName() != "tconstpool" &&
2643 Operator->getName() != "tjumptable" &&
2644 Operator->getName() != "tframeindex" &&
2645 Operator->getName() != "texternalsym" &&
2646 Operator->getName() != "tblockaddress" &&
2647 Operator->getName() != "tglobaladdr" &&
2648 Operator->getName() != "bb" &&
2649 Operator->getName() != "vt" &&
2650 Operator->getName() != "mcsym")
2651 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2654 std::vector<TreePatternNode*> Children;
2656 // Parse all the operands.
2657 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
2658 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
2660 // If the operator is an intrinsic, then this is just syntactic sugar for for
2661 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
2662 // convert the intrinsic name to a number.
2663 if (Operator->isSubClassOf("Intrinsic")) {
2664 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2665 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2667 // If this intrinsic returns void, it must have side-effects and thus a
2669 if (Int.IS.RetVTs.empty())
2670 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
2671 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
2672 // Has side-effects, requires chain.
2673 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
2674 else // Otherwise, no chain.
2675 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
2677 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
2678 Children.insert(Children.begin(), IIDNode);
2681 if (Operator->isSubClassOf("ComplexPattern")) {
2682 for (unsigned i = 0; i < Children.size(); ++i) {
2683 TreePatternNode *Child = Children[i];
2685 if (Child->getName().empty())
2686 error("All arguments to a ComplexPattern must be named");
2688 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2689 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2690 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2691 auto OperandId = std::make_pair(Operator, i);
2692 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2693 if (PrevOp != ComplexPatternOperands.end()) {
2694 if (PrevOp->getValue() != OperandId)
2695 error("All ComplexPattern operands must appear consistently: "
2696 "in the same order in just one ComplexPattern instance.");
2698 ComplexPatternOperands[Child->getName()] = OperandId;
2702 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2703 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
2704 Result->setName(OpName);
2706 if (Dag->getName()) {
2707 assert(Result->getName().empty());
2708 Result->setName(Dag->getNameStr());
2713 /// SimplifyTree - See if we can simplify this tree to eliminate something that
2714 /// will never match in favor of something obvious that will. This is here
2715 /// strictly as a convenience to target authors because it allows them to write
2716 /// more type generic things and have useless type casts fold away.
2718 /// This returns true if any change is made.
2719 static bool SimplifyTree(TreePatternNode *&N) {
2723 // If we have a bitconvert with a resolved type and if the source and
2724 // destination types are the same, then the bitconvert is useless, remove it.
2725 if (N->getOperator()->getName() == "bitconvert" &&
2726 N->getExtType(0).isValueTypeByHwMode(false) &&
2727 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2728 N->getName().empty()) {
2734 // Walk all children.
2735 bool MadeChange = false;
2736 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2737 TreePatternNode *Child = N->getChild(i);
2738 MadeChange |= SimplifyTree(Child);
2739 N->setChild(i, Child);
2746 /// InferAllTypes - Infer/propagate as many types throughout the expression
2747 /// patterns as possible. Return true if all types are inferred, false
2748 /// otherwise. Flags an error if a type contradiction is found.
2750 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2751 if (NamedNodes.empty())
2752 ComputeNamedNodes();
2754 bool MadeChange = true;
2755 while (MadeChange) {
2757 for (TreePatternNode *&Tree : Trees) {
2758 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2759 MadeChange |= SimplifyTree(Tree);
2762 // If there are constraints on our named nodes, apply them.
2763 for (auto &Entry : NamedNodes) {
2764 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
2766 // If we have input named node types, propagate their types to the named
2769 if (!InNamedTypes->count(Entry.getKey())) {
2770 error("Node '" + std::string(Entry.getKey()) +
2771 "' in output pattern but not input pattern");
2775 const SmallVectorImpl<TreePatternNode*> &InNodes =
2776 InNamedTypes->find(Entry.getKey())->second;
2778 // The input types should be fully resolved by now.
2779 for (TreePatternNode *Node : Nodes) {
2780 // If this node is a register class, and it is the root of the pattern
2781 // then we're mapping something onto an input register. We allow
2782 // changing the type of the input register in this case. This allows
2783 // us to match things like:
2784 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2785 if (Node == Trees[0] && Node->isLeaf()) {
2786 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
2787 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2788 DI->getDef()->isSubClassOf("RegisterOperand")))
2792 assert(Node->getNumTypes() == 1 &&
2793 InNodes[0]->getNumTypes() == 1 &&
2794 "FIXME: cannot name multiple result nodes yet");
2795 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2800 // If there are multiple nodes with the same name, they must all have the
2802 if (Entry.second.size() > 1) {
2803 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
2804 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
2805 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
2806 "FIXME: cannot name multiple result nodes yet");
2808 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2809 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
2815 bool HasUnresolvedTypes = false;
2816 for (const TreePatternNode *Tree : Trees)
2817 HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
2818 return !HasUnresolvedTypes;
2821 void TreePattern::print(raw_ostream &OS) const {
2822 OS << getRecord()->getName();
2823 if (!Args.empty()) {
2824 OS << "(" << Args[0];
2825 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2826 OS << ", " << Args[i];
2831 if (Trees.size() > 1)
2833 for (const TreePatternNode *Tree : Trees) {
2839 if (Trees.size() > 1)
2843 void TreePattern::dump() const { print(errs()); }
2845 //===----------------------------------------------------------------------===//
2846 // CodeGenDAGPatterns implementation
2849 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R,
2850 PatternRewriterFn PatternRewriter)
2851 : Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()),
2852 PatternRewriter(PatternRewriter) {
2854 Intrinsics = CodeGenIntrinsicTable(Records, false);
2855 TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
2857 ParseNodeTransforms();
2858 ParseComplexPatterns();
2859 ParsePatternFragments();
2860 ParseDefaultOperands();
2861 ParseInstructions();
2862 ParsePatternFragments(/*OutFrags*/true);
2865 // Break patterns with parameterized types into a series of patterns,
2866 // where each one has a fixed type and is predicated on the conditions
2867 // of the associated HW mode.
2868 ExpandHwModeBasedTypes();
2870 // Generate variants. For example, commutative patterns can match
2871 // multiple ways. Add them to PatternsToMatch as well.
2874 // Infer instruction flags. For example, we can detect loads,
2875 // stores, and side effects in many cases by examining an
2876 // instruction's pattern.
2877 InferInstructionFlags();
2879 // Verify that instruction flags match the patterns.
2880 VerifyInstructionFlags();
2883 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
2884 Record *N = Records.getDef(Name);
2885 if (!N || !N->isSubClassOf("SDNode"))
2886 PrintFatalError("Error getting SDNode '" + Name + "'!");
2891 // Parse all of the SDNode definitions for the target, populating SDNodes.
2892 void CodeGenDAGPatterns::ParseNodeInfo() {
2893 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2894 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
2896 while (!Nodes.empty()) {
2897 Record *R = Nodes.back();
2898 SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
2902 // Get the builtin intrinsic nodes.
2903 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2904 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2905 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2908 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2909 /// map, and emit them to the file as functions.
2910 void CodeGenDAGPatterns::ParseNodeTransforms() {
2911 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2912 while (!Xforms.empty()) {
2913 Record *XFormNode = Xforms.back();
2914 Record *SDNode = XFormNode->getValueAsDef("Opcode");
2915 StringRef Code = XFormNode->getValueAsString("XFormFunction");
2916 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
2922 void CodeGenDAGPatterns::ParseComplexPatterns() {
2923 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2924 while (!AMs.empty()) {
2925 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2931 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2932 /// file, building up the PatternFragments map. After we've collected them all,
2933 /// inline fragments together as necessary, so that there are no references left
2934 /// inside a pattern fragment to a pattern fragment.
2936 void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
2937 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
2939 // First step, parse all of the fragments.
2940 for (Record *Frag : Fragments) {
2941 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2944 DagInit *Tree = Frag->getValueAsDag("Fragment");
2946 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2947 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
2950 // Validate the argument list, converting it to set, to discard duplicates.
2951 std::vector<std::string> &Args = P->getArgList();
2952 // Copy the args so we can take StringRefs to them.
2953 auto ArgsCopy = Args;
2954 SmallDenseSet<StringRef, 4> OperandsSet;
2955 OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
2957 if (OperandsSet.count(""))
2958 P->error("Cannot have unnamed 'node' values in pattern fragment!");
2960 // Parse the operands list.
2961 DagInit *OpsList = Frag->getValueAsDag("Operands");
2962 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
2963 // Special cases: ops == outs == ins. Different names are used to
2964 // improve readability.
2966 (OpsOp->getDef()->getName() != "ops" &&
2967 OpsOp->getDef()->getName() != "outs" &&
2968 OpsOp->getDef()->getName() != "ins"))
2969 P->error("Operands list should start with '(ops ... '!");
2971 // Copy over the arguments.
2973 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
2974 if (!isa<DefInit>(OpsList->getArg(j)) ||
2975 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
2976 P->error("Operands list should all be 'node' values.");
2977 if (!OpsList->getArgName(j))
2978 P->error("Operands list should have names for each operand!");
2979 StringRef ArgNameStr = OpsList->getArgNameStr(j);
2980 if (!OperandsSet.count(ArgNameStr))
2981 P->error("'" + ArgNameStr +
2982 "' does not occur in pattern or was multiply specified!");
2983 OperandsSet.erase(ArgNameStr);
2984 Args.push_back(ArgNameStr);
2987 if (!OperandsSet.empty())
2988 P->error("Operands list does not contain an entry for operand '" +
2989 *OperandsSet.begin() + "'!");
2991 // If there is a code init for this fragment, keep track of the fact that
2992 // this fragment uses it.
2993 TreePredicateFn PredFn(P);
2994 if (!PredFn.isAlwaysTrue())
2995 P->getOnlyTree()->addPredicateFn(PredFn);
2997 // If there is a node transformation corresponding to this, keep track of
2999 Record *Transform = Frag->getValueAsDef("OperandTransform");
3000 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
3001 P->getOnlyTree()->setTransformFn(Transform);
3004 // Now that we've parsed all of the tree fragments, do a closure on them so
3005 // that there are not references to PatFrags left inside of them.
3006 for (Record *Frag : Fragments) {
3007 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
3010 TreePattern &ThePat = *PatternFragments[Frag];
3011 ThePat.InlinePatternFragments();
3013 // Infer as many types as possible. Don't worry about it if we don't infer
3014 // all of them, some may depend on the inputs of the pattern.
3015 ThePat.InferAllTypes();
3016 ThePat.resetError();
3018 // If debugging, print out the pattern fragment result.
3019 DEBUG(ThePat.dump());
3023 void CodeGenDAGPatterns::ParseDefaultOperands() {
3024 std::vector<Record*> DefaultOps;
3025 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
3027 // Find some SDNode.
3028 assert(!SDNodes.empty() && "No SDNodes parsed?");
3029 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
3031 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
3032 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
3034 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
3035 // SomeSDnode so that we can parse this.
3036 std::vector<std::pair<Init*, StringInit*> > Ops;
3037 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
3038 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
3039 DefaultInfo->getArgName(op)));
3040 DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
3042 // Create a TreePattern to parse this.
3043 TreePattern P(DefaultOps[i], DI, false, *this);
3044 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
3046 // Copy the operands over into a DAGDefaultOperand.
3047 DAGDefaultOperand DefaultOpInfo;
3049 TreePatternNode *T = P.getTree(0);
3050 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
3051 TreePatternNode *TPN = T->getChild(op);
3052 while (TPN->ApplyTypeConstraints(P, false))
3053 /* Resolve all types */;
3055 if (TPN->ContainsUnresolvedType(P)) {
3056 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
3057 DefaultOps[i]->getName() +
3058 "' doesn't have a concrete type!");
3060 DefaultOpInfo.DefaultOps.push_back(TPN);
3063 // Insert it into the DefaultOperands map so we can find it later.
3064 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
3068 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3069 /// instruction input. Return true if this is a real use.
3070 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
3071 std::map<std::string, TreePatternNode*> &InstInputs) {
3072 // No name -> not interesting.
3073 if (Pat->getName().empty()) {
3074 if (Pat->isLeaf()) {
3075 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
3076 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
3077 DI->getDef()->isSubClassOf("RegisterOperand")))
3078 I->error("Input " + DI->getDef()->getName() + " must be named!");
3084 if (Pat->isLeaf()) {
3085 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
3086 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
3089 Rec = Pat->getOperator();
3092 // SRCVALUE nodes are ignored.
3093 if (Rec->getName() == "srcvalue")
3096 TreePatternNode *&Slot = InstInputs[Pat->getName()];
3102 if (Slot->isLeaf()) {
3103 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
3105 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
3106 SlotRec = Slot->getOperator();
3109 // Ensure that the inputs agree if we've already seen this input.
3111 I->error("All $" + Pat->getName() + " inputs must agree with each other");
3112 if (Slot->getExtTypes() != Pat->getExtTypes())
3113 I->error("All $" + Pat->getName() + " inputs must agree with each other");
3117 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3118 /// part of "I", the instruction), computing the set of inputs and outputs of
3119 /// the pattern. Report errors if we see anything naughty.
3120 void CodeGenDAGPatterns::
3121 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
3122 std::map<std::string, TreePatternNode*> &InstInputs,
3123 std::map<std::string, TreePatternNode*>&InstResults,
3124 std::vector<Record*> &InstImpResults) {
3125 if (Pat->isLeaf()) {
3126 bool isUse = HandleUse(I, Pat, InstInputs);
3127 if (!isUse && Pat->getTransformFn())
3128 I->error("Cannot specify a transform function for a non-input value!");
3132 if (Pat->getOperator()->getName() == "implicit") {
3133 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
3134 TreePatternNode *Dest = Pat->getChild(i);
3135 if (!Dest->isLeaf())
3136 I->error("implicitly defined value should be a register!");
3138 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
3139 if (!Val || !Val->getDef()->isSubClassOf("Register"))
3140 I->error("implicitly defined value should be a register!");
3141 InstImpResults.push_back(Val->getDef());
3146 if (Pat->getOperator()->getName() != "set") {
3147 // If this is not a set, verify that the children nodes are not void typed,
3149 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
3150 if (Pat->getChild(i)->getNumTypes() == 0)
3151 I->error("Cannot have void nodes inside of patterns!");
3152 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
3156 // If this is a non-leaf node with no children, treat it basically as if
3157 // it were a leaf. This handles nodes like (imm).
3158 bool isUse = HandleUse(I, Pat, InstInputs);
3160 if (!isUse && Pat->getTransformFn())
3161 I->error("Cannot specify a transform function for a non-input value!");
3165 // Otherwise, this is a set, validate and collect instruction results.
3166 if (Pat->getNumChildren() == 0)
3167 I->error("set requires operands!");
3169 if (Pat->getTransformFn())
3170 I->error("Cannot specify a transform function on a set node!");
3172 // Check the set destinations.
3173 unsigned NumDests = Pat->getNumChildren()-1;
3174 for (unsigned i = 0; i != NumDests; ++i) {
3175 TreePatternNode *Dest = Pat->getChild(i);
3176 if (!Dest->isLeaf())
3177 I->error("set destination should be a register!");
3179 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
3181 I->error("set destination should be a register!");
3185 if (Val->getDef()->isSubClassOf("RegisterClass") ||
3186 Val->getDef()->isSubClassOf("ValueType") ||
3187 Val->getDef()->isSubClassOf("RegisterOperand") ||
3188 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
3189 if (Dest->getName().empty())
3190 I->error("set destination must have a name!");
3191 if (InstResults.count(Dest->getName()))
3192 I->error("cannot set '" + Dest->getName() +"' multiple times");
3193 InstResults[Dest->getName()] = Dest;
3194 } else if (Val->getDef()->isSubClassOf("Register")) {
3195 InstImpResults.push_back(Val->getDef());
3197 I->error("set destination should be a register!");
3201 // Verify and collect info from the computation.
3202 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
3203 InstInputs, InstResults, InstImpResults);
3206 //===----------------------------------------------------------------------===//
3207 // Instruction Analysis
3208 //===----------------------------------------------------------------------===//
3210 class InstAnalyzer {
3211 const CodeGenDAGPatterns &CDP;
3213 bool hasSideEffects;
3219 InstAnalyzer(const CodeGenDAGPatterns &cdp)
3220 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
3221 isBitcast(false), isVariadic(false) {}
3223 void Analyze(const TreePattern *Pat) {
3224 // Assume only the first tree is the pattern. The others are clobber nodes.
3225 AnalyzeNode(Pat->getTree(0));
3228 void Analyze(const PatternToMatch &Pat) {
3229 AnalyzeNode(Pat.getSrcPattern());
3233 bool IsNodeBitcast(const TreePatternNode *N) const {
3234 if (hasSideEffects || mayLoad || mayStore || isVariadic)
3237 if (N->getNumChildren() != 2)
3240 const TreePatternNode *N0 = N->getChild(0);
3241 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
3244 const TreePatternNode *N1 = N->getChild(1);
3247 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
3250 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
3251 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
3253 return OpInfo.getEnumName() == "ISD::BITCAST";
3257 void AnalyzeNode(const TreePatternNode *N) {
3259 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
3260 Record *LeafRec = DI->getDef();
3261 // Handle ComplexPattern leaves.
3262 if (LeafRec->isSubClassOf("ComplexPattern")) {
3263 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
3264 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
3265 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
3266 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
3272 // Analyze children.
3273 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3274 AnalyzeNode(N->getChild(i));
3276 // Ignore set nodes, which are not SDNodes.
3277 if (N->getOperator()->getName() == "set") {
3278 isBitcast = IsNodeBitcast(N);
3282 // Notice properties of the node.
3283 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
3284 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
3285 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
3286 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
3288 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
3289 // If this is an intrinsic, analyze it.
3290 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
3291 mayLoad = true;// These may load memory.
3293 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
3294 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
3296 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
3297 IntInfo->hasSideEffects)
3298 // ReadWriteMem intrinsics can have other strange effects.
3299 hasSideEffects = true;
3305 static bool InferFromPattern(CodeGenInstruction &InstInfo,
3306 const InstAnalyzer &PatInfo,
3310 // Remember where InstInfo got its flags.
3311 if (InstInfo.hasUndefFlags())
3312 InstInfo.InferredFrom = PatDef;
3314 // Check explicitly set flags for consistency.
3315 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3316 !InstInfo.hasSideEffects_Unset) {
3317 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3318 // the pattern has no side effects. That could be useful for div/rem
3319 // instructions that may trap.
3320 if (!InstInfo.hasSideEffects) {
3322 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
3323 Twine(InstInfo.hasSideEffects));
3327 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3329 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
3330 Twine(InstInfo.mayStore));
3333 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3334 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
3335 // Some targets translate immediates to loads.
3336 if (!InstInfo.mayLoad) {
3338 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
3339 Twine(InstInfo.mayLoad));
3343 // Transfer inferred flags.
3344 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3345 InstInfo.mayStore |= PatInfo.mayStore;
3346 InstInfo.mayLoad |= PatInfo.mayLoad;
3348 // These flags are silently added without any verification.
3349 InstInfo.isBitcast |= PatInfo.isBitcast;
3351 // Don't infer isVariadic. This flag means something different on SDNodes and
3352 // instructions. For example, a CALL SDNode is variadic because it has the
3353 // call arguments as operands, but a CALL instruction is not variadic - it
3354 // has argument registers as implicit, not explicit uses.
3359 /// hasNullFragReference - Return true if the DAG has any reference to the
3360 /// null_frag operator.
3361 static bool hasNullFragReference(DagInit *DI) {
3362 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
3363 if (!OpDef) return false;
3364 Record *Operator = OpDef->getDef();
3366 // If this is the null fragment, return true.
3367 if (Operator->getName() == "null_frag") return true;
3368 // If any of the arguments reference the null fragment, return true.
3369 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
3370 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
3371 if (Arg && hasNullFragReference(Arg))
3378 /// hasNullFragReference - Return true if any DAG in the list references
3379 /// the null_frag operator.
3380 static bool hasNullFragReference(ListInit *LI) {
3381 for (Init *I : LI->getValues()) {
3382 DagInit *DI = dyn_cast<DagInit>(I);
3383 assert(DI && "non-dag in an instruction Pattern list?!");
3384 if (hasNullFragReference(DI))
3390 /// Get all the instructions in a tree.
3392 getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
3395 if (Tree->getOperator()->isSubClassOf("Instruction"))
3396 Instrs.push_back(Tree->getOperator());
3397 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
3398 getInstructionsInTree(Tree->getChild(i), Instrs);
3401 /// Check the class of a pattern leaf node against the instruction operand it
3403 static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
3408 // Allow direct value types to be used in instruction set patterns.
3409 // The type will be checked later.
3410 if (Leaf->isSubClassOf("ValueType"))
3413 // Patterns can also be ComplexPattern instances.
3414 if (Leaf->isSubClassOf("ComplexPattern"))
3420 const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
3421 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
3423 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
3425 // Parse the instruction.
3426 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
3427 // Inline pattern fragments into it.
3428 I->InlinePatternFragments();
3430 // Infer as many types as possible. If we cannot infer all of them, we can
3431 // never do anything with this instruction pattern: report it to the user.
3432 if (!I->InferAllTypes())
3433 I->error("Could not infer all types in pattern!");
3435 // InstInputs - Keep track of all of the inputs of the instruction, along
3436 // with the record they are declared as.
3437 std::map<std::string, TreePatternNode*> InstInputs;
3439 // InstResults - Keep track of all the virtual registers that are 'set'
3440 // in the instruction, including what reg class they are.
3441 std::map<std::string, TreePatternNode*> InstResults;
3443 std::vector<Record*> InstImpResults;
3445 // Verify that the top-level forms in the instruction are of void type, and
3446 // fill in the InstResults map.
3447 SmallString<32> TypesString;
3448 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
3449 TypesString.clear();
3450 TreePatternNode *Pat = I->getTree(j);
3451 if (Pat->getNumTypes() != 0) {
3452 raw_svector_ostream OS(TypesString);
3453 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3456 Pat->getExtType(k).writeToStream(OS);
3458 I->error("Top-level forms in instruction pattern should have"
3459 " void types, has types " +
3463 // Find inputs and outputs, and verify the structure of the uses/defs.
3464 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
3468 // Now that we have inputs and outputs of the pattern, inspect the operands
3469 // list for the instruction. This determines the order that operands are
3470 // added to the machine instruction the node corresponds to.
3471 unsigned NumResults = InstResults.size();
3473 // Parse the operands list from the (ops) list, validating it.
3474 assert(I->getArgList().empty() && "Args list should still be empty here!");
3476 // Check that all of the results occur first in the list.
3477 std::vector<Record*> Results;
3478 SmallVector<TreePatternNode *, 2> ResNodes;
3479 for (unsigned i = 0; i != NumResults; ++i) {
3480 if (i == CGI.Operands.size())
3481 I->error("'" + InstResults.begin()->first +
3482 "' set but does not appear in operand list!");
3483 const std::string &OpName = CGI.Operands[i].Name;
3485 // Check that it exists in InstResults.
3486 TreePatternNode *RNode = InstResults[OpName];
3488 I->error("Operand $" + OpName + " does not exist in operand list!");
3490 ResNodes.push_back(RNode);
3492 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
3494 I->error("Operand $" + OpName + " should be a set destination: all "
3495 "outputs must occur before inputs in operand list!");
3497 if (!checkOperandClass(CGI.Operands[i], R))
3498 I->error("Operand $" + OpName + " class mismatch!");
3500 // Remember the return type.
3501 Results.push_back(CGI.Operands[i].Rec);
3503 // Okay, this one checks out.
3504 InstResults.erase(OpName);
3507 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
3508 // the copy while we're checking the inputs.
3509 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
3511 std::vector<TreePatternNode*> ResultNodeOperands;
3512 std::vector<Record*> Operands;
3513 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3514 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3515 const std::string &OpName = Op.Name;
3517 I->error("Operand #" + utostr(i) + " in operands list has no name!");
3519 if (!InstInputsCheck.count(OpName)) {
3520 // If this is an operand with a DefaultOps set filled in, we can ignore
3521 // this. When we codegen it, we will do so as always executed.
3522 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3523 // Does it have a non-empty DefaultOps field? If so, ignore this
3525 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3528 I->error("Operand $" + OpName +
3529 " does not appear in the instruction pattern");
3531 TreePatternNode *InVal = InstInputsCheck[OpName];
3532 InstInputsCheck.erase(OpName); // It occurred, remove from map.
3534 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3535 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3536 if (!checkOperandClass(Op, InRec))
3537 I->error("Operand $" + OpName + "'s register class disagrees"
3538 " between the operand and pattern");
3540 Operands.push_back(Op.Rec);
3542 // Construct the result for the dest-pattern operand list.
3543 TreePatternNode *OpNode = InVal->clone();
3545 // No predicate is useful on the result.
3546 OpNode->clearPredicateFns();
3548 // Promote the xform function to be an explicit node if set.
3549 if (Record *Xform = OpNode->getTransformFn()) {
3550 OpNode->setTransformFn(nullptr);
3551 std::vector<TreePatternNode*> Children;
3552 Children.push_back(OpNode);
3553 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3556 ResultNodeOperands.push_back(OpNode);
3559 if (!InstInputsCheck.empty())
3560 I->error("Input operand $" + InstInputsCheck.begin()->first +
3561 " occurs in pattern but not in operands list!");
3563 TreePatternNode *ResultPattern =
3564 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3565 GetNumNodeResults(I->getRecord(), *this));
3566 // Copy fully inferred output node types to instruction result pattern.
3567 for (unsigned i = 0; i != NumResults; ++i) {
3568 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3569 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3572 // Create and insert the instruction.
3573 // FIXME: InstImpResults should not be part of DAGInstruction.
3574 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3575 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3577 // Use a temporary tree pattern to infer all types and make sure that the
3578 // constructed result is correct. This depends on the instruction already
3579 // being inserted into the DAGInsts map.
3580 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3581 Temp.InferAllTypes(&I->getNamedNodesMap());
3583 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3584 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3586 return TheInsertedInst;
3589 /// ParseInstructions - Parse all of the instructions, inlining and resolving
3590 /// any fragments involved. This populates the Instructions list with fully
3591 /// resolved instructions.
3592 void CodeGenDAGPatterns::ParseInstructions() {
3593 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3595 for (Record *Instr : Instrs) {
3596 ListInit *LI = nullptr;
3598 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3599 LI = Instr->getValueAsListInit("Pattern");
3601 // If there is no pattern, only collect minimal information about the
3602 // instruction for its operand list. We have to assume that there is one
3603 // result, as we have no detailed info. A pattern which references the
3604 // null_frag operator is as-if no pattern were specified. Normally this
3605 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3607 if (!LI || LI->empty() || hasNullFragReference(LI)) {
3608 std::vector<Record*> Results;
3609 std::vector<Record*> Operands;
3611 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3613 if (InstInfo.Operands.size() != 0) {
3614 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3615 Results.push_back(InstInfo.Operands[j].Rec);
3617 // The rest are inputs.
3618 for (unsigned j = InstInfo.Operands.NumDefs,
3619 e = InstInfo.Operands.size(); j < e; ++j)
3620 Operands.push_back(InstInfo.Operands[j].Rec);
3623 // Create and insert the instruction.
3624 std::vector<Record*> ImpResults;
3625 Instructions.insert(std::make_pair(Instr,
3626 DAGInstruction(nullptr, Results, Operands, ImpResults)));
3627 continue; // no pattern.
3630 CodeGenInstruction &CGI = Target.getInstruction(Instr);
3631 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3634 DEBUG(DI.getPattern()->dump());
3637 // If we can, convert the instructions to be patterns that are matched!
3638 for (auto &Entry : Instructions) {
3639 DAGInstruction &TheInst = Entry.second;
3640 TreePattern *I = TheInst.getPattern();
3641 if (!I) continue; // No pattern.
3643 if (PatternRewriter)
3645 // FIXME: Assume only the first tree is the pattern. The others are clobber
3647 TreePatternNode *Pattern = I->getTree(0);
3648 TreePatternNode *SrcPattern;
3649 if (Pattern->getOperator()->getName() == "set") {
3650 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3652 // Not a set (store or something?)
3653 SrcPattern = Pattern;
3656 Record *Instr = Entry.first;
3657 ListInit *Preds = Instr->getValueAsListInit("Predicates");
3658 int Complexity = Instr->getValueAsInt("AddedComplexity");
3661 PatternToMatch(Instr, makePredList(Preds), SrcPattern,
3662 TheInst.getResultPattern(), TheInst.getImpResults(),
3663 Complexity, Instr->getID()));
3668 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3670 static void FindNames(const TreePatternNode *P,
3671 std::map<std::string, NameRecord> &Names,
3672 TreePattern *PatternTop) {
3673 if (!P->getName().empty()) {
3674 NameRecord &Rec = Names[P->getName()];
3675 // If this is the first instance of the name, remember the node.
3676 if (Rec.second++ == 0)
3678 else if (Rec.first->getExtTypes() != P->getExtTypes())
3679 PatternTop->error("repetition of value: $" + P->getName() +
3680 " where different uses have different types!");
3684 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3685 FindNames(P->getChild(i), Names, PatternTop);
3689 std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) {
3690 std::vector<Predicate> Preds;
3691 for (Init *I : L->getValues()) {
3692 if (DefInit *Pred = dyn_cast<DefInit>(I))
3693 Preds.push_back(Pred->getDef());
3695 llvm_unreachable("Non-def on the list");
3698 // Sort so that different orders get canonicalized to the same string.
3699 std::sort(Preds.begin(), Preds.end());
3703 void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
3704 PatternToMatch &&PTM) {
3705 // Do some sanity checking on the pattern we're about to match.
3707 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3708 PrintWarning(Pattern->getRecord()->getLoc(),
3709 Twine("Pattern can never match: ") + Reason);
3713 // If the source pattern's root is a complex pattern, that complex pattern
3714 // must specify the nodes it can potentially match.
3715 if (const ComplexPattern *CP =
3716 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3717 if (CP->getRootNodes().empty())
3718 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3722 // Find all of the named values in the input and output, ensure they have the
3724 std::map<std::string, NameRecord> SrcNames, DstNames;
3725 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3726 FindNames(PTM.getDstPattern(), DstNames, Pattern);
3728 // Scan all of the named values in the destination pattern, rejecting them if
3729 // they don't exist in the input pattern.
3730 for (const auto &Entry : DstNames) {
3731 if (SrcNames[Entry.first].first == nullptr)
3732 Pattern->error("Pattern has input without matching name in output: $" +
3736 // Scan all of the named values in the source pattern, rejecting them if the
3737 // name isn't used in the dest, and isn't used to tie two values together.
3738 for (const auto &Entry : SrcNames)
3739 if (DstNames[Entry.first].first == nullptr &&
3740 SrcNames[Entry.first].second == 1)
3741 Pattern->error("Pattern has dead named input: $" + Entry.first);
3743 PatternsToMatch.push_back(std::move(PTM));
3746 void CodeGenDAGPatterns::InferInstructionFlags() {
3747 ArrayRef<const CodeGenInstruction*> Instructions =
3748 Target.getInstructionsByEnumValue();
3750 // First try to infer flags from the primary instruction pattern, if any.
3751 SmallVector<CodeGenInstruction*, 8> Revisit;
3752 unsigned Errors = 0;
3753 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3754 CodeGenInstruction &InstInfo =
3755 const_cast<CodeGenInstruction &>(*Instructions[i]);
3757 // Get the primary instruction pattern.
3758 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3760 if (InstInfo.hasUndefFlags())
3761 Revisit.push_back(&InstInfo);
3764 InstAnalyzer PatInfo(*this);
3765 PatInfo.Analyze(Pattern);
3766 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
3769 // Second, look for single-instruction patterns defined outside the
3771 for (const PatternToMatch &PTM : ptms()) {
3772 // We can only infer from single-instruction patterns, otherwise we won't
3773 // know which instruction should get the flags.
3774 SmallVector<Record*, 8> PatInstrs;
3775 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3776 if (PatInstrs.size() != 1)
3779 // Get the single instruction.
3780 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3782 // Only infer properties from the first pattern. We'll verify the others.
3783 if (InstInfo.InferredFrom)
3786 InstAnalyzer PatInfo(*this);
3787 PatInfo.Analyze(PTM);
3788 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3792 PrintFatalError("pattern conflicts");
3794 // Revisit instructions with undefined flags and no pattern.
3795 if (Target.guessInstructionProperties()) {
3796 for (CodeGenInstruction *InstInfo : Revisit) {
3797 if (InstInfo->InferredFrom)
3799 // The mayLoad and mayStore flags default to false.
3800 // Conservatively assume hasSideEffects if it wasn't explicit.
3801 if (InstInfo->hasSideEffects_Unset)
3802 InstInfo->hasSideEffects = true;
3807 // Complain about any flags that are still undefined.
3808 for (CodeGenInstruction *InstInfo : Revisit) {
3809 if (InstInfo->InferredFrom)
3811 if (InstInfo->hasSideEffects_Unset)
3812 PrintError(InstInfo->TheDef->getLoc(),
3813 "Can't infer hasSideEffects from patterns");
3814 if (InstInfo->mayStore_Unset)
3815 PrintError(InstInfo->TheDef->getLoc(),
3816 "Can't infer mayStore from patterns");
3817 if (InstInfo->mayLoad_Unset)
3818 PrintError(InstInfo->TheDef->getLoc(),
3819 "Can't infer mayLoad from patterns");
3824 /// Verify instruction flags against pattern node properties.
3825 void CodeGenDAGPatterns::VerifyInstructionFlags() {
3826 unsigned Errors = 0;
3827 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3828 const PatternToMatch &PTM = *I;
3829 SmallVector<Record*, 8> Instrs;
3830 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3834 // Count the number of instructions with each flag set.
3835 unsigned NumSideEffects = 0;
3836 unsigned NumStores = 0;
3837 unsigned NumLoads = 0;
3838 for (const Record *Instr : Instrs) {
3839 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3840 NumSideEffects += InstInfo.hasSideEffects;
3841 NumStores += InstInfo.mayStore;
3842 NumLoads += InstInfo.mayLoad;
3845 // Analyze the source pattern.
3846 InstAnalyzer PatInfo(*this);
3847 PatInfo.Analyze(PTM);
3849 // Collect error messages.
3850 SmallVector<std::string, 4> Msgs;
3852 // Check for missing flags in the output.
3853 // Permit extra flags for now at least.
3854 if (PatInfo.hasSideEffects && !NumSideEffects)
3855 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3857 // Don't verify store flags on instructions with side effects. At least for
3858 // intrinsics, side effects implies mayStore.
3859 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3860 Msgs.push_back("pattern may store, but mayStore isn't set");
3862 // Similarly, mayStore implies mayLoad on intrinsics.
3863 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3864 Msgs.push_back("pattern may load, but mayLoad isn't set");
3866 // Print error messages.
3871 for (const std::string &Msg : Msgs)
3872 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
3873 (Instrs.size() == 1 ?
3874 "instruction" : "output instructions"));
3875 // Provide the location of the relevant instruction definitions.
3876 for (const Record *Instr : Instrs) {
3877 if (Instr != PTM.getSrcRecord())
3878 PrintError(Instr->getLoc(), "defined here");
3879 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3880 if (InstInfo.InferredFrom &&
3881 InstInfo.InferredFrom != InstInfo.TheDef &&
3882 InstInfo.InferredFrom != PTM.getSrcRecord())
3883 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
3887 PrintFatalError("Errors in DAG patterns");
3890 /// Given a pattern result with an unresolved type, see if we can find one
3891 /// instruction with an unresolved result type. Force this result type to an
3892 /// arbitrary element if it's possible types to converge results.
3893 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3897 // Analyze children.
3898 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3899 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3902 if (!N->getOperator()->isSubClassOf("Instruction"))
3905 // If this type is already concrete or completely unknown we can't do
3907 TypeInfer &TI = TP.getInfer();
3908 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3909 if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
3912 // Otherwise, force its type to an arbitrary choice.
3913 if (TI.forceArbitrary(N->getExtType(i)))
3920 void CodeGenDAGPatterns::ParsePatterns() {
3921 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3923 for (Record *CurPattern : Patterns) {
3924 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
3926 // If the pattern references the null_frag, there's nothing to do.
3927 if (hasNullFragReference(Tree))
3930 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
3932 // Inline pattern fragments into it.
3933 Pattern->InlinePatternFragments();
3935 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
3936 if (LI->empty()) continue; // no pattern.
3938 // Parse the instruction.
3939 TreePattern Result(CurPattern, LI, false, *this);
3941 // Inline pattern fragments into it.
3942 Result.InlinePatternFragments();
3944 if (Result.getNumTrees() != 1)
3945 Result.error("Cannot handle instructions producing instructions "
3946 "with temporaries yet!");
3948 bool IterateInference;
3949 bool InferredAllPatternTypes, InferredAllResultTypes;
3951 // Infer as many types as possible. If we cannot infer all of them, we
3952 // can never do anything with this pattern: report it to the user.
3953 InferredAllPatternTypes =
3954 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
3956 // Infer as many types as possible. If we cannot infer all of them, we
3957 // can never do anything with this pattern: report it to the user.
3958 InferredAllResultTypes =
3959 Result.InferAllTypes(&Pattern->getNamedNodesMap());
3961 IterateInference = false;
3963 // Apply the type of the result to the source pattern. This helps us
3964 // resolve cases where the input type is known to be a pointer type (which
3965 // is considered resolved), but the result knows it needs to be 32- or
3966 // 64-bits. Infer the other way for good measure.
3967 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
3968 Pattern->getTree(0)->getNumTypes());
3970 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3971 i, Result.getTree(0)->getExtType(i), Result);
3972 IterateInference |= Result.getTree(0)->UpdateNodeType(
3973 i, Pattern->getTree(0)->getExtType(i), Result);
3976 // If our iteration has converged and the input pattern's types are fully
3977 // resolved but the result pattern is not fully resolved, we may have a
3978 // situation where we have two instructions in the result pattern and
3979 // the instructions require a common register class, but don't care about
3980 // what actual MVT is used. This is actually a bug in our modelling:
3981 // output patterns should have register classes, not MVTs.
3983 // In any case, to handle this, we just go through and disambiguate some
3984 // arbitrary types to the result pattern's nodes.
3985 if (!IterateInference && InferredAllPatternTypes &&
3986 !InferredAllResultTypes)
3988 ForceArbitraryInstResultType(Result.getTree(0), Result);
3989 } while (IterateInference);
3991 // Verify that we inferred enough types that we can do something with the
3992 // pattern and result. If these fire the user has to add type casts.
3993 if (!InferredAllPatternTypes)
3994 Pattern->error("Could not infer all types in pattern!");
3995 if (!InferredAllResultTypes) {
3997 Result.error("Could not infer all types in pattern result!");
4000 // Validate that the input pattern is correct.
4001 std::map<std::string, TreePatternNode*> InstInputs;
4002 std::map<std::string, TreePatternNode*> InstResults;
4003 std::vector<Record*> InstImpResults;
4004 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
4005 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
4006 InstInputs, InstResults,
4009 // Promote the xform function to be an explicit node if set.
4010 TreePatternNode *DstPattern = Result.getOnlyTree();
4011 std::vector<TreePatternNode*> ResultNodeOperands;
4012 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
4013 TreePatternNode *OpNode = DstPattern->getChild(ii);
4014 if (Record *Xform = OpNode->getTransformFn()) {
4015 OpNode->setTransformFn(nullptr);
4016 std::vector<TreePatternNode*> Children;
4017 Children.push_back(OpNode);
4018 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
4020 ResultNodeOperands.push_back(OpNode);
4022 DstPattern = Result.getOnlyTree();
4023 if (!DstPattern->isLeaf())
4024 DstPattern = new TreePatternNode(DstPattern->getOperator(),
4026 DstPattern->getNumTypes());
4028 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
4029 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
4031 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
4032 Temp.InferAllTypes();
4034 // A pattern may end up with an "impossible" type, i.e. a situation
4035 // where all types have been eliminated for some node in this pattern.
4036 // This could occur for intrinsics that only make sense for a specific
4037 // value type, and use a specific register class. If, for some mode,
4038 // that register class does not accept that type, the type inference
4039 // will lead to a contradiction, which is not an error however, but
4040 // a sign that this pattern will simply never match.
4041 if (Pattern->getTree(0)->hasPossibleType() &&
4042 Temp.getOnlyTree()->hasPossibleType()) {
4043 ListInit *Preds = CurPattern->getValueAsListInit("Predicates");
4044 int Complexity = CurPattern->getValueAsInt("AddedComplexity");
4045 if (PatternRewriter)
4046 PatternRewriter(Pattern);
4050 CurPattern, makePredList(Preds), Pattern->getTree(0),
4051 Temp.getOnlyTree(), std::move(InstImpResults), Complexity,
4052 CurPattern->getID()));
4057 static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
4058 for (const TypeSetByHwMode &VTS : N->getExtTypes())
4059 for (const auto &I : VTS)
4060 Modes.insert(I.first);
4062 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
4063 collectModes(Modes, N->getChild(i));
4066 void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
4067 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
4068 std::map<unsigned,std::vector<Predicate>> ModeChecks;
4069 std::vector<PatternToMatch> Copy = PatternsToMatch;
4070 PatternsToMatch.clear();
4072 auto AppendPattern = [this,&ModeChecks](PatternToMatch &P, unsigned Mode) {
4073 TreePatternNode *NewSrc = P.SrcPattern->clone();
4074 TreePatternNode *NewDst = P.DstPattern->clone();
4075 if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
4081 std::vector<Predicate> Preds = P.Predicates;
4082 const std::vector<Predicate> &MC = ModeChecks[Mode];
4083 Preds.insert(Preds.end(), MC.begin(), MC.end());
4084 PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, NewSrc, NewDst,
4085 P.getDstRegs(), P.getAddedComplexity(),
4086 Record::getNewUID(), Mode);
4089 for (PatternToMatch &P : Copy) {
4090 TreePatternNode *SrcP = nullptr, *DstP = nullptr;
4091 if (P.SrcPattern->hasProperTypeByHwMode())
4092 SrcP = P.SrcPattern;
4093 if (P.DstPattern->hasProperTypeByHwMode())
4094 DstP = P.DstPattern;
4095 if (!SrcP && !DstP) {
4096 PatternsToMatch.push_back(P);
4100 std::set<unsigned> Modes;
4102 collectModes(Modes, SrcP);
4104 collectModes(Modes, DstP);
4106 // The predicate for the default mode needs to be constructed for each
4107 // pattern separately.
4108 // Since not all modes must be present in each pattern, if a mode m is
4109 // absent, then there is no point in constructing a check for m. If such
4110 // a check was created, it would be equivalent to checking the default
4111 // mode, except not all modes' predicates would be a part of the checking
4112 // code. The subsequently generated check for the default mode would then
4113 // have the exact same patterns, but a different predicate code. To avoid
4114 // duplicated patterns with different predicate checks, construct the
4115 // default check as a negation of all predicates that are actually present
4116 // in the source/destination patterns.
4117 std::vector<Predicate> DefaultPred;
4119 for (unsigned M : Modes) {
4120 if (M == DefaultMode)
4122 if (ModeChecks.find(M) != ModeChecks.end())
4125 // Fill the map entry for this mode.
4126 const HwMode &HM = CGH.getMode(M);
4127 ModeChecks[M].emplace_back(Predicate(HM.Features, true));
4129 // Add negations of the HM's predicates to the default predicate.
4130 DefaultPred.emplace_back(Predicate(HM.Features, false));
4133 for (unsigned M : Modes) {
4134 if (M == DefaultMode)
4136 AppendPattern(P, M);
4139 bool HasDefault = Modes.count(DefaultMode);
4141 AppendPattern(P, DefaultMode);
4145 /// Dependent variable map for CodeGenDAGPattern variant generation
4146 typedef StringMap<int> DepVarMap;
4148 static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
4150 if (N->hasName() && isa<DefInit>(N->getLeafValue()))
4151 DepMap[N->getName()]++;
4153 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
4154 FindDepVarsOf(N->getChild(i), DepMap);
4158 /// Find dependent variables within child patterns
4159 static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
4160 DepVarMap depcounts;
4161 FindDepVarsOf(N, depcounts);
4162 for (const auto &Pair : depcounts) {
4163 if (Pair.getValue() > 1)
4164 DepVars.insert(Pair.getKey());
4169 /// Dump the dependent variable set:
4170 static void DumpDepVars(MultipleUseVarSet &DepVars) {
4171 if (DepVars.empty()) {
4172 DEBUG(errs() << "<empty set>");
4174 DEBUG(errs() << "[ ");
4175 for (const auto &DepVar : DepVars) {
4176 DEBUG(errs() << DepVar.getKey() << " ");
4178 DEBUG(errs() << "]");
4184 /// CombineChildVariants - Given a bunch of permutations of each child of the
4185 /// 'operator' node, put them together in all possible ways.
4186 static void CombineChildVariants(TreePatternNode *Orig,
4187 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
4188 std::vector<TreePatternNode*> &OutVariants,
4189 CodeGenDAGPatterns &CDP,
4190 const MultipleUseVarSet &DepVars) {
4191 // Make sure that each operand has at least one variant to choose from.
4192 for (const auto &Variants : ChildVariants)
4193 if (Variants.empty())
4196 // The end result is an all-pairs construction of the resultant pattern.
4197 std::vector<unsigned> Idxs;
4198 Idxs.resize(ChildVariants.size());
4202 DEBUG(if (!Idxs.empty()) {
4203 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
4204 for (unsigned Idx : Idxs) {
4205 errs() << Idx << " ";
4210 // Create the variant and add it to the output list.
4211 std::vector<TreePatternNode*> NewChildren;
4212 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
4213 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
4214 auto R = llvm::make_unique<TreePatternNode>(
4215 Orig->getOperator(), NewChildren, Orig->getNumTypes());
4217 // Copy over properties.
4218 R->setName(Orig->getName());
4219 R->setPredicateFns(Orig->getPredicateFns());
4220 R->setTransformFn(Orig->getTransformFn());
4221 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
4222 R->setType(i, Orig->getExtType(i));
4224 // If this pattern cannot match, do not include it as a variant.
4225 std::string ErrString;
4226 // Scan to see if this pattern has already been emitted. We can get
4227 // duplication due to things like commuting:
4228 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4229 // which are the same pattern. Ignore the dups.
4230 if (R->canPatternMatch(ErrString, CDP) &&
4231 none_of(OutVariants, [&](TreePatternNode *Variant) {
4232 return R->isIsomorphicTo(Variant, DepVars);
4234 OutVariants.push_back(R.release());
4236 // Increment indices to the next permutation by incrementing the
4237 // indices from last index backward, e.g., generate the sequence
4238 // [0, 0], [0, 1], [1, 0], [1, 1].
4240 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
4241 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
4246 NotDone = (IdxsIdx >= 0);
4250 /// CombineChildVariants - A helper function for binary operators.
4252 static void CombineChildVariants(TreePatternNode *Orig,
4253 const std::vector<TreePatternNode*> &LHS,
4254 const std::vector<TreePatternNode*> &RHS,
4255 std::vector<TreePatternNode*> &OutVariants,
4256 CodeGenDAGPatterns &CDP,
4257 const MultipleUseVarSet &DepVars) {
4258 std::vector<std::vector<TreePatternNode*> > ChildVariants;
4259 ChildVariants.push_back(LHS);
4260 ChildVariants.push_back(RHS);
4261 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
4265 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
4266 std::vector<TreePatternNode *> &Children) {
4267 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
4268 Record *Operator = N->getOperator();
4270 // Only permit raw nodes.
4271 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
4272 N->getTransformFn()) {
4273 Children.push_back(N);
4277 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
4278 Children.push_back(N->getChild(0));
4280 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
4282 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
4283 Children.push_back(N->getChild(1));
4285 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
4288 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4289 /// the (potentially recursive) pattern by using algebraic laws.
4291 static void GenerateVariantsOf(TreePatternNode *N,
4292 std::vector<TreePatternNode*> &OutVariants,
4293 CodeGenDAGPatterns &CDP,
4294 const MultipleUseVarSet &DepVars) {
4295 // We cannot permute leaves or ComplexPattern uses.
4296 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
4297 OutVariants.push_back(N);
4301 // Look up interesting info about the node.
4302 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
4304 // If this node is associative, re-associate.
4305 if (NodeInfo.hasProperty(SDNPAssociative)) {
4306 // Re-associate by pulling together all of the linked operators
4307 std::vector<TreePatternNode*> MaximalChildren;
4308 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
4310 // Only handle child sizes of 3. Otherwise we'll end up trying too many
4312 if (MaximalChildren.size() == 3) {
4313 // Find the variants of all of our maximal children.
4314 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
4315 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
4316 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
4317 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
4319 // There are only two ways we can permute the tree:
4320 // (A op B) op C and A op (B op C)
4321 // Within these forms, we can also permute A/B/C.
4323 // Generate legal pair permutations of A/B/C.
4324 std::vector<TreePatternNode*> ABVariants;
4325 std::vector<TreePatternNode*> BAVariants;
4326 std::vector<TreePatternNode*> ACVariants;
4327 std::vector<TreePatternNode*> CAVariants;
4328 std::vector<TreePatternNode*> BCVariants;
4329 std::vector<TreePatternNode*> CBVariants;
4330 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4331 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4332 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4333 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4334 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4335 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
4337 // Combine those into the result: (x op x) op x
4338 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4339 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4340 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4341 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4342 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4343 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
4345 // Combine those into the result: x op (x op x)
4346 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4347 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4348 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4349 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4350 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4351 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
4356 // Compute permutations of all children.
4357 std::vector<std::vector<TreePatternNode*> > ChildVariants;
4358 ChildVariants.resize(N->getNumChildren());
4359 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
4360 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
4362 // Build all permutations based on how the children were formed.
4363 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
4365 // If this node is commutative, consider the commuted order.
4366 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4367 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
4368 assert((N->getNumChildren()>=2 || isCommIntrinsic) &&
4369 "Commutative but doesn't have 2 children!");
4370 // Don't count children which are actually register references.
4372 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4373 TreePatternNode *Child = N->getChild(i);
4374 if (Child->isLeaf())
4375 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
4376 Record *RR = DI->getDef();
4377 if (RR->isSubClassOf("Register"))
4382 // Consider the commuted order.
4383 if (isCommIntrinsic) {
4384 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4385 // operands are the commutative operands, and there might be more operands
4388 "Commutative intrinsic should have at least 3 children!");
4389 std::vector<std::vector<TreePatternNode*> > Variants;
4390 Variants.push_back(ChildVariants[0]); // Intrinsic id.
4391 Variants.push_back(ChildVariants[2]);
4392 Variants.push_back(ChildVariants[1]);
4393 for (unsigned i = 3; i != NC; ++i)
4394 Variants.push_back(ChildVariants[i]);
4395 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
4396 } else if (NC == N->getNumChildren()) {
4397 std::vector<std::vector<TreePatternNode*> > Variants;
4398 Variants.push_back(ChildVariants[1]);
4399 Variants.push_back(ChildVariants[0]);
4400 for (unsigned i = 2; i != NC; ++i)
4401 Variants.push_back(ChildVariants[i]);
4402 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
4408 // GenerateVariants - Generate variants. For example, commutative patterns can
4409 // match multiple ways. Add them to PatternsToMatch as well.
4410 void CodeGenDAGPatterns::GenerateVariants() {
4411 DEBUG(errs() << "Generating instruction variants.\n");
4413 // Loop over all of the patterns we've collected, checking to see if we can
4414 // generate variants of the instruction, through the exploitation of
4415 // identities. This permits the target to provide aggressive matching without
4416 // the .td file having to contain tons of variants of instructions.
4418 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4419 // intentionally do not reconsider these. Any variants of added patterns have
4420 // already been added.
4422 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
4423 MultipleUseVarSet DepVars;
4424 std::vector<TreePatternNode*> Variants;
4425 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
4426 DEBUG(errs() << "Dependent/multiply used variables: ");
4427 DEBUG(DumpDepVars(DepVars));
4428 DEBUG(errs() << "\n");
4429 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
4432 assert(!Variants.empty() && "Must create at least original variant!");
4433 if (Variants.size() == 1) // No additional variants for this pattern.
4436 DEBUG(errs() << "FOUND VARIANTS OF: ";
4437 PatternsToMatch[i].getSrcPattern()->dump();
4440 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
4441 TreePatternNode *Variant = Variants[v];
4443 DEBUG(errs() << " VAR#" << v << ": ";
4447 // Scan to see if an instruction or explicit pattern already matches this.
4448 bool AlreadyExists = false;
4449 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
4450 // Skip if the top level predicates do not match.
4451 if (PatternsToMatch[i].getPredicates() !=
4452 PatternsToMatch[p].getPredicates())
4454 // Check to see if this variant already exists.
4455 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
4457 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
4458 AlreadyExists = true;
4462 // If we already have it, ignore the variant.
4463 if (AlreadyExists) continue;
4465 // Otherwise, add it to the list of patterns we have.
4466 PatternsToMatch.push_back(PatternToMatch(
4467 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
4468 Variant, PatternsToMatch[i].getDstPattern(),
4469 PatternsToMatch[i].getDstRegs(),
4470 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
4473 DEBUG(errs() << "\n");