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/// Checks if \p V is one of vector-like instructions, i.e. undef,
55/// insertelement/extractelement with constant indices for fixed vector type
56/// or extractvalue instruction.
58
59/// \returns the number of elements for Ty.
60unsigned getNumElements(Type *Ty);
61
62/// Returns power-of-2 number of elements in a single register (part), given
63/// the total number of elements \p Size and number of registers (parts) \p
64/// NumParts.
65unsigned getPartNumElems(unsigned Size, unsigned NumParts);
66
67/// Returns correct remaining number of elements, considering total amount
68/// \p Size, (power-of-2 number) of elements in a single register
69/// \p PartNumElems and current register (part) \p Part.
70unsigned getNumElems(unsigned Size, unsigned PartNumElems, unsigned Part);
71
72#if !defined(NDEBUG)
73/// Print a short descriptor of the instruction bundle suitable for debug
74/// output.
75std::string shortBundleName(ArrayRef<Value *> VL, int Idx = -1);
76#endif
77
78/// \returns True if all of the instructions in \p VL are in the same block.
80
81/// \returns True if all of the values in \p VL are constants (but not
82/// globals/constant expressions).
84
85/// \returns True if all of the values in \p VL are identical or some of them
86/// are UndefValue.
88
89/// Checks if \p LHS and \p RHS are the same intrinsic, or one is llvm.fma
90/// and the other is llvm.fmuladd, since both lower to the same fused
91/// vector operation.
92/// \returns the intrinsic ID to use for the pair (\p RHS if the IDs match,
93/// otherwise Intrinsic::fma), or Intrinsic::not_intrinsic if they are not
94/// equivalent.
96
97/// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
98/// For BinaryOperator, it also checks if \p ValWithUses is used in specific
99/// patterns that make it effectively commutative (like equality comparisons
100/// with zero).
101/// In most cases, users should not call this function directly (since \p I and
102/// \p ValWithUses are the same). However, when analyzing interchangeable
103/// instructions, we need to use the converted opcode along with the original
104/// uses.
105/// \param I The instruction to check for commutativity
106/// \param ValWithUses The value whose uses are analyzed for special
107/// patterns
108bool isCommutative(const Instruction *I, const Value *ValWithUses,
109 bool IsCopyable = false);
110
111/// This is a helper function to check whether \p I is commutative.
112/// This is a convenience wrapper that calls the two-parameter version of
113/// isCommutative with the same instruction for both parameters. This is
114/// the common case where the instruction being checked for commutativity
115/// is the same as the instruction whose uses are analyzed for special
116/// patterns (see the two-parameter version above for details).
117/// \param I The instruction to check for commutativity
118/// \returns true if the instruction is commutative, false otherwise
119bool isCommutative(const Instruction *I);
120
121/// Checks if the operand is commutative. In commutative operations, not all
122/// operands might commutable, e.g. for fmuladd only 2 first operands are
123/// commutable.
124bool isCommutableOperand(const Instruction *I, Value *ValWithUses, unsigned Op,
125 bool IsCopyable = false);
126
127/// \returns number of operands of \p I, considering commutativity. Returns 2
128/// for commutative intrinsics.
129/// \param I The instruction to check for commutativity
131
132/// \returns inserting or extracting index of InsertElement, ExtractElement
133/// or InsertValue instruction, using \p Offset as base offset for index.
134/// \returns std::nullopt if the index is not an immediate.
135std::optional<unsigned> getElementIndex(const Value *Inst, unsigned Offset = 0);
136
137/// \returns True if all of the values in \p VL use the same opcode.
138/// For comparison instructions, also checks if predicates match.
139/// PoisonValues are considered matching. Interchangeable instructions are
140/// not considered.
142
143/// \returns Optional element Idx for Extract{Value,Element} instructions.
144std::optional<unsigned> getExtractIndex(const Instruction *E);
145
146/// Compute the inverse permutation \p Mask of \p Indices.
148
149/// Reorders the list of scalars in accordance with the given \p Mask.
151
152/// \returns True iff every value in \p VL has the same Type as the first.
154
155/// Checks if the provided value does not require scheduling. It does not
156/// require scheduling if this is not an instruction or it is an instruction
157/// that does not read/write memory and all operands are either not
158/// instructions or phi nodes or instructions from different blocks.
160
161/// Checks if the provided value does not require scheduling. It does not
162/// require scheduling if this is not an instruction or it is an instruction
163/// that does not read/write memory and all users are phi nodes or
164/// instructions from different blocks.
166
167/// Checks if the specified value does not require scheduling. It does not
168/// require scheduling if all operands and all users do not need to be
169/// scheduled in the current basic block.
171
172/// Checks if the specified array of instructions does not require scheduling.
173/// It is so if all either instructions have operands that do not require
174/// scheduling or their users do not require scheduling since they are phis or
175/// in other basic blocks.
177
178/// \returns inserting or extracting index of InsertElement / ExtractElement
179/// instruction, using \p Offset as base offset for index. Only instantiated
180/// for InsertElementInst and ExtractElementInst (see SLPUtils.cpp).
181template <typename T>
182std::optional<unsigned> getInsertExtractIndex(const Value *Inst,
183 unsigned Offset);
184
185void transformScalarShuffleIndiciesToVector(unsigned VecTyNumElements,
187
188/// \returns the number of groups of shufflevector
189/// A group has the following features
190/// 1. All of value in a group are shufflevector.
191/// 2. The mask of all shufflevector is isExtractSubvectorMask.
192/// 3. The mask of all shufflevector uses all of the elements of the source.
193/// e.g., it is 1 group (%0)
194/// %1 = shufflevector <16 x i8> %0, <16 x i8> poison,
195/// <8 x i32> <i32 0, i32 1, i32 2, i32 3, i32 4, i32 5, i32 6, i32 7>
196/// %2 = shufflevector <16 x i8> %0, <16 x i8> poison,
197/// <8 x i32> <i32 8, i32 9, i32 10, i32 11, i32 12, i32 13, i32 14, i32 15>
198/// it is 2 groups (%3 and %4)
199/// %5 = shufflevector <8 x i16> %3, <8 x i16> poison,
200/// <4 x i32> <i32 0, i32 1, i32 2, i32 3>
201/// %6 = shufflevector <8 x i16> %3, <8 x i16> poison,
202/// <4 x i32> <i32 4, i32 5, i32 6, i32 7>
203/// %7 = shufflevector <8 x i16> %4, <8 x i16> poison,
204/// <4 x i32> <i32 0, i32 1, i32 2, i32 3>
205/// %8 = shufflevector <8 x i16> %4, <8 x i16> poison,
206/// <4 x i32> <i32 4, i32 5, i32 6, i32 7>
207/// it is 0 group
208/// %12 = shufflevector <8 x i16> %10, <8 x i16> poison,
209/// <4 x i32> <i32 0, i32 1, i32 2, i32 3>
210/// %13 = shufflevector <8 x i16> %11, <8 x i16> poison,
211/// <4 x i32> <i32 0, i32 1, i32 2, i32 3>
213
214/// \returns a shufflevector mask which is used to vectorize shufflevectors
215/// e.g.,
216/// %5 = shufflevector <8 x i16> %3, <8 x i16> poison,
217/// <4 x i32> <i32 0, i32 1, i32 2, i32 3>
218/// %6 = shufflevector <8 x i16> %3, <8 x i16> poison,
219/// <4 x i32> <i32 4, i32 5, i32 6, i32 7>
220/// %7 = shufflevector <8 x i16> %4, <8 x i16> poison,
221/// <4 x i32> <i32 0, i32 1, i32 2, i32 3>
222/// %8 = shufflevector <8 x i16> %4, <8 x i16> poison,
223/// <4 x i32> <i32 4, i32 5, i32 6, i32 7>
224/// the result is
225/// <0, 1, 2, 3, 12, 13, 14, 15, 16, 17, 18, 19, 28, 29, 30, 31>
227
228/// Specifies the way the mask should be analyzed for undefs/poisonous elements
229/// in the shuffle mask.
230enum class UseMask {
231 FirstArg, ///< The mask is expected to be for permutation of 1-2 vectors,
232 ///< check for the mask elements for the first argument (mask
233 ///< indices are in range [0:VF)).
234 SecondArg, ///< The mask is expected to be for permutation of 2 vectors, check
235 ///< for the mask elements for the second argument (mask indices
236 ///< are in range [VF:2*VF))
237 UndefsAsMask ///< Consider undef mask elements (-1) as placeholders for
238 ///< future shuffle elements and mark them as ones as being used
239 ///< in future. Non-undef elements are considered as unused since
240 ///< they're already marked as used in the mask.
241};
242
243/// Prepares a use bitset for the given mask either for the first argument or
244/// for the second.
245SmallBitVector buildUseMask(int VF, ArrayRef<int> Mask, UseMask MaskArg);
246
247/// Checks if the given value is actually an undefined constant vector.
248/// Also, if the \p UseMask is not empty, tries to check if the non-masked
249/// elements actually mask the insertelement buildvector, if any.
250template <bool IsPoisonOnly = false>
252 const SmallBitVector &UseMask = {});
253
254/// \returns True if in-tree use also needs extract. This refers to
255/// possible scalar operand in vectorized instruction.
256bool doesInTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
257 TargetLibraryInfo *TLI,
258 const TargetTransformInfo *TTI);
259
260/// \returns the AA location that is being access by the instruction.
261MemoryLocation getLocation(Instruction *I);
262
263/// \returns True if the instruction is not a volatile or atomic load/store.
264bool isSimple(Instruction *I);
265
266/// Checks if the loads with scalar type \p ScalarTy and pointer operands
267/// \p PointerOps are each (optionally via a constant-offset GEP) a
268/// `select Cond, A, B` picking between the same two base pointers A/B on
269/// every lane - the shape a fully unrolled `x = cond ? A[i] : B[i]` takes. On
270/// success \p TrueBase / \p FalseBase are the candidate bases and
271/// \p Conditions holds each lane's `select` condition, used to build the
272/// blend mask. Lane \p Idx must be at `Base + Idx * sizeof(ScalarTy)`; only
273/// dense, natural lane order starting at the base is recognized (reordered or
274/// partial groups fall back to Gather/Scatter).
275bool isSelectedBaseLoad(Type *ScalarTy, ArrayRef<Value *> PointerOps,
276 const DataLayout &DL, Value *&TrueBase,
277 Value *&FalseBase,
278 SmallVectorImpl<Value *> &Conditions);
279
280/// Shuffles \p Mask in accordance with the given \p SubMask.
281/// \param ExtendingManyInputs Supports reshuffling of the mask with not only
282/// one but two input vectors.
283void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask,
284 bool ExtendingManyInputs = false);
285
286/// Order may have elements assigned special value (size) which is out of
287/// bounds. Such indices only appear on places which correspond to undef values
288/// (see canReuseExtract for details) and used in order to avoid undef values
289/// have effect on operands ordering.
290/// The first loop below simply finds all unused indices and then the next loop
291/// nest assigns these indices for undef values positions.
292/// As an example below Order has two undef positions and they have assigned
293/// values 3 and 7 respectively:
294/// before: 6 9 5 4 9 2 1 0
295/// after: 6 3 5 4 7 2 1 0
297
298/// \returns a bitset for selecting opcodes. false for Opcode0 and true for
299/// Opcode1.
300SmallBitVector getAltInstrMask(ArrayRef<Value *> VL, Type *ScalarTy,
301 unsigned Opcode0, unsigned Opcode1);
302
303/// Replicates the given \p Val \p VF times.
305
306/// \returns the masked division/remainder intrinsic corresponding to \p
307/// Opcode. Disabled lanes of these intrinsics are poison rather than UB,
308/// unlike the plain opcode.
310
311} // namespace llvm::slpvectorizer
312
313#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:253
bool areAllOperandsNonInsts(Value *V)
Checks if the provided value does not require scheduling.
Definition SLPUtils.cpp:336
std::optional< unsigned > getElementIndex(const Value *Inst, unsigned Offset)
Definition SLPUtils.cpp:207
bool doesInTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst, TargetLibraryInfo *TLI, const TargetTransformInfo *TTI)
Definition SLPUtils.cpp:511
MemoryLocation getLocation(Instruction *I)
Definition SLPUtils.cpp:539
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:557
SmallBitVector getAltInstrMask(ArrayRef< Value * > VL, Type *ScalarTy, unsigned Opcode0, unsigned Opcode1)
Definition SLPUtils.cpp:646
SmallBitVector isUndefVector(const Value *V, const SmallBitVector &UseMask)
Checks if the given value is actually an undefined constant vector.
Definition SLPUtils.cpp:461
Intrinsic::ID getMaskedDivRemIntrinsic(unsigned Opcode)
Definition SLPUtils.cpp:669
bool isUsedOutsideBlock(Value *V)
Checks if the provided value does not require scheduling.
Definition SLPUtils.cpp:349
bool doesNotNeedToSchedule(ArrayRef< Value * > VL)
Checks if the specified array of instructions does not require scheduling.
Definition SLPUtils.cpp:367
std::optional< unsigned > getInsertExtractIndex(const Value *Inst, unsigned Offset)
Definition SLPUtils.cpp:303
void reorderScalars(SmallVectorImpl< Value * > &Scalars, ArrayRef< int > Mask)
Reorders the list of scalars in accordance with the given Mask.
Definition SLPUtils.cpp:286
bool allSameType(ArrayRef< Value * > VL)
Definition SLPUtils.cpp:296
bool allSameOpcode(ArrayRef< Value * > VL)
Definition SLPUtils.cpp:235
bool isSplat(ArrayRef< Value * > VL)
Definition SLPUtils.cpp:118
unsigned getNumElements(Type *Ty)
Definition SLPUtils.cpp:63
std::string shortBundleName(ArrayRef< Value * > VL, int Idx)
Print a short descriptor of the instruction bundle suitable for debug output.
Definition SLPUtils.cpp:80
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:71
bool isCommutableOperand(const Instruction *I, Value *ValWithUses, unsigned Op, bool IsCopyable)
Checks if the operand is commutative.
Definition SLPUtils.cpp:179
void transformScalarShuffleIndiciesToVector(unsigned VecTyNumElements, SmallVectorImpl< int > &Mask)
Definition SLPUtils.cpp:372
SmallVector< int > calculateShufflevectorMask(ArrayRef< Value * > VL)
Definition SLPUtils.cpp:427
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:444
bool isCommutative(const Instruction *I, const Value *ValWithUses, bool IsCopyable)
Definition SLPUtils.cpp:142
unsigned getNumberOfPotentiallyCommutativeOps(Instruction *I)
Definition SLPUtils.cpp:197
bool allConstant(ArrayRef< Value * > VL)
Definition SLPUtils.cpp:112
void inversePermutation(ArrayRef< unsigned > Indices, SmallVectorImpl< int > &Mask)
Compute the inverse permutation Mask of Indices.
Definition SLPUtils.cpp:277
bool allSameBlock(ArrayRef< Value * > VL)
Definition SLPUtils.cpp:90
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:133
UseMask
Specifies the way the mask should be analyzed for undefs/poisonous elements in the shuffle mask.
Definition SLPUtils.h:230
@ SecondArg
The mask is expected to be for permutation of 2 vectors, check for the mask elements for the second a...
Definition SLPUtils.h:234
@ UndefsAsMask
Consider undef mask elements (-1) as placeholders for future shuffle elements and mark them as ones a...
Definition SLPUtils.h:237
@ FirstArg
The mask is expected to be for permutation of 1-2 vectors, check for the mask elements for the first ...
Definition SLPUtils.h:231
void addMask(SmallVectorImpl< int > &Mask, ArrayRef< int > SubMask, bool ExtendingManyInputs)
Shuffles Mask in accordance with the given SubMask.
Definition SLPUtils.cpp:597
bool isSimple(Instruction *I)
Definition SLPUtils.cpp:547
bool isBinOpIdentityConstant(const Value *V, unsigned Opcode)
Definition SLPUtils.cpp:38
unsigned getShufflevectorNumGroups(ArrayRef< Value * > VL)
Definition SLPUtils.cpp:387
SmallVector< Constant * > replicateMask(ArrayRef< Constant * > Val, unsigned VF)
Replicates the given Val VF times.
Definition SLPUtils.cpp:660
bool isVectorLikeInstWithConstOps(Value *V)
Checks if V is one of vector-like instructions, i.e.
Definition SLPUtils.cpp:43
bool doesNotNeedToBeScheduled(Value *V)
Checks if the specified value does not require scheduling.
Definition SLPUtils.cpp:363
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:75
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:622
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 >