1 //===----------- VectorUtils.cpp - Vectorizer utility functions -----------===//
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 defines vectorizer utilities.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/Analysis/VectorUtils.h"
14 #include "llvm/ADT/EquivalenceClasses.h"
15 #include "llvm/Analysis/DemandedBits.h"
16 #include "llvm/Analysis/LoopInfo.h"
17 #include "llvm/Analysis/LoopIterator.h"
18 #include "llvm/Analysis/ScalarEvolution.h"
19 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
20 #include "llvm/Analysis/TargetTransformInfo.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/IRBuilder.h"
24 #include "llvm/IR/PatternMatch.h"
25 #include "llvm/IR/Value.h"
26 #include "llvm/Support/CommandLine.h"
28 #define DEBUG_TYPE "vectorutils"
31 using namespace llvm::PatternMatch
;
33 /// Maximum factor for an interleaved memory access.
34 static cl::opt
<unsigned> MaxInterleaveGroupFactor(
35 "max-interleave-group-factor", cl::Hidden
,
36 cl::desc("Maximum factor for an interleaved access group (default = 8)"),
39 /// Return true if all of the intrinsic's arguments and return type are scalars
40 /// for the scalar form of the intrinsic, and vectors for the vector form of the
41 /// intrinsic (except operands that are marked as always being scalar by
42 /// isVectorIntrinsicWithScalarOpAtArg).
43 bool llvm::isTriviallyVectorizable(Intrinsic::ID ID
) {
45 case Intrinsic::abs
: // Begin integer bit-manipulation.
46 case Intrinsic::bswap
:
47 case Intrinsic::bitreverse
:
48 case Intrinsic::ctpop
:
57 case Intrinsic::sadd_sat
:
58 case Intrinsic::ssub_sat
:
59 case Intrinsic::uadd_sat
:
60 case Intrinsic::usub_sat
:
61 case Intrinsic::smul_fix
:
62 case Intrinsic::smul_fix_sat
:
63 case Intrinsic::umul_fix
:
64 case Intrinsic::umul_fix_sat
:
65 case Intrinsic::sqrt
: // Begin floating-point.
71 case Intrinsic::log10
:
74 case Intrinsic::minnum
:
75 case Intrinsic::maxnum
:
76 case Intrinsic::minimum
:
77 case Intrinsic::maximum
:
78 case Intrinsic::copysign
:
79 case Intrinsic::floor
:
81 case Intrinsic::trunc
:
83 case Intrinsic::nearbyint
:
84 case Intrinsic::round
:
85 case Intrinsic::roundeven
:
88 case Intrinsic::fmuladd
:
89 case Intrinsic::is_fpclass
:
91 case Intrinsic::canonicalize
:
92 case Intrinsic::fptosi_sat
:
93 case Intrinsic::fptoui_sat
:
100 /// Identifies if the vector form of the intrinsic has a scalar operand.
101 bool llvm::isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID
,
102 unsigned ScalarOpdIdx
) {
105 case Intrinsic::ctlz
:
106 case Intrinsic::cttz
:
107 case Intrinsic::is_fpclass
:
108 case Intrinsic::powi
:
109 return (ScalarOpdIdx
== 1);
110 case Intrinsic::smul_fix
:
111 case Intrinsic::smul_fix_sat
:
112 case Intrinsic::umul_fix
:
113 case Intrinsic::umul_fix_sat
:
114 return (ScalarOpdIdx
== 2);
120 bool llvm::isVectorIntrinsicWithOverloadTypeAtArg(Intrinsic::ID ID
,
123 case Intrinsic::fptosi_sat
:
124 case Intrinsic::fptoui_sat
:
125 return OpdIdx
== -1 || OpdIdx
== 0;
126 case Intrinsic::is_fpclass
:
128 case Intrinsic::powi
:
129 return OpdIdx
== -1 || OpdIdx
== 1;
135 /// Returns intrinsic ID for call.
136 /// For the input call instruction it finds mapping intrinsic and returns
137 /// its ID, in case it does not found it return not_intrinsic.
138 Intrinsic::ID
llvm::getVectorIntrinsicIDForCall(const CallInst
*CI
,
139 const TargetLibraryInfo
*TLI
) {
140 Intrinsic::ID ID
= getIntrinsicForCallSite(*CI
, TLI
);
141 if (ID
== Intrinsic::not_intrinsic
)
142 return Intrinsic::not_intrinsic
;
144 if (isTriviallyVectorizable(ID
) || ID
== Intrinsic::lifetime_start
||
145 ID
== Intrinsic::lifetime_end
|| ID
== Intrinsic::assume
||
146 ID
== Intrinsic::experimental_noalias_scope_decl
||
147 ID
== Intrinsic::sideeffect
|| ID
== Intrinsic::pseudoprobe
)
149 return Intrinsic::not_intrinsic
;
152 /// Given a vector and an element number, see if the scalar value is
153 /// already around as a register, for example if it were inserted then extracted
155 Value
*llvm::findScalarElement(Value
*V
, unsigned EltNo
) {
156 assert(V
->getType()->isVectorTy() && "Not looking at a vector?");
157 VectorType
*VTy
= cast
<VectorType
>(V
->getType());
158 // For fixed-length vector, return undef for out of range access.
159 if (auto *FVTy
= dyn_cast
<FixedVectorType
>(VTy
)) {
160 unsigned Width
= FVTy
->getNumElements();
162 return UndefValue::get(FVTy
->getElementType());
165 if (Constant
*C
= dyn_cast
<Constant
>(V
))
166 return C
->getAggregateElement(EltNo
);
168 if (InsertElementInst
*III
= dyn_cast
<InsertElementInst
>(V
)) {
169 // If this is an insert to a variable element, we don't know what it is.
170 if (!isa
<ConstantInt
>(III
->getOperand(2)))
172 unsigned IIElt
= cast
<ConstantInt
>(III
->getOperand(2))->getZExtValue();
174 // If this is an insert to the element we are looking for, return the
177 return III
->getOperand(1);
179 // Guard against infinite loop on malformed, unreachable IR.
180 if (III
== III
->getOperand(0))
183 // Otherwise, the insertelement doesn't modify the value, recurse on its
185 return findScalarElement(III
->getOperand(0), EltNo
);
188 ShuffleVectorInst
*SVI
= dyn_cast
<ShuffleVectorInst
>(V
);
189 // Restrict the following transformation to fixed-length vector.
190 if (SVI
&& isa
<FixedVectorType
>(SVI
->getType())) {
192 cast
<FixedVectorType
>(SVI
->getOperand(0)->getType())->getNumElements();
193 int InEl
= SVI
->getMaskValue(EltNo
);
195 return UndefValue::get(VTy
->getElementType());
196 if (InEl
< (int)LHSWidth
)
197 return findScalarElement(SVI
->getOperand(0), InEl
);
198 return findScalarElement(SVI
->getOperand(1), InEl
- LHSWidth
);
201 // Extract a value from a vector add operation with a constant zero.
202 // TODO: Use getBinOpIdentity() to generalize this.
203 Value
*Val
; Constant
*C
;
204 if (match(V
, m_Add(m_Value(Val
), m_Constant(C
))))
205 if (Constant
*Elt
= C
->getAggregateElement(EltNo
))
206 if (Elt
->isNullValue())
207 return findScalarElement(Val
, EltNo
);
209 // If the vector is a splat then we can trivially find the scalar element.
210 if (isa
<ScalableVectorType
>(VTy
))
211 if (Value
*Splat
= getSplatValue(V
))
212 if (EltNo
< VTy
->getElementCount().getKnownMinValue())
215 // Otherwise, we don't know.
219 int llvm::getSplatIndex(ArrayRef
<int> Mask
) {
222 // Ignore invalid (undefined) mask elements.
226 // There can be only 1 non-negative mask element value if this is a splat.
227 if (SplatIndex
!= -1 && SplatIndex
!= M
)
230 // Initialize the splat index to the 1st non-negative mask element.
233 assert((SplatIndex
== -1 || SplatIndex
>= 0) && "Negative index?");
237 /// Get splat value if the input is a splat vector or return nullptr.
238 /// This function is not fully general. It checks only 2 cases:
239 /// the input value is (1) a splat constant vector or (2) a sequence
240 /// of instructions that broadcasts a scalar at element 0.
241 Value
*llvm::getSplatValue(const Value
*V
) {
242 if (isa
<VectorType
>(V
->getType()))
243 if (auto *C
= dyn_cast
<Constant
>(V
))
244 return C
->getSplatValue();
246 // shuf (inselt ?, Splat, 0), ?, <0, undef, 0, ...>
249 m_Shuffle(m_InsertElt(m_Value(), m_Value(Splat
), m_ZeroInt()),
250 m_Value(), m_ZeroMask())))
256 bool llvm::isSplatValue(const Value
*V
, int Index
, unsigned Depth
) {
257 assert(Depth
<= MaxAnalysisRecursionDepth
&& "Limit Search Depth");
259 if (isa
<VectorType
>(V
->getType())) {
260 if (isa
<UndefValue
>(V
))
262 // FIXME: We can allow undefs, but if Index was specified, we may want to
263 // check that the constant is defined at that index.
264 if (auto *C
= dyn_cast
<Constant
>(V
))
265 return C
->getSplatValue() != nullptr;
268 if (auto *Shuf
= dyn_cast
<ShuffleVectorInst
>(V
)) {
269 // FIXME: We can safely allow undefs here. If Index was specified, we will
270 // check that the mask elt is defined at the required index.
271 if (!all_equal(Shuf
->getShuffleMask()))
278 // Match a specific element. The mask should be defined at and match the
280 return Shuf
->getMaskValue(Index
) == Index
;
283 // The remaining tests are all recursive, so bail out if we hit the limit.
284 if (Depth
++ == MaxAnalysisRecursionDepth
)
287 // If both operands of a binop are splats, the result is a splat.
289 if (match(V
, m_BinOp(m_Value(X
), m_Value(Y
))))
290 return isSplatValue(X
, Index
, Depth
) && isSplatValue(Y
, Index
, Depth
);
292 // If all operands of a select are splats, the result is a splat.
293 if (match(V
, m_Select(m_Value(X
), m_Value(Y
), m_Value(Z
))))
294 return isSplatValue(X
, Index
, Depth
) && isSplatValue(Y
, Index
, Depth
) &&
295 isSplatValue(Z
, Index
, Depth
);
297 // TODO: Add support for unary ops (fneg), casts, intrinsics (overflow ops).
302 bool llvm::getShuffleDemandedElts(int SrcWidth
, ArrayRef
<int> Mask
,
303 const APInt
&DemandedElts
, APInt
&DemandedLHS
,
304 APInt
&DemandedRHS
, bool AllowUndefElts
) {
305 DemandedLHS
= DemandedRHS
= APInt::getZero(SrcWidth
);
307 // Early out if we don't demand any elements.
308 if (DemandedElts
.isZero())
311 // Simple case of a shuffle with zeroinitializer.
312 if (all_of(Mask
, [](int Elt
) { return Elt
== 0; })) {
313 DemandedLHS
.setBit(0);
317 for (unsigned I
= 0, E
= Mask
.size(); I
!= E
; ++I
) {
319 assert((-1 <= M
) && (M
< (SrcWidth
* 2)) &&
320 "Invalid shuffle mask constant");
322 if (!DemandedElts
[I
] || (AllowUndefElts
&& (M
< 0)))
325 // For undef elements, we don't know anything about the common state of
326 // the shuffle result.
331 DemandedLHS
.setBit(M
);
333 DemandedRHS
.setBit(M
- SrcWidth
);
339 void llvm::narrowShuffleMaskElts(int Scale
, ArrayRef
<int> Mask
,
340 SmallVectorImpl
<int> &ScaledMask
) {
341 assert(Scale
> 0 && "Unexpected scaling factor");
343 // Fast-path: if no scaling, then it is just a copy.
345 ScaledMask
.assign(Mask
.begin(), Mask
.end());
350 for (int MaskElt
: Mask
) {
352 assert(((uint64_t)Scale
* MaskElt
+ (Scale
- 1)) <= INT32_MAX
&&
353 "Overflowed 32-bits");
355 for (int SliceElt
= 0; SliceElt
!= Scale
; ++SliceElt
)
356 ScaledMask
.push_back(MaskElt
< 0 ? MaskElt
: Scale
* MaskElt
+ SliceElt
);
360 bool llvm::widenShuffleMaskElts(int Scale
, ArrayRef
<int> Mask
,
361 SmallVectorImpl
<int> &ScaledMask
) {
362 assert(Scale
> 0 && "Unexpected scaling factor");
364 // Fast-path: if no scaling, then it is just a copy.
366 ScaledMask
.assign(Mask
.begin(), Mask
.end());
370 // We must map the original elements down evenly to a type with less elements.
371 int NumElts
= Mask
.size();
372 if (NumElts
% Scale
!= 0)
376 ScaledMask
.reserve(NumElts
/ Scale
);
378 // Step through the input mask by splitting into Scale-sized slices.
380 ArrayRef
<int> MaskSlice
= Mask
.take_front(Scale
);
381 assert((int)MaskSlice
.size() == Scale
&& "Expected Scale-sized slice.");
383 // The first element of the slice determines how we evaluate this slice.
384 int SliceFront
= MaskSlice
.front();
385 if (SliceFront
< 0) {
386 // Negative values (undef or other "sentinel" values) must be equal across
388 if (!all_equal(MaskSlice
))
390 ScaledMask
.push_back(SliceFront
);
392 // A positive mask element must be cleanly divisible.
393 if (SliceFront
% Scale
!= 0)
395 // Elements of the slice must be consecutive.
396 for (int i
= 1; i
< Scale
; ++i
)
397 if (MaskSlice
[i
] != SliceFront
+ i
)
399 ScaledMask
.push_back(SliceFront
/ Scale
);
401 Mask
= Mask
.drop_front(Scale
);
402 } while (!Mask
.empty());
404 assert((int)ScaledMask
.size() * Scale
== NumElts
&& "Unexpected scaled mask");
406 // All elements of the original mask can be scaled down to map to the elements
407 // of a mask with wider elements.
411 void llvm::getShuffleMaskWithWidestElts(ArrayRef
<int> Mask
,
412 SmallVectorImpl
<int> &ScaledMask
) {
413 std::array
<SmallVector
<int, 16>, 2> TmpMasks
;
414 SmallVectorImpl
<int> *Output
= &TmpMasks
[0], *Tmp
= &TmpMasks
[1];
415 ArrayRef
<int> InputMask
= Mask
;
416 for (unsigned Scale
= 2; Scale
<= InputMask
.size(); ++Scale
) {
417 while (widenShuffleMaskElts(Scale
, InputMask
, *Output
)) {
419 std::swap(Output
, Tmp
);
422 ScaledMask
.assign(InputMask
.begin(), InputMask
.end());
425 void llvm::processShuffleMasks(
426 ArrayRef
<int> Mask
, unsigned NumOfSrcRegs
, unsigned NumOfDestRegs
,
427 unsigned NumOfUsedRegs
, function_ref
<void()> NoInputAction
,
428 function_ref
<void(ArrayRef
<int>, unsigned, unsigned)> SingleInputAction
,
429 function_ref
<void(ArrayRef
<int>, unsigned, unsigned)> ManyInputsAction
) {
430 SmallVector
<SmallVector
<SmallVector
<int>>> Res(NumOfDestRegs
);
431 // Try to perform better estimation of the permutation.
432 // 1. Split the source/destination vectors into real registers.
433 // 2. Do the mask analysis to identify which real registers are
435 int Sz
= Mask
.size();
436 unsigned SzDest
= Sz
/ NumOfDestRegs
;
437 unsigned SzSrc
= Sz
/ NumOfSrcRegs
;
438 for (unsigned I
= 0; I
< NumOfDestRegs
; ++I
) {
439 auto &RegMasks
= Res
[I
];
440 RegMasks
.assign(NumOfSrcRegs
, {});
441 // Check that the values in dest registers are in the one src
443 for (unsigned K
= 0; K
< SzDest
; ++K
) {
444 int Idx
= I
* SzDest
+ K
;
447 if (Mask
[Idx
] >= Sz
|| Mask
[Idx
] == PoisonMaskElem
)
449 int SrcRegIdx
= Mask
[Idx
] / SzSrc
;
450 // Add a cost of PermuteTwoSrc for each new source register permute,
451 // if we have more than one source registers.
452 if (RegMasks
[SrcRegIdx
].empty())
453 RegMasks
[SrcRegIdx
].assign(SzDest
, PoisonMaskElem
);
454 RegMasks
[SrcRegIdx
][K
] = Mask
[Idx
] % SzSrc
;
457 // Process split mask.
458 for (unsigned I
= 0; I
< NumOfUsedRegs
; ++I
) {
461 count_if(Dest
, [](ArrayRef
<int> Mask
) { return !Mask
.empty(); });
462 switch (NumSrcRegs
) {
464 // No input vectors were used!
468 // Find the only mask with at least single undef mask elem.
470 find_if(Dest
, [](ArrayRef
<int> Mask
) { return !Mask
.empty(); });
471 unsigned SrcReg
= std::distance(Dest
.begin(), It
);
472 SingleInputAction(*It
, SrcReg
, I
);
476 // The first mask is a permutation of a single register. Since we have >2
477 // input registers to shuffle, we merge the masks for 2 first registers
478 // and generate a shuffle of 2 registers rather than the reordering of the
479 // first register and then shuffle with the second register. Next,
480 // generate the shuffles of the resulting register + the remaining
481 // registers from the list.
482 auto &&CombineMasks
= [](MutableArrayRef
<int> FirstMask
,
483 ArrayRef
<int> SecondMask
) {
484 for (int Idx
= 0, VF
= FirstMask
.size(); Idx
< VF
; ++Idx
) {
485 if (SecondMask
[Idx
] != PoisonMaskElem
) {
486 assert(FirstMask
[Idx
] == PoisonMaskElem
&&
487 "Expected undefined mask element.");
488 FirstMask
[Idx
] = SecondMask
[Idx
] + VF
;
492 auto &&NormalizeMask
= [](MutableArrayRef
<int> Mask
) {
493 for (int Idx
= 0, VF
= Mask
.size(); Idx
< VF
; ++Idx
) {
494 if (Mask
[Idx
] != PoisonMaskElem
)
502 MutableArrayRef
<int> FirstMask
, SecondMask
;
503 for (unsigned I
= 0; I
< NumOfDestRegs
; ++I
) {
504 SmallVectorImpl
<int> &RegMask
= Dest
[I
];
508 if (FirstIdx
== SecondIdx
) {
514 SecondMask
= RegMask
;
515 CombineMasks(FirstMask
, SecondMask
);
516 ManyInputsAction(FirstMask
, FirstIdx
, SecondIdx
);
517 NormalizeMask(FirstMask
);
519 SecondMask
= FirstMask
;
520 SecondIdx
= FirstIdx
;
522 if (FirstIdx
!= SecondIdx
&& SecondIdx
>= 0) {
523 CombineMasks(SecondMask
, FirstMask
);
524 ManyInputsAction(SecondMask
, SecondIdx
, FirstIdx
);
525 Dest
[FirstIdx
].clear();
526 NormalizeMask(SecondMask
);
528 } while (SecondIdx
>= 0);
535 MapVector
<Instruction
*, uint64_t>
536 llvm::computeMinimumValueSizes(ArrayRef
<BasicBlock
*> Blocks
, DemandedBits
&DB
,
537 const TargetTransformInfo
*TTI
) {
539 // DemandedBits will give us every value's live-out bits. But we want
540 // to ensure no extra casts would need to be inserted, so every DAG
541 // of connected values must have the same minimum bitwidth.
542 EquivalenceClasses
<Value
*> ECs
;
543 SmallVector
<Value
*, 16> Worklist
;
544 SmallPtrSet
<Value
*, 4> Roots
;
545 SmallPtrSet
<Value
*, 16> Visited
;
546 DenseMap
<Value
*, uint64_t> DBits
;
547 SmallPtrSet
<Instruction
*, 4> InstructionSet
;
548 MapVector
<Instruction
*, uint64_t> MinBWs
;
550 // Determine the roots. We work bottom-up, from truncs or icmps.
551 bool SeenExtFromIllegalType
= false;
552 for (auto *BB
: Blocks
)
553 for (auto &I
: *BB
) {
554 InstructionSet
.insert(&I
);
556 if (TTI
&& (isa
<ZExtInst
>(&I
) || isa
<SExtInst
>(&I
)) &&
557 !TTI
->isTypeLegal(I
.getOperand(0)->getType()))
558 SeenExtFromIllegalType
= true;
560 // Only deal with non-vector integers up to 64-bits wide.
561 if ((isa
<TruncInst
>(&I
) || isa
<ICmpInst
>(&I
)) &&
562 !I
.getType()->isVectorTy() &&
563 I
.getOperand(0)->getType()->getScalarSizeInBits() <= 64) {
564 // Don't make work for ourselves. If we know the loaded type is legal,
565 // don't add it to the worklist.
566 if (TTI
&& isa
<TruncInst
>(&I
) && TTI
->isTypeLegal(I
.getType()))
569 Worklist
.push_back(&I
);
574 if (Worklist
.empty() || (TTI
&& !SeenExtFromIllegalType
))
577 // Now proceed breadth-first, unioning values together.
578 while (!Worklist
.empty()) {
579 Value
*Val
= Worklist
.pop_back_val();
580 Value
*Leader
= ECs
.getOrInsertLeaderValue(Val
);
582 if (!Visited
.insert(Val
).second
)
585 // Non-instructions terminate a chain successfully.
586 if (!isa
<Instruction
>(Val
))
588 Instruction
*I
= cast
<Instruction
>(Val
);
590 // If we encounter a type that is larger than 64 bits, we can't represent
592 if (DB
.getDemandedBits(I
).getBitWidth() > 64)
593 return MapVector
<Instruction
*, uint64_t>();
595 uint64_t V
= DB
.getDemandedBits(I
).getZExtValue();
599 // Casts, loads and instructions outside of our range terminate a chain
601 if (isa
<SExtInst
>(I
) || isa
<ZExtInst
>(I
) || isa
<LoadInst
>(I
) ||
602 !InstructionSet
.count(I
))
605 // Unsafe casts terminate a chain unsuccessfully. We can't do anything
606 // useful with bitcasts, ptrtoints or inttoptrs and it'd be unsafe to
607 // transform anything that relies on them.
608 if (isa
<BitCastInst
>(I
) || isa
<PtrToIntInst
>(I
) || isa
<IntToPtrInst
>(I
) ||
609 !I
->getType()->isIntegerTy()) {
610 DBits
[Leader
] |= ~0ULL;
614 // We don't modify the types of PHIs. Reductions will already have been
615 // truncated if possible, and inductions' sizes will have been chosen by
620 if (DBits
[Leader
] == ~0ULL)
621 // All bits demanded, no point continuing.
624 for (Value
*O
: cast
<User
>(I
)->operands()) {
625 ECs
.unionSets(Leader
, O
);
626 Worklist
.push_back(O
);
630 // Now we've discovered all values, walk them to see if there are
631 // any users we didn't see. If there are, we can't optimize that
633 for (auto &I
: DBits
)
634 for (auto *U
: I
.first
->users())
635 if (U
->getType()->isIntegerTy() && DBits
.count(U
) == 0)
636 DBits
[ECs
.getOrInsertLeaderValue(I
.first
)] |= ~0ULL;
638 for (auto I
= ECs
.begin(), E
= ECs
.end(); I
!= E
; ++I
) {
639 uint64_t LeaderDemandedBits
= 0;
640 for (Value
*M
: llvm::make_range(ECs
.member_begin(I
), ECs
.member_end()))
641 LeaderDemandedBits
|= DBits
[M
];
643 uint64_t MinBW
= llvm::bit_width(LeaderDemandedBits
);
644 // Round up to a power of 2
645 MinBW
= llvm::bit_ceil(MinBW
);
647 // We don't modify the types of PHIs. Reductions will already have been
648 // truncated if possible, and inductions' sizes will have been chosen by
650 // If we are required to shrink a PHI, abandon this entire equivalence class.
652 for (Value
*M
: llvm::make_range(ECs
.member_begin(I
), ECs
.member_end()))
653 if (isa
<PHINode
>(M
) && MinBW
< M
->getType()->getScalarSizeInBits()) {
660 for (Value
*M
: llvm::make_range(ECs
.member_begin(I
), ECs
.member_end())) {
661 auto *MI
= dyn_cast
<Instruction
>(M
);
664 Type
*Ty
= M
->getType();
666 Ty
= MI
->getOperand(0)->getType();
668 if (MinBW
>= Ty
->getScalarSizeInBits())
671 // If any of M's operands demand more bits than MinBW then M cannot be
672 // performed safely in MinBW.
673 if (any_of(MI
->operands(), [&DB
, MinBW
](Use
&U
) {
674 auto *CI
= dyn_cast
<ConstantInt
>(U
);
675 // For constants shift amounts, check if the shift would result in
678 isa
<ShlOperator
, LShrOperator
, AShrOperator
>(U
.getUser()) &&
679 U
.getOperandNo() == 1)
680 return CI
->uge(MinBW
);
681 uint64_t BW
= bit_width(DB
.getDemandedBits(&U
).getZExtValue());
682 return bit_ceil(BW
) > MinBW
;
693 /// Add all access groups in @p AccGroups to @p List.
694 template <typename ListT
>
695 static void addToAccessGroupList(ListT
&List
, MDNode
*AccGroups
) {
696 // Interpret an access group as a list containing itself.
697 if (AccGroups
->getNumOperands() == 0) {
698 assert(isValidAsAccessGroup(AccGroups
) && "Node must be an access group");
699 List
.insert(AccGroups
);
703 for (const auto &AccGroupListOp
: AccGroups
->operands()) {
704 auto *Item
= cast
<MDNode
>(AccGroupListOp
.get());
705 assert(isValidAsAccessGroup(Item
) && "List item must be an access group");
710 MDNode
*llvm::uniteAccessGroups(MDNode
*AccGroups1
, MDNode
*AccGroups2
) {
715 if (AccGroups1
== AccGroups2
)
718 SmallSetVector
<Metadata
*, 4> Union
;
719 addToAccessGroupList(Union
, AccGroups1
);
720 addToAccessGroupList(Union
, AccGroups2
);
722 if (Union
.size() == 0)
724 if (Union
.size() == 1)
725 return cast
<MDNode
>(Union
.front());
727 LLVMContext
&Ctx
= AccGroups1
->getContext();
728 return MDNode::get(Ctx
, Union
.getArrayRef());
731 MDNode
*llvm::intersectAccessGroups(const Instruction
*Inst1
,
732 const Instruction
*Inst2
) {
733 bool MayAccessMem1
= Inst1
->mayReadOrWriteMemory();
734 bool MayAccessMem2
= Inst2
->mayReadOrWriteMemory();
736 if (!MayAccessMem1
&& !MayAccessMem2
)
739 return Inst2
->getMetadata(LLVMContext::MD_access_group
);
741 return Inst1
->getMetadata(LLVMContext::MD_access_group
);
743 MDNode
*MD1
= Inst1
->getMetadata(LLVMContext::MD_access_group
);
744 MDNode
*MD2
= Inst2
->getMetadata(LLVMContext::MD_access_group
);
750 // Use set for scalable 'contains' check.
751 SmallPtrSet
<Metadata
*, 4> AccGroupSet2
;
752 addToAccessGroupList(AccGroupSet2
, MD2
);
754 SmallVector
<Metadata
*, 4> Intersection
;
755 if (MD1
->getNumOperands() == 0) {
756 assert(isValidAsAccessGroup(MD1
) && "Node must be an access group");
757 if (AccGroupSet2
.count(MD1
))
758 Intersection
.push_back(MD1
);
760 for (const MDOperand
&Node
: MD1
->operands()) {
761 auto *Item
= cast
<MDNode
>(Node
.get());
762 assert(isValidAsAccessGroup(Item
) && "List item must be an access group");
763 if (AccGroupSet2
.count(Item
))
764 Intersection
.push_back(Item
);
768 if (Intersection
.size() == 0)
770 if (Intersection
.size() == 1)
771 return cast
<MDNode
>(Intersection
.front());
773 LLVMContext
&Ctx
= Inst1
->getContext();
774 return MDNode::get(Ctx
, Intersection
);
777 /// \returns \p I after propagating metadata from \p VL.
778 Instruction
*llvm::propagateMetadata(Instruction
*Inst
, ArrayRef
<Value
*> VL
) {
781 Instruction
*I0
= cast
<Instruction
>(VL
[0]);
782 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> Metadata
;
783 I0
->getAllMetadataOtherThanDebugLoc(Metadata
);
785 for (auto Kind
: {LLVMContext::MD_tbaa
, LLVMContext::MD_alias_scope
,
786 LLVMContext::MD_noalias
, LLVMContext::MD_fpmath
,
787 LLVMContext::MD_nontemporal
, LLVMContext::MD_invariant_load
,
788 LLVMContext::MD_access_group
}) {
789 MDNode
*MD
= I0
->getMetadata(Kind
);
791 for (int J
= 1, E
= VL
.size(); MD
&& J
!= E
; ++J
) {
792 const Instruction
*IJ
= cast
<Instruction
>(VL
[J
]);
793 MDNode
*IMD
= IJ
->getMetadata(Kind
);
795 case LLVMContext::MD_tbaa
:
796 MD
= MDNode::getMostGenericTBAA(MD
, IMD
);
798 case LLVMContext::MD_alias_scope
:
799 MD
= MDNode::getMostGenericAliasScope(MD
, IMD
);
801 case LLVMContext::MD_fpmath
:
802 MD
= MDNode::getMostGenericFPMath(MD
, IMD
);
804 case LLVMContext::MD_noalias
:
805 case LLVMContext::MD_nontemporal
:
806 case LLVMContext::MD_invariant_load
:
807 MD
= MDNode::intersect(MD
, IMD
);
809 case LLVMContext::MD_access_group
:
810 MD
= intersectAccessGroups(Inst
, IJ
);
813 llvm_unreachable("unhandled metadata");
817 Inst
->setMetadata(Kind
, MD
);
824 llvm::createBitMaskForGaps(IRBuilderBase
&Builder
, unsigned VF
,
825 const InterleaveGroup
<Instruction
> &Group
) {
826 // All 1's means mask is not needed.
827 if (Group
.getNumMembers() == Group
.getFactor())
830 // TODO: support reversed access.
831 assert(!Group
.isReverse() && "Reversed group not supported.");
833 SmallVector
<Constant
*, 16> Mask
;
834 for (unsigned i
= 0; i
< VF
; i
++)
835 for (unsigned j
= 0; j
< Group
.getFactor(); ++j
) {
836 unsigned HasMember
= Group
.getMember(j
) ? 1 : 0;
837 Mask
.push_back(Builder
.getInt1(HasMember
));
840 return ConstantVector::get(Mask
);
843 llvm::SmallVector
<int, 16>
844 llvm::createReplicatedMask(unsigned ReplicationFactor
, unsigned VF
) {
845 SmallVector
<int, 16> MaskVec
;
846 for (unsigned i
= 0; i
< VF
; i
++)
847 for (unsigned j
= 0; j
< ReplicationFactor
; j
++)
848 MaskVec
.push_back(i
);
853 llvm::SmallVector
<int, 16> llvm::createInterleaveMask(unsigned VF
,
855 SmallVector
<int, 16> Mask
;
856 for (unsigned i
= 0; i
< VF
; i
++)
857 for (unsigned j
= 0; j
< NumVecs
; j
++)
858 Mask
.push_back(j
* VF
+ i
);
863 llvm::SmallVector
<int, 16>
864 llvm::createStrideMask(unsigned Start
, unsigned Stride
, unsigned VF
) {
865 SmallVector
<int, 16> Mask
;
866 for (unsigned i
= 0; i
< VF
; i
++)
867 Mask
.push_back(Start
+ i
* Stride
);
872 llvm::SmallVector
<int, 16> llvm::createSequentialMask(unsigned Start
,
874 unsigned NumUndefs
) {
875 SmallVector
<int, 16> Mask
;
876 for (unsigned i
= 0; i
< NumInts
; i
++)
877 Mask
.push_back(Start
+ i
);
879 for (unsigned i
= 0; i
< NumUndefs
; i
++)
885 llvm::SmallVector
<int, 16> llvm::createUnaryMask(ArrayRef
<int> Mask
,
887 // Avoid casts in the loop and make sure we have a reasonable number.
888 int NumEltsSigned
= NumElts
;
889 assert(NumEltsSigned
> 0 && "Expected smaller or non-zero element count");
891 // If the mask chooses an element from operand 1, reduce it to choose from the
892 // corresponding element of operand 0. Undef mask elements are unchanged.
893 SmallVector
<int, 16> UnaryMask
;
894 for (int MaskElt
: Mask
) {
895 assert((MaskElt
< NumEltsSigned
* 2) && "Expected valid shuffle mask");
896 int UnaryElt
= MaskElt
>= NumEltsSigned
? MaskElt
- NumEltsSigned
: MaskElt
;
897 UnaryMask
.push_back(UnaryElt
);
902 /// A helper function for concatenating vectors. This function concatenates two
903 /// vectors having the same element type. If the second vector has fewer
904 /// elements than the first, it is padded with undefs.
905 static Value
*concatenateTwoVectors(IRBuilderBase
&Builder
, Value
*V1
,
907 VectorType
*VecTy1
= dyn_cast
<VectorType
>(V1
->getType());
908 VectorType
*VecTy2
= dyn_cast
<VectorType
>(V2
->getType());
909 assert(VecTy1
&& VecTy2
&&
910 VecTy1
->getScalarType() == VecTy2
->getScalarType() &&
911 "Expect two vectors with the same element type");
913 unsigned NumElts1
= cast
<FixedVectorType
>(VecTy1
)->getNumElements();
914 unsigned NumElts2
= cast
<FixedVectorType
>(VecTy2
)->getNumElements();
915 assert(NumElts1
>= NumElts2
&& "Unexpect the first vector has less elements");
917 if (NumElts1
> NumElts2
) {
918 // Extend with UNDEFs.
919 V2
= Builder
.CreateShuffleVector(
920 V2
, createSequentialMask(0, NumElts2
, NumElts1
- NumElts2
));
923 return Builder
.CreateShuffleVector(
924 V1
, V2
, createSequentialMask(0, NumElts1
+ NumElts2
, 0));
927 Value
*llvm::concatenateVectors(IRBuilderBase
&Builder
,
928 ArrayRef
<Value
*> Vecs
) {
929 unsigned NumVecs
= Vecs
.size();
930 assert(NumVecs
> 1 && "Should be at least two vectors");
932 SmallVector
<Value
*, 8> ResList
;
933 ResList
.append(Vecs
.begin(), Vecs
.end());
935 SmallVector
<Value
*, 8> TmpList
;
936 for (unsigned i
= 0; i
< NumVecs
- 1; i
+= 2) {
937 Value
*V0
= ResList
[i
], *V1
= ResList
[i
+ 1];
938 assert((V0
->getType() == V1
->getType() || i
== NumVecs
- 2) &&
939 "Only the last vector may have a different type");
941 TmpList
.push_back(concatenateTwoVectors(Builder
, V0
, V1
));
944 // Push the last vector if the total number of vectors is odd.
945 if (NumVecs
% 2 != 0)
946 TmpList
.push_back(ResList
[NumVecs
- 1]);
949 NumVecs
= ResList
.size();
950 } while (NumVecs
> 1);
955 bool llvm::maskIsAllZeroOrUndef(Value
*Mask
) {
956 assert(isa
<VectorType
>(Mask
->getType()) &&
957 isa
<IntegerType
>(Mask
->getType()->getScalarType()) &&
958 cast
<IntegerType
>(Mask
->getType()->getScalarType())->getBitWidth() ==
960 "Mask must be a vector of i1");
962 auto *ConstMask
= dyn_cast
<Constant
>(Mask
);
965 if (ConstMask
->isNullValue() || isa
<UndefValue
>(ConstMask
))
967 if (isa
<ScalableVectorType
>(ConstMask
->getType()))
971 E
= cast
<FixedVectorType
>(ConstMask
->getType())->getNumElements();
973 if (auto *MaskElt
= ConstMask
->getAggregateElement(I
))
974 if (MaskElt
->isNullValue() || isa
<UndefValue
>(MaskElt
))
981 bool llvm::maskIsAllOneOrUndef(Value
*Mask
) {
982 assert(isa
<VectorType
>(Mask
->getType()) &&
983 isa
<IntegerType
>(Mask
->getType()->getScalarType()) &&
984 cast
<IntegerType
>(Mask
->getType()->getScalarType())->getBitWidth() ==
986 "Mask must be a vector of i1");
988 auto *ConstMask
= dyn_cast
<Constant
>(Mask
);
991 if (ConstMask
->isAllOnesValue() || isa
<UndefValue
>(ConstMask
))
993 if (isa
<ScalableVectorType
>(ConstMask
->getType()))
997 E
= cast
<FixedVectorType
>(ConstMask
->getType())->getNumElements();
999 if (auto *MaskElt
= ConstMask
->getAggregateElement(I
))
1000 if (MaskElt
->isAllOnesValue() || isa
<UndefValue
>(MaskElt
))
1007 /// TODO: This is a lot like known bits, but for
1008 /// vectors. Is there something we can common this with?
1009 APInt
llvm::possiblyDemandedEltsInMask(Value
*Mask
) {
1010 assert(isa
<FixedVectorType
>(Mask
->getType()) &&
1011 isa
<IntegerType
>(Mask
->getType()->getScalarType()) &&
1012 cast
<IntegerType
>(Mask
->getType()->getScalarType())->getBitWidth() ==
1014 "Mask must be a fixed width vector of i1");
1016 const unsigned VWidth
=
1017 cast
<FixedVectorType
>(Mask
->getType())->getNumElements();
1018 APInt DemandedElts
= APInt::getAllOnes(VWidth
);
1019 if (auto *CV
= dyn_cast
<ConstantVector
>(Mask
))
1020 for (unsigned i
= 0; i
< VWidth
; i
++)
1021 if (CV
->getAggregateElement(i
)->isNullValue())
1022 DemandedElts
.clearBit(i
);
1023 return DemandedElts
;
1026 bool InterleavedAccessInfo::isStrided(int Stride
) {
1027 unsigned Factor
= std::abs(Stride
);
1028 return Factor
>= 2 && Factor
<= MaxInterleaveGroupFactor
;
1031 void InterleavedAccessInfo::collectConstStrideAccesses(
1032 MapVector
<Instruction
*, StrideDescriptor
> &AccessStrideInfo
,
1033 const DenseMap
<Value
*, const SCEV
*> &Strides
) {
1034 auto &DL
= TheLoop
->getHeader()->getModule()->getDataLayout();
1036 // Since it's desired that the load/store instructions be maintained in
1037 // "program order" for the interleaved access analysis, we have to visit the
1038 // blocks in the loop in reverse postorder (i.e., in a topological order).
1039 // Such an ordering will ensure that any load/store that may be executed
1040 // before a second load/store will precede the second load/store in
1041 // AccessStrideInfo.
1042 LoopBlocksDFS
DFS(TheLoop
);
1044 for (BasicBlock
*BB
: make_range(DFS
.beginRPO(), DFS
.endRPO()))
1045 for (auto &I
: *BB
) {
1046 Value
*Ptr
= getLoadStorePointerOperand(&I
);
1049 Type
*ElementTy
= getLoadStoreType(&I
);
1051 // Currently, codegen doesn't support cases where the type size doesn't
1052 // match the alloc size. Skip them for now.
1053 uint64_t Size
= DL
.getTypeAllocSize(ElementTy
);
1054 if (Size
* 8 != DL
.getTypeSizeInBits(ElementTy
))
1057 // We don't check wrapping here because we don't know yet if Ptr will be
1058 // part of a full group or a group with gaps. Checking wrapping for all
1059 // pointers (even those that end up in groups with no gaps) will be overly
1060 // conservative. For full groups, wrapping should be ok since if we would
1061 // wrap around the address space we would do a memory access at nullptr
1062 // even without the transformation. The wrapping checks are therefore
1063 // deferred until after we've formed the interleaved groups.
1065 getPtrStride(PSE
, ElementTy
, Ptr
, TheLoop
, Strides
,
1066 /*Assume=*/true, /*ShouldCheckWrap=*/false).value_or(0);
1068 const SCEV
*Scev
= replaceSymbolicStrideSCEV(PSE
, Strides
, Ptr
);
1069 AccessStrideInfo
[&I
] = StrideDescriptor(Stride
, Scev
, Size
,
1070 getLoadStoreAlignment(&I
));
1074 // Analyze interleaved accesses and collect them into interleaved load and
1077 // When generating code for an interleaved load group, we effectively hoist all
1078 // loads in the group to the location of the first load in program order. When
1079 // generating code for an interleaved store group, we sink all stores to the
1080 // location of the last store. This code motion can change the order of load
1081 // and store instructions and may break dependences.
1083 // The code generation strategy mentioned above ensures that we won't violate
1084 // any write-after-read (WAR) dependences.
1086 // E.g., for the WAR dependence: a = A[i]; // (1)
1089 // The store group of (2) is always inserted at or below (2), and the load
1090 // group of (1) is always inserted at or above (1). Thus, the instructions will
1091 // never be reordered. All other dependences are checked to ensure the
1092 // correctness of the instruction reordering.
1094 // The algorithm visits all memory accesses in the loop in bottom-up program
1095 // order. Program order is established by traversing the blocks in the loop in
1096 // reverse postorder when collecting the accesses.
1098 // We visit the memory accesses in bottom-up order because it can simplify the
1099 // construction of store groups in the presence of write-after-write (WAW)
1102 // E.g., for the WAW dependence: A[i] = a; // (1)
1104 // A[i + 1] = c; // (3)
1106 // We will first create a store group with (3) and (2). (1) can't be added to
1107 // this group because it and (2) are dependent. However, (1) can be grouped
1108 // with other accesses that may precede it in program order. Note that a
1109 // bottom-up order does not imply that WAW dependences should not be checked.
1110 void InterleavedAccessInfo::analyzeInterleaving(
1111 bool EnablePredicatedInterleavedMemAccesses
) {
1112 LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
1113 const auto &Strides
= LAI
->getSymbolicStrides();
1115 // Holds all accesses with a constant stride.
1116 MapVector
<Instruction
*, StrideDescriptor
> AccessStrideInfo
;
1117 collectConstStrideAccesses(AccessStrideInfo
, Strides
);
1119 if (AccessStrideInfo
.empty())
1122 // Collect the dependences in the loop.
1123 collectDependences();
1125 // Holds all interleaved store groups temporarily.
1126 SmallSetVector
<InterleaveGroup
<Instruction
> *, 4> StoreGroups
;
1127 // Holds all interleaved load groups temporarily.
1128 SmallSetVector
<InterleaveGroup
<Instruction
> *, 4> LoadGroups
;
1129 // Groups added to this set cannot have new members added.
1130 SmallPtrSet
<InterleaveGroup
<Instruction
> *, 4> CompletedLoadGroups
;
1132 // Search in bottom-up program order for pairs of accesses (A and B) that can
1133 // form interleaved load or store groups. In the algorithm below, access A
1134 // precedes access B in program order. We initialize a group for B in the
1135 // outer loop of the algorithm, and then in the inner loop, we attempt to
1136 // insert each A into B's group if:
1138 // 1. A and B have the same stride,
1139 // 2. A and B have the same memory object size, and
1140 // 3. A belongs in B's group according to its distance from B.
1142 // Special care is taken to ensure group formation will not break any
1144 for (auto BI
= AccessStrideInfo
.rbegin(), E
= AccessStrideInfo
.rend();
1146 Instruction
*B
= BI
->first
;
1147 StrideDescriptor DesB
= BI
->second
;
1149 // Initialize a group for B if it has an allowable stride. Even if we don't
1150 // create a group for B, we continue with the bottom-up algorithm to ensure
1151 // we don't break any of B's dependences.
1152 InterleaveGroup
<Instruction
> *GroupB
= nullptr;
1153 if (isStrided(DesB
.Stride
) &&
1154 (!isPredicated(B
->getParent()) || EnablePredicatedInterleavedMemAccesses
)) {
1155 GroupB
= getInterleaveGroup(B
);
1157 LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B
1159 GroupB
= createInterleaveGroup(B
, DesB
.Stride
, DesB
.Alignment
);
1160 if (B
->mayWriteToMemory())
1161 StoreGroups
.insert(GroupB
);
1163 LoadGroups
.insert(GroupB
);
1167 for (auto AI
= std::next(BI
); AI
!= E
; ++AI
) {
1168 Instruction
*A
= AI
->first
;
1169 StrideDescriptor DesA
= AI
->second
;
1171 // Our code motion strategy implies that we can't have dependences
1172 // between accesses in an interleaved group and other accesses located
1173 // between the first and last member of the group. Note that this also
1174 // means that a group can't have more than one member at a given offset.
1175 // The accesses in a group can have dependences with other accesses, but
1176 // we must ensure we don't extend the boundaries of the group such that
1177 // we encompass those dependent accesses.
1179 // For example, assume we have the sequence of accesses shown below in a
1182 // (1, 2) is a group | A[i] = a; // (1)
1183 // | A[i-1] = b; // (2) |
1184 // A[i-3] = c; // (3)
1185 // A[i] = d; // (4) | (2, 4) is not a group
1187 // Because accesses (2) and (3) are dependent, we can group (2) with (1)
1188 // but not with (4). If we did, the dependent access (3) would be within
1189 // the boundaries of the (2, 4) group.
1190 auto DependentMember
= [&](InterleaveGroup
<Instruction
> *Group
,
1191 StrideEntry
*A
) -> Instruction
* {
1192 for (uint32_t Index
= 0; Index
< Group
->getFactor(); ++Index
) {
1193 Instruction
*MemberOfGroupB
= Group
->getMember(Index
);
1194 if (MemberOfGroupB
&& !canReorderMemAccessesForInterleavedGroups(
1195 A
, &*AccessStrideInfo
.find(MemberOfGroupB
)))
1196 return MemberOfGroupB
;
1201 auto GroupA
= getInterleaveGroup(A
);
1202 // If A is a load, dependencies are tolerable, there's nothing to do here.
1203 // If both A and B belong to the same (store) group, they are independent,
1204 // even if dependencies have not been recorded.
1205 // If both GroupA and GroupB are null, there's nothing to do here.
1206 if (A
->mayWriteToMemory() && GroupA
!= GroupB
) {
1207 Instruction
*DependentInst
= nullptr;
1208 // If GroupB is a load group, we have to compare AI against all
1209 // members of GroupB because if any load within GroupB has a dependency
1210 // on AI, we need to mark GroupB as complete and also release the
1211 // store GroupA (if A belongs to one). The former prevents incorrect
1212 // hoisting of load B above store A while the latter prevents incorrect
1213 // sinking of store A below load B.
1214 if (GroupB
&& LoadGroups
.contains(GroupB
))
1215 DependentInst
= DependentMember(GroupB
, &*AI
);
1216 else if (!canReorderMemAccessesForInterleavedGroups(&*AI
, &*BI
))
1219 if (DependentInst
) {
1220 // A has a store dependence on B (or on some load within GroupB) and
1221 // is part of a store group. Release A's group to prevent illegal
1222 // sinking of A below B. A will then be free to form another group
1223 // with instructions that precede it.
1224 if (GroupA
&& StoreGroups
.contains(GroupA
)) {
1225 LLVM_DEBUG(dbgs() << "LV: Invalidated store group due to "
1226 "dependence between "
1227 << *A
<< " and " << *DependentInst
<< '\n');
1228 StoreGroups
.remove(GroupA
);
1229 releaseGroup(GroupA
);
1231 // If B is a load and part of an interleave group, no earlier loads
1232 // can be added to B's interleave group, because this would mean the
1233 // DependentInst would move across store A. Mark the interleave group
1235 if (GroupB
&& LoadGroups
.contains(GroupB
)) {
1236 LLVM_DEBUG(dbgs() << "LV: Marking interleave group for " << *B
1237 << " as complete.\n");
1238 CompletedLoadGroups
.insert(GroupB
);
1242 if (CompletedLoadGroups
.contains(GroupB
)) {
1243 // Skip trying to add A to B, continue to look for other conflicting A's
1244 // in groups to be released.
1248 // At this point, we've checked for illegal code motion. If either A or B
1249 // isn't strided, there's nothing left to do.
1250 if (!isStrided(DesA
.Stride
) || !isStrided(DesB
.Stride
))
1253 // Ignore A if it's already in a group or isn't the same kind of memory
1255 // Note that mayReadFromMemory() isn't mutually exclusive to
1256 // mayWriteToMemory in the case of atomic loads. We shouldn't see those
1257 // here, canVectorizeMemory() should have returned false - except for the
1258 // case we asked for optimization remarks.
1259 if (isInterleaved(A
) ||
1260 (A
->mayReadFromMemory() != B
->mayReadFromMemory()) ||
1261 (A
->mayWriteToMemory() != B
->mayWriteToMemory()))
1264 // Check rules 1 and 2. Ignore A if its stride or size is different from
1266 if (DesA
.Stride
!= DesB
.Stride
|| DesA
.Size
!= DesB
.Size
)
1269 // Ignore A if the memory object of A and B don't belong to the same
1271 if (getLoadStoreAddressSpace(A
) != getLoadStoreAddressSpace(B
))
1274 // Calculate the distance from A to B.
1275 const SCEVConstant
*DistToB
= dyn_cast
<SCEVConstant
>(
1276 PSE
.getSE()->getMinusSCEV(DesA
.Scev
, DesB
.Scev
));
1279 int64_t DistanceToB
= DistToB
->getAPInt().getSExtValue();
1281 // Check rule 3. Ignore A if its distance to B is not a multiple of the
1283 if (DistanceToB
% static_cast<int64_t>(DesB
.Size
))
1286 // All members of a predicated interleave-group must have the same predicate,
1287 // and currently must reside in the same BB.
1288 BasicBlock
*BlockA
= A
->getParent();
1289 BasicBlock
*BlockB
= B
->getParent();
1290 if ((isPredicated(BlockA
) || isPredicated(BlockB
)) &&
1291 (!EnablePredicatedInterleavedMemAccesses
|| BlockA
!= BlockB
))
1294 // The index of A is the index of B plus A's distance to B in multiples
1297 GroupB
->getIndex(B
) + DistanceToB
/ static_cast<int64_t>(DesB
.Size
);
1299 // Try to insert A into B's group.
1300 if (GroupB
->insertMember(A
, IndexA
, DesA
.Alignment
)) {
1301 LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A
<< '\n'
1302 << " into the interleave group with" << *B
1304 InterleaveGroupMap
[A
] = GroupB
;
1306 // Set the first load in program order as the insert position.
1307 if (A
->mayReadFromMemory())
1308 GroupB
->setInsertPos(A
);
1310 } // Iteration over A accesses.
1311 } // Iteration over B accesses.
1313 auto InvalidateGroupIfMemberMayWrap
= [&](InterleaveGroup
<Instruction
> *Group
,
1315 std::string FirstOrLast
) -> bool {
1316 Instruction
*Member
= Group
->getMember(Index
);
1317 assert(Member
&& "Group member does not exist");
1318 Value
*MemberPtr
= getLoadStorePointerOperand(Member
);
1319 Type
*AccessTy
= getLoadStoreType(Member
);
1320 if (getPtrStride(PSE
, AccessTy
, MemberPtr
, TheLoop
, Strides
,
1321 /*Assume=*/false, /*ShouldCheckWrap=*/true).value_or(0))
1323 LLVM_DEBUG(dbgs() << "LV: Invalidate candidate interleaved group due to "
1325 << " group member potentially pointer-wrapping.\n");
1326 releaseGroup(Group
);
1330 // Remove interleaved groups with gaps whose memory
1331 // accesses may wrap around. We have to revisit the getPtrStride analysis,
1332 // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
1333 // not check wrapping (see documentation there).
1334 // FORNOW we use Assume=false;
1335 // TODO: Change to Assume=true but making sure we don't exceed the threshold
1336 // of runtime SCEV assumptions checks (thereby potentially failing to
1337 // vectorize altogether).
1338 // Additional optional optimizations:
1339 // TODO: If we are peeling the loop and we know that the first pointer doesn't
1340 // wrap then we can deduce that all pointers in the group don't wrap.
1341 // This means that we can forcefully peel the loop in order to only have to
1342 // check the first pointer for no-wrap. When we'll change to use Assume=true
1343 // we'll only need at most one runtime check per interleaved group.
1344 for (auto *Group
: LoadGroups
) {
1345 // Case 1: A full group. Can Skip the checks; For full groups, if the wide
1346 // load would wrap around the address space we would do a memory access at
1347 // nullptr even without the transformation.
1348 if (Group
->getNumMembers() == Group
->getFactor())
1351 // Case 2: If first and last members of the group don't wrap this implies
1352 // that all the pointers in the group don't wrap.
1353 // So we check only group member 0 (which is always guaranteed to exist),
1354 // and group member Factor - 1; If the latter doesn't exist we rely on
1355 // peeling (if it is a non-reversed accsess -- see Case 3).
1356 if (InvalidateGroupIfMemberMayWrap(Group
, 0, std::string("first")))
1358 if (Group
->getMember(Group
->getFactor() - 1))
1359 InvalidateGroupIfMemberMayWrap(Group
, Group
->getFactor() - 1,
1360 std::string("last"));
1362 // Case 3: A non-reversed interleaved load group with gaps: We need
1363 // to execute at least one scalar epilogue iteration. This will ensure
1364 // we don't speculatively access memory out-of-bounds. We only need
1365 // to look for a member at index factor - 1, since every group must have
1366 // a member at index zero.
1367 if (Group
->isReverse()) {
1369 dbgs() << "LV: Invalidate candidate interleaved group due to "
1370 "a reverse access with gaps.\n");
1371 releaseGroup(Group
);
1375 dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
1376 RequiresScalarEpilogue
= true;
1380 for (auto *Group
: StoreGroups
) {
1381 // Case 1: A full group. Can Skip the checks; For full groups, if the wide
1382 // store would wrap around the address space we would do a memory access at
1383 // nullptr even without the transformation.
1384 if (Group
->getNumMembers() == Group
->getFactor())
1387 // Interleave-store-group with gaps is implemented using masked wide store.
1388 // Remove interleaved store groups with gaps if
1389 // masked-interleaved-accesses are not enabled by the target.
1390 if (!EnablePredicatedInterleavedMemAccesses
) {
1392 dbgs() << "LV: Invalidate candidate interleaved store group due "
1394 releaseGroup(Group
);
1398 // Case 2: If first and last members of the group don't wrap this implies
1399 // that all the pointers in the group don't wrap.
1400 // So we check only group member 0 (which is always guaranteed to exist),
1401 // and the last group member. Case 3 (scalar epilog) is not relevant for
1402 // stores with gaps, which are implemented with masked-store (rather than
1403 // speculative access, as in loads).
1404 if (InvalidateGroupIfMemberMayWrap(Group
, 0, std::string("first")))
1406 for (int Index
= Group
->getFactor() - 1; Index
> 0; Index
--)
1407 if (Group
->getMember(Index
)) {
1408 InvalidateGroupIfMemberMayWrap(Group
, Index
, std::string("last"));
1414 void InterleavedAccessInfo::invalidateGroupsRequiringScalarEpilogue() {
1415 // If no group had triggered the requirement to create an epilogue loop,
1416 // there is nothing to do.
1417 if (!requiresScalarEpilogue())
1420 bool ReleasedGroup
= false;
1421 // Release groups requiring scalar epilogues. Note that this also removes them
1422 // from InterleaveGroups.
1423 for (auto *Group
: make_early_inc_range(InterleaveGroups
)) {
1424 if (!Group
->requiresScalarEpilogue())
1428 << "LV: Invalidate candidate interleaved group due to gaps that "
1429 "require a scalar epilogue (not allowed under optsize) and cannot "
1430 "be masked (not enabled). \n");
1431 releaseGroup(Group
);
1432 ReleasedGroup
= true;
1434 assert(ReleasedGroup
&& "At least one group must be invalidated, as a "
1435 "scalar epilogue was required");
1436 (void)ReleasedGroup
;
1437 RequiresScalarEpilogue
= false;
1440 template <typename InstT
>
1441 void InterleaveGroup
<InstT
>::addMetadata(InstT
*NewInst
) const {
1442 llvm_unreachable("addMetadata can only be used for Instruction");
1447 void InterleaveGroup
<Instruction
>::addMetadata(Instruction
*NewInst
) const {
1448 SmallVector
<Value
*, 4> VL
;
1449 std::transform(Members
.begin(), Members
.end(), std::back_inserter(VL
),
1450 [](std::pair
<int, Instruction
*> p
) { return p
.second
; });
1451 propagateMetadata(NewInst
, VL
);
1455 void VFABI::getVectorVariantNames(
1456 const CallInst
&CI
, SmallVectorImpl
<std::string
> &VariantMappings
) {
1457 const StringRef S
= CI
.getFnAttr(VFABI::MappingsAttrName
).getValueAsString();
1461 SmallVector
<StringRef
, 8> ListAttr
;
1462 S
.split(ListAttr
, ",");
1464 for (const auto &S
: SetVector
<StringRef
>(ListAttr
.begin(), ListAttr
.end())) {
1466 LLVM_DEBUG(dbgs() << "VFABI: adding mapping '" << S
<< "'\n");
1467 std::optional
<VFInfo
> Info
=
1468 VFABI::tryDemangleForVFABI(S
, *(CI
.getModule()));
1469 assert(Info
&& "Invalid name for a VFABI variant.");
1470 assert(CI
.getModule()->getFunction(Info
->VectorName
) &&
1471 "Vector function is missing.");
1473 VariantMappings
.push_back(std::string(S
));
1477 bool VFShape::hasValidParameterList() const {
1478 for (unsigned Pos
= 0, NumParams
= Parameters
.size(); Pos
< NumParams
;
1480 assert(Parameters
[Pos
].ParamPos
== Pos
&& "Broken parameter list.");
1482 switch (Parameters
[Pos
].ParamKind
) {
1483 default: // Nothing to check.
1485 case VFParamKind::OMP_Linear
:
1486 case VFParamKind::OMP_LinearRef
:
1487 case VFParamKind::OMP_LinearVal
:
1488 case VFParamKind::OMP_LinearUVal
:
1489 // Compile time linear steps must be non-zero.
1490 if (Parameters
[Pos
].LinearStepOrPos
== 0)
1493 case VFParamKind::OMP_LinearPos
:
1494 case VFParamKind::OMP_LinearRefPos
:
1495 case VFParamKind::OMP_LinearValPos
:
1496 case VFParamKind::OMP_LinearUValPos
:
1497 // The runtime linear step must be referring to some other
1498 // parameters in the signature.
1499 if (Parameters
[Pos
].LinearStepOrPos
>= int(NumParams
))
1501 // The linear step parameter must be marked as uniform.
1502 if (Parameters
[Parameters
[Pos
].LinearStepOrPos
].ParamKind
!=
1503 VFParamKind::OMP_Uniform
)
1505 // The linear step parameter can't point at itself.
1506 if (Parameters
[Pos
].LinearStepOrPos
== int(Pos
))
1509 case VFParamKind::GlobalPredicate
:
1510 // The global predicate must be the unique. Can be placed anywhere in the
1512 for (unsigned NextPos
= Pos
+ 1; NextPos
< NumParams
; ++NextPos
)
1513 if (Parameters
[NextPos
].ParamKind
== VFParamKind::GlobalPredicate
)