1 //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the CodeGenDAGPatterns class, which is used to read and
10 // represent the patterns present in a .td file for instructions.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenDAGPatterns.h"
15 #include "llvm/ADT/BitVector.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/MapVector.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/TableGen/Error.h"
27 #include "llvm/TableGen/Record.h"
34 #define DEBUG_TYPE "dag-patterns"
36 static inline bool isIntegerOrPtr(MVT VT
) {
37 return VT
.isInteger() || VT
== MVT::iPTR
;
39 static inline bool isFloatingPoint(MVT VT
) {
40 return VT
.isFloatingPoint();
42 static inline bool isVector(MVT VT
) {
45 static inline bool isScalar(MVT VT
) {
46 return !VT
.isVector();
49 template <typename Predicate
>
50 static bool berase_if(MachineValueTypeSet
&S
, Predicate P
) {
52 // It is ok to iterate over MachineValueTypeSet and remove elements from it
63 // --- TypeSetByHwMode
65 // This is a parameterized type-set class. For each mode there is a list
66 // of types that are currently possible for a given tree node. Type
67 // inference will apply to each mode separately.
69 TypeSetByHwMode::TypeSetByHwMode(ArrayRef
<ValueTypeByHwMode
> VTList
) {
70 for (const ValueTypeByHwMode
&VVT
: VTList
) {
72 AddrSpaces
.push_back(VVT
.PtrAddrSpace
);
76 bool TypeSetByHwMode::isValueTypeByHwMode(bool AllowEmpty
) const {
77 for (const auto &I
: *this) {
78 if (I
.second
.size() > 1)
80 if (!AllowEmpty
&& I
.second
.empty())
86 ValueTypeByHwMode
TypeSetByHwMode::getValueTypeByHwMode() const {
87 assert(isValueTypeByHwMode(true) &&
88 "The type set has multiple types for at least one HW mode");
89 ValueTypeByHwMode VVT
;
90 auto ASI
= AddrSpaces
.begin();
92 for (const auto &I
: *this) {
93 MVT T
= I
.second
.empty() ? MVT::Other
: *I
.second
.begin();
94 VVT
.getOrCreateTypeForMode(I
.first
, T
);
95 if (ASI
!= AddrSpaces
.end())
96 VVT
.PtrAddrSpace
= *ASI
++;
101 bool TypeSetByHwMode::isPossible() const {
102 for (const auto &I
: *this)
103 if (!I
.second
.empty())
108 bool TypeSetByHwMode::insert(const ValueTypeByHwMode
&VVT
) {
109 bool Changed
= false;
110 bool ContainsDefault
= false;
113 SmallDenseSet
<unsigned, 4> Modes
;
114 for (const auto &P
: VVT
) {
115 unsigned M
= P
.first
;
117 // Make sure there exists a set for each specific mode from VVT.
118 Changed
|= getOrCreate(M
).insert(P
.second
).second
;
119 // Cache VVT's default mode.
120 if (DefaultMode
== M
) {
121 ContainsDefault
= true;
126 // If VVT has a default mode, add the corresponding type to all
127 // modes in "this" that do not exist in VVT.
129 for (auto &I
: *this)
130 if (!Modes
.count(I
.first
))
131 Changed
|= I
.second
.insert(DT
).second
;
136 // Constrain the type set to be the intersection with VTS.
137 bool TypeSetByHwMode::constrain(const TypeSetByHwMode
&VTS
) {
138 bool Changed
= false;
140 for (const auto &I
: VTS
) {
141 unsigned M
= I
.first
;
142 if (M
== DefaultMode
|| hasMode(M
))
144 Map
.insert({M
, Map
.at(DefaultMode
)});
149 for (auto &I
: *this) {
150 unsigned M
= I
.first
;
151 SetType
&S
= I
.second
;
152 if (VTS
.hasMode(M
) || VTS
.hasDefault()) {
153 Changed
|= intersect(I
.second
, VTS
.get(M
));
154 } else if (!S
.empty()) {
162 template <typename Predicate
>
163 bool TypeSetByHwMode::constrain(Predicate P
) {
164 bool Changed
= false;
165 for (auto &I
: *this)
166 Changed
|= berase_if(I
.second
, [&P
](MVT VT
) { return !P(VT
); });
170 template <typename Predicate
>
171 bool TypeSetByHwMode::assign_if(const TypeSetByHwMode
&VTS
, Predicate P
) {
173 for (const auto &I
: VTS
) {
174 SetType
&S
= getOrCreate(I
.first
);
175 for (auto J
: I
.second
)
182 void TypeSetByHwMode::writeToStream(raw_ostream
&OS
) const {
183 SmallVector
<unsigned, 4> Modes
;
184 Modes
.reserve(Map
.size());
186 for (const auto &I
: *this)
187 Modes
.push_back(I
.first
);
192 array_pod_sort(Modes
.begin(), Modes
.end());
195 for (unsigned M
: Modes
) {
196 OS
<< ' ' << getModeName(M
) << ':';
197 writeToStream(get(M
), OS
);
202 void TypeSetByHwMode::writeToStream(const SetType
&S
, raw_ostream
&OS
) {
203 SmallVector
<MVT
, 4> Types(S
.begin(), S
.end());
204 array_pod_sort(Types
.begin(), Types
.end());
207 for (unsigned i
= 0, e
= Types
.size(); i
!= e
; ++i
) {
208 OS
<< ValueTypeByHwMode::getMVTName(Types
[i
]);
215 bool TypeSetByHwMode::operator==(const TypeSetByHwMode
&VTS
) const {
216 // The isSimple call is much quicker than hasDefault - check this first.
217 bool IsSimple
= isSimple();
218 bool VTSIsSimple
= VTS
.isSimple();
219 if (IsSimple
&& VTSIsSimple
)
220 return *begin() == *VTS
.begin();
222 // Speedup: We have a default if the set is simple.
223 bool HaveDefault
= IsSimple
|| hasDefault();
224 bool VTSHaveDefault
= VTSIsSimple
|| VTS
.hasDefault();
225 if (HaveDefault
!= VTSHaveDefault
)
228 SmallDenseSet
<unsigned, 4> Modes
;
229 for (auto &I
: *this)
230 Modes
.insert(I
.first
);
231 for (const auto &I
: VTS
)
232 Modes
.insert(I
.first
);
235 // Both sets have default mode.
236 for (unsigned M
: Modes
) {
237 if (get(M
) != VTS
.get(M
))
241 // Neither set has default mode.
242 for (unsigned M
: Modes
) {
243 // If there is no default mode, an empty set is equivalent to not having
244 // the corresponding mode.
245 bool NoModeThis
= !hasMode(M
) || get(M
).empty();
246 bool NoModeVTS
= !VTS
.hasMode(M
) || VTS
.get(M
).empty();
247 if (NoModeThis
!= NoModeVTS
)
250 if (get(M
) != VTS
.get(M
))
259 raw_ostream
&operator<<(raw_ostream
&OS
, const TypeSetByHwMode
&T
) {
266 void TypeSetByHwMode::dump() const {
267 dbgs() << *this << '\n';
270 bool TypeSetByHwMode::intersect(SetType
&Out
, const SetType
&In
) {
271 bool OutP
= Out
.count(MVT::iPTR
), InP
= In
.count(MVT::iPTR
);
272 auto Int
= [&In
](MVT T
) -> bool { return !In
.count(T
); };
275 return berase_if(Out
, Int
);
277 // Compute the intersection of scalars separately to account for only
278 // one set containing iPTR.
279 // The itersection of iPTR with a set of integer scalar types that does not
280 // include iPTR will result in the most specific scalar type:
281 // - iPTR is more specific than any set with two elements or more
282 // - iPTR is less specific than any single integer scalar type.
284 // { iPTR } * { i32 } -> { i32 }
285 // { iPTR } * { i32 i64 } -> { iPTR }
287 // { iPTR i32 } * { i32 } -> { i32 }
288 // { iPTR i32 } * { i32 i64 } -> { i32 i64 }
289 // { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 }
291 // Compute the difference between the two sets in such a way that the
292 // iPTR is in the set that is being subtracted. This is to see if there
293 // are any extra scalars in the set without iPTR that are not in the
294 // set containing iPTR. Then the iPTR could be considered a "wildcard"
295 // matching these scalars. If there is only one such scalar, it would
296 // replace the iPTR, if there are more, the iPTR would be retained.
300 berase_if(Diff
, [&In
](MVT T
) { return In
.count(T
); });
301 // Pre-remove these elements and rely only on InP/OutP to determine
302 // whether a change has been made.
303 berase_if(Out
, [&Diff
](MVT T
) { return Diff
.count(T
); });
306 berase_if(Diff
, [&Out
](MVT T
) { return Out
.count(T
); });
307 Out
.erase(MVT::iPTR
);
310 // The actual intersection.
311 bool Changed
= berase_if(Out
, Int
);
312 unsigned NumD
= Diff
.size();
317 Out
.insert(*Diff
.begin());
318 // This is a change only if Out was the one with iPTR (which is now
322 // Multiple elements from Out are now replaced with iPTR.
323 Out
.insert(MVT::iPTR
);
329 bool TypeSetByHwMode::validate() const {
333 bool AllEmpty
= true;
334 for (const auto &I
: *this)
335 AllEmpty
&= I
.second
.empty();
343 bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode
&Out
,
344 const TypeSetByHwMode
&In
) {
345 ValidateOnExit
_1(Out
, *this);
347 if (In
.empty() || Out
== In
|| TP
.hasError())
354 bool Changed
= Out
.constrain(In
);
355 if (Changed
&& Out
.empty())
356 TP
.error("Type contradiction");
361 bool TypeInfer::forceArbitrary(TypeSetByHwMode
&Out
) {
362 ValidateOnExit
_1(Out
, *this);
365 assert(!Out
.empty() && "cannot pick from an empty set");
367 bool Changed
= false;
368 for (auto &I
: Out
) {
369 TypeSetByHwMode::SetType
&S
= I
.second
;
372 MVT T
= *S
.begin(); // Pick the first element.
380 bool TypeInfer::EnforceInteger(TypeSetByHwMode
&Out
) {
381 ValidateOnExit
_1(Out
, *this);
385 return Out
.constrain(isIntegerOrPtr
);
387 return Out
.assign_if(getLegalTypes(), isIntegerOrPtr
);
390 bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode
&Out
) {
391 ValidateOnExit
_1(Out
, *this);
395 return Out
.constrain(isFloatingPoint
);
397 return Out
.assign_if(getLegalTypes(), isFloatingPoint
);
400 bool TypeInfer::EnforceScalar(TypeSetByHwMode
&Out
) {
401 ValidateOnExit
_1(Out
, *this);
405 return Out
.constrain(isScalar
);
407 return Out
.assign_if(getLegalTypes(), isScalar
);
410 bool TypeInfer::EnforceVector(TypeSetByHwMode
&Out
) {
411 ValidateOnExit
_1(Out
, *this);
415 return Out
.constrain(isVector
);
417 return Out
.assign_if(getLegalTypes(), isVector
);
420 bool TypeInfer::EnforceAny(TypeSetByHwMode
&Out
) {
421 ValidateOnExit
_1(Out
, *this);
422 if (TP
.hasError() || !Out
.empty())
425 Out
= getLegalTypes();
429 template <typename Iter
, typename Pred
, typename Less
>
430 static Iter
min_if(Iter B
, Iter E
, Pred P
, Less L
) {
434 for (Iter I
= B
; I
!= E
; ++I
) {
437 if (Min
== E
|| L(*I
, *Min
))
443 template <typename Iter
, typename Pred
, typename Less
>
444 static Iter
max_if(Iter B
, Iter E
, Pred P
, Less L
) {
448 for (Iter I
= B
; I
!= E
; ++I
) {
451 if (Max
== E
|| L(*Max
, *I
))
457 /// Make sure that for each type in Small, there exists a larger type in Big.
458 bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode
&Small
,
459 TypeSetByHwMode
&Big
) {
460 ValidateOnExit
_1(Small
, *this), _2(Big
, *this);
463 bool Changed
= false;
466 Changed
|= EnforceAny(Small
);
468 Changed
|= EnforceAny(Big
);
470 assert(Small
.hasDefault() && Big
.hasDefault());
472 std::vector
<unsigned> Modes
= union_modes(Small
, Big
);
474 // 1. Only allow integer or floating point types and make sure that
475 // both sides are both integer or both floating point.
476 // 2. Make sure that either both sides have vector types, or neither
478 for (unsigned M
: Modes
) {
479 TypeSetByHwMode::SetType
&S
= Small
.get(M
);
480 TypeSetByHwMode::SetType
&B
= Big
.get(M
);
482 if (any_of(S
, isIntegerOrPtr
) && any_of(S
, isIntegerOrPtr
)) {
483 auto NotInt
= [](MVT VT
) { return !isIntegerOrPtr(VT
); };
484 Changed
|= berase_if(S
, NotInt
) |
485 berase_if(B
, NotInt
);
486 } else if (any_of(S
, isFloatingPoint
) && any_of(B
, isFloatingPoint
)) {
487 auto NotFP
= [](MVT VT
) { return !isFloatingPoint(VT
); };
488 Changed
|= berase_if(S
, NotFP
) |
490 } else if (S
.empty() || B
.empty()) {
491 Changed
= !S
.empty() || !B
.empty();
495 TP
.error("Incompatible types");
499 if (none_of(S
, isVector
) || none_of(B
, isVector
)) {
500 Changed
|= berase_if(S
, isVector
) |
501 berase_if(B
, isVector
);
505 auto LT
= [](MVT A
, MVT B
) -> bool {
506 return A
.getScalarSizeInBits() < B
.getScalarSizeInBits() ||
507 (A
.getScalarSizeInBits() == B
.getScalarSizeInBits() &&
508 A
.getSizeInBits() < B
.getSizeInBits());
510 auto LE
= [<
](MVT A
, MVT B
) -> bool {
511 // This function is used when removing elements: when a vector is compared
512 // to a non-vector, it should return false (to avoid removal).
513 if (A
.isVector() != B
.isVector())
516 return LT(A
, B
) || (A
.getScalarSizeInBits() == B
.getScalarSizeInBits() &&
517 A
.getSizeInBits() == B
.getSizeInBits());
520 for (unsigned M
: Modes
) {
521 TypeSetByHwMode::SetType
&S
= Small
.get(M
);
522 TypeSetByHwMode::SetType
&B
= Big
.get(M
);
523 // MinS = min scalar in Small, remove all scalars from Big that are
524 // smaller-or-equal than MinS.
525 auto MinS
= min_if(S
.begin(), S
.end(), isScalar
, LT
);
527 Changed
|= berase_if(B
, std::bind(LE
, std::placeholders::_1
, *MinS
));
529 // MaxS = max scalar in Big, remove all scalars from Small that are
531 auto MaxS
= max_if(B
.begin(), B
.end(), isScalar
, LT
);
533 Changed
|= berase_if(S
, std::bind(LE
, *MaxS
, std::placeholders::_1
));
535 // MinV = min vector in Small, remove all vectors from Big that are
536 // smaller-or-equal than MinV.
537 auto MinV
= min_if(S
.begin(), S
.end(), isVector
, LT
);
539 Changed
|= berase_if(B
, std::bind(LE
, std::placeholders::_1
, *MinV
));
541 // MaxV = max vector in Big, remove all vectors from Small that are
543 auto MaxV
= max_if(B
.begin(), B
.end(), isVector
, LT
);
545 Changed
|= berase_if(S
, std::bind(LE
, *MaxV
, std::placeholders::_1
));
551 /// 1. Ensure that for each type T in Vec, T is a vector type, and that
552 /// for each type U in Elem, U is a scalar type.
553 /// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)
554 /// type T in Vec, such that U is the element type of T.
555 bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode
&Vec
,
556 TypeSetByHwMode
&Elem
) {
557 ValidateOnExit
_1(Vec
, *this), _2(Elem
, *this);
560 bool Changed
= false;
563 Changed
|= EnforceVector(Vec
);
565 Changed
|= EnforceScalar(Elem
);
567 for (unsigned M
: union_modes(Vec
, Elem
)) {
568 TypeSetByHwMode::SetType
&V
= Vec
.get(M
);
569 TypeSetByHwMode::SetType
&E
= Elem
.get(M
);
571 Changed
|= berase_if(V
, isScalar
); // Scalar = !vector
572 Changed
|= berase_if(E
, isVector
); // Vector = !scalar
573 assert(!V
.empty() && !E
.empty());
575 SmallSet
<MVT
,4> VT
, ST
;
576 // Collect element types from the "vector" set.
578 VT
.insert(T
.getVectorElementType());
579 // Collect scalar types from the "element" set.
583 // Remove from V all (vector) types whose element type is not in S.
584 Changed
|= berase_if(V
, [&ST
](MVT T
) -> bool {
585 return !ST
.count(T
.getVectorElementType());
587 // Remove from E all (scalar) types, for which there is no corresponding
589 Changed
|= berase_if(E
, [&VT
](MVT T
) -> bool { return !VT
.count(T
); });
595 bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode
&Vec
,
596 const ValueTypeByHwMode
&VVT
) {
597 TypeSetByHwMode
Tmp(VVT
);
598 ValidateOnExit
_1(Vec
, *this), _2(Tmp
, *this);
599 return EnforceVectorEltTypeIs(Vec
, Tmp
);
602 /// Ensure that for each type T in Sub, T is a vector type, and there
603 /// exists a type U in Vec such that U is a vector type with the same
604 /// element type as T and at least as many elements as T.
605 bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode
&Vec
,
606 TypeSetByHwMode
&Sub
) {
607 ValidateOnExit
_1(Vec
, *this), _2(Sub
, *this);
611 /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.
612 auto IsSubVec
= [](MVT B
, MVT P
) -> bool {
613 if (!B
.isVector() || !P
.isVector())
615 // Logically a <4 x i32> is a valid subvector of <n x 4 x i32>
616 // but until there are obvious use-cases for this, keep the
618 if (B
.isScalableVector() != P
.isScalableVector())
620 if (B
.getVectorElementType() != P
.getVectorElementType())
622 return B
.getVectorNumElements() < P
.getVectorNumElements();
625 /// Return true if S has no element (vector type) that T is a sub-vector of,
626 /// i.e. has the same element type as T and more elements.
627 auto NoSubV
= [&IsSubVec
](const TypeSetByHwMode::SetType
&S
, MVT T
) -> bool {
628 for (const auto &I
: S
)
634 /// Return true if S has no element (vector type) that T is a super-vector
635 /// of, i.e. has the same element type as T and fewer elements.
636 auto NoSupV
= [&IsSubVec
](const TypeSetByHwMode::SetType
&S
, MVT T
) -> bool {
637 for (const auto &I
: S
)
643 bool Changed
= false;
646 Changed
|= EnforceVector(Vec
);
648 Changed
|= EnforceVector(Sub
);
650 for (unsigned M
: union_modes(Vec
, Sub
)) {
651 TypeSetByHwMode::SetType
&S
= Sub
.get(M
);
652 TypeSetByHwMode::SetType
&V
= Vec
.get(M
);
654 Changed
|= berase_if(S
, isScalar
);
656 // Erase all types from S that are not sub-vectors of a type in V.
657 Changed
|= berase_if(S
, std::bind(NoSubV
, V
, std::placeholders::_1
));
659 // Erase all types from V that are not super-vectors of a type in S.
660 Changed
|= berase_if(V
, std::bind(NoSupV
, S
, std::placeholders::_1
));
666 /// 1. Ensure that V has a scalar type iff W has a scalar type.
667 /// 2. Ensure that for each vector type T in V, there exists a vector
668 /// type U in W, such that T and U have the same number of elements.
669 /// 3. Ensure that for each vector type U in W, there exists a vector
670 /// type T in V, such that T and U have the same number of elements
672 bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode
&V
, TypeSetByHwMode
&W
) {
673 ValidateOnExit
_1(V
, *this), _2(W
, *this);
677 bool Changed
= false;
679 Changed
|= EnforceAny(V
);
681 Changed
|= EnforceAny(W
);
683 // An actual vector type cannot have 0 elements, so we can treat scalars
684 // as zero-length vectors. This way both vectors and scalars can be
685 // processed identically.
686 auto NoLength
= [](const SmallSet
<unsigned,2> &Lengths
, MVT T
) -> bool {
687 return !Lengths
.count(T
.isVector() ? T
.getVectorNumElements() : 0);
690 for (unsigned M
: union_modes(V
, W
)) {
691 TypeSetByHwMode::SetType
&VS
= V
.get(M
);
692 TypeSetByHwMode::SetType
&WS
= W
.get(M
);
694 SmallSet
<unsigned,2> VN
, WN
;
696 VN
.insert(T
.isVector() ? T
.getVectorNumElements() : 0);
698 WN
.insert(T
.isVector() ? T
.getVectorNumElements() : 0);
700 Changed
|= berase_if(VS
, std::bind(NoLength
, WN
, std::placeholders::_1
));
701 Changed
|= berase_if(WS
, std::bind(NoLength
, VN
, std::placeholders::_1
));
706 /// 1. Ensure that for each type T in A, there exists a type U in B,
707 /// such that T and U have equal size in bits.
708 /// 2. Ensure that for each type U in B, there exists a type T in A
709 /// such that T and U have equal size in bits (reverse of 1).
710 bool TypeInfer::EnforceSameSize(TypeSetByHwMode
&A
, TypeSetByHwMode
&B
) {
711 ValidateOnExit
_1(A
, *this), _2(B
, *this);
714 bool Changed
= false;
716 Changed
|= EnforceAny(A
);
718 Changed
|= EnforceAny(B
);
720 auto NoSize
= [](const SmallSet
<unsigned,2> &Sizes
, MVT T
) -> bool {
721 return !Sizes
.count(T
.getSizeInBits());
724 for (unsigned M
: union_modes(A
, B
)) {
725 TypeSetByHwMode::SetType
&AS
= A
.get(M
);
726 TypeSetByHwMode::SetType
&BS
= B
.get(M
);
727 SmallSet
<unsigned,2> AN
, BN
;
730 AN
.insert(T
.getSizeInBits());
732 BN
.insert(T
.getSizeInBits());
734 Changed
|= berase_if(AS
, std::bind(NoSize
, BN
, std::placeholders::_1
));
735 Changed
|= berase_if(BS
, std::bind(NoSize
, AN
, std::placeholders::_1
));
741 void TypeInfer::expandOverloads(TypeSetByHwMode
&VTS
) {
742 ValidateOnExit
_1(VTS
, *this);
743 const TypeSetByHwMode
&Legal
= getLegalTypes();
744 assert(Legal
.isDefaultOnly() && "Default-mode only expected");
745 const TypeSetByHwMode::SetType
&LegalTypes
= Legal
.get(DefaultMode
);
748 expandOverloads(I
.second
, LegalTypes
);
751 void TypeInfer::expandOverloads(TypeSetByHwMode::SetType
&Out
,
752 const TypeSetByHwMode::SetType
&Legal
) {
755 if (!T
.isOverloaded())
759 // MachineValueTypeSet allows iteration and erasing.
764 switch (Ov
.SimpleTy
) {
766 Out
.insert(MVT::iPTR
);
769 for (MVT T
: MVT::integer_valuetypes())
772 for (MVT T
: MVT::integer_vector_valuetypes())
777 for (MVT T
: MVT::fp_valuetypes())
780 for (MVT T
: MVT::fp_vector_valuetypes())
785 for (MVT T
: MVT::vector_valuetypes())
790 for (MVT T
: MVT::all_valuetypes())
800 const TypeSetByHwMode
&TypeInfer::getLegalTypes() {
801 if (!LegalTypesCached
) {
802 TypeSetByHwMode::SetType
&LegalTypes
= LegalCache
.getOrCreate(DefaultMode
);
803 // Stuff all types from all modes into the default mode.
804 const TypeSetByHwMode
<S
= TP
.getDAGPatterns().getLegalTypes();
805 for (const auto &I
: LTS
)
806 LegalTypes
.insert(I
.second
);
807 LegalTypesCached
= true;
809 assert(LegalCache
.isDefaultOnly() && "Default-mode only expected");
814 TypeInfer::ValidateOnExit::~ValidateOnExit() {
815 if (Infer
.Validate
&& !VTS
.validate()) {
816 dbgs() << "Type set is empty for each HW mode:\n"
817 "possible type contradiction in the pattern below "
818 "(use -print-records with llvm-tblgen to see all "
819 "expanded records).\n";
821 llvm_unreachable(nullptr);
827 //===----------------------------------------------------------------------===//
828 // ScopedName Implementation
829 //===----------------------------------------------------------------------===//
831 bool ScopedName::operator==(const ScopedName
&o
) const {
832 return Scope
== o
.Scope
&& Identifier
== o
.Identifier
;
835 bool ScopedName::operator!=(const ScopedName
&o
) const {
836 return !(*this == o
);
840 //===----------------------------------------------------------------------===//
841 // TreePredicateFn Implementation
842 //===----------------------------------------------------------------------===//
844 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
845 TreePredicateFn::TreePredicateFn(TreePattern
*N
) : PatFragRec(N
) {
847 (!hasPredCode() || !hasImmCode()) &&
848 ".td file corrupt: can't have a node predicate *and* an imm predicate");
851 bool TreePredicateFn::hasPredCode() const {
852 return isLoad() || isStore() || isAtomic() ||
853 !PatFragRec
->getRecord()->getValueAsString("PredicateCode").empty();
856 std::string
TreePredicateFn::getPredCode() const {
857 std::string Code
= "";
859 if (!isLoad() && !isStore() && !isAtomic()) {
860 Record
*MemoryVT
= getMemoryVT();
863 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
864 "MemoryVT requires IsLoad or IsStore");
867 if (!isLoad() && !isStore()) {
869 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
870 "IsUnindexed requires IsLoad or IsStore");
872 Record
*ScalarMemoryVT
= getScalarMemoryVT();
875 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
876 "ScalarMemoryVT requires IsLoad or IsStore");
879 if (isLoad() + isStore() + isAtomic() > 1)
880 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
881 "IsLoad, IsStore, and IsAtomic are mutually exclusive");
884 if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&
885 !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&
886 getScalarMemoryVT() == nullptr && getAddressSpaces() == nullptr &&
887 getMinAlignment() < 1)
888 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
889 "IsLoad cannot be used by itself");
892 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
893 "IsNonExtLoad requires IsLoad");
895 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
896 "IsAnyExtLoad requires IsLoad");
898 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
899 "IsSignExtLoad requires IsLoad");
901 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
902 "IsZeroExtLoad requires IsLoad");
906 if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&
907 getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr &&
908 getAddressSpaces() == nullptr && getMinAlignment() < 1)
909 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
910 "IsStore cannot be used by itself");
912 if (isNonTruncStore())
913 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
914 "IsNonTruncStore requires IsStore");
916 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
917 "IsTruncStore requires IsStore");
921 if (getMemoryVT() == nullptr && !isAtomicOrderingMonotonic() &&
922 !isAtomicOrderingAcquire() && !isAtomicOrderingRelease() &&
923 !isAtomicOrderingAcquireRelease() &&
924 !isAtomicOrderingSequentiallyConsistent() &&
925 !isAtomicOrderingAcquireOrStronger() &&
926 !isAtomicOrderingReleaseOrStronger() &&
927 !isAtomicOrderingWeakerThanAcquire() &&
928 !isAtomicOrderingWeakerThanRelease())
929 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
930 "IsAtomic cannot be used by itself");
932 if (isAtomicOrderingMonotonic())
933 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
934 "IsAtomicOrderingMonotonic requires IsAtomic");
935 if (isAtomicOrderingAcquire())
936 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
937 "IsAtomicOrderingAcquire requires IsAtomic");
938 if (isAtomicOrderingRelease())
939 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
940 "IsAtomicOrderingRelease requires IsAtomic");
941 if (isAtomicOrderingAcquireRelease())
942 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
943 "IsAtomicOrderingAcquireRelease requires IsAtomic");
944 if (isAtomicOrderingSequentiallyConsistent())
945 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
946 "IsAtomicOrderingSequentiallyConsistent requires IsAtomic");
947 if (isAtomicOrderingAcquireOrStronger())
948 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
949 "IsAtomicOrderingAcquireOrStronger requires IsAtomic");
950 if (isAtomicOrderingReleaseOrStronger())
951 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
952 "IsAtomicOrderingReleaseOrStronger requires IsAtomic");
953 if (isAtomicOrderingWeakerThanAcquire())
954 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
955 "IsAtomicOrderingWeakerThanAcquire requires IsAtomic");
958 if (isLoad() || isStore() || isAtomic()) {
959 if (ListInit
*AddressSpaces
= getAddressSpaces()) {
960 Code
+= "unsigned AddrSpace = cast<MemSDNode>(N)->getAddressSpace();\n"
964 for (Init
*Val
: AddressSpaces
->getValues()) {
970 IntInit
*IntVal
= dyn_cast
<IntInit
>(Val
);
972 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
973 "AddressSpaces element must be integer");
976 Code
+= "AddrSpace != " + utostr(IntVal
->getValue());
979 Code
+= ")\nreturn false;\n";
982 int64_t MinAlign
= getMinAlignment();
984 Code
+= "if (cast<MemSDNode>(N)->getAlignment() < ";
985 Code
+= utostr(MinAlign
);
986 Code
+= ")\nreturn false;\n";
989 Record
*MemoryVT
= getMemoryVT();
992 Code
+= ("if (cast<MemSDNode>(N)->getMemoryVT() != MVT::" +
993 MemoryVT
->getName() + ") return false;\n")
997 if (isAtomic() && isAtomicOrderingMonotonic())
998 Code
+= "if (cast<AtomicSDNode>(N)->getOrdering() != "
999 "AtomicOrdering::Monotonic) return false;\n";
1000 if (isAtomic() && isAtomicOrderingAcquire())
1001 Code
+= "if (cast<AtomicSDNode>(N)->getOrdering() != "
1002 "AtomicOrdering::Acquire) return false;\n";
1003 if (isAtomic() && isAtomicOrderingRelease())
1004 Code
+= "if (cast<AtomicSDNode>(N)->getOrdering() != "
1005 "AtomicOrdering::Release) return false;\n";
1006 if (isAtomic() && isAtomicOrderingAcquireRelease())
1007 Code
+= "if (cast<AtomicSDNode>(N)->getOrdering() != "
1008 "AtomicOrdering::AcquireRelease) return false;\n";
1009 if (isAtomic() && isAtomicOrderingSequentiallyConsistent())
1010 Code
+= "if (cast<AtomicSDNode>(N)->getOrdering() != "
1011 "AtomicOrdering::SequentiallyConsistent) return false;\n";
1013 if (isAtomic() && isAtomicOrderingAcquireOrStronger())
1014 Code
+= "if (!isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1016 if (isAtomic() && isAtomicOrderingWeakerThanAcquire())
1017 Code
+= "if (isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1020 if (isAtomic() && isAtomicOrderingReleaseOrStronger())
1021 Code
+= "if (!isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1023 if (isAtomic() && isAtomicOrderingWeakerThanRelease())
1024 Code
+= "if (isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1027 if (isLoad() || isStore()) {
1028 StringRef SDNodeName
= isLoad() ? "LoadSDNode" : "StoreSDNode";
1031 Code
+= ("if (cast<" + SDNodeName
+
1032 ">(N)->getAddressingMode() != ISD::UNINDEXED) "
1037 if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
1038 isZeroExtLoad()) > 1)
1039 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1040 "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
1041 "IsZeroExtLoad are mutually exclusive");
1043 Code
+= "if (cast<LoadSDNode>(N)->getExtensionType() != "
1044 "ISD::NON_EXTLOAD) return false;\n";
1046 Code
+= "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
1048 if (isSignExtLoad())
1049 Code
+= "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
1051 if (isZeroExtLoad())
1052 Code
+= "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
1055 if ((isNonTruncStore() + isTruncStore()) > 1)
1057 getOrigPatFragRecord()->getRecord()->getLoc(),
1058 "IsNonTruncStore, and IsTruncStore are mutually exclusive");
1059 if (isNonTruncStore())
1061 " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1064 " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1067 Record
*ScalarMemoryVT
= getScalarMemoryVT();
1070 Code
+= ("if (cast<" + SDNodeName
+
1071 ">(N)->getMemoryVT().getScalarType() != MVT::" +
1072 ScalarMemoryVT
->getName() + ") return false;\n")
1076 std::string PredicateCode
= PatFragRec
->getRecord()->getValueAsString("PredicateCode");
1078 Code
+= PredicateCode
;
1080 if (PredicateCode
.empty() && !Code
.empty())
1081 Code
+= "return true;\n";
1086 bool TreePredicateFn::hasImmCode() const {
1087 return !PatFragRec
->getRecord()->getValueAsString("ImmediateCode").empty();
1090 std::string
TreePredicateFn::getImmCode() const {
1091 return PatFragRec
->getRecord()->getValueAsString("ImmediateCode");
1094 bool TreePredicateFn::immCodeUsesAPInt() const {
1095 return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
1098 bool TreePredicateFn::immCodeUsesAPFloat() const {
1100 // The return value will be false when IsAPFloat is unset.
1101 return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
1105 bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field
,
1109 getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field
, Unset
);
1112 return Result
== Value
;
1114 bool TreePredicateFn::usesOperands() const {
1115 return isPredefinedPredicateEqualTo("PredicateCodeUsesOperands", true);
1117 bool TreePredicateFn::isLoad() const {
1118 return isPredefinedPredicateEqualTo("IsLoad", true);
1120 bool TreePredicateFn::isStore() const {
1121 return isPredefinedPredicateEqualTo("IsStore", true);
1123 bool TreePredicateFn::isAtomic() const {
1124 return isPredefinedPredicateEqualTo("IsAtomic", true);
1126 bool TreePredicateFn::isUnindexed() const {
1127 return isPredefinedPredicateEqualTo("IsUnindexed", true);
1129 bool TreePredicateFn::isNonExtLoad() const {
1130 return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
1132 bool TreePredicateFn::isAnyExtLoad() const {
1133 return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
1135 bool TreePredicateFn::isSignExtLoad() const {
1136 return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
1138 bool TreePredicateFn::isZeroExtLoad() const {
1139 return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
1141 bool TreePredicateFn::isNonTruncStore() const {
1142 return isPredefinedPredicateEqualTo("IsTruncStore", false);
1144 bool TreePredicateFn::isTruncStore() const {
1145 return isPredefinedPredicateEqualTo("IsTruncStore", true);
1147 bool TreePredicateFn::isAtomicOrderingMonotonic() const {
1148 return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true);
1150 bool TreePredicateFn::isAtomicOrderingAcquire() const {
1151 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true);
1153 bool TreePredicateFn::isAtomicOrderingRelease() const {
1154 return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true);
1156 bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
1157 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true);
1159 bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
1160 return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent",
1163 bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {
1164 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", true);
1166 bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {
1167 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", false);
1169 bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {
1170 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", true);
1172 bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {
1173 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", false);
1175 Record
*TreePredicateFn::getMemoryVT() const {
1176 Record
*R
= getOrigPatFragRecord()->getRecord();
1177 if (R
->isValueUnset("MemoryVT"))
1179 return R
->getValueAsDef("MemoryVT");
1182 ListInit
*TreePredicateFn::getAddressSpaces() const {
1183 Record
*R
= getOrigPatFragRecord()->getRecord();
1184 if (R
->isValueUnset("AddressSpaces"))
1186 return R
->getValueAsListInit("AddressSpaces");
1189 int64_t TreePredicateFn::getMinAlignment() const {
1190 Record
*R
= getOrigPatFragRecord()->getRecord();
1191 if (R
->isValueUnset("MinAlignment"))
1193 return R
->getValueAsInt("MinAlignment");
1196 Record
*TreePredicateFn::getScalarMemoryVT() const {
1197 Record
*R
= getOrigPatFragRecord()->getRecord();
1198 if (R
->isValueUnset("ScalarMemoryVT"))
1200 return R
->getValueAsDef("ScalarMemoryVT");
1202 bool TreePredicateFn::hasGISelPredicateCode() const {
1203 return !PatFragRec
->getRecord()
1204 ->getValueAsString("GISelPredicateCode")
1207 std::string
TreePredicateFn::getGISelPredicateCode() const {
1208 return PatFragRec
->getRecord()->getValueAsString("GISelPredicateCode");
1211 StringRef
TreePredicateFn::getImmType() const {
1212 if (immCodeUsesAPInt())
1213 return "const APInt &";
1214 if (immCodeUsesAPFloat())
1215 return "const APFloat &";
1219 StringRef
TreePredicateFn::getImmTypeIdentifier() const {
1220 if (immCodeUsesAPInt())
1222 else if (immCodeUsesAPFloat())
1227 /// isAlwaysTrue - Return true if this is a noop predicate.
1228 bool TreePredicateFn::isAlwaysTrue() const {
1229 return !hasPredCode() && !hasImmCode();
1232 /// Return the name to use in the generated code to reference this, this is
1233 /// "Predicate_foo" if from a pattern fragment "foo".
1234 std::string
TreePredicateFn::getFnName() const {
1235 return "Predicate_" + PatFragRec
->getRecord()->getName().str();
1238 /// getCodeToRunOnSDNode - Return the code for the function body that
1239 /// evaluates this predicate. The argument is expected to be in "Node",
1240 /// not N. This handles casting and conversion to a concrete node type as
1242 std::string
TreePredicateFn::getCodeToRunOnSDNode() const {
1243 // Handle immediate predicates first.
1244 std::string ImmCode
= getImmCode();
1245 if (!ImmCode
.empty()) {
1247 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1248 "IsLoad cannot be used with ImmLeaf or its subclasses");
1250 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1251 "IsStore cannot be used with ImmLeaf or its subclasses");
1254 getOrigPatFragRecord()->getRecord()->getLoc(),
1255 "IsUnindexed cannot be used with ImmLeaf or its subclasses");
1258 getOrigPatFragRecord()->getRecord()->getLoc(),
1259 "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
1262 getOrigPatFragRecord()->getRecord()->getLoc(),
1263 "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
1264 if (isSignExtLoad())
1266 getOrigPatFragRecord()->getRecord()->getLoc(),
1267 "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
1268 if (isZeroExtLoad())
1270 getOrigPatFragRecord()->getRecord()->getLoc(),
1271 "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
1272 if (isNonTruncStore())
1274 getOrigPatFragRecord()->getRecord()->getLoc(),
1275 "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
1278 getOrigPatFragRecord()->getRecord()->getLoc(),
1279 "IsTruncStore cannot be used with ImmLeaf or its subclasses");
1281 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1282 "MemoryVT cannot be used with ImmLeaf or its subclasses");
1283 if (getScalarMemoryVT())
1285 getOrigPatFragRecord()->getRecord()->getLoc(),
1286 "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
1288 std::string Result
= (" " + getImmType() + " Imm = ").str();
1289 if (immCodeUsesAPFloat())
1290 Result
+= "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
1291 else if (immCodeUsesAPInt())
1292 Result
+= "cast<ConstantSDNode>(Node)->getAPIntValue();\n";
1294 Result
+= "cast<ConstantSDNode>(Node)->getSExtValue();\n";
1295 return Result
+ ImmCode
;
1298 // Handle arbitrary node predicates.
1299 assert(hasPredCode() && "Don't have any predicate code!");
1300 StringRef ClassName
;
1301 if (PatFragRec
->getOnlyTree()->isLeaf())
1302 ClassName
= "SDNode";
1304 Record
*Op
= PatFragRec
->getOnlyTree()->getOperator();
1305 ClassName
= PatFragRec
->getDAGPatterns().getSDNodeInfo(Op
).getSDClassName();
1308 if (ClassName
== "SDNode")
1309 Result
= " SDNode *N = Node;\n";
1311 Result
= " auto *N = cast<" + ClassName
.str() + ">(Node);\n";
1313 return (Twine(Result
) + " (void)N;\n" + getPredCode()).str();
1316 //===----------------------------------------------------------------------===//
1317 // PatternToMatch implementation
1320 static bool isImmAllOnesAllZerosMatch(const TreePatternNode
*P
) {
1323 DefInit
*DI
= dyn_cast
<DefInit
>(P
->getLeafValue());
1327 Record
*R
= DI
->getDef();
1328 return R
->getName() == "immAllOnesV" || R
->getName() == "immAllZerosV";
1331 /// getPatternSize - Return the 'size' of this pattern. We want to match large
1332 /// patterns before small ones. This is used to determine the size of a
1334 static unsigned getPatternSize(const TreePatternNode
*P
,
1335 const CodeGenDAGPatterns
&CGP
) {
1336 unsigned Size
= 3; // The node itself.
1337 // If the root node is a ConstantSDNode, increases its size.
1338 // e.g. (set R32:$dst, 0).
1339 if (P
->isLeaf() && isa
<IntInit
>(P
->getLeafValue()))
1342 if (const ComplexPattern
*AM
= P
->getComplexPatternInfo(CGP
)) {
1343 Size
+= AM
->getComplexity();
1344 // We don't want to count any children twice, so return early.
1348 // If this node has some predicate function that must match, it adds to the
1349 // complexity of this node.
1350 if (!P
->getPredicateCalls().empty())
1353 // Count children in the count if they are also nodes.
1354 for (unsigned i
= 0, e
= P
->getNumChildren(); i
!= e
; ++i
) {
1355 const TreePatternNode
*Child
= P
->getChild(i
);
1356 if (!Child
->isLeaf() && Child
->getNumTypes()) {
1357 const TypeSetByHwMode
&T0
= Child
->getExtType(0);
1358 // At this point, all variable type sets should be simple, i.e. only
1359 // have a default mode.
1360 if (T0
.getMachineValueType() != MVT::Other
) {
1361 Size
+= getPatternSize(Child
, CGP
);
1365 if (Child
->isLeaf()) {
1366 if (isa
<IntInit
>(Child
->getLeafValue()))
1367 Size
+= 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
1368 else if (Child
->getComplexPatternInfo(CGP
))
1369 Size
+= getPatternSize(Child
, CGP
);
1370 else if (isImmAllOnesAllZerosMatch(Child
))
1371 Size
+= 4; // Matches a build_vector(+3) and a predicate (+1).
1372 else if (!Child
->getPredicateCalls().empty())
1380 /// Compute the complexity metric for the input pattern. This roughly
1381 /// corresponds to the number of nodes that are covered.
1382 int PatternToMatch::
1383 getPatternComplexity(const CodeGenDAGPatterns
&CGP
) const {
1384 return getPatternSize(getSrcPattern(), CGP
) + getAddedComplexity();
1387 /// getPredicateCheck - Return a single string containing all of this
1388 /// pattern's predicates concatenated with "&&" operators.
1390 std::string
PatternToMatch::getPredicateCheck() const {
1391 SmallVector
<const Predicate
*,4> PredList
;
1392 for (const Predicate
&P
: Predicates
) {
1393 if (!P
.getCondString().empty())
1394 PredList
.push_back(&P
);
1396 llvm::sort(PredList
, deref
<llvm::less
>());
1399 for (unsigned i
= 0, e
= PredList
.size(); i
!= e
; ++i
) {
1402 Check
+= '(' + PredList
[i
]->getCondString() + ')';
1407 //===----------------------------------------------------------------------===//
1408 // SDTypeConstraint implementation
1411 SDTypeConstraint::SDTypeConstraint(Record
*R
, const CodeGenHwModes
&CGH
) {
1412 OperandNo
= R
->getValueAsInt("OperandNum");
1414 if (R
->isSubClassOf("SDTCisVT")) {
1415 ConstraintType
= SDTCisVT
;
1416 VVT
= getValueTypeByHwMode(R
->getValueAsDef("VT"), CGH
);
1417 for (const auto &P
: VVT
)
1418 if (P
.second
== MVT::isVoid
)
1419 PrintFatalError(R
->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
1420 } else if (R
->isSubClassOf("SDTCisPtrTy")) {
1421 ConstraintType
= SDTCisPtrTy
;
1422 } else if (R
->isSubClassOf("SDTCisInt")) {
1423 ConstraintType
= SDTCisInt
;
1424 } else if (R
->isSubClassOf("SDTCisFP")) {
1425 ConstraintType
= SDTCisFP
;
1426 } else if (R
->isSubClassOf("SDTCisVec")) {
1427 ConstraintType
= SDTCisVec
;
1428 } else if (R
->isSubClassOf("SDTCisSameAs")) {
1429 ConstraintType
= SDTCisSameAs
;
1430 x
.SDTCisSameAs_Info
.OtherOperandNum
= R
->getValueAsInt("OtherOperandNum");
1431 } else if (R
->isSubClassOf("SDTCisVTSmallerThanOp")) {
1432 ConstraintType
= SDTCisVTSmallerThanOp
;
1433 x
.SDTCisVTSmallerThanOp_Info
.OtherOperandNum
=
1434 R
->getValueAsInt("OtherOperandNum");
1435 } else if (R
->isSubClassOf("SDTCisOpSmallerThanOp")) {
1436 ConstraintType
= SDTCisOpSmallerThanOp
;
1437 x
.SDTCisOpSmallerThanOp_Info
.BigOperandNum
=
1438 R
->getValueAsInt("BigOperandNum");
1439 } else if (R
->isSubClassOf("SDTCisEltOfVec")) {
1440 ConstraintType
= SDTCisEltOfVec
;
1441 x
.SDTCisEltOfVec_Info
.OtherOperandNum
= R
->getValueAsInt("OtherOpNum");
1442 } else if (R
->isSubClassOf("SDTCisSubVecOfVec")) {
1443 ConstraintType
= SDTCisSubVecOfVec
;
1444 x
.SDTCisSubVecOfVec_Info
.OtherOperandNum
=
1445 R
->getValueAsInt("OtherOpNum");
1446 } else if (R
->isSubClassOf("SDTCVecEltisVT")) {
1447 ConstraintType
= SDTCVecEltisVT
;
1448 VVT
= getValueTypeByHwMode(R
->getValueAsDef("VT"), CGH
);
1449 for (const auto &P
: VVT
) {
1452 PrintFatalError(R
->getLoc(),
1453 "Cannot use vector type as SDTCVecEltisVT");
1454 if (!T
.isInteger() && !T
.isFloatingPoint())
1455 PrintFatalError(R
->getLoc(), "Must use integer or floating point type "
1456 "as SDTCVecEltisVT");
1458 } else if (R
->isSubClassOf("SDTCisSameNumEltsAs")) {
1459 ConstraintType
= SDTCisSameNumEltsAs
;
1460 x
.SDTCisSameNumEltsAs_Info
.OtherOperandNum
=
1461 R
->getValueAsInt("OtherOperandNum");
1462 } else if (R
->isSubClassOf("SDTCisSameSizeAs")) {
1463 ConstraintType
= SDTCisSameSizeAs
;
1464 x
.SDTCisSameSizeAs_Info
.OtherOperandNum
=
1465 R
->getValueAsInt("OtherOperandNum");
1467 PrintFatalError(R
->getLoc(),
1468 "Unrecognized SDTypeConstraint '" + R
->getName() + "'!\n");
1472 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
1473 /// N, and the result number in ResNo.
1474 static TreePatternNode
*getOperandNum(unsigned OpNo
, TreePatternNode
*N
,
1475 const SDNodeInfo
&NodeInfo
,
1477 unsigned NumResults
= NodeInfo
.getNumResults();
1478 if (OpNo
< NumResults
) {
1485 if (OpNo
>= N
->getNumChildren()) {
1487 raw_string_ostream
OS(S
);
1488 OS
<< "Invalid operand number in type constraint "
1489 << (OpNo
+NumResults
) << " ";
1491 PrintFatalError(OS
.str());
1494 return N
->getChild(OpNo
);
1497 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
1498 /// constraint to the nodes operands. This returns true if it makes a
1499 /// change, false otherwise. If a type contradiction is found, flag an error.
1500 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode
*N
,
1501 const SDNodeInfo
&NodeInfo
,
1502 TreePattern
&TP
) const {
1506 unsigned ResNo
= 0; // The result number being referenced.
1507 TreePatternNode
*NodeToApply
= getOperandNum(OperandNo
, N
, NodeInfo
, ResNo
);
1508 TypeInfer
&TI
= TP
.getInfer();
1510 switch (ConstraintType
) {
1512 // Operand must be a particular type.
1513 return NodeToApply
->UpdateNodeType(ResNo
, VVT
, TP
);
1515 // Operand must be same as target pointer type.
1516 return NodeToApply
->UpdateNodeType(ResNo
, MVT::iPTR
, TP
);
1518 // Require it to be one of the legal integer VTs.
1519 return TI
.EnforceInteger(NodeToApply
->getExtType(ResNo
));
1521 // Require it to be one of the legal fp VTs.
1522 return TI
.EnforceFloatingPoint(NodeToApply
->getExtType(ResNo
));
1524 // Require it to be one of the legal vector VTs.
1525 return TI
.EnforceVector(NodeToApply
->getExtType(ResNo
));
1526 case SDTCisSameAs
: {
1527 unsigned OResNo
= 0;
1528 TreePatternNode
*OtherNode
=
1529 getOperandNum(x
.SDTCisSameAs_Info
.OtherOperandNum
, N
, NodeInfo
, OResNo
);
1530 return NodeToApply
->UpdateNodeType(ResNo
, OtherNode
->getExtType(OResNo
),TP
)|
1531 OtherNode
->UpdateNodeType(OResNo
,NodeToApply
->getExtType(ResNo
),TP
);
1533 case SDTCisVTSmallerThanOp
: {
1534 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1535 // have an integer type that is smaller than the VT.
1536 if (!NodeToApply
->isLeaf() ||
1537 !isa
<DefInit
>(NodeToApply
->getLeafValue()) ||
1538 !static_cast<DefInit
*>(NodeToApply
->getLeafValue())->getDef()
1539 ->isSubClassOf("ValueType")) {
1540 TP
.error(N
->getOperator()->getName() + " expects a VT operand!");
1543 DefInit
*DI
= static_cast<DefInit
*>(NodeToApply
->getLeafValue());
1544 const CodeGenTarget
&T
= TP
.getDAGPatterns().getTargetInfo();
1545 auto VVT
= getValueTypeByHwMode(DI
->getDef(), T
.getHwModes());
1546 TypeSetByHwMode
TypeListTmp(VVT
);
1548 unsigned OResNo
= 0;
1549 TreePatternNode
*OtherNode
=
1550 getOperandNum(x
.SDTCisVTSmallerThanOp_Info
.OtherOperandNum
, N
, NodeInfo
,
1553 return TI
.EnforceSmallerThan(TypeListTmp
, OtherNode
->getExtType(OResNo
));
1555 case SDTCisOpSmallerThanOp
: {
1556 unsigned BResNo
= 0;
1557 TreePatternNode
*BigOperand
=
1558 getOperandNum(x
.SDTCisOpSmallerThanOp_Info
.BigOperandNum
, N
, NodeInfo
,
1560 return TI
.EnforceSmallerThan(NodeToApply
->getExtType(ResNo
),
1561 BigOperand
->getExtType(BResNo
));
1563 case SDTCisEltOfVec
: {
1564 unsigned VResNo
= 0;
1565 TreePatternNode
*VecOperand
=
1566 getOperandNum(x
.SDTCisEltOfVec_Info
.OtherOperandNum
, N
, NodeInfo
,
1568 // Filter vector types out of VecOperand that don't have the right element
1570 return TI
.EnforceVectorEltTypeIs(VecOperand
->getExtType(VResNo
),
1571 NodeToApply
->getExtType(ResNo
));
1573 case SDTCisSubVecOfVec
: {
1574 unsigned VResNo
= 0;
1575 TreePatternNode
*BigVecOperand
=
1576 getOperandNum(x
.SDTCisSubVecOfVec_Info
.OtherOperandNum
, N
, NodeInfo
,
1579 // Filter vector types out of BigVecOperand that don't have the
1580 // right subvector type.
1581 return TI
.EnforceVectorSubVectorTypeIs(BigVecOperand
->getExtType(VResNo
),
1582 NodeToApply
->getExtType(ResNo
));
1584 case SDTCVecEltisVT
: {
1585 return TI
.EnforceVectorEltTypeIs(NodeToApply
->getExtType(ResNo
), VVT
);
1587 case SDTCisSameNumEltsAs
: {
1588 unsigned OResNo
= 0;
1589 TreePatternNode
*OtherNode
=
1590 getOperandNum(x
.SDTCisSameNumEltsAs_Info
.OtherOperandNum
,
1591 N
, NodeInfo
, OResNo
);
1592 return TI
.EnforceSameNumElts(OtherNode
->getExtType(OResNo
),
1593 NodeToApply
->getExtType(ResNo
));
1595 case SDTCisSameSizeAs
: {
1596 unsigned OResNo
= 0;
1597 TreePatternNode
*OtherNode
=
1598 getOperandNum(x
.SDTCisSameSizeAs_Info
.OtherOperandNum
,
1599 N
, NodeInfo
, OResNo
);
1600 return TI
.EnforceSameSize(OtherNode
->getExtType(OResNo
),
1601 NodeToApply
->getExtType(ResNo
));
1604 llvm_unreachable("Invalid ConstraintType!");
1607 // Update the node type to match an instruction operand or result as specified
1608 // in the ins or outs lists on the instruction definition. Return true if the
1609 // type was actually changed.
1610 bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo
,
1613 // The 'unknown' operand indicates that types should be inferred from the
1615 if (Operand
->isSubClassOf("unknown_class"))
1618 // The Operand class specifies a type directly.
1619 if (Operand
->isSubClassOf("Operand")) {
1620 Record
*R
= Operand
->getValueAsDef("Type");
1621 const CodeGenTarget
&T
= TP
.getDAGPatterns().getTargetInfo();
1622 return UpdateNodeType(ResNo
, getValueTypeByHwMode(R
, T
.getHwModes()), TP
);
1625 // PointerLikeRegClass has a type that is determined at runtime.
1626 if (Operand
->isSubClassOf("PointerLikeRegClass"))
1627 return UpdateNodeType(ResNo
, MVT::iPTR
, TP
);
1629 // Both RegisterClass and RegisterOperand operands derive their types from a
1630 // register class def.
1631 Record
*RC
= nullptr;
1632 if (Operand
->isSubClassOf("RegisterClass"))
1634 else if (Operand
->isSubClassOf("RegisterOperand"))
1635 RC
= Operand
->getValueAsDef("RegClass");
1637 assert(RC
&& "Unknown operand type");
1638 CodeGenTarget
&Tgt
= TP
.getDAGPatterns().getTargetInfo();
1639 return UpdateNodeType(ResNo
, Tgt
.getRegisterClass(RC
).getValueTypes(), TP
);
1642 bool TreePatternNode::ContainsUnresolvedType(TreePattern
&TP
) const {
1643 for (unsigned i
= 0, e
= Types
.size(); i
!= e
; ++i
)
1644 if (!TP
.getInfer().isConcrete(Types
[i
], true))
1646 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
1647 if (getChild(i
)->ContainsUnresolvedType(TP
))
1652 bool TreePatternNode::hasProperTypeByHwMode() const {
1653 for (const TypeSetByHwMode
&S
: Types
)
1654 if (!S
.isDefaultOnly())
1656 for (const TreePatternNodePtr
&C
: Children
)
1657 if (C
->hasProperTypeByHwMode())
1662 bool TreePatternNode::hasPossibleType() const {
1663 for (const TypeSetByHwMode
&S
: Types
)
1664 if (!S
.isPossible())
1666 for (const TreePatternNodePtr
&C
: Children
)
1667 if (!C
->hasPossibleType())
1672 bool TreePatternNode::setDefaultMode(unsigned Mode
) {
1673 for (TypeSetByHwMode
&S
: Types
) {
1675 // Check if the selected mode had a type conflict.
1676 if (S
.get(DefaultMode
).empty())
1679 for (const TreePatternNodePtr
&C
: Children
)
1680 if (!C
->setDefaultMode(Mode
))
1685 //===----------------------------------------------------------------------===//
1686 // SDNodeInfo implementation
1688 SDNodeInfo::SDNodeInfo(Record
*R
, const CodeGenHwModes
&CGH
) : Def(R
) {
1689 EnumName
= R
->getValueAsString("Opcode");
1690 SDClassName
= R
->getValueAsString("SDClass");
1691 Record
*TypeProfile
= R
->getValueAsDef("TypeProfile");
1692 NumResults
= TypeProfile
->getValueAsInt("NumResults");
1693 NumOperands
= TypeProfile
->getValueAsInt("NumOperands");
1695 // Parse the properties.
1696 Properties
= parseSDPatternOperatorProperties(R
);
1698 // Parse the type constraints.
1699 std::vector
<Record
*> ConstraintList
=
1700 TypeProfile
->getValueAsListOfDefs("Constraints");
1701 for (Record
*R
: ConstraintList
)
1702 TypeConstraints
.emplace_back(R
, CGH
);
1705 /// getKnownType - If the type constraints on this node imply a fixed type
1706 /// (e.g. all stores return void, etc), then return it as an
1707 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
1708 MVT::SimpleValueType
SDNodeInfo::getKnownType(unsigned ResNo
) const {
1709 unsigned NumResults
= getNumResults();
1710 assert(NumResults
<= 1 &&
1711 "We only work with nodes with zero or one result so far!");
1712 assert(ResNo
== 0 && "Only handles single result nodes so far");
1714 for (const SDTypeConstraint
&Constraint
: TypeConstraints
) {
1715 // Make sure that this applies to the correct node result.
1716 if (Constraint
.OperandNo
>= NumResults
) // FIXME: need value #
1719 switch (Constraint
.ConstraintType
) {
1721 case SDTypeConstraint::SDTCisVT
:
1722 if (Constraint
.VVT
.isSimple())
1723 return Constraint
.VVT
.getSimple().SimpleTy
;
1725 case SDTypeConstraint::SDTCisPtrTy
:
1732 //===----------------------------------------------------------------------===//
1733 // TreePatternNode implementation
1736 static unsigned GetNumNodeResults(Record
*Operator
, CodeGenDAGPatterns
&CDP
) {
1737 if (Operator
->getName() == "set" ||
1738 Operator
->getName() == "implicit")
1739 return 0; // All return nothing.
1741 if (Operator
->isSubClassOf("Intrinsic"))
1742 return CDP
.getIntrinsic(Operator
).IS
.RetVTs
.size();
1744 if (Operator
->isSubClassOf("SDNode"))
1745 return CDP
.getSDNodeInfo(Operator
).getNumResults();
1747 if (Operator
->isSubClassOf("PatFrags")) {
1748 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1749 // the forward reference case where one pattern fragment references another
1750 // before it is processed.
1751 if (TreePattern
*PFRec
= CDP
.getPatternFragmentIfRead(Operator
)) {
1752 // The number of results of a fragment with alternative records is the
1753 // maximum number of results across all alternatives.
1754 unsigned NumResults
= 0;
1755 for (auto T
: PFRec
->getTrees())
1756 NumResults
= std::max(NumResults
, T
->getNumTypes());
1760 ListInit
*LI
= Operator
->getValueAsListInit("Fragments");
1761 assert(LI
&& "Invalid Fragment");
1762 unsigned NumResults
= 0;
1763 for (Init
*I
: LI
->getValues()) {
1764 Record
*Op
= nullptr;
1765 if (DagInit
*Dag
= dyn_cast
<DagInit
>(I
))
1766 if (DefInit
*DI
= dyn_cast
<DefInit
>(Dag
->getOperator()))
1768 assert(Op
&& "Invalid Fragment");
1769 NumResults
= std::max(NumResults
, GetNumNodeResults(Op
, CDP
));
1774 if (Operator
->isSubClassOf("Instruction")) {
1775 CodeGenInstruction
&InstInfo
= CDP
.getTargetInfo().getInstruction(Operator
);
1777 unsigned NumDefsToAdd
= InstInfo
.Operands
.NumDefs
;
1779 // Subtract any defaulted outputs.
1780 for (unsigned i
= 0; i
!= InstInfo
.Operands
.NumDefs
; ++i
) {
1781 Record
*OperandNode
= InstInfo
.Operands
[i
].Rec
;
1783 if (OperandNode
->isSubClassOf("OperandWithDefaultOps") &&
1784 !CDP
.getDefaultOperand(OperandNode
).DefaultOps
.empty())
1788 // Add on one implicit def if it has a resolvable type.
1789 if (InstInfo
.HasOneImplicitDefWithKnownVT(CDP
.getTargetInfo()) !=MVT::Other
)
1791 return NumDefsToAdd
;
1794 if (Operator
->isSubClassOf("SDNodeXForm"))
1795 return 1; // FIXME: Generalize SDNodeXForm
1797 if (Operator
->isSubClassOf("ValueType"))
1798 return 1; // A type-cast of one result.
1800 if (Operator
->isSubClassOf("ComplexPattern"))
1803 errs() << *Operator
;
1804 PrintFatalError("Unhandled node in GetNumNodeResults");
1807 void TreePatternNode::print(raw_ostream
&OS
) const {
1809 OS
<< *getLeafValue();
1811 OS
<< '(' << getOperator()->getName();
1813 for (unsigned i
= 0, e
= Types
.size(); i
!= e
; ++i
) {
1815 getExtType(i
).writeToStream(OS
);
1819 if (getNumChildren() != 0) {
1821 getChild(0)->print(OS
);
1822 for (unsigned i
= 1, e
= getNumChildren(); i
!= e
; ++i
) {
1824 getChild(i
)->print(OS
);
1830 for (const TreePredicateCall
&Pred
: PredicateCalls
) {
1833 OS
<< Pred
.Scope
<< ":";
1834 OS
<< Pred
.Fn
.getFnName() << ">>";
1837 OS
<< "<<X:" << TransformFn
->getName() << ">>";
1838 if (!getName().empty())
1839 OS
<< ":$" << getName();
1841 for (const ScopedName
&Name
: NamesAsPredicateArg
)
1842 OS
<< ":$pred:" << Name
.getScope() << ":" << Name
.getIdentifier();
1844 void TreePatternNode::dump() const {
1848 /// isIsomorphicTo - Return true if this node is recursively
1849 /// isomorphic to the specified node. For this comparison, the node's
1850 /// entire state is considered. The assigned name is ignored, since
1851 /// nodes with differing names are considered isomorphic. However, if
1852 /// the assigned name is present in the dependent variable set, then
1853 /// the assigned name is considered significant and the node is
1854 /// isomorphic if the names match.
1855 bool TreePatternNode::isIsomorphicTo(const TreePatternNode
*N
,
1856 const MultipleUseVarSet
&DepVars
) const {
1857 if (N
== this) return true;
1858 if (N
->isLeaf() != isLeaf() || getExtTypes() != N
->getExtTypes() ||
1859 getPredicateCalls() != N
->getPredicateCalls() ||
1860 getTransformFn() != N
->getTransformFn())
1864 if (DefInit
*DI
= dyn_cast
<DefInit
>(getLeafValue())) {
1865 if (DefInit
*NDI
= dyn_cast
<DefInit
>(N
->getLeafValue())) {
1866 return ((DI
->getDef() == NDI
->getDef())
1867 && (DepVars
.find(getName()) == DepVars
.end()
1868 || getName() == N
->getName()));
1871 return getLeafValue() == N
->getLeafValue();
1874 if (N
->getOperator() != getOperator() ||
1875 N
->getNumChildren() != getNumChildren()) return false;
1876 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
1877 if (!getChild(i
)->isIsomorphicTo(N
->getChild(i
), DepVars
))
1882 /// clone - Make a copy of this tree and all of its children.
1884 TreePatternNodePtr
TreePatternNode::clone() const {
1885 TreePatternNodePtr New
;
1887 New
= std::make_shared
<TreePatternNode
>(getLeafValue(), getNumTypes());
1889 std::vector
<TreePatternNodePtr
> CChildren
;
1890 CChildren
.reserve(Children
.size());
1891 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
1892 CChildren
.push_back(getChild(i
)->clone());
1893 New
= std::make_shared
<TreePatternNode
>(getOperator(), std::move(CChildren
),
1896 New
->setName(getName());
1897 New
->setNamesAsPredicateArg(getNamesAsPredicateArg());
1899 New
->setPredicateCalls(getPredicateCalls());
1900 New
->setTransformFn(getTransformFn());
1904 /// RemoveAllTypes - Recursively strip all the types of this tree.
1905 void TreePatternNode::RemoveAllTypes() {
1906 // Reset to unknown type.
1907 std::fill(Types
.begin(), Types
.end(), TypeSetByHwMode());
1908 if (isLeaf()) return;
1909 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
1910 getChild(i
)->RemoveAllTypes();
1914 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1915 /// with actual values specified by ArgMap.
1916 void TreePatternNode::SubstituteFormalArguments(
1917 std::map
<std::string
, TreePatternNodePtr
> &ArgMap
) {
1918 if (isLeaf()) return;
1920 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
) {
1921 TreePatternNode
*Child
= getChild(i
);
1922 if (Child
->isLeaf()) {
1923 Init
*Val
= Child
->getLeafValue();
1924 // Note that, when substituting into an output pattern, Val might be an
1926 if (isa
<UnsetInit
>(Val
) || (isa
<DefInit
>(Val
) &&
1927 cast
<DefInit
>(Val
)->getDef()->getName() == "node")) {
1928 // We found a use of a formal argument, replace it with its value.
1929 TreePatternNodePtr NewChild
= ArgMap
[Child
->getName()];
1930 assert(NewChild
&& "Couldn't find formal argument!");
1931 assert((Child
->getPredicateCalls().empty() ||
1932 NewChild
->getPredicateCalls() == Child
->getPredicateCalls()) &&
1933 "Non-empty child predicate clobbered!");
1934 setChild(i
, std::move(NewChild
));
1937 getChild(i
)->SubstituteFormalArguments(ArgMap
);
1943 /// InlinePatternFragments - If this pattern refers to any pattern
1944 /// fragments, return the set of inlined versions (this can be more than
1945 /// one if a PatFrags record has multiple alternatives).
1946 void TreePatternNode::InlinePatternFragments(
1947 TreePatternNodePtr T
, TreePattern
&TP
,
1948 std::vector
<TreePatternNodePtr
> &OutAlternatives
) {
1954 OutAlternatives
.push_back(T
); // nothing to do.
1958 Record
*Op
= getOperator();
1960 if (!Op
->isSubClassOf("PatFrags")) {
1961 if (getNumChildren() == 0) {
1962 OutAlternatives
.push_back(T
);
1966 // Recursively inline children nodes.
1967 std::vector
<std::vector
<TreePatternNodePtr
> > ChildAlternatives
;
1968 ChildAlternatives
.resize(getNumChildren());
1969 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
) {
1970 TreePatternNodePtr Child
= getChildShared(i
);
1971 Child
->InlinePatternFragments(Child
, TP
, ChildAlternatives
[i
]);
1972 // If there are no alternatives for any child, there are no
1973 // alternatives for this expression as whole.
1974 if (ChildAlternatives
[i
].empty())
1977 for (auto NewChild
: ChildAlternatives
[i
])
1978 assert((Child
->getPredicateCalls().empty() ||
1979 NewChild
->getPredicateCalls() == Child
->getPredicateCalls()) &&
1980 "Non-empty child predicate clobbered!");
1983 // The end result is an all-pairs construction of the resultant pattern.
1984 std::vector
<unsigned> Idxs
;
1985 Idxs
.resize(ChildAlternatives
.size());
1988 // Create the variant and add it to the output list.
1989 std::vector
<TreePatternNodePtr
> NewChildren
;
1990 for (unsigned i
= 0, e
= ChildAlternatives
.size(); i
!= e
; ++i
)
1991 NewChildren
.push_back(ChildAlternatives
[i
][Idxs
[i
]]);
1992 TreePatternNodePtr R
= std::make_shared
<TreePatternNode
>(
1993 getOperator(), std::move(NewChildren
), getNumTypes());
1995 // Copy over properties.
1996 R
->setName(getName());
1997 R
->setNamesAsPredicateArg(getNamesAsPredicateArg());
1998 R
->setPredicateCalls(getPredicateCalls());
1999 R
->setTransformFn(getTransformFn());
2000 for (unsigned i
= 0, e
= getNumTypes(); i
!= e
; ++i
)
2001 R
->setType(i
, getExtType(i
));
2002 for (unsigned i
= 0, e
= getNumResults(); i
!= e
; ++i
)
2003 R
->setResultIndex(i
, getResultIndex(i
));
2005 // Register alternative.
2006 OutAlternatives
.push_back(R
);
2008 // Increment indices to the next permutation by incrementing the
2009 // indices from last index backward, e.g., generate the sequence
2010 // [0, 0], [0, 1], [1, 0], [1, 1].
2012 for (IdxsIdx
= Idxs
.size() - 1; IdxsIdx
>= 0; --IdxsIdx
) {
2013 if (++Idxs
[IdxsIdx
] == ChildAlternatives
[IdxsIdx
].size())
2018 NotDone
= (IdxsIdx
>= 0);
2024 // Otherwise, we found a reference to a fragment. First, look up its
2025 // TreePattern record.
2026 TreePattern
*Frag
= TP
.getDAGPatterns().getPatternFragment(Op
);
2028 // Verify that we are passing the right number of operands.
2029 if (Frag
->getNumArgs() != Children
.size()) {
2030 TP
.error("'" + Op
->getName() + "' fragment requires " +
2031 Twine(Frag
->getNumArgs()) + " operands!");
2035 TreePredicateFn
PredFn(Frag
);
2037 if (TreePredicateFn(Frag
).usesOperands())
2038 Scope
= TP
.getDAGPatterns().allocateScope();
2040 // Compute the map of formal to actual arguments.
2041 std::map
<std::string
, TreePatternNodePtr
> ArgMap
;
2042 for (unsigned i
= 0, e
= Frag
->getNumArgs(); i
!= e
; ++i
) {
2043 TreePatternNodePtr Child
= getChildShared(i
);
2045 Child
= Child
->clone();
2046 Child
->addNameAsPredicateArg(ScopedName(Scope
, Frag
->getArgName(i
)));
2048 ArgMap
[Frag
->getArgName(i
)] = Child
;
2051 // Loop over all fragment alternatives.
2052 for (auto Alternative
: Frag
->getTrees()) {
2053 TreePatternNodePtr FragTree
= Alternative
->clone();
2055 if (!PredFn
.isAlwaysTrue())
2056 FragTree
->addPredicateCall(PredFn
, Scope
);
2058 // Resolve formal arguments to their actual value.
2059 if (Frag
->getNumArgs())
2060 FragTree
->SubstituteFormalArguments(ArgMap
);
2062 // Transfer types. Note that the resolved alternative may have fewer
2063 // (but not more) results than the PatFrags node.
2064 FragTree
->setName(getName());
2065 for (unsigned i
= 0, e
= FragTree
->getNumTypes(); i
!= e
; ++i
)
2066 FragTree
->UpdateNodeType(i
, getExtType(i
), TP
);
2068 // Transfer in the old predicates.
2069 for (const TreePredicateCall
&Pred
: getPredicateCalls())
2070 FragTree
->addPredicateCall(Pred
);
2072 // The fragment we inlined could have recursive inlining that is needed. See
2073 // if there are any pattern fragments in it and inline them as needed.
2074 FragTree
->InlinePatternFragments(FragTree
, TP
, OutAlternatives
);
2078 /// getImplicitType - Check to see if the specified record has an implicit
2079 /// type which should be applied to it. This will infer the type of register
2080 /// references from the register file information, for example.
2082 /// When Unnamed is set, return the type of a DAG operand with no name, such as
2083 /// the F8RC register class argument in:
2085 /// (COPY_TO_REGCLASS GPR:$src, F8RC)
2087 /// When Unnamed is false, return the type of a named DAG operand such as the
2088 /// GPR:$src operand above.
2090 static TypeSetByHwMode
getImplicitType(Record
*R
, unsigned ResNo
,
2094 CodeGenDAGPatterns
&CDP
= TP
.getDAGPatterns();
2096 // Check to see if this is a register operand.
2097 if (R
->isSubClassOf("RegisterOperand")) {
2098 assert(ResNo
== 0 && "Regoperand ref only has one result!");
2100 return TypeSetByHwMode(); // Unknown.
2101 Record
*RegClass
= R
->getValueAsDef("RegClass");
2102 const CodeGenTarget
&T
= TP
.getDAGPatterns().getTargetInfo();
2103 return TypeSetByHwMode(T
.getRegisterClass(RegClass
).getValueTypes());
2106 // Check to see if this is a register or a register class.
2107 if (R
->isSubClassOf("RegisterClass")) {
2108 assert(ResNo
== 0 && "Regclass ref only has one result!");
2109 // An unnamed register class represents itself as an i32 immediate, for
2110 // example on a COPY_TO_REGCLASS instruction.
2112 return TypeSetByHwMode(MVT::i32
);
2114 // In a named operand, the register class provides the possible set of
2117 return TypeSetByHwMode(); // Unknown.
2118 const CodeGenTarget
&T
= TP
.getDAGPatterns().getTargetInfo();
2119 return TypeSetByHwMode(T
.getRegisterClass(R
).getValueTypes());
2122 if (R
->isSubClassOf("PatFrags")) {
2123 assert(ResNo
== 0 && "FIXME: PatFrag with multiple results?");
2124 // Pattern fragment types will be resolved when they are inlined.
2125 return TypeSetByHwMode(); // Unknown.
2128 if (R
->isSubClassOf("Register")) {
2129 assert(ResNo
== 0 && "Registers only produce one result!");
2131 return TypeSetByHwMode(); // Unknown.
2132 const CodeGenTarget
&T
= TP
.getDAGPatterns().getTargetInfo();
2133 return TypeSetByHwMode(T
.getRegisterVTs(R
));
2136 if (R
->isSubClassOf("SubRegIndex")) {
2137 assert(ResNo
== 0 && "SubRegisterIndices only produce one result!");
2138 return TypeSetByHwMode(MVT::i32
);
2141 if (R
->isSubClassOf("ValueType")) {
2142 assert(ResNo
== 0 && "This node only has one result!");
2143 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
2145 // (sext_inreg GPR:$src, i16)
2148 return TypeSetByHwMode(MVT::Other
);
2149 // With a name, the ValueType simply provides the type of the named
2152 // (sext_inreg i32:$src, i16)
2155 return TypeSetByHwMode(); // Unknown.
2156 const CodeGenHwModes
&CGH
= CDP
.getTargetInfo().getHwModes();
2157 return TypeSetByHwMode(getValueTypeByHwMode(R
, CGH
));
2160 if (R
->isSubClassOf("CondCode")) {
2161 assert(ResNo
== 0 && "This node only has one result!");
2162 // Using a CondCodeSDNode.
2163 return TypeSetByHwMode(MVT::Other
);
2166 if (R
->isSubClassOf("ComplexPattern")) {
2167 assert(ResNo
== 0 && "FIXME: ComplexPattern with multiple results?");
2169 return TypeSetByHwMode(); // Unknown.
2170 return TypeSetByHwMode(CDP
.getComplexPattern(R
).getValueType());
2172 if (R
->isSubClassOf("PointerLikeRegClass")) {
2173 assert(ResNo
== 0 && "Regclass can only have one result!");
2174 TypeSetByHwMode
VTS(MVT::iPTR
);
2175 TP
.getInfer().expandOverloads(VTS
);
2179 if (R
->getName() == "node" || R
->getName() == "srcvalue" ||
2180 R
->getName() == "zero_reg" || R
->getName() == "immAllOnesV" ||
2181 R
->getName() == "immAllZerosV" || R
->getName() == "undef_tied_input") {
2183 return TypeSetByHwMode(); // Unknown.
2186 if (R
->isSubClassOf("Operand")) {
2187 const CodeGenHwModes
&CGH
= CDP
.getTargetInfo().getHwModes();
2188 Record
*T
= R
->getValueAsDef("Type");
2189 return TypeSetByHwMode(getValueTypeByHwMode(T
, CGH
));
2192 TP
.error("Unknown node flavor used in pattern: " + R
->getName());
2193 return TypeSetByHwMode(MVT::Other
);
2197 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
2198 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
2199 const CodeGenIntrinsic
*TreePatternNode::
2200 getIntrinsicInfo(const CodeGenDAGPatterns
&CDP
) const {
2201 if (getOperator() != CDP
.get_intrinsic_void_sdnode() &&
2202 getOperator() != CDP
.get_intrinsic_w_chain_sdnode() &&
2203 getOperator() != CDP
.get_intrinsic_wo_chain_sdnode())
2206 unsigned IID
= cast
<IntInit
>(getChild(0)->getLeafValue())->getValue();
2207 return &CDP
.getIntrinsicInfo(IID
);
2210 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
2211 /// return the ComplexPattern information, otherwise return null.
2212 const ComplexPattern
*
2213 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns
&CGP
) const {
2216 DefInit
*DI
= dyn_cast
<DefInit
>(getLeafValue());
2221 Rec
= getOperator();
2223 if (!Rec
->isSubClassOf("ComplexPattern"))
2225 return &CGP
.getComplexPattern(Rec
);
2228 unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns
&CGP
) const {
2229 // A ComplexPattern specifically declares how many results it fills in.
2230 if (const ComplexPattern
*CP
= getComplexPatternInfo(CGP
))
2231 return CP
->getNumOperands();
2233 // If MIOperandInfo is specified, that gives the count.
2235 DefInit
*DI
= dyn_cast
<DefInit
>(getLeafValue());
2236 if (DI
&& DI
->getDef()->isSubClassOf("Operand")) {
2237 DagInit
*MIOps
= DI
->getDef()->getValueAsDag("MIOperandInfo");
2238 if (MIOps
->getNumArgs())
2239 return MIOps
->getNumArgs();
2243 // Otherwise there is just one result.
2247 /// NodeHasProperty - Return true if this node has the specified property.
2248 bool TreePatternNode::NodeHasProperty(SDNP Property
,
2249 const CodeGenDAGPatterns
&CGP
) const {
2251 if (const ComplexPattern
*CP
= getComplexPatternInfo(CGP
))
2252 return CP
->hasProperty(Property
);
2257 if (Property
!= SDNPHasChain
) {
2258 // The chain proprety is already present on the different intrinsic node
2259 // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
2260 // on the intrinsic. Anything else is specific to the individual intrinsic.
2261 if (const CodeGenIntrinsic
*Int
= getIntrinsicInfo(CGP
))
2262 return Int
->hasProperty(Property
);
2265 if (!Operator
->isSubClassOf("SDPatternOperator"))
2268 return CGP
.getSDNodeInfo(Operator
).hasProperty(Property
);
2274 /// TreeHasProperty - Return true if any node in this tree has the specified
2276 bool TreePatternNode::TreeHasProperty(SDNP Property
,
2277 const CodeGenDAGPatterns
&CGP
) const {
2278 if (NodeHasProperty(Property
, CGP
))
2280 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
2281 if (getChild(i
)->TreeHasProperty(Property
, CGP
))
2286 /// isCommutativeIntrinsic - Return true if the node corresponds to a
2287 /// commutative intrinsic.
2289 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns
&CDP
) const {
2290 if (const CodeGenIntrinsic
*Int
= getIntrinsicInfo(CDP
))
2291 return Int
->isCommutative
;
2295 static bool isOperandClass(const TreePatternNode
*N
, StringRef Class
) {
2297 return N
->getOperator()->isSubClassOf(Class
);
2299 DefInit
*DI
= dyn_cast
<DefInit
>(N
->getLeafValue());
2300 if (DI
&& DI
->getDef()->isSubClassOf(Class
))
2306 static void emitTooManyOperandsError(TreePattern
&TP
,
2310 TP
.error("Instruction '" + InstName
+ "' was provided " + Twine(Actual
) +
2311 " operands but expected only " + Twine(Expected
) + "!");
2314 static void emitTooFewOperandsError(TreePattern
&TP
,
2317 TP
.error("Instruction '" + InstName
+
2318 "' expects more than the provided " + Twine(Actual
) + " operands!");
2321 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
2322 /// this node and its children in the tree. This returns true if it makes a
2323 /// change, false otherwise. If a type contradiction is found, flag an error.
2324 bool TreePatternNode::ApplyTypeConstraints(TreePattern
&TP
, bool NotRegisters
) {
2328 CodeGenDAGPatterns
&CDP
= TP
.getDAGPatterns();
2330 if (DefInit
*DI
= dyn_cast
<DefInit
>(getLeafValue())) {
2331 // If it's a regclass or something else known, include the type.
2332 bool MadeChange
= false;
2333 for (unsigned i
= 0, e
= Types
.size(); i
!= e
; ++i
)
2334 MadeChange
|= UpdateNodeType(i
, getImplicitType(DI
->getDef(), i
,
2336 !hasName(), TP
), TP
);
2340 if (IntInit
*II
= dyn_cast
<IntInit
>(getLeafValue())) {
2341 assert(Types
.size() == 1 && "Invalid IntInit");
2343 // Int inits are always integers. :)
2344 bool MadeChange
= TP
.getInfer().EnforceInteger(Types
[0]);
2346 if (!TP
.getInfer().isConcrete(Types
[0], false))
2349 ValueTypeByHwMode VVT
= TP
.getInfer().getConcrete(Types
[0], false);
2350 for (auto &P
: VVT
) {
2351 MVT::SimpleValueType VT
= P
.second
.SimpleTy
;
2352 if (VT
== MVT::iPTR
|| VT
== MVT::iPTRAny
)
2354 unsigned Size
= MVT(VT
).getSizeInBits();
2355 // Make sure that the value is representable for this type.
2358 // Check that the value doesn't use more bits than we have. It must
2359 // either be a sign- or zero-extended equivalent of the original.
2360 int64_t SignBitAndAbove
= II
->getValue() >> (Size
- 1);
2361 if (SignBitAndAbove
== -1 || SignBitAndAbove
== 0 ||
2362 SignBitAndAbove
== 1)
2365 TP
.error("Integer value '" + Twine(II
->getValue()) +
2366 "' is out of range for type '" + getEnumName(VT
) + "'!");
2375 if (const CodeGenIntrinsic
*Int
= getIntrinsicInfo(CDP
)) {
2376 bool MadeChange
= false;
2378 // Apply the result type to the node.
2379 unsigned NumRetVTs
= Int
->IS
.RetVTs
.size();
2380 unsigned NumParamVTs
= Int
->IS
.ParamVTs
.size();
2382 for (unsigned i
= 0, e
= NumRetVTs
; i
!= e
; ++i
)
2383 MadeChange
|= UpdateNodeType(i
, Int
->IS
.RetVTs
[i
], TP
);
2385 if (getNumChildren() != NumParamVTs
+ 1) {
2386 TP
.error("Intrinsic '" + Int
->Name
+ "' expects " + Twine(NumParamVTs
) +
2387 " operands, not " + Twine(getNumChildren() - 1) + " operands!");
2391 // Apply type info to the intrinsic ID.
2392 MadeChange
|= getChild(0)->UpdateNodeType(0, MVT::iPTR
, TP
);
2394 for (unsigned i
= 0, e
= getNumChildren()-1; i
!= e
; ++i
) {
2395 MadeChange
|= getChild(i
+1)->ApplyTypeConstraints(TP
, NotRegisters
);
2397 MVT::SimpleValueType OpVT
= Int
->IS
.ParamVTs
[i
];
2398 assert(getChild(i
+1)->getNumTypes() == 1 && "Unhandled case");
2399 MadeChange
|= getChild(i
+1)->UpdateNodeType(0, OpVT
, TP
);
2404 if (getOperator()->isSubClassOf("SDNode")) {
2405 const SDNodeInfo
&NI
= CDP
.getSDNodeInfo(getOperator());
2407 // Check that the number of operands is sane. Negative operands -> varargs.
2408 if (NI
.getNumOperands() >= 0 &&
2409 getNumChildren() != (unsigned)NI
.getNumOperands()) {
2410 TP
.error(getOperator()->getName() + " node requires exactly " +
2411 Twine(NI
.getNumOperands()) + " operands!");
2415 bool MadeChange
= false;
2416 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
2417 MadeChange
|= getChild(i
)->ApplyTypeConstraints(TP
, NotRegisters
);
2418 MadeChange
|= NI
.ApplyTypeConstraints(this, TP
);
2422 if (getOperator()->isSubClassOf("Instruction")) {
2423 const DAGInstruction
&Inst
= CDP
.getInstruction(getOperator());
2424 CodeGenInstruction
&InstInfo
=
2425 CDP
.getTargetInfo().getInstruction(getOperator());
2427 bool MadeChange
= false;
2429 // Apply the result types to the node, these come from the things in the
2430 // (outs) list of the instruction.
2431 unsigned NumResultsToAdd
= std::min(InstInfo
.Operands
.NumDefs
,
2432 Inst
.getNumResults());
2433 for (unsigned ResNo
= 0; ResNo
!= NumResultsToAdd
; ++ResNo
)
2434 MadeChange
|= UpdateNodeTypeFromInst(ResNo
, Inst
.getResult(ResNo
), TP
);
2436 // If the instruction has implicit defs, we apply the first one as a result.
2437 // FIXME: This sucks, it should apply all implicit defs.
2438 if (!InstInfo
.ImplicitDefs
.empty()) {
2439 unsigned ResNo
= NumResultsToAdd
;
2441 // FIXME: Generalize to multiple possible types and multiple possible
2443 MVT::SimpleValueType VT
=
2444 InstInfo
.HasOneImplicitDefWithKnownVT(CDP
.getTargetInfo());
2446 if (VT
!= MVT::Other
)
2447 MadeChange
|= UpdateNodeType(ResNo
, VT
, TP
);
2450 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2452 if (getOperator()->getName() == "INSERT_SUBREG") {
2453 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
2454 MadeChange
|= UpdateNodeType(0, getChild(0)->getExtType(0), TP
);
2455 MadeChange
|= getChild(0)->UpdateNodeType(0, getExtType(0), TP
);
2456 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2457 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2460 unsigned NChild
= getNumChildren();
2462 TP
.error("REG_SEQUENCE requires at least 3 operands!");
2466 if (NChild
% 2 == 0) {
2467 TP
.error("REG_SEQUENCE requires an odd number of operands!");
2471 if (!isOperandClass(getChild(0), "RegisterClass")) {
2472 TP
.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2476 for (unsigned I
= 1; I
< NChild
; I
+= 2) {
2477 TreePatternNode
*SubIdxChild
= getChild(I
+ 1);
2478 if (!isOperandClass(SubIdxChild
, "SubRegIndex")) {
2479 TP
.error("REG_SEQUENCE requires a SubRegIndex for operand " +
2480 Twine(I
+ 1) + "!");
2486 // If one or more operands with a default value appear at the end of the
2487 // formal operand list for an instruction, we allow them to be overridden
2488 // by optional operands provided in the pattern.
2490 // But if an operand B without a default appears at any point after an
2491 // operand A with a default, then we don't allow A to be overridden,
2492 // because there would be no way to specify whether the next operand in
2493 // the pattern was intended to override A or skip it.
2494 unsigned NonOverridableOperands
= Inst
.getNumOperands();
2495 while (NonOverridableOperands
> 0 &&
2496 CDP
.operandHasDefault(Inst
.getOperand(NonOverridableOperands
-1)))
2497 --NonOverridableOperands
;
2499 unsigned ChildNo
= 0;
2500 for (unsigned i
= 0, e
= Inst
.getNumOperands(); i
!= e
; ++i
) {
2501 Record
*OperandNode
= Inst
.getOperand(i
);
2503 // If the operand has a default value, do we use it? We must use the
2504 // default if we've run out of children of the pattern DAG to consume,
2505 // or if the operand is followed by a non-defaulted one.
2506 if (CDP
.operandHasDefault(OperandNode
) &&
2507 (i
< NonOverridableOperands
|| ChildNo
>= getNumChildren()))
2510 // If we have run out of child nodes and there _isn't_ a default
2511 // value we can use for the next operand, give an error.
2512 if (ChildNo
>= getNumChildren()) {
2513 emitTooFewOperandsError(TP
, getOperator()->getName(), getNumChildren());
2517 TreePatternNode
*Child
= getChild(ChildNo
++);
2518 unsigned ChildResNo
= 0; // Instructions always use res #0 of their op.
2520 // If the operand has sub-operands, they may be provided by distinct
2521 // child patterns, so attempt to match each sub-operand separately.
2522 if (OperandNode
->isSubClassOf("Operand")) {
2523 DagInit
*MIOpInfo
= OperandNode
->getValueAsDag("MIOperandInfo");
2524 if (unsigned NumArgs
= MIOpInfo
->getNumArgs()) {
2525 // But don't do that if the whole operand is being provided by
2526 // a single ComplexPattern-related Operand.
2528 if (Child
->getNumMIResults(CDP
) < NumArgs
) {
2529 // Match first sub-operand against the child we already have.
2530 Record
*SubRec
= cast
<DefInit
>(MIOpInfo
->getArg(0))->getDef();
2532 Child
->UpdateNodeTypeFromInst(ChildResNo
, SubRec
, TP
);
2534 // And the remaining sub-operands against subsequent children.
2535 for (unsigned Arg
= 1; Arg
< NumArgs
; ++Arg
) {
2536 if (ChildNo
>= getNumChildren()) {
2537 emitTooFewOperandsError(TP
, getOperator()->getName(),
2541 Child
= getChild(ChildNo
++);
2543 SubRec
= cast
<DefInit
>(MIOpInfo
->getArg(Arg
))->getDef();
2545 Child
->UpdateNodeTypeFromInst(ChildResNo
, SubRec
, TP
);
2552 // If we didn't match by pieces above, attempt to match the whole
2554 MadeChange
|= Child
->UpdateNodeTypeFromInst(ChildResNo
, OperandNode
, TP
);
2557 if (!InstInfo
.Operands
.isVariadic
&& ChildNo
!= getNumChildren()) {
2558 emitTooManyOperandsError(TP
, getOperator()->getName(),
2559 ChildNo
, getNumChildren());
2563 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
2564 MadeChange
|= getChild(i
)->ApplyTypeConstraints(TP
, NotRegisters
);
2568 if (getOperator()->isSubClassOf("ComplexPattern")) {
2569 bool MadeChange
= false;
2571 for (unsigned i
= 0; i
< getNumChildren(); ++i
)
2572 MadeChange
|= getChild(i
)->ApplyTypeConstraints(TP
, NotRegisters
);
2577 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
2579 // Node transforms always take one operand.
2580 if (getNumChildren() != 1) {
2581 TP
.error("Node transform '" + getOperator()->getName() +
2582 "' requires one operand!");
2586 bool MadeChange
= getChild(0)->ApplyTypeConstraints(TP
, NotRegisters
);
2590 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2591 /// RHS of a commutative operation, not the on LHS.
2592 static bool OnlyOnRHSOfCommutative(TreePatternNode
*N
) {
2593 if (!N
->isLeaf() && N
->getOperator()->getName() == "imm")
2595 if (N
->isLeaf() && isa
<IntInit
>(N
->getLeafValue()))
2601 /// canPatternMatch - If it is impossible for this pattern to match on this
2602 /// target, fill in Reason and return false. Otherwise, return true. This is
2603 /// used as a sanity check for .td files (to prevent people from writing stuff
2604 /// that can never possibly work), and to prevent the pattern permuter from
2605 /// generating stuff that is useless.
2606 bool TreePatternNode::canPatternMatch(std::string
&Reason
,
2607 const CodeGenDAGPatterns
&CDP
) {
2608 if (isLeaf()) return true;
2610 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
2611 if (!getChild(i
)->canPatternMatch(Reason
, CDP
))
2614 // If this is an intrinsic, handle cases that would make it not match. For
2615 // example, if an operand is required to be an immediate.
2616 if (getOperator()->isSubClassOf("Intrinsic")) {
2621 if (getOperator()->isSubClassOf("ComplexPattern"))
2624 // If this node is a commutative operator, check that the LHS isn't an
2626 const SDNodeInfo
&NodeInfo
= CDP
.getSDNodeInfo(getOperator());
2627 bool isCommIntrinsic
= isCommutativeIntrinsic(CDP
);
2628 if (NodeInfo
.hasProperty(SDNPCommutative
) || isCommIntrinsic
) {
2629 // Scan all of the operands of the node and make sure that only the last one
2630 // is a constant node, unless the RHS also is.
2631 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
2632 unsigned Skip
= isCommIntrinsic
? 1 : 0; // First operand is intrinsic id.
2633 for (unsigned i
= Skip
, e
= getNumChildren()-1; i
!= e
; ++i
)
2634 if (OnlyOnRHSOfCommutative(getChild(i
))) {
2635 Reason
="Immediate value must be on the RHS of commutative operators!";
2644 //===----------------------------------------------------------------------===//
2645 // TreePattern implementation
2648 TreePattern::TreePattern(Record
*TheRec
, ListInit
*RawPat
, bool isInput
,
2649 CodeGenDAGPatterns
&cdp
) : TheRecord(TheRec
), CDP(cdp
),
2650 isInputPattern(isInput
), HasError(false),
2652 for (Init
*I
: RawPat
->getValues())
2653 Trees
.push_back(ParseTreePattern(I
, ""));
2656 TreePattern::TreePattern(Record
*TheRec
, DagInit
*Pat
, bool isInput
,
2657 CodeGenDAGPatterns
&cdp
) : TheRecord(TheRec
), CDP(cdp
),
2658 isInputPattern(isInput
), HasError(false),
2660 Trees
.push_back(ParseTreePattern(Pat
, ""));
2663 TreePattern::TreePattern(Record
*TheRec
, TreePatternNodePtr Pat
, bool isInput
,
2664 CodeGenDAGPatterns
&cdp
)
2665 : TheRecord(TheRec
), CDP(cdp
), isInputPattern(isInput
), HasError(false),
2667 Trees
.push_back(Pat
);
2670 void TreePattern::error(const Twine
&Msg
) {
2674 PrintError(TheRecord
->getLoc(), "In " + TheRecord
->getName() + ": " + Msg
);
2678 void TreePattern::ComputeNamedNodes() {
2679 for (TreePatternNodePtr
&Tree
: Trees
)
2680 ComputeNamedNodes(Tree
.get());
2683 void TreePattern::ComputeNamedNodes(TreePatternNode
*N
) {
2684 if (!N
->getName().empty())
2685 NamedNodes
[N
->getName()].push_back(N
);
2687 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
)
2688 ComputeNamedNodes(N
->getChild(i
));
2691 TreePatternNodePtr
TreePattern::ParseTreePattern(Init
*TheInit
,
2693 if (DefInit
*DI
= dyn_cast
<DefInit
>(TheInit
)) {
2694 Record
*R
= DI
->getDef();
2696 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
2697 // TreePatternNode of its own. For example:
2698 /// (foo GPR, imm) -> (foo GPR, (imm))
2699 if (R
->isSubClassOf("SDNode") || R
->isSubClassOf("PatFrags"))
2700 return ParseTreePattern(
2701 DagInit::get(DI
, nullptr,
2702 std::vector
<std::pair
<Init
*, StringInit
*> >()),
2706 TreePatternNodePtr Res
= std::make_shared
<TreePatternNode
>(DI
, 1);
2707 if (R
->getName() == "node" && !OpName
.empty()) {
2709 error("'node' argument requires a name to match with operand list");
2710 Args
.push_back(OpName
);
2713 Res
->setName(OpName
);
2717 // ?:$name or just $name.
2718 if (isa
<UnsetInit
>(TheInit
)) {
2720 error("'?' argument requires a name to match with operand list");
2721 TreePatternNodePtr Res
= std::make_shared
<TreePatternNode
>(TheInit
, 1);
2722 Args
.push_back(OpName
);
2723 Res
->setName(OpName
);
2727 if (isa
<IntInit
>(TheInit
) || isa
<BitInit
>(TheInit
)) {
2728 if (!OpName
.empty())
2729 error("Constant int or bit argument should not have a name!");
2730 if (isa
<BitInit
>(TheInit
))
2731 TheInit
= TheInit
->convertInitializerTo(IntRecTy::get());
2732 return std::make_shared
<TreePatternNode
>(TheInit
, 1);
2735 if (BitsInit
*BI
= dyn_cast
<BitsInit
>(TheInit
)) {
2736 // Turn this into an IntInit.
2737 Init
*II
= BI
->convertInitializerTo(IntRecTy::get());
2738 if (!II
|| !isa
<IntInit
>(II
))
2739 error("Bits value must be constants!");
2740 return ParseTreePattern(II
, OpName
);
2743 DagInit
*Dag
= dyn_cast
<DagInit
>(TheInit
);
2745 TheInit
->print(errs());
2746 error("Pattern has unexpected init kind!");
2748 DefInit
*OpDef
= dyn_cast
<DefInit
>(Dag
->getOperator());
2749 if (!OpDef
) error("Pattern has unexpected operator type!");
2750 Record
*Operator
= OpDef
->getDef();
2752 if (Operator
->isSubClassOf("ValueType")) {
2753 // If the operator is a ValueType, then this must be "type cast" of a leaf
2755 if (Dag
->getNumArgs() != 1)
2756 error("Type cast only takes one operand!");
2758 TreePatternNodePtr New
=
2759 ParseTreePattern(Dag
->getArg(0), Dag
->getArgNameStr(0));
2761 // Apply the type cast.
2762 assert(New
->getNumTypes() == 1 && "FIXME: Unhandled");
2763 const CodeGenHwModes
&CGH
= getDAGPatterns().getTargetInfo().getHwModes();
2764 New
->UpdateNodeType(0, getValueTypeByHwMode(Operator
, CGH
), *this);
2766 if (!OpName
.empty())
2767 error("ValueType cast should not have a name!");
2771 // Verify that this is something that makes sense for an operator.
2772 if (!Operator
->isSubClassOf("PatFrags") &&
2773 !Operator
->isSubClassOf("SDNode") &&
2774 !Operator
->isSubClassOf("Instruction") &&
2775 !Operator
->isSubClassOf("SDNodeXForm") &&
2776 !Operator
->isSubClassOf("Intrinsic") &&
2777 !Operator
->isSubClassOf("ComplexPattern") &&
2778 Operator
->getName() != "set" &&
2779 Operator
->getName() != "implicit")
2780 error("Unrecognized node '" + Operator
->getName() + "'!");
2782 // Check to see if this is something that is illegal in an input pattern.
2783 if (isInputPattern
) {
2784 if (Operator
->isSubClassOf("Instruction") ||
2785 Operator
->isSubClassOf("SDNodeXForm"))
2786 error("Cannot use '" + Operator
->getName() + "' in an input pattern!");
2788 if (Operator
->isSubClassOf("Intrinsic"))
2789 error("Cannot use '" + Operator
->getName() + "' in an output pattern!");
2791 if (Operator
->isSubClassOf("SDNode") &&
2792 Operator
->getName() != "imm" &&
2793 Operator
->getName() != "fpimm" &&
2794 Operator
->getName() != "tglobaltlsaddr" &&
2795 Operator
->getName() != "tconstpool" &&
2796 Operator
->getName() != "tjumptable" &&
2797 Operator
->getName() != "tframeindex" &&
2798 Operator
->getName() != "texternalsym" &&
2799 Operator
->getName() != "tblockaddress" &&
2800 Operator
->getName() != "tglobaladdr" &&
2801 Operator
->getName() != "bb" &&
2802 Operator
->getName() != "vt" &&
2803 Operator
->getName() != "mcsym")
2804 error("Cannot use '" + Operator
->getName() + "' in an output pattern!");
2807 std::vector
<TreePatternNodePtr
> Children
;
2809 // Parse all the operands.
2810 for (unsigned i
= 0, e
= Dag
->getNumArgs(); i
!= e
; ++i
)
2811 Children
.push_back(ParseTreePattern(Dag
->getArg(i
), Dag
->getArgNameStr(i
)));
2813 // Get the actual number of results before Operator is converted to an intrinsic
2814 // node (which is hard-coded to have either zero or one result).
2815 unsigned NumResults
= GetNumNodeResults(Operator
, CDP
);
2817 // If the operator is an intrinsic, then this is just syntactic sugar for
2818 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
2819 // convert the intrinsic name to a number.
2820 if (Operator
->isSubClassOf("Intrinsic")) {
2821 const CodeGenIntrinsic
&Int
= getDAGPatterns().getIntrinsic(Operator
);
2822 unsigned IID
= getDAGPatterns().getIntrinsicID(Operator
)+1;
2824 // If this intrinsic returns void, it must have side-effects and thus a
2826 if (Int
.IS
.RetVTs
.empty())
2827 Operator
= getDAGPatterns().get_intrinsic_void_sdnode();
2828 else if (Int
.ModRef
!= CodeGenIntrinsic::NoMem
|| Int
.hasSideEffects
)
2829 // Has side-effects, requires chain.
2830 Operator
= getDAGPatterns().get_intrinsic_w_chain_sdnode();
2831 else // Otherwise, no chain.
2832 Operator
= getDAGPatterns().get_intrinsic_wo_chain_sdnode();
2834 Children
.insert(Children
.begin(),
2835 std::make_shared
<TreePatternNode
>(IntInit::get(IID
), 1));
2838 if (Operator
->isSubClassOf("ComplexPattern")) {
2839 for (unsigned i
= 0; i
< Children
.size(); ++i
) {
2840 TreePatternNodePtr Child
= Children
[i
];
2842 if (Child
->getName().empty())
2843 error("All arguments to a ComplexPattern must be named");
2845 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2846 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2847 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2848 auto OperandId
= std::make_pair(Operator
, i
);
2849 auto PrevOp
= ComplexPatternOperands
.find(Child
->getName());
2850 if (PrevOp
!= ComplexPatternOperands
.end()) {
2851 if (PrevOp
->getValue() != OperandId
)
2852 error("All ComplexPattern operands must appear consistently: "
2853 "in the same order in just one ComplexPattern instance.");
2855 ComplexPatternOperands
[Child
->getName()] = OperandId
;
2859 TreePatternNodePtr Result
=
2860 std::make_shared
<TreePatternNode
>(Operator
, std::move(Children
),
2862 Result
->setName(OpName
);
2864 if (Dag
->getName()) {
2865 assert(Result
->getName().empty());
2866 Result
->setName(Dag
->getNameStr());
2871 /// SimplifyTree - See if we can simplify this tree to eliminate something that
2872 /// will never match in favor of something obvious that will. This is here
2873 /// strictly as a convenience to target authors because it allows them to write
2874 /// more type generic things and have useless type casts fold away.
2876 /// This returns true if any change is made.
2877 static bool SimplifyTree(TreePatternNodePtr
&N
) {
2881 // If we have a bitconvert with a resolved type and if the source and
2882 // destination types are the same, then the bitconvert is useless, remove it.
2883 if (N
->getOperator()->getName() == "bitconvert" &&
2884 N
->getExtType(0).isValueTypeByHwMode(false) &&
2885 N
->getExtType(0) == N
->getChild(0)->getExtType(0) &&
2886 N
->getName().empty()) {
2887 N
= N
->getChildShared(0);
2892 // Walk all children.
2893 bool MadeChange
= false;
2894 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
) {
2895 TreePatternNodePtr Child
= N
->getChildShared(i
);
2896 MadeChange
|= SimplifyTree(Child
);
2897 N
->setChild(i
, std::move(Child
));
2904 /// InferAllTypes - Infer/propagate as many types throughout the expression
2905 /// patterns as possible. Return true if all types are inferred, false
2906 /// otherwise. Flags an error if a type contradiction is found.
2908 InferAllTypes(const StringMap
<SmallVector
<TreePatternNode
*,1> > *InNamedTypes
) {
2909 if (NamedNodes
.empty())
2910 ComputeNamedNodes();
2912 bool MadeChange
= true;
2913 while (MadeChange
) {
2915 for (TreePatternNodePtr
&Tree
: Trees
) {
2916 MadeChange
|= Tree
->ApplyTypeConstraints(*this, false);
2917 MadeChange
|= SimplifyTree(Tree
);
2920 // If there are constraints on our named nodes, apply them.
2921 for (auto &Entry
: NamedNodes
) {
2922 SmallVectorImpl
<TreePatternNode
*> &Nodes
= Entry
.second
;
2924 // If we have input named node types, propagate their types to the named
2927 if (!InNamedTypes
->count(Entry
.getKey())) {
2928 error("Node '" + std::string(Entry
.getKey()) +
2929 "' in output pattern but not input pattern");
2933 const SmallVectorImpl
<TreePatternNode
*> &InNodes
=
2934 InNamedTypes
->find(Entry
.getKey())->second
;
2936 // The input types should be fully resolved by now.
2937 for (TreePatternNode
*Node
: Nodes
) {
2938 // If this node is a register class, and it is the root of the pattern
2939 // then we're mapping something onto an input register. We allow
2940 // changing the type of the input register in this case. This allows
2941 // us to match things like:
2942 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2943 if (Node
== Trees
[0].get() && Node
->isLeaf()) {
2944 DefInit
*DI
= dyn_cast
<DefInit
>(Node
->getLeafValue());
2945 if (DI
&& (DI
->getDef()->isSubClassOf("RegisterClass") ||
2946 DI
->getDef()->isSubClassOf("RegisterOperand")))
2950 assert(Node
->getNumTypes() == 1 &&
2951 InNodes
[0]->getNumTypes() == 1 &&
2952 "FIXME: cannot name multiple result nodes yet");
2953 MadeChange
|= Node
->UpdateNodeType(0, InNodes
[0]->getExtType(0),
2958 // If there are multiple nodes with the same name, they must all have the
2960 if (Entry
.second
.size() > 1) {
2961 for (unsigned i
= 0, e
= Nodes
.size()-1; i
!= e
; ++i
) {
2962 TreePatternNode
*N1
= Nodes
[i
], *N2
= Nodes
[i
+1];
2963 assert(N1
->getNumTypes() == 1 && N2
->getNumTypes() == 1 &&
2964 "FIXME: cannot name multiple result nodes yet");
2966 MadeChange
|= N1
->UpdateNodeType(0, N2
->getExtType(0), *this);
2967 MadeChange
|= N2
->UpdateNodeType(0, N1
->getExtType(0), *this);
2973 bool HasUnresolvedTypes
= false;
2974 for (const TreePatternNodePtr
&Tree
: Trees
)
2975 HasUnresolvedTypes
|= Tree
->ContainsUnresolvedType(*this);
2976 return !HasUnresolvedTypes
;
2979 void TreePattern::print(raw_ostream
&OS
) const {
2980 OS
<< getRecord()->getName();
2981 if (!Args
.empty()) {
2982 OS
<< "(" << Args
[0];
2983 for (unsigned i
= 1, e
= Args
.size(); i
!= e
; ++i
)
2984 OS
<< ", " << Args
[i
];
2989 if (Trees
.size() > 1)
2991 for (const TreePatternNodePtr
&Tree
: Trees
) {
2997 if (Trees
.size() > 1)
3001 void TreePattern::dump() const { print(errs()); }
3003 //===----------------------------------------------------------------------===//
3004 // CodeGenDAGPatterns implementation
3007 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper
&R
,
3008 PatternRewriterFn PatternRewriter
)
3009 : Records(R
), Target(R
), LegalVTS(Target
.getLegalValueTypes()),
3010 PatternRewriter(PatternRewriter
) {
3012 Intrinsics
= CodeGenIntrinsicTable(Records
, false);
3013 TgtIntrinsics
= CodeGenIntrinsicTable(Records
, true);
3015 ParseNodeTransforms();
3016 ParseComplexPatterns();
3017 ParsePatternFragments();
3018 ParseDefaultOperands();
3019 ParseInstructions();
3020 ParsePatternFragments(/*OutFrags*/true);
3023 // Break patterns with parameterized types into a series of patterns,
3024 // where each one has a fixed type and is predicated on the conditions
3025 // of the associated HW mode.
3026 ExpandHwModeBasedTypes();
3028 // Generate variants. For example, commutative patterns can match
3029 // multiple ways. Add them to PatternsToMatch as well.
3032 // Infer instruction flags. For example, we can detect loads,
3033 // stores, and side effects in many cases by examining an
3034 // instruction's pattern.
3035 InferInstructionFlags();
3037 // Verify that instruction flags match the patterns.
3038 VerifyInstructionFlags();
3041 Record
*CodeGenDAGPatterns::getSDNodeNamed(const std::string
&Name
) const {
3042 Record
*N
= Records
.getDef(Name
);
3043 if (!N
|| !N
->isSubClassOf("SDNode"))
3044 PrintFatalError("Error getting SDNode '" + Name
+ "'!");
3049 // Parse all of the SDNode definitions for the target, populating SDNodes.
3050 void CodeGenDAGPatterns::ParseNodeInfo() {
3051 std::vector
<Record
*> Nodes
= Records
.getAllDerivedDefinitions("SDNode");
3052 const CodeGenHwModes
&CGH
= getTargetInfo().getHwModes();
3054 while (!Nodes
.empty()) {
3055 Record
*R
= Nodes
.back();
3056 SDNodes
.insert(std::make_pair(R
, SDNodeInfo(R
, CGH
)));
3060 // Get the builtin intrinsic nodes.
3061 intrinsic_void_sdnode
= getSDNodeNamed("intrinsic_void");
3062 intrinsic_w_chain_sdnode
= getSDNodeNamed("intrinsic_w_chain");
3063 intrinsic_wo_chain_sdnode
= getSDNodeNamed("intrinsic_wo_chain");
3066 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
3067 /// map, and emit them to the file as functions.
3068 void CodeGenDAGPatterns::ParseNodeTransforms() {
3069 std::vector
<Record
*> Xforms
= Records
.getAllDerivedDefinitions("SDNodeXForm");
3070 while (!Xforms
.empty()) {
3071 Record
*XFormNode
= Xforms
.back();
3072 Record
*SDNode
= XFormNode
->getValueAsDef("Opcode");
3073 StringRef Code
= XFormNode
->getValueAsString("XFormFunction");
3074 SDNodeXForms
.insert(std::make_pair(XFormNode
, NodeXForm(SDNode
, Code
)));
3080 void CodeGenDAGPatterns::ParseComplexPatterns() {
3081 std::vector
<Record
*> AMs
= Records
.getAllDerivedDefinitions("ComplexPattern");
3082 while (!AMs
.empty()) {
3083 ComplexPatterns
.insert(std::make_pair(AMs
.back(), AMs
.back()));
3089 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
3090 /// file, building up the PatternFragments map. After we've collected them all,
3091 /// inline fragments together as necessary, so that there are no references left
3092 /// inside a pattern fragment to a pattern fragment.
3094 void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags
) {
3095 std::vector
<Record
*> Fragments
= Records
.getAllDerivedDefinitions("PatFrags");
3097 // First step, parse all of the fragments.
3098 for (Record
*Frag
: Fragments
) {
3099 if (OutFrags
!= Frag
->isSubClassOf("OutPatFrag"))
3102 ListInit
*LI
= Frag
->getValueAsListInit("Fragments");
3104 (PatternFragments
[Frag
] = llvm::make_unique
<TreePattern
>(
3105 Frag
, LI
, !Frag
->isSubClassOf("OutPatFrag"),
3108 // Validate the argument list, converting it to set, to discard duplicates.
3109 std::vector
<std::string
> &Args
= P
->getArgList();
3110 // Copy the args so we can take StringRefs to them.
3111 auto ArgsCopy
= Args
;
3112 SmallDenseSet
<StringRef
, 4> OperandsSet
;
3113 OperandsSet
.insert(ArgsCopy
.begin(), ArgsCopy
.end());
3115 if (OperandsSet
.count(""))
3116 P
->error("Cannot have unnamed 'node' values in pattern fragment!");
3118 // Parse the operands list.
3119 DagInit
*OpsList
= Frag
->getValueAsDag("Operands");
3120 DefInit
*OpsOp
= dyn_cast
<DefInit
>(OpsList
->getOperator());
3121 // Special cases: ops == outs == ins. Different names are used to
3122 // improve readability.
3124 (OpsOp
->getDef()->getName() != "ops" &&
3125 OpsOp
->getDef()->getName() != "outs" &&
3126 OpsOp
->getDef()->getName() != "ins"))
3127 P
->error("Operands list should start with '(ops ... '!");
3129 // Copy over the arguments.
3131 for (unsigned j
= 0, e
= OpsList
->getNumArgs(); j
!= e
; ++j
) {
3132 if (!isa
<DefInit
>(OpsList
->getArg(j
)) ||
3133 cast
<DefInit
>(OpsList
->getArg(j
))->getDef()->getName() != "node")
3134 P
->error("Operands list should all be 'node' values.");
3135 if (!OpsList
->getArgName(j
))
3136 P
->error("Operands list should have names for each operand!");
3137 StringRef ArgNameStr
= OpsList
->getArgNameStr(j
);
3138 if (!OperandsSet
.count(ArgNameStr
))
3139 P
->error("'" + ArgNameStr
+
3140 "' does not occur in pattern or was multiply specified!");
3141 OperandsSet
.erase(ArgNameStr
);
3142 Args
.push_back(ArgNameStr
);
3145 if (!OperandsSet
.empty())
3146 P
->error("Operands list does not contain an entry for operand '" +
3147 *OperandsSet
.begin() + "'!");
3149 // If there is a node transformation corresponding to this, keep track of
3151 Record
*Transform
= Frag
->getValueAsDef("OperandTransform");
3152 if (!getSDNodeTransform(Transform
).second
.empty()) // not noop xform?
3153 for (auto T
: P
->getTrees())
3154 T
->setTransformFn(Transform
);
3157 // Now that we've parsed all of the tree fragments, do a closure on them so
3158 // that there are not references to PatFrags left inside of them.
3159 for (Record
*Frag
: Fragments
) {
3160 if (OutFrags
!= Frag
->isSubClassOf("OutPatFrag"))
3163 TreePattern
&ThePat
= *PatternFragments
[Frag
];
3164 ThePat
.InlinePatternFragments();
3166 // Infer as many types as possible. Don't worry about it if we don't infer
3167 // all of them, some may depend on the inputs of the pattern. Also, don't
3168 // validate type sets; validation may cause spurious failures e.g. if a
3169 // fragment needs floating-point types but the current target does not have
3170 // any (this is only an error if that fragment is ever used!).
3172 TypeInfer::SuppressValidation
SV(ThePat
.getInfer());
3173 ThePat
.InferAllTypes();
3174 ThePat
.resetError();
3177 // If debugging, print out the pattern fragment result.
3178 LLVM_DEBUG(ThePat
.dump());
3182 void CodeGenDAGPatterns::ParseDefaultOperands() {
3183 std::vector
<Record
*> DefaultOps
;
3184 DefaultOps
= Records
.getAllDerivedDefinitions("OperandWithDefaultOps");
3186 // Find some SDNode.
3187 assert(!SDNodes
.empty() && "No SDNodes parsed?");
3188 Init
*SomeSDNode
= DefInit::get(SDNodes
.begin()->first
);
3190 for (unsigned i
= 0, e
= DefaultOps
.size(); i
!= e
; ++i
) {
3191 DagInit
*DefaultInfo
= DefaultOps
[i
]->getValueAsDag("DefaultOps");
3193 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
3194 // SomeSDnode so that we can parse this.
3195 std::vector
<std::pair
<Init
*, StringInit
*> > Ops
;
3196 for (unsigned op
= 0, e
= DefaultInfo
->getNumArgs(); op
!= e
; ++op
)
3197 Ops
.push_back(std::make_pair(DefaultInfo
->getArg(op
),
3198 DefaultInfo
->getArgName(op
)));
3199 DagInit
*DI
= DagInit::get(SomeSDNode
, nullptr, Ops
);
3201 // Create a TreePattern to parse this.
3202 TreePattern
P(DefaultOps
[i
], DI
, false, *this);
3203 assert(P
.getNumTrees() == 1 && "This ctor can only produce one tree!");
3205 // Copy the operands over into a DAGDefaultOperand.
3206 DAGDefaultOperand DefaultOpInfo
;
3208 const TreePatternNodePtr
&T
= P
.getTree(0);
3209 for (unsigned op
= 0, e
= T
->getNumChildren(); op
!= e
; ++op
) {
3210 TreePatternNodePtr TPN
= T
->getChildShared(op
);
3211 while (TPN
->ApplyTypeConstraints(P
, false))
3212 /* Resolve all types */;
3214 if (TPN
->ContainsUnresolvedType(P
)) {
3215 PrintFatalError("Value #" + Twine(i
) + " of OperandWithDefaultOps '" +
3216 DefaultOps
[i
]->getName() +
3217 "' doesn't have a concrete type!");
3219 DefaultOpInfo
.DefaultOps
.push_back(std::move(TPN
));
3222 // Insert it into the DefaultOperands map so we can find it later.
3223 DefaultOperands
[DefaultOps
[i
]] = DefaultOpInfo
;
3227 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3228 /// instruction input. Return true if this is a real use.
3229 static bool HandleUse(TreePattern
&I
, TreePatternNodePtr Pat
,
3230 std::map
<std::string
, TreePatternNodePtr
> &InstInputs
) {
3231 // No name -> not interesting.
3232 if (Pat
->getName().empty()) {
3233 if (Pat
->isLeaf()) {
3234 DefInit
*DI
= dyn_cast
<DefInit
>(Pat
->getLeafValue());
3235 if (DI
&& (DI
->getDef()->isSubClassOf("RegisterClass") ||
3236 DI
->getDef()->isSubClassOf("RegisterOperand")))
3237 I
.error("Input " + DI
->getDef()->getName() + " must be named!");
3243 if (Pat
->isLeaf()) {
3244 DefInit
*DI
= dyn_cast
<DefInit
>(Pat
->getLeafValue());
3246 I
.error("Input $" + Pat
->getName() + " must be an identifier!");
3249 Rec
= Pat
->getOperator();
3252 // SRCVALUE nodes are ignored.
3253 if (Rec
->getName() == "srcvalue")
3256 TreePatternNodePtr
&Slot
= InstInputs
[Pat
->getName()];
3262 if (Slot
->isLeaf()) {
3263 SlotRec
= cast
<DefInit
>(Slot
->getLeafValue())->getDef();
3265 assert(Slot
->getNumChildren() == 0 && "can't be a use with children!");
3266 SlotRec
= Slot
->getOperator();
3269 // Ensure that the inputs agree if we've already seen this input.
3271 I
.error("All $" + Pat
->getName() + " inputs must agree with each other");
3272 // Ensure that the types can agree as well.
3273 Slot
->UpdateNodeType(0, Pat
->getExtType(0), I
);
3274 Pat
->UpdateNodeType(0, Slot
->getExtType(0), I
);
3275 if (Slot
->getExtTypes() != Pat
->getExtTypes())
3276 I
.error("All $" + Pat
->getName() + " inputs must agree with each other");
3280 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3281 /// part of "I", the instruction), computing the set of inputs and outputs of
3282 /// the pattern. Report errors if we see anything naughty.
3283 void CodeGenDAGPatterns::FindPatternInputsAndOutputs(
3284 TreePattern
&I
, TreePatternNodePtr Pat
,
3285 std::map
<std::string
, TreePatternNodePtr
> &InstInputs
,
3286 MapVector
<std::string
, TreePatternNodePtr
, std::map
<std::string
, unsigned>>
3288 std::vector
<Record
*> &InstImpResults
) {
3290 // The instruction pattern still has unresolved fragments. For *named*
3291 // nodes we must resolve those here. This may not result in multiple
3293 if (!Pat
->getName().empty()) {
3294 TreePattern
SrcPattern(I
.getRecord(), Pat
, true, *this);
3295 SrcPattern
.InlinePatternFragments();
3296 SrcPattern
.InferAllTypes();
3297 Pat
= SrcPattern
.getOnlyTree();
3300 if (Pat
->isLeaf()) {
3301 bool isUse
= HandleUse(I
, Pat
, InstInputs
);
3302 if (!isUse
&& Pat
->getTransformFn())
3303 I
.error("Cannot specify a transform function for a non-input value!");
3307 if (Pat
->getOperator()->getName() == "implicit") {
3308 for (unsigned i
= 0, e
= Pat
->getNumChildren(); i
!= e
; ++i
) {
3309 TreePatternNode
*Dest
= Pat
->getChild(i
);
3310 if (!Dest
->isLeaf())
3311 I
.error("implicitly defined value should be a register!");
3313 DefInit
*Val
= dyn_cast
<DefInit
>(Dest
->getLeafValue());
3314 if (!Val
|| !Val
->getDef()->isSubClassOf("Register"))
3315 I
.error("implicitly defined value should be a register!");
3316 InstImpResults
.push_back(Val
->getDef());
3321 if (Pat
->getOperator()->getName() != "set") {
3322 // If this is not a set, verify that the children nodes are not void typed,
3324 for (unsigned i
= 0, e
= Pat
->getNumChildren(); i
!= e
; ++i
) {
3325 if (Pat
->getChild(i
)->getNumTypes() == 0)
3326 I
.error("Cannot have void nodes inside of patterns!");
3327 FindPatternInputsAndOutputs(I
, Pat
->getChildShared(i
), InstInputs
,
3328 InstResults
, InstImpResults
);
3331 // If this is a non-leaf node with no children, treat it basically as if
3332 // it were a leaf. This handles nodes like (imm).
3333 bool isUse
= HandleUse(I
, Pat
, InstInputs
);
3335 if (!isUse
&& Pat
->getTransformFn())
3336 I
.error("Cannot specify a transform function for a non-input value!");
3340 // Otherwise, this is a set, validate and collect instruction results.
3341 if (Pat
->getNumChildren() == 0)
3342 I
.error("set requires operands!");
3344 if (Pat
->getTransformFn())
3345 I
.error("Cannot specify a transform function on a set node!");
3347 // Check the set destinations.
3348 unsigned NumDests
= Pat
->getNumChildren()-1;
3349 for (unsigned i
= 0; i
!= NumDests
; ++i
) {
3350 TreePatternNodePtr Dest
= Pat
->getChildShared(i
);
3351 // For set destinations we also must resolve fragments here.
3352 TreePattern
DestPattern(I
.getRecord(), Dest
, false, *this);
3353 DestPattern
.InlinePatternFragments();
3354 DestPattern
.InferAllTypes();
3355 Dest
= DestPattern
.getOnlyTree();
3357 if (!Dest
->isLeaf())
3358 I
.error("set destination should be a register!");
3360 DefInit
*Val
= dyn_cast
<DefInit
>(Dest
->getLeafValue());
3362 I
.error("set destination should be a register!");
3366 if (Val
->getDef()->isSubClassOf("RegisterClass") ||
3367 Val
->getDef()->isSubClassOf("ValueType") ||
3368 Val
->getDef()->isSubClassOf("RegisterOperand") ||
3369 Val
->getDef()->isSubClassOf("PointerLikeRegClass")) {
3370 if (Dest
->getName().empty())
3371 I
.error("set destination must have a name!");
3372 if (InstResults
.count(Dest
->getName()))
3373 I
.error("cannot set '" + Dest
->getName() + "' multiple times");
3374 InstResults
[Dest
->getName()] = Dest
;
3375 } else if (Val
->getDef()->isSubClassOf("Register")) {
3376 InstImpResults
.push_back(Val
->getDef());
3378 I
.error("set destination should be a register!");
3382 // Verify and collect info from the computation.
3383 FindPatternInputsAndOutputs(I
, Pat
->getChildShared(NumDests
), InstInputs
,
3384 InstResults
, InstImpResults
);
3387 //===----------------------------------------------------------------------===//
3388 // Instruction Analysis
3389 //===----------------------------------------------------------------------===//
3391 class InstAnalyzer
{
3392 const CodeGenDAGPatterns
&CDP
;
3394 bool hasSideEffects
;
3401 InstAnalyzer(const CodeGenDAGPatterns
&cdp
)
3402 : CDP(cdp
), hasSideEffects(false), mayStore(false), mayLoad(false),
3403 isBitcast(false), isVariadic(false), hasChain(false) {}
3405 void Analyze(const PatternToMatch
&Pat
) {
3406 const TreePatternNode
*N
= Pat
.getSrcPattern();
3408 // These properties are detected only on the root node.
3409 isBitcast
= IsNodeBitcast(N
);
3413 bool IsNodeBitcast(const TreePatternNode
*N
) const {
3414 if (hasSideEffects
|| mayLoad
|| mayStore
|| isVariadic
)
3419 if (N
->getNumChildren() != 1 || !N
->getChild(0)->isLeaf())
3422 const SDNodeInfo
&OpInfo
= CDP
.getSDNodeInfo(N
->getOperator());
3423 if (OpInfo
.getNumResults() != 1 || OpInfo
.getNumOperands() != 1)
3425 return OpInfo
.getEnumName() == "ISD::BITCAST";
3429 void AnalyzeNode(const TreePatternNode
*N
) {
3431 if (DefInit
*DI
= dyn_cast
<DefInit
>(N
->getLeafValue())) {
3432 Record
*LeafRec
= DI
->getDef();
3433 // Handle ComplexPattern leaves.
3434 if (LeafRec
->isSubClassOf("ComplexPattern")) {
3435 const ComplexPattern
&CP
= CDP
.getComplexPattern(LeafRec
);
3436 if (CP
.hasProperty(SDNPMayStore
)) mayStore
= true;
3437 if (CP
.hasProperty(SDNPMayLoad
)) mayLoad
= true;
3438 if (CP
.hasProperty(SDNPSideEffect
)) hasSideEffects
= true;
3444 // Analyze children.
3445 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
)
3446 AnalyzeNode(N
->getChild(i
));
3448 // Notice properties of the node.
3449 if (N
->NodeHasProperty(SDNPMayStore
, CDP
)) mayStore
= true;
3450 if (N
->NodeHasProperty(SDNPMayLoad
, CDP
)) mayLoad
= true;
3451 if (N
->NodeHasProperty(SDNPSideEffect
, CDP
)) hasSideEffects
= true;
3452 if (N
->NodeHasProperty(SDNPVariadic
, CDP
)) isVariadic
= true;
3453 if (N
->NodeHasProperty(SDNPHasChain
, CDP
)) hasChain
= true;
3455 if (const CodeGenIntrinsic
*IntInfo
= N
->getIntrinsicInfo(CDP
)) {
3456 // If this is an intrinsic, analyze it.
3457 if (IntInfo
->ModRef
& CodeGenIntrinsic::MR_Ref
)
3458 mayLoad
= true;// These may load memory.
3460 if (IntInfo
->ModRef
& CodeGenIntrinsic::MR_Mod
)
3461 mayStore
= true;// Intrinsics that can write to memory are 'mayStore'.
3463 if (IntInfo
->ModRef
>= CodeGenIntrinsic::ReadWriteMem
||
3464 IntInfo
->hasSideEffects
)
3465 // ReadWriteMem intrinsics can have other strange effects.
3466 hasSideEffects
= true;
3472 static bool InferFromPattern(CodeGenInstruction
&InstInfo
,
3473 const InstAnalyzer
&PatInfo
,
3477 // Remember where InstInfo got its flags.
3478 if (InstInfo
.hasUndefFlags())
3479 InstInfo
.InferredFrom
= PatDef
;
3481 // Check explicitly set flags for consistency.
3482 if (InstInfo
.hasSideEffects
!= PatInfo
.hasSideEffects
&&
3483 !InstInfo
.hasSideEffects_Unset
) {
3484 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3485 // the pattern has no side effects. That could be useful for div/rem
3486 // instructions that may trap.
3487 if (!InstInfo
.hasSideEffects
) {
3489 PrintError(PatDef
->getLoc(), "Pattern doesn't match hasSideEffects = " +
3490 Twine(InstInfo
.hasSideEffects
));
3494 if (InstInfo
.mayStore
!= PatInfo
.mayStore
&& !InstInfo
.mayStore_Unset
) {
3496 PrintError(PatDef
->getLoc(), "Pattern doesn't match mayStore = " +
3497 Twine(InstInfo
.mayStore
));
3500 if (InstInfo
.mayLoad
!= PatInfo
.mayLoad
&& !InstInfo
.mayLoad_Unset
) {
3501 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
3502 // Some targets translate immediates to loads.
3503 if (!InstInfo
.mayLoad
) {
3505 PrintError(PatDef
->getLoc(), "Pattern doesn't match mayLoad = " +
3506 Twine(InstInfo
.mayLoad
));
3510 // Transfer inferred flags.
3511 InstInfo
.hasSideEffects
|= PatInfo
.hasSideEffects
;
3512 InstInfo
.mayStore
|= PatInfo
.mayStore
;
3513 InstInfo
.mayLoad
|= PatInfo
.mayLoad
;
3515 // These flags are silently added without any verification.
3516 // FIXME: To match historical behavior of TableGen, for now add those flags
3517 // only when we're inferring from the primary instruction pattern.
3518 if (PatDef
->isSubClassOf("Instruction")) {
3519 InstInfo
.isBitcast
|= PatInfo
.isBitcast
;
3520 InstInfo
.hasChain
|= PatInfo
.hasChain
;
3521 InstInfo
.hasChain_Inferred
= true;
3524 // Don't infer isVariadic. This flag means something different on SDNodes and
3525 // instructions. For example, a CALL SDNode is variadic because it has the
3526 // call arguments as operands, but a CALL instruction is not variadic - it
3527 // has argument registers as implicit, not explicit uses.
3532 /// hasNullFragReference - Return true if the DAG has any reference to the
3533 /// null_frag operator.
3534 static bool hasNullFragReference(DagInit
*DI
) {
3535 DefInit
*OpDef
= dyn_cast
<DefInit
>(DI
->getOperator());
3536 if (!OpDef
) return false;
3537 Record
*Operator
= OpDef
->getDef();
3539 // If this is the null fragment, return true.
3540 if (Operator
->getName() == "null_frag") return true;
3541 // If any of the arguments reference the null fragment, return true.
3542 for (unsigned i
= 0, e
= DI
->getNumArgs(); i
!= e
; ++i
) {
3543 DagInit
*Arg
= dyn_cast
<DagInit
>(DI
->getArg(i
));
3544 if (Arg
&& hasNullFragReference(Arg
))
3551 /// hasNullFragReference - Return true if any DAG in the list references
3552 /// the null_frag operator.
3553 static bool hasNullFragReference(ListInit
*LI
) {
3554 for (Init
*I
: LI
->getValues()) {
3555 DagInit
*DI
= dyn_cast
<DagInit
>(I
);
3556 assert(DI
&& "non-dag in an instruction Pattern list?!");
3557 if (hasNullFragReference(DI
))
3563 /// Get all the instructions in a tree.
3565 getInstructionsInTree(TreePatternNode
*Tree
, SmallVectorImpl
<Record
*> &Instrs
) {
3568 if (Tree
->getOperator()->isSubClassOf("Instruction"))
3569 Instrs
.push_back(Tree
->getOperator());
3570 for (unsigned i
= 0, e
= Tree
->getNumChildren(); i
!= e
; ++i
)
3571 getInstructionsInTree(Tree
->getChild(i
), Instrs
);
3574 /// Check the class of a pattern leaf node against the instruction operand it
3576 static bool checkOperandClass(CGIOperandList::OperandInfo
&OI
,
3581 // Allow direct value types to be used in instruction set patterns.
3582 // The type will be checked later.
3583 if (Leaf
->isSubClassOf("ValueType"))
3586 // Patterns can also be ComplexPattern instances.
3587 if (Leaf
->isSubClassOf("ComplexPattern"))
3593 void CodeGenDAGPatterns::parseInstructionPattern(
3594 CodeGenInstruction
&CGI
, ListInit
*Pat
, DAGInstMap
&DAGInsts
) {
3596 assert(!DAGInsts
.count(CGI
.TheDef
) && "Instruction already parsed!");
3598 // Parse the instruction.
3599 TreePattern
I(CGI
.TheDef
, Pat
, true, *this);
3601 // InstInputs - Keep track of all of the inputs of the instruction, along
3602 // with the record they are declared as.
3603 std::map
<std::string
, TreePatternNodePtr
> InstInputs
;
3605 // InstResults - Keep track of all the virtual registers that are 'set'
3606 // in the instruction, including what reg class they are.
3607 MapVector
<std::string
, TreePatternNodePtr
, std::map
<std::string
, unsigned>>
3610 std::vector
<Record
*> InstImpResults
;
3612 // Verify that the top-level forms in the instruction are of void type, and
3613 // fill in the InstResults map.
3614 SmallString
<32> TypesString
;
3615 for (unsigned j
= 0, e
= I
.getNumTrees(); j
!= e
; ++j
) {
3616 TypesString
.clear();
3617 TreePatternNodePtr Pat
= I
.getTree(j
);
3618 if (Pat
->getNumTypes() != 0) {
3619 raw_svector_ostream
OS(TypesString
);
3620 for (unsigned k
= 0, ke
= Pat
->getNumTypes(); k
!= ke
; ++k
) {
3623 Pat
->getExtType(k
).writeToStream(OS
);
3625 I
.error("Top-level forms in instruction pattern should have"
3626 " void types, has types " +
3630 // Find inputs and outputs, and verify the structure of the uses/defs.
3631 FindPatternInputsAndOutputs(I
, Pat
, InstInputs
, InstResults
,
3635 // Now that we have inputs and outputs of the pattern, inspect the operands
3636 // list for the instruction. This determines the order that operands are
3637 // added to the machine instruction the node corresponds to.
3638 unsigned NumResults
= InstResults
.size();
3640 // Parse the operands list from the (ops) list, validating it.
3641 assert(I
.getArgList().empty() && "Args list should still be empty here!");
3643 // Check that all of the results occur first in the list.
3644 std::vector
<Record
*> Results
;
3645 std::vector
<unsigned> ResultIndices
;
3646 SmallVector
<TreePatternNodePtr
, 2> ResNodes
;
3647 for (unsigned i
= 0; i
!= NumResults
; ++i
) {
3648 if (i
== CGI
.Operands
.size()) {
3649 const std::string
&OpName
=
3650 std::find_if(InstResults
.begin(), InstResults
.end(),
3651 [](const std::pair
<std::string
, TreePatternNodePtr
> &P
) {
3656 I
.error("'" + OpName
+ "' set but does not appear in operand list!");
3659 const std::string
&OpName
= CGI
.Operands
[i
].Name
;
3661 // Check that it exists in InstResults.
3662 auto InstResultIter
= InstResults
.find(OpName
);
3663 if (InstResultIter
== InstResults
.end() || !InstResultIter
->second
)
3664 I
.error("Operand $" + OpName
+ " does not exist in operand list!");
3666 TreePatternNodePtr RNode
= InstResultIter
->second
;
3667 Record
*R
= cast
<DefInit
>(RNode
->getLeafValue())->getDef();
3668 ResNodes
.push_back(std::move(RNode
));
3670 I
.error("Operand $" + OpName
+ " should be a set destination: all "
3671 "outputs must occur before inputs in operand list!");
3673 if (!checkOperandClass(CGI
.Operands
[i
], R
))
3674 I
.error("Operand $" + OpName
+ " class mismatch!");
3676 // Remember the return type.
3677 Results
.push_back(CGI
.Operands
[i
].Rec
);
3679 // Remember the result index.
3680 ResultIndices
.push_back(std::distance(InstResults
.begin(), InstResultIter
));
3682 // Okay, this one checks out.
3683 InstResultIter
->second
= nullptr;
3686 // Loop over the inputs next.
3687 std::vector
<TreePatternNodePtr
> ResultNodeOperands
;
3688 std::vector
<Record
*> Operands
;
3689 for (unsigned i
= NumResults
, e
= CGI
.Operands
.size(); i
!= e
; ++i
) {
3690 CGIOperandList::OperandInfo
&Op
= CGI
.Operands
[i
];
3691 const std::string
&OpName
= Op
.Name
;
3693 I
.error("Operand #" + Twine(i
) + " in operands list has no name!");
3695 if (!InstInputs
.count(OpName
)) {
3696 // If this is an operand with a DefaultOps set filled in, we can ignore
3697 // this. When we codegen it, we will do so as always executed.
3698 if (Op
.Rec
->isSubClassOf("OperandWithDefaultOps")) {
3699 // Does it have a non-empty DefaultOps field? If so, ignore this
3701 if (!getDefaultOperand(Op
.Rec
).DefaultOps
.empty())
3704 I
.error("Operand $" + OpName
+
3705 " does not appear in the instruction pattern");
3707 TreePatternNodePtr InVal
= InstInputs
[OpName
];
3708 InstInputs
.erase(OpName
); // It occurred, remove from map.
3710 if (InVal
->isLeaf() && isa
<DefInit
>(InVal
->getLeafValue())) {
3711 Record
*InRec
= static_cast<DefInit
*>(InVal
->getLeafValue())->getDef();
3712 if (!checkOperandClass(Op
, InRec
))
3713 I
.error("Operand $" + OpName
+ "'s register class disagrees"
3714 " between the operand and pattern");
3716 Operands
.push_back(Op
.Rec
);
3718 // Construct the result for the dest-pattern operand list.
3719 TreePatternNodePtr OpNode
= InVal
->clone();
3721 // No predicate is useful on the result.
3722 OpNode
->clearPredicateCalls();
3724 // Promote the xform function to be an explicit node if set.
3725 if (Record
*Xform
= OpNode
->getTransformFn()) {
3726 OpNode
->setTransformFn(nullptr);
3727 std::vector
<TreePatternNodePtr
> Children
;
3728 Children
.push_back(OpNode
);
3729 OpNode
= std::make_shared
<TreePatternNode
>(Xform
, std::move(Children
),
3730 OpNode
->getNumTypes());
3733 ResultNodeOperands
.push_back(std::move(OpNode
));
3736 if (!InstInputs
.empty())
3737 I
.error("Input operand $" + InstInputs
.begin()->first
+
3738 " occurs in pattern but not in operands list!");
3740 TreePatternNodePtr ResultPattern
= std::make_shared
<TreePatternNode
>(
3741 I
.getRecord(), std::move(ResultNodeOperands
),
3742 GetNumNodeResults(I
.getRecord(), *this));
3743 // Copy fully inferred output node types to instruction result pattern.
3744 for (unsigned i
= 0; i
!= NumResults
; ++i
) {
3745 assert(ResNodes
[i
]->getNumTypes() == 1 && "FIXME: Unhandled");
3746 ResultPattern
->setType(i
, ResNodes
[i
]->getExtType(0));
3747 ResultPattern
->setResultIndex(i
, ResultIndices
[i
]);
3750 // FIXME: Assume only the first tree is the pattern. The others are clobber
3752 TreePatternNodePtr Pattern
= I
.getTree(0);
3753 TreePatternNodePtr SrcPattern
;
3754 if (Pattern
->getOperator()->getName() == "set") {
3755 SrcPattern
= Pattern
->getChild(Pattern
->getNumChildren()-1)->clone();
3757 // Not a set (store or something?)
3758 SrcPattern
= Pattern
;
3761 // Create and insert the instruction.
3762 // FIXME: InstImpResults should not be part of DAGInstruction.
3763 Record
*R
= I
.getRecord();
3764 DAGInsts
.emplace(std::piecewise_construct
, std::forward_as_tuple(R
),
3765 std::forward_as_tuple(Results
, Operands
, InstImpResults
,
3766 SrcPattern
, ResultPattern
));
3768 LLVM_DEBUG(I
.dump());
3771 /// ParseInstructions - Parse all of the instructions, inlining and resolving
3772 /// any fragments involved. This populates the Instructions list with fully
3773 /// resolved instructions.
3774 void CodeGenDAGPatterns::ParseInstructions() {
3775 std::vector
<Record
*> Instrs
= Records
.getAllDerivedDefinitions("Instruction");
3777 for (Record
*Instr
: Instrs
) {
3778 ListInit
*LI
= nullptr;
3780 if (isa
<ListInit
>(Instr
->getValueInit("Pattern")))
3781 LI
= Instr
->getValueAsListInit("Pattern");
3783 // If there is no pattern, only collect minimal information about the
3784 // instruction for its operand list. We have to assume that there is one
3785 // result, as we have no detailed info. A pattern which references the
3786 // null_frag operator is as-if no pattern were specified. Normally this
3787 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3789 if (!LI
|| LI
->empty() || hasNullFragReference(LI
)) {
3790 std::vector
<Record
*> Results
;
3791 std::vector
<Record
*> Operands
;
3793 CodeGenInstruction
&InstInfo
= Target
.getInstruction(Instr
);
3795 if (InstInfo
.Operands
.size() != 0) {
3796 for (unsigned j
= 0, e
= InstInfo
.Operands
.NumDefs
; j
< e
; ++j
)
3797 Results
.push_back(InstInfo
.Operands
[j
].Rec
);
3799 // The rest are inputs.
3800 for (unsigned j
= InstInfo
.Operands
.NumDefs
,
3801 e
= InstInfo
.Operands
.size(); j
< e
; ++j
)
3802 Operands
.push_back(InstInfo
.Operands
[j
].Rec
);
3805 // Create and insert the instruction.
3806 std::vector
<Record
*> ImpResults
;
3807 Instructions
.insert(std::make_pair(Instr
,
3808 DAGInstruction(Results
, Operands
, ImpResults
)));
3809 continue; // no pattern.
3812 CodeGenInstruction
&CGI
= Target
.getInstruction(Instr
);
3813 parseInstructionPattern(CGI
, LI
, Instructions
);
3816 // If we can, convert the instructions to be patterns that are matched!
3817 for (auto &Entry
: Instructions
) {
3818 Record
*Instr
= Entry
.first
;
3819 DAGInstruction
&TheInst
= Entry
.second
;
3820 TreePatternNodePtr SrcPattern
= TheInst
.getSrcPattern();
3821 TreePatternNodePtr ResultPattern
= TheInst
.getResultPattern();
3823 if (SrcPattern
&& ResultPattern
) {
3824 TreePattern
Pattern(Instr
, SrcPattern
, true, *this);
3825 TreePattern
Result(Instr
, ResultPattern
, false, *this);
3826 ParseOnePattern(Instr
, Pattern
, Result
, TheInst
.getImpResults());
3831 typedef std::pair
<TreePatternNode
*, unsigned> NameRecord
;
3833 static void FindNames(TreePatternNode
*P
,
3834 std::map
<std::string
, NameRecord
> &Names
,
3835 TreePattern
*PatternTop
) {
3836 if (!P
->getName().empty()) {
3837 NameRecord
&Rec
= Names
[P
->getName()];
3838 // If this is the first instance of the name, remember the node.
3839 if (Rec
.second
++ == 0)
3841 else if (Rec
.first
->getExtTypes() != P
->getExtTypes())
3842 PatternTop
->error("repetition of value: $" + P
->getName() +
3843 " where different uses have different types!");
3847 for (unsigned i
= 0, e
= P
->getNumChildren(); i
!= e
; ++i
)
3848 FindNames(P
->getChild(i
), Names
, PatternTop
);
3852 std::vector
<Predicate
> CodeGenDAGPatterns::makePredList(ListInit
*L
) {
3853 std::vector
<Predicate
> Preds
;
3854 for (Init
*I
: L
->getValues()) {
3855 if (DefInit
*Pred
= dyn_cast
<DefInit
>(I
))
3856 Preds
.push_back(Pred
->getDef());
3858 llvm_unreachable("Non-def on the list");
3861 // Sort so that different orders get canonicalized to the same string.
3866 void CodeGenDAGPatterns::AddPatternToMatch(TreePattern
*Pattern
,
3867 PatternToMatch
&&PTM
) {
3868 // Do some sanity checking on the pattern we're about to match.
3870 if (!PTM
.getSrcPattern()->canPatternMatch(Reason
, *this)) {
3871 PrintWarning(Pattern
->getRecord()->getLoc(),
3872 Twine("Pattern can never match: ") + Reason
);
3876 // If the source pattern's root is a complex pattern, that complex pattern
3877 // must specify the nodes it can potentially match.
3878 if (const ComplexPattern
*CP
=
3879 PTM
.getSrcPattern()->getComplexPatternInfo(*this))
3880 if (CP
->getRootNodes().empty())
3881 Pattern
->error("ComplexPattern at root must specify list of opcodes it"
3885 // Find all of the named values in the input and output, ensure they have the
3887 std::map
<std::string
, NameRecord
> SrcNames
, DstNames
;
3888 FindNames(PTM
.getSrcPattern(), SrcNames
, Pattern
);
3889 FindNames(PTM
.getDstPattern(), DstNames
, Pattern
);
3891 // Scan all of the named values in the destination pattern, rejecting them if
3892 // they don't exist in the input pattern.
3893 for (const auto &Entry
: DstNames
) {
3894 if (SrcNames
[Entry
.first
].first
== nullptr)
3895 Pattern
->error("Pattern has input without matching name in output: $" +
3899 // Scan all of the named values in the source pattern, rejecting them if the
3900 // name isn't used in the dest, and isn't used to tie two values together.
3901 for (const auto &Entry
: SrcNames
)
3902 if (DstNames
[Entry
.first
].first
== nullptr &&
3903 SrcNames
[Entry
.first
].second
== 1)
3904 Pattern
->error("Pattern has dead named input: $" + Entry
.first
);
3906 PatternsToMatch
.push_back(PTM
);
3909 void CodeGenDAGPatterns::InferInstructionFlags() {
3910 ArrayRef
<const CodeGenInstruction
*> Instructions
=
3911 Target
.getInstructionsByEnumValue();
3913 unsigned Errors
= 0;
3915 // Try to infer flags from all patterns in PatternToMatch. These include
3916 // both the primary instruction patterns (which always come first) and
3917 // patterns defined outside the instruction.
3918 for (const PatternToMatch
&PTM
: ptms()) {
3919 // We can only infer from single-instruction patterns, otherwise we won't
3920 // know which instruction should get the flags.
3921 SmallVector
<Record
*, 8> PatInstrs
;
3922 getInstructionsInTree(PTM
.getDstPattern(), PatInstrs
);
3923 if (PatInstrs
.size() != 1)
3926 // Get the single instruction.
3927 CodeGenInstruction
&InstInfo
= Target
.getInstruction(PatInstrs
.front());
3929 // Only infer properties from the first pattern. We'll verify the others.
3930 if (InstInfo
.InferredFrom
)
3933 InstAnalyzer
PatInfo(*this);
3934 PatInfo
.Analyze(PTM
);
3935 Errors
+= InferFromPattern(InstInfo
, PatInfo
, PTM
.getSrcRecord());
3939 PrintFatalError("pattern conflicts");
3941 // If requested by the target, guess any undefined properties.
3942 if (Target
.guessInstructionProperties()) {
3943 for (unsigned i
= 0, e
= Instructions
.size(); i
!= e
; ++i
) {
3944 CodeGenInstruction
*InstInfo
=
3945 const_cast<CodeGenInstruction
*>(Instructions
[i
]);
3946 if (InstInfo
->InferredFrom
)
3948 // The mayLoad and mayStore flags default to false.
3949 // Conservatively assume hasSideEffects if it wasn't explicit.
3950 if (InstInfo
->hasSideEffects_Unset
)
3951 InstInfo
->hasSideEffects
= true;
3956 // Complain about any flags that are still undefined.
3957 for (unsigned i
= 0, e
= Instructions
.size(); i
!= e
; ++i
) {
3958 CodeGenInstruction
*InstInfo
=
3959 const_cast<CodeGenInstruction
*>(Instructions
[i
]);
3960 if (InstInfo
->InferredFrom
)
3962 if (InstInfo
->hasSideEffects_Unset
)
3963 PrintError(InstInfo
->TheDef
->getLoc(),
3964 "Can't infer hasSideEffects from patterns");
3965 if (InstInfo
->mayStore_Unset
)
3966 PrintError(InstInfo
->TheDef
->getLoc(),
3967 "Can't infer mayStore from patterns");
3968 if (InstInfo
->mayLoad_Unset
)
3969 PrintError(InstInfo
->TheDef
->getLoc(),
3970 "Can't infer mayLoad from patterns");
3975 /// Verify instruction flags against pattern node properties.
3976 void CodeGenDAGPatterns::VerifyInstructionFlags() {
3977 unsigned Errors
= 0;
3978 for (ptm_iterator I
= ptm_begin(), E
= ptm_end(); I
!= E
; ++I
) {
3979 const PatternToMatch
&PTM
= *I
;
3980 SmallVector
<Record
*, 8> Instrs
;
3981 getInstructionsInTree(PTM
.getDstPattern(), Instrs
);
3985 // Count the number of instructions with each flag set.
3986 unsigned NumSideEffects
= 0;
3987 unsigned NumStores
= 0;
3988 unsigned NumLoads
= 0;
3989 for (const Record
*Instr
: Instrs
) {
3990 const CodeGenInstruction
&InstInfo
= Target
.getInstruction(Instr
);
3991 NumSideEffects
+= InstInfo
.hasSideEffects
;
3992 NumStores
+= InstInfo
.mayStore
;
3993 NumLoads
+= InstInfo
.mayLoad
;
3996 // Analyze the source pattern.
3997 InstAnalyzer
PatInfo(*this);
3998 PatInfo
.Analyze(PTM
);
4000 // Collect error messages.
4001 SmallVector
<std::string
, 4> Msgs
;
4003 // Check for missing flags in the output.
4004 // Permit extra flags for now at least.
4005 if (PatInfo
.hasSideEffects
&& !NumSideEffects
)
4006 Msgs
.push_back("pattern has side effects, but hasSideEffects isn't set");
4008 // Don't verify store flags on instructions with side effects. At least for
4009 // intrinsics, side effects implies mayStore.
4010 if (!PatInfo
.hasSideEffects
&& PatInfo
.mayStore
&& !NumStores
)
4011 Msgs
.push_back("pattern may store, but mayStore isn't set");
4013 // Similarly, mayStore implies mayLoad on intrinsics.
4014 if (!PatInfo
.mayStore
&& PatInfo
.mayLoad
&& !NumLoads
)
4015 Msgs
.push_back("pattern may load, but mayLoad isn't set");
4017 // Print error messages.
4022 for (const std::string
&Msg
: Msgs
)
4023 PrintError(PTM
.getSrcRecord()->getLoc(), Twine(Msg
) + " on the " +
4024 (Instrs
.size() == 1 ?
4025 "instruction" : "output instructions"));
4026 // Provide the location of the relevant instruction definitions.
4027 for (const Record
*Instr
: Instrs
) {
4028 if (Instr
!= PTM
.getSrcRecord())
4029 PrintError(Instr
->getLoc(), "defined here");
4030 const CodeGenInstruction
&InstInfo
= Target
.getInstruction(Instr
);
4031 if (InstInfo
.InferredFrom
&&
4032 InstInfo
.InferredFrom
!= InstInfo
.TheDef
&&
4033 InstInfo
.InferredFrom
!= PTM
.getSrcRecord())
4034 PrintError(InstInfo
.InferredFrom
->getLoc(), "inferred from pattern");
4038 PrintFatalError("Errors in DAG patterns");
4041 /// Given a pattern result with an unresolved type, see if we can find one
4042 /// instruction with an unresolved result type. Force this result type to an
4043 /// arbitrary element if it's possible types to converge results.
4044 static bool ForceArbitraryInstResultType(TreePatternNode
*N
, TreePattern
&TP
) {
4048 // Analyze children.
4049 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
)
4050 if (ForceArbitraryInstResultType(N
->getChild(i
), TP
))
4053 if (!N
->getOperator()->isSubClassOf("Instruction"))
4056 // If this type is already concrete or completely unknown we can't do
4058 TypeInfer
&TI
= TP
.getInfer();
4059 for (unsigned i
= 0, e
= N
->getNumTypes(); i
!= e
; ++i
) {
4060 if (N
->getExtType(i
).empty() || TI
.isConcrete(N
->getExtType(i
), false))
4063 // Otherwise, force its type to an arbitrary choice.
4064 if (TI
.forceArbitrary(N
->getExtType(i
)))
4071 // Promote xform function to be an explicit node wherever set.
4072 static TreePatternNodePtr
PromoteXForms(TreePatternNodePtr N
) {
4073 if (Record
*Xform
= N
->getTransformFn()) {
4074 N
->setTransformFn(nullptr);
4075 std::vector
<TreePatternNodePtr
> Children
;
4076 Children
.push_back(PromoteXForms(N
));
4077 return std::make_shared
<TreePatternNode
>(Xform
, std::move(Children
),
4082 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
) {
4083 TreePatternNodePtr Child
= N
->getChildShared(i
);
4084 N
->setChild(i
, PromoteXForms(Child
));
4089 void CodeGenDAGPatterns::ParseOnePattern(Record
*TheDef
,
4090 TreePattern
&Pattern
, TreePattern
&Result
,
4091 const std::vector
<Record
*> &InstImpResults
) {
4093 // Inline pattern fragments and expand multiple alternatives.
4094 Pattern
.InlinePatternFragments();
4095 Result
.InlinePatternFragments();
4097 if (Result
.getNumTrees() != 1)
4098 Result
.error("Cannot use multi-alternative fragments in result pattern!");
4101 bool IterateInference
;
4102 bool InferredAllPatternTypes
, InferredAllResultTypes
;
4104 // Infer as many types as possible. If we cannot infer all of them, we
4105 // can never do anything with this pattern: report it to the user.
4106 InferredAllPatternTypes
=
4107 Pattern
.InferAllTypes(&Pattern
.getNamedNodesMap());
4109 // Infer as many types as possible. If we cannot infer all of them, we
4110 // can never do anything with this pattern: report it to the user.
4111 InferredAllResultTypes
=
4112 Result
.InferAllTypes(&Pattern
.getNamedNodesMap());
4114 IterateInference
= false;
4116 // Apply the type of the result to the source pattern. This helps us
4117 // resolve cases where the input type is known to be a pointer type (which
4118 // is considered resolved), but the result knows it needs to be 32- or
4119 // 64-bits. Infer the other way for good measure.
4120 for (auto T
: Pattern
.getTrees())
4121 for (unsigned i
= 0, e
= std::min(Result
.getOnlyTree()->getNumTypes(),
4124 IterateInference
|= T
->UpdateNodeType(
4125 i
, Result
.getOnlyTree()->getExtType(i
), Result
);
4126 IterateInference
|= Result
.getOnlyTree()->UpdateNodeType(
4127 i
, T
->getExtType(i
), Result
);
4130 // If our iteration has converged and the input pattern's types are fully
4131 // resolved but the result pattern is not fully resolved, we may have a
4132 // situation where we have two instructions in the result pattern and
4133 // the instructions require a common register class, but don't care about
4134 // what actual MVT is used. This is actually a bug in our modelling:
4135 // output patterns should have register classes, not MVTs.
4137 // In any case, to handle this, we just go through and disambiguate some
4138 // arbitrary types to the result pattern's nodes.
4139 if (!IterateInference
&& InferredAllPatternTypes
&&
4140 !InferredAllResultTypes
)
4142 ForceArbitraryInstResultType(Result
.getTree(0).get(), Result
);
4143 } while (IterateInference
);
4145 // Verify that we inferred enough types that we can do something with the
4146 // pattern and result. If these fire the user has to add type casts.
4147 if (!InferredAllPatternTypes
)
4148 Pattern
.error("Could not infer all types in pattern!");
4149 if (!InferredAllResultTypes
) {
4151 Result
.error("Could not infer all types in pattern result!");
4154 // Promote xform function to be an explicit node wherever set.
4155 TreePatternNodePtr DstShared
= PromoteXForms(Result
.getOnlyTree());
4157 TreePattern
Temp(Result
.getRecord(), DstShared
, false, *this);
4158 Temp
.InferAllTypes();
4160 ListInit
*Preds
= TheDef
->getValueAsListInit("Predicates");
4161 int Complexity
= TheDef
->getValueAsInt("AddedComplexity");
4163 if (PatternRewriter
)
4164 PatternRewriter(&Pattern
);
4166 // A pattern may end up with an "impossible" type, i.e. a situation
4167 // where all types have been eliminated for some node in this pattern.
4168 // This could occur for intrinsics that only make sense for a specific
4169 // value type, and use a specific register class. If, for some mode,
4170 // that register class does not accept that type, the type inference
4171 // will lead to a contradiction, which is not an error however, but
4172 // a sign that this pattern will simply never match.
4173 if (Temp
.getOnlyTree()->hasPossibleType())
4174 for (auto T
: Pattern
.getTrees())
4175 if (T
->hasPossibleType())
4176 AddPatternToMatch(&Pattern
,
4177 PatternToMatch(TheDef
, makePredList(Preds
),
4178 T
, Temp
.getOnlyTree(),
4179 InstImpResults
, Complexity
,
4183 void CodeGenDAGPatterns::ParsePatterns() {
4184 std::vector
<Record
*> Patterns
= Records
.getAllDerivedDefinitions("Pattern");
4186 for (Record
*CurPattern
: Patterns
) {
4187 DagInit
*Tree
= CurPattern
->getValueAsDag("PatternToMatch");
4189 // If the pattern references the null_frag, there's nothing to do.
4190 if (hasNullFragReference(Tree
))
4193 TreePattern
Pattern(CurPattern
, Tree
, true, *this);
4195 ListInit
*LI
= CurPattern
->getValueAsListInit("ResultInstrs");
4196 if (LI
->empty()) continue; // no pattern.
4198 // Parse the instruction.
4199 TreePattern
Result(CurPattern
, LI
, false, *this);
4201 if (Result
.getNumTrees() != 1)
4202 Result
.error("Cannot handle instructions producing instructions "
4203 "with temporaries yet!");
4205 // Validate that the input pattern is correct.
4206 std::map
<std::string
, TreePatternNodePtr
> InstInputs
;
4207 MapVector
<std::string
, TreePatternNodePtr
, std::map
<std::string
, unsigned>>
4209 std::vector
<Record
*> InstImpResults
;
4210 for (unsigned j
= 0, ee
= Pattern
.getNumTrees(); j
!= ee
; ++j
)
4211 FindPatternInputsAndOutputs(Pattern
, Pattern
.getTree(j
), InstInputs
,
4212 InstResults
, InstImpResults
);
4214 ParseOnePattern(CurPattern
, Pattern
, Result
, InstImpResults
);
4218 static void collectModes(std::set
<unsigned> &Modes
, const TreePatternNode
*N
) {
4219 for (const TypeSetByHwMode
&VTS
: N
->getExtTypes())
4220 for (const auto &I
: VTS
)
4221 Modes
.insert(I
.first
);
4223 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
)
4224 collectModes(Modes
, N
->getChild(i
));
4227 void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
4228 const CodeGenHwModes
&CGH
= getTargetInfo().getHwModes();
4229 std::map
<unsigned,std::vector
<Predicate
>> ModeChecks
;
4230 std::vector
<PatternToMatch
> Copy
= PatternsToMatch
;
4231 PatternsToMatch
.clear();
4233 auto AppendPattern
= [this, &ModeChecks
](PatternToMatch
&P
, unsigned Mode
) {
4234 TreePatternNodePtr NewSrc
= P
.SrcPattern
->clone();
4235 TreePatternNodePtr NewDst
= P
.DstPattern
->clone();
4236 if (!NewSrc
->setDefaultMode(Mode
) || !NewDst
->setDefaultMode(Mode
)) {
4240 std::vector
<Predicate
> Preds
= P
.Predicates
;
4241 const std::vector
<Predicate
> &MC
= ModeChecks
[Mode
];
4242 Preds
.insert(Preds
.end(), MC
.begin(), MC
.end());
4243 PatternsToMatch
.emplace_back(P
.getSrcRecord(), Preds
, std::move(NewSrc
),
4244 std::move(NewDst
), P
.getDstRegs(),
4245 P
.getAddedComplexity(), Record::getNewUID(),
4249 for (PatternToMatch
&P
: Copy
) {
4250 TreePatternNodePtr SrcP
= nullptr, DstP
= nullptr;
4251 if (P
.SrcPattern
->hasProperTypeByHwMode())
4252 SrcP
= P
.SrcPattern
;
4253 if (P
.DstPattern
->hasProperTypeByHwMode())
4254 DstP
= P
.DstPattern
;
4255 if (!SrcP
&& !DstP
) {
4256 PatternsToMatch
.push_back(P
);
4260 std::set
<unsigned> Modes
;
4262 collectModes(Modes
, SrcP
.get());
4264 collectModes(Modes
, DstP
.get());
4266 // The predicate for the default mode needs to be constructed for each
4267 // pattern separately.
4268 // Since not all modes must be present in each pattern, if a mode m is
4269 // absent, then there is no point in constructing a check for m. If such
4270 // a check was created, it would be equivalent to checking the default
4271 // mode, except not all modes' predicates would be a part of the checking
4272 // code. The subsequently generated check for the default mode would then
4273 // have the exact same patterns, but a different predicate code. To avoid
4274 // duplicated patterns with different predicate checks, construct the
4275 // default check as a negation of all predicates that are actually present
4276 // in the source/destination patterns.
4277 std::vector
<Predicate
> DefaultPred
;
4279 for (unsigned M
: Modes
) {
4280 if (M
== DefaultMode
)
4282 if (ModeChecks
.find(M
) != ModeChecks
.end())
4285 // Fill the map entry for this mode.
4286 const HwMode
&HM
= CGH
.getMode(M
);
4287 ModeChecks
[M
].emplace_back(Predicate(HM
.Features
, true));
4289 // Add negations of the HM's predicates to the default predicate.
4290 DefaultPred
.emplace_back(Predicate(HM
.Features
, false));
4293 for (unsigned M
: Modes
) {
4294 if (M
== DefaultMode
)
4296 AppendPattern(P
, M
);
4299 bool HasDefault
= Modes
.count(DefaultMode
);
4301 AppendPattern(P
, DefaultMode
);
4305 /// Dependent variable map for CodeGenDAGPattern variant generation
4306 typedef StringMap
<int> DepVarMap
;
4308 static void FindDepVarsOf(TreePatternNode
*N
, DepVarMap
&DepMap
) {
4310 if (N
->hasName() && isa
<DefInit
>(N
->getLeafValue()))
4311 DepMap
[N
->getName()]++;
4313 for (size_t i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
)
4314 FindDepVarsOf(N
->getChild(i
), DepMap
);
4318 /// Find dependent variables within child patterns
4319 static void FindDepVars(TreePatternNode
*N
, MultipleUseVarSet
&DepVars
) {
4320 DepVarMap depcounts
;
4321 FindDepVarsOf(N
, depcounts
);
4322 for (const auto &Pair
: depcounts
) {
4323 if (Pair
.getValue() > 1)
4324 DepVars
.insert(Pair
.getKey());
4329 /// Dump the dependent variable set:
4330 static void DumpDepVars(MultipleUseVarSet
&DepVars
) {
4331 if (DepVars
.empty()) {
4332 LLVM_DEBUG(errs() << "<empty set>");
4334 LLVM_DEBUG(errs() << "[ ");
4335 for (const auto &DepVar
: DepVars
) {
4336 LLVM_DEBUG(errs() << DepVar
.getKey() << " ");
4338 LLVM_DEBUG(errs() << "]");
4344 /// CombineChildVariants - Given a bunch of permutations of each child of the
4345 /// 'operator' node, put them together in all possible ways.
4346 static void CombineChildVariants(
4347 TreePatternNodePtr Orig
,
4348 const std::vector
<std::vector
<TreePatternNodePtr
>> &ChildVariants
,
4349 std::vector
<TreePatternNodePtr
> &OutVariants
, CodeGenDAGPatterns
&CDP
,
4350 const MultipleUseVarSet
&DepVars
) {
4351 // Make sure that each operand has at least one variant to choose from.
4352 for (const auto &Variants
: ChildVariants
)
4353 if (Variants
.empty())
4356 // The end result is an all-pairs construction of the resultant pattern.
4357 std::vector
<unsigned> Idxs
;
4358 Idxs
.resize(ChildVariants
.size());
4362 LLVM_DEBUG(if (!Idxs
.empty()) {
4363 errs() << Orig
->getOperator()->getName() << ": Idxs = [ ";
4364 for (unsigned Idx
: Idxs
) {
4365 errs() << Idx
<< " ";
4370 // Create the variant and add it to the output list.
4371 std::vector
<TreePatternNodePtr
> NewChildren
;
4372 for (unsigned i
= 0, e
= ChildVariants
.size(); i
!= e
; ++i
)
4373 NewChildren
.push_back(ChildVariants
[i
][Idxs
[i
]]);
4374 TreePatternNodePtr R
= std::make_shared
<TreePatternNode
>(
4375 Orig
->getOperator(), std::move(NewChildren
), Orig
->getNumTypes());
4377 // Copy over properties.
4378 R
->setName(Orig
->getName());
4379 R
->setNamesAsPredicateArg(Orig
->getNamesAsPredicateArg());
4380 R
->setPredicateCalls(Orig
->getPredicateCalls());
4381 R
->setTransformFn(Orig
->getTransformFn());
4382 for (unsigned i
= 0, e
= Orig
->getNumTypes(); i
!= e
; ++i
)
4383 R
->setType(i
, Orig
->getExtType(i
));
4385 // If this pattern cannot match, do not include it as a variant.
4386 std::string ErrString
;
4387 // Scan to see if this pattern has already been emitted. We can get
4388 // duplication due to things like commuting:
4389 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4390 // which are the same pattern. Ignore the dups.
4391 if (R
->canPatternMatch(ErrString
, CDP
) &&
4392 none_of(OutVariants
, [&](TreePatternNodePtr Variant
) {
4393 return R
->isIsomorphicTo(Variant
.get(), DepVars
);
4395 OutVariants
.push_back(R
);
4397 // Increment indices to the next permutation by incrementing the
4398 // indices from last index backward, e.g., generate the sequence
4399 // [0, 0], [0, 1], [1, 0], [1, 1].
4401 for (IdxsIdx
= Idxs
.size() - 1; IdxsIdx
>= 0; --IdxsIdx
) {
4402 if (++Idxs
[IdxsIdx
] == ChildVariants
[IdxsIdx
].size())
4407 NotDone
= (IdxsIdx
>= 0);
4411 /// CombineChildVariants - A helper function for binary operators.
4413 static void CombineChildVariants(TreePatternNodePtr Orig
,
4414 const std::vector
<TreePatternNodePtr
> &LHS
,
4415 const std::vector
<TreePatternNodePtr
> &RHS
,
4416 std::vector
<TreePatternNodePtr
> &OutVariants
,
4417 CodeGenDAGPatterns
&CDP
,
4418 const MultipleUseVarSet
&DepVars
) {
4419 std::vector
<std::vector
<TreePatternNodePtr
>> ChildVariants
;
4420 ChildVariants
.push_back(LHS
);
4421 ChildVariants
.push_back(RHS
);
4422 CombineChildVariants(Orig
, ChildVariants
, OutVariants
, CDP
, DepVars
);
4426 GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N
,
4427 std::vector
<TreePatternNodePtr
> &Children
) {
4428 assert(N
->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
4429 Record
*Operator
= N
->getOperator();
4431 // Only permit raw nodes.
4432 if (!N
->getName().empty() || !N
->getPredicateCalls().empty() ||
4433 N
->getTransformFn()) {
4434 Children
.push_back(N
);
4438 if (N
->getChild(0)->isLeaf() || N
->getChild(0)->getOperator() != Operator
)
4439 Children
.push_back(N
->getChildShared(0));
4441 GatherChildrenOfAssociativeOpcode(N
->getChildShared(0), Children
);
4443 if (N
->getChild(1)->isLeaf() || N
->getChild(1)->getOperator() != Operator
)
4444 Children
.push_back(N
->getChildShared(1));
4446 GatherChildrenOfAssociativeOpcode(N
->getChildShared(1), Children
);
4449 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4450 /// the (potentially recursive) pattern by using algebraic laws.
4452 static void GenerateVariantsOf(TreePatternNodePtr N
,
4453 std::vector
<TreePatternNodePtr
> &OutVariants
,
4454 CodeGenDAGPatterns
&CDP
,
4455 const MultipleUseVarSet
&DepVars
) {
4456 // We cannot permute leaves or ComplexPattern uses.
4457 if (N
->isLeaf() || N
->getOperator()->isSubClassOf("ComplexPattern")) {
4458 OutVariants
.push_back(N
);
4462 // Look up interesting info about the node.
4463 const SDNodeInfo
&NodeInfo
= CDP
.getSDNodeInfo(N
->getOperator());
4465 // If this node is associative, re-associate.
4466 if (NodeInfo
.hasProperty(SDNPAssociative
)) {
4467 // Re-associate by pulling together all of the linked operators
4468 std::vector
<TreePatternNodePtr
> MaximalChildren
;
4469 GatherChildrenOfAssociativeOpcode(N
, MaximalChildren
);
4471 // Only handle child sizes of 3. Otherwise we'll end up trying too many
4473 if (MaximalChildren
.size() == 3) {
4474 // Find the variants of all of our maximal children.
4475 std::vector
<TreePatternNodePtr
> AVariants
, BVariants
, CVariants
;
4476 GenerateVariantsOf(MaximalChildren
[0], AVariants
, CDP
, DepVars
);
4477 GenerateVariantsOf(MaximalChildren
[1], BVariants
, CDP
, DepVars
);
4478 GenerateVariantsOf(MaximalChildren
[2], CVariants
, CDP
, DepVars
);
4480 // There are only two ways we can permute the tree:
4481 // (A op B) op C and A op (B op C)
4482 // Within these forms, we can also permute A/B/C.
4484 // Generate legal pair permutations of A/B/C.
4485 std::vector
<TreePatternNodePtr
> ABVariants
;
4486 std::vector
<TreePatternNodePtr
> BAVariants
;
4487 std::vector
<TreePatternNodePtr
> ACVariants
;
4488 std::vector
<TreePatternNodePtr
> CAVariants
;
4489 std::vector
<TreePatternNodePtr
> BCVariants
;
4490 std::vector
<TreePatternNodePtr
> CBVariants
;
4491 CombineChildVariants(N
, AVariants
, BVariants
, ABVariants
, CDP
, DepVars
);
4492 CombineChildVariants(N
, BVariants
, AVariants
, BAVariants
, CDP
, DepVars
);
4493 CombineChildVariants(N
, AVariants
, CVariants
, ACVariants
, CDP
, DepVars
);
4494 CombineChildVariants(N
, CVariants
, AVariants
, CAVariants
, CDP
, DepVars
);
4495 CombineChildVariants(N
, BVariants
, CVariants
, BCVariants
, CDP
, DepVars
);
4496 CombineChildVariants(N
, CVariants
, BVariants
, CBVariants
, CDP
, DepVars
);
4498 // Combine those into the result: (x op x) op x
4499 CombineChildVariants(N
, ABVariants
, CVariants
, OutVariants
, CDP
, DepVars
);
4500 CombineChildVariants(N
, BAVariants
, CVariants
, OutVariants
, CDP
, DepVars
);
4501 CombineChildVariants(N
, ACVariants
, BVariants
, OutVariants
, CDP
, DepVars
);
4502 CombineChildVariants(N
, CAVariants
, BVariants
, OutVariants
, CDP
, DepVars
);
4503 CombineChildVariants(N
, BCVariants
, AVariants
, OutVariants
, CDP
, DepVars
);
4504 CombineChildVariants(N
, CBVariants
, AVariants
, OutVariants
, CDP
, DepVars
);
4506 // Combine those into the result: x op (x op x)
4507 CombineChildVariants(N
, CVariants
, ABVariants
, OutVariants
, CDP
, DepVars
);
4508 CombineChildVariants(N
, CVariants
, BAVariants
, OutVariants
, CDP
, DepVars
);
4509 CombineChildVariants(N
, BVariants
, ACVariants
, OutVariants
, CDP
, DepVars
);
4510 CombineChildVariants(N
, BVariants
, CAVariants
, OutVariants
, CDP
, DepVars
);
4511 CombineChildVariants(N
, AVariants
, BCVariants
, OutVariants
, CDP
, DepVars
);
4512 CombineChildVariants(N
, AVariants
, CBVariants
, OutVariants
, CDP
, DepVars
);
4517 // Compute permutations of all children.
4518 std::vector
<std::vector
<TreePatternNodePtr
>> ChildVariants
;
4519 ChildVariants
.resize(N
->getNumChildren());
4520 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
)
4521 GenerateVariantsOf(N
->getChildShared(i
), ChildVariants
[i
], CDP
, DepVars
);
4523 // Build all permutations based on how the children were formed.
4524 CombineChildVariants(N
, ChildVariants
, OutVariants
, CDP
, DepVars
);
4526 // If this node is commutative, consider the commuted order.
4527 bool isCommIntrinsic
= N
->isCommutativeIntrinsic(CDP
);
4528 if (NodeInfo
.hasProperty(SDNPCommutative
) || isCommIntrinsic
) {
4529 assert((N
->getNumChildren()>=2 || isCommIntrinsic
) &&
4530 "Commutative but doesn't have 2 children!");
4531 // Don't count children which are actually register references.
4533 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
) {
4534 TreePatternNode
*Child
= N
->getChild(i
);
4535 if (Child
->isLeaf())
4536 if (DefInit
*DI
= dyn_cast
<DefInit
>(Child
->getLeafValue())) {
4537 Record
*RR
= DI
->getDef();
4538 if (RR
->isSubClassOf("Register"))
4543 // Consider the commuted order.
4544 if (isCommIntrinsic
) {
4545 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4546 // operands are the commutative operands, and there might be more operands
4549 "Commutative intrinsic should have at least 3 children!");
4550 std::vector
<std::vector
<TreePatternNodePtr
>> Variants
;
4551 Variants
.push_back(std::move(ChildVariants
[0])); // Intrinsic id.
4552 Variants
.push_back(std::move(ChildVariants
[2]));
4553 Variants
.push_back(std::move(ChildVariants
[1]));
4554 for (unsigned i
= 3; i
!= NC
; ++i
)
4555 Variants
.push_back(std::move(ChildVariants
[i
]));
4556 CombineChildVariants(N
, Variants
, OutVariants
, CDP
, DepVars
);
4557 } else if (NC
== N
->getNumChildren()) {
4558 std::vector
<std::vector
<TreePatternNodePtr
>> Variants
;
4559 Variants
.push_back(std::move(ChildVariants
[1]));
4560 Variants
.push_back(std::move(ChildVariants
[0]));
4561 for (unsigned i
= 2; i
!= NC
; ++i
)
4562 Variants
.push_back(std::move(ChildVariants
[i
]));
4563 CombineChildVariants(N
, Variants
, OutVariants
, CDP
, DepVars
);
4569 // GenerateVariants - Generate variants. For example, commutative patterns can
4570 // match multiple ways. Add them to PatternsToMatch as well.
4571 void CodeGenDAGPatterns::GenerateVariants() {
4572 LLVM_DEBUG(errs() << "Generating instruction variants.\n");
4574 // Loop over all of the patterns we've collected, checking to see if we can
4575 // generate variants of the instruction, through the exploitation of
4576 // identities. This permits the target to provide aggressive matching without
4577 // the .td file having to contain tons of variants of instructions.
4579 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4580 // intentionally do not reconsider these. Any variants of added patterns have
4581 // already been added.
4583 const unsigned NumOriginalPatterns
= PatternsToMatch
.size();
4584 BitVector
MatchedPatterns(NumOriginalPatterns
);
4585 std::vector
<BitVector
> MatchedPredicates(NumOriginalPatterns
,
4586 BitVector(NumOriginalPatterns
));
4588 typedef std::pair
<MultipleUseVarSet
, std::vector
<TreePatternNodePtr
>>
4590 std::map
<unsigned, DepsAndVariants
> PatternsWithVariants
;
4592 // Collect patterns with more than one variant.
4593 for (unsigned i
= 0; i
!= NumOriginalPatterns
; ++i
) {
4594 MultipleUseVarSet DepVars
;
4595 std::vector
<TreePatternNodePtr
> Variants
;
4596 FindDepVars(PatternsToMatch
[i
].getSrcPattern(), DepVars
);
4597 LLVM_DEBUG(errs() << "Dependent/multiply used variables: ");
4598 LLVM_DEBUG(DumpDepVars(DepVars
));
4599 LLVM_DEBUG(errs() << "\n");
4600 GenerateVariantsOf(PatternsToMatch
[i
].getSrcPatternShared(), Variants
,
4603 assert(!Variants
.empty() && "Must create at least original variant!");
4604 if (Variants
.size() == 1) // No additional variants for this pattern.
4607 LLVM_DEBUG(errs() << "FOUND VARIANTS OF: ";
4608 PatternsToMatch
[i
].getSrcPattern()->dump(); errs() << "\n");
4610 PatternsWithVariants
[i
] = std::make_pair(DepVars
, Variants
);
4612 // Cache matching predicates.
4613 if (MatchedPatterns
[i
])
4616 const std::vector
<Predicate
> &Predicates
=
4617 PatternsToMatch
[i
].getPredicates();
4619 BitVector
&Matches
= MatchedPredicates
[i
];
4620 MatchedPatterns
.set(i
);
4623 // Don't test patterns that have already been cached - it won't match.
4624 for (unsigned p
= 0; p
!= NumOriginalPatterns
; ++p
)
4625 if (!MatchedPatterns
[p
])
4626 Matches
[p
] = (Predicates
== PatternsToMatch
[p
].getPredicates());
4628 // Copy this to all the matching patterns.
4629 for (int p
= Matches
.find_first(); p
!= -1; p
= Matches
.find_next(p
))
4631 MatchedPatterns
.set(p
);
4632 MatchedPredicates
[p
] = Matches
;
4636 for (auto it
: PatternsWithVariants
) {
4637 unsigned i
= it
.first
;
4638 const MultipleUseVarSet
&DepVars
= it
.second
.first
;
4639 const std::vector
<TreePatternNodePtr
> &Variants
= it
.second
.second
;
4641 for (unsigned v
= 0, e
= Variants
.size(); v
!= e
; ++v
) {
4642 TreePatternNodePtr Variant
= Variants
[v
];
4643 BitVector
&Matches
= MatchedPredicates
[i
];
4645 LLVM_DEBUG(errs() << " VAR#" << v
<< ": "; Variant
->dump();
4648 // Scan to see if an instruction or explicit pattern already matches this.
4649 bool AlreadyExists
= false;
4650 for (unsigned p
= 0, e
= PatternsToMatch
.size(); p
!= e
; ++p
) {
4651 // Skip if the top level predicates do not match.
4654 // Check to see if this variant already exists.
4655 if (Variant
->isIsomorphicTo(PatternsToMatch
[p
].getSrcPattern(),
4657 LLVM_DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
4658 AlreadyExists
= true;
4662 // If we already have it, ignore the variant.
4663 if (AlreadyExists
) continue;
4665 // Otherwise, add it to the list of patterns we have.
4666 PatternsToMatch
.push_back(PatternToMatch(
4667 PatternsToMatch
[i
].getSrcRecord(), PatternsToMatch
[i
].getPredicates(),
4668 Variant
, PatternsToMatch
[i
].getDstPatternShared(),
4669 PatternsToMatch
[i
].getDstRegs(),
4670 PatternsToMatch
[i
].getAddedComplexity(), Record::getNewUID()));
4671 MatchedPredicates
.push_back(Matches
);
4673 // Add a new match the same as this pattern.
4674 for (auto &P
: MatchedPredicates
)
4678 LLVM_DEBUG(errs() << "\n");