LLVM 24.0.0git
SLPUtils.h
Go to the documentation of this file.
1//===- SLPUtils.h - SLP Vectorizer free utility helpers --------*- C++ -*-===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// Internal header used by SLPVectorizer.cpp. It declares free helper
10// functions that do not depend on BoUpSLP, InstructionsState, or any other
11// SLP-private type. Splitting them out keeps SLPVectorizer.cpp focused on
12// the build / legality / cost / codegen pipeline.
13//
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_LIB_TRANSFORMS_VECTORIZE_SLPVECTORIZER_SLPUTILS_H
17#define LLVM_LIB_TRANSFORMS_VECTORIZE_SLPVECTORIZER_SLPUTILS_H
18
19#include "llvm/ADT/ArrayRef.h"
23#include "llvm/IR/Intrinsics.h"
24
25#include <optional>
26#include <string>
27
28namespace llvm {
29class Constant;
30class DataLayout;
31class Instruction;
34class Type;
35class Value;
36} // namespace llvm
37
38namespace llvm::slpvectorizer {
39
40/// Limit of the number of uses for potentially transformed instructions/values,
41/// used in checks to avoid compile-time explode.
42inline constexpr int UsesLimit = 64;
43
44/// \returns True if the value is a constant (but not globals/constant
45/// expressions).
46bool isConstant(Value *V);
47
48/// \returns True if \p V is the integer identity constant for binary \p Opcode
49/// (e.g. 0 for add, 1 for mul, all-ones for and). Floating-point identities are
50/// excluded: a ConstantInt never matches the ConstantFP getBinOpIdentity()
51/// returns for FAdd/FMul, whose identity fast-math may break anyway.
52bool isBinOpIdentityConstant(const Value *V, unsigned Opcode);
53
54/// \returns the opcode of the combines emitted for a reassociated node:
55/// subtract chains regroup their positive and negative operand columns with
56/// plain adds.
57unsigned getReassocCombineOpcode(unsigned Opcode);
58
59/// \returns True if \p I can be a link of a flattenable binary chain:
60/// subtracts flatten as adds of a negated leaf, float subtracts need reassoc
61/// to allow the regrouping.
63
64/// Checks if \p V is one of vector-like instructions, i.e. undef,
65/// insertelement/extractelement with constant indices for fixed vector type
66/// or extractvalue instruction.
68
69/// \returns the number of elements for Ty.
70unsigned getNumElements(Type *Ty);
71
72/// Returns power-of-2 number of elements in a single register (part), given
73/// the total number of elements \p Size and number of registers (parts) \p
74/// NumParts.
75unsigned getPartNumElems(unsigned Size, unsigned NumParts);
76
77/// Returns correct remaining number of elements, considering total amount
78/// \p Size, (power-of-2 number) of elements in a single register
79/// \p PartNumElems and current register (part) \p Part.
80unsigned getNumElems(unsigned Size, unsigned PartNumElems, unsigned Part);
81
82#if !defined(NDEBUG)
83/// Print a short descriptor of the instruction bundle suitable for debug
84/// output.
85std::string shortBundleName(ArrayRef<Value *> VL, int Idx = -1);
86#endif
87
88/// \returns True if all of the instructions in \p VL are in the same block.
90
91/// \returns True if all of the values in \p VL are constants (but not
92/// globals/constant expressions).
94
95/// \returns True if all of the values in \p VL are identical or some of them
96/// are UndefValue.
98
99/// Checks if \p LHS and \p RHS are the same intrinsic, or one is llvm.fma
100/// and the other is llvm.fmuladd, since both lower to the same fused
101/// vector operation.
102/// \returns the intrinsic ID to use for the pair (\p RHS if the IDs match,
103/// otherwise Intrinsic::fma), or Intrinsic::not_intrinsic if they are not
104/// equivalent.
106
107/// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
108/// For BinaryOperator, it also checks if \p ValWithUses is used in specific
109/// patterns that make it effectively commutative (like equality comparisons
110/// with zero).
111/// In most cases, users should not call this function directly (since \p I and
112/// \p ValWithUses are the same). However, when analyzing interchangeable
113/// instructions, we need to use the converted opcode along with the original
114/// uses.
115/// \param I The instruction to check for commutativity
116/// \param ValWithUses The value whose uses are analyzed for special
117/// patterns
118bool isCommutative(const Instruction *I, const Value *ValWithUses,
119 bool IsCopyable = false);
120
121/// This is a helper function to check whether \p I is commutative.
122/// This is a convenience wrapper that calls the two-parameter version of
123/// isCommutative with the same instruction for both parameters. This is
124/// the common case where the instruction being checked for commutativity
125/// is the same as the instruction whose uses are analyzed for special
126/// patterns (see the two-parameter version above for details).
127/// \param I The instruction to check for commutativity
128/// \returns true if the instruction is commutative, false otherwise
129bool isCommutative(const Instruction *I);
130
131/// Checks if the operand is commutative. In commutative operations, not all
132/// operands might commutable, e.g. for fmuladd only 2 first operands are
133/// commutable.
134bool isCommutableOperand(const Instruction *I, Value *ValWithUses, unsigned Op,
135 bool IsCopyable = false);
136
137/// \returns number of operands of \p I, considering commutativity. Returns 2
138/// for commutative intrinsics.
139/// \param I The instruction to check for commutativity
141
142/// \returns inserting or extracting index of InsertElement, ExtractElement
143/// or InsertValue instruction, using \p Offset as base offset for index.
144/// \returns std::nullopt if the index is not an immediate.
145std::optional<unsigned> getElementIndex(const Value *Inst, unsigned Offset = 0);
146
147/// \returns True if all of the values in \p VL use the same opcode.
148/// For comparison instructions, also checks if predicates match.
149/// PoisonValues are considered matching. Interchangeable instructions are
150/// not considered.
152
153/// \returns Optional element Idx for Extract{Value,Element} instructions.
154std::optional<unsigned> getExtractIndex(const Instruction *E);
155
156/// Compute the inverse permutation \p Mask of \p Indices.
158
159/// Reorders the list of scalars in accordance with the given \p Mask.
161
162/// \returns True iff every value in \p VL has the same Type as the first.
164
165/// Checks if the provided value does not require scheduling. It does not
166/// require scheduling if this is not an instruction or it is an instruction
167/// that does not read/write memory and all operands are either not
168/// instructions or phi nodes or instructions from different blocks.
170
171/// Checks if the provided value does not require scheduling. It does not
172/// require scheduling if this is not an instruction or it is an instruction
173/// that does not read/write memory and all users are phi nodes or
174/// instructions from different blocks.
176
177/// Checks if the specified value does not require scheduling. It does not
178/// require scheduling if all operands and all users do not need to be
179/// scheduled in the current basic block.
181
182/// Checks if the specified array of instructions does not require scheduling.
183/// It is so if all either instructions have operands that do not require
184/// scheduling or their users do not require scheduling since they are phis or
185/// in other basic blocks.
187
188/// \returns inserting or extracting index of InsertElement / ExtractElement
189/// instruction, using \p Offset as base offset for index. Only instantiated
190/// for InsertElementInst and ExtractElementInst (see SLPUtils.cpp).
191template <typename T>
192std::optional<unsigned> getInsertExtractIndex(const Value *Inst,
193 unsigned Offset);
194
195void transformScalarShuffleIndiciesToVector(unsigned VecTyNumElements,
197
198/// \returns the number of groups of shufflevector
199/// A group has the following features
200/// 1. All of value in a group are shufflevector.
201/// 2. The mask of all shufflevector is isExtractSubvectorMask.
202/// 3. The mask of all shufflevector uses all of the elements of the source.
203/// e.g., it is 1 group (%0)
204/// %1 = shufflevector <16 x i8> %0, <16 x i8> poison,
205/// <8 x i32> <i32 0, i32 1, i32 2, i32 3, i32 4, i32 5, i32 6, i32 7>
206/// %2 = shufflevector <16 x i8> %0, <16 x i8> poison,
207/// <8 x i32> <i32 8, i32 9, i32 10, i32 11, i32 12, i32 13, i32 14, i32 15>
208/// it is 2 groups (%3 and %4)
209/// %5 = shufflevector <8 x i16> %3, <8 x i16> poison,
210/// <4 x i32> <i32 0, i32 1, i32 2, i32 3>
211/// %6 = shufflevector <8 x i16> %3, <8 x i16> poison,
212/// <4 x i32> <i32 4, i32 5, i32 6, i32 7>
213/// %7 = shufflevector <8 x i16> %4, <8 x i16> poison,
214/// <4 x i32> <i32 0, i32 1, i32 2, i32 3>
215/// %8 = shufflevector <8 x i16> %4, <8 x i16> poison,
216/// <4 x i32> <i32 4, i32 5, i32 6, i32 7>
217/// it is 0 group
218/// %12 = shufflevector <8 x i16> %10, <8 x i16> poison,
219/// <4 x i32> <i32 0, i32 1, i32 2, i32 3>
220/// %13 = shufflevector <8 x i16> %11, <8 x i16> poison,
221/// <4 x i32> <i32 0, i32 1, i32 2, i32 3>
223
224/// \returns a shufflevector mask which is used to vectorize shufflevectors
225/// e.g.,
226/// %5 = shufflevector <8 x i16> %3, <8 x i16> poison,
227/// <4 x i32> <i32 0, i32 1, i32 2, i32 3>
228/// %6 = shufflevector <8 x i16> %3, <8 x i16> poison,
229/// <4 x i32> <i32 4, i32 5, i32 6, i32 7>
230/// %7 = shufflevector <8 x i16> %4, <8 x i16> poison,
231/// <4 x i32> <i32 0, i32 1, i32 2, i32 3>
232/// %8 = shufflevector <8 x i16> %4, <8 x i16> poison,
233/// <4 x i32> <i32 4, i32 5, i32 6, i32 7>
234/// the result is
235/// <0, 1, 2, 3, 12, 13, 14, 15, 16, 17, 18, 19, 28, 29, 30, 31>
237
238/// Specifies the way the mask should be analyzed for undefs/poisonous elements
239/// in the shuffle mask.
240enum class UseMask {
241 FirstArg, ///< The mask is expected to be for permutation of 1-2 vectors,
242 ///< check for the mask elements for the first argument (mask
243 ///< indices are in range [0:VF)).
244 SecondArg, ///< The mask is expected to be for permutation of 2 vectors, check
245 ///< for the mask elements for the second argument (mask indices
246 ///< are in range [VF:2*VF))
247 UndefsAsMask ///< Consider undef mask elements (-1) as placeholders for
248 ///< future shuffle elements and mark them as ones as being used
249 ///< in future. Non-undef elements are considered as unused since
250 ///< they're already marked as used in the mask.
251};
252
253/// Prepares a use bitset for the given mask either for the first argument or
254/// for the second.
255SmallBitVector buildUseMask(int VF, ArrayRef<int> Mask, UseMask MaskArg);
256
257/// Checks if the given value is actually an undefined constant vector.
258/// Also, if the \p UseMask is not empty, tries to check if the non-masked
259/// elements actually mask the insertelement buildvector, if any.
260template <bool IsPoisonOnly = false>
262 const SmallBitVector &UseMask = {});
263
264/// \returns True if in-tree use also needs extract. This refers to
265/// possible scalar operand in vectorized instruction.
266bool doesInTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
267 TargetLibraryInfo *TLI,
268 const TargetTransformInfo *TTI);
269
270/// \returns the AA location that is being access by the instruction.
271MemoryLocation getLocation(Instruction *I);
272
273/// \returns True if the instruction is not a volatile or atomic load/store.
274bool isSimple(Instruction *I);
275
276/// Checks if the loads with scalar type \p ScalarTy and pointer operands
277/// \p PointerOps are each (optionally via a constant-offset GEP) a
278/// `select Cond, A, B` picking between the same two base pointers A/B on
279/// every lane - the shape a fully unrolled `x = cond ? A[i] : B[i]` takes. On
280/// success \p TrueBase / \p FalseBase are the candidate bases and
281/// \p Conditions holds each lane's `select` condition, used to build the
282/// blend mask. Lane \p Idx must be at `Base + Idx * sizeof(ScalarTy)`; only
283/// dense, natural lane order starting at the base is recognized (reordered or
284/// partial groups fall back to Gather/Scatter).
285bool isSelectedBaseLoad(Type *ScalarTy, ArrayRef<Value *> PointerOps,
286 const DataLayout &DL, Value *&TrueBase,
287 Value *&FalseBase,
288 SmallVectorImpl<Value *> &Conditions);
289
290/// Shuffles \p Mask in accordance with the given \p SubMask.
291/// \param ExtendingManyInputs Supports reshuffling of the mask with not only
292/// one but two input vectors.
293void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask,
294 bool ExtendingManyInputs = false);
295
296/// Order may have elements assigned special value (size) which is out of
297/// bounds. Such indices only appear on places which correspond to undef values
298/// (see canReuseExtract for details) and used in order to avoid undef values
299/// have effect on operands ordering.
300/// The first loop below simply finds all unused indices and then the next loop
301/// nest assigns these indices for undef values positions.
302/// As an example below Order has two undef positions and they have assigned
303/// values 3 and 7 respectively:
304/// before: 6 9 5 4 9 2 1 0
305/// after: 6 3 5 4 7 2 1 0
307
308/// \returns a bitset for selecting opcodes. false for Opcode0 and true for
309/// Opcode1.
310SmallBitVector getAltInstrMask(ArrayRef<Value *> VL, Type *ScalarTy,
311 unsigned Opcode0, unsigned Opcode1);
312
313/// Replicates the given \p Val \p VF times.
315
316/// \returns the masked division/remainder intrinsic corresponding to \p
317/// Opcode. Disabled lanes of these intrinsics are poison rather than UB,
318/// unlike the plain opcode.
320
321/// Returns true if \p I forms a vectorizable bundle on its own and its single
322/// user does not tear the vector apart. Loads and addresses are excluded: the
323/// tree is built without the users, so it does not pay off the extracts. A
324/// cast, feeding a multi-used cast, is excluded for the same reason, such a
325/// user stays scalar. The fp-to-int conversions move the result to the other
326/// register domain, so the extracts are paid on top of the repacking. The
327/// values, feeding the inserts, are vectorized together with them by the
328/// dedicated attempt.
329bool isOnceUsedSeed(const Instruction *I);
330
331/// If \p V is a single-use fpext of a single-use fptrunc forming a round-trip
332/// back to the type of \p V, returns the fptrunc; the round-trip source is its
333/// operand, always an instruction of the same type as \p V. If
334/// \p MustBeElidable, matches only when the intermediate rounding may be
335/// removed: both casts must allow contraction and the widening cast cannot
336/// produce nan/inf.
337Instruction *lookThroughCastRoundTrip(Value *V, bool MustBeElidable);
338
339} // namespace llvm::slpvectorizer
340
341#endif // LLVM_LIB_TRANSFORMS_VECTORIZE_SLPVECTORIZER_SLPUTILS_H
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define I(x, y, z)
Definition MD5.cpp:57
This file provides utility analysis objects describing memory locations.
This file implements the SmallBitVector class.
This file defines the SmallVector class.
Value * RHS
Value * LHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM Value Representation.
Definition Value.h:75
A private "module" namespace for types and utilities used by this pass.
std::optional< unsigned > getExtractIndex(const Instruction *E)
Definition SLPUtils.cpp:272
bool areAllOperandsNonInsts(Value *V)
Checks if the provided value does not require scheduling.
Definition SLPUtils.cpp:355
std::optional< unsigned > getElementIndex(const Value *Inst, unsigned Offset)
Definition SLPUtils.cpp:226
bool doesInTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst, TargetLibraryInfo *TLI, const TargetTransformInfo *TTI)
Definition SLPUtils.cpp:530
MemoryLocation getLocation(Instruction *I)
Definition SLPUtils.cpp:558
bool isSelectedBaseLoad(Type *ScalarTy, ArrayRef< Value * > PointerOps, const DataLayout &DL, Value *&TrueBase, Value *&FalseBase, SmallVectorImpl< Value * > &Conditions)
Checks if the loads with scalar type ScalarTy and pointer operands PointerOps are each (optionally vi...
Definition SLPUtils.cpp:576
SmallBitVector getAltInstrMask(ArrayRef< Value * > VL, Type *ScalarTy, unsigned Opcode0, unsigned Opcode1)
Definition SLPUtils.cpp:665
SmallBitVector isUndefVector(const Value *V, const SmallBitVector &UseMask)
Checks if the given value is actually an undefined constant vector.
Definition SLPUtils.cpp:480
Intrinsic::ID getMaskedDivRemIntrinsic(unsigned Opcode)
Definition SLPUtils.cpp:688
bool isUsedOutsideBlock(Value *V)
Checks if the provided value does not require scheduling.
Definition SLPUtils.cpp:368
bool doesNotNeedToSchedule(ArrayRef< Value * > VL)
Checks if the specified array of instructions does not require scheduling.
Definition SLPUtils.cpp:386
std::optional< unsigned > getInsertExtractIndex(const Value *Inst, unsigned Offset)
Definition SLPUtils.cpp:322
void reorderScalars(SmallVectorImpl< Value * > &Scalars, ArrayRef< int > Mask)
Reorders the list of scalars in accordance with the given Mask.
Definition SLPUtils.cpp:305
bool allSameType(ArrayRef< Value * > VL)
Definition SLPUtils.cpp:315
bool allSameOpcode(ArrayRef< Value * > VL)
Definition SLPUtils.cpp:254
bool isSplat(ArrayRef< Value * > VL)
Definition SLPUtils.cpp:137
unsigned getNumElements(Type *Ty)
Definition SLPUtils.cpp:82
std::string shortBundleName(ArrayRef< Value * > VL, int Idx)
Print a short descriptor of the instruction bundle suitable for debug output.
Definition SLPUtils.cpp:99
bool isOnceUsedSeed(const Instruction *I)
Returns true if I forms a vectorizable bundle on its own and its single user does not tear the vector...
Definition SLPUtils.cpp:730
unsigned getPartNumElems(unsigned Size, unsigned NumParts)
Returns power-of-2 number of elements in a single register (part), given the total number of elements...
Definition SLPUtils.cpp:90
bool isCommutableOperand(const Instruction *I, Value *ValWithUses, unsigned Op, bool IsCopyable)
Checks if the operand is commutative.
Definition SLPUtils.cpp:198
void transformScalarShuffleIndiciesToVector(unsigned VecTyNumElements, SmallVectorImpl< int > &Mask)
Definition SLPUtils.cpp:391
SmallVector< int > calculateShufflevectorMask(ArrayRef< Value * > VL)
Definition SLPUtils.cpp:446
SmallBitVector buildUseMask(int VF, ArrayRef< int > Mask, UseMask MaskArg)
Prepares a use bitset for the given mask either for the first argument or for the second.
Definition SLPUtils.cpp:463
bool isCommutative(const Instruction *I, const Value *ValWithUses, bool IsCopyable)
Definition SLPUtils.cpp:161
unsigned getNumberOfPotentiallyCommutativeOps(Instruction *I)
Definition SLPUtils.cpp:216
bool allConstant(ArrayRef< Value * > VL)
Definition SLPUtils.cpp:131
void inversePermutation(ArrayRef< unsigned > Indices, SmallVectorImpl< int > &Mask)
Compute the inverse permutation Mask of Indices.
Definition SLPUtils.cpp:296
bool allSameBlock(ArrayRef< Value * > VL)
Definition SLPUtils.cpp:109
bool isReassocChainLink(const Instruction *I)
Definition SLPUtils.cpp:54
Intrinsic::ID isEquivalentIntrinsicID(Intrinsic::ID LHS, Intrinsic::ID RHS)
Checks if LHS and RHS are the same intrinsic, or one is llvm.fma and the other is llvm....
Definition SLPUtils.cpp:152
UseMask
Specifies the way the mask should be analyzed for undefs/poisonous elements in the shuffle mask.
Definition SLPUtils.h:240
@ SecondArg
The mask is expected to be for permutation of 2 vectors, check for the mask elements for the second a...
Definition SLPUtils.h:244
@ UndefsAsMask
Consider undef mask elements (-1) as placeholders for future shuffle elements and mark them as ones a...
Definition SLPUtils.h:247
@ FirstArg
The mask is expected to be for permutation of 1-2 vectors, check for the mask elements for the first ...
Definition SLPUtils.h:241
void addMask(SmallVectorImpl< int > &Mask, ArrayRef< int > SubMask, bool ExtendingManyInputs)
Shuffles Mask in accordance with the given SubMask.
Definition SLPUtils.cpp:616
bool isSimple(Instruction *I)
Definition SLPUtils.cpp:566
Instruction * lookThroughCastRoundTrip(Value *V, bool MustBeElidable)
If V is a single-use fpext of a single-use fptrunc forming a round-trip back to the type of V,...
Definition SLPUtils.cpp:757
bool isBinOpIdentityConstant(const Value *V, unsigned Opcode)
Definition SLPUtils.cpp:38
unsigned getShufflevectorNumGroups(ArrayRef< Value * > VL)
Definition SLPUtils.cpp:406
SmallVector< Constant * > replicateMask(ArrayRef< Constant * > Val, unsigned VF)
Replicates the given Val VF times.
Definition SLPUtils.cpp:679
unsigned getReassocCombineOpcode(unsigned Opcode)
Definition SLPUtils.cpp:43
bool isVectorLikeInstWithConstOps(Value *V)
Checks if V is one of vector-like instructions, i.e.
Definition SLPUtils.cpp:62
bool doesNotNeedToBeScheduled(Value *V)
Checks if the specified value does not require scheduling.
Definition SLPUtils.cpp:382
unsigned getNumElems(unsigned Size, unsigned PartNumElems, unsigned Part)
Returns correct remaining number of elements, considering total amount Size, (power-of-2 number) of e...
Definition SLPUtils.cpp:94
constexpr int UsesLimit
Limit of the number of uses for potentially transformed instructions/values, used in checks to avoid ...
Definition SLPUtils.h:42
bool isConstant(Value *V)
Definition SLPUtils.cpp:34
void fixupOrderingIndices(MutableArrayRef< unsigned > Order)
Order may have elements assigned special value (size) which is out of bounds.
Definition SLPUtils.cpp:641
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:578
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
TargetTransformInfo TTI
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >