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_fixedlen_vector_valuetypes())
775 for (MVT T
: MVT::integer_scalable_vector_valuetypes())
780 for (MVT T
: MVT::fp_valuetypes())
783 for (MVT T
: MVT::fp_fixedlen_vector_valuetypes())
786 for (MVT T
: MVT::fp_scalable_vector_valuetypes())
791 for (MVT T
: MVT::vector_valuetypes())
796 for (MVT T
: MVT::all_valuetypes())
806 const TypeSetByHwMode
&TypeInfer::getLegalTypes() {
807 if (!LegalTypesCached
) {
808 TypeSetByHwMode::SetType
&LegalTypes
= LegalCache
.getOrCreate(DefaultMode
);
809 // Stuff all types from all modes into the default mode.
810 const TypeSetByHwMode
<S
= TP
.getDAGPatterns().getLegalTypes();
811 for (const auto &I
: LTS
)
812 LegalTypes
.insert(I
.second
);
813 LegalTypesCached
= true;
815 assert(LegalCache
.isDefaultOnly() && "Default-mode only expected");
820 TypeInfer::ValidateOnExit::~ValidateOnExit() {
821 if (Infer
.Validate
&& !VTS
.validate()) {
822 dbgs() << "Type set is empty for each HW mode:\n"
823 "possible type contradiction in the pattern below "
824 "(use -print-records with llvm-tblgen to see all "
825 "expanded records).\n";
827 llvm_unreachable(nullptr);
833 //===----------------------------------------------------------------------===//
834 // ScopedName Implementation
835 //===----------------------------------------------------------------------===//
837 bool ScopedName::operator==(const ScopedName
&o
) const {
838 return Scope
== o
.Scope
&& Identifier
== o
.Identifier
;
841 bool ScopedName::operator!=(const ScopedName
&o
) const {
842 return !(*this == o
);
846 //===----------------------------------------------------------------------===//
847 // TreePredicateFn Implementation
848 //===----------------------------------------------------------------------===//
850 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
851 TreePredicateFn::TreePredicateFn(TreePattern
*N
) : PatFragRec(N
) {
853 (!hasPredCode() || !hasImmCode()) &&
854 ".td file corrupt: can't have a node predicate *and* an imm predicate");
857 bool TreePredicateFn::hasPredCode() const {
858 return isLoad() || isStore() || isAtomic() ||
859 !PatFragRec
->getRecord()->getValueAsString("PredicateCode").empty();
862 std::string
TreePredicateFn::getPredCode() const {
863 std::string Code
= "";
865 if (!isLoad() && !isStore() && !isAtomic()) {
866 Record
*MemoryVT
= getMemoryVT();
869 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
870 "MemoryVT requires IsLoad or IsStore");
873 if (!isLoad() && !isStore()) {
875 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
876 "IsUnindexed requires IsLoad or IsStore");
878 Record
*ScalarMemoryVT
= getScalarMemoryVT();
881 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
882 "ScalarMemoryVT requires IsLoad or IsStore");
885 if (isLoad() + isStore() + isAtomic() > 1)
886 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
887 "IsLoad, IsStore, and IsAtomic are mutually exclusive");
890 if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&
891 !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&
892 getScalarMemoryVT() == nullptr && getAddressSpaces() == nullptr &&
893 getMinAlignment() < 1)
894 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
895 "IsLoad cannot be used by itself");
898 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
899 "IsNonExtLoad requires IsLoad");
901 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
902 "IsAnyExtLoad requires IsLoad");
904 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
905 "IsSignExtLoad requires IsLoad");
907 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
908 "IsZeroExtLoad requires IsLoad");
912 if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&
913 getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr &&
914 getAddressSpaces() == nullptr && getMinAlignment() < 1)
915 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
916 "IsStore cannot be used by itself");
918 if (isNonTruncStore())
919 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
920 "IsNonTruncStore requires IsStore");
922 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
923 "IsTruncStore requires IsStore");
927 if (getMemoryVT() == nullptr && !isAtomicOrderingMonotonic() &&
928 getAddressSpaces() == nullptr &&
929 !isAtomicOrderingAcquire() && !isAtomicOrderingRelease() &&
930 !isAtomicOrderingAcquireRelease() &&
931 !isAtomicOrderingSequentiallyConsistent() &&
932 !isAtomicOrderingAcquireOrStronger() &&
933 !isAtomicOrderingReleaseOrStronger() &&
934 !isAtomicOrderingWeakerThanAcquire() &&
935 !isAtomicOrderingWeakerThanRelease())
936 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
937 "IsAtomic cannot be used by itself");
939 if (isAtomicOrderingMonotonic())
940 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
941 "IsAtomicOrderingMonotonic requires IsAtomic");
942 if (isAtomicOrderingAcquire())
943 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
944 "IsAtomicOrderingAcquire requires IsAtomic");
945 if (isAtomicOrderingRelease())
946 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
947 "IsAtomicOrderingRelease requires IsAtomic");
948 if (isAtomicOrderingAcquireRelease())
949 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
950 "IsAtomicOrderingAcquireRelease requires IsAtomic");
951 if (isAtomicOrderingSequentiallyConsistent())
952 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
953 "IsAtomicOrderingSequentiallyConsistent requires IsAtomic");
954 if (isAtomicOrderingAcquireOrStronger())
955 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
956 "IsAtomicOrderingAcquireOrStronger requires IsAtomic");
957 if (isAtomicOrderingReleaseOrStronger())
958 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
959 "IsAtomicOrderingReleaseOrStronger requires IsAtomic");
960 if (isAtomicOrderingWeakerThanAcquire())
961 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
962 "IsAtomicOrderingWeakerThanAcquire requires IsAtomic");
965 if (isLoad() || isStore() || isAtomic()) {
966 if (ListInit
*AddressSpaces
= getAddressSpaces()) {
967 Code
+= "unsigned AddrSpace = cast<MemSDNode>(N)->getAddressSpace();\n"
971 for (Init
*Val
: AddressSpaces
->getValues()) {
977 IntInit
*IntVal
= dyn_cast
<IntInit
>(Val
);
979 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
980 "AddressSpaces element must be integer");
983 Code
+= "AddrSpace != " + utostr(IntVal
->getValue());
986 Code
+= ")\nreturn false;\n";
989 int64_t MinAlign
= getMinAlignment();
991 Code
+= "if (cast<MemSDNode>(N)->getAlignment() < ";
992 Code
+= utostr(MinAlign
);
993 Code
+= ")\nreturn false;\n";
996 Record
*MemoryVT
= getMemoryVT();
999 Code
+= ("if (cast<MemSDNode>(N)->getMemoryVT() != MVT::" +
1000 MemoryVT
->getName() + ") return false;\n")
1004 if (isAtomic() && isAtomicOrderingMonotonic())
1005 Code
+= "if (cast<AtomicSDNode>(N)->getOrdering() != "
1006 "AtomicOrdering::Monotonic) return false;\n";
1007 if (isAtomic() && isAtomicOrderingAcquire())
1008 Code
+= "if (cast<AtomicSDNode>(N)->getOrdering() != "
1009 "AtomicOrdering::Acquire) return false;\n";
1010 if (isAtomic() && isAtomicOrderingRelease())
1011 Code
+= "if (cast<AtomicSDNode>(N)->getOrdering() != "
1012 "AtomicOrdering::Release) return false;\n";
1013 if (isAtomic() && isAtomicOrderingAcquireRelease())
1014 Code
+= "if (cast<AtomicSDNode>(N)->getOrdering() != "
1015 "AtomicOrdering::AcquireRelease) return false;\n";
1016 if (isAtomic() && isAtomicOrderingSequentiallyConsistent())
1017 Code
+= "if (cast<AtomicSDNode>(N)->getOrdering() != "
1018 "AtomicOrdering::SequentiallyConsistent) return false;\n";
1020 if (isAtomic() && isAtomicOrderingAcquireOrStronger())
1021 Code
+= "if (!isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1023 if (isAtomic() && isAtomicOrderingWeakerThanAcquire())
1024 Code
+= "if (isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1027 if (isAtomic() && isAtomicOrderingReleaseOrStronger())
1028 Code
+= "if (!isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1030 if (isAtomic() && isAtomicOrderingWeakerThanRelease())
1031 Code
+= "if (isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1034 if (isLoad() || isStore()) {
1035 StringRef SDNodeName
= isLoad() ? "LoadSDNode" : "StoreSDNode";
1038 Code
+= ("if (cast<" + SDNodeName
+
1039 ">(N)->getAddressingMode() != ISD::UNINDEXED) "
1044 if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
1045 isZeroExtLoad()) > 1)
1046 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1047 "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
1048 "IsZeroExtLoad are mutually exclusive");
1050 Code
+= "if (cast<LoadSDNode>(N)->getExtensionType() != "
1051 "ISD::NON_EXTLOAD) return false;\n";
1053 Code
+= "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
1055 if (isSignExtLoad())
1056 Code
+= "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
1058 if (isZeroExtLoad())
1059 Code
+= "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
1062 if ((isNonTruncStore() + isTruncStore()) > 1)
1064 getOrigPatFragRecord()->getRecord()->getLoc(),
1065 "IsNonTruncStore, and IsTruncStore are mutually exclusive");
1066 if (isNonTruncStore())
1068 " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1071 " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1074 Record
*ScalarMemoryVT
= getScalarMemoryVT();
1077 Code
+= ("if (cast<" + SDNodeName
+
1078 ">(N)->getMemoryVT().getScalarType() != MVT::" +
1079 ScalarMemoryVT
->getName() + ") return false;\n")
1083 std::string PredicateCode
= PatFragRec
->getRecord()->getValueAsString("PredicateCode");
1085 Code
+= PredicateCode
;
1087 if (PredicateCode
.empty() && !Code
.empty())
1088 Code
+= "return true;\n";
1093 bool TreePredicateFn::hasImmCode() const {
1094 return !PatFragRec
->getRecord()->getValueAsString("ImmediateCode").empty();
1097 std::string
TreePredicateFn::getImmCode() const {
1098 return PatFragRec
->getRecord()->getValueAsString("ImmediateCode");
1101 bool TreePredicateFn::immCodeUsesAPInt() const {
1102 return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
1105 bool TreePredicateFn::immCodeUsesAPFloat() const {
1107 // The return value will be false when IsAPFloat is unset.
1108 return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
1112 bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field
,
1116 getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field
, Unset
);
1119 return Result
== Value
;
1121 bool TreePredicateFn::usesOperands() const {
1122 return isPredefinedPredicateEqualTo("PredicateCodeUsesOperands", true);
1124 bool TreePredicateFn::isLoad() const {
1125 return isPredefinedPredicateEqualTo("IsLoad", true);
1127 bool TreePredicateFn::isStore() const {
1128 return isPredefinedPredicateEqualTo("IsStore", true);
1130 bool TreePredicateFn::isAtomic() const {
1131 return isPredefinedPredicateEqualTo("IsAtomic", true);
1133 bool TreePredicateFn::isUnindexed() const {
1134 return isPredefinedPredicateEqualTo("IsUnindexed", true);
1136 bool TreePredicateFn::isNonExtLoad() const {
1137 return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
1139 bool TreePredicateFn::isAnyExtLoad() const {
1140 return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
1142 bool TreePredicateFn::isSignExtLoad() const {
1143 return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
1145 bool TreePredicateFn::isZeroExtLoad() const {
1146 return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
1148 bool TreePredicateFn::isNonTruncStore() const {
1149 return isPredefinedPredicateEqualTo("IsTruncStore", false);
1151 bool TreePredicateFn::isTruncStore() const {
1152 return isPredefinedPredicateEqualTo("IsTruncStore", true);
1154 bool TreePredicateFn::isAtomicOrderingMonotonic() const {
1155 return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true);
1157 bool TreePredicateFn::isAtomicOrderingAcquire() const {
1158 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true);
1160 bool TreePredicateFn::isAtomicOrderingRelease() const {
1161 return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true);
1163 bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
1164 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true);
1166 bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
1167 return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent",
1170 bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {
1171 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", true);
1173 bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {
1174 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", false);
1176 bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {
1177 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", true);
1179 bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {
1180 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", false);
1182 Record
*TreePredicateFn::getMemoryVT() const {
1183 Record
*R
= getOrigPatFragRecord()->getRecord();
1184 if (R
->isValueUnset("MemoryVT"))
1186 return R
->getValueAsDef("MemoryVT");
1189 ListInit
*TreePredicateFn::getAddressSpaces() const {
1190 Record
*R
= getOrigPatFragRecord()->getRecord();
1191 if (R
->isValueUnset("AddressSpaces"))
1193 return R
->getValueAsListInit("AddressSpaces");
1196 int64_t TreePredicateFn::getMinAlignment() const {
1197 Record
*R
= getOrigPatFragRecord()->getRecord();
1198 if (R
->isValueUnset("MinAlignment"))
1200 return R
->getValueAsInt("MinAlignment");
1203 Record
*TreePredicateFn::getScalarMemoryVT() const {
1204 Record
*R
= getOrigPatFragRecord()->getRecord();
1205 if (R
->isValueUnset("ScalarMemoryVT"))
1207 return R
->getValueAsDef("ScalarMemoryVT");
1209 bool TreePredicateFn::hasGISelPredicateCode() const {
1210 return !PatFragRec
->getRecord()
1211 ->getValueAsString("GISelPredicateCode")
1214 std::string
TreePredicateFn::getGISelPredicateCode() const {
1215 return PatFragRec
->getRecord()->getValueAsString("GISelPredicateCode");
1218 StringRef
TreePredicateFn::getImmType() const {
1219 if (immCodeUsesAPInt())
1220 return "const APInt &";
1221 if (immCodeUsesAPFloat())
1222 return "const APFloat &";
1226 StringRef
TreePredicateFn::getImmTypeIdentifier() const {
1227 if (immCodeUsesAPInt())
1229 else if (immCodeUsesAPFloat())
1234 /// isAlwaysTrue - Return true if this is a noop predicate.
1235 bool TreePredicateFn::isAlwaysTrue() const {
1236 return !hasPredCode() && !hasImmCode();
1239 /// Return the name to use in the generated code to reference this, this is
1240 /// "Predicate_foo" if from a pattern fragment "foo".
1241 std::string
TreePredicateFn::getFnName() const {
1242 return "Predicate_" + PatFragRec
->getRecord()->getName().str();
1245 /// getCodeToRunOnSDNode - Return the code for the function body that
1246 /// evaluates this predicate. The argument is expected to be in "Node",
1247 /// not N. This handles casting and conversion to a concrete node type as
1249 std::string
TreePredicateFn::getCodeToRunOnSDNode() const {
1250 // Handle immediate predicates first.
1251 std::string ImmCode
= getImmCode();
1252 if (!ImmCode
.empty()) {
1254 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1255 "IsLoad cannot be used with ImmLeaf or its subclasses");
1257 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1258 "IsStore cannot be used with ImmLeaf or its subclasses");
1261 getOrigPatFragRecord()->getRecord()->getLoc(),
1262 "IsUnindexed cannot be used with ImmLeaf or its subclasses");
1265 getOrigPatFragRecord()->getRecord()->getLoc(),
1266 "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
1269 getOrigPatFragRecord()->getRecord()->getLoc(),
1270 "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
1271 if (isSignExtLoad())
1273 getOrigPatFragRecord()->getRecord()->getLoc(),
1274 "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
1275 if (isZeroExtLoad())
1277 getOrigPatFragRecord()->getRecord()->getLoc(),
1278 "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
1279 if (isNonTruncStore())
1281 getOrigPatFragRecord()->getRecord()->getLoc(),
1282 "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
1285 getOrigPatFragRecord()->getRecord()->getLoc(),
1286 "IsTruncStore cannot be used with ImmLeaf or its subclasses");
1288 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1289 "MemoryVT cannot be used with ImmLeaf or its subclasses");
1290 if (getScalarMemoryVT())
1292 getOrigPatFragRecord()->getRecord()->getLoc(),
1293 "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
1295 std::string Result
= (" " + getImmType() + " Imm = ").str();
1296 if (immCodeUsesAPFloat())
1297 Result
+= "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
1298 else if (immCodeUsesAPInt())
1299 Result
+= "cast<ConstantSDNode>(Node)->getAPIntValue();\n";
1301 Result
+= "cast<ConstantSDNode>(Node)->getSExtValue();\n";
1302 return Result
+ ImmCode
;
1305 // Handle arbitrary node predicates.
1306 assert(hasPredCode() && "Don't have any predicate code!");
1307 StringRef ClassName
;
1308 if (PatFragRec
->getOnlyTree()->isLeaf())
1309 ClassName
= "SDNode";
1311 Record
*Op
= PatFragRec
->getOnlyTree()->getOperator();
1312 ClassName
= PatFragRec
->getDAGPatterns().getSDNodeInfo(Op
).getSDClassName();
1315 if (ClassName
== "SDNode")
1316 Result
= " SDNode *N = Node;\n";
1318 Result
= " auto *N = cast<" + ClassName
.str() + ">(Node);\n";
1320 return (Twine(Result
) + " (void)N;\n" + getPredCode()).str();
1323 //===----------------------------------------------------------------------===//
1324 // PatternToMatch implementation
1327 static bool isImmAllOnesAllZerosMatch(const TreePatternNode
*P
) {
1330 DefInit
*DI
= dyn_cast
<DefInit
>(P
->getLeafValue());
1334 Record
*R
= DI
->getDef();
1335 return R
->getName() == "immAllOnesV" || R
->getName() == "immAllZerosV";
1338 /// getPatternSize - Return the 'size' of this pattern. We want to match large
1339 /// patterns before small ones. This is used to determine the size of a
1341 static unsigned getPatternSize(const TreePatternNode
*P
,
1342 const CodeGenDAGPatterns
&CGP
) {
1343 unsigned Size
= 3; // The node itself.
1344 // If the root node is a ConstantSDNode, increases its size.
1345 // e.g. (set R32:$dst, 0).
1346 if (P
->isLeaf() && isa
<IntInit
>(P
->getLeafValue()))
1349 if (const ComplexPattern
*AM
= P
->getComplexPatternInfo(CGP
)) {
1350 Size
+= AM
->getComplexity();
1351 // We don't want to count any children twice, so return early.
1355 // If this node has some predicate function that must match, it adds to the
1356 // complexity of this node.
1357 if (!P
->getPredicateCalls().empty())
1360 // Count children in the count if they are also nodes.
1361 for (unsigned i
= 0, e
= P
->getNumChildren(); i
!= e
; ++i
) {
1362 const TreePatternNode
*Child
= P
->getChild(i
);
1363 if (!Child
->isLeaf() && Child
->getNumTypes()) {
1364 const TypeSetByHwMode
&T0
= Child
->getExtType(0);
1365 // At this point, all variable type sets should be simple, i.e. only
1366 // have a default mode.
1367 if (T0
.getMachineValueType() != MVT::Other
) {
1368 Size
+= getPatternSize(Child
, CGP
);
1372 if (Child
->isLeaf()) {
1373 if (isa
<IntInit
>(Child
->getLeafValue()))
1374 Size
+= 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
1375 else if (Child
->getComplexPatternInfo(CGP
))
1376 Size
+= getPatternSize(Child
, CGP
);
1377 else if (isImmAllOnesAllZerosMatch(Child
))
1378 Size
+= 4; // Matches a build_vector(+3) and a predicate (+1).
1379 else if (!Child
->getPredicateCalls().empty())
1387 /// Compute the complexity metric for the input pattern. This roughly
1388 /// corresponds to the number of nodes that are covered.
1389 int PatternToMatch::
1390 getPatternComplexity(const CodeGenDAGPatterns
&CGP
) const {
1391 return getPatternSize(getSrcPattern(), CGP
) + getAddedComplexity();
1394 /// getPredicateCheck - Return a single string containing all of this
1395 /// pattern's predicates concatenated with "&&" operators.
1397 std::string
PatternToMatch::getPredicateCheck() const {
1398 SmallVector
<const Predicate
*,4> PredList
;
1399 for (const Predicate
&P
: Predicates
) {
1400 if (!P
.getCondString().empty())
1401 PredList
.push_back(&P
);
1403 llvm::sort(PredList
, deref
<std::less
<>>());
1406 for (unsigned i
= 0, e
= PredList
.size(); i
!= e
; ++i
) {
1409 Check
+= '(' + PredList
[i
]->getCondString() + ')';
1414 //===----------------------------------------------------------------------===//
1415 // SDTypeConstraint implementation
1418 SDTypeConstraint::SDTypeConstraint(Record
*R
, const CodeGenHwModes
&CGH
) {
1419 OperandNo
= R
->getValueAsInt("OperandNum");
1421 if (R
->isSubClassOf("SDTCisVT")) {
1422 ConstraintType
= SDTCisVT
;
1423 VVT
= getValueTypeByHwMode(R
->getValueAsDef("VT"), CGH
);
1424 for (const auto &P
: VVT
)
1425 if (P
.second
== MVT::isVoid
)
1426 PrintFatalError(R
->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
1427 } else if (R
->isSubClassOf("SDTCisPtrTy")) {
1428 ConstraintType
= SDTCisPtrTy
;
1429 } else if (R
->isSubClassOf("SDTCisInt")) {
1430 ConstraintType
= SDTCisInt
;
1431 } else if (R
->isSubClassOf("SDTCisFP")) {
1432 ConstraintType
= SDTCisFP
;
1433 } else if (R
->isSubClassOf("SDTCisVec")) {
1434 ConstraintType
= SDTCisVec
;
1435 } else if (R
->isSubClassOf("SDTCisSameAs")) {
1436 ConstraintType
= SDTCisSameAs
;
1437 x
.SDTCisSameAs_Info
.OtherOperandNum
= R
->getValueAsInt("OtherOperandNum");
1438 } else if (R
->isSubClassOf("SDTCisVTSmallerThanOp")) {
1439 ConstraintType
= SDTCisVTSmallerThanOp
;
1440 x
.SDTCisVTSmallerThanOp_Info
.OtherOperandNum
=
1441 R
->getValueAsInt("OtherOperandNum");
1442 } else if (R
->isSubClassOf("SDTCisOpSmallerThanOp")) {
1443 ConstraintType
= SDTCisOpSmallerThanOp
;
1444 x
.SDTCisOpSmallerThanOp_Info
.BigOperandNum
=
1445 R
->getValueAsInt("BigOperandNum");
1446 } else if (R
->isSubClassOf("SDTCisEltOfVec")) {
1447 ConstraintType
= SDTCisEltOfVec
;
1448 x
.SDTCisEltOfVec_Info
.OtherOperandNum
= R
->getValueAsInt("OtherOpNum");
1449 } else if (R
->isSubClassOf("SDTCisSubVecOfVec")) {
1450 ConstraintType
= SDTCisSubVecOfVec
;
1451 x
.SDTCisSubVecOfVec_Info
.OtherOperandNum
=
1452 R
->getValueAsInt("OtherOpNum");
1453 } else if (R
->isSubClassOf("SDTCVecEltisVT")) {
1454 ConstraintType
= SDTCVecEltisVT
;
1455 VVT
= getValueTypeByHwMode(R
->getValueAsDef("VT"), CGH
);
1456 for (const auto &P
: VVT
) {
1459 PrintFatalError(R
->getLoc(),
1460 "Cannot use vector type as SDTCVecEltisVT");
1461 if (!T
.isInteger() && !T
.isFloatingPoint())
1462 PrintFatalError(R
->getLoc(), "Must use integer or floating point type "
1463 "as SDTCVecEltisVT");
1465 } else if (R
->isSubClassOf("SDTCisSameNumEltsAs")) {
1466 ConstraintType
= SDTCisSameNumEltsAs
;
1467 x
.SDTCisSameNumEltsAs_Info
.OtherOperandNum
=
1468 R
->getValueAsInt("OtherOperandNum");
1469 } else if (R
->isSubClassOf("SDTCisSameSizeAs")) {
1470 ConstraintType
= SDTCisSameSizeAs
;
1471 x
.SDTCisSameSizeAs_Info
.OtherOperandNum
=
1472 R
->getValueAsInt("OtherOperandNum");
1474 PrintFatalError(R
->getLoc(),
1475 "Unrecognized SDTypeConstraint '" + R
->getName() + "'!\n");
1479 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
1480 /// N, and the result number in ResNo.
1481 static TreePatternNode
*getOperandNum(unsigned OpNo
, TreePatternNode
*N
,
1482 const SDNodeInfo
&NodeInfo
,
1484 unsigned NumResults
= NodeInfo
.getNumResults();
1485 if (OpNo
< NumResults
) {
1492 if (OpNo
>= N
->getNumChildren()) {
1494 raw_string_ostream
OS(S
);
1495 OS
<< "Invalid operand number in type constraint "
1496 << (OpNo
+NumResults
) << " ";
1498 PrintFatalError(OS
.str());
1501 return N
->getChild(OpNo
);
1504 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
1505 /// constraint to the nodes operands. This returns true if it makes a
1506 /// change, false otherwise. If a type contradiction is found, flag an error.
1507 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode
*N
,
1508 const SDNodeInfo
&NodeInfo
,
1509 TreePattern
&TP
) const {
1513 unsigned ResNo
= 0; // The result number being referenced.
1514 TreePatternNode
*NodeToApply
= getOperandNum(OperandNo
, N
, NodeInfo
, ResNo
);
1515 TypeInfer
&TI
= TP
.getInfer();
1517 switch (ConstraintType
) {
1519 // Operand must be a particular type.
1520 return NodeToApply
->UpdateNodeType(ResNo
, VVT
, TP
);
1522 // Operand must be same as target pointer type.
1523 return NodeToApply
->UpdateNodeType(ResNo
, MVT::iPTR
, TP
);
1525 // Require it to be one of the legal integer VTs.
1526 return TI
.EnforceInteger(NodeToApply
->getExtType(ResNo
));
1528 // Require it to be one of the legal fp VTs.
1529 return TI
.EnforceFloatingPoint(NodeToApply
->getExtType(ResNo
));
1531 // Require it to be one of the legal vector VTs.
1532 return TI
.EnforceVector(NodeToApply
->getExtType(ResNo
));
1533 case SDTCisSameAs
: {
1534 unsigned OResNo
= 0;
1535 TreePatternNode
*OtherNode
=
1536 getOperandNum(x
.SDTCisSameAs_Info
.OtherOperandNum
, N
, NodeInfo
, OResNo
);
1537 return NodeToApply
->UpdateNodeType(ResNo
, OtherNode
->getExtType(OResNo
),TP
)|
1538 OtherNode
->UpdateNodeType(OResNo
,NodeToApply
->getExtType(ResNo
),TP
);
1540 case SDTCisVTSmallerThanOp
: {
1541 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1542 // have an integer type that is smaller than the VT.
1543 if (!NodeToApply
->isLeaf() ||
1544 !isa
<DefInit
>(NodeToApply
->getLeafValue()) ||
1545 !static_cast<DefInit
*>(NodeToApply
->getLeafValue())->getDef()
1546 ->isSubClassOf("ValueType")) {
1547 TP
.error(N
->getOperator()->getName() + " expects a VT operand!");
1550 DefInit
*DI
= static_cast<DefInit
*>(NodeToApply
->getLeafValue());
1551 const CodeGenTarget
&T
= TP
.getDAGPatterns().getTargetInfo();
1552 auto VVT
= getValueTypeByHwMode(DI
->getDef(), T
.getHwModes());
1553 TypeSetByHwMode
TypeListTmp(VVT
);
1555 unsigned OResNo
= 0;
1556 TreePatternNode
*OtherNode
=
1557 getOperandNum(x
.SDTCisVTSmallerThanOp_Info
.OtherOperandNum
, N
, NodeInfo
,
1560 return TI
.EnforceSmallerThan(TypeListTmp
, OtherNode
->getExtType(OResNo
));
1562 case SDTCisOpSmallerThanOp
: {
1563 unsigned BResNo
= 0;
1564 TreePatternNode
*BigOperand
=
1565 getOperandNum(x
.SDTCisOpSmallerThanOp_Info
.BigOperandNum
, N
, NodeInfo
,
1567 return TI
.EnforceSmallerThan(NodeToApply
->getExtType(ResNo
),
1568 BigOperand
->getExtType(BResNo
));
1570 case SDTCisEltOfVec
: {
1571 unsigned VResNo
= 0;
1572 TreePatternNode
*VecOperand
=
1573 getOperandNum(x
.SDTCisEltOfVec_Info
.OtherOperandNum
, N
, NodeInfo
,
1575 // Filter vector types out of VecOperand that don't have the right element
1577 return TI
.EnforceVectorEltTypeIs(VecOperand
->getExtType(VResNo
),
1578 NodeToApply
->getExtType(ResNo
));
1580 case SDTCisSubVecOfVec
: {
1581 unsigned VResNo
= 0;
1582 TreePatternNode
*BigVecOperand
=
1583 getOperandNum(x
.SDTCisSubVecOfVec_Info
.OtherOperandNum
, N
, NodeInfo
,
1586 // Filter vector types out of BigVecOperand that don't have the
1587 // right subvector type.
1588 return TI
.EnforceVectorSubVectorTypeIs(BigVecOperand
->getExtType(VResNo
),
1589 NodeToApply
->getExtType(ResNo
));
1591 case SDTCVecEltisVT
: {
1592 return TI
.EnforceVectorEltTypeIs(NodeToApply
->getExtType(ResNo
), VVT
);
1594 case SDTCisSameNumEltsAs
: {
1595 unsigned OResNo
= 0;
1596 TreePatternNode
*OtherNode
=
1597 getOperandNum(x
.SDTCisSameNumEltsAs_Info
.OtherOperandNum
,
1598 N
, NodeInfo
, OResNo
);
1599 return TI
.EnforceSameNumElts(OtherNode
->getExtType(OResNo
),
1600 NodeToApply
->getExtType(ResNo
));
1602 case SDTCisSameSizeAs
: {
1603 unsigned OResNo
= 0;
1604 TreePatternNode
*OtherNode
=
1605 getOperandNum(x
.SDTCisSameSizeAs_Info
.OtherOperandNum
,
1606 N
, NodeInfo
, OResNo
);
1607 return TI
.EnforceSameSize(OtherNode
->getExtType(OResNo
),
1608 NodeToApply
->getExtType(ResNo
));
1611 llvm_unreachable("Invalid ConstraintType!");
1614 // Update the node type to match an instruction operand or result as specified
1615 // in the ins or outs lists on the instruction definition. Return true if the
1616 // type was actually changed.
1617 bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo
,
1620 // The 'unknown' operand indicates that types should be inferred from the
1622 if (Operand
->isSubClassOf("unknown_class"))
1625 // The Operand class specifies a type directly.
1626 if (Operand
->isSubClassOf("Operand")) {
1627 Record
*R
= Operand
->getValueAsDef("Type");
1628 const CodeGenTarget
&T
= TP
.getDAGPatterns().getTargetInfo();
1629 return UpdateNodeType(ResNo
, getValueTypeByHwMode(R
, T
.getHwModes()), TP
);
1632 // PointerLikeRegClass has a type that is determined at runtime.
1633 if (Operand
->isSubClassOf("PointerLikeRegClass"))
1634 return UpdateNodeType(ResNo
, MVT::iPTR
, TP
);
1636 // Both RegisterClass and RegisterOperand operands derive their types from a
1637 // register class def.
1638 Record
*RC
= nullptr;
1639 if (Operand
->isSubClassOf("RegisterClass"))
1641 else if (Operand
->isSubClassOf("RegisterOperand"))
1642 RC
= Operand
->getValueAsDef("RegClass");
1644 assert(RC
&& "Unknown operand type");
1645 CodeGenTarget
&Tgt
= TP
.getDAGPatterns().getTargetInfo();
1646 return UpdateNodeType(ResNo
, Tgt
.getRegisterClass(RC
).getValueTypes(), TP
);
1649 bool TreePatternNode::ContainsUnresolvedType(TreePattern
&TP
) const {
1650 for (unsigned i
= 0, e
= Types
.size(); i
!= e
; ++i
)
1651 if (!TP
.getInfer().isConcrete(Types
[i
], true))
1653 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
1654 if (getChild(i
)->ContainsUnresolvedType(TP
))
1659 bool TreePatternNode::hasProperTypeByHwMode() const {
1660 for (const TypeSetByHwMode
&S
: Types
)
1661 if (!S
.isDefaultOnly())
1663 for (const TreePatternNodePtr
&C
: Children
)
1664 if (C
->hasProperTypeByHwMode())
1669 bool TreePatternNode::hasPossibleType() const {
1670 for (const TypeSetByHwMode
&S
: Types
)
1671 if (!S
.isPossible())
1673 for (const TreePatternNodePtr
&C
: Children
)
1674 if (!C
->hasPossibleType())
1679 bool TreePatternNode::setDefaultMode(unsigned Mode
) {
1680 for (TypeSetByHwMode
&S
: Types
) {
1682 // Check if the selected mode had a type conflict.
1683 if (S
.get(DefaultMode
).empty())
1686 for (const TreePatternNodePtr
&C
: Children
)
1687 if (!C
->setDefaultMode(Mode
))
1692 //===----------------------------------------------------------------------===//
1693 // SDNodeInfo implementation
1695 SDNodeInfo::SDNodeInfo(Record
*R
, const CodeGenHwModes
&CGH
) : Def(R
) {
1696 EnumName
= R
->getValueAsString("Opcode");
1697 SDClassName
= R
->getValueAsString("SDClass");
1698 Record
*TypeProfile
= R
->getValueAsDef("TypeProfile");
1699 NumResults
= TypeProfile
->getValueAsInt("NumResults");
1700 NumOperands
= TypeProfile
->getValueAsInt("NumOperands");
1702 // Parse the properties.
1703 Properties
= parseSDPatternOperatorProperties(R
);
1705 // Parse the type constraints.
1706 std::vector
<Record
*> ConstraintList
=
1707 TypeProfile
->getValueAsListOfDefs("Constraints");
1708 for (Record
*R
: ConstraintList
)
1709 TypeConstraints
.emplace_back(R
, CGH
);
1712 /// getKnownType - If the type constraints on this node imply a fixed type
1713 /// (e.g. all stores return void, etc), then return it as an
1714 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
1715 MVT::SimpleValueType
SDNodeInfo::getKnownType(unsigned ResNo
) const {
1716 unsigned NumResults
= getNumResults();
1717 assert(NumResults
<= 1 &&
1718 "We only work with nodes with zero or one result so far!");
1719 assert(ResNo
== 0 && "Only handles single result nodes so far");
1721 for (const SDTypeConstraint
&Constraint
: TypeConstraints
) {
1722 // Make sure that this applies to the correct node result.
1723 if (Constraint
.OperandNo
>= NumResults
) // FIXME: need value #
1726 switch (Constraint
.ConstraintType
) {
1728 case SDTypeConstraint::SDTCisVT
:
1729 if (Constraint
.VVT
.isSimple())
1730 return Constraint
.VVT
.getSimple().SimpleTy
;
1732 case SDTypeConstraint::SDTCisPtrTy
:
1739 //===----------------------------------------------------------------------===//
1740 // TreePatternNode implementation
1743 static unsigned GetNumNodeResults(Record
*Operator
, CodeGenDAGPatterns
&CDP
) {
1744 if (Operator
->getName() == "set" ||
1745 Operator
->getName() == "implicit")
1746 return 0; // All return nothing.
1748 if (Operator
->isSubClassOf("Intrinsic"))
1749 return CDP
.getIntrinsic(Operator
).IS
.RetVTs
.size();
1751 if (Operator
->isSubClassOf("SDNode"))
1752 return CDP
.getSDNodeInfo(Operator
).getNumResults();
1754 if (Operator
->isSubClassOf("PatFrags")) {
1755 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1756 // the forward reference case where one pattern fragment references another
1757 // before it is processed.
1758 if (TreePattern
*PFRec
= CDP
.getPatternFragmentIfRead(Operator
)) {
1759 // The number of results of a fragment with alternative records is the
1760 // maximum number of results across all alternatives.
1761 unsigned NumResults
= 0;
1762 for (auto T
: PFRec
->getTrees())
1763 NumResults
= std::max(NumResults
, T
->getNumTypes());
1767 ListInit
*LI
= Operator
->getValueAsListInit("Fragments");
1768 assert(LI
&& "Invalid Fragment");
1769 unsigned NumResults
= 0;
1770 for (Init
*I
: LI
->getValues()) {
1771 Record
*Op
= nullptr;
1772 if (DagInit
*Dag
= dyn_cast
<DagInit
>(I
))
1773 if (DefInit
*DI
= dyn_cast
<DefInit
>(Dag
->getOperator()))
1775 assert(Op
&& "Invalid Fragment");
1776 NumResults
= std::max(NumResults
, GetNumNodeResults(Op
, CDP
));
1781 if (Operator
->isSubClassOf("Instruction")) {
1782 CodeGenInstruction
&InstInfo
= CDP
.getTargetInfo().getInstruction(Operator
);
1784 unsigned NumDefsToAdd
= InstInfo
.Operands
.NumDefs
;
1786 // Subtract any defaulted outputs.
1787 for (unsigned i
= 0; i
!= InstInfo
.Operands
.NumDefs
; ++i
) {
1788 Record
*OperandNode
= InstInfo
.Operands
[i
].Rec
;
1790 if (OperandNode
->isSubClassOf("OperandWithDefaultOps") &&
1791 !CDP
.getDefaultOperand(OperandNode
).DefaultOps
.empty())
1795 // Add on one implicit def if it has a resolvable type.
1796 if (InstInfo
.HasOneImplicitDefWithKnownVT(CDP
.getTargetInfo()) !=MVT::Other
)
1798 return NumDefsToAdd
;
1801 if (Operator
->isSubClassOf("SDNodeXForm"))
1802 return 1; // FIXME: Generalize SDNodeXForm
1804 if (Operator
->isSubClassOf("ValueType"))
1805 return 1; // A type-cast of one result.
1807 if (Operator
->isSubClassOf("ComplexPattern"))
1810 errs() << *Operator
;
1811 PrintFatalError("Unhandled node in GetNumNodeResults");
1814 void TreePatternNode::print(raw_ostream
&OS
) const {
1816 OS
<< *getLeafValue();
1818 OS
<< '(' << getOperator()->getName();
1820 for (unsigned i
= 0, e
= Types
.size(); i
!= e
; ++i
) {
1822 getExtType(i
).writeToStream(OS
);
1826 if (getNumChildren() != 0) {
1828 getChild(0)->print(OS
);
1829 for (unsigned i
= 1, e
= getNumChildren(); i
!= e
; ++i
) {
1831 getChild(i
)->print(OS
);
1837 for (const TreePredicateCall
&Pred
: PredicateCalls
) {
1840 OS
<< Pred
.Scope
<< ":";
1841 OS
<< Pred
.Fn
.getFnName() << ">>";
1844 OS
<< "<<X:" << TransformFn
->getName() << ">>";
1845 if (!getName().empty())
1846 OS
<< ":$" << getName();
1848 for (const ScopedName
&Name
: NamesAsPredicateArg
)
1849 OS
<< ":$pred:" << Name
.getScope() << ":" << Name
.getIdentifier();
1851 void TreePatternNode::dump() const {
1855 /// isIsomorphicTo - Return true if this node is recursively
1856 /// isomorphic to the specified node. For this comparison, the node's
1857 /// entire state is considered. The assigned name is ignored, since
1858 /// nodes with differing names are considered isomorphic. However, if
1859 /// the assigned name is present in the dependent variable set, then
1860 /// the assigned name is considered significant and the node is
1861 /// isomorphic if the names match.
1862 bool TreePatternNode::isIsomorphicTo(const TreePatternNode
*N
,
1863 const MultipleUseVarSet
&DepVars
) const {
1864 if (N
== this) return true;
1865 if (N
->isLeaf() != isLeaf() || getExtTypes() != N
->getExtTypes() ||
1866 getPredicateCalls() != N
->getPredicateCalls() ||
1867 getTransformFn() != N
->getTransformFn())
1871 if (DefInit
*DI
= dyn_cast
<DefInit
>(getLeafValue())) {
1872 if (DefInit
*NDI
= dyn_cast
<DefInit
>(N
->getLeafValue())) {
1873 return ((DI
->getDef() == NDI
->getDef())
1874 && (DepVars
.find(getName()) == DepVars
.end()
1875 || getName() == N
->getName()));
1878 return getLeafValue() == N
->getLeafValue();
1881 if (N
->getOperator() != getOperator() ||
1882 N
->getNumChildren() != getNumChildren()) return false;
1883 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
1884 if (!getChild(i
)->isIsomorphicTo(N
->getChild(i
), DepVars
))
1889 /// clone - Make a copy of this tree and all of its children.
1891 TreePatternNodePtr
TreePatternNode::clone() const {
1892 TreePatternNodePtr New
;
1894 New
= std::make_shared
<TreePatternNode
>(getLeafValue(), getNumTypes());
1896 std::vector
<TreePatternNodePtr
> CChildren
;
1897 CChildren
.reserve(Children
.size());
1898 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
1899 CChildren
.push_back(getChild(i
)->clone());
1900 New
= std::make_shared
<TreePatternNode
>(getOperator(), std::move(CChildren
),
1903 New
->setName(getName());
1904 New
->setNamesAsPredicateArg(getNamesAsPredicateArg());
1906 New
->setPredicateCalls(getPredicateCalls());
1907 New
->setTransformFn(getTransformFn());
1911 /// RemoveAllTypes - Recursively strip all the types of this tree.
1912 void TreePatternNode::RemoveAllTypes() {
1913 // Reset to unknown type.
1914 std::fill(Types
.begin(), Types
.end(), TypeSetByHwMode());
1915 if (isLeaf()) return;
1916 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
1917 getChild(i
)->RemoveAllTypes();
1921 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1922 /// with actual values specified by ArgMap.
1923 void TreePatternNode::SubstituteFormalArguments(
1924 std::map
<std::string
, TreePatternNodePtr
> &ArgMap
) {
1925 if (isLeaf()) return;
1927 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
) {
1928 TreePatternNode
*Child
= getChild(i
);
1929 if (Child
->isLeaf()) {
1930 Init
*Val
= Child
->getLeafValue();
1931 // Note that, when substituting into an output pattern, Val might be an
1933 if (isa
<UnsetInit
>(Val
) || (isa
<DefInit
>(Val
) &&
1934 cast
<DefInit
>(Val
)->getDef()->getName() == "node")) {
1935 // We found a use of a formal argument, replace it with its value.
1936 TreePatternNodePtr NewChild
= ArgMap
[Child
->getName()];
1937 assert(NewChild
&& "Couldn't find formal argument!");
1938 assert((Child
->getPredicateCalls().empty() ||
1939 NewChild
->getPredicateCalls() == Child
->getPredicateCalls()) &&
1940 "Non-empty child predicate clobbered!");
1941 setChild(i
, std::move(NewChild
));
1944 getChild(i
)->SubstituteFormalArguments(ArgMap
);
1950 /// InlinePatternFragments - If this pattern refers to any pattern
1951 /// fragments, return the set of inlined versions (this can be more than
1952 /// one if a PatFrags record has multiple alternatives).
1953 void TreePatternNode::InlinePatternFragments(
1954 TreePatternNodePtr T
, TreePattern
&TP
,
1955 std::vector
<TreePatternNodePtr
> &OutAlternatives
) {
1961 OutAlternatives
.push_back(T
); // nothing to do.
1965 Record
*Op
= getOperator();
1967 if (!Op
->isSubClassOf("PatFrags")) {
1968 if (getNumChildren() == 0) {
1969 OutAlternatives
.push_back(T
);
1973 // Recursively inline children nodes.
1974 std::vector
<std::vector
<TreePatternNodePtr
> > ChildAlternatives
;
1975 ChildAlternatives
.resize(getNumChildren());
1976 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
) {
1977 TreePatternNodePtr Child
= getChildShared(i
);
1978 Child
->InlinePatternFragments(Child
, TP
, ChildAlternatives
[i
]);
1979 // If there are no alternatives for any child, there are no
1980 // alternatives for this expression as whole.
1981 if (ChildAlternatives
[i
].empty())
1984 for (auto NewChild
: ChildAlternatives
[i
])
1985 assert((Child
->getPredicateCalls().empty() ||
1986 NewChild
->getPredicateCalls() == Child
->getPredicateCalls()) &&
1987 "Non-empty child predicate clobbered!");
1990 // The end result is an all-pairs construction of the resultant pattern.
1991 std::vector
<unsigned> Idxs
;
1992 Idxs
.resize(ChildAlternatives
.size());
1995 // Create the variant and add it to the output list.
1996 std::vector
<TreePatternNodePtr
> NewChildren
;
1997 for (unsigned i
= 0, e
= ChildAlternatives
.size(); i
!= e
; ++i
)
1998 NewChildren
.push_back(ChildAlternatives
[i
][Idxs
[i
]]);
1999 TreePatternNodePtr R
= std::make_shared
<TreePatternNode
>(
2000 getOperator(), std::move(NewChildren
), getNumTypes());
2002 // Copy over properties.
2003 R
->setName(getName());
2004 R
->setNamesAsPredicateArg(getNamesAsPredicateArg());
2005 R
->setPredicateCalls(getPredicateCalls());
2006 R
->setTransformFn(getTransformFn());
2007 for (unsigned i
= 0, e
= getNumTypes(); i
!= e
; ++i
)
2008 R
->setType(i
, getExtType(i
));
2009 for (unsigned i
= 0, e
= getNumResults(); i
!= e
; ++i
)
2010 R
->setResultIndex(i
, getResultIndex(i
));
2012 // Register alternative.
2013 OutAlternatives
.push_back(R
);
2015 // Increment indices to the next permutation by incrementing the
2016 // indices from last index backward, e.g., generate the sequence
2017 // [0, 0], [0, 1], [1, 0], [1, 1].
2019 for (IdxsIdx
= Idxs
.size() - 1; IdxsIdx
>= 0; --IdxsIdx
) {
2020 if (++Idxs
[IdxsIdx
] == ChildAlternatives
[IdxsIdx
].size())
2025 NotDone
= (IdxsIdx
>= 0);
2031 // Otherwise, we found a reference to a fragment. First, look up its
2032 // TreePattern record.
2033 TreePattern
*Frag
= TP
.getDAGPatterns().getPatternFragment(Op
);
2035 // Verify that we are passing the right number of operands.
2036 if (Frag
->getNumArgs() != Children
.size()) {
2037 TP
.error("'" + Op
->getName() + "' fragment requires " +
2038 Twine(Frag
->getNumArgs()) + " operands!");
2042 TreePredicateFn
PredFn(Frag
);
2044 if (TreePredicateFn(Frag
).usesOperands())
2045 Scope
= TP
.getDAGPatterns().allocateScope();
2047 // Compute the map of formal to actual arguments.
2048 std::map
<std::string
, TreePatternNodePtr
> ArgMap
;
2049 for (unsigned i
= 0, e
= Frag
->getNumArgs(); i
!= e
; ++i
) {
2050 TreePatternNodePtr Child
= getChildShared(i
);
2052 Child
= Child
->clone();
2053 Child
->addNameAsPredicateArg(ScopedName(Scope
, Frag
->getArgName(i
)));
2055 ArgMap
[Frag
->getArgName(i
)] = Child
;
2058 // Loop over all fragment alternatives.
2059 for (auto Alternative
: Frag
->getTrees()) {
2060 TreePatternNodePtr FragTree
= Alternative
->clone();
2062 if (!PredFn
.isAlwaysTrue())
2063 FragTree
->addPredicateCall(PredFn
, Scope
);
2065 // Resolve formal arguments to their actual value.
2066 if (Frag
->getNumArgs())
2067 FragTree
->SubstituteFormalArguments(ArgMap
);
2069 // Transfer types. Note that the resolved alternative may have fewer
2070 // (but not more) results than the PatFrags node.
2071 FragTree
->setName(getName());
2072 for (unsigned i
= 0, e
= FragTree
->getNumTypes(); i
!= e
; ++i
)
2073 FragTree
->UpdateNodeType(i
, getExtType(i
), TP
);
2075 // Transfer in the old predicates.
2076 for (const TreePredicateCall
&Pred
: getPredicateCalls())
2077 FragTree
->addPredicateCall(Pred
);
2079 // The fragment we inlined could have recursive inlining that is needed. See
2080 // if there are any pattern fragments in it and inline them as needed.
2081 FragTree
->InlinePatternFragments(FragTree
, TP
, OutAlternatives
);
2085 /// getImplicitType - Check to see if the specified record has an implicit
2086 /// type which should be applied to it. This will infer the type of register
2087 /// references from the register file information, for example.
2089 /// When Unnamed is set, return the type of a DAG operand with no name, such as
2090 /// the F8RC register class argument in:
2092 /// (COPY_TO_REGCLASS GPR:$src, F8RC)
2094 /// When Unnamed is false, return the type of a named DAG operand such as the
2095 /// GPR:$src operand above.
2097 static TypeSetByHwMode
getImplicitType(Record
*R
, unsigned ResNo
,
2101 CodeGenDAGPatterns
&CDP
= TP
.getDAGPatterns();
2103 // Check to see if this is a register operand.
2104 if (R
->isSubClassOf("RegisterOperand")) {
2105 assert(ResNo
== 0 && "Regoperand ref only has one result!");
2107 return TypeSetByHwMode(); // Unknown.
2108 Record
*RegClass
= R
->getValueAsDef("RegClass");
2109 const CodeGenTarget
&T
= TP
.getDAGPatterns().getTargetInfo();
2110 return TypeSetByHwMode(T
.getRegisterClass(RegClass
).getValueTypes());
2113 // Check to see if this is a register or a register class.
2114 if (R
->isSubClassOf("RegisterClass")) {
2115 assert(ResNo
== 0 && "Regclass ref only has one result!");
2116 // An unnamed register class represents itself as an i32 immediate, for
2117 // example on a COPY_TO_REGCLASS instruction.
2119 return TypeSetByHwMode(MVT::i32
);
2121 // In a named operand, the register class provides the possible set of
2124 return TypeSetByHwMode(); // Unknown.
2125 const CodeGenTarget
&T
= TP
.getDAGPatterns().getTargetInfo();
2126 return TypeSetByHwMode(T
.getRegisterClass(R
).getValueTypes());
2129 if (R
->isSubClassOf("PatFrags")) {
2130 assert(ResNo
== 0 && "FIXME: PatFrag with multiple results?");
2131 // Pattern fragment types will be resolved when they are inlined.
2132 return TypeSetByHwMode(); // Unknown.
2135 if (R
->isSubClassOf("Register")) {
2136 assert(ResNo
== 0 && "Registers only produce one result!");
2138 return TypeSetByHwMode(); // Unknown.
2139 const CodeGenTarget
&T
= TP
.getDAGPatterns().getTargetInfo();
2140 return TypeSetByHwMode(T
.getRegisterVTs(R
));
2143 if (R
->isSubClassOf("SubRegIndex")) {
2144 assert(ResNo
== 0 && "SubRegisterIndices only produce one result!");
2145 return TypeSetByHwMode(MVT::i32
);
2148 if (R
->isSubClassOf("ValueType")) {
2149 assert(ResNo
== 0 && "This node only has one result!");
2150 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
2152 // (sext_inreg GPR:$src, i16)
2155 return TypeSetByHwMode(MVT::Other
);
2156 // With a name, the ValueType simply provides the type of the named
2159 // (sext_inreg i32:$src, i16)
2162 return TypeSetByHwMode(); // Unknown.
2163 const CodeGenHwModes
&CGH
= CDP
.getTargetInfo().getHwModes();
2164 return TypeSetByHwMode(getValueTypeByHwMode(R
, CGH
));
2167 if (R
->isSubClassOf("CondCode")) {
2168 assert(ResNo
== 0 && "This node only has one result!");
2169 // Using a CondCodeSDNode.
2170 return TypeSetByHwMode(MVT::Other
);
2173 if (R
->isSubClassOf("ComplexPattern")) {
2174 assert(ResNo
== 0 && "FIXME: ComplexPattern with multiple results?");
2176 return TypeSetByHwMode(); // Unknown.
2177 return TypeSetByHwMode(CDP
.getComplexPattern(R
).getValueType());
2179 if (R
->isSubClassOf("PointerLikeRegClass")) {
2180 assert(ResNo
== 0 && "Regclass can only have one result!");
2181 TypeSetByHwMode
VTS(MVT::iPTR
);
2182 TP
.getInfer().expandOverloads(VTS
);
2186 if (R
->getName() == "node" || R
->getName() == "srcvalue" ||
2187 R
->getName() == "zero_reg" || R
->getName() == "immAllOnesV" ||
2188 R
->getName() == "immAllZerosV" || R
->getName() == "undef_tied_input") {
2190 return TypeSetByHwMode(); // Unknown.
2193 if (R
->isSubClassOf("Operand")) {
2194 const CodeGenHwModes
&CGH
= CDP
.getTargetInfo().getHwModes();
2195 Record
*T
= R
->getValueAsDef("Type");
2196 return TypeSetByHwMode(getValueTypeByHwMode(T
, CGH
));
2199 TP
.error("Unknown node flavor used in pattern: " + R
->getName());
2200 return TypeSetByHwMode(MVT::Other
);
2204 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
2205 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
2206 const CodeGenIntrinsic
*TreePatternNode::
2207 getIntrinsicInfo(const CodeGenDAGPatterns
&CDP
) const {
2208 if (getOperator() != CDP
.get_intrinsic_void_sdnode() &&
2209 getOperator() != CDP
.get_intrinsic_w_chain_sdnode() &&
2210 getOperator() != CDP
.get_intrinsic_wo_chain_sdnode())
2213 unsigned IID
= cast
<IntInit
>(getChild(0)->getLeafValue())->getValue();
2214 return &CDP
.getIntrinsicInfo(IID
);
2217 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
2218 /// return the ComplexPattern information, otherwise return null.
2219 const ComplexPattern
*
2220 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns
&CGP
) const {
2223 DefInit
*DI
= dyn_cast
<DefInit
>(getLeafValue());
2228 Rec
= getOperator();
2230 if (!Rec
->isSubClassOf("ComplexPattern"))
2232 return &CGP
.getComplexPattern(Rec
);
2235 unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns
&CGP
) const {
2236 // A ComplexPattern specifically declares how many results it fills in.
2237 if (const ComplexPattern
*CP
= getComplexPatternInfo(CGP
))
2238 return CP
->getNumOperands();
2240 // If MIOperandInfo is specified, that gives the count.
2242 DefInit
*DI
= dyn_cast
<DefInit
>(getLeafValue());
2243 if (DI
&& DI
->getDef()->isSubClassOf("Operand")) {
2244 DagInit
*MIOps
= DI
->getDef()->getValueAsDag("MIOperandInfo");
2245 if (MIOps
->getNumArgs())
2246 return MIOps
->getNumArgs();
2250 // Otherwise there is just one result.
2254 /// NodeHasProperty - Return true if this node has the specified property.
2255 bool TreePatternNode::NodeHasProperty(SDNP Property
,
2256 const CodeGenDAGPatterns
&CGP
) const {
2258 if (const ComplexPattern
*CP
= getComplexPatternInfo(CGP
))
2259 return CP
->hasProperty(Property
);
2264 if (Property
!= SDNPHasChain
) {
2265 // The chain proprety is already present on the different intrinsic node
2266 // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
2267 // on the intrinsic. Anything else is specific to the individual intrinsic.
2268 if (const CodeGenIntrinsic
*Int
= getIntrinsicInfo(CGP
))
2269 return Int
->hasProperty(Property
);
2272 if (!Operator
->isSubClassOf("SDPatternOperator"))
2275 return CGP
.getSDNodeInfo(Operator
).hasProperty(Property
);
2281 /// TreeHasProperty - Return true if any node in this tree has the specified
2283 bool TreePatternNode::TreeHasProperty(SDNP Property
,
2284 const CodeGenDAGPatterns
&CGP
) const {
2285 if (NodeHasProperty(Property
, CGP
))
2287 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
2288 if (getChild(i
)->TreeHasProperty(Property
, CGP
))
2293 /// isCommutativeIntrinsic - Return true if the node corresponds to a
2294 /// commutative intrinsic.
2296 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns
&CDP
) const {
2297 if (const CodeGenIntrinsic
*Int
= getIntrinsicInfo(CDP
))
2298 return Int
->isCommutative
;
2302 static bool isOperandClass(const TreePatternNode
*N
, StringRef Class
) {
2304 return N
->getOperator()->isSubClassOf(Class
);
2306 DefInit
*DI
= dyn_cast
<DefInit
>(N
->getLeafValue());
2307 if (DI
&& DI
->getDef()->isSubClassOf(Class
))
2313 static void emitTooManyOperandsError(TreePattern
&TP
,
2317 TP
.error("Instruction '" + InstName
+ "' was provided " + Twine(Actual
) +
2318 " operands but expected only " + Twine(Expected
) + "!");
2321 static void emitTooFewOperandsError(TreePattern
&TP
,
2324 TP
.error("Instruction '" + InstName
+
2325 "' expects more than the provided " + Twine(Actual
) + " operands!");
2328 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
2329 /// this node and its children in the tree. This returns true if it makes a
2330 /// change, false otherwise. If a type contradiction is found, flag an error.
2331 bool TreePatternNode::ApplyTypeConstraints(TreePattern
&TP
, bool NotRegisters
) {
2335 CodeGenDAGPatterns
&CDP
= TP
.getDAGPatterns();
2337 if (DefInit
*DI
= dyn_cast
<DefInit
>(getLeafValue())) {
2338 // If it's a regclass or something else known, include the type.
2339 bool MadeChange
= false;
2340 for (unsigned i
= 0, e
= Types
.size(); i
!= e
; ++i
)
2341 MadeChange
|= UpdateNodeType(i
, getImplicitType(DI
->getDef(), i
,
2343 !hasName(), TP
), TP
);
2347 if (IntInit
*II
= dyn_cast
<IntInit
>(getLeafValue())) {
2348 assert(Types
.size() == 1 && "Invalid IntInit");
2350 // Int inits are always integers. :)
2351 bool MadeChange
= TP
.getInfer().EnforceInteger(Types
[0]);
2353 if (!TP
.getInfer().isConcrete(Types
[0], false))
2356 ValueTypeByHwMode VVT
= TP
.getInfer().getConcrete(Types
[0], false);
2357 for (auto &P
: VVT
) {
2358 MVT::SimpleValueType VT
= P
.second
.SimpleTy
;
2359 if (VT
== MVT::iPTR
|| VT
== MVT::iPTRAny
)
2361 unsigned Size
= MVT(VT
).getSizeInBits();
2362 // Make sure that the value is representable for this type.
2365 // Check that the value doesn't use more bits than we have. It must
2366 // either be a sign- or zero-extended equivalent of the original.
2367 int64_t SignBitAndAbove
= II
->getValue() >> (Size
- 1);
2368 if (SignBitAndAbove
== -1 || SignBitAndAbove
== 0 ||
2369 SignBitAndAbove
== 1)
2372 TP
.error("Integer value '" + Twine(II
->getValue()) +
2373 "' is out of range for type '" + getEnumName(VT
) + "'!");
2382 if (const CodeGenIntrinsic
*Int
= getIntrinsicInfo(CDP
)) {
2383 bool MadeChange
= false;
2385 // Apply the result type to the node.
2386 unsigned NumRetVTs
= Int
->IS
.RetVTs
.size();
2387 unsigned NumParamVTs
= Int
->IS
.ParamVTs
.size();
2389 for (unsigned i
= 0, e
= NumRetVTs
; i
!= e
; ++i
)
2390 MadeChange
|= UpdateNodeType(i
, Int
->IS
.RetVTs
[i
], TP
);
2392 if (getNumChildren() != NumParamVTs
+ 1) {
2393 TP
.error("Intrinsic '" + Int
->Name
+ "' expects " + Twine(NumParamVTs
) +
2394 " operands, not " + Twine(getNumChildren() - 1) + " operands!");
2398 // Apply type info to the intrinsic ID.
2399 MadeChange
|= getChild(0)->UpdateNodeType(0, MVT::iPTR
, TP
);
2401 for (unsigned i
= 0, e
= getNumChildren()-1; i
!= e
; ++i
) {
2402 MadeChange
|= getChild(i
+1)->ApplyTypeConstraints(TP
, NotRegisters
);
2404 MVT::SimpleValueType OpVT
= Int
->IS
.ParamVTs
[i
];
2405 assert(getChild(i
+1)->getNumTypes() == 1 && "Unhandled case");
2406 MadeChange
|= getChild(i
+1)->UpdateNodeType(0, OpVT
, TP
);
2411 if (getOperator()->isSubClassOf("SDNode")) {
2412 const SDNodeInfo
&NI
= CDP
.getSDNodeInfo(getOperator());
2414 // Check that the number of operands is sane. Negative operands -> varargs.
2415 if (NI
.getNumOperands() >= 0 &&
2416 getNumChildren() != (unsigned)NI
.getNumOperands()) {
2417 TP
.error(getOperator()->getName() + " node requires exactly " +
2418 Twine(NI
.getNumOperands()) + " operands!");
2422 bool MadeChange
= false;
2423 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
2424 MadeChange
|= getChild(i
)->ApplyTypeConstraints(TP
, NotRegisters
);
2425 MadeChange
|= NI
.ApplyTypeConstraints(this, TP
);
2429 if (getOperator()->isSubClassOf("Instruction")) {
2430 const DAGInstruction
&Inst
= CDP
.getInstruction(getOperator());
2431 CodeGenInstruction
&InstInfo
=
2432 CDP
.getTargetInfo().getInstruction(getOperator());
2434 bool MadeChange
= false;
2436 // Apply the result types to the node, these come from the things in the
2437 // (outs) list of the instruction.
2438 unsigned NumResultsToAdd
= std::min(InstInfo
.Operands
.NumDefs
,
2439 Inst
.getNumResults());
2440 for (unsigned ResNo
= 0; ResNo
!= NumResultsToAdd
; ++ResNo
)
2441 MadeChange
|= UpdateNodeTypeFromInst(ResNo
, Inst
.getResult(ResNo
), TP
);
2443 // If the instruction has implicit defs, we apply the first one as a result.
2444 // FIXME: This sucks, it should apply all implicit defs.
2445 if (!InstInfo
.ImplicitDefs
.empty()) {
2446 unsigned ResNo
= NumResultsToAdd
;
2448 // FIXME: Generalize to multiple possible types and multiple possible
2450 MVT::SimpleValueType VT
=
2451 InstInfo
.HasOneImplicitDefWithKnownVT(CDP
.getTargetInfo());
2453 if (VT
!= MVT::Other
)
2454 MadeChange
|= UpdateNodeType(ResNo
, VT
, TP
);
2457 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2459 if (getOperator()->getName() == "INSERT_SUBREG") {
2460 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
2461 MadeChange
|= UpdateNodeType(0, getChild(0)->getExtType(0), TP
);
2462 MadeChange
|= getChild(0)->UpdateNodeType(0, getExtType(0), TP
);
2463 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2464 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2467 unsigned NChild
= getNumChildren();
2469 TP
.error("REG_SEQUENCE requires at least 3 operands!");
2473 if (NChild
% 2 == 0) {
2474 TP
.error("REG_SEQUENCE requires an odd number of operands!");
2478 if (!isOperandClass(getChild(0), "RegisterClass")) {
2479 TP
.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2483 for (unsigned I
= 1; I
< NChild
; I
+= 2) {
2484 TreePatternNode
*SubIdxChild
= getChild(I
+ 1);
2485 if (!isOperandClass(SubIdxChild
, "SubRegIndex")) {
2486 TP
.error("REG_SEQUENCE requires a SubRegIndex for operand " +
2487 Twine(I
+ 1) + "!");
2493 // If one or more operands with a default value appear at the end of the
2494 // formal operand list for an instruction, we allow them to be overridden
2495 // by optional operands provided in the pattern.
2497 // But if an operand B without a default appears at any point after an
2498 // operand A with a default, then we don't allow A to be overridden,
2499 // because there would be no way to specify whether the next operand in
2500 // the pattern was intended to override A or skip it.
2501 unsigned NonOverridableOperands
= Inst
.getNumOperands();
2502 while (NonOverridableOperands
> 0 &&
2503 CDP
.operandHasDefault(Inst
.getOperand(NonOverridableOperands
-1)))
2504 --NonOverridableOperands
;
2506 unsigned ChildNo
= 0;
2507 for (unsigned i
= 0, e
= Inst
.getNumOperands(); i
!= e
; ++i
) {
2508 Record
*OperandNode
= Inst
.getOperand(i
);
2510 // If the operand has a default value, do we use it? We must use the
2511 // default if we've run out of children of the pattern DAG to consume,
2512 // or if the operand is followed by a non-defaulted one.
2513 if (CDP
.operandHasDefault(OperandNode
) &&
2514 (i
< NonOverridableOperands
|| ChildNo
>= getNumChildren()))
2517 // If we have run out of child nodes and there _isn't_ a default
2518 // value we can use for the next operand, give an error.
2519 if (ChildNo
>= getNumChildren()) {
2520 emitTooFewOperandsError(TP
, getOperator()->getName(), getNumChildren());
2524 TreePatternNode
*Child
= getChild(ChildNo
++);
2525 unsigned ChildResNo
= 0; // Instructions always use res #0 of their op.
2527 // If the operand has sub-operands, they may be provided by distinct
2528 // child patterns, so attempt to match each sub-operand separately.
2529 if (OperandNode
->isSubClassOf("Operand")) {
2530 DagInit
*MIOpInfo
= OperandNode
->getValueAsDag("MIOperandInfo");
2531 if (unsigned NumArgs
= MIOpInfo
->getNumArgs()) {
2532 // But don't do that if the whole operand is being provided by
2533 // a single ComplexPattern-related Operand.
2535 if (Child
->getNumMIResults(CDP
) < NumArgs
) {
2536 // Match first sub-operand against the child we already have.
2537 Record
*SubRec
= cast
<DefInit
>(MIOpInfo
->getArg(0))->getDef();
2539 Child
->UpdateNodeTypeFromInst(ChildResNo
, SubRec
, TP
);
2541 // And the remaining sub-operands against subsequent children.
2542 for (unsigned Arg
= 1; Arg
< NumArgs
; ++Arg
) {
2543 if (ChildNo
>= getNumChildren()) {
2544 emitTooFewOperandsError(TP
, getOperator()->getName(),
2548 Child
= getChild(ChildNo
++);
2550 SubRec
= cast
<DefInit
>(MIOpInfo
->getArg(Arg
))->getDef();
2552 Child
->UpdateNodeTypeFromInst(ChildResNo
, SubRec
, TP
);
2559 // If we didn't match by pieces above, attempt to match the whole
2561 MadeChange
|= Child
->UpdateNodeTypeFromInst(ChildResNo
, OperandNode
, TP
);
2564 if (!InstInfo
.Operands
.isVariadic
&& ChildNo
!= getNumChildren()) {
2565 emitTooManyOperandsError(TP
, getOperator()->getName(),
2566 ChildNo
, getNumChildren());
2570 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
2571 MadeChange
|= getChild(i
)->ApplyTypeConstraints(TP
, NotRegisters
);
2575 if (getOperator()->isSubClassOf("ComplexPattern")) {
2576 bool MadeChange
= false;
2578 for (unsigned i
= 0; i
< getNumChildren(); ++i
)
2579 MadeChange
|= getChild(i
)->ApplyTypeConstraints(TP
, NotRegisters
);
2584 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
2586 // Node transforms always take one operand.
2587 if (getNumChildren() != 1) {
2588 TP
.error("Node transform '" + getOperator()->getName() +
2589 "' requires one operand!");
2593 bool MadeChange
= getChild(0)->ApplyTypeConstraints(TP
, NotRegisters
);
2597 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2598 /// RHS of a commutative operation, not the on LHS.
2599 static bool OnlyOnRHSOfCommutative(TreePatternNode
*N
) {
2600 if (!N
->isLeaf() && N
->getOperator()->getName() == "imm")
2602 if (N
->isLeaf() && isa
<IntInit
>(N
->getLeafValue()))
2608 /// canPatternMatch - If it is impossible for this pattern to match on this
2609 /// target, fill in Reason and return false. Otherwise, return true. This is
2610 /// used as a sanity check for .td files (to prevent people from writing stuff
2611 /// that can never possibly work), and to prevent the pattern permuter from
2612 /// generating stuff that is useless.
2613 bool TreePatternNode::canPatternMatch(std::string
&Reason
,
2614 const CodeGenDAGPatterns
&CDP
) {
2615 if (isLeaf()) return true;
2617 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
2618 if (!getChild(i
)->canPatternMatch(Reason
, CDP
))
2621 // If this is an intrinsic, handle cases that would make it not match. For
2622 // example, if an operand is required to be an immediate.
2623 if (getOperator()->isSubClassOf("Intrinsic")) {
2628 if (getOperator()->isSubClassOf("ComplexPattern"))
2631 // If this node is a commutative operator, check that the LHS isn't an
2633 const SDNodeInfo
&NodeInfo
= CDP
.getSDNodeInfo(getOperator());
2634 bool isCommIntrinsic
= isCommutativeIntrinsic(CDP
);
2635 if (NodeInfo
.hasProperty(SDNPCommutative
) || isCommIntrinsic
) {
2636 // Scan all of the operands of the node and make sure that only the last one
2637 // is a constant node, unless the RHS also is.
2638 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
2639 unsigned Skip
= isCommIntrinsic
? 1 : 0; // First operand is intrinsic id.
2640 for (unsigned i
= Skip
, e
= getNumChildren()-1; i
!= e
; ++i
)
2641 if (OnlyOnRHSOfCommutative(getChild(i
))) {
2642 Reason
="Immediate value must be on the RHS of commutative operators!";
2651 //===----------------------------------------------------------------------===//
2652 // TreePattern implementation
2655 TreePattern::TreePattern(Record
*TheRec
, ListInit
*RawPat
, bool isInput
,
2656 CodeGenDAGPatterns
&cdp
) : TheRecord(TheRec
), CDP(cdp
),
2657 isInputPattern(isInput
), HasError(false),
2659 for (Init
*I
: RawPat
->getValues())
2660 Trees
.push_back(ParseTreePattern(I
, ""));
2663 TreePattern::TreePattern(Record
*TheRec
, DagInit
*Pat
, bool isInput
,
2664 CodeGenDAGPatterns
&cdp
) : TheRecord(TheRec
), CDP(cdp
),
2665 isInputPattern(isInput
), HasError(false),
2667 Trees
.push_back(ParseTreePattern(Pat
, ""));
2670 TreePattern::TreePattern(Record
*TheRec
, TreePatternNodePtr Pat
, bool isInput
,
2671 CodeGenDAGPatterns
&cdp
)
2672 : TheRecord(TheRec
), CDP(cdp
), isInputPattern(isInput
), HasError(false),
2674 Trees
.push_back(Pat
);
2677 void TreePattern::error(const Twine
&Msg
) {
2681 PrintError(TheRecord
->getLoc(), "In " + TheRecord
->getName() + ": " + Msg
);
2685 void TreePattern::ComputeNamedNodes() {
2686 for (TreePatternNodePtr
&Tree
: Trees
)
2687 ComputeNamedNodes(Tree
.get());
2690 void TreePattern::ComputeNamedNodes(TreePatternNode
*N
) {
2691 if (!N
->getName().empty())
2692 NamedNodes
[N
->getName()].push_back(N
);
2694 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
)
2695 ComputeNamedNodes(N
->getChild(i
));
2698 TreePatternNodePtr
TreePattern::ParseTreePattern(Init
*TheInit
,
2700 if (DefInit
*DI
= dyn_cast
<DefInit
>(TheInit
)) {
2701 Record
*R
= DI
->getDef();
2703 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
2704 // TreePatternNode of its own. For example:
2705 /// (foo GPR, imm) -> (foo GPR, (imm))
2706 if (R
->isSubClassOf("SDNode") || R
->isSubClassOf("PatFrags"))
2707 return ParseTreePattern(
2708 DagInit::get(DI
, nullptr,
2709 std::vector
<std::pair
<Init
*, StringInit
*> >()),
2713 TreePatternNodePtr Res
= std::make_shared
<TreePatternNode
>(DI
, 1);
2714 if (R
->getName() == "node" && !OpName
.empty()) {
2716 error("'node' argument requires a name to match with operand list");
2717 Args
.push_back(OpName
);
2720 Res
->setName(OpName
);
2724 // ?:$name or just $name.
2725 if (isa
<UnsetInit
>(TheInit
)) {
2727 error("'?' argument requires a name to match with operand list");
2728 TreePatternNodePtr Res
= std::make_shared
<TreePatternNode
>(TheInit
, 1);
2729 Args
.push_back(OpName
);
2730 Res
->setName(OpName
);
2734 if (isa
<IntInit
>(TheInit
) || isa
<BitInit
>(TheInit
)) {
2735 if (!OpName
.empty())
2736 error("Constant int or bit argument should not have a name!");
2737 if (isa
<BitInit
>(TheInit
))
2738 TheInit
= TheInit
->convertInitializerTo(IntRecTy::get());
2739 return std::make_shared
<TreePatternNode
>(TheInit
, 1);
2742 if (BitsInit
*BI
= dyn_cast
<BitsInit
>(TheInit
)) {
2743 // Turn this into an IntInit.
2744 Init
*II
= BI
->convertInitializerTo(IntRecTy::get());
2745 if (!II
|| !isa
<IntInit
>(II
))
2746 error("Bits value must be constants!");
2747 return ParseTreePattern(II
, OpName
);
2750 DagInit
*Dag
= dyn_cast
<DagInit
>(TheInit
);
2752 TheInit
->print(errs());
2753 error("Pattern has unexpected init kind!");
2755 DefInit
*OpDef
= dyn_cast
<DefInit
>(Dag
->getOperator());
2756 if (!OpDef
) error("Pattern has unexpected operator type!");
2757 Record
*Operator
= OpDef
->getDef();
2759 if (Operator
->isSubClassOf("ValueType")) {
2760 // If the operator is a ValueType, then this must be "type cast" of a leaf
2762 if (Dag
->getNumArgs() != 1)
2763 error("Type cast only takes one operand!");
2765 TreePatternNodePtr New
=
2766 ParseTreePattern(Dag
->getArg(0), Dag
->getArgNameStr(0));
2768 // Apply the type cast.
2769 assert(New
->getNumTypes() == 1 && "FIXME: Unhandled");
2770 const CodeGenHwModes
&CGH
= getDAGPatterns().getTargetInfo().getHwModes();
2771 New
->UpdateNodeType(0, getValueTypeByHwMode(Operator
, CGH
), *this);
2773 if (!OpName
.empty())
2774 error("ValueType cast should not have a name!");
2778 // Verify that this is something that makes sense for an operator.
2779 if (!Operator
->isSubClassOf("PatFrags") &&
2780 !Operator
->isSubClassOf("SDNode") &&
2781 !Operator
->isSubClassOf("Instruction") &&
2782 !Operator
->isSubClassOf("SDNodeXForm") &&
2783 !Operator
->isSubClassOf("Intrinsic") &&
2784 !Operator
->isSubClassOf("ComplexPattern") &&
2785 Operator
->getName() != "set" &&
2786 Operator
->getName() != "implicit")
2787 error("Unrecognized node '" + Operator
->getName() + "'!");
2789 // Check to see if this is something that is illegal in an input pattern.
2790 if (isInputPattern
) {
2791 if (Operator
->isSubClassOf("Instruction") ||
2792 Operator
->isSubClassOf("SDNodeXForm"))
2793 error("Cannot use '" + Operator
->getName() + "' in an input pattern!");
2795 if (Operator
->isSubClassOf("Intrinsic"))
2796 error("Cannot use '" + Operator
->getName() + "' in an output pattern!");
2798 if (Operator
->isSubClassOf("SDNode") &&
2799 Operator
->getName() != "imm" &&
2800 Operator
->getName() != "fpimm" &&
2801 Operator
->getName() != "tglobaltlsaddr" &&
2802 Operator
->getName() != "tconstpool" &&
2803 Operator
->getName() != "tjumptable" &&
2804 Operator
->getName() != "tframeindex" &&
2805 Operator
->getName() != "texternalsym" &&
2806 Operator
->getName() != "tblockaddress" &&
2807 Operator
->getName() != "tglobaladdr" &&
2808 Operator
->getName() != "bb" &&
2809 Operator
->getName() != "vt" &&
2810 Operator
->getName() != "mcsym")
2811 error("Cannot use '" + Operator
->getName() + "' in an output pattern!");
2814 std::vector
<TreePatternNodePtr
> Children
;
2816 // Parse all the operands.
2817 for (unsigned i
= 0, e
= Dag
->getNumArgs(); i
!= e
; ++i
)
2818 Children
.push_back(ParseTreePattern(Dag
->getArg(i
), Dag
->getArgNameStr(i
)));
2820 // Get the actual number of results before Operator is converted to an intrinsic
2821 // node (which is hard-coded to have either zero or one result).
2822 unsigned NumResults
= GetNumNodeResults(Operator
, CDP
);
2824 // If the operator is an intrinsic, then this is just syntactic sugar for
2825 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
2826 // convert the intrinsic name to a number.
2827 if (Operator
->isSubClassOf("Intrinsic")) {
2828 const CodeGenIntrinsic
&Int
= getDAGPatterns().getIntrinsic(Operator
);
2829 unsigned IID
= getDAGPatterns().getIntrinsicID(Operator
)+1;
2831 // If this intrinsic returns void, it must have side-effects and thus a
2833 if (Int
.IS
.RetVTs
.empty())
2834 Operator
= getDAGPatterns().get_intrinsic_void_sdnode();
2835 else if (Int
.ModRef
!= CodeGenIntrinsic::NoMem
|| Int
.hasSideEffects
)
2836 // Has side-effects, requires chain.
2837 Operator
= getDAGPatterns().get_intrinsic_w_chain_sdnode();
2838 else // Otherwise, no chain.
2839 Operator
= getDAGPatterns().get_intrinsic_wo_chain_sdnode();
2841 Children
.insert(Children
.begin(),
2842 std::make_shared
<TreePatternNode
>(IntInit::get(IID
), 1));
2845 if (Operator
->isSubClassOf("ComplexPattern")) {
2846 for (unsigned i
= 0; i
< Children
.size(); ++i
) {
2847 TreePatternNodePtr Child
= Children
[i
];
2849 if (Child
->getName().empty())
2850 error("All arguments to a ComplexPattern must be named");
2852 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2853 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2854 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2855 auto OperandId
= std::make_pair(Operator
, i
);
2856 auto PrevOp
= ComplexPatternOperands
.find(Child
->getName());
2857 if (PrevOp
!= ComplexPatternOperands
.end()) {
2858 if (PrevOp
->getValue() != OperandId
)
2859 error("All ComplexPattern operands must appear consistently: "
2860 "in the same order in just one ComplexPattern instance.");
2862 ComplexPatternOperands
[Child
->getName()] = OperandId
;
2866 TreePatternNodePtr Result
=
2867 std::make_shared
<TreePatternNode
>(Operator
, std::move(Children
),
2869 Result
->setName(OpName
);
2871 if (Dag
->getName()) {
2872 assert(Result
->getName().empty());
2873 Result
->setName(Dag
->getNameStr());
2878 /// SimplifyTree - See if we can simplify this tree to eliminate something that
2879 /// will never match in favor of something obvious that will. This is here
2880 /// strictly as a convenience to target authors because it allows them to write
2881 /// more type generic things and have useless type casts fold away.
2883 /// This returns true if any change is made.
2884 static bool SimplifyTree(TreePatternNodePtr
&N
) {
2888 // If we have a bitconvert with a resolved type and if the source and
2889 // destination types are the same, then the bitconvert is useless, remove it.
2890 if (N
->getOperator()->getName() == "bitconvert" &&
2891 N
->getExtType(0).isValueTypeByHwMode(false) &&
2892 N
->getExtType(0) == N
->getChild(0)->getExtType(0) &&
2893 N
->getName().empty()) {
2894 N
= N
->getChildShared(0);
2899 // Walk all children.
2900 bool MadeChange
= false;
2901 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
) {
2902 TreePatternNodePtr Child
= N
->getChildShared(i
);
2903 MadeChange
|= SimplifyTree(Child
);
2904 N
->setChild(i
, std::move(Child
));
2911 /// InferAllTypes - Infer/propagate as many types throughout the expression
2912 /// patterns as possible. Return true if all types are inferred, false
2913 /// otherwise. Flags an error if a type contradiction is found.
2915 InferAllTypes(const StringMap
<SmallVector
<TreePatternNode
*,1> > *InNamedTypes
) {
2916 if (NamedNodes
.empty())
2917 ComputeNamedNodes();
2919 bool MadeChange
= true;
2920 while (MadeChange
) {
2922 for (TreePatternNodePtr
&Tree
: Trees
) {
2923 MadeChange
|= Tree
->ApplyTypeConstraints(*this, false);
2924 MadeChange
|= SimplifyTree(Tree
);
2927 // If there are constraints on our named nodes, apply them.
2928 for (auto &Entry
: NamedNodes
) {
2929 SmallVectorImpl
<TreePatternNode
*> &Nodes
= Entry
.second
;
2931 // If we have input named node types, propagate their types to the named
2934 if (!InNamedTypes
->count(Entry
.getKey())) {
2935 error("Node '" + std::string(Entry
.getKey()) +
2936 "' in output pattern but not input pattern");
2940 const SmallVectorImpl
<TreePatternNode
*> &InNodes
=
2941 InNamedTypes
->find(Entry
.getKey())->second
;
2943 // The input types should be fully resolved by now.
2944 for (TreePatternNode
*Node
: Nodes
) {
2945 // If this node is a register class, and it is the root of the pattern
2946 // then we're mapping something onto an input register. We allow
2947 // changing the type of the input register in this case. This allows
2948 // us to match things like:
2949 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2950 if (Node
== Trees
[0].get() && Node
->isLeaf()) {
2951 DefInit
*DI
= dyn_cast
<DefInit
>(Node
->getLeafValue());
2952 if (DI
&& (DI
->getDef()->isSubClassOf("RegisterClass") ||
2953 DI
->getDef()->isSubClassOf("RegisterOperand")))
2957 assert(Node
->getNumTypes() == 1 &&
2958 InNodes
[0]->getNumTypes() == 1 &&
2959 "FIXME: cannot name multiple result nodes yet");
2960 MadeChange
|= Node
->UpdateNodeType(0, InNodes
[0]->getExtType(0),
2965 // If there are multiple nodes with the same name, they must all have the
2967 if (Entry
.second
.size() > 1) {
2968 for (unsigned i
= 0, e
= Nodes
.size()-1; i
!= e
; ++i
) {
2969 TreePatternNode
*N1
= Nodes
[i
], *N2
= Nodes
[i
+1];
2970 assert(N1
->getNumTypes() == 1 && N2
->getNumTypes() == 1 &&
2971 "FIXME: cannot name multiple result nodes yet");
2973 MadeChange
|= N1
->UpdateNodeType(0, N2
->getExtType(0), *this);
2974 MadeChange
|= N2
->UpdateNodeType(0, N1
->getExtType(0), *this);
2980 bool HasUnresolvedTypes
= false;
2981 for (const TreePatternNodePtr
&Tree
: Trees
)
2982 HasUnresolvedTypes
|= Tree
->ContainsUnresolvedType(*this);
2983 return !HasUnresolvedTypes
;
2986 void TreePattern::print(raw_ostream
&OS
) const {
2987 OS
<< getRecord()->getName();
2988 if (!Args
.empty()) {
2989 OS
<< "(" << Args
[0];
2990 for (unsigned i
= 1, e
= Args
.size(); i
!= e
; ++i
)
2991 OS
<< ", " << Args
[i
];
2996 if (Trees
.size() > 1)
2998 for (const TreePatternNodePtr
&Tree
: Trees
) {
3004 if (Trees
.size() > 1)
3008 void TreePattern::dump() const { print(errs()); }
3010 //===----------------------------------------------------------------------===//
3011 // CodeGenDAGPatterns implementation
3014 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper
&R
,
3015 PatternRewriterFn PatternRewriter
)
3016 : Records(R
), Target(R
), LegalVTS(Target
.getLegalValueTypes()),
3017 PatternRewriter(PatternRewriter
) {
3019 Intrinsics
= CodeGenIntrinsicTable(Records
, false);
3020 TgtIntrinsics
= CodeGenIntrinsicTable(Records
, true);
3022 ParseNodeTransforms();
3023 ParseComplexPatterns();
3024 ParsePatternFragments();
3025 ParseDefaultOperands();
3026 ParseInstructions();
3027 ParsePatternFragments(/*OutFrags*/true);
3030 // Break patterns with parameterized types into a series of patterns,
3031 // where each one has a fixed type and is predicated on the conditions
3032 // of the associated HW mode.
3033 ExpandHwModeBasedTypes();
3035 // Generate variants. For example, commutative patterns can match
3036 // multiple ways. Add them to PatternsToMatch as well.
3039 // Infer instruction flags. For example, we can detect loads,
3040 // stores, and side effects in many cases by examining an
3041 // instruction's pattern.
3042 InferInstructionFlags();
3044 // Verify that instruction flags match the patterns.
3045 VerifyInstructionFlags();
3048 Record
*CodeGenDAGPatterns::getSDNodeNamed(const std::string
&Name
) const {
3049 Record
*N
= Records
.getDef(Name
);
3050 if (!N
|| !N
->isSubClassOf("SDNode"))
3051 PrintFatalError("Error getting SDNode '" + Name
+ "'!");
3056 // Parse all of the SDNode definitions for the target, populating SDNodes.
3057 void CodeGenDAGPatterns::ParseNodeInfo() {
3058 std::vector
<Record
*> Nodes
= Records
.getAllDerivedDefinitions("SDNode");
3059 const CodeGenHwModes
&CGH
= getTargetInfo().getHwModes();
3061 while (!Nodes
.empty()) {
3062 Record
*R
= Nodes
.back();
3063 SDNodes
.insert(std::make_pair(R
, SDNodeInfo(R
, CGH
)));
3067 // Get the builtin intrinsic nodes.
3068 intrinsic_void_sdnode
= getSDNodeNamed("intrinsic_void");
3069 intrinsic_w_chain_sdnode
= getSDNodeNamed("intrinsic_w_chain");
3070 intrinsic_wo_chain_sdnode
= getSDNodeNamed("intrinsic_wo_chain");
3073 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
3074 /// map, and emit them to the file as functions.
3075 void CodeGenDAGPatterns::ParseNodeTransforms() {
3076 std::vector
<Record
*> Xforms
= Records
.getAllDerivedDefinitions("SDNodeXForm");
3077 while (!Xforms
.empty()) {
3078 Record
*XFormNode
= Xforms
.back();
3079 Record
*SDNode
= XFormNode
->getValueAsDef("Opcode");
3080 StringRef Code
= XFormNode
->getValueAsString("XFormFunction");
3081 SDNodeXForms
.insert(std::make_pair(XFormNode
, NodeXForm(SDNode
, Code
)));
3087 void CodeGenDAGPatterns::ParseComplexPatterns() {
3088 std::vector
<Record
*> AMs
= Records
.getAllDerivedDefinitions("ComplexPattern");
3089 while (!AMs
.empty()) {
3090 ComplexPatterns
.insert(std::make_pair(AMs
.back(), AMs
.back()));
3096 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
3097 /// file, building up the PatternFragments map. After we've collected them all,
3098 /// inline fragments together as necessary, so that there are no references left
3099 /// inside a pattern fragment to a pattern fragment.
3101 void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags
) {
3102 std::vector
<Record
*> Fragments
= Records
.getAllDerivedDefinitions("PatFrags");
3104 // First step, parse all of the fragments.
3105 for (Record
*Frag
: Fragments
) {
3106 if (OutFrags
!= Frag
->isSubClassOf("OutPatFrag"))
3109 ListInit
*LI
= Frag
->getValueAsListInit("Fragments");
3111 (PatternFragments
[Frag
] = std::make_unique
<TreePattern
>(
3112 Frag
, LI
, !Frag
->isSubClassOf("OutPatFrag"),
3115 // Validate the argument list, converting it to set, to discard duplicates.
3116 std::vector
<std::string
> &Args
= P
->getArgList();
3117 // Copy the args so we can take StringRefs to them.
3118 auto ArgsCopy
= Args
;
3119 SmallDenseSet
<StringRef
, 4> OperandsSet
;
3120 OperandsSet
.insert(ArgsCopy
.begin(), ArgsCopy
.end());
3122 if (OperandsSet
.count(""))
3123 P
->error("Cannot have unnamed 'node' values in pattern fragment!");
3125 // Parse the operands list.
3126 DagInit
*OpsList
= Frag
->getValueAsDag("Operands");
3127 DefInit
*OpsOp
= dyn_cast
<DefInit
>(OpsList
->getOperator());
3128 // Special cases: ops == outs == ins. Different names are used to
3129 // improve readability.
3131 (OpsOp
->getDef()->getName() != "ops" &&
3132 OpsOp
->getDef()->getName() != "outs" &&
3133 OpsOp
->getDef()->getName() != "ins"))
3134 P
->error("Operands list should start with '(ops ... '!");
3136 // Copy over the arguments.
3138 for (unsigned j
= 0, e
= OpsList
->getNumArgs(); j
!= e
; ++j
) {
3139 if (!isa
<DefInit
>(OpsList
->getArg(j
)) ||
3140 cast
<DefInit
>(OpsList
->getArg(j
))->getDef()->getName() != "node")
3141 P
->error("Operands list should all be 'node' values.");
3142 if (!OpsList
->getArgName(j
))
3143 P
->error("Operands list should have names for each operand!");
3144 StringRef ArgNameStr
= OpsList
->getArgNameStr(j
);
3145 if (!OperandsSet
.count(ArgNameStr
))
3146 P
->error("'" + ArgNameStr
+
3147 "' does not occur in pattern or was multiply specified!");
3148 OperandsSet
.erase(ArgNameStr
);
3149 Args
.push_back(ArgNameStr
);
3152 if (!OperandsSet
.empty())
3153 P
->error("Operands list does not contain an entry for operand '" +
3154 *OperandsSet
.begin() + "'!");
3156 // If there is a node transformation corresponding to this, keep track of
3158 Record
*Transform
= Frag
->getValueAsDef("OperandTransform");
3159 if (!getSDNodeTransform(Transform
).second
.empty()) // not noop xform?
3160 for (auto T
: P
->getTrees())
3161 T
->setTransformFn(Transform
);
3164 // Now that we've parsed all of the tree fragments, do a closure on them so
3165 // that there are not references to PatFrags left inside of them.
3166 for (Record
*Frag
: Fragments
) {
3167 if (OutFrags
!= Frag
->isSubClassOf("OutPatFrag"))
3170 TreePattern
&ThePat
= *PatternFragments
[Frag
];
3171 ThePat
.InlinePatternFragments();
3173 // Infer as many types as possible. Don't worry about it if we don't infer
3174 // all of them, some may depend on the inputs of the pattern. Also, don't
3175 // validate type sets; validation may cause spurious failures e.g. if a
3176 // fragment needs floating-point types but the current target does not have
3177 // any (this is only an error if that fragment is ever used!).
3179 TypeInfer::SuppressValidation
SV(ThePat
.getInfer());
3180 ThePat
.InferAllTypes();
3181 ThePat
.resetError();
3184 // If debugging, print out the pattern fragment result.
3185 LLVM_DEBUG(ThePat
.dump());
3189 void CodeGenDAGPatterns::ParseDefaultOperands() {
3190 std::vector
<Record
*> DefaultOps
;
3191 DefaultOps
= Records
.getAllDerivedDefinitions("OperandWithDefaultOps");
3193 // Find some SDNode.
3194 assert(!SDNodes
.empty() && "No SDNodes parsed?");
3195 Init
*SomeSDNode
= DefInit::get(SDNodes
.begin()->first
);
3197 for (unsigned i
= 0, e
= DefaultOps
.size(); i
!= e
; ++i
) {
3198 DagInit
*DefaultInfo
= DefaultOps
[i
]->getValueAsDag("DefaultOps");
3200 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
3201 // SomeSDnode so that we can parse this.
3202 std::vector
<std::pair
<Init
*, StringInit
*> > Ops
;
3203 for (unsigned op
= 0, e
= DefaultInfo
->getNumArgs(); op
!= e
; ++op
)
3204 Ops
.push_back(std::make_pair(DefaultInfo
->getArg(op
),
3205 DefaultInfo
->getArgName(op
)));
3206 DagInit
*DI
= DagInit::get(SomeSDNode
, nullptr, Ops
);
3208 // Create a TreePattern to parse this.
3209 TreePattern
P(DefaultOps
[i
], DI
, false, *this);
3210 assert(P
.getNumTrees() == 1 && "This ctor can only produce one tree!");
3212 // Copy the operands over into a DAGDefaultOperand.
3213 DAGDefaultOperand DefaultOpInfo
;
3215 const TreePatternNodePtr
&T
= P
.getTree(0);
3216 for (unsigned op
= 0, e
= T
->getNumChildren(); op
!= e
; ++op
) {
3217 TreePatternNodePtr TPN
= T
->getChildShared(op
);
3218 while (TPN
->ApplyTypeConstraints(P
, false))
3219 /* Resolve all types */;
3221 if (TPN
->ContainsUnresolvedType(P
)) {
3222 PrintFatalError("Value #" + Twine(i
) + " of OperandWithDefaultOps '" +
3223 DefaultOps
[i
]->getName() +
3224 "' doesn't have a concrete type!");
3226 DefaultOpInfo
.DefaultOps
.push_back(std::move(TPN
));
3229 // Insert it into the DefaultOperands map so we can find it later.
3230 DefaultOperands
[DefaultOps
[i
]] = DefaultOpInfo
;
3234 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3235 /// instruction input. Return true if this is a real use.
3236 static bool HandleUse(TreePattern
&I
, TreePatternNodePtr Pat
,
3237 std::map
<std::string
, TreePatternNodePtr
> &InstInputs
) {
3238 // No name -> not interesting.
3239 if (Pat
->getName().empty()) {
3240 if (Pat
->isLeaf()) {
3241 DefInit
*DI
= dyn_cast
<DefInit
>(Pat
->getLeafValue());
3242 if (DI
&& (DI
->getDef()->isSubClassOf("RegisterClass") ||
3243 DI
->getDef()->isSubClassOf("RegisterOperand")))
3244 I
.error("Input " + DI
->getDef()->getName() + " must be named!");
3250 if (Pat
->isLeaf()) {
3251 DefInit
*DI
= dyn_cast
<DefInit
>(Pat
->getLeafValue());
3253 I
.error("Input $" + Pat
->getName() + " must be an identifier!");
3256 Rec
= Pat
->getOperator();
3259 // SRCVALUE nodes are ignored.
3260 if (Rec
->getName() == "srcvalue")
3263 TreePatternNodePtr
&Slot
= InstInputs
[Pat
->getName()];
3269 if (Slot
->isLeaf()) {
3270 SlotRec
= cast
<DefInit
>(Slot
->getLeafValue())->getDef();
3272 assert(Slot
->getNumChildren() == 0 && "can't be a use with children!");
3273 SlotRec
= Slot
->getOperator();
3276 // Ensure that the inputs agree if we've already seen this input.
3278 I
.error("All $" + Pat
->getName() + " inputs must agree with each other");
3279 // Ensure that the types can agree as well.
3280 Slot
->UpdateNodeType(0, Pat
->getExtType(0), I
);
3281 Pat
->UpdateNodeType(0, Slot
->getExtType(0), I
);
3282 if (Slot
->getExtTypes() != Pat
->getExtTypes())
3283 I
.error("All $" + Pat
->getName() + " inputs must agree with each other");
3287 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3288 /// part of "I", the instruction), computing the set of inputs and outputs of
3289 /// the pattern. Report errors if we see anything naughty.
3290 void CodeGenDAGPatterns::FindPatternInputsAndOutputs(
3291 TreePattern
&I
, TreePatternNodePtr Pat
,
3292 std::map
<std::string
, TreePatternNodePtr
> &InstInputs
,
3293 MapVector
<std::string
, TreePatternNodePtr
, std::map
<std::string
, unsigned>>
3295 std::vector
<Record
*> &InstImpResults
) {
3297 // The instruction pattern still has unresolved fragments. For *named*
3298 // nodes we must resolve those here. This may not result in multiple
3300 if (!Pat
->getName().empty()) {
3301 TreePattern
SrcPattern(I
.getRecord(), Pat
, true, *this);
3302 SrcPattern
.InlinePatternFragments();
3303 SrcPattern
.InferAllTypes();
3304 Pat
= SrcPattern
.getOnlyTree();
3307 if (Pat
->isLeaf()) {
3308 bool isUse
= HandleUse(I
, Pat
, InstInputs
);
3309 if (!isUse
&& Pat
->getTransformFn())
3310 I
.error("Cannot specify a transform function for a non-input value!");
3314 if (Pat
->getOperator()->getName() == "implicit") {
3315 for (unsigned i
= 0, e
= Pat
->getNumChildren(); i
!= e
; ++i
) {
3316 TreePatternNode
*Dest
= Pat
->getChild(i
);
3317 if (!Dest
->isLeaf())
3318 I
.error("implicitly defined value should be a register!");
3320 DefInit
*Val
= dyn_cast
<DefInit
>(Dest
->getLeafValue());
3321 if (!Val
|| !Val
->getDef()->isSubClassOf("Register"))
3322 I
.error("implicitly defined value should be a register!");
3323 InstImpResults
.push_back(Val
->getDef());
3328 if (Pat
->getOperator()->getName() != "set") {
3329 // If this is not a set, verify that the children nodes are not void typed,
3331 for (unsigned i
= 0, e
= Pat
->getNumChildren(); i
!= e
; ++i
) {
3332 if (Pat
->getChild(i
)->getNumTypes() == 0)
3333 I
.error("Cannot have void nodes inside of patterns!");
3334 FindPatternInputsAndOutputs(I
, Pat
->getChildShared(i
), InstInputs
,
3335 InstResults
, InstImpResults
);
3338 // If this is a non-leaf node with no children, treat it basically as if
3339 // it were a leaf. This handles nodes like (imm).
3340 bool isUse
= HandleUse(I
, Pat
, InstInputs
);
3342 if (!isUse
&& Pat
->getTransformFn())
3343 I
.error("Cannot specify a transform function for a non-input value!");
3347 // Otherwise, this is a set, validate and collect instruction results.
3348 if (Pat
->getNumChildren() == 0)
3349 I
.error("set requires operands!");
3351 if (Pat
->getTransformFn())
3352 I
.error("Cannot specify a transform function on a set node!");
3354 // Check the set destinations.
3355 unsigned NumDests
= Pat
->getNumChildren()-1;
3356 for (unsigned i
= 0; i
!= NumDests
; ++i
) {
3357 TreePatternNodePtr Dest
= Pat
->getChildShared(i
);
3358 // For set destinations we also must resolve fragments here.
3359 TreePattern
DestPattern(I
.getRecord(), Dest
, false, *this);
3360 DestPattern
.InlinePatternFragments();
3361 DestPattern
.InferAllTypes();
3362 Dest
= DestPattern
.getOnlyTree();
3364 if (!Dest
->isLeaf())
3365 I
.error("set destination should be a register!");
3367 DefInit
*Val
= dyn_cast
<DefInit
>(Dest
->getLeafValue());
3369 I
.error("set destination should be a register!");
3373 if (Val
->getDef()->isSubClassOf("RegisterClass") ||
3374 Val
->getDef()->isSubClassOf("ValueType") ||
3375 Val
->getDef()->isSubClassOf("RegisterOperand") ||
3376 Val
->getDef()->isSubClassOf("PointerLikeRegClass")) {
3377 if (Dest
->getName().empty())
3378 I
.error("set destination must have a name!");
3379 if (InstResults
.count(Dest
->getName()))
3380 I
.error("cannot set '" + Dest
->getName() + "' multiple times");
3381 InstResults
[Dest
->getName()] = Dest
;
3382 } else if (Val
->getDef()->isSubClassOf("Register")) {
3383 InstImpResults
.push_back(Val
->getDef());
3385 I
.error("set destination should be a register!");
3389 // Verify and collect info from the computation.
3390 FindPatternInputsAndOutputs(I
, Pat
->getChildShared(NumDests
), InstInputs
,
3391 InstResults
, InstImpResults
);
3394 //===----------------------------------------------------------------------===//
3395 // Instruction Analysis
3396 //===----------------------------------------------------------------------===//
3398 class InstAnalyzer
{
3399 const CodeGenDAGPatterns
&CDP
;
3401 bool hasSideEffects
;
3408 InstAnalyzer(const CodeGenDAGPatterns
&cdp
)
3409 : CDP(cdp
), hasSideEffects(false), mayStore(false), mayLoad(false),
3410 isBitcast(false), isVariadic(false), hasChain(false) {}
3412 void Analyze(const PatternToMatch
&Pat
) {
3413 const TreePatternNode
*N
= Pat
.getSrcPattern();
3415 // These properties are detected only on the root node.
3416 isBitcast
= IsNodeBitcast(N
);
3420 bool IsNodeBitcast(const TreePatternNode
*N
) const {
3421 if (hasSideEffects
|| mayLoad
|| mayStore
|| isVariadic
)
3426 if (N
->getNumChildren() != 1 || !N
->getChild(0)->isLeaf())
3429 const SDNodeInfo
&OpInfo
= CDP
.getSDNodeInfo(N
->getOperator());
3430 if (OpInfo
.getNumResults() != 1 || OpInfo
.getNumOperands() != 1)
3432 return OpInfo
.getEnumName() == "ISD::BITCAST";
3436 void AnalyzeNode(const TreePatternNode
*N
) {
3438 if (DefInit
*DI
= dyn_cast
<DefInit
>(N
->getLeafValue())) {
3439 Record
*LeafRec
= DI
->getDef();
3440 // Handle ComplexPattern leaves.
3441 if (LeafRec
->isSubClassOf("ComplexPattern")) {
3442 const ComplexPattern
&CP
= CDP
.getComplexPattern(LeafRec
);
3443 if (CP
.hasProperty(SDNPMayStore
)) mayStore
= true;
3444 if (CP
.hasProperty(SDNPMayLoad
)) mayLoad
= true;
3445 if (CP
.hasProperty(SDNPSideEffect
)) hasSideEffects
= true;
3451 // Analyze children.
3452 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
)
3453 AnalyzeNode(N
->getChild(i
));
3455 // Notice properties of the node.
3456 if (N
->NodeHasProperty(SDNPMayStore
, CDP
)) mayStore
= true;
3457 if (N
->NodeHasProperty(SDNPMayLoad
, CDP
)) mayLoad
= true;
3458 if (N
->NodeHasProperty(SDNPSideEffect
, CDP
)) hasSideEffects
= true;
3459 if (N
->NodeHasProperty(SDNPVariadic
, CDP
)) isVariadic
= true;
3460 if (N
->NodeHasProperty(SDNPHasChain
, CDP
)) hasChain
= true;
3462 if (const CodeGenIntrinsic
*IntInfo
= N
->getIntrinsicInfo(CDP
)) {
3463 // If this is an intrinsic, analyze it.
3464 if (IntInfo
->ModRef
& CodeGenIntrinsic::MR_Ref
)
3465 mayLoad
= true;// These may load memory.
3467 if (IntInfo
->ModRef
& CodeGenIntrinsic::MR_Mod
)
3468 mayStore
= true;// Intrinsics that can write to memory are 'mayStore'.
3470 if (IntInfo
->ModRef
>= CodeGenIntrinsic::ReadWriteMem
||
3471 IntInfo
->hasSideEffects
)
3472 // ReadWriteMem intrinsics can have other strange effects.
3473 hasSideEffects
= true;
3479 static bool InferFromPattern(CodeGenInstruction
&InstInfo
,
3480 const InstAnalyzer
&PatInfo
,
3484 // Remember where InstInfo got its flags.
3485 if (InstInfo
.hasUndefFlags())
3486 InstInfo
.InferredFrom
= PatDef
;
3488 // Check explicitly set flags for consistency.
3489 if (InstInfo
.hasSideEffects
!= PatInfo
.hasSideEffects
&&
3490 !InstInfo
.hasSideEffects_Unset
) {
3491 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3492 // the pattern has no side effects. That could be useful for div/rem
3493 // instructions that may trap.
3494 if (!InstInfo
.hasSideEffects
) {
3496 PrintError(PatDef
->getLoc(), "Pattern doesn't match hasSideEffects = " +
3497 Twine(InstInfo
.hasSideEffects
));
3501 if (InstInfo
.mayStore
!= PatInfo
.mayStore
&& !InstInfo
.mayStore_Unset
) {
3503 PrintError(PatDef
->getLoc(), "Pattern doesn't match mayStore = " +
3504 Twine(InstInfo
.mayStore
));
3507 if (InstInfo
.mayLoad
!= PatInfo
.mayLoad
&& !InstInfo
.mayLoad_Unset
) {
3508 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
3509 // Some targets translate immediates to loads.
3510 if (!InstInfo
.mayLoad
) {
3512 PrintError(PatDef
->getLoc(), "Pattern doesn't match mayLoad = " +
3513 Twine(InstInfo
.mayLoad
));
3517 // Transfer inferred flags.
3518 InstInfo
.hasSideEffects
|= PatInfo
.hasSideEffects
;
3519 InstInfo
.mayStore
|= PatInfo
.mayStore
;
3520 InstInfo
.mayLoad
|= PatInfo
.mayLoad
;
3522 // These flags are silently added without any verification.
3523 // FIXME: To match historical behavior of TableGen, for now add those flags
3524 // only when we're inferring from the primary instruction pattern.
3525 if (PatDef
->isSubClassOf("Instruction")) {
3526 InstInfo
.isBitcast
|= PatInfo
.isBitcast
;
3527 InstInfo
.hasChain
|= PatInfo
.hasChain
;
3528 InstInfo
.hasChain_Inferred
= true;
3531 // Don't infer isVariadic. This flag means something different on SDNodes and
3532 // instructions. For example, a CALL SDNode is variadic because it has the
3533 // call arguments as operands, but a CALL instruction is not variadic - it
3534 // has argument registers as implicit, not explicit uses.
3539 /// hasNullFragReference - Return true if the DAG has any reference to the
3540 /// null_frag operator.
3541 static bool hasNullFragReference(DagInit
*DI
) {
3542 DefInit
*OpDef
= dyn_cast
<DefInit
>(DI
->getOperator());
3543 if (!OpDef
) return false;
3544 Record
*Operator
= OpDef
->getDef();
3546 // If this is the null fragment, return true.
3547 if (Operator
->getName() == "null_frag") return true;
3548 // If any of the arguments reference the null fragment, return true.
3549 for (unsigned i
= 0, e
= DI
->getNumArgs(); i
!= e
; ++i
) {
3550 DagInit
*Arg
= dyn_cast
<DagInit
>(DI
->getArg(i
));
3551 if (Arg
&& hasNullFragReference(Arg
))
3558 /// hasNullFragReference - Return true if any DAG in the list references
3559 /// the null_frag operator.
3560 static bool hasNullFragReference(ListInit
*LI
) {
3561 for (Init
*I
: LI
->getValues()) {
3562 DagInit
*DI
= dyn_cast
<DagInit
>(I
);
3563 assert(DI
&& "non-dag in an instruction Pattern list?!");
3564 if (hasNullFragReference(DI
))
3570 /// Get all the instructions in a tree.
3572 getInstructionsInTree(TreePatternNode
*Tree
, SmallVectorImpl
<Record
*> &Instrs
) {
3575 if (Tree
->getOperator()->isSubClassOf("Instruction"))
3576 Instrs
.push_back(Tree
->getOperator());
3577 for (unsigned i
= 0, e
= Tree
->getNumChildren(); i
!= e
; ++i
)
3578 getInstructionsInTree(Tree
->getChild(i
), Instrs
);
3581 /// Check the class of a pattern leaf node against the instruction operand it
3583 static bool checkOperandClass(CGIOperandList::OperandInfo
&OI
,
3588 // Allow direct value types to be used in instruction set patterns.
3589 // The type will be checked later.
3590 if (Leaf
->isSubClassOf("ValueType"))
3593 // Patterns can also be ComplexPattern instances.
3594 if (Leaf
->isSubClassOf("ComplexPattern"))
3600 void CodeGenDAGPatterns::parseInstructionPattern(
3601 CodeGenInstruction
&CGI
, ListInit
*Pat
, DAGInstMap
&DAGInsts
) {
3603 assert(!DAGInsts
.count(CGI
.TheDef
) && "Instruction already parsed!");
3605 // Parse the instruction.
3606 TreePattern
I(CGI
.TheDef
, Pat
, true, *this);
3608 // InstInputs - Keep track of all of the inputs of the instruction, along
3609 // with the record they are declared as.
3610 std::map
<std::string
, TreePatternNodePtr
> InstInputs
;
3612 // InstResults - Keep track of all the virtual registers that are 'set'
3613 // in the instruction, including what reg class they are.
3614 MapVector
<std::string
, TreePatternNodePtr
, std::map
<std::string
, unsigned>>
3617 std::vector
<Record
*> InstImpResults
;
3619 // Verify that the top-level forms in the instruction are of void type, and
3620 // fill in the InstResults map.
3621 SmallString
<32> TypesString
;
3622 for (unsigned j
= 0, e
= I
.getNumTrees(); j
!= e
; ++j
) {
3623 TypesString
.clear();
3624 TreePatternNodePtr Pat
= I
.getTree(j
);
3625 if (Pat
->getNumTypes() != 0) {
3626 raw_svector_ostream
OS(TypesString
);
3627 for (unsigned k
= 0, ke
= Pat
->getNumTypes(); k
!= ke
; ++k
) {
3630 Pat
->getExtType(k
).writeToStream(OS
);
3632 I
.error("Top-level forms in instruction pattern should have"
3633 " void types, has types " +
3637 // Find inputs and outputs, and verify the structure of the uses/defs.
3638 FindPatternInputsAndOutputs(I
, Pat
, InstInputs
, InstResults
,
3642 // Now that we have inputs and outputs of the pattern, inspect the operands
3643 // list for the instruction. This determines the order that operands are
3644 // added to the machine instruction the node corresponds to.
3645 unsigned NumResults
= InstResults
.size();
3647 // Parse the operands list from the (ops) list, validating it.
3648 assert(I
.getArgList().empty() && "Args list should still be empty here!");
3650 // Check that all of the results occur first in the list.
3651 std::vector
<Record
*> Results
;
3652 std::vector
<unsigned> ResultIndices
;
3653 SmallVector
<TreePatternNodePtr
, 2> ResNodes
;
3654 for (unsigned i
= 0; i
!= NumResults
; ++i
) {
3655 if (i
== CGI
.Operands
.size()) {
3656 const std::string
&OpName
=
3657 std::find_if(InstResults
.begin(), InstResults
.end(),
3658 [](const std::pair
<std::string
, TreePatternNodePtr
> &P
) {
3663 I
.error("'" + OpName
+ "' set but does not appear in operand list!");
3666 const std::string
&OpName
= CGI
.Operands
[i
].Name
;
3668 // Check that it exists in InstResults.
3669 auto InstResultIter
= InstResults
.find(OpName
);
3670 if (InstResultIter
== InstResults
.end() || !InstResultIter
->second
)
3671 I
.error("Operand $" + OpName
+ " does not exist in operand list!");
3673 TreePatternNodePtr RNode
= InstResultIter
->second
;
3674 Record
*R
= cast
<DefInit
>(RNode
->getLeafValue())->getDef();
3675 ResNodes
.push_back(std::move(RNode
));
3677 I
.error("Operand $" + OpName
+ " should be a set destination: all "
3678 "outputs must occur before inputs in operand list!");
3680 if (!checkOperandClass(CGI
.Operands
[i
], R
))
3681 I
.error("Operand $" + OpName
+ " class mismatch!");
3683 // Remember the return type.
3684 Results
.push_back(CGI
.Operands
[i
].Rec
);
3686 // Remember the result index.
3687 ResultIndices
.push_back(std::distance(InstResults
.begin(), InstResultIter
));
3689 // Okay, this one checks out.
3690 InstResultIter
->second
= nullptr;
3693 // Loop over the inputs next.
3694 std::vector
<TreePatternNodePtr
> ResultNodeOperands
;
3695 std::vector
<Record
*> Operands
;
3696 for (unsigned i
= NumResults
, e
= CGI
.Operands
.size(); i
!= e
; ++i
) {
3697 CGIOperandList::OperandInfo
&Op
= CGI
.Operands
[i
];
3698 const std::string
&OpName
= Op
.Name
;
3700 I
.error("Operand #" + Twine(i
) + " in operands list has no name!");
3702 if (!InstInputs
.count(OpName
)) {
3703 // If this is an operand with a DefaultOps set filled in, we can ignore
3704 // this. When we codegen it, we will do so as always executed.
3705 if (Op
.Rec
->isSubClassOf("OperandWithDefaultOps")) {
3706 // Does it have a non-empty DefaultOps field? If so, ignore this
3708 if (!getDefaultOperand(Op
.Rec
).DefaultOps
.empty())
3711 I
.error("Operand $" + OpName
+
3712 " does not appear in the instruction pattern");
3714 TreePatternNodePtr InVal
= InstInputs
[OpName
];
3715 InstInputs
.erase(OpName
); // It occurred, remove from map.
3717 if (InVal
->isLeaf() && isa
<DefInit
>(InVal
->getLeafValue())) {
3718 Record
*InRec
= static_cast<DefInit
*>(InVal
->getLeafValue())->getDef();
3719 if (!checkOperandClass(Op
, InRec
))
3720 I
.error("Operand $" + OpName
+ "'s register class disagrees"
3721 " between the operand and pattern");
3723 Operands
.push_back(Op
.Rec
);
3725 // Construct the result for the dest-pattern operand list.
3726 TreePatternNodePtr OpNode
= InVal
->clone();
3728 // No predicate is useful on the result.
3729 OpNode
->clearPredicateCalls();
3731 // Promote the xform function to be an explicit node if set.
3732 if (Record
*Xform
= OpNode
->getTransformFn()) {
3733 OpNode
->setTransformFn(nullptr);
3734 std::vector
<TreePatternNodePtr
> Children
;
3735 Children
.push_back(OpNode
);
3736 OpNode
= std::make_shared
<TreePatternNode
>(Xform
, std::move(Children
),
3737 OpNode
->getNumTypes());
3740 ResultNodeOperands
.push_back(std::move(OpNode
));
3743 if (!InstInputs
.empty())
3744 I
.error("Input operand $" + InstInputs
.begin()->first
+
3745 " occurs in pattern but not in operands list!");
3747 TreePatternNodePtr ResultPattern
= std::make_shared
<TreePatternNode
>(
3748 I
.getRecord(), std::move(ResultNodeOperands
),
3749 GetNumNodeResults(I
.getRecord(), *this));
3750 // Copy fully inferred output node types to instruction result pattern.
3751 for (unsigned i
= 0; i
!= NumResults
; ++i
) {
3752 assert(ResNodes
[i
]->getNumTypes() == 1 && "FIXME: Unhandled");
3753 ResultPattern
->setType(i
, ResNodes
[i
]->getExtType(0));
3754 ResultPattern
->setResultIndex(i
, ResultIndices
[i
]);
3757 // FIXME: Assume only the first tree is the pattern. The others are clobber
3759 TreePatternNodePtr Pattern
= I
.getTree(0);
3760 TreePatternNodePtr SrcPattern
;
3761 if (Pattern
->getOperator()->getName() == "set") {
3762 SrcPattern
= Pattern
->getChild(Pattern
->getNumChildren()-1)->clone();
3764 // Not a set (store or something?)
3765 SrcPattern
= Pattern
;
3768 // Create and insert the instruction.
3769 // FIXME: InstImpResults should not be part of DAGInstruction.
3770 Record
*R
= I
.getRecord();
3771 DAGInsts
.emplace(std::piecewise_construct
, std::forward_as_tuple(R
),
3772 std::forward_as_tuple(Results
, Operands
, InstImpResults
,
3773 SrcPattern
, ResultPattern
));
3775 LLVM_DEBUG(I
.dump());
3778 /// ParseInstructions - Parse all of the instructions, inlining and resolving
3779 /// any fragments involved. This populates the Instructions list with fully
3780 /// resolved instructions.
3781 void CodeGenDAGPatterns::ParseInstructions() {
3782 std::vector
<Record
*> Instrs
= Records
.getAllDerivedDefinitions("Instruction");
3784 for (Record
*Instr
: Instrs
) {
3785 ListInit
*LI
= nullptr;
3787 if (isa
<ListInit
>(Instr
->getValueInit("Pattern")))
3788 LI
= Instr
->getValueAsListInit("Pattern");
3790 // If there is no pattern, only collect minimal information about the
3791 // instruction for its operand list. We have to assume that there is one
3792 // result, as we have no detailed info. A pattern which references the
3793 // null_frag operator is as-if no pattern were specified. Normally this
3794 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3796 if (!LI
|| LI
->empty() || hasNullFragReference(LI
)) {
3797 std::vector
<Record
*> Results
;
3798 std::vector
<Record
*> Operands
;
3800 CodeGenInstruction
&InstInfo
= Target
.getInstruction(Instr
);
3802 if (InstInfo
.Operands
.size() != 0) {
3803 for (unsigned j
= 0, e
= InstInfo
.Operands
.NumDefs
; j
< e
; ++j
)
3804 Results
.push_back(InstInfo
.Operands
[j
].Rec
);
3806 // The rest are inputs.
3807 for (unsigned j
= InstInfo
.Operands
.NumDefs
,
3808 e
= InstInfo
.Operands
.size(); j
< e
; ++j
)
3809 Operands
.push_back(InstInfo
.Operands
[j
].Rec
);
3812 // Create and insert the instruction.
3813 std::vector
<Record
*> ImpResults
;
3814 Instructions
.insert(std::make_pair(Instr
,
3815 DAGInstruction(Results
, Operands
, ImpResults
)));
3816 continue; // no pattern.
3819 CodeGenInstruction
&CGI
= Target
.getInstruction(Instr
);
3820 parseInstructionPattern(CGI
, LI
, Instructions
);
3823 // If we can, convert the instructions to be patterns that are matched!
3824 for (auto &Entry
: Instructions
) {
3825 Record
*Instr
= Entry
.first
;
3826 DAGInstruction
&TheInst
= Entry
.second
;
3827 TreePatternNodePtr SrcPattern
= TheInst
.getSrcPattern();
3828 TreePatternNodePtr ResultPattern
= TheInst
.getResultPattern();
3830 if (SrcPattern
&& ResultPattern
) {
3831 TreePattern
Pattern(Instr
, SrcPattern
, true, *this);
3832 TreePattern
Result(Instr
, ResultPattern
, false, *this);
3833 ParseOnePattern(Instr
, Pattern
, Result
, TheInst
.getImpResults());
3838 typedef std::pair
<TreePatternNode
*, unsigned> NameRecord
;
3840 static void FindNames(TreePatternNode
*P
,
3841 std::map
<std::string
, NameRecord
> &Names
,
3842 TreePattern
*PatternTop
) {
3843 if (!P
->getName().empty()) {
3844 NameRecord
&Rec
= Names
[P
->getName()];
3845 // If this is the first instance of the name, remember the node.
3846 if (Rec
.second
++ == 0)
3848 else if (Rec
.first
->getExtTypes() != P
->getExtTypes())
3849 PatternTop
->error("repetition of value: $" + P
->getName() +
3850 " where different uses have different types!");
3854 for (unsigned i
= 0, e
= P
->getNumChildren(); i
!= e
; ++i
)
3855 FindNames(P
->getChild(i
), Names
, PatternTop
);
3859 std::vector
<Predicate
> CodeGenDAGPatterns::makePredList(ListInit
*L
) {
3860 std::vector
<Predicate
> Preds
;
3861 for (Init
*I
: L
->getValues()) {
3862 if (DefInit
*Pred
= dyn_cast
<DefInit
>(I
))
3863 Preds
.push_back(Pred
->getDef());
3865 llvm_unreachable("Non-def on the list");
3868 // Sort so that different orders get canonicalized to the same string.
3873 void CodeGenDAGPatterns::AddPatternToMatch(TreePattern
*Pattern
,
3874 PatternToMatch
&&PTM
) {
3875 // Do some sanity checking on the pattern we're about to match.
3877 if (!PTM
.getSrcPattern()->canPatternMatch(Reason
, *this)) {
3878 PrintWarning(Pattern
->getRecord()->getLoc(),
3879 Twine("Pattern can never match: ") + Reason
);
3883 // If the source pattern's root is a complex pattern, that complex pattern
3884 // must specify the nodes it can potentially match.
3885 if (const ComplexPattern
*CP
=
3886 PTM
.getSrcPattern()->getComplexPatternInfo(*this))
3887 if (CP
->getRootNodes().empty())
3888 Pattern
->error("ComplexPattern at root must specify list of opcodes it"
3892 // Find all of the named values in the input and output, ensure they have the
3894 std::map
<std::string
, NameRecord
> SrcNames
, DstNames
;
3895 FindNames(PTM
.getSrcPattern(), SrcNames
, Pattern
);
3896 FindNames(PTM
.getDstPattern(), DstNames
, Pattern
);
3898 // Scan all of the named values in the destination pattern, rejecting them if
3899 // they don't exist in the input pattern.
3900 for (const auto &Entry
: DstNames
) {
3901 if (SrcNames
[Entry
.first
].first
== nullptr)
3902 Pattern
->error("Pattern has input without matching name in output: $" +
3906 // Scan all of the named values in the source pattern, rejecting them if the
3907 // name isn't used in the dest, and isn't used to tie two values together.
3908 for (const auto &Entry
: SrcNames
)
3909 if (DstNames
[Entry
.first
].first
== nullptr &&
3910 SrcNames
[Entry
.first
].second
== 1)
3911 Pattern
->error("Pattern has dead named input: $" + Entry
.first
);
3913 PatternsToMatch
.push_back(PTM
);
3916 void CodeGenDAGPatterns::InferInstructionFlags() {
3917 ArrayRef
<const CodeGenInstruction
*> Instructions
=
3918 Target
.getInstructionsByEnumValue();
3920 unsigned Errors
= 0;
3922 // Try to infer flags from all patterns in PatternToMatch. These include
3923 // both the primary instruction patterns (which always come first) and
3924 // patterns defined outside the instruction.
3925 for (const PatternToMatch
&PTM
: ptms()) {
3926 // We can only infer from single-instruction patterns, otherwise we won't
3927 // know which instruction should get the flags.
3928 SmallVector
<Record
*, 8> PatInstrs
;
3929 getInstructionsInTree(PTM
.getDstPattern(), PatInstrs
);
3930 if (PatInstrs
.size() != 1)
3933 // Get the single instruction.
3934 CodeGenInstruction
&InstInfo
= Target
.getInstruction(PatInstrs
.front());
3936 // Only infer properties from the first pattern. We'll verify the others.
3937 if (InstInfo
.InferredFrom
)
3940 InstAnalyzer
PatInfo(*this);
3941 PatInfo
.Analyze(PTM
);
3942 Errors
+= InferFromPattern(InstInfo
, PatInfo
, PTM
.getSrcRecord());
3946 PrintFatalError("pattern conflicts");
3948 // If requested by the target, guess any undefined properties.
3949 if (Target
.guessInstructionProperties()) {
3950 for (unsigned i
= 0, e
= Instructions
.size(); i
!= e
; ++i
) {
3951 CodeGenInstruction
*InstInfo
=
3952 const_cast<CodeGenInstruction
*>(Instructions
[i
]);
3953 if (InstInfo
->InferredFrom
)
3955 // The mayLoad and mayStore flags default to false.
3956 // Conservatively assume hasSideEffects if it wasn't explicit.
3957 if (InstInfo
->hasSideEffects_Unset
)
3958 InstInfo
->hasSideEffects
= true;
3963 // Complain about any flags that are still undefined.
3964 for (unsigned i
= 0, e
= Instructions
.size(); i
!= e
; ++i
) {
3965 CodeGenInstruction
*InstInfo
=
3966 const_cast<CodeGenInstruction
*>(Instructions
[i
]);
3967 if (InstInfo
->InferredFrom
)
3969 if (InstInfo
->hasSideEffects_Unset
)
3970 PrintError(InstInfo
->TheDef
->getLoc(),
3971 "Can't infer hasSideEffects from patterns");
3972 if (InstInfo
->mayStore_Unset
)
3973 PrintError(InstInfo
->TheDef
->getLoc(),
3974 "Can't infer mayStore from patterns");
3975 if (InstInfo
->mayLoad_Unset
)
3976 PrintError(InstInfo
->TheDef
->getLoc(),
3977 "Can't infer mayLoad from patterns");
3982 /// Verify instruction flags against pattern node properties.
3983 void CodeGenDAGPatterns::VerifyInstructionFlags() {
3984 unsigned Errors
= 0;
3985 for (ptm_iterator I
= ptm_begin(), E
= ptm_end(); I
!= E
; ++I
) {
3986 const PatternToMatch
&PTM
= *I
;
3987 SmallVector
<Record
*, 8> Instrs
;
3988 getInstructionsInTree(PTM
.getDstPattern(), Instrs
);
3992 // Count the number of instructions with each flag set.
3993 unsigned NumSideEffects
= 0;
3994 unsigned NumStores
= 0;
3995 unsigned NumLoads
= 0;
3996 for (const Record
*Instr
: Instrs
) {
3997 const CodeGenInstruction
&InstInfo
= Target
.getInstruction(Instr
);
3998 NumSideEffects
+= InstInfo
.hasSideEffects
;
3999 NumStores
+= InstInfo
.mayStore
;
4000 NumLoads
+= InstInfo
.mayLoad
;
4003 // Analyze the source pattern.
4004 InstAnalyzer
PatInfo(*this);
4005 PatInfo
.Analyze(PTM
);
4007 // Collect error messages.
4008 SmallVector
<std::string
, 4> Msgs
;
4010 // Check for missing flags in the output.
4011 // Permit extra flags for now at least.
4012 if (PatInfo
.hasSideEffects
&& !NumSideEffects
)
4013 Msgs
.push_back("pattern has side effects, but hasSideEffects isn't set");
4015 // Don't verify store flags on instructions with side effects. At least for
4016 // intrinsics, side effects implies mayStore.
4017 if (!PatInfo
.hasSideEffects
&& PatInfo
.mayStore
&& !NumStores
)
4018 Msgs
.push_back("pattern may store, but mayStore isn't set");
4020 // Similarly, mayStore implies mayLoad on intrinsics.
4021 if (!PatInfo
.mayStore
&& PatInfo
.mayLoad
&& !NumLoads
)
4022 Msgs
.push_back("pattern may load, but mayLoad isn't set");
4024 // Print error messages.
4029 for (const std::string
&Msg
: Msgs
)
4030 PrintError(PTM
.getSrcRecord()->getLoc(), Twine(Msg
) + " on the " +
4031 (Instrs
.size() == 1 ?
4032 "instruction" : "output instructions"));
4033 // Provide the location of the relevant instruction definitions.
4034 for (const Record
*Instr
: Instrs
) {
4035 if (Instr
!= PTM
.getSrcRecord())
4036 PrintError(Instr
->getLoc(), "defined here");
4037 const CodeGenInstruction
&InstInfo
= Target
.getInstruction(Instr
);
4038 if (InstInfo
.InferredFrom
&&
4039 InstInfo
.InferredFrom
!= InstInfo
.TheDef
&&
4040 InstInfo
.InferredFrom
!= PTM
.getSrcRecord())
4041 PrintError(InstInfo
.InferredFrom
->getLoc(), "inferred from pattern");
4045 PrintFatalError("Errors in DAG patterns");
4048 /// Given a pattern result with an unresolved type, see if we can find one
4049 /// instruction with an unresolved result type. Force this result type to an
4050 /// arbitrary element if it's possible types to converge results.
4051 static bool ForceArbitraryInstResultType(TreePatternNode
*N
, TreePattern
&TP
) {
4055 // Analyze children.
4056 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
)
4057 if (ForceArbitraryInstResultType(N
->getChild(i
), TP
))
4060 if (!N
->getOperator()->isSubClassOf("Instruction"))
4063 // If this type is already concrete or completely unknown we can't do
4065 TypeInfer
&TI
= TP
.getInfer();
4066 for (unsigned i
= 0, e
= N
->getNumTypes(); i
!= e
; ++i
) {
4067 if (N
->getExtType(i
).empty() || TI
.isConcrete(N
->getExtType(i
), false))
4070 // Otherwise, force its type to an arbitrary choice.
4071 if (TI
.forceArbitrary(N
->getExtType(i
)))
4078 // Promote xform function to be an explicit node wherever set.
4079 static TreePatternNodePtr
PromoteXForms(TreePatternNodePtr N
) {
4080 if (Record
*Xform
= N
->getTransformFn()) {
4081 N
->setTransformFn(nullptr);
4082 std::vector
<TreePatternNodePtr
> Children
;
4083 Children
.push_back(PromoteXForms(N
));
4084 return std::make_shared
<TreePatternNode
>(Xform
, std::move(Children
),
4089 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
) {
4090 TreePatternNodePtr Child
= N
->getChildShared(i
);
4091 N
->setChild(i
, PromoteXForms(Child
));
4096 void CodeGenDAGPatterns::ParseOnePattern(Record
*TheDef
,
4097 TreePattern
&Pattern
, TreePattern
&Result
,
4098 const std::vector
<Record
*> &InstImpResults
) {
4100 // Inline pattern fragments and expand multiple alternatives.
4101 Pattern
.InlinePatternFragments();
4102 Result
.InlinePatternFragments();
4104 if (Result
.getNumTrees() != 1)
4105 Result
.error("Cannot use multi-alternative fragments in result pattern!");
4108 bool IterateInference
;
4109 bool InferredAllPatternTypes
, InferredAllResultTypes
;
4111 // Infer as many types as possible. If we cannot infer all of them, we
4112 // can never do anything with this pattern: report it to the user.
4113 InferredAllPatternTypes
=
4114 Pattern
.InferAllTypes(&Pattern
.getNamedNodesMap());
4116 // Infer as many types as possible. If we cannot infer all of them, we
4117 // can never do anything with this pattern: report it to the user.
4118 InferredAllResultTypes
=
4119 Result
.InferAllTypes(&Pattern
.getNamedNodesMap());
4121 IterateInference
= false;
4123 // Apply the type of the result to the source pattern. This helps us
4124 // resolve cases where the input type is known to be a pointer type (which
4125 // is considered resolved), but the result knows it needs to be 32- or
4126 // 64-bits. Infer the other way for good measure.
4127 for (auto T
: Pattern
.getTrees())
4128 for (unsigned i
= 0, e
= std::min(Result
.getOnlyTree()->getNumTypes(),
4131 IterateInference
|= T
->UpdateNodeType(
4132 i
, Result
.getOnlyTree()->getExtType(i
), Result
);
4133 IterateInference
|= Result
.getOnlyTree()->UpdateNodeType(
4134 i
, T
->getExtType(i
), Result
);
4137 // If our iteration has converged and the input pattern's types are fully
4138 // resolved but the result pattern is not fully resolved, we may have a
4139 // situation where we have two instructions in the result pattern and
4140 // the instructions require a common register class, but don't care about
4141 // what actual MVT is used. This is actually a bug in our modelling:
4142 // output patterns should have register classes, not MVTs.
4144 // In any case, to handle this, we just go through and disambiguate some
4145 // arbitrary types to the result pattern's nodes.
4146 if (!IterateInference
&& InferredAllPatternTypes
&&
4147 !InferredAllResultTypes
)
4149 ForceArbitraryInstResultType(Result
.getTree(0).get(), Result
);
4150 } while (IterateInference
);
4152 // Verify that we inferred enough types that we can do something with the
4153 // pattern and result. If these fire the user has to add type casts.
4154 if (!InferredAllPatternTypes
)
4155 Pattern
.error("Could not infer all types in pattern!");
4156 if (!InferredAllResultTypes
) {
4158 Result
.error("Could not infer all types in pattern result!");
4161 // Promote xform function to be an explicit node wherever set.
4162 TreePatternNodePtr DstShared
= PromoteXForms(Result
.getOnlyTree());
4164 TreePattern
Temp(Result
.getRecord(), DstShared
, false, *this);
4165 Temp
.InferAllTypes();
4167 ListInit
*Preds
= TheDef
->getValueAsListInit("Predicates");
4168 int Complexity
= TheDef
->getValueAsInt("AddedComplexity");
4170 if (PatternRewriter
)
4171 PatternRewriter(&Pattern
);
4173 // A pattern may end up with an "impossible" type, i.e. a situation
4174 // where all types have been eliminated for some node in this pattern.
4175 // This could occur for intrinsics that only make sense for a specific
4176 // value type, and use a specific register class. If, for some mode,
4177 // that register class does not accept that type, the type inference
4178 // will lead to a contradiction, which is not an error however, but
4179 // a sign that this pattern will simply never match.
4180 if (Temp
.getOnlyTree()->hasPossibleType())
4181 for (auto T
: Pattern
.getTrees())
4182 if (T
->hasPossibleType())
4183 AddPatternToMatch(&Pattern
,
4184 PatternToMatch(TheDef
, makePredList(Preds
),
4185 T
, Temp
.getOnlyTree(),
4186 InstImpResults
, Complexity
,
4190 void CodeGenDAGPatterns::ParsePatterns() {
4191 std::vector
<Record
*> Patterns
= Records
.getAllDerivedDefinitions("Pattern");
4193 for (Record
*CurPattern
: Patterns
) {
4194 DagInit
*Tree
= CurPattern
->getValueAsDag("PatternToMatch");
4196 // If the pattern references the null_frag, there's nothing to do.
4197 if (hasNullFragReference(Tree
))
4200 TreePattern
Pattern(CurPattern
, Tree
, true, *this);
4202 ListInit
*LI
= CurPattern
->getValueAsListInit("ResultInstrs");
4203 if (LI
->empty()) continue; // no pattern.
4205 // Parse the instruction.
4206 TreePattern
Result(CurPattern
, LI
, false, *this);
4208 if (Result
.getNumTrees() != 1)
4209 Result
.error("Cannot handle instructions producing instructions "
4210 "with temporaries yet!");
4212 // Validate that the input pattern is correct.
4213 std::map
<std::string
, TreePatternNodePtr
> InstInputs
;
4214 MapVector
<std::string
, TreePatternNodePtr
, std::map
<std::string
, unsigned>>
4216 std::vector
<Record
*> InstImpResults
;
4217 for (unsigned j
= 0, ee
= Pattern
.getNumTrees(); j
!= ee
; ++j
)
4218 FindPatternInputsAndOutputs(Pattern
, Pattern
.getTree(j
), InstInputs
,
4219 InstResults
, InstImpResults
);
4221 ParseOnePattern(CurPattern
, Pattern
, Result
, InstImpResults
);
4225 static void collectModes(std::set
<unsigned> &Modes
, const TreePatternNode
*N
) {
4226 for (const TypeSetByHwMode
&VTS
: N
->getExtTypes())
4227 for (const auto &I
: VTS
)
4228 Modes
.insert(I
.first
);
4230 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
)
4231 collectModes(Modes
, N
->getChild(i
));
4234 void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
4235 const CodeGenHwModes
&CGH
= getTargetInfo().getHwModes();
4236 std::map
<unsigned,std::vector
<Predicate
>> ModeChecks
;
4237 std::vector
<PatternToMatch
> Copy
= PatternsToMatch
;
4238 PatternsToMatch
.clear();
4240 auto AppendPattern
= [this, &ModeChecks
](PatternToMatch
&P
, unsigned Mode
) {
4241 TreePatternNodePtr NewSrc
= P
.SrcPattern
->clone();
4242 TreePatternNodePtr NewDst
= P
.DstPattern
->clone();
4243 if (!NewSrc
->setDefaultMode(Mode
) || !NewDst
->setDefaultMode(Mode
)) {
4247 std::vector
<Predicate
> Preds
= P
.Predicates
;
4248 const std::vector
<Predicate
> &MC
= ModeChecks
[Mode
];
4249 Preds
.insert(Preds
.end(), MC
.begin(), MC
.end());
4250 PatternsToMatch
.emplace_back(P
.getSrcRecord(), Preds
, std::move(NewSrc
),
4251 std::move(NewDst
), P
.getDstRegs(),
4252 P
.getAddedComplexity(), Record::getNewUID(),
4256 for (PatternToMatch
&P
: Copy
) {
4257 TreePatternNodePtr SrcP
= nullptr, DstP
= nullptr;
4258 if (P
.SrcPattern
->hasProperTypeByHwMode())
4259 SrcP
= P
.SrcPattern
;
4260 if (P
.DstPattern
->hasProperTypeByHwMode())
4261 DstP
= P
.DstPattern
;
4262 if (!SrcP
&& !DstP
) {
4263 PatternsToMatch
.push_back(P
);
4267 std::set
<unsigned> Modes
;
4269 collectModes(Modes
, SrcP
.get());
4271 collectModes(Modes
, DstP
.get());
4273 // The predicate for the default mode needs to be constructed for each
4274 // pattern separately.
4275 // Since not all modes must be present in each pattern, if a mode m is
4276 // absent, then there is no point in constructing a check for m. If such
4277 // a check was created, it would be equivalent to checking the default
4278 // mode, except not all modes' predicates would be a part of the checking
4279 // code. The subsequently generated check for the default mode would then
4280 // have the exact same patterns, but a different predicate code. To avoid
4281 // duplicated patterns with different predicate checks, construct the
4282 // default check as a negation of all predicates that are actually present
4283 // in the source/destination patterns.
4284 std::vector
<Predicate
> DefaultPred
;
4286 for (unsigned M
: Modes
) {
4287 if (M
== DefaultMode
)
4289 if (ModeChecks
.find(M
) != ModeChecks
.end())
4292 // Fill the map entry for this mode.
4293 const HwMode
&HM
= CGH
.getMode(M
);
4294 ModeChecks
[M
].emplace_back(Predicate(HM
.Features
, true));
4296 // Add negations of the HM's predicates to the default predicate.
4297 DefaultPred
.emplace_back(Predicate(HM
.Features
, false));
4300 for (unsigned M
: Modes
) {
4301 if (M
== DefaultMode
)
4303 AppendPattern(P
, M
);
4306 bool HasDefault
= Modes
.count(DefaultMode
);
4308 AppendPattern(P
, DefaultMode
);
4312 /// Dependent variable map for CodeGenDAGPattern variant generation
4313 typedef StringMap
<int> DepVarMap
;
4315 static void FindDepVarsOf(TreePatternNode
*N
, DepVarMap
&DepMap
) {
4317 if (N
->hasName() && isa
<DefInit
>(N
->getLeafValue()))
4318 DepMap
[N
->getName()]++;
4320 for (size_t i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
)
4321 FindDepVarsOf(N
->getChild(i
), DepMap
);
4325 /// Find dependent variables within child patterns
4326 static void FindDepVars(TreePatternNode
*N
, MultipleUseVarSet
&DepVars
) {
4327 DepVarMap depcounts
;
4328 FindDepVarsOf(N
, depcounts
);
4329 for (const auto &Pair
: depcounts
) {
4330 if (Pair
.getValue() > 1)
4331 DepVars
.insert(Pair
.getKey());
4336 /// Dump the dependent variable set:
4337 static void DumpDepVars(MultipleUseVarSet
&DepVars
) {
4338 if (DepVars
.empty()) {
4339 LLVM_DEBUG(errs() << "<empty set>");
4341 LLVM_DEBUG(errs() << "[ ");
4342 for (const auto &DepVar
: DepVars
) {
4343 LLVM_DEBUG(errs() << DepVar
.getKey() << " ");
4345 LLVM_DEBUG(errs() << "]");
4351 /// CombineChildVariants - Given a bunch of permutations of each child of the
4352 /// 'operator' node, put them together in all possible ways.
4353 static void CombineChildVariants(
4354 TreePatternNodePtr Orig
,
4355 const std::vector
<std::vector
<TreePatternNodePtr
>> &ChildVariants
,
4356 std::vector
<TreePatternNodePtr
> &OutVariants
, CodeGenDAGPatterns
&CDP
,
4357 const MultipleUseVarSet
&DepVars
) {
4358 // Make sure that each operand has at least one variant to choose from.
4359 for (const auto &Variants
: ChildVariants
)
4360 if (Variants
.empty())
4363 // The end result is an all-pairs construction of the resultant pattern.
4364 std::vector
<unsigned> Idxs
;
4365 Idxs
.resize(ChildVariants
.size());
4369 LLVM_DEBUG(if (!Idxs
.empty()) {
4370 errs() << Orig
->getOperator()->getName() << ": Idxs = [ ";
4371 for (unsigned Idx
: Idxs
) {
4372 errs() << Idx
<< " ";
4377 // Create the variant and add it to the output list.
4378 std::vector
<TreePatternNodePtr
> NewChildren
;
4379 for (unsigned i
= 0, e
= ChildVariants
.size(); i
!= e
; ++i
)
4380 NewChildren
.push_back(ChildVariants
[i
][Idxs
[i
]]);
4381 TreePatternNodePtr R
= std::make_shared
<TreePatternNode
>(
4382 Orig
->getOperator(), std::move(NewChildren
), Orig
->getNumTypes());
4384 // Copy over properties.
4385 R
->setName(Orig
->getName());
4386 R
->setNamesAsPredicateArg(Orig
->getNamesAsPredicateArg());
4387 R
->setPredicateCalls(Orig
->getPredicateCalls());
4388 R
->setTransformFn(Orig
->getTransformFn());
4389 for (unsigned i
= 0, e
= Orig
->getNumTypes(); i
!= e
; ++i
)
4390 R
->setType(i
, Orig
->getExtType(i
));
4392 // If this pattern cannot match, do not include it as a variant.
4393 std::string ErrString
;
4394 // Scan to see if this pattern has already been emitted. We can get
4395 // duplication due to things like commuting:
4396 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4397 // which are the same pattern. Ignore the dups.
4398 if (R
->canPatternMatch(ErrString
, CDP
) &&
4399 none_of(OutVariants
, [&](TreePatternNodePtr Variant
) {
4400 return R
->isIsomorphicTo(Variant
.get(), DepVars
);
4402 OutVariants
.push_back(R
);
4404 // Increment indices to the next permutation by incrementing the
4405 // indices from last index backward, e.g., generate the sequence
4406 // [0, 0], [0, 1], [1, 0], [1, 1].
4408 for (IdxsIdx
= Idxs
.size() - 1; IdxsIdx
>= 0; --IdxsIdx
) {
4409 if (++Idxs
[IdxsIdx
] == ChildVariants
[IdxsIdx
].size())
4414 NotDone
= (IdxsIdx
>= 0);
4418 /// CombineChildVariants - A helper function for binary operators.
4420 static void CombineChildVariants(TreePatternNodePtr Orig
,
4421 const std::vector
<TreePatternNodePtr
> &LHS
,
4422 const std::vector
<TreePatternNodePtr
> &RHS
,
4423 std::vector
<TreePatternNodePtr
> &OutVariants
,
4424 CodeGenDAGPatterns
&CDP
,
4425 const MultipleUseVarSet
&DepVars
) {
4426 std::vector
<std::vector
<TreePatternNodePtr
>> ChildVariants
;
4427 ChildVariants
.push_back(LHS
);
4428 ChildVariants
.push_back(RHS
);
4429 CombineChildVariants(Orig
, ChildVariants
, OutVariants
, CDP
, DepVars
);
4433 GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N
,
4434 std::vector
<TreePatternNodePtr
> &Children
) {
4435 assert(N
->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
4436 Record
*Operator
= N
->getOperator();
4438 // Only permit raw nodes.
4439 if (!N
->getName().empty() || !N
->getPredicateCalls().empty() ||
4440 N
->getTransformFn()) {
4441 Children
.push_back(N
);
4445 if (N
->getChild(0)->isLeaf() || N
->getChild(0)->getOperator() != Operator
)
4446 Children
.push_back(N
->getChildShared(0));
4448 GatherChildrenOfAssociativeOpcode(N
->getChildShared(0), Children
);
4450 if (N
->getChild(1)->isLeaf() || N
->getChild(1)->getOperator() != Operator
)
4451 Children
.push_back(N
->getChildShared(1));
4453 GatherChildrenOfAssociativeOpcode(N
->getChildShared(1), Children
);
4456 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4457 /// the (potentially recursive) pattern by using algebraic laws.
4459 static void GenerateVariantsOf(TreePatternNodePtr N
,
4460 std::vector
<TreePatternNodePtr
> &OutVariants
,
4461 CodeGenDAGPatterns
&CDP
,
4462 const MultipleUseVarSet
&DepVars
) {
4463 // We cannot permute leaves or ComplexPattern uses.
4464 if (N
->isLeaf() || N
->getOperator()->isSubClassOf("ComplexPattern")) {
4465 OutVariants
.push_back(N
);
4469 // Look up interesting info about the node.
4470 const SDNodeInfo
&NodeInfo
= CDP
.getSDNodeInfo(N
->getOperator());
4472 // If this node is associative, re-associate.
4473 if (NodeInfo
.hasProperty(SDNPAssociative
)) {
4474 // Re-associate by pulling together all of the linked operators
4475 std::vector
<TreePatternNodePtr
> MaximalChildren
;
4476 GatherChildrenOfAssociativeOpcode(N
, MaximalChildren
);
4478 // Only handle child sizes of 3. Otherwise we'll end up trying too many
4480 if (MaximalChildren
.size() == 3) {
4481 // Find the variants of all of our maximal children.
4482 std::vector
<TreePatternNodePtr
> AVariants
, BVariants
, CVariants
;
4483 GenerateVariantsOf(MaximalChildren
[0], AVariants
, CDP
, DepVars
);
4484 GenerateVariantsOf(MaximalChildren
[1], BVariants
, CDP
, DepVars
);
4485 GenerateVariantsOf(MaximalChildren
[2], CVariants
, CDP
, DepVars
);
4487 // There are only two ways we can permute the tree:
4488 // (A op B) op C and A op (B op C)
4489 // Within these forms, we can also permute A/B/C.
4491 // Generate legal pair permutations of A/B/C.
4492 std::vector
<TreePatternNodePtr
> ABVariants
;
4493 std::vector
<TreePatternNodePtr
> BAVariants
;
4494 std::vector
<TreePatternNodePtr
> ACVariants
;
4495 std::vector
<TreePatternNodePtr
> CAVariants
;
4496 std::vector
<TreePatternNodePtr
> BCVariants
;
4497 std::vector
<TreePatternNodePtr
> CBVariants
;
4498 CombineChildVariants(N
, AVariants
, BVariants
, ABVariants
, CDP
, DepVars
);
4499 CombineChildVariants(N
, BVariants
, AVariants
, BAVariants
, CDP
, DepVars
);
4500 CombineChildVariants(N
, AVariants
, CVariants
, ACVariants
, CDP
, DepVars
);
4501 CombineChildVariants(N
, CVariants
, AVariants
, CAVariants
, CDP
, DepVars
);
4502 CombineChildVariants(N
, BVariants
, CVariants
, BCVariants
, CDP
, DepVars
);
4503 CombineChildVariants(N
, CVariants
, BVariants
, CBVariants
, CDP
, DepVars
);
4505 // Combine those into the result: (x op x) op x
4506 CombineChildVariants(N
, ABVariants
, CVariants
, OutVariants
, CDP
, DepVars
);
4507 CombineChildVariants(N
, BAVariants
, CVariants
, OutVariants
, CDP
, DepVars
);
4508 CombineChildVariants(N
, ACVariants
, BVariants
, OutVariants
, CDP
, DepVars
);
4509 CombineChildVariants(N
, CAVariants
, BVariants
, OutVariants
, CDP
, DepVars
);
4510 CombineChildVariants(N
, BCVariants
, AVariants
, OutVariants
, CDP
, DepVars
);
4511 CombineChildVariants(N
, CBVariants
, AVariants
, OutVariants
, CDP
, DepVars
);
4513 // Combine those into the result: x op (x op x)
4514 CombineChildVariants(N
, CVariants
, ABVariants
, OutVariants
, CDP
, DepVars
);
4515 CombineChildVariants(N
, CVariants
, BAVariants
, OutVariants
, CDP
, DepVars
);
4516 CombineChildVariants(N
, BVariants
, ACVariants
, OutVariants
, CDP
, DepVars
);
4517 CombineChildVariants(N
, BVariants
, CAVariants
, OutVariants
, CDP
, DepVars
);
4518 CombineChildVariants(N
, AVariants
, BCVariants
, OutVariants
, CDP
, DepVars
);
4519 CombineChildVariants(N
, AVariants
, CBVariants
, OutVariants
, CDP
, DepVars
);
4524 // Compute permutations of all children.
4525 std::vector
<std::vector
<TreePatternNodePtr
>> ChildVariants
;
4526 ChildVariants
.resize(N
->getNumChildren());
4527 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
)
4528 GenerateVariantsOf(N
->getChildShared(i
), ChildVariants
[i
], CDP
, DepVars
);
4530 // Build all permutations based on how the children were formed.
4531 CombineChildVariants(N
, ChildVariants
, OutVariants
, CDP
, DepVars
);
4533 // If this node is commutative, consider the commuted order.
4534 bool isCommIntrinsic
= N
->isCommutativeIntrinsic(CDP
);
4535 if (NodeInfo
.hasProperty(SDNPCommutative
) || isCommIntrinsic
) {
4536 assert((N
->getNumChildren()>=2 || isCommIntrinsic
) &&
4537 "Commutative but doesn't have 2 children!");
4538 // Don't count children which are actually register references.
4540 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
) {
4541 TreePatternNode
*Child
= N
->getChild(i
);
4542 if (Child
->isLeaf())
4543 if (DefInit
*DI
= dyn_cast
<DefInit
>(Child
->getLeafValue())) {
4544 Record
*RR
= DI
->getDef();
4545 if (RR
->isSubClassOf("Register"))
4550 // Consider the commuted order.
4551 if (isCommIntrinsic
) {
4552 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4553 // operands are the commutative operands, and there might be more operands
4556 "Commutative intrinsic should have at least 3 children!");
4557 std::vector
<std::vector
<TreePatternNodePtr
>> Variants
;
4558 Variants
.push_back(std::move(ChildVariants
[0])); // Intrinsic id.
4559 Variants
.push_back(std::move(ChildVariants
[2]));
4560 Variants
.push_back(std::move(ChildVariants
[1]));
4561 for (unsigned i
= 3; i
!= NC
; ++i
)
4562 Variants
.push_back(std::move(ChildVariants
[i
]));
4563 CombineChildVariants(N
, Variants
, OutVariants
, CDP
, DepVars
);
4564 } else if (NC
== N
->getNumChildren()) {
4565 std::vector
<std::vector
<TreePatternNodePtr
>> Variants
;
4566 Variants
.push_back(std::move(ChildVariants
[1]));
4567 Variants
.push_back(std::move(ChildVariants
[0]));
4568 for (unsigned i
= 2; i
!= NC
; ++i
)
4569 Variants
.push_back(std::move(ChildVariants
[i
]));
4570 CombineChildVariants(N
, Variants
, OutVariants
, CDP
, DepVars
);
4576 // GenerateVariants - Generate variants. For example, commutative patterns can
4577 // match multiple ways. Add them to PatternsToMatch as well.
4578 void CodeGenDAGPatterns::GenerateVariants() {
4579 LLVM_DEBUG(errs() << "Generating instruction variants.\n");
4581 // Loop over all of the patterns we've collected, checking to see if we can
4582 // generate variants of the instruction, through the exploitation of
4583 // identities. This permits the target to provide aggressive matching without
4584 // the .td file having to contain tons of variants of instructions.
4586 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4587 // intentionally do not reconsider these. Any variants of added patterns have
4588 // already been added.
4590 const unsigned NumOriginalPatterns
= PatternsToMatch
.size();
4591 BitVector
MatchedPatterns(NumOriginalPatterns
);
4592 std::vector
<BitVector
> MatchedPredicates(NumOriginalPatterns
,
4593 BitVector(NumOriginalPatterns
));
4595 typedef std::pair
<MultipleUseVarSet
, std::vector
<TreePatternNodePtr
>>
4597 std::map
<unsigned, DepsAndVariants
> PatternsWithVariants
;
4599 // Collect patterns with more than one variant.
4600 for (unsigned i
= 0; i
!= NumOriginalPatterns
; ++i
) {
4601 MultipleUseVarSet DepVars
;
4602 std::vector
<TreePatternNodePtr
> Variants
;
4603 FindDepVars(PatternsToMatch
[i
].getSrcPattern(), DepVars
);
4604 LLVM_DEBUG(errs() << "Dependent/multiply used variables: ");
4605 LLVM_DEBUG(DumpDepVars(DepVars
));
4606 LLVM_DEBUG(errs() << "\n");
4607 GenerateVariantsOf(PatternsToMatch
[i
].getSrcPatternShared(), Variants
,
4610 assert(!Variants
.empty() && "Must create at least original variant!");
4611 if (Variants
.size() == 1) // No additional variants for this pattern.
4614 LLVM_DEBUG(errs() << "FOUND VARIANTS OF: ";
4615 PatternsToMatch
[i
].getSrcPattern()->dump(); errs() << "\n");
4617 PatternsWithVariants
[i
] = std::make_pair(DepVars
, Variants
);
4619 // Cache matching predicates.
4620 if (MatchedPatterns
[i
])
4623 const std::vector
<Predicate
> &Predicates
=
4624 PatternsToMatch
[i
].getPredicates();
4626 BitVector
&Matches
= MatchedPredicates
[i
];
4627 MatchedPatterns
.set(i
);
4630 // Don't test patterns that have already been cached - it won't match.
4631 for (unsigned p
= 0; p
!= NumOriginalPatterns
; ++p
)
4632 if (!MatchedPatterns
[p
])
4633 Matches
[p
] = (Predicates
== PatternsToMatch
[p
].getPredicates());
4635 // Copy this to all the matching patterns.
4636 for (int p
= Matches
.find_first(); p
!= -1; p
= Matches
.find_next(p
))
4638 MatchedPatterns
.set(p
);
4639 MatchedPredicates
[p
] = Matches
;
4643 for (auto it
: PatternsWithVariants
) {
4644 unsigned i
= it
.first
;
4645 const MultipleUseVarSet
&DepVars
= it
.second
.first
;
4646 const std::vector
<TreePatternNodePtr
> &Variants
= it
.second
.second
;
4648 for (unsigned v
= 0, e
= Variants
.size(); v
!= e
; ++v
) {
4649 TreePatternNodePtr Variant
= Variants
[v
];
4650 BitVector
&Matches
= MatchedPredicates
[i
];
4652 LLVM_DEBUG(errs() << " VAR#" << v
<< ": "; Variant
->dump();
4655 // Scan to see if an instruction or explicit pattern already matches this.
4656 bool AlreadyExists
= false;
4657 for (unsigned p
= 0, e
= PatternsToMatch
.size(); p
!= e
; ++p
) {
4658 // Skip if the top level predicates do not match.
4661 // Check to see if this variant already exists.
4662 if (Variant
->isIsomorphicTo(PatternsToMatch
[p
].getSrcPattern(),
4664 LLVM_DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
4665 AlreadyExists
= true;
4669 // If we already have it, ignore the variant.
4670 if (AlreadyExists
) continue;
4672 // Otherwise, add it to the list of patterns we have.
4673 PatternsToMatch
.push_back(PatternToMatch(
4674 PatternsToMatch
[i
].getSrcRecord(), PatternsToMatch
[i
].getPredicates(),
4675 Variant
, PatternsToMatch
[i
].getDstPatternShared(),
4676 PatternsToMatch
[i
].getDstRegs(),
4677 PatternsToMatch
[i
].getAddedComplexity(), Record::getNewUID()));
4678 MatchedPredicates
.push_back(Matches
);
4680 // Add a new match the same as this pattern.
4681 for (auto &P
: MatchedPredicates
)
4685 LLVM_DEBUG(errs() << "\n");