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/GetElementPtrTypeIterator.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/PatternMatch.h"
26 #include "llvm/IR/Value.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 /// hasVectorInstrinsicScalarOpd).
43 bool llvm::isTriviallyVectorizable(Intrinsic::ID ID
) {
45 case Intrinsic::bswap
: // Begin integer bit-manipulation.
46 case Intrinsic::bitreverse
:
47 case Intrinsic::ctpop
:
52 case Intrinsic::sadd_sat
:
53 case Intrinsic::ssub_sat
:
54 case Intrinsic::uadd_sat
:
55 case Intrinsic::usub_sat
:
56 case Intrinsic::smul_fix
:
57 case Intrinsic::smul_fix_sat
:
58 case Intrinsic::umul_fix
:
59 case Intrinsic::sqrt
: // Begin floating-point.
65 case Intrinsic::log10
:
68 case Intrinsic::minnum
:
69 case Intrinsic::maxnum
:
70 case Intrinsic::minimum
:
71 case Intrinsic::maximum
:
72 case Intrinsic::copysign
:
73 case Intrinsic::floor
:
75 case Intrinsic::trunc
:
77 case Intrinsic::nearbyint
:
78 case Intrinsic::round
:
81 case Intrinsic::fmuladd
:
83 case Intrinsic::canonicalize
:
90 /// Identifies if the vector form of the intrinsic has a scalar operand.
91 bool llvm::hasVectorInstrinsicScalarOpd(Intrinsic::ID ID
,
92 unsigned ScalarOpdIdx
) {
97 return (ScalarOpdIdx
== 1);
98 case Intrinsic::smul_fix
:
99 case Intrinsic::smul_fix_sat
:
100 case Intrinsic::umul_fix
:
101 return (ScalarOpdIdx
== 2);
107 /// Returns intrinsic ID for call.
108 /// For the input call instruction it finds mapping intrinsic and returns
109 /// its ID, in case it does not found it return not_intrinsic.
110 Intrinsic::ID
llvm::getVectorIntrinsicIDForCall(const CallInst
*CI
,
111 const TargetLibraryInfo
*TLI
) {
112 Intrinsic::ID ID
= getIntrinsicForCallSite(CI
, TLI
);
113 if (ID
== Intrinsic::not_intrinsic
)
114 return Intrinsic::not_intrinsic
;
116 if (isTriviallyVectorizable(ID
) || ID
== Intrinsic::lifetime_start
||
117 ID
== Intrinsic::lifetime_end
|| ID
== Intrinsic::assume
||
118 ID
== Intrinsic::sideeffect
)
120 return Intrinsic::not_intrinsic
;
123 /// Find the operand of the GEP that should be checked for consecutive
124 /// stores. This ignores trailing indices that have no effect on the final
126 unsigned llvm::getGEPInductionOperand(const GetElementPtrInst
*Gep
) {
127 const DataLayout
&DL
= Gep
->getModule()->getDataLayout();
128 unsigned LastOperand
= Gep
->getNumOperands() - 1;
129 unsigned GEPAllocSize
= DL
.getTypeAllocSize(Gep
->getResultElementType());
131 // Walk backwards and try to peel off zeros.
132 while (LastOperand
> 1 && match(Gep
->getOperand(LastOperand
), m_Zero())) {
133 // Find the type we're currently indexing into.
134 gep_type_iterator GEPTI
= gep_type_begin(Gep
);
135 std::advance(GEPTI
, LastOperand
- 2);
137 // If it's a type with the same allocation size as the result of the GEP we
138 // can peel off the zero index.
139 if (DL
.getTypeAllocSize(GEPTI
.getIndexedType()) != GEPAllocSize
)
147 /// If the argument is a GEP, then returns the operand identified by
148 /// getGEPInductionOperand. However, if there is some other non-loop-invariant
149 /// operand, it returns that instead.
150 Value
*llvm::stripGetElementPtr(Value
*Ptr
, ScalarEvolution
*SE
, Loop
*Lp
) {
151 GetElementPtrInst
*GEP
= dyn_cast
<GetElementPtrInst
>(Ptr
);
155 unsigned InductionOperand
= getGEPInductionOperand(GEP
);
157 // Check that all of the gep indices are uniform except for our induction
159 for (unsigned i
= 0, e
= GEP
->getNumOperands(); i
!= e
; ++i
)
160 if (i
!= InductionOperand
&&
161 !SE
->isLoopInvariant(SE
->getSCEV(GEP
->getOperand(i
)), Lp
))
163 return GEP
->getOperand(InductionOperand
);
166 /// If a value has only one user that is a CastInst, return it.
167 Value
*llvm::getUniqueCastUse(Value
*Ptr
, Loop
*Lp
, Type
*Ty
) {
168 Value
*UniqueCast
= nullptr;
169 for (User
*U
: Ptr
->users()) {
170 CastInst
*CI
= dyn_cast
<CastInst
>(U
);
171 if (CI
&& CI
->getType() == Ty
) {
181 /// Get the stride of a pointer access in a loop. Looks for symbolic
182 /// strides "a[i*stride]". Returns the symbolic stride, or null otherwise.
183 Value
*llvm::getStrideFromPointer(Value
*Ptr
, ScalarEvolution
*SE
, Loop
*Lp
) {
184 auto *PtrTy
= dyn_cast
<PointerType
>(Ptr
->getType());
185 if (!PtrTy
|| PtrTy
->isAggregateType())
188 // Try to remove a gep instruction to make the pointer (actually index at this
189 // point) easier analyzable. If OrigPtr is equal to Ptr we are analyzing the
190 // pointer, otherwise, we are analyzing the index.
191 Value
*OrigPtr
= Ptr
;
193 // The size of the pointer access.
194 int64_t PtrAccessSize
= 1;
196 Ptr
= stripGetElementPtr(Ptr
, SE
, Lp
);
197 const SCEV
*V
= SE
->getSCEV(Ptr
);
201 while (const SCEVCastExpr
*C
= dyn_cast
<SCEVCastExpr
>(V
))
204 const SCEVAddRecExpr
*S
= dyn_cast
<SCEVAddRecExpr
>(V
);
208 V
= S
->getStepRecurrence(*SE
);
212 // Strip off the size of access multiplication if we are still analyzing the
214 if (OrigPtr
== Ptr
) {
215 if (const SCEVMulExpr
*M
= dyn_cast
<SCEVMulExpr
>(V
)) {
216 if (M
->getOperand(0)->getSCEVType() != scConstant
)
219 const APInt
&APStepVal
= cast
<SCEVConstant
>(M
->getOperand(0))->getAPInt();
221 // Huge step value - give up.
222 if (APStepVal
.getBitWidth() > 64)
225 int64_t StepVal
= APStepVal
.getSExtValue();
226 if (PtrAccessSize
!= StepVal
)
228 V
= M
->getOperand(1);
233 Type
*StripedOffRecurrenceCast
= nullptr;
234 if (const SCEVCastExpr
*C
= dyn_cast
<SCEVCastExpr
>(V
)) {
235 StripedOffRecurrenceCast
= C
->getType();
239 // Look for the loop invariant symbolic value.
240 const SCEVUnknown
*U
= dyn_cast
<SCEVUnknown
>(V
);
244 Value
*Stride
= U
->getValue();
245 if (!Lp
->isLoopInvariant(Stride
))
248 // If we have stripped off the recurrence cast we have to make sure that we
249 // return the value that is used in this loop so that we can replace it later.
250 if (StripedOffRecurrenceCast
)
251 Stride
= getUniqueCastUse(Stride
, Lp
, StripedOffRecurrenceCast
);
256 /// Given a vector and an element number, see if the scalar value is
257 /// already around as a register, for example if it were inserted then extracted
259 Value
*llvm::findScalarElement(Value
*V
, unsigned EltNo
) {
260 assert(V
->getType()->isVectorTy() && "Not looking at a vector?");
261 VectorType
*VTy
= cast
<VectorType
>(V
->getType());
262 unsigned Width
= VTy
->getNumElements();
263 if (EltNo
>= Width
) // Out of range access.
264 return UndefValue::get(VTy
->getElementType());
266 if (Constant
*C
= dyn_cast
<Constant
>(V
))
267 return C
->getAggregateElement(EltNo
);
269 if (InsertElementInst
*III
= dyn_cast
<InsertElementInst
>(V
)) {
270 // If this is an insert to a variable element, we don't know what it is.
271 if (!isa
<ConstantInt
>(III
->getOperand(2)))
273 unsigned IIElt
= cast
<ConstantInt
>(III
->getOperand(2))->getZExtValue();
275 // If this is an insert to the element we are looking for, return the
278 return III
->getOperand(1);
280 // Otherwise, the insertelement doesn't modify the value, recurse on its
282 return findScalarElement(III
->getOperand(0), EltNo
);
285 if (ShuffleVectorInst
*SVI
= dyn_cast
<ShuffleVectorInst
>(V
)) {
286 unsigned LHSWidth
= SVI
->getOperand(0)->getType()->getVectorNumElements();
287 int InEl
= SVI
->getMaskValue(EltNo
);
289 return UndefValue::get(VTy
->getElementType());
290 if (InEl
< (int)LHSWidth
)
291 return findScalarElement(SVI
->getOperand(0), InEl
);
292 return findScalarElement(SVI
->getOperand(1), InEl
- LHSWidth
);
295 // Extract a value from a vector add operation with a constant zero.
296 // TODO: Use getBinOpIdentity() to generalize this.
297 Value
*Val
; Constant
*C
;
298 if (match(V
, m_Add(m_Value(Val
), m_Constant(C
))))
299 if (Constant
*Elt
= C
->getAggregateElement(EltNo
))
300 if (Elt
->isNullValue())
301 return findScalarElement(Val
, EltNo
);
303 // Otherwise, we don't know.
307 /// Get splat value if the input is a splat vector or return nullptr.
308 /// This function is not fully general. It checks only 2 cases:
309 /// the input value is (1) a splat constant vector or (2) a sequence
310 /// of instructions that broadcasts a scalar at element 0.
311 const llvm::Value
*llvm::getSplatValue(const Value
*V
) {
312 if (isa
<VectorType
>(V
->getType()))
313 if (auto *C
= dyn_cast
<Constant
>(V
))
314 return C
->getSplatValue();
316 // shuf (inselt ?, Splat, 0), ?, <0, undef, 0, ...>
318 if (match(V
, m_ShuffleVector(m_InsertElement(m_Value(), m_Value(Splat
),
320 m_Value(), m_ZeroInt())))
326 // This setting is based on its counterpart in value tracking, but it could be
327 // adjusted if needed.
328 const unsigned MaxDepth
= 6;
330 bool llvm::isSplatValue(const Value
*V
, unsigned Depth
) {
331 assert(Depth
<= MaxDepth
&& "Limit Search Depth");
333 if (isa
<VectorType
>(V
->getType())) {
334 if (isa
<UndefValue
>(V
))
336 // FIXME: Constant splat analysis does not allow undef elements.
337 if (auto *C
= dyn_cast
<Constant
>(V
))
338 return C
->getSplatValue() != nullptr;
341 // FIXME: Constant splat analysis does not allow undef elements.
343 if (match(V
, m_ShuffleVector(m_Value(), m_Value(), m_Constant(Mask
))))
344 return Mask
->getSplatValue() != nullptr;
346 // The remaining tests are all recursive, so bail out if we hit the limit.
347 if (Depth
++ == MaxDepth
)
350 // If both operands of a binop are splats, the result is a splat.
352 if (match(V
, m_BinOp(m_Value(X
), m_Value(Y
))))
353 return isSplatValue(X
, Depth
) && isSplatValue(Y
, Depth
);
355 // If all operands of a select are splats, the result is a splat.
356 if (match(V
, m_Select(m_Value(X
), m_Value(Y
), m_Value(Z
))))
357 return isSplatValue(X
, Depth
) && isSplatValue(Y
, Depth
) &&
358 isSplatValue(Z
, Depth
);
360 // TODO: Add support for unary ops (fneg), casts, intrinsics (overflow ops).
365 MapVector
<Instruction
*, uint64_t>
366 llvm::computeMinimumValueSizes(ArrayRef
<BasicBlock
*> Blocks
, DemandedBits
&DB
,
367 const TargetTransformInfo
*TTI
) {
369 // DemandedBits will give us every value's live-out bits. But we want
370 // to ensure no extra casts would need to be inserted, so every DAG
371 // of connected values must have the same minimum bitwidth.
372 EquivalenceClasses
<Value
*> ECs
;
373 SmallVector
<Value
*, 16> Worklist
;
374 SmallPtrSet
<Value
*, 4> Roots
;
375 SmallPtrSet
<Value
*, 16> Visited
;
376 DenseMap
<Value
*, uint64_t> DBits
;
377 SmallPtrSet
<Instruction
*, 4> InstructionSet
;
378 MapVector
<Instruction
*, uint64_t> MinBWs
;
380 // Determine the roots. We work bottom-up, from truncs or icmps.
381 bool SeenExtFromIllegalType
= false;
382 for (auto *BB
: Blocks
)
383 for (auto &I
: *BB
) {
384 InstructionSet
.insert(&I
);
386 if (TTI
&& (isa
<ZExtInst
>(&I
) || isa
<SExtInst
>(&I
)) &&
387 !TTI
->isTypeLegal(I
.getOperand(0)->getType()))
388 SeenExtFromIllegalType
= true;
390 // Only deal with non-vector integers up to 64-bits wide.
391 if ((isa
<TruncInst
>(&I
) || isa
<ICmpInst
>(&I
)) &&
392 !I
.getType()->isVectorTy() &&
393 I
.getOperand(0)->getType()->getScalarSizeInBits() <= 64) {
394 // Don't make work for ourselves. If we know the loaded type is legal,
395 // don't add it to the worklist.
396 if (TTI
&& isa
<TruncInst
>(&I
) && TTI
->isTypeLegal(I
.getType()))
399 Worklist
.push_back(&I
);
404 if (Worklist
.empty() || (TTI
&& !SeenExtFromIllegalType
))
407 // Now proceed breadth-first, unioning values together.
408 while (!Worklist
.empty()) {
409 Value
*Val
= Worklist
.pop_back_val();
410 Value
*Leader
= ECs
.getOrInsertLeaderValue(Val
);
412 if (Visited
.count(Val
))
416 // Non-instructions terminate a chain successfully.
417 if (!isa
<Instruction
>(Val
))
419 Instruction
*I
= cast
<Instruction
>(Val
);
421 // If we encounter a type that is larger than 64 bits, we can't represent
423 if (DB
.getDemandedBits(I
).getBitWidth() > 64)
424 return MapVector
<Instruction
*, uint64_t>();
426 uint64_t V
= DB
.getDemandedBits(I
).getZExtValue();
430 // Casts, loads and instructions outside of our range terminate a chain
432 if (isa
<SExtInst
>(I
) || isa
<ZExtInst
>(I
) || isa
<LoadInst
>(I
) ||
433 !InstructionSet
.count(I
))
436 // Unsafe casts terminate a chain unsuccessfully. We can't do anything
437 // useful with bitcasts, ptrtoints or inttoptrs and it'd be unsafe to
438 // transform anything that relies on them.
439 if (isa
<BitCastInst
>(I
) || isa
<PtrToIntInst
>(I
) || isa
<IntToPtrInst
>(I
) ||
440 !I
->getType()->isIntegerTy()) {
441 DBits
[Leader
] |= ~0ULL;
445 // We don't modify the types of PHIs. Reductions will already have been
446 // truncated if possible, and inductions' sizes will have been chosen by
451 if (DBits
[Leader
] == ~0ULL)
452 // All bits demanded, no point continuing.
455 for (Value
*O
: cast
<User
>(I
)->operands()) {
456 ECs
.unionSets(Leader
, O
);
457 Worklist
.push_back(O
);
461 // Now we've discovered all values, walk them to see if there are
462 // any users we didn't see. If there are, we can't optimize that
464 for (auto &I
: DBits
)
465 for (auto *U
: I
.first
->users())
466 if (U
->getType()->isIntegerTy() && DBits
.count(U
) == 0)
467 DBits
[ECs
.getOrInsertLeaderValue(I
.first
)] |= ~0ULL;
469 for (auto I
= ECs
.begin(), E
= ECs
.end(); I
!= E
; ++I
) {
470 uint64_t LeaderDemandedBits
= 0;
471 for (auto MI
= ECs
.member_begin(I
), ME
= ECs
.member_end(); MI
!= ME
; ++MI
)
472 LeaderDemandedBits
|= DBits
[*MI
];
474 uint64_t MinBW
= (sizeof(LeaderDemandedBits
) * 8) -
475 llvm::countLeadingZeros(LeaderDemandedBits
);
476 // Round up to a power of 2
477 if (!isPowerOf2_64((uint64_t)MinBW
))
478 MinBW
= NextPowerOf2(MinBW
);
480 // We don't modify the types of PHIs. Reductions will already have been
481 // truncated if possible, and inductions' sizes will have been chosen by
483 // If we are required to shrink a PHI, abandon this entire equivalence class.
485 for (auto MI
= ECs
.member_begin(I
), ME
= ECs
.member_end(); MI
!= ME
; ++MI
)
486 if (isa
<PHINode
>(*MI
) && MinBW
< (*MI
)->getType()->getScalarSizeInBits()) {
493 for (auto MI
= ECs
.member_begin(I
), ME
= ECs
.member_end(); MI
!= ME
; ++MI
) {
494 if (!isa
<Instruction
>(*MI
))
496 Type
*Ty
= (*MI
)->getType();
497 if (Roots
.count(*MI
))
498 Ty
= cast
<Instruction
>(*MI
)->getOperand(0)->getType();
499 if (MinBW
< Ty
->getScalarSizeInBits())
500 MinBWs
[cast
<Instruction
>(*MI
)] = MinBW
;
507 /// Add all access groups in @p AccGroups to @p List.
508 template <typename ListT
>
509 static void addToAccessGroupList(ListT
&List
, MDNode
*AccGroups
) {
510 // Interpret an access group as a list containing itself.
511 if (AccGroups
->getNumOperands() == 0) {
512 assert(isValidAsAccessGroup(AccGroups
) && "Node must be an access group");
513 List
.insert(AccGroups
);
517 for (auto &AccGroupListOp
: AccGroups
->operands()) {
518 auto *Item
= cast
<MDNode
>(AccGroupListOp
.get());
519 assert(isValidAsAccessGroup(Item
) && "List item must be an access group");
524 MDNode
*llvm::uniteAccessGroups(MDNode
*AccGroups1
, MDNode
*AccGroups2
) {
529 if (AccGroups1
== AccGroups2
)
532 SmallSetVector
<Metadata
*, 4> Union
;
533 addToAccessGroupList(Union
, AccGroups1
);
534 addToAccessGroupList(Union
, AccGroups2
);
536 if (Union
.size() == 0)
538 if (Union
.size() == 1)
539 return cast
<MDNode
>(Union
.front());
541 LLVMContext
&Ctx
= AccGroups1
->getContext();
542 return MDNode::get(Ctx
, Union
.getArrayRef());
545 MDNode
*llvm::intersectAccessGroups(const Instruction
*Inst1
,
546 const Instruction
*Inst2
) {
547 bool MayAccessMem1
= Inst1
->mayReadOrWriteMemory();
548 bool MayAccessMem2
= Inst2
->mayReadOrWriteMemory();
550 if (!MayAccessMem1
&& !MayAccessMem2
)
553 return Inst2
->getMetadata(LLVMContext::MD_access_group
);
555 return Inst1
->getMetadata(LLVMContext::MD_access_group
);
557 MDNode
*MD1
= Inst1
->getMetadata(LLVMContext::MD_access_group
);
558 MDNode
*MD2
= Inst2
->getMetadata(LLVMContext::MD_access_group
);
564 // Use set for scalable 'contains' check.
565 SmallPtrSet
<Metadata
*, 4> AccGroupSet2
;
566 addToAccessGroupList(AccGroupSet2
, MD2
);
568 SmallVector
<Metadata
*, 4> Intersection
;
569 if (MD1
->getNumOperands() == 0) {
570 assert(isValidAsAccessGroup(MD1
) && "Node must be an access group");
571 if (AccGroupSet2
.count(MD1
))
572 Intersection
.push_back(MD1
);
574 for (const MDOperand
&Node
: MD1
->operands()) {
575 auto *Item
= cast
<MDNode
>(Node
.get());
576 assert(isValidAsAccessGroup(Item
) && "List item must be an access group");
577 if (AccGroupSet2
.count(Item
))
578 Intersection
.push_back(Item
);
582 if (Intersection
.size() == 0)
584 if (Intersection
.size() == 1)
585 return cast
<MDNode
>(Intersection
.front());
587 LLVMContext
&Ctx
= Inst1
->getContext();
588 return MDNode::get(Ctx
, Intersection
);
591 /// \returns \p I after propagating metadata from \p VL.
592 Instruction
*llvm::propagateMetadata(Instruction
*Inst
, ArrayRef
<Value
*> VL
) {
593 Instruction
*I0
= cast
<Instruction
>(VL
[0]);
594 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> Metadata
;
595 I0
->getAllMetadataOtherThanDebugLoc(Metadata
);
597 for (auto Kind
: {LLVMContext::MD_tbaa
, LLVMContext::MD_alias_scope
,
598 LLVMContext::MD_noalias
, LLVMContext::MD_fpmath
,
599 LLVMContext::MD_nontemporal
, LLVMContext::MD_invariant_load
,
600 LLVMContext::MD_access_group
}) {
601 MDNode
*MD
= I0
->getMetadata(Kind
);
603 for (int J
= 1, E
= VL
.size(); MD
&& J
!= E
; ++J
) {
604 const Instruction
*IJ
= cast
<Instruction
>(VL
[J
]);
605 MDNode
*IMD
= IJ
->getMetadata(Kind
);
607 case LLVMContext::MD_tbaa
:
608 MD
= MDNode::getMostGenericTBAA(MD
, IMD
);
610 case LLVMContext::MD_alias_scope
:
611 MD
= MDNode::getMostGenericAliasScope(MD
, IMD
);
613 case LLVMContext::MD_fpmath
:
614 MD
= MDNode::getMostGenericFPMath(MD
, IMD
);
616 case LLVMContext::MD_noalias
:
617 case LLVMContext::MD_nontemporal
:
618 case LLVMContext::MD_invariant_load
:
619 MD
= MDNode::intersect(MD
, IMD
);
621 case LLVMContext::MD_access_group
:
622 MD
= intersectAccessGroups(Inst
, IJ
);
625 llvm_unreachable("unhandled metadata");
629 Inst
->setMetadata(Kind
, MD
);
636 llvm::createBitMaskForGaps(IRBuilder
<> &Builder
, unsigned VF
,
637 const InterleaveGroup
<Instruction
> &Group
) {
638 // All 1's means mask is not needed.
639 if (Group
.getNumMembers() == Group
.getFactor())
642 // TODO: support reversed access.
643 assert(!Group
.isReverse() && "Reversed group not supported.");
645 SmallVector
<Constant
*, 16> Mask
;
646 for (unsigned i
= 0; i
< VF
; i
++)
647 for (unsigned j
= 0; j
< Group
.getFactor(); ++j
) {
648 unsigned HasMember
= Group
.getMember(j
) ? 1 : 0;
649 Mask
.push_back(Builder
.getInt1(HasMember
));
652 return ConstantVector::get(Mask
);
655 Constant
*llvm::createReplicatedMask(IRBuilder
<> &Builder
,
656 unsigned ReplicationFactor
, unsigned VF
) {
657 SmallVector
<Constant
*, 16> MaskVec
;
658 for (unsigned i
= 0; i
< VF
; i
++)
659 for (unsigned j
= 0; j
< ReplicationFactor
; j
++)
660 MaskVec
.push_back(Builder
.getInt32(i
));
662 return ConstantVector::get(MaskVec
);
665 Constant
*llvm::createInterleaveMask(IRBuilder
<> &Builder
, unsigned VF
,
667 SmallVector
<Constant
*, 16> Mask
;
668 for (unsigned i
= 0; i
< VF
; i
++)
669 for (unsigned j
= 0; j
< NumVecs
; j
++)
670 Mask
.push_back(Builder
.getInt32(j
* VF
+ i
));
672 return ConstantVector::get(Mask
);
675 Constant
*llvm::createStrideMask(IRBuilder
<> &Builder
, unsigned Start
,
676 unsigned Stride
, unsigned VF
) {
677 SmallVector
<Constant
*, 16> Mask
;
678 for (unsigned i
= 0; i
< VF
; i
++)
679 Mask
.push_back(Builder
.getInt32(Start
+ i
* Stride
));
681 return ConstantVector::get(Mask
);
684 Constant
*llvm::createSequentialMask(IRBuilder
<> &Builder
, unsigned Start
,
685 unsigned NumInts
, unsigned NumUndefs
) {
686 SmallVector
<Constant
*, 16> Mask
;
687 for (unsigned i
= 0; i
< NumInts
; i
++)
688 Mask
.push_back(Builder
.getInt32(Start
+ i
));
690 Constant
*Undef
= UndefValue::get(Builder
.getInt32Ty());
691 for (unsigned i
= 0; i
< NumUndefs
; i
++)
692 Mask
.push_back(Undef
);
694 return ConstantVector::get(Mask
);
697 /// A helper function for concatenating vectors. This function concatenates two
698 /// vectors having the same element type. If the second vector has fewer
699 /// elements than the first, it is padded with undefs.
700 static Value
*concatenateTwoVectors(IRBuilder
<> &Builder
, Value
*V1
,
702 VectorType
*VecTy1
= dyn_cast
<VectorType
>(V1
->getType());
703 VectorType
*VecTy2
= dyn_cast
<VectorType
>(V2
->getType());
704 assert(VecTy1
&& VecTy2
&&
705 VecTy1
->getScalarType() == VecTy2
->getScalarType() &&
706 "Expect two vectors with the same element type");
708 unsigned NumElts1
= VecTy1
->getNumElements();
709 unsigned NumElts2
= VecTy2
->getNumElements();
710 assert(NumElts1
>= NumElts2
&& "Unexpect the first vector has less elements");
712 if (NumElts1
> NumElts2
) {
713 // Extend with UNDEFs.
715 createSequentialMask(Builder
, 0, NumElts2
, NumElts1
- NumElts2
);
716 V2
= Builder
.CreateShuffleVector(V2
, UndefValue::get(VecTy2
), ExtMask
);
719 Constant
*Mask
= createSequentialMask(Builder
, 0, NumElts1
+ NumElts2
, 0);
720 return Builder
.CreateShuffleVector(V1
, V2
, Mask
);
723 Value
*llvm::concatenateVectors(IRBuilder
<> &Builder
, ArrayRef
<Value
*> Vecs
) {
724 unsigned NumVecs
= Vecs
.size();
725 assert(NumVecs
> 1 && "Should be at least two vectors");
727 SmallVector
<Value
*, 8> ResList
;
728 ResList
.append(Vecs
.begin(), Vecs
.end());
730 SmallVector
<Value
*, 8> TmpList
;
731 for (unsigned i
= 0; i
< NumVecs
- 1; i
+= 2) {
732 Value
*V0
= ResList
[i
], *V1
= ResList
[i
+ 1];
733 assert((V0
->getType() == V1
->getType() || i
== NumVecs
- 2) &&
734 "Only the last vector may have a different type");
736 TmpList
.push_back(concatenateTwoVectors(Builder
, V0
, V1
));
739 // Push the last vector if the total number of vectors is odd.
740 if (NumVecs
% 2 != 0)
741 TmpList
.push_back(ResList
[NumVecs
- 1]);
744 NumVecs
= ResList
.size();
745 } while (NumVecs
> 1);
750 bool llvm::maskIsAllZeroOrUndef(Value
*Mask
) {
751 auto *ConstMask
= dyn_cast
<Constant
>(Mask
);
754 if (ConstMask
->isNullValue() || isa
<UndefValue
>(ConstMask
))
756 for (unsigned I
= 0, E
= ConstMask
->getType()->getVectorNumElements(); I
!= E
;
758 if (auto *MaskElt
= ConstMask
->getAggregateElement(I
))
759 if (MaskElt
->isNullValue() || isa
<UndefValue
>(MaskElt
))
767 bool llvm::maskIsAllOneOrUndef(Value
*Mask
) {
768 auto *ConstMask
= dyn_cast
<Constant
>(Mask
);
771 if (ConstMask
->isAllOnesValue() || isa
<UndefValue
>(ConstMask
))
773 for (unsigned I
= 0, E
= ConstMask
->getType()->getVectorNumElements(); I
!= E
;
775 if (auto *MaskElt
= ConstMask
->getAggregateElement(I
))
776 if (MaskElt
->isAllOnesValue() || isa
<UndefValue
>(MaskElt
))
783 /// TODO: This is a lot like known bits, but for
784 /// vectors. Is there something we can common this with?
785 APInt
llvm::possiblyDemandedEltsInMask(Value
*Mask
) {
787 const unsigned VWidth
= cast
<VectorType
>(Mask
->getType())->getNumElements();
788 APInt DemandedElts
= APInt::getAllOnesValue(VWidth
);
789 if (auto *CV
= dyn_cast
<ConstantVector
>(Mask
))
790 for (unsigned i
= 0; i
< VWidth
; i
++)
791 if (CV
->getAggregateElement(i
)->isNullValue())
792 DemandedElts
.clearBit(i
);
796 bool InterleavedAccessInfo::isStrided(int Stride
) {
797 unsigned Factor
= std::abs(Stride
);
798 return Factor
>= 2 && Factor
<= MaxInterleaveGroupFactor
;
801 void InterleavedAccessInfo::collectConstStrideAccesses(
802 MapVector
<Instruction
*, StrideDescriptor
> &AccessStrideInfo
,
803 const ValueToValueMap
&Strides
) {
804 auto &DL
= TheLoop
->getHeader()->getModule()->getDataLayout();
806 // Since it's desired that the load/store instructions be maintained in
807 // "program order" for the interleaved access analysis, we have to visit the
808 // blocks in the loop in reverse postorder (i.e., in a topological order).
809 // Such an ordering will ensure that any load/store that may be executed
810 // before a second load/store will precede the second load/store in
812 LoopBlocksDFS
DFS(TheLoop
);
814 for (BasicBlock
*BB
: make_range(DFS
.beginRPO(), DFS
.endRPO()))
815 for (auto &I
: *BB
) {
816 auto *LI
= dyn_cast
<LoadInst
>(&I
);
817 auto *SI
= dyn_cast
<StoreInst
>(&I
);
821 Value
*Ptr
= getLoadStorePointerOperand(&I
);
822 // We don't check wrapping here because we don't know yet if Ptr will be
823 // part of a full group or a group with gaps. Checking wrapping for all
824 // pointers (even those that end up in groups with no gaps) will be overly
825 // conservative. For full groups, wrapping should be ok since if we would
826 // wrap around the address space we would do a memory access at nullptr
827 // even without the transformation. The wrapping checks are therefore
828 // deferred until after we've formed the interleaved groups.
829 int64_t Stride
= getPtrStride(PSE
, Ptr
, TheLoop
, Strides
,
830 /*Assume=*/true, /*ShouldCheckWrap=*/false);
832 const SCEV
*Scev
= replaceSymbolicStrideSCEV(PSE
, Strides
, Ptr
);
833 PointerType
*PtrTy
= dyn_cast
<PointerType
>(Ptr
->getType());
834 uint64_t Size
= DL
.getTypeAllocSize(PtrTy
->getElementType());
836 // An alignment of 0 means target ABI alignment.
837 unsigned Align
= getLoadStoreAlignment(&I
);
839 Align
= DL
.getABITypeAlignment(PtrTy
->getElementType());
841 AccessStrideInfo
[&I
] = StrideDescriptor(Stride
, Scev
, Size
, Align
);
845 // Analyze interleaved accesses and collect them into interleaved load and
848 // When generating code for an interleaved load group, we effectively hoist all
849 // loads in the group to the location of the first load in program order. When
850 // generating code for an interleaved store group, we sink all stores to the
851 // location of the last store. This code motion can change the order of load
852 // and store instructions and may break dependences.
854 // The code generation strategy mentioned above ensures that we won't violate
855 // any write-after-read (WAR) dependences.
857 // E.g., for the WAR dependence: a = A[i]; // (1)
860 // The store group of (2) is always inserted at or below (2), and the load
861 // group of (1) is always inserted at or above (1). Thus, the instructions will
862 // never be reordered. All other dependences are checked to ensure the
863 // correctness of the instruction reordering.
865 // The algorithm visits all memory accesses in the loop in bottom-up program
866 // order. Program order is established by traversing the blocks in the loop in
867 // reverse postorder when collecting the accesses.
869 // We visit the memory accesses in bottom-up order because it can simplify the
870 // construction of store groups in the presence of write-after-write (WAW)
873 // E.g., for the WAW dependence: A[i] = a; // (1)
875 // A[i + 1] = c; // (3)
877 // We will first create a store group with (3) and (2). (1) can't be added to
878 // this group because it and (2) are dependent. However, (1) can be grouped
879 // with other accesses that may precede it in program order. Note that a
880 // bottom-up order does not imply that WAW dependences should not be checked.
881 void InterleavedAccessInfo::analyzeInterleaving(
882 bool EnablePredicatedInterleavedMemAccesses
) {
883 LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
884 const ValueToValueMap
&Strides
= LAI
->getSymbolicStrides();
886 // Holds all accesses with a constant stride.
887 MapVector
<Instruction
*, StrideDescriptor
> AccessStrideInfo
;
888 collectConstStrideAccesses(AccessStrideInfo
, Strides
);
890 if (AccessStrideInfo
.empty())
893 // Collect the dependences in the loop.
894 collectDependences();
896 // Holds all interleaved store groups temporarily.
897 SmallSetVector
<InterleaveGroup
<Instruction
> *, 4> StoreGroups
;
898 // Holds all interleaved load groups temporarily.
899 SmallSetVector
<InterleaveGroup
<Instruction
> *, 4> LoadGroups
;
901 // Search in bottom-up program order for pairs of accesses (A and B) that can
902 // form interleaved load or store groups. In the algorithm below, access A
903 // precedes access B in program order. We initialize a group for B in the
904 // outer loop of the algorithm, and then in the inner loop, we attempt to
905 // insert each A into B's group if:
907 // 1. A and B have the same stride,
908 // 2. A and B have the same memory object size, and
909 // 3. A belongs in B's group according to its distance from B.
911 // Special care is taken to ensure group formation will not break any
913 for (auto BI
= AccessStrideInfo
.rbegin(), E
= AccessStrideInfo
.rend();
915 Instruction
*B
= BI
->first
;
916 StrideDescriptor DesB
= BI
->second
;
918 // Initialize a group for B if it has an allowable stride. Even if we don't
919 // create a group for B, we continue with the bottom-up algorithm to ensure
920 // we don't break any of B's dependences.
921 InterleaveGroup
<Instruction
> *Group
= nullptr;
922 if (isStrided(DesB
.Stride
) &&
923 (!isPredicated(B
->getParent()) || EnablePredicatedInterleavedMemAccesses
)) {
924 Group
= getInterleaveGroup(B
);
926 LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B
928 Group
= createInterleaveGroup(B
, DesB
.Stride
, DesB
.Align
);
930 if (B
->mayWriteToMemory())
931 StoreGroups
.insert(Group
);
933 LoadGroups
.insert(Group
);
936 for (auto AI
= std::next(BI
); AI
!= E
; ++AI
) {
937 Instruction
*A
= AI
->first
;
938 StrideDescriptor DesA
= AI
->second
;
940 // Our code motion strategy implies that we can't have dependences
941 // between accesses in an interleaved group and other accesses located
942 // between the first and last member of the group. Note that this also
943 // means that a group can't have more than one member at a given offset.
944 // The accesses in a group can have dependences with other accesses, but
945 // we must ensure we don't extend the boundaries of the group such that
946 // we encompass those dependent accesses.
948 // For example, assume we have the sequence of accesses shown below in a
951 // (1, 2) is a group | A[i] = a; // (1)
952 // | A[i-1] = b; // (2) |
953 // A[i-3] = c; // (3)
954 // A[i] = d; // (4) | (2, 4) is not a group
956 // Because accesses (2) and (3) are dependent, we can group (2) with (1)
957 // but not with (4). If we did, the dependent access (3) would be within
958 // the boundaries of the (2, 4) group.
959 if (!canReorderMemAccessesForInterleavedGroups(&*AI
, &*BI
)) {
960 // If a dependence exists and A is already in a group, we know that A
961 // must be a store since A precedes B and WAR dependences are allowed.
962 // Thus, A would be sunk below B. We release A's group to prevent this
963 // illegal code motion. A will then be free to form another group with
964 // instructions that precede it.
965 if (isInterleaved(A
)) {
966 InterleaveGroup
<Instruction
> *StoreGroup
= getInterleaveGroup(A
);
968 LLVM_DEBUG(dbgs() << "LV: Invalidated store group due to "
969 "dependence between " << *A
<< " and "<< *B
<< '\n');
971 StoreGroups
.remove(StoreGroup
);
972 releaseGroup(StoreGroup
);
975 // If a dependence exists and A is not already in a group (or it was
976 // and we just released it), B might be hoisted above A (if B is a
977 // load) or another store might be sunk below A (if B is a store). In
978 // either case, we can't add additional instructions to B's group. B
979 // will only form a group with instructions that it precedes.
983 // At this point, we've checked for illegal code motion. If either A or B
984 // isn't strided, there's nothing left to do.
985 if (!isStrided(DesA
.Stride
) || !isStrided(DesB
.Stride
))
988 // Ignore A if it's already in a group or isn't the same kind of memory
990 // Note that mayReadFromMemory() isn't mutually exclusive to
991 // mayWriteToMemory in the case of atomic loads. We shouldn't see those
992 // here, canVectorizeMemory() should have returned false - except for the
993 // case we asked for optimization remarks.
994 if (isInterleaved(A
) ||
995 (A
->mayReadFromMemory() != B
->mayReadFromMemory()) ||
996 (A
->mayWriteToMemory() != B
->mayWriteToMemory()))
999 // Check rules 1 and 2. Ignore A if its stride or size is different from
1001 if (DesA
.Stride
!= DesB
.Stride
|| DesA
.Size
!= DesB
.Size
)
1004 // Ignore A if the memory object of A and B don't belong to the same
1006 if (getLoadStoreAddressSpace(A
) != getLoadStoreAddressSpace(B
))
1009 // Calculate the distance from A to B.
1010 const SCEVConstant
*DistToB
= dyn_cast
<SCEVConstant
>(
1011 PSE
.getSE()->getMinusSCEV(DesA
.Scev
, DesB
.Scev
));
1014 int64_t DistanceToB
= DistToB
->getAPInt().getSExtValue();
1016 // Check rule 3. Ignore A if its distance to B is not a multiple of the
1018 if (DistanceToB
% static_cast<int64_t>(DesB
.Size
))
1021 // All members of a predicated interleave-group must have the same predicate,
1022 // and currently must reside in the same BB.
1023 BasicBlock
*BlockA
= A
->getParent();
1024 BasicBlock
*BlockB
= B
->getParent();
1025 if ((isPredicated(BlockA
) || isPredicated(BlockB
)) &&
1026 (!EnablePredicatedInterleavedMemAccesses
|| BlockA
!= BlockB
))
1029 // The index of A is the index of B plus A's distance to B in multiples
1032 Group
->getIndex(B
) + DistanceToB
/ static_cast<int64_t>(DesB
.Size
);
1034 // Try to insert A into B's group.
1035 if (Group
->insertMember(A
, IndexA
, DesA
.Align
)) {
1036 LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A
<< '\n'
1037 << " into the interleave group with" << *B
1039 InterleaveGroupMap
[A
] = Group
;
1041 // Set the first load in program order as the insert position.
1042 if (A
->mayReadFromMemory())
1043 Group
->setInsertPos(A
);
1045 } // Iteration over A accesses.
1046 } // Iteration over B accesses.
1048 // Remove interleaved store groups with gaps.
1049 for (auto *Group
: StoreGroups
)
1050 if (Group
->getNumMembers() != Group
->getFactor()) {
1052 dbgs() << "LV: Invalidate candidate interleaved store group due "
1054 releaseGroup(Group
);
1056 // Remove interleaved groups with gaps (currently only loads) whose memory
1057 // accesses may wrap around. We have to revisit the getPtrStride analysis,
1058 // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
1059 // not check wrapping (see documentation there).
1060 // FORNOW we use Assume=false;
1061 // TODO: Change to Assume=true but making sure we don't exceed the threshold
1062 // of runtime SCEV assumptions checks (thereby potentially failing to
1063 // vectorize altogether).
1064 // Additional optional optimizations:
1065 // TODO: If we are peeling the loop and we know that the first pointer doesn't
1066 // wrap then we can deduce that all pointers in the group don't wrap.
1067 // This means that we can forcefully peel the loop in order to only have to
1068 // check the first pointer for no-wrap. When we'll change to use Assume=true
1069 // we'll only need at most one runtime check per interleaved group.
1070 for (auto *Group
: LoadGroups
) {
1071 // Case 1: A full group. Can Skip the checks; For full groups, if the wide
1072 // load would wrap around the address space we would do a memory access at
1073 // nullptr even without the transformation.
1074 if (Group
->getNumMembers() == Group
->getFactor())
1077 // Case 2: If first and last members of the group don't wrap this implies
1078 // that all the pointers in the group don't wrap.
1079 // So we check only group member 0 (which is always guaranteed to exist),
1080 // and group member Factor - 1; If the latter doesn't exist we rely on
1081 // peeling (if it is a non-reversed accsess -- see Case 3).
1082 Value
*FirstMemberPtr
= getLoadStorePointerOperand(Group
->getMember(0));
1083 if (!getPtrStride(PSE
, FirstMemberPtr
, TheLoop
, Strides
, /*Assume=*/false,
1084 /*ShouldCheckWrap=*/true)) {
1086 dbgs() << "LV: Invalidate candidate interleaved group due to "
1087 "first group member potentially pointer-wrapping.\n");
1088 releaseGroup(Group
);
1091 Instruction
*LastMember
= Group
->getMember(Group
->getFactor() - 1);
1093 Value
*LastMemberPtr
= getLoadStorePointerOperand(LastMember
);
1094 if (!getPtrStride(PSE
, LastMemberPtr
, TheLoop
, Strides
, /*Assume=*/false,
1095 /*ShouldCheckWrap=*/true)) {
1097 dbgs() << "LV: Invalidate candidate interleaved group due to "
1098 "last group member potentially pointer-wrapping.\n");
1099 releaseGroup(Group
);
1102 // Case 3: A non-reversed interleaved load group with gaps: We need
1103 // to execute at least one scalar epilogue iteration. This will ensure
1104 // we don't speculatively access memory out-of-bounds. We only need
1105 // to look for a member at index factor - 1, since every group must have
1106 // a member at index zero.
1107 if (Group
->isReverse()) {
1109 dbgs() << "LV: Invalidate candidate interleaved group due to "
1110 "a reverse access with gaps.\n");
1111 releaseGroup(Group
);
1115 dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
1116 RequiresScalarEpilogue
= true;
1121 void InterleavedAccessInfo::invalidateGroupsRequiringScalarEpilogue() {
1122 // If no group had triggered the requirement to create an epilogue loop,
1123 // there is nothing to do.
1124 if (!requiresScalarEpilogue())
1127 // Avoid releasing a Group twice.
1128 SmallPtrSet
<InterleaveGroup
<Instruction
> *, 4> DelSet
;
1129 for (auto &I
: InterleaveGroupMap
) {
1130 InterleaveGroup
<Instruction
> *Group
= I
.second
;
1131 if (Group
->requiresScalarEpilogue())
1132 DelSet
.insert(Group
);
1134 for (auto *Ptr
: DelSet
) {
1137 << "LV: Invalidate candidate interleaved group due to gaps that "
1138 "require a scalar epilogue (not allowed under optsize) and cannot "
1139 "be masked (not enabled). \n");
1143 RequiresScalarEpilogue
= false;
1146 template <typename InstT
>
1147 void InterleaveGroup
<InstT
>::addMetadata(InstT
*NewInst
) const {
1148 llvm_unreachable("addMetadata can only be used for Instruction");
1153 void InterleaveGroup
<Instruction
>::addMetadata(Instruction
*NewInst
) const {
1154 SmallVector
<Value
*, 4> VL
;
1155 std::transform(Members
.begin(), Members
.end(), std::back_inserter(VL
),
1156 [](std::pair
<int, Instruction
*> p
) { return p
.second
; });
1157 propagateMetadata(NewInst
, VL
);