1 //===- LoopVectorizationLegality.cpp --------------------------------------===//
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 provides loop vectorization legality analysis. Original code
10 // resided in LoopVectorize.cpp for a long time.
12 // At this point, it is implemented as a utility class, not as an analysis
13 // pass. It should be easy to create an analysis pass around it if there
14 // is a need (but D45420 needs to happen first).
16 #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
17 #include "llvm/Analysis/VectorUtils.h"
18 #include "llvm/IR/IntrinsicInst.h"
22 #define LV_NAME "loop-vectorize"
23 #define DEBUG_TYPE LV_NAME
25 extern cl::opt
<bool> EnableVPlanPredication
;
28 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden
,
29 cl::desc("Enable if-conversion during vectorization."));
31 static cl::opt
<unsigned> PragmaVectorizeMemoryCheckThreshold(
32 "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden
,
33 cl::desc("The maximum allowed number of runtime memory checks with a "
34 "vectorize(enable) pragma."));
36 static cl::opt
<unsigned> VectorizeSCEVCheckThreshold(
37 "vectorize-scev-check-threshold", cl::init(16), cl::Hidden
,
38 cl::desc("The maximum number of SCEV checks allowed."));
40 static cl::opt
<unsigned> PragmaVectorizeSCEVCheckThreshold(
41 "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden
,
42 cl::desc("The maximum number of SCEV checks allowed with a "
43 "vectorize(enable) pragma"));
45 /// Maximum vectorization interleave count.
46 static const unsigned MaxInterleaveFactor
= 16;
50 OptimizationRemarkAnalysis
createLVMissedAnalysis(const char *PassName
,
54 Value
*CodeRegion
= TheLoop
->getHeader();
55 DebugLoc DL
= TheLoop
->getStartLoc();
58 CodeRegion
= I
->getParent();
59 // If there is no debug location attached to the instruction, revert back to
62 DL
= I
->getDebugLoc();
65 OptimizationRemarkAnalysis
R(PassName
, RemarkName
, DL
, CodeRegion
);
66 R
<< "loop not vectorized: ";
70 bool LoopVectorizeHints::Hint::validate(unsigned Val
) {
73 return isPowerOf2_32(Val
) && Val
<= VectorizerParams::MaxVectorWidth
;
75 return isPowerOf2_32(Val
) && Val
<= MaxInterleaveFactor
;
79 return (Val
== 0 || Val
== 1);
84 LoopVectorizeHints::LoopVectorizeHints(const Loop
*L
,
85 bool InterleaveOnlyWhenForced
,
86 OptimizationRemarkEmitter
&ORE
)
87 : Width("vectorize.width", VectorizerParams::VectorizationFactor
, HK_WIDTH
),
88 Interleave("interleave.count", InterleaveOnlyWhenForced
, HK_UNROLL
),
89 Force("vectorize.enable", FK_Undefined
, HK_FORCE
),
90 IsVectorized("isvectorized", 0, HK_ISVECTORIZED
), TheLoop(L
), ORE(ORE
) {
91 // Populate values with existing loop metadata.
92 getHintsFromMetadata();
94 // force-vector-interleave overrides DisableInterleaving.
95 if (VectorizerParams::isInterleaveForced())
96 Interleave
.Value
= VectorizerParams::VectorizationInterleave
;
98 if (IsVectorized
.Value
!= 1)
99 // If the vectorization width and interleaving count are both 1 then
100 // consider the loop to have been already vectorized because there's
101 // nothing more that we can do.
102 IsVectorized
.Value
= Width
.Value
== 1 && Interleave
.Value
== 1;
103 LLVM_DEBUG(if (InterleaveOnlyWhenForced
&& Interleave
.Value
== 1) dbgs()
104 << "LV: Interleaving disabled by the pass manager\n");
107 void LoopVectorizeHints::setAlreadyVectorized() {
108 LLVMContext
&Context
= TheLoop
->getHeader()->getContext();
110 MDNode
*IsVectorizedMD
= MDNode::get(
112 {MDString::get(Context
, "llvm.loop.isvectorized"),
113 ConstantAsMetadata::get(ConstantInt::get(Context
, APInt(32, 1)))});
114 MDNode
*LoopID
= TheLoop
->getLoopID();
116 makePostTransformationMetadata(Context
, LoopID
,
117 {Twine(Prefix(), "vectorize.").str(),
118 Twine(Prefix(), "interleave.").str()},
120 TheLoop
->setLoopID(NewLoopID
);
122 // Update internal cache.
123 IsVectorized
.Value
= 1;
126 bool LoopVectorizeHints::allowVectorization(
127 Function
*F
, Loop
*L
, bool VectorizeOnlyWhenForced
) const {
128 if (getForce() == LoopVectorizeHints::FK_Disabled
) {
129 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
130 emitRemarkWithHints();
134 if (VectorizeOnlyWhenForced
&& getForce() != LoopVectorizeHints::FK_Enabled
) {
135 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
136 emitRemarkWithHints();
140 if (getIsVectorized() == 1) {
141 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
142 // FIXME: Add interleave.disable metadata. This will allow
143 // vectorize.disable to be used without disabling the pass and errors
144 // to differentiate between disabled vectorization and a width of 1.
146 return OptimizationRemarkAnalysis(vectorizeAnalysisPassName(),
147 "AllDisabled", L
->getStartLoc(),
149 << "loop not vectorized: vectorization and interleaving are "
150 "explicitly disabled, or the loop has already been "
159 void LoopVectorizeHints::emitRemarkWithHints() const {
163 if (Force
.Value
== LoopVectorizeHints::FK_Disabled
)
164 return OptimizationRemarkMissed(LV_NAME
, "MissedExplicitlyDisabled",
165 TheLoop
->getStartLoc(),
166 TheLoop
->getHeader())
167 << "loop not vectorized: vectorization is explicitly disabled";
169 OptimizationRemarkMissed
R(LV_NAME
, "MissedDetails",
170 TheLoop
->getStartLoc(), TheLoop
->getHeader());
171 R
<< "loop not vectorized";
172 if (Force
.Value
== LoopVectorizeHints::FK_Enabled
) {
173 R
<< " (Force=" << NV("Force", true);
174 if (Width
.Value
!= 0)
175 R
<< ", Vector Width=" << NV("VectorWidth", Width
.Value
);
176 if (Interleave
.Value
!= 0)
177 R
<< ", Interleave Count=" << NV("InterleaveCount", Interleave
.Value
);
185 const char *LoopVectorizeHints::vectorizeAnalysisPassName() const {
188 if (getForce() == LoopVectorizeHints::FK_Disabled
)
190 if (getForce() == LoopVectorizeHints::FK_Undefined
&& getWidth() == 0)
192 return OptimizationRemarkAnalysis::AlwaysPrint
;
195 void LoopVectorizeHints::getHintsFromMetadata() {
196 MDNode
*LoopID
= TheLoop
->getLoopID();
200 // First operand should refer to the loop id itself.
201 assert(LoopID
->getNumOperands() > 0 && "requires at least one operand");
202 assert(LoopID
->getOperand(0) == LoopID
&& "invalid loop id");
204 for (unsigned i
= 1, ie
= LoopID
->getNumOperands(); i
< ie
; ++i
) {
205 const MDString
*S
= nullptr;
206 SmallVector
<Metadata
*, 4> Args
;
208 // The expected hint is either a MDString or a MDNode with the first
209 // operand a MDString.
210 if (const MDNode
*MD
= dyn_cast
<MDNode
>(LoopID
->getOperand(i
))) {
211 if (!MD
|| MD
->getNumOperands() == 0)
213 S
= dyn_cast
<MDString
>(MD
->getOperand(0));
214 for (unsigned i
= 1, ie
= MD
->getNumOperands(); i
< ie
; ++i
)
215 Args
.push_back(MD
->getOperand(i
));
217 S
= dyn_cast
<MDString
>(LoopID
->getOperand(i
));
218 assert(Args
.size() == 0 && "too many arguments for MDString");
224 // Check if the hint starts with the loop metadata prefix.
225 StringRef Name
= S
->getString();
226 if (Args
.size() == 1)
227 setHint(Name
, Args
[0]);
231 void LoopVectorizeHints::setHint(StringRef Name
, Metadata
*Arg
) {
232 if (!Name
.startswith(Prefix()))
234 Name
= Name
.substr(Prefix().size(), StringRef::npos
);
236 const ConstantInt
*C
= mdconst::dyn_extract
<ConstantInt
>(Arg
);
239 unsigned Val
= C
->getZExtValue();
241 Hint
*Hints
[] = {&Width
, &Interleave
, &Force
, &IsVectorized
};
242 for (auto H
: Hints
) {
243 if (Name
== H
->Name
) {
244 if (H
->validate(Val
))
247 LLVM_DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name
<< "'\n");
253 bool LoopVectorizationRequirements::doesNotMeet(
254 Function
*F
, Loop
*L
, const LoopVectorizeHints
&Hints
) {
255 const char *PassName
= Hints
.vectorizeAnalysisPassName();
257 if (UnsafeAlgebraInst
&& !Hints
.allowReordering()) {
259 return OptimizationRemarkAnalysisFPCommute(
260 PassName
, "CantReorderFPOps", UnsafeAlgebraInst
->getDebugLoc(),
261 UnsafeAlgebraInst
->getParent())
262 << "loop not vectorized: cannot prove it is safe to reorder "
263 "floating-point operations";
268 // Test if runtime memcheck thresholds are exceeded.
269 bool PragmaThresholdReached
=
270 NumRuntimePointerChecks
> PragmaVectorizeMemoryCheckThreshold
;
271 bool ThresholdReached
=
272 NumRuntimePointerChecks
> VectorizerParams::RuntimeMemoryCheckThreshold
;
273 if ((ThresholdReached
&& !Hints
.allowReordering()) ||
274 PragmaThresholdReached
) {
276 return OptimizationRemarkAnalysisAliasing(PassName
, "CantReorderMemOps",
279 << "loop not vectorized: cannot prove it is safe to reorder "
282 LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
289 // Return true if the inner loop \p Lp is uniform with regard to the outer loop
290 // \p OuterLp (i.e., if the outer loop is vectorized, all the vector lanes
291 // executing the inner loop will execute the same iterations). This check is
292 // very constrained for now but it will be relaxed in the future. \p Lp is
293 // considered uniform if it meets all the following conditions:
294 // 1) it has a canonical IV (starting from 0 and with stride 1),
295 // 2) its latch terminator is a conditional branch and,
296 // 3) its latch condition is a compare instruction whose operands are the
297 // canonical IV and an OuterLp invariant.
298 // This check doesn't take into account the uniformity of other conditions not
299 // related to the loop latch because they don't affect the loop uniformity.
301 // NOTE: We decided to keep all these checks and its associated documentation
302 // together so that we can easily have a picture of the current supported loop
303 // nests. However, some of the current checks don't depend on \p OuterLp and
304 // would be redundantly executed for each \p Lp if we invoked this function for
305 // different candidate outer loops. This is not the case for now because we
306 // don't currently have the infrastructure to evaluate multiple candidate outer
307 // loops and \p OuterLp will be a fixed parameter while we only support explicit
308 // outer loop vectorization. It's also very likely that these checks go away
309 // before introducing the aforementioned infrastructure. However, if this is not
310 // the case, we should move the \p OuterLp independent checks to a separate
311 // function that is only executed once for each \p Lp.
312 static bool isUniformLoop(Loop
*Lp
, Loop
*OuterLp
) {
313 assert(Lp
->getLoopLatch() && "Expected loop with a single latch.");
315 // If Lp is the outer loop, it's uniform by definition.
318 assert(OuterLp
->contains(Lp
) && "OuterLp must contain Lp.");
321 PHINode
*IV
= Lp
->getCanonicalInductionVariable();
323 LLVM_DEBUG(dbgs() << "LV: Canonical IV not found.\n");
328 BasicBlock
*Latch
= Lp
->getLoopLatch();
329 auto *LatchBr
= dyn_cast
<BranchInst
>(Latch
->getTerminator());
330 if (!LatchBr
|| LatchBr
->isUnconditional()) {
331 LLVM_DEBUG(dbgs() << "LV: Unsupported loop latch branch.\n");
336 auto *LatchCmp
= dyn_cast
<CmpInst
>(LatchBr
->getCondition());
339 dbgs() << "LV: Loop latch condition is not a compare instruction.\n");
343 Value
*CondOp0
= LatchCmp
->getOperand(0);
344 Value
*CondOp1
= LatchCmp
->getOperand(1);
345 Value
*IVUpdate
= IV
->getIncomingValueForBlock(Latch
);
346 if (!(CondOp0
== IVUpdate
&& OuterLp
->isLoopInvariant(CondOp1
)) &&
347 !(CondOp1
== IVUpdate
&& OuterLp
->isLoopInvariant(CondOp0
))) {
348 LLVM_DEBUG(dbgs() << "LV: Loop latch condition is not uniform.\n");
355 // Return true if \p Lp and all its nested loops are uniform with regard to \p
357 static bool isUniformLoopNest(Loop
*Lp
, Loop
*OuterLp
) {
358 if (!isUniformLoop(Lp
, OuterLp
))
361 // Check if nested loops are uniform.
362 for (Loop
*SubLp
: *Lp
)
363 if (!isUniformLoopNest(SubLp
, OuterLp
))
369 /// Check whether it is safe to if-convert this phi node.
371 /// Phi nodes with constant expressions that can trap are not safe to if
373 static bool canIfConvertPHINodes(BasicBlock
*BB
) {
374 for (PHINode
&Phi
: BB
->phis()) {
375 for (Value
*V
: Phi
.incoming_values())
376 if (auto *C
= dyn_cast
<Constant
>(V
))
383 static Type
*convertPointerToIntegerType(const DataLayout
&DL
, Type
*Ty
) {
384 if (Ty
->isPointerTy())
385 return DL
.getIntPtrType(Ty
);
387 // It is possible that char's or short's overflow when we ask for the loop's
388 // trip count, work around this by changing the type size.
389 if (Ty
->getScalarSizeInBits() < 32)
390 return Type::getInt32Ty(Ty
->getContext());
395 static Type
*getWiderType(const DataLayout
&DL
, Type
*Ty0
, Type
*Ty1
) {
396 Ty0
= convertPointerToIntegerType(DL
, Ty0
);
397 Ty1
= convertPointerToIntegerType(DL
, Ty1
);
398 if (Ty0
->getScalarSizeInBits() > Ty1
->getScalarSizeInBits())
403 /// Check that the instruction has outside loop users and is not an
404 /// identified reduction variable.
405 static bool hasOutsideLoopUser(const Loop
*TheLoop
, Instruction
*Inst
,
406 SmallPtrSetImpl
<Value
*> &AllowedExit
) {
407 // Reductions, Inductions and non-header phis are allowed to have exit users. All
408 // other instructions must not have external users.
409 if (!AllowedExit
.count(Inst
))
410 // Check that all of the users of the loop are inside the BB.
411 for (User
*U
: Inst
->users()) {
412 Instruction
*UI
= cast
<Instruction
>(U
);
413 // This user may be a reduction exit value.
414 if (!TheLoop
->contains(UI
)) {
415 LLVM_DEBUG(dbgs() << "LV: Found an outside user for : " << *UI
<< '\n');
422 int LoopVectorizationLegality::isConsecutivePtr(Value
*Ptr
) {
423 const ValueToValueMap
&Strides
=
424 getSymbolicStrides() ? *getSymbolicStrides() : ValueToValueMap();
426 int Stride
= getPtrStride(PSE
, Ptr
, TheLoop
, Strides
, true, false);
427 if (Stride
== 1 || Stride
== -1)
432 bool LoopVectorizationLegality::isUniform(Value
*V
) {
433 return LAI
->isUniform(V
);
436 bool LoopVectorizationLegality::canVectorizeOuterLoop() {
437 assert(!TheLoop
->empty() && "We are not vectorizing an outer loop.");
438 // Store the result and return it at the end instead of exiting early, in case
439 // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
441 bool DoExtraAnalysis
= ORE
->allowExtraAnalysis(DEBUG_TYPE
);
443 for (BasicBlock
*BB
: TheLoop
->blocks()) {
444 // Check whether the BB terminator is a BranchInst. Any other terminator is
445 // not supported yet.
446 auto *Br
= dyn_cast
<BranchInst
>(BB
->getTerminator());
448 LLVM_DEBUG(dbgs() << "LV: Unsupported basic block terminator.\n");
449 ORE
->emit(createMissedAnalysis("CFGNotUnderstood")
450 << "loop control flow is not understood by vectorizer");
457 // Check whether the BranchInst is a supported one. Only unconditional
458 // branches, conditional branches with an outer loop invariant condition or
459 // backedges are supported.
460 // FIXME: We skip these checks when VPlan predication is enabled as we
461 // want to allow divergent branches. This whole check will be removed
462 // once VPlan predication is on by default.
463 if (!EnableVPlanPredication
&& Br
&& Br
->isConditional() &&
464 !TheLoop
->isLoopInvariant(Br
->getCondition()) &&
465 !LI
->isLoopHeader(Br
->getSuccessor(0)) &&
466 !LI
->isLoopHeader(Br
->getSuccessor(1))) {
467 LLVM_DEBUG(dbgs() << "LV: Unsupported conditional branch.\n");
468 ORE
->emit(createMissedAnalysis("CFGNotUnderstood")
469 << "loop control flow is not understood by vectorizer");
477 // Check whether inner loops are uniform. At this point, we only support
478 // simple outer loops scenarios with uniform nested loops.
479 if (!isUniformLoopNest(TheLoop
/*loop nest*/,
480 TheLoop
/*context outer loop*/)) {
483 << "LV: Not vectorizing: Outer loop contains divergent loops.\n");
484 ORE
->emit(createMissedAnalysis("CFGNotUnderstood")
485 << "loop control flow is not understood by vectorizer");
492 // Check whether we are able to set up outer loop induction.
493 if (!setupOuterLoopInductions()) {
495 dbgs() << "LV: Not vectorizing: Unsupported outer loop Phi(s).\n");
496 ORE
->emit(createMissedAnalysis("UnsupportedPhi")
497 << "Unsupported outer loop Phi(s)");
507 void LoopVectorizationLegality::addInductionPhi(
508 PHINode
*Phi
, const InductionDescriptor
&ID
,
509 SmallPtrSetImpl
<Value
*> &AllowedExit
) {
510 Inductions
[Phi
] = ID
;
512 // In case this induction also comes with casts that we know we can ignore
513 // in the vectorized loop body, record them here. All casts could be recorded
514 // here for ignoring, but suffices to record only the first (as it is the
515 // only one that may bw used outside the cast sequence).
516 const SmallVectorImpl
<Instruction
*> &Casts
= ID
.getCastInsts();
518 InductionCastsToIgnore
.insert(*Casts
.begin());
520 Type
*PhiTy
= Phi
->getType();
521 const DataLayout
&DL
= Phi
->getModule()->getDataLayout();
523 // Get the widest type.
524 if (!PhiTy
->isFloatingPointTy()) {
526 WidestIndTy
= convertPointerToIntegerType(DL
, PhiTy
);
528 WidestIndTy
= getWiderType(DL
, PhiTy
, WidestIndTy
);
531 // Int inductions are special because we only allow one IV.
532 if (ID
.getKind() == InductionDescriptor::IK_IntInduction
&&
533 ID
.getConstIntStepValue() && ID
.getConstIntStepValue()->isOne() &&
534 isa
<Constant
>(ID
.getStartValue()) &&
535 cast
<Constant
>(ID
.getStartValue())->isNullValue()) {
537 // Use the phi node with the widest type as induction. Use the last
538 // one if there are multiple (no good reason for doing this other
539 // than it is expedient). We've checked that it begins at zero and
540 // steps by one, so this is a canonical induction variable.
541 if (!PrimaryInduction
|| PhiTy
== WidestIndTy
)
542 PrimaryInduction
= Phi
;
545 // Both the PHI node itself, and the "post-increment" value feeding
546 // back into the PHI node may have external users.
547 // We can allow those uses, except if the SCEVs we have for them rely
548 // on predicates that only hold within the loop, since allowing the exit
549 // currently means re-using this SCEV outside the loop (see PR33706 for more
551 if (PSE
.getUnionPredicate().isAlwaysTrue()) {
552 AllowedExit
.insert(Phi
);
553 AllowedExit
.insert(Phi
->getIncomingValueForBlock(TheLoop
->getLoopLatch()));
556 LLVM_DEBUG(dbgs() << "LV: Found an induction variable.\n");
559 bool LoopVectorizationLegality::setupOuterLoopInductions() {
560 BasicBlock
*Header
= TheLoop
->getHeader();
562 // Returns true if a given Phi is a supported induction.
563 auto isSupportedPhi
= [&](PHINode
&Phi
) -> bool {
564 InductionDescriptor ID
;
565 if (InductionDescriptor::isInductionPHI(&Phi
, TheLoop
, PSE
, ID
) &&
566 ID
.getKind() == InductionDescriptor::IK_IntInduction
) {
567 addInductionPhi(&Phi
, ID
, AllowedExit
);
570 // Bail out for any Phi in the outer loop header that is not a supported
574 << "LV: Found unsupported PHI for outer loop vectorization.\n");
579 if (llvm::all_of(Header
->phis(), isSupportedPhi
))
585 bool LoopVectorizationLegality::canVectorizeInstrs() {
586 BasicBlock
*Header
= TheLoop
->getHeader();
588 // Look for the attribute signaling the absence of NaNs.
589 Function
&F
= *Header
->getParent();
591 F
.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
593 // For each block in the loop.
594 for (BasicBlock
*BB
: TheLoop
->blocks()) {
595 // Scan the instructions in the block and look for hazards.
596 for (Instruction
&I
: *BB
) {
597 if (auto *Phi
= dyn_cast
<PHINode
>(&I
)) {
598 Type
*PhiTy
= Phi
->getType();
599 // Check that this PHI type is allowed.
600 if (!PhiTy
->isIntegerTy() && !PhiTy
->isFloatingPointTy() &&
601 !PhiTy
->isPointerTy()) {
602 ORE
->emit(createMissedAnalysis("CFGNotUnderstood", Phi
)
603 << "loop control flow is not understood by vectorizer");
604 LLVM_DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
608 // If this PHINode is not in the header block, then we know that we
609 // can convert it to select during if-conversion. No need to check if
610 // the PHIs in this block are induction or reduction variables.
612 // Non-header phi nodes that have outside uses can be vectorized. Add
613 // them to the list of allowed exits.
614 // Unsafe cyclic dependencies with header phis are identified during
615 // legalization for reduction, induction and first order
620 // We only allow if-converted PHIs with exactly two incoming values.
621 if (Phi
->getNumIncomingValues() != 2) {
622 ORE
->emit(createMissedAnalysis("CFGNotUnderstood", Phi
)
623 << "control flow not understood by vectorizer");
624 LLVM_DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
628 RecurrenceDescriptor RedDes
;
629 if (RecurrenceDescriptor::isReductionPHI(Phi
, TheLoop
, RedDes
, DB
, AC
,
631 if (RedDes
.hasUnsafeAlgebra())
632 Requirements
->addUnsafeAlgebraInst(RedDes
.getUnsafeAlgebraInst());
633 AllowedExit
.insert(RedDes
.getLoopExitInstr());
634 Reductions
[Phi
] = RedDes
;
638 // TODO: Instead of recording the AllowedExit, it would be good to record the
639 // complementary set: NotAllowedExit. These include (but may not be
641 // 1. Reduction phis as they represent the one-before-last value, which
642 // is not available when vectorized
643 // 2. Induction phis and increment when SCEV predicates cannot be used
644 // outside the loop - see addInductionPhi
645 // 3. Non-Phis with outside uses when SCEV predicates cannot be used
646 // outside the loop - see call to hasOutsideLoopUser in the non-phi
648 // 4. FirstOrderRecurrence phis that can possibly be handled by
650 // By recording these, we can then reason about ways to vectorize each
651 // of these NotAllowedExit.
652 InductionDescriptor ID
;
653 if (InductionDescriptor::isInductionPHI(Phi
, TheLoop
, PSE
, ID
)) {
654 addInductionPhi(Phi
, ID
, AllowedExit
);
655 if (ID
.hasUnsafeAlgebra() && !HasFunNoNaNAttr
)
656 Requirements
->addUnsafeAlgebraInst(ID
.getUnsafeAlgebraInst());
660 if (RecurrenceDescriptor::isFirstOrderRecurrence(Phi
, TheLoop
,
662 FirstOrderRecurrences
.insert(Phi
);
666 // As a last resort, coerce the PHI to a AddRec expression
667 // and re-try classifying it a an induction PHI.
668 if (InductionDescriptor::isInductionPHI(Phi
, TheLoop
, PSE
, ID
, true)) {
669 addInductionPhi(Phi
, ID
, AllowedExit
);
673 ORE
->emit(createMissedAnalysis("NonReductionValueUsedOutsideLoop", Phi
)
674 << "value that could not be identified as "
675 "reduction is used outside the loop");
676 LLVM_DEBUG(dbgs() << "LV: Found an unidentified PHI." << *Phi
<< "\n");
678 } // end of PHI handling
680 // We handle calls that:
681 // * Are debug info intrinsics.
682 // * Have a mapping to an IR intrinsic.
683 // * Have a vector version available.
684 auto *CI
= dyn_cast
<CallInst
>(&I
);
685 if (CI
&& !getVectorIntrinsicIDForCall(CI
, TLI
) &&
686 !isa
<DbgInfoIntrinsic
>(CI
) &&
687 !(CI
->getCalledFunction() && TLI
&&
688 TLI
->isFunctionVectorizable(CI
->getCalledFunction()->getName()))) {
689 // If the call is a recognized math libary call, it is likely that
690 // we can vectorize it given loosened floating-point constraints.
693 TLI
&& CI
->getCalledFunction() &&
694 CI
->getType()->isFloatingPointTy() &&
695 TLI
->getLibFunc(CI
->getCalledFunction()->getName(), Func
) &&
696 TLI
->hasOptimizedCodeGen(Func
);
699 // TODO: Ideally, we should not use clang-specific language here,
700 // but it's hard to provide meaningful yet generic advice.
701 // Also, should this be guarded by allowExtraAnalysis() and/or be part
702 // of the returned info from isFunctionVectorizable()?
703 ORE
->emit(createMissedAnalysis("CantVectorizeLibcall", CI
)
704 << "library call cannot be vectorized. "
705 "Try compiling with -fno-math-errno, -ffast-math, "
708 ORE
->emit(createMissedAnalysis("CantVectorizeCall", CI
)
709 << "call instruction cannot be vectorized");
712 dbgs() << "LV: Found a non-intrinsic callsite.\n");
716 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
717 // second argument is the same (i.e. loop invariant)
718 if (CI
&& hasVectorInstrinsicScalarOpd(
719 getVectorIntrinsicIDForCall(CI
, TLI
), 1)) {
720 auto *SE
= PSE
.getSE();
721 if (!SE
->isLoopInvariant(PSE
.getSCEV(CI
->getOperand(1)), TheLoop
)) {
722 ORE
->emit(createMissedAnalysis("CantVectorizeIntrinsic", CI
)
723 << "intrinsic instruction cannot be vectorized");
725 << "LV: Found unvectorizable intrinsic " << *CI
<< "\n");
730 // Check that the instruction return type is vectorizable.
731 // Also, we can't vectorize extractelement instructions.
732 if ((!VectorType::isValidElementType(I
.getType()) &&
733 !I
.getType()->isVoidTy()) ||
734 isa
<ExtractElementInst
>(I
)) {
735 ORE
->emit(createMissedAnalysis("CantVectorizeInstructionReturnType", &I
)
736 << "instruction return type cannot be vectorized");
737 LLVM_DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
741 // Check that the stored type is vectorizable.
742 if (auto *ST
= dyn_cast
<StoreInst
>(&I
)) {
743 Type
*T
= ST
->getValueOperand()->getType();
744 if (!VectorType::isValidElementType(T
)) {
745 ORE
->emit(createMissedAnalysis("CantVectorizeStore", ST
)
746 << "store instruction cannot be vectorized");
750 // FP instructions can allow unsafe algebra, thus vectorizable by
751 // non-IEEE-754 compliant SIMD units.
752 // This applies to floating-point math operations and calls, not memory
753 // operations, shuffles, or casts, as they don't change precision or
755 } else if (I
.getType()->isFloatingPointTy() && (CI
|| I
.isBinaryOp()) &&
757 LLVM_DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n");
758 Hints
->setPotentiallyUnsafe();
761 // Reduction instructions are allowed to have exit users.
762 // All other instructions must not have external users.
763 if (hasOutsideLoopUser(TheLoop
, &I
, AllowedExit
)) {
764 // We can safely vectorize loops where instructions within the loop are
765 // used outside the loop only if the SCEV predicates within the loop is
766 // same as outside the loop. Allowing the exit means reusing the SCEV
768 if (PSE
.getUnionPredicate().isAlwaysTrue()) {
769 AllowedExit
.insert(&I
);
772 ORE
->emit(createMissedAnalysis("ValueUsedOutsideLoop", &I
)
773 << "value cannot be used outside the loop");
779 if (!PrimaryInduction
) {
780 LLVM_DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
781 if (Inductions
.empty()) {
782 ORE
->emit(createMissedAnalysis("NoInductionVariable")
783 << "loop induction variable could not be identified");
785 } else if (!WidestIndTy
) {
786 ORE
->emit(createMissedAnalysis("NoIntegerInductionVariable")
787 << "integer loop induction variable could not be identified");
792 // Now we know the widest induction type, check if our found induction
793 // is the same size. If it's not, unset it here and InnerLoopVectorizer
794 // will create another.
795 if (PrimaryInduction
&& WidestIndTy
!= PrimaryInduction
->getType())
796 PrimaryInduction
= nullptr;
801 bool LoopVectorizationLegality::canVectorizeMemory() {
802 LAI
= &(*GetLAA
)(*TheLoop
);
803 const OptimizationRemarkAnalysis
*LAR
= LAI
->getReport();
806 return OptimizationRemarkAnalysis(Hints
->vectorizeAnalysisPassName(),
807 "loop not vectorized: ", *LAR
);
810 if (!LAI
->canVectorizeMemory())
813 if (LAI
->hasDependenceInvolvingLoopInvariantAddress()) {
814 ORE
->emit(createMissedAnalysis("CantVectorizeStoreToLoopInvariantAddress")
815 << "write to a loop invariant address could not "
818 dbgs() << "LV: Non vectorizable stores to a uniform address\n");
821 Requirements
->addRuntimePointerChecks(LAI
->getNumRuntimePointerChecks());
822 PSE
.addPredicate(LAI
->getPSE().getUnionPredicate());
827 bool LoopVectorizationLegality::isInductionPhi(const Value
*V
) {
828 Value
*In0
= const_cast<Value
*>(V
);
829 PHINode
*PN
= dyn_cast_or_null
<PHINode
>(In0
);
833 return Inductions
.count(PN
);
836 bool LoopVectorizationLegality::isCastedInductionVariable(const Value
*V
) {
837 auto *Inst
= dyn_cast
<Instruction
>(V
);
838 return (Inst
&& InductionCastsToIgnore
.count(Inst
));
841 bool LoopVectorizationLegality::isInductionVariable(const Value
*V
) {
842 return isInductionPhi(V
) || isCastedInductionVariable(V
);
845 bool LoopVectorizationLegality::isFirstOrderRecurrence(const PHINode
*Phi
) {
846 return FirstOrderRecurrences
.count(Phi
);
849 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock
*BB
) {
850 return LoopAccessInfo::blockNeedsPredication(BB
, TheLoop
, DT
);
853 bool LoopVectorizationLegality::blockCanBePredicated(
854 BasicBlock
*BB
, SmallPtrSetImpl
<Value
*> &SafePtrs
) {
855 const bool IsAnnotatedParallel
= TheLoop
->isAnnotatedParallel();
857 for (Instruction
&I
: *BB
) {
858 // Check that we don't have a constant expression that can trap as operand.
859 for (Value
*Operand
: I
.operands()) {
860 if (auto *C
= dyn_cast
<Constant
>(Operand
))
864 // We might be able to hoist the load.
865 if (I
.mayReadFromMemory()) {
866 auto *LI
= dyn_cast
<LoadInst
>(&I
);
869 if (!SafePtrs
.count(LI
->getPointerOperand())) {
870 // !llvm.mem.parallel_loop_access implies if-conversion safety.
871 // Otherwise, record that the load needs (real or emulated) masking
872 // and let the cost model decide.
873 if (!IsAnnotatedParallel
)
879 if (I
.mayWriteToMemory()) {
880 auto *SI
= dyn_cast
<StoreInst
>(&I
);
883 // Predicated store requires some form of masking:
884 // 1) masked store HW instruction,
885 // 2) emulation via load-blend-store (only if safe and legal to do so,
886 // be aware on the race conditions), or
887 // 3) element-by-element predicate check and scalar store.
898 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
899 if (!EnableIfConversion
) {
900 ORE
->emit(createMissedAnalysis("IfConversionDisabled")
901 << "if-conversion is disabled");
905 assert(TheLoop
->getNumBlocks() > 1 && "Single block loops are vectorizable");
907 // A list of pointers that we can safely read and write to.
908 SmallPtrSet
<Value
*, 8> SafePointes
;
910 // Collect safe addresses.
911 for (BasicBlock
*BB
: TheLoop
->blocks()) {
912 if (blockNeedsPredication(BB
))
915 for (Instruction
&I
: *BB
)
916 if (auto *Ptr
= getLoadStorePointerOperand(&I
))
917 SafePointes
.insert(Ptr
);
920 // Collect the blocks that need predication.
921 BasicBlock
*Header
= TheLoop
->getHeader();
922 for (BasicBlock
*BB
: TheLoop
->blocks()) {
923 // We don't support switch statements inside loops.
924 if (!isa
<BranchInst
>(BB
->getTerminator())) {
925 ORE
->emit(createMissedAnalysis("LoopContainsSwitch", BB
->getTerminator())
926 << "loop contains a switch statement");
930 // We must be able to predicate all blocks that need to be predicated.
931 if (blockNeedsPredication(BB
)) {
932 if (!blockCanBePredicated(BB
, SafePointes
)) {
933 ORE
->emit(createMissedAnalysis("NoCFGForSelect", BB
->getTerminator())
934 << "control flow cannot be substituted for a select");
937 } else if (BB
!= Header
&& !canIfConvertPHINodes(BB
)) {
938 ORE
->emit(createMissedAnalysis("NoCFGForSelect", BB
->getTerminator())
939 << "control flow cannot be substituted for a select");
944 // We can if-convert this loop.
948 // Helper function to canVectorizeLoopNestCFG.
949 bool LoopVectorizationLegality::canVectorizeLoopCFG(Loop
*Lp
,
950 bool UseVPlanNativePath
) {
951 assert((UseVPlanNativePath
|| Lp
->empty()) &&
952 "VPlan-native path is not enabled.");
954 // TODO: ORE should be improved to show more accurate information when an
955 // outer loop can't be vectorized because a nested loop is not understood or
956 // legal. Something like: "outer_loop_location: loop not vectorized:
957 // (inner_loop_location) loop control flow is not understood by vectorizer".
959 // Store the result and return it at the end instead of exiting early, in case
960 // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
962 bool DoExtraAnalysis
= ORE
->allowExtraAnalysis(DEBUG_TYPE
);
964 // We must have a loop in canonical form. Loops with indirectbr in them cannot
966 if (!Lp
->getLoopPreheader()) {
967 LLVM_DEBUG(dbgs() << "LV: Loop doesn't have a legal pre-header.\n");
968 ORE
->emit(createMissedAnalysis("CFGNotUnderstood")
969 << "loop control flow is not understood by vectorizer");
976 // We must have a single backedge.
977 if (Lp
->getNumBackEdges() != 1) {
978 ORE
->emit(createMissedAnalysis("CFGNotUnderstood")
979 << "loop control flow is not understood by vectorizer");
986 // We must have a single exiting block.
987 if (!Lp
->getExitingBlock()) {
988 ORE
->emit(createMissedAnalysis("CFGNotUnderstood")
989 << "loop control flow is not understood by vectorizer");
996 // We only handle bottom-tested loops, i.e. loop in which the condition is
997 // checked at the end of each iteration. With that we can assume that all
998 // instructions in the loop are executed the same number of times.
999 if (Lp
->getExitingBlock() != Lp
->getLoopLatch()) {
1000 ORE
->emit(createMissedAnalysis("CFGNotUnderstood")
1001 << "loop control flow is not understood by vectorizer");
1002 if (DoExtraAnalysis
)
1011 bool LoopVectorizationLegality::canVectorizeLoopNestCFG(
1012 Loop
*Lp
, bool UseVPlanNativePath
) {
1013 // Store the result and return it at the end instead of exiting early, in case
1014 // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1016 bool DoExtraAnalysis
= ORE
->allowExtraAnalysis(DEBUG_TYPE
);
1017 if (!canVectorizeLoopCFG(Lp
, UseVPlanNativePath
)) {
1018 if (DoExtraAnalysis
)
1024 // Recursively check whether the loop control flow of nested loops is
1026 for (Loop
*SubLp
: *Lp
)
1027 if (!canVectorizeLoopNestCFG(SubLp
, UseVPlanNativePath
)) {
1028 if (DoExtraAnalysis
)
1037 bool LoopVectorizationLegality::canVectorize(bool UseVPlanNativePath
) {
1038 // Store the result and return it at the end instead of exiting early, in case
1039 // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1042 bool DoExtraAnalysis
= ORE
->allowExtraAnalysis(DEBUG_TYPE
);
1043 // Check whether the loop-related control flow in the loop nest is expected by
1045 if (!canVectorizeLoopNestCFG(TheLoop
, UseVPlanNativePath
)) {
1046 if (DoExtraAnalysis
)
1052 // We need to have a loop header.
1053 LLVM_DEBUG(dbgs() << "LV: Found a loop: " << TheLoop
->getHeader()->getName()
1056 // Specific checks for outer loops. We skip the remaining legal checks at this
1057 // point because they don't support outer loops.
1058 if (!TheLoop
->empty()) {
1059 assert(UseVPlanNativePath
&& "VPlan-native path is not enabled.");
1061 if (!canVectorizeOuterLoop()) {
1062 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Unsupported outer loop.\n");
1063 // TODO: Implement DoExtraAnalysis when subsequent legal checks support
1068 LLVM_DEBUG(dbgs() << "LV: We can vectorize this outer loop!\n");
1072 assert(TheLoop
->empty() && "Inner loop expected.");
1073 // Check if we can if-convert non-single-bb loops.
1074 unsigned NumBlocks
= TheLoop
->getNumBlocks();
1075 if (NumBlocks
!= 1 && !canVectorizeWithIfConvert()) {
1076 LLVM_DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1077 if (DoExtraAnalysis
)
1083 // Check if we can vectorize the instructions and CFG in this loop.
1084 if (!canVectorizeInstrs()) {
1085 LLVM_DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
1086 if (DoExtraAnalysis
)
1092 // Go over each instruction and look at memory deps.
1093 if (!canVectorizeMemory()) {
1094 LLVM_DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
1095 if (DoExtraAnalysis
)
1101 LLVM_DEBUG(dbgs() << "LV: We can vectorize this loop"
1102 << (LAI
->getRuntimePointerChecking()->Need
1103 ? " (with a runtime bound check)"
1107 unsigned SCEVThreshold
= VectorizeSCEVCheckThreshold
;
1108 if (Hints
->getForce() == LoopVectorizeHints::FK_Enabled
)
1109 SCEVThreshold
= PragmaVectorizeSCEVCheckThreshold
;
1111 if (PSE
.getUnionPredicate().getComplexity() > SCEVThreshold
) {
1112 ORE
->emit(createMissedAnalysis("TooManySCEVRunTimeChecks")
1113 << "Too many SCEV assumptions need to be made and checked "
1115 LLVM_DEBUG(dbgs() << "LV: Too many SCEV checks needed.\n");
1116 if (DoExtraAnalysis
)
1122 // Okay! We've done all the tests. If any have failed, return false. Otherwise
1123 // we can vectorize, and at this point we don't have any other mem analysis
1124 // which may limit our maximum vectorization factor, so just return true with
1129 bool LoopVectorizationLegality::canFoldTailByMasking() {
1131 LLVM_DEBUG(dbgs() << "LV: checking if tail can be folded by masking.\n");
1133 if (!PrimaryInduction
) {
1134 ORE
->emit(createMissedAnalysis("NoPrimaryInduction")
1135 << "Missing a primary induction variable in the loop, which is "
1136 << "needed in order to fold tail by masking as required.");
1137 LLVM_DEBUG(dbgs() << "LV: No primary induction, cannot fold tail by "
1142 // TODO: handle reductions when tail is folded by masking.
1143 if (!Reductions
.empty()) {
1144 ORE
->emit(createMissedAnalysis("ReductionFoldingTailByMasking")
1145 << "Cannot fold tail by masking in the presence of reductions.");
1146 LLVM_DEBUG(dbgs() << "LV: Loop has reductions, cannot fold tail by "
1151 // TODO: handle outside users when tail is folded by masking.
1152 for (auto *AE
: AllowedExit
) {
1153 // Check that all users of allowed exit values are inside the loop.
1154 for (User
*U
: AE
->users()) {
1155 Instruction
*UI
= cast
<Instruction
>(U
);
1156 if (TheLoop
->contains(UI
))
1158 ORE
->emit(createMissedAnalysis("LiveOutFoldingTailByMasking")
1159 << "Cannot fold tail by masking in the presence of live outs.");
1160 LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking, loop has an "
1161 << "outside user for : " << *UI
<< '\n');
1166 // The list of pointers that we can safely read and write to remains empty.
1167 SmallPtrSet
<Value
*, 8> SafePointers
;
1169 // Check and mark all blocks for predication, including those that ordinarily
1170 // do not need predication such as the header block.
1171 for (BasicBlock
*BB
: TheLoop
->blocks()) {
1172 if (!blockCanBePredicated(BB
, SafePointers
)) {
1173 ORE
->emit(createMissedAnalysis("NoCFGForSelect", BB
->getTerminator())
1174 << "control flow cannot be substituted for a select");
1175 LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking as required.\n");
1180 LLVM_DEBUG(dbgs() << "LV: can fold tail by masking.\n");