LLVM 23.0.0git
LoopVectorizationLegality.cpp
Go to the documentation of this file.
1//===- LoopVectorizationLegality.cpp --------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides loop vectorization legality analysis. Original code
10// resided in LoopVectorize.cpp for a long time.
11//
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).
15//
16
19#include "llvm/Analysis/Loads.h"
28#include "llvm/IR/Dominators.h"
33
34using namespace llvm;
35using namespace PatternMatch;
36
37#define LV_NAME "loop-vectorize"
38#define DEBUG_TYPE LV_NAME
39
40static cl::opt<bool>
41 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
42 cl::desc("Enable if-conversion during vectorization."));
43
44static cl::opt<bool>
45AllowStridedPointerIVs("lv-strided-pointer-ivs", cl::init(false), cl::Hidden,
46 cl::desc("Enable recognition of non-constant strided "
47 "pointer induction variables."));
48
49static cl::opt<bool>
50 HintsAllowReordering("hints-allow-reordering", cl::init(true), cl::Hidden,
51 cl::desc("Allow enabling loop hints to reorder "
52 "FP operations during vectorization."));
53
54// TODO: Move size-based thresholds out of legality checking, make cost based
55// decisions instead of hard thresholds.
57 "vectorize-scev-check-threshold", cl::init(16), cl::Hidden,
58 cl::desc("The maximum number of SCEV checks allowed."));
59
61 "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden,
62 cl::desc("The maximum number of SCEV checks allowed with a "
63 "vectorize(enable) pragma"));
64
67 "scalable-vectorization", cl::init(LoopVectorizeHints::SK_Unspecified),
69 cl::desc("Control whether the compiler can use scalable vectors to "
70 "vectorize a loop"),
73 "Scalable vectorization is disabled."),
76 "Scalable vectorization is available and favored when the "
77 "cost is inconclusive."),
80 "Scalable vectorization is available and favored when the "
81 "cost is inconclusive."),
84 "Scalable vectorization is available and always favored when "
85 "feasible")));
86
88 "enable-histogram-loop-vectorization", cl::init(false), cl::Hidden,
89 cl::desc("Enables autovectorization of some loops containing histograms"));
90
91/// Maximum vectorization interleave count.
92static const unsigned MaxInterleaveFactor = 16;
93
94namespace llvm {
95
96bool LoopVectorizeHints::Hint::validate(unsigned Val) {
97 switch (Kind) {
98 case HK_WIDTH:
100 case HK_INTERLEAVE:
101 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
102 case HK_FORCE:
103 return (Val <= 1);
104 case HK_ISVECTORIZED:
105 case HK_PREDICATE:
106 case HK_SCALABLE:
107 return (Val == 0 || Val == 1);
108 }
109 return false;
110}
111
113 bool InterleaveOnlyWhenForced,
116 : Width("vectorize.width", VectorizerParams::VectorizationFactor, HK_WIDTH),
117 Interleave("interleave.count", InterleaveOnlyWhenForced, HK_INTERLEAVE),
118 Force("vectorize.enable", FK_Undefined, HK_FORCE),
119 IsVectorized("isvectorized", 0, HK_ISVECTORIZED),
120 Predicate("vectorize.predicate.enable", FK_Undefined, HK_PREDICATE),
121 Scalable("vectorize.scalable.enable", SK_Unspecified, HK_SCALABLE),
122 TheLoop(L), ORE(ORE) {
123 // Populate values with existing loop metadata.
124 getHintsFromMetadata();
125
126 // force-vector-interleave overrides DisableInterleaving.
129
130 // If the metadata doesn't explicitly specify whether to enable scalable
131 // vectorization, then decide based on the following criteria (increasing
132 // level of priority):
133 // - Target default
134 // - Metadata width
135 // - Force option (always overrides)
137 if (TTI)
138 Scalable.Value = TTI->enableScalableVectorization() ? SK_PreferScalable
140
141 if (Width.Value)
142 // If the width is set, but the metadata says nothing about the scalable
143 // property, then assume it concerns only a fixed-width UserVF.
144 // If width is not set, the flag takes precedence.
145 Scalable.Value = SK_FixedWidthOnly;
146 }
147
148 // If the flag is set to force any use of scalable vectors, override the loop
149 // hints.
150 if (ForceScalableVectorization.getValue() !=
152 Scalable.Value = ForceScalableVectorization.getValue();
153
154 // Scalable vectorization is disabled if no preference is specified.
156 Scalable.Value = SK_FixedWidthOnly;
157
158 if (IsVectorized.Value != 1)
159 // If the vectorization width and interleaving count are both 1 then
160 // consider the loop to have been already vectorized because there's
161 // nothing more that we can do.
162 IsVectorized.Value =
164 LLVM_DEBUG(if (InterleaveOnlyWhenForced && getInterleave() == 1) dbgs()
165 << "LV: Interleaving disabled by the pass manager\n");
166}
167
169 TheLoop->addIntLoopAttribute("llvm.loop.isvectorized", 1,
170 {Twine(Prefix(), "vectorize.").str(),
171 Twine(Prefix(), "interleave.").str()});
172
173 // Update internal cache.
174 IsVectorized.Value = 1;
175}
176
177void LoopVectorizeHints::reportDisallowedVectorization(
178 const StringRef DebugMsg, const StringRef RemarkName,
179 const StringRef RemarkMsg, const Loop *L) const {
180 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: " << DebugMsg << ".\n");
181 ORE.emit(OptimizationRemarkMissed(LV_NAME, RemarkName, L->getStartLoc(),
182 L->getHeader())
183 << "loop not vectorized: " << RemarkMsg);
184}
185
187 Function *F, Loop *L, bool VectorizeOnlyWhenForced) const {
189 if (Force.Value == LoopVectorizeHints::FK_Disabled) {
190 reportDisallowedVectorization("#pragma vectorize disable",
191 "MissedExplicitlyDisabled",
192 "vectorization is explicitly disabled", L);
193 } else if (hasDisableAllTransformsHint(L)) {
194 reportDisallowedVectorization("loop hasDisableAllTransformsHint",
195 "MissedTransformsDisabled",
196 "loop transformations are disabled", L);
197 } else {
198 llvm_unreachable("loop vect disabled for an unknown reason");
199 }
200 return false;
201 }
202
203 if (VectorizeOnlyWhenForced && getForce() != LoopVectorizeHints::FK_Enabled) {
204 reportDisallowedVectorization(
205 "VectorizeOnlyWhenForced is set, and no #pragma vectorize enable",
206 "MissedForceOnly", "only vectorizing loops that explicitly request it",
207 L);
208 return false;
209 }
210
211 if (getIsVectorized() == 1) {
212 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
213 // FIXME: Add interleave.disable metadata. This will allow
214 // vectorize.disable to be used without disabling the pass and errors
215 // to differentiate between disabled vectorization and a width of 1.
216 ORE.emit([&]() {
217 return OptimizationRemarkAnalysis(LV_NAME, "AllDisabled",
218 L->getStartLoc(), L->getHeader())
219 << "loop not vectorized: vectorization and interleaving are "
220 "explicitly disabled, or the loop has already been "
221 "vectorized";
222 });
223 return false;
224 }
225
226 return true;
227}
228
230 using namespace ore;
231
232 ORE.emit([&]() {
233 if (Force.Value == LoopVectorizeHints::FK_Disabled)
234 return OptimizationRemarkMissed(LV_NAME, "MissedExplicitlyDisabled",
235 TheLoop->getStartLoc(),
236 TheLoop->getHeader())
237 << "loop not vectorized: vectorization is explicitly disabled";
238
239 OptimizationRemarkMissed R(LV_NAME, "MissedDetails", TheLoop->getStartLoc(),
240 TheLoop->getHeader());
241 R << "loop not vectorized";
242 if (Force.Value == LoopVectorizeHints::FK_Enabled) {
243 R << " (Force=" << NV("Force", true);
244 if (Width.Value != 0)
245 R << ", Vector Width=" << NV("VectorWidth", getWidth());
246 if (getInterleave() != 0)
247 R << ", Interleave Count=" << NV("InterleaveCount", getInterleave());
248 R << ")";
249 }
250 return R;
251 });
252}
253
255 // Allow the vectorizer to change the order of operations if enabling
256 // loop hints are provided
257 ElementCount EC = getWidth();
258 return HintsAllowReordering &&
260 EC.getKnownMinValue() > 1);
261}
262
263void LoopVectorizeHints::getHintsFromMetadata() {
264 MDNode *LoopID = TheLoop->getLoopID();
265 if (!LoopID)
266 return;
267
268 // First operand should refer to the loop id itself.
269 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
270 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
271
272 for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
273 const MDString *S = nullptr;
275
276 // The expected hint is either a MDString or a MDNode with the first
277 // operand a MDString.
278 if (const MDNode *MD = dyn_cast<MDNode>(MDO)) {
279 if (!MD || MD->getNumOperands() == 0)
280 continue;
281 S = dyn_cast<MDString>(MD->getOperand(0));
282 for (unsigned Idx = 1; Idx < MD->getNumOperands(); ++Idx)
283 Args.push_back(MD->getOperand(Idx));
284 } else {
285 S = dyn_cast<MDString>(MDO);
286 assert(Args.size() == 0 && "too many arguments for MDString");
287 }
288
289 if (!S)
290 continue;
291
292 // Check if the hint starts with the loop metadata prefix.
293 StringRef Name = S->getString();
294 if (Args.size() == 1)
295 setHint(Name, Args[0]);
296 }
297}
298
299void LoopVectorizeHints::setHint(StringRef Name, Metadata *Arg) {
300 if (!Name.consume_front(Prefix()))
301 return;
302
303 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
304 if (!C)
305 return;
306 unsigned Val = C->getZExtValue();
307
308 Hint *Hints[] = {&Width, &Interleave, &Force,
309 &IsVectorized, &Predicate, &Scalable};
310 for (auto *H : Hints) {
311 if (Name == H->Name) {
312 if (H->validate(Val))
313 H->Value = Val;
314 else
315 LLVM_DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
316 break;
317 }
318 }
319}
320
321// Return true if the inner loop \p Lp is uniform with regard to the outer loop
322// \p OuterLp (i.e., if the outer loop is vectorized, all the vector lanes
323// executing the inner loop will execute the same iterations). This check is
324// very constrained for now but it will be relaxed in the future. \p Lp is
325// considered uniform if it meets all the following conditions:
326// 1) it has a canonical IV (starting from 0 and with stride 1),
327// 2) its latch terminator is a conditional branch and,
328// 3) its latch condition is a compare instruction whose operands are the
329// canonical IV and an OuterLp invariant.
330// This check doesn't take into account the uniformity of other conditions not
331// related to the loop latch because they don't affect the loop uniformity.
332//
333// NOTE: We decided to keep all these checks and its associated documentation
334// together so that we can easily have a picture of the current supported loop
335// nests. However, some of the current checks don't depend on \p OuterLp and
336// would be redundantly executed for each \p Lp if we invoked this function for
337// different candidate outer loops. This is not the case for now because we
338// don't currently have the infrastructure to evaluate multiple candidate outer
339// loops and \p OuterLp will be a fixed parameter while we only support explicit
340// outer loop vectorization. It's also very likely that these checks go away
341// before introducing the aforementioned infrastructure. However, if this is not
342// the case, we should move the \p OuterLp independent checks to a separate
343// function that is only executed once for each \p Lp.
344static bool isUniformLoop(Loop *Lp, Loop *OuterLp) {
345 assert(Lp->getLoopLatch() && "Expected loop with a single latch.");
346
347 // If Lp is the outer loop, it's uniform by definition.
348 if (Lp == OuterLp)
349 return true;
350 assert(OuterLp->contains(Lp) && "OuterLp must contain Lp.");
351
352 // 1.
354 if (!IV) {
355 LLVM_DEBUG(dbgs() << "LV: Canonical IV not found.\n");
356 return false;
357 }
358
359 // 2.
360 BasicBlock *Latch = Lp->getLoopLatch();
361 auto *LatchBr = dyn_cast<CondBrInst>(Latch->getTerminator());
362 if (!LatchBr) {
363 LLVM_DEBUG(dbgs() << "LV: Unsupported loop latch branch.\n");
364 return false;
365 }
366
367 // 3.
368 auto *LatchCmp = dyn_cast<CmpInst>(LatchBr->getCondition());
369 if (!LatchCmp) {
371 dbgs() << "LV: Loop latch condition is not a compare instruction.\n");
372 return false;
373 }
374
375 Value *CondOp0 = LatchCmp->getOperand(0);
376 Value *CondOp1 = LatchCmp->getOperand(1);
377 Value *IVUpdate = IV->getIncomingValueForBlock(Latch);
378 if (!(CondOp0 == IVUpdate && OuterLp->isLoopInvariant(CondOp1)) &&
379 !(CondOp1 == IVUpdate && OuterLp->isLoopInvariant(CondOp0))) {
380 LLVM_DEBUG(dbgs() << "LV: Loop latch condition is not uniform.\n");
381 return false;
382 }
383
384 return true;
385}
386
387// Return true if \p Lp and all its nested loops are uniform with regard to \p
388// OuterLp.
389static bool isUniformLoopNest(Loop *Lp, Loop *OuterLp) {
390 if (!isUniformLoop(Lp, OuterLp))
391 return false;
392
393 // Check if nested loops are uniform.
394 for (Loop *SubLp : *Lp)
395 if (!isUniformLoopNest(SubLp, OuterLp))
396 return false;
397
398 return true;
399}
400
402 assert(Ty->isIntOrPtrTy() && "Expected integer or pointer type");
403
404 if (Ty->isPointerTy())
405 return DL.getIntPtrType(Ty->getContext(), Ty->getPointerAddressSpace());
406
407 // It is possible that char's or short's overflow when we ask for the loop's
408 // trip count, work around this by changing the type size.
409 if (Ty->getScalarSizeInBits() < 32)
410 return Type::getInt32Ty(Ty->getContext());
411
412 return cast<IntegerType>(Ty);
413}
414
416 Type *Ty1) {
419 return TyA->getScalarSizeInBits() > TyB->getScalarSizeInBits() ? TyA : TyB;
420}
421
422/// Check that the instruction has outside loop users and is not an
423/// identified reduction variable.
424static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
425 SmallPtrSetImpl<Value *> &AllowedExit) {
426 // Reductions, Inductions and non-header phis are allowed to have exit users. All
427 // other instructions must not have external users.
428 if (!AllowedExit.count(Inst))
429 // Check that all of the users of the loop are inside the BB.
430 for (User *U : Inst->users()) {
432 // This user may be a reduction exit value.
433 if (!TheLoop->contains(UI)) {
434 LLVM_DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
435 return true;
436 }
437 }
438 return false;
439}
440
441/// Returns true if A and B have same pointer operands or same SCEVs addresses
443 StoreInst *B) {
444 // Compare store
445 if (A == B)
446 return true;
447
448 // Otherwise Compare pointers
449 Value *APtr = A->getPointerOperand();
450 Value *BPtr = B->getPointerOperand();
451 if (APtr == BPtr)
452 return true;
453
454 // Otherwise compare address SCEVs
455 return SE->getSCEV(APtr) == SE->getSCEV(BPtr);
456}
457
459 Value *Ptr) const {
460 // FIXME: Currently, the set of symbolic strides is sometimes queried before
461 // it's collected. This happens from canVectorizeWithIfConvert, when the
462 // pointer is checked to reference consecutive elements suitable for a
463 // masked access.
464 const auto &Strides =
465 LAI ? LAI->getSymbolicStrides() : DenseMap<Value *, const SCEV *>();
466
467 int Stride = getPtrStride(PSE, AccessTy, Ptr, TheLoop, *DT, Strides,
468 AllowRuntimeSCEVChecks, false)
469 .value_or(0);
470 if (Stride == 1 || Stride == -1)
471 return Stride;
472 return 0;
473}
474
476 return LAI->isInvariant(V);
477}
478
479namespace {
480/// A rewriter to build the SCEVs for each of the VF lanes in the expected
481/// vectorized loop, which can then be compared to detect their uniformity. This
482/// is done by replacing the AddRec SCEVs of the original scalar loop (TheLoop)
483/// with new AddRecs where the step is multiplied by StepMultiplier and Offset *
484/// Step is added. Also checks if all sub-expressions are analyzable w.r.t.
485/// uniformity.
486class SCEVAddRecForUniformityRewriter
487 : public SCEVRewriteVisitor<SCEVAddRecForUniformityRewriter> {
488 /// Multiplier to be applied to the step of AddRecs in TheLoop.
489 unsigned StepMultiplier;
490
491 /// Offset to be added to the AddRecs in TheLoop.
492 unsigned Offset;
493
494 /// Loop for which to rewrite AddRecsFor.
495 Loop *TheLoop;
496
497 /// Is any sub-expressions not analyzable w.r.t. uniformity?
498 bool CannotAnalyze = false;
499
500 bool canAnalyze() const { return !CannotAnalyze; }
501
502public:
503 SCEVAddRecForUniformityRewriter(ScalarEvolution &SE, unsigned StepMultiplier,
504 unsigned Offset, Loop *TheLoop)
505 : SCEVRewriteVisitor(SE), StepMultiplier(StepMultiplier), Offset(Offset),
506 TheLoop(TheLoop) {}
507
508 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
509 assert(Expr->getLoop() == TheLoop &&
510 "addrec outside of TheLoop must be invariant and should have been "
511 "handled earlier");
512 // Build a new AddRec by multiplying the step by StepMultiplier and
513 // incrementing the start by Offset * step.
514 Type *Ty = Expr->getType();
515 const SCEV *Step = Expr->getStepRecurrence(SE);
516 if (!SE.isLoopInvariant(Step, TheLoop)) {
517 CannotAnalyze = true;
518 return Expr;
519 }
520 const SCEV *NewStep =
521 SE.getMulExpr(Step, SE.getConstant(Ty, StepMultiplier));
522 const SCEV *ScaledOffset = SE.getMulExpr(Step, SE.getConstant(Ty, Offset));
523 const SCEV *NewStart =
524 SE.getAddExpr(Expr->getStart(), SCEVUse(ScaledOffset));
525 return SE.getAddRecExpr(NewStart, NewStep, TheLoop, SCEV::FlagAnyWrap);
526 }
527
528 const SCEV *visit(const SCEV *S) {
529 if (CannotAnalyze || SE.isLoopInvariant(S, TheLoop))
530 return S;
532 }
533
534 const SCEV *visitUnknown(const SCEVUnknown *S) {
535 if (SE.isLoopInvariant(S, TheLoop))
536 return S;
537 // The value could vary across iterations.
538 CannotAnalyze = true;
539 return S;
540 }
541
542 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *S) {
543 // Could not analyze the expression.
544 CannotAnalyze = true;
545 return S;
546 }
547
548 static const SCEV *rewrite(const SCEV *S, ScalarEvolution &SE,
549 unsigned StepMultiplier, unsigned Offset,
550 Loop *TheLoop) {
551 /// Bail out if the expression does not contain an UDiv expression.
552 /// Uniform values which are not loop invariant require operations to strip
553 /// out the lowest bits. For now just look for UDivs and use it to avoid
554 /// re-writing UDIV-free expressions for other lanes to limit compile time.
555 if (!SCEVExprContains(S,
556 [](const SCEV *S) { return isa<SCEVUDivExpr>(S); }))
557 return SE.getCouldNotCompute();
558
559 SCEVAddRecForUniformityRewriter Rewriter(SE, StepMultiplier, Offset,
560 TheLoop);
561 const SCEV *Result = Rewriter.visit(S);
562
563 if (Rewriter.canAnalyze())
564 return Result;
565 return SE.getCouldNotCompute();
566 }
567};
568
569} // namespace
570
572 if (isInvariant(V))
573 return true;
574 if (VF.isScalable())
575 return false;
576 if (VF.isScalar())
577 return true;
578
579 // Since we rely on SCEV for uniformity, if the type is not SCEVable, it is
580 // never considered uniform.
581 auto *SE = PSE.getSE();
582 if (!SE->isSCEVable(V->getType()))
583 return false;
584 const SCEV *S = SE->getSCEV(V);
585
586 // Rewrite AddRecs in TheLoop to step by VF and check if the expression for
587 // lane 0 matches the expressions for all other lanes.
588 unsigned FixedVF = VF.getKnownMinValue();
589 const SCEV *FirstLaneExpr =
590 SCEVAddRecForUniformityRewriter::rewrite(S, *SE, FixedVF, 0, TheLoop);
591 if (isa<SCEVCouldNotCompute>(FirstLaneExpr))
592 return false;
593
594 // Make sure the expressions for lanes FixedVF-1..1 match the expression for
595 // lane 0. We check lanes in reverse order for compile-time, as frequently
596 // checking the last lane is sufficient to rule out uniformity.
597 return all_of(reverse(seq<unsigned>(1, FixedVF)), [&](unsigned I) {
598 const SCEV *IthLaneExpr =
599 SCEVAddRecForUniformityRewriter::rewrite(S, *SE, FixedVF, I, TheLoop);
600 return FirstLaneExpr == IthLaneExpr;
601 });
602}
603
605 ElementCount VF) const {
607 if (!Ptr)
608 return false;
609 // Note: There's nothing inherent which prevents predicated loads and
610 // stores from being uniform. The current lowering simply doesn't handle
611 // it; in particular, the cost model distinguishes scatter/gather from
612 // scalar w/predication, and we currently rely on the scalar path.
613 return isUniform(Ptr, VF) && !blockNeedsPredication(I.getParent());
614}
615
616bool LoopVectorizationLegality::canVectorizeOuterLoop() {
617 assert(!TheLoop->isInnermost() && "We are not vectorizing an outer loop.");
618 // Store the result and return it at the end instead of exiting early, in case
619 // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
620 bool Result = true;
621 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
622
623 for (BasicBlock *BB : TheLoop->blocks()) {
624 // Check whether the BB terminator is a branch. Any other terminator is
625 // not supported yet.
626 Instruction *Term = BB->getTerminator();
628 reportVectorizationFailure("Unsupported basic block terminator",
629 "loop control flow is not understood by vectorizer",
630 "CFGNotUnderstood", ORE, TheLoop);
631 if (DoExtraAnalysis)
632 Result = false;
633 else
634 return false;
635 }
636
637 // Check whether the branch is a supported one. Only unconditional
638 // branches, conditional branches with an outer loop invariant condition or
639 // backedges are supported.
640 // FIXME: We skip these checks when VPlan predication is enabled as we
641 // want to allow divergent branches. This whole check will be removed
642 // once VPlan predication is on by default.
643 auto *Br = dyn_cast<CondBrInst>(Term);
644 if (Br && !TheLoop->isLoopInvariant(Br->getCondition()) &&
645 !LI->isLoopHeader(Br->getSuccessor(0)) &&
646 !LI->isLoopHeader(Br->getSuccessor(1))) {
647 reportVectorizationFailure("Unsupported conditional branch",
648 "loop control flow is not understood by vectorizer",
649 "CFGNotUnderstood", ORE, TheLoop);
650 if (DoExtraAnalysis)
651 Result = false;
652 else
653 return false;
654 }
655 }
656
657 // Check whether inner loops are uniform. At this point, we only support
658 // simple outer loops scenarios with uniform nested loops.
659 if (!isUniformLoopNest(TheLoop /*loop nest*/,
660 TheLoop /*context outer loop*/)) {
661 reportVectorizationFailure("Outer loop contains divergent loops",
662 "loop control flow is not understood by vectorizer",
663 "CFGNotUnderstood", ORE, TheLoop);
664 if (DoExtraAnalysis)
665 Result = false;
666 else
667 return false;
668 }
669
670 // Check whether we are able to set up outer loop induction.
671 if (!setupOuterLoopInductions()) {
672 reportVectorizationFailure("Unsupported outer loop Phi(s)",
673 "UnsupportedPhi", ORE, TheLoop);
674 if (DoExtraAnalysis)
675 Result = false;
676 else
677 return false;
678 }
679
680 return Result;
681}
682
683void LoopVectorizationLegality::addInductionPhi(
684 PHINode *Phi, const InductionDescriptor &ID,
685 SmallPtrSetImpl<Value *> &AllowedExit) {
686 Inductions[Phi] = ID;
687
688 // In case this induction also comes with casts that we know we can ignore
689 // in the vectorized loop body, record them here. All casts could be recorded
690 // here for ignoring, but suffices to record only the first (as it is the
691 // only one that may bw used outside the cast sequence).
692 ArrayRef<Instruction *> Casts = ID.getCastInsts();
693 if (!Casts.empty())
694 InductionCastsToIgnore.insert(*Casts.begin());
695
696 Type *PhiTy = Phi->getType();
697 const DataLayout &DL = Phi->getDataLayout();
698
699 assert((PhiTy->isIntOrPtrTy() || PhiTy->isFloatingPointTy()) &&
700 "Expected int, ptr, or FP induction phi type");
701
702 // Get the widest type.
703 if (PhiTy->isIntOrPtrTy()) {
704 if (!WidestIndTy)
705 WidestIndTy = getInductionIntegerTy(DL, PhiTy);
706 else
707 WidestIndTy = getWiderInductionTy(DL, PhiTy, WidestIndTy);
708 }
709
710 // Int inductions are special because we only allow one IV.
711 if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
712 ID.getConstIntStepValue() && ID.getConstIntStepValue()->isOne() &&
713 isa<Constant>(ID.getStartValue()) &&
714 cast<Constant>(ID.getStartValue())->isNullValue()) {
715
716 // Use the phi node with the widest type as induction. Use the last
717 // one if there are multiple (no good reason for doing this other
718 // than it is expedient). We've checked that it begins at zero and
719 // steps by one, so this is a canonical induction variable.
720 if (!PrimaryInduction || PhiTy == WidestIndTy)
721 PrimaryInduction = Phi;
722 }
723
724 // Both the PHI node itself, and the "post-increment" value feeding
725 // back into the PHI node may have external users.
726 // We can allow those uses, except if the SCEVs we have for them rely
727 // on predicates that only hold within the loop, since allowing the exit
728 // currently means re-using this SCEV outside the loop (see PR33706 for more
729 // details).
730 if (PSE.getPredicate().isAlwaysTrue()) {
731 AllowedExit.insert(Phi);
732 AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch()));
733 }
734
735 LLVM_DEBUG(dbgs() << "LV: Found an induction variable.\n");
736}
737
738bool LoopVectorizationLegality::setupOuterLoopInductions() {
739 BasicBlock *Header = TheLoop->getHeader();
740
741 // Returns true if a given Phi is a supported induction.
742 auto IsSupportedPhi = [&](PHINode &Phi) -> bool {
743 InductionDescriptor ID;
744 if (InductionDescriptor::isInductionPHI(&Phi, TheLoop, PSE, ID) &&
746 addInductionPhi(&Phi, ID, AllowedExit);
747 return true;
748 }
749 // Bail out for any Phi in the outer loop header that is not a supported
750 // induction.
752 dbgs() << "LV: Found unsupported PHI for outer loop vectorization.\n");
753 return false;
754 };
755
756 return llvm::all_of(Header->phis(), IsSupportedPhi);
757}
758
759/// Checks if a function is scalarizable according to the TLI, in
760/// the sense that it should be vectorized and then expanded in
761/// multiple scalar calls. This is represented in the
762/// TLI via mappings that do not specify a vector name, as in the
763/// following example:
764///
765/// const VecDesc VecIntrinsics[] = {
766/// {"llvm.phx.abs.i32", "", 4}
767/// };
768static bool isTLIScalarize(const TargetLibraryInfo &TLI, const CallInst &CI) {
769 const StringRef ScalarName = CI.getCalledFunction()->getName();
770 bool Scalarize = TLI.isFunctionVectorizable(ScalarName);
771 // Check that all known VFs are not associated to a vector
772 // function, i.e. the vector name is emty.
773 if (Scalarize) {
774 ElementCount WidestFixedVF, WidestScalableVF;
775 TLI.getWidestVF(ScalarName, WidestFixedVF, WidestScalableVF);
777 ElementCount::isKnownLE(VF, WidestFixedVF); VF *= 2)
778 Scalarize &= !TLI.isFunctionVectorizable(ScalarName, VF);
780 ElementCount::isKnownLE(VF, WidestScalableVF); VF *= 2)
781 Scalarize &= !TLI.isFunctionVectorizable(ScalarName, VF);
782 assert((WidestScalableVF.isZero() || !Scalarize) &&
783 "Caller may decide to scalarize a variant using a scalable VF");
784 }
785 return Scalarize;
786}
787
788bool LoopVectorizationLegality::canVectorizeInstrs() {
789 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
790 bool Result = true;
791
792 // For each block in the loop.
793 for (BasicBlock *BB : TheLoop->blocks()) {
794 // Scan the instructions in the block and look for hazards.
795 for (Instruction &I : *BB) {
796 Result &= canVectorizeInstr(I);
797 if (!DoExtraAnalysis && !Result)
798 return false;
799 }
800 }
801
802 if (!PrimaryInduction) {
803 if (Inductions.empty()) {
805 "Did not find one integer induction var",
806 "loop induction variable could not be identified",
807 "NoInductionVariable", ORE, TheLoop);
808 return false;
809 }
810 if (!WidestIndTy) {
812 "Did not find one integer induction var",
813 "integer loop induction variable could not be identified",
814 "NoIntegerInductionVariable", ORE, TheLoop);
815 return false;
816 }
817 LLVM_DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
818 }
819
820 // Now we know the widest induction type, check if our found induction
821 // is the same size. If it's not, unset it here and InnerLoopVectorizer
822 // will create another.
823 if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType())
824 PrimaryInduction = nullptr;
825
826 return Result;
827}
828
829bool LoopVectorizationLegality::canVectorizeInstr(Instruction &I) {
830 BasicBlock *BB = I.getParent();
831 BasicBlock *Header = TheLoop->getHeader();
832
833 if (auto *Phi = dyn_cast<PHINode>(&I)) {
834 Type *PhiTy = Phi->getType();
835 // Check that this PHI type is allowed.
836 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
837 !PhiTy->isPointerTy()) {
839 "Found a non-int non-pointer PHI",
840 "loop control flow is not understood by vectorizer",
841 "CFGNotUnderstood", ORE, TheLoop);
842 return false;
843 }
844
845 // If this PHINode is not in the header block, then we know that we
846 // can convert it to select during if-conversion. No need to check if
847 // the PHIs in this block are induction or reduction variables.
848 if (BB != Header) {
849 // Non-header phi nodes that have outside uses can be vectorized. Add
850 // them to the list of allowed exits.
851 // Unsafe cyclic dependencies with header phis are identified during
852 // legalization for reduction, induction and fixed order
853 // recurrences.
854 AllowedExit.insert(&I);
855 return true;
856 }
857
858 // We only allow if-converted PHIs with exactly two incoming values.
859 if (Phi->getNumIncomingValues() != 2) {
861 "Found an invalid PHI",
862 "loop control flow is not understood by vectorizer",
863 "CFGNotUnderstood", ORE, TheLoop, Phi);
864 return false;
865 }
866
867 RecurrenceDescriptor RedDes;
868 if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes, DB, AC, DT,
869 PSE.getSE())) {
870 Requirements->addExactFPMathInst(RedDes.getExactFPMathInst());
871 AllowedExit.insert(RedDes.getLoopExitInstr());
872 Reductions[Phi] = std::move(RedDes);
875 RedDes.getRecurrenceKind())) &&
876 "Only min/max recurrences are allowed to have multiple uses "
877 "currently");
878 return true;
879 }
880
881 // We prevent matching non-constant strided pointer IVS to preserve
882 // historical vectorizer behavior after a generalization of the
883 // IVDescriptor code. The intent is to remove this check, but we
884 // have to fix issues around code quality for such loops first.
885 auto IsDisallowedStridedPointerInduction =
886 [](const InductionDescriptor &ID) {
888 return false;
889 return ID.getKind() == InductionDescriptor::IK_PtrInduction &&
890 ID.getConstIntStepValue() == nullptr;
891 };
892
893 // TODO: Instead of recording the AllowedExit, it would be good to
894 // record the complementary set: NotAllowedExit. These include (but may
895 // not be limited to):
896 // 1. Reduction phis as they represent the one-before-last value, which
897 // is not available when vectorized
898 // 2. Induction phis and increment when SCEV predicates cannot be used
899 // outside the loop - see addInductionPhi
900 // 3. Non-Phis with outside uses when SCEV predicates cannot be used
901 // outside the loop - see call to hasOutsideLoopUser in the non-phi
902 // handling below
903 // 4. FixedOrderRecurrence phis that can possibly be handled by
904 // extraction.
905 // By recording these, we can then reason about ways to vectorize each
906 // of these NotAllowedExit.
907 InductionDescriptor ID;
908 if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID) &&
909 !IsDisallowedStridedPointerInduction(ID)) {
910 addInductionPhi(Phi, ID, AllowedExit);
911 Requirements->addExactFPMathInst(ID.getExactFPMathInst());
912 return true;
913 }
914
915 if (RecurrenceDescriptor::isFixedOrderRecurrence(Phi, TheLoop, DT)) {
916 AllowedExit.insert(Phi);
917 FixedOrderRecurrences.insert(Phi);
918 return true;
919 }
920
921 // As a last resort, coerce the PHI to a AddRec expression
922 // and re-try classifying it a an induction PHI.
923 if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true) &&
924 !IsDisallowedStridedPointerInduction(ID)) {
925 addInductionPhi(Phi, ID, AllowedExit);
926 return true;
927 }
928
929 reportVectorizationFailure("Found an unidentified PHI",
930 "value that could not be identified as "
931 "reduction is used outside the loop",
932 "NonReductionValueUsedOutsideLoop", ORE, TheLoop,
933 Phi);
934 return false;
935 } // end of PHI handling
936
937 // We handle calls that:
938 // * Have a mapping to an IR intrinsic.
939 // * Have a vector version available.
940 auto *CI = dyn_cast<CallInst>(&I);
941
942 if (CI && !getVectorIntrinsicIDForCall(CI, TLI) &&
943 !(CI->getCalledFunction() && TLI &&
944 (!VFDatabase::getMappings(*CI).empty() || isTLIScalarize(*TLI, *CI)))) {
945 // If the call is a recognized math libary call, it is likely that
946 // we can vectorize it given loosened floating-point constraints.
947 LibFunc Func;
948 bool IsMathLibCall =
949 TLI && CI->getCalledFunction() && CI->getType()->isFloatingPointTy() &&
950 TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
951 TLI->hasOptimizedCodeGen(Func);
952
953 if (IsMathLibCall) {
954 // TODO: Ideally, we should not use clang-specific language here,
955 // but it's hard to provide meaningful yet generic advice.
956 // Also, should this be guarded by allowExtraAnalysis() and/or be part
957 // of the returned info from isFunctionVectorizable()?
959 "Found a non-intrinsic callsite",
960 "library call cannot be vectorized. "
961 "Try compiling with -fno-math-errno, -ffast-math, "
962 "or similar flags",
963 "CantVectorizeLibcall", ORE, TheLoop, CI);
964 } else {
965 reportVectorizationFailure("Found a non-intrinsic callsite",
966 "call instruction cannot be vectorized",
967 "CantVectorizeLibcall", ORE, TheLoop, CI);
968 }
969 return false;
970 }
971
972 // Some intrinsics have scalar arguments and should be same in order for
973 // them to be vectorized (i.e. loop invariant).
974 if (CI) {
975 auto *SE = PSE.getSE();
976 Intrinsic::ID IntrinID = getVectorIntrinsicIDForCall(CI, TLI);
977 for (unsigned Idx = 0; Idx < CI->arg_size(); ++Idx)
978 if (isVectorIntrinsicWithScalarOpAtArg(IntrinID, Idx, TTI)) {
979 if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(Idx)), TheLoop)) {
981 "Found unvectorizable intrinsic",
982 "intrinsic instruction cannot be vectorized",
983 "CantVectorizeIntrinsic", ORE, TheLoop, CI);
984 return false;
985 }
986 }
987 }
988
989 // If we found a vectorized variant of a function, note that so LV can
990 // make better decisions about maximum VF.
991 if (CI && !VFDatabase::getMappings(*CI).empty())
992 VecCallVariantsFound = true;
993
994 auto CanWidenInstructionTy = [](Instruction const &Inst) {
995 Type *InstTy = Inst.getType();
996 if (!isa<StructType>(InstTy))
997 return canVectorizeTy(InstTy);
998
999 // For now, we only recognize struct values returned from calls where
1000 // all users are extractvalue as vectorizable. All element types of the
1001 // struct must be types that can be widened.
1002 return isa<CallInst>(Inst) && canVectorizeTy(InstTy) &&
1003 all_of(Inst.users(), IsaPred<ExtractValueInst>);
1004 };
1005
1006 // Check that the instruction return type is vectorizable.
1007 // We can't vectorize casts from vector type to scalar type.
1008 // Also, we can't vectorize extractelement instructions.
1009 if (!CanWidenInstructionTy(I) ||
1010 (isa<CastInst>(I) &&
1011 !VectorType::isValidElementType(I.getOperand(0)->getType())) ||
1013 reportVectorizationFailure("Found unvectorizable type",
1014 "instruction return type cannot be vectorized",
1015 "CantVectorizeInstructionReturnType", ORE,
1016 TheLoop, &I);
1017 return false;
1018 }
1019
1020 // Check that the stored type is vectorizable.
1021 if (auto *ST = dyn_cast<StoreInst>(&I)) {
1022 Type *T = ST->getValueOperand()->getType();
1024 reportVectorizationFailure("Store instruction cannot be vectorized",
1025 "CantVectorizeStore", ORE, TheLoop, ST);
1026 return false;
1027 }
1028
1029 // For nontemporal stores, check that a nontemporal vector version is
1030 // supported on the target.
1031 if (ST->getMetadata(LLVMContext::MD_nontemporal)) {
1032 // Arbitrarily try a vector of 2 elements.
1033 auto *VecTy = FixedVectorType::get(T, /*NumElts=*/2);
1034 assert(VecTy && "did not find vectorized version of stored type");
1035 if (!TTI->isLegalNTStore(VecTy, ST->getAlign())) {
1037 "nontemporal store instruction cannot be vectorized",
1038 "CantVectorizeNontemporalStore", ORE, TheLoop, ST);
1039 return false;
1040 }
1041 }
1042
1043 } else if (auto *LD = dyn_cast<LoadInst>(&I)) {
1044 if (LD->getMetadata(LLVMContext::MD_nontemporal)) {
1045 // For nontemporal loads, check that a nontemporal vector version is
1046 // supported on the target (arbitrarily try a vector of 2 elements).
1047 auto *VecTy = FixedVectorType::get(I.getType(), /*NumElts=*/2);
1048 assert(VecTy && "did not find vectorized version of load type");
1049 if (!TTI->isLegalNTLoad(VecTy, LD->getAlign())) {
1051 "nontemporal load instruction cannot be vectorized",
1052 "CantVectorizeNontemporalLoad", ORE, TheLoop, LD);
1053 return false;
1054 }
1055 }
1056
1057 // FP instructions can allow unsafe algebra, thus vectorizable by
1058 // non-IEEE-754 compliant SIMD units.
1059 // This applies to floating-point math operations and calls, not memory
1060 // operations, shuffles, or casts, as they don't change precision or
1061 // semantics.
1062 } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) &&
1063 !I.isFast()) {
1064 LLVM_DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n");
1065 Hints->setPotentiallyUnsafe();
1066 }
1067
1068 // Reduction instructions are allowed to have exit users.
1069 // All other instructions must not have external users.
1070 if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) {
1071 // We can safely vectorize loops where instructions within the loop are
1072 // used outside the loop only if the SCEV predicates within the loop is
1073 // same as outside the loop. Allowing the exit means reusing the SCEV
1074 // outside the loop.
1075 if (PSE.getPredicate().isAlwaysTrue()) {
1076 AllowedExit.insert(&I);
1077 return true;
1078 }
1079 reportVectorizationFailure("Value cannot be used outside the loop",
1080 "ValueUsedOutsideLoop", ORE, TheLoop, &I);
1081 return false;
1082 }
1083
1084 return true;
1085}
1086
1087/// Find histogram operations that match high-level code in loops:
1088/// \code
1089/// buckets[indices[i]]+=step;
1090/// \endcode
1091///
1092/// It matches a pattern starting from \p HSt, which Stores to the 'buckets'
1093/// array the computed histogram. It uses a BinOp to sum all counts, storing
1094/// them using a loop-variant index Load from the 'indices' input array.
1095///
1096/// On successful matches it updates the STATISTIC 'HistogramsDetected',
1097/// regardless of hardware support. When there is support, it additionally
1098/// stores the BinOp/Load pairs in \p HistogramCounts, as well the pointers
1099/// used to update histogram in \p HistogramPtrs.
1100static bool findHistogram(LoadInst *LI, StoreInst *HSt, Loop *TheLoop,
1101 const PredicatedScalarEvolution &PSE,
1102 SmallVectorImpl<HistogramInfo> &Histograms) {
1103
1104 // Store value must come from a Binary Operation.
1105 Instruction *HPtrInstr = nullptr;
1106 BinaryOperator *HBinOp = nullptr;
1107 if (!match(HSt, m_Store(m_BinOp(HBinOp), m_Instruction(HPtrInstr))))
1108 return false;
1109
1110 // BinOp must be an Add or a Sub modifying the bucket value by a
1111 // loop invariant amount.
1112 // FIXME: We assume the loop invariant term is on the RHS.
1113 // Fine for an immediate/constant, but maybe not a generic value?
1114 Value *HIncVal = nullptr;
1115 if (!match(HBinOp, m_Add(m_Load(m_Specific(HPtrInstr)), m_Value(HIncVal))) &&
1116 !match(HBinOp, m_Sub(m_Load(m_Specific(HPtrInstr)), m_Value(HIncVal))))
1117 return false;
1118
1119 // Make sure the increment value is loop invariant.
1120 if (!TheLoop->isLoopInvariant(HIncVal))
1121 return false;
1122
1123 // The address to store is calculated through a GEP Instruction.
1125 if (!GEP)
1126 return false;
1127
1128 // Restrict address calculation to constant indices except for the last term.
1129 Value *HIdx = nullptr;
1130 for (Value *Index : GEP->indices()) {
1131 if (HIdx)
1132 return false;
1133 if (!isa<ConstantInt>(Index))
1134 HIdx = Index;
1135 }
1136
1137 if (!HIdx)
1138 return false;
1139
1140 // Check that the index is calculated by loading from another array. Ignore
1141 // any extensions.
1142 // FIXME: Support indices from other sources than a linear load from memory?
1143 // We're currently trying to match an operation looping over an array
1144 // of indices, but there could be additional levels of indirection
1145 // in place, or possibly some additional calculation to form the index
1146 // from the loaded data.
1147 Value *VPtrVal;
1148 if (!match(HIdx, m_ZExtOrSExtOrSelf(m_Load(m_Value(VPtrVal)))))
1149 return false;
1150
1151 // Make sure the index address varies in this loop, not an outer loop.
1152 const auto *AR = dyn_cast<SCEVAddRecExpr>(PSE.getSE()->getSCEV(VPtrVal));
1153 if (!AR || AR->getLoop() != TheLoop)
1154 return false;
1155
1156 // Ensure we'll have the same mask by checking that all parts of the histogram
1157 // (gather load, update, scatter store) are in the same block.
1158 LoadInst *IndexedLoad = cast<LoadInst>(HBinOp->getOperand(0));
1159 BasicBlock *LdBB = IndexedLoad->getParent();
1160 if (LdBB != HBinOp->getParent() || LdBB != HSt->getParent())
1161 return false;
1162
1163 LLVM_DEBUG(dbgs() << "LV: Found histogram for: " << *HSt << "\n");
1164
1165 // Store the operations that make up the histogram.
1166 Histograms.emplace_back(IndexedLoad, HBinOp, HSt);
1167 return true;
1168}
1169
1170bool LoopVectorizationLegality::canVectorizeIndirectUnsafeDependences() {
1171 // For now, we only support an IndirectUnsafe dependency that calculates
1172 // a histogram
1174 return false;
1175
1176 // Find a single IndirectUnsafe dependency.
1177 const MemoryDepChecker::Dependence *IUDep = nullptr;
1178 const MemoryDepChecker &DepChecker = LAI->getDepChecker();
1179 const auto *Deps = DepChecker.getDependences();
1180 // If there were too many dependences, LAA abandons recording them. We can't
1181 // proceed safely if we don't know what the dependences are.
1182 if (!Deps)
1183 return false;
1184
1185 for (const MemoryDepChecker::Dependence &Dep : *Deps) {
1186 // Ignore dependencies that are either known to be safe or can be
1187 // checked at runtime.
1190 continue;
1191
1192 // We're only interested in IndirectUnsafe dependencies here, where the
1193 // address might come from a load from memory. We also only want to handle
1194 // one such dependency, at least for now.
1195 if (Dep.Type != MemoryDepChecker::Dependence::IndirectUnsafe || IUDep)
1196 return false;
1197
1198 IUDep = &Dep;
1199 }
1200 if (!IUDep)
1201 return false;
1202
1203 // For now only normal loads and stores are supported.
1204 LoadInst *LI = dyn_cast<LoadInst>(IUDep->getSource(DepChecker));
1205 StoreInst *SI = dyn_cast<StoreInst>(IUDep->getDestination(DepChecker));
1206
1207 if (!LI || !SI)
1208 return false;
1209
1210 LLVM_DEBUG(dbgs() << "LV: Checking for a histogram on: " << *SI << "\n");
1211 return findHistogram(LI, SI, TheLoop, LAI->getPSE(), Histograms);
1212}
1213
1214bool LoopVectorizationLegality::canVectorizeMemory() {
1215 LAI = &LAIs.getInfo(*TheLoop);
1216 const OptimizationRemarkAnalysis *LAR = LAI->getReport();
1217 if (LAR) {
1218 ORE->emit([&]() {
1219 return OptimizationRemarkAnalysis(LV_NAME, "loop not vectorized: ", *LAR);
1220 });
1221 }
1222
1223 if (!LAI->canVectorizeMemory()) {
1226 "Cannot vectorize unsafe dependencies in uncountable exit loop with "
1227 "side effects",
1228 "CantVectorizeUnsafeDependencyForEELoopWithSideEffects", ORE,
1229 TheLoop);
1230 return false;
1231 }
1232
1233 return canVectorizeIndirectUnsafeDependences();
1234 }
1235
1236 if (LAI->hasLoadStoreDependenceInvolvingLoopInvariantAddress()) {
1237 reportVectorizationFailure("We don't allow storing to uniform addresses",
1238 "write to a loop invariant address could not "
1239 "be vectorized",
1240 "CantVectorizeStoreToLoopInvariantAddress", ORE,
1241 TheLoop);
1242 return false;
1243 }
1244
1245 // We can vectorize stores to invariant address when final reduction value is
1246 // guaranteed to be stored at the end of the loop. Also, if decision to
1247 // vectorize loop is made, runtime checks are added so as to make sure that
1248 // invariant address won't alias with any other objects.
1249 if (!LAI->getStoresToInvariantAddresses().empty()) {
1250 // For each invariant address, check if last stored value is unconditional
1251 // and the address is not calculated inside the loop.
1252 for (StoreInst *SI : LAI->getStoresToInvariantAddresses()) {
1254 continue;
1255
1256 if (blockNeedsPredication(SI->getParent())) {
1258 "We don't allow storing to uniform addresses",
1259 "write of conditional recurring variant value to a loop "
1260 "invariant address could not be vectorized",
1261 "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop);
1262 return false;
1263 }
1264
1265 // Invariant address should be defined outside of loop. LICM pass usually
1266 // makes sure it happens, but in rare cases it does not, we do not want
1267 // to overcomplicate vectorization to support this case.
1268 if (Instruction *Ptr = dyn_cast<Instruction>(SI->getPointerOperand())) {
1269 if (TheLoop->contains(Ptr)) {
1271 "Invariant address is calculated inside the loop",
1272 "write to a loop invariant address could not "
1273 "be vectorized",
1274 "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop);
1275 return false;
1276 }
1277 }
1278 }
1279
1280 if (LAI->hasStoreStoreDependenceInvolvingLoopInvariantAddress()) {
1281 // For each invariant address, check its last stored value is the result
1282 // of one of our reductions.
1283 //
1284 // We do not check if dependence with loads exists because that is already
1285 // checked via hasLoadStoreDependenceInvolvingLoopInvariantAddress.
1286 ScalarEvolution *SE = PSE.getSE();
1287 SmallVector<StoreInst *, 4> UnhandledStores;
1288 for (StoreInst *SI : LAI->getStoresToInvariantAddresses()) {
1290 // Earlier stores to this address are effectively deadcode.
1291 // With opaque pointers it is possible for one pointer to be used with
1292 // different sizes of stored values:
1293 // store i32 0, ptr %x
1294 // store i8 0, ptr %x
1295 // The latest store doesn't complitely overwrite the first one in the
1296 // example. That is why we have to make sure that types of stored
1297 // values are same.
1298 // TODO: Check that bitwidth of unhandled store is smaller then the
1299 // one that overwrites it and add a test.
1300 erase_if(UnhandledStores, [SE, SI](StoreInst *I) {
1301 return storeToSameAddress(SE, SI, I) &&
1302 I->getValueOperand()->getType() ==
1303 SI->getValueOperand()->getType();
1304 });
1305 continue;
1306 }
1307 UnhandledStores.push_back(SI);
1308 }
1309
1310 bool IsOK = UnhandledStores.empty();
1311 // TODO: we should also validate against InvariantMemSets.
1312 if (!IsOK) {
1314 "We don't allow storing to uniform addresses",
1315 "write to a loop invariant address could not "
1316 "be vectorized",
1317 "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop);
1318 return false;
1319 }
1320 }
1321 }
1322
1323 PSE.addPredicate(LAI->getPSE().getPredicate());
1324 return true;
1325}
1326
1328 bool EnableStrictReductions) {
1329
1330 // First check if there is any ExactFP math or if we allow reassociations
1331 if (!Requirements->getExactFPInst() || Hints->allowReordering())
1332 return true;
1333
1334 // If the above is false, we have ExactFPMath & do not allow reordering.
1335 // If the EnableStrictReductions flag is set, first check if we have any
1336 // Exact FP induction vars, which we cannot vectorize.
1337 if (!EnableStrictReductions ||
1338 any_of(getInductionVars(), [&](auto &Induction) -> bool {
1339 InductionDescriptor IndDesc = Induction.second;
1340 return IndDesc.getExactFPMathInst();
1341 }))
1342 return false;
1343
1344 // We can now only vectorize if all reductions with Exact FP math also
1345 // have the isOrdered flag set, which indicates that we can move the
1346 // reduction operations in-loop.
1347 return (all_of(getReductionVars(), [&](auto &Reduction) -> bool {
1348 const RecurrenceDescriptor &RdxDesc = Reduction.second;
1349 return !RdxDesc.hasExactFPMath() || RdxDesc.isOrdered();
1350 }));
1351}
1352
1354 return any_of(getReductionVars(), [&](auto &Reduction) -> bool {
1355 const RecurrenceDescriptor &RdxDesc = Reduction.second;
1356 return RdxDesc.IntermediateStore == SI;
1357 });
1358}
1359
1361 return any_of(getReductionVars(), [&](auto &Reduction) -> bool {
1362 const RecurrenceDescriptor &RdxDesc = Reduction.second;
1363 if (!RdxDesc.IntermediateStore)
1364 return false;
1365
1366 ScalarEvolution *SE = PSE.getSE();
1367 Value *InvariantAddress = RdxDesc.IntermediateStore->getPointerOperand();
1368 return V == InvariantAddress ||
1369 SE->getSCEV(V) == SE->getSCEV(InvariantAddress);
1370 });
1371}
1372
1374 Value *In0 = const_cast<Value *>(V);
1376 if (!PN)
1377 return false;
1378
1379 return Inductions.count(PN);
1380}
1381
1382const InductionDescriptor *
1384 if (!isInductionPhi(Phi))
1385 return nullptr;
1386 auto &ID = getInductionVars().find(Phi)->second;
1387 if (ID.getKind() == InductionDescriptor::IK_IntInduction ||
1389 return &ID;
1390 return nullptr;
1391}
1392
1393const InductionDescriptor *
1395 if (!isInductionPhi(Phi))
1396 return nullptr;
1397 auto &ID = getInductionVars().find(Phi)->second;
1399 return &ID;
1400 return nullptr;
1401}
1402
1404 const Value *V) const {
1405 auto *Inst = dyn_cast<Instruction>(V);
1406 return (Inst && InductionCastsToIgnore.count(Inst));
1407}
1408
1412
1414 const PHINode *Phi) const {
1415 return FixedOrderRecurrences.count(Phi);
1416}
1417
1419 const BasicBlock *BB) const {
1420 // When vectorizing early exits, create predicates for the latch block only.
1421 // For a single early exit, it must be a direct predecessor of the latch.
1422 // For multiple early exits, they form a chain where each exiting block
1423 // dominates all subsequent blocks up to the latch.
1424 BasicBlock *Latch = TheLoop->getLoopLatch();
1426 return BB == Latch;
1427 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
1428}
1429
1430bool LoopVectorizationLegality::blockCanBePredicated(
1431 BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs,
1432 SmallPtrSetImpl<const Instruction *> &MaskedOp) const {
1433 for (Instruction &I : *BB) {
1434 // We can predicate blocks with calls to assume, as long as we drop them in
1435 // case we flatten the CFG via predication.
1437 MaskedOp.insert(&I);
1438 continue;
1439 }
1440
1441 // Do not let llvm.experimental.noalias.scope.decl block the vectorization.
1442 // TODO: there might be cases that it should block the vectorization. Let's
1443 // ignore those for now.
1445 continue;
1446
1447 // We can allow masked calls if there's at least one vector variant, even
1448 // if we end up scalarizing due to the cost model calculations.
1449 // TODO: Allow other calls if they have appropriate attributes... readonly
1450 // and argmemonly?
1451 if (CallInst *CI = dyn_cast<CallInst>(&I))
1453 MaskedOp.insert(CI);
1454 continue;
1455 }
1456
1457 // Loads are handled via masking (or speculated if safe to do so.)
1458 if (auto *LI = dyn_cast<LoadInst>(&I)) {
1459 if (!SafePtrs.count(LI->getPointerOperand()))
1460 MaskedOp.insert(LI);
1461 continue;
1462 }
1463
1464 // Predicated store requires some form of masking:
1465 // 1) masked store HW instruction,
1466 // 2) emulation via load-blend-store (only if safe and legal to do so,
1467 // be aware on the race conditions), or
1468 // 3) element-by-element predicate check and scalar store.
1469 if (auto *SI = dyn_cast<StoreInst>(&I)) {
1470 MaskedOp.insert(SI);
1471 continue;
1472 }
1473
1474 if (I.mayReadFromMemory() || I.mayWriteToMemory() || I.mayThrow())
1475 return false;
1476 }
1477
1478 return true;
1479}
1480
1481bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1482 if (!EnableIfConversion) {
1483 reportVectorizationFailure("If-conversion is disabled",
1484 "IfConversionDisabled", ORE, TheLoop);
1485 return false;
1486 }
1487
1488 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1489
1490 // A list of pointers which are known to be dereferenceable within scope of
1491 // the loop body for each iteration of the loop which executes. That is,
1492 // the memory pointed to can be dereferenced (with the access size implied by
1493 // the value's type) unconditionally within the loop header without
1494 // introducing a new fault.
1495 SmallPtrSet<Value *, 8> SafePointers;
1496
1497 // Collect safe addresses.
1498 for (BasicBlock *BB : TheLoop->blocks()) {
1499 if (!blockNeedsPredication(BB)) {
1500 for (Instruction &I : *BB)
1501 if (auto *Ptr = getLoadStorePointerOperand(&I))
1502 SafePointers.insert(Ptr);
1503 continue;
1504 }
1505
1506 // For a block which requires predication, a address may be safe to access
1507 // in the loop w/o predication if we can prove dereferenceability facts
1508 // sufficient to ensure it'll never fault within the loop. For the moment,
1509 // we restrict this to loads; stores are more complicated due to
1510 // concurrency restrictions.
1511 ScalarEvolution &SE = *PSE.getSE();
1513 for (Instruction &I : *BB) {
1514 LoadInst *LI = dyn_cast<LoadInst>(&I);
1515
1516 // Make sure we can execute all computations feeding into Ptr in the loop
1517 // w/o triggering UB and that none of the out-of-loop operands are poison.
1518 // We do not need to check if operations inside the loop can produce
1519 // poison due to flags (e.g. due to an inbounds GEP going out of bounds),
1520 // because flags will be dropped when executing them unconditionally.
1521 // TODO: Results could be improved by considering poison-propagation
1522 // properties of visited ops.
1523 auto CanSpeculatePointerOp = [this](Value *Ptr) {
1524 SmallVector<Value *> Worklist = {Ptr};
1525 SmallPtrSet<Value *, 4> Visited;
1526 while (!Worklist.empty()) {
1527 Value *CurrV = Worklist.pop_back_val();
1528 if (!Visited.insert(CurrV).second)
1529 continue;
1530
1531 auto *CurrI = dyn_cast<Instruction>(CurrV);
1532 if (!CurrI || !TheLoop->contains(CurrI)) {
1533 // If operands from outside the loop may be poison then Ptr may also
1534 // be poison.
1535 if (!isGuaranteedNotToBePoison(CurrV, AC,
1536 TheLoop->getLoopPredecessor()
1537 ->getTerminator()
1538 ->getIterator(),
1539 DT))
1540 return false;
1541 continue;
1542 }
1543
1544 // A loaded value may be poison, independent of any flags.
1545 if (isa<LoadInst>(CurrI) && !isGuaranteedNotToBePoison(CurrV, AC))
1546 return false;
1547
1548 // For other ops, assume poison can only be introduced via flags,
1549 // which can be dropped.
1550 if (!isa<PHINode>(CurrI) && !isSafeToSpeculativelyExecute(CurrI))
1551 return false;
1552 append_range(Worklist, CurrI->operands());
1553 }
1554 return true;
1555 };
1556 // Pass the Predicates pointer to isDereferenceableAndAlignedInLoop so
1557 // that it will consider loops that need guarding by SCEV checks. The
1558 // vectoriser will generate these checks if we decide to vectorise.
1559 if (LI && !LI->getType()->isVectorTy() && !mustSuppressSpeculation(*LI) &&
1560 CanSpeculatePointerOp(LI->getPointerOperand()) &&
1561 isDereferenceableAndAlignedInLoop(LI, TheLoop, SE, *DT, AC,
1562 &Predicates))
1563 SafePointers.insert(LI->getPointerOperand());
1564 Predicates.clear();
1565 }
1566 }
1567
1568 // Collect the blocks that need predication.
1569 for (BasicBlock *BB : TheLoop->blocks()) {
1570 // We support only branches and switch statements as terminators inside the
1571 // loop.
1572 if (isa<SwitchInst>(BB->getTerminator())) {
1573 if (TheLoop->isLoopExiting(BB)) {
1574 reportVectorizationFailure("Loop contains an unsupported switch",
1575 "LoopContainsUnsupportedSwitch", ORE,
1576 TheLoop, BB->getTerminator());
1577 return false;
1578 }
1579 } else if (!isa<UncondBrInst, CondBrInst>(BB->getTerminator())) {
1580 reportVectorizationFailure("Loop contains an unsupported terminator",
1581 "LoopContainsUnsupportedTerminator", ORE,
1582 TheLoop, BB->getTerminator());
1583 return false;
1584 }
1585
1586 // We must be able to predicate all blocks that need to be predicated.
1587 if (blockNeedsPredication(BB) &&
1588 !blockCanBePredicated(BB, SafePointers, ConditionallyExecutedOps)) {
1590 "Control flow cannot be substituted for a select", "NoCFGForSelect",
1591 ORE, TheLoop, BB->getTerminator());
1592 return false;
1593 }
1594 }
1595
1596 // We can if-convert this loop.
1597 return true;
1598}
1599
1600// Helper function to canVectorizeLoopNestCFG.
1601bool LoopVectorizationLegality::canVectorizeLoopCFG(Loop *Lp,
1602 bool UseVPlanNativePath) {
1603 assert((UseVPlanNativePath || Lp->isInnermost()) &&
1604 "VPlan-native path is not enabled.");
1605
1606 // TODO: ORE should be improved to show more accurate information when an
1607 // outer loop can't be vectorized because a nested loop is not understood or
1608 // legal. Something like: "outer_loop_location: loop not vectorized:
1609 // (inner_loop_location) loop control flow is not understood by vectorizer".
1610
1611 // Store the result and return it at the end instead of exiting early, in case
1612 // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1613 bool Result = true;
1614 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1615
1616 // We must have a loop in canonical form. Loops with indirectbr in them cannot
1617 // be canonicalized.
1618 if (!Lp->getLoopPreheader()) {
1619 reportVectorizationFailure("Loop doesn't have a legal pre-header",
1620 "loop control flow is not understood by vectorizer",
1621 "CFGNotUnderstood", ORE, TheLoop);
1622 if (DoExtraAnalysis)
1623 Result = false;
1624 else
1625 return false;
1626 }
1627
1628 // We must have a single backedge.
1629 if (Lp->getNumBackEdges() != 1) {
1630 reportVectorizationFailure("The loop must have a single backedge",
1631 "loop control flow is not understood by vectorizer",
1632 "CFGNotUnderstood", ORE, TheLoop);
1633 if (DoExtraAnalysis)
1634 Result = false;
1635 else
1636 return false;
1637 }
1638
1639 // The latch must be terminated by a branch.
1640 BasicBlock *Latch = Lp->getLoopLatch();
1641 if (Latch && !isa<UncondBrInst, CondBrInst>(Latch->getTerminator())) {
1643 "The loop latch terminator is not a UncondBrInst/CondBrInst",
1644 "loop control flow is not understood by vectorizer", "CFGNotUnderstood",
1645 ORE, TheLoop);
1646 if (DoExtraAnalysis)
1647 Result = false;
1648 else
1649 return false;
1650 }
1651
1652 return Result;
1653}
1654
1655bool LoopVectorizationLegality::canVectorizeLoopNestCFG(
1656 Loop *Lp, bool UseVPlanNativePath) {
1657 // Store the result and return it at the end instead of exiting early, in case
1658 // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1659 bool Result = true;
1660 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1661 if (!canVectorizeLoopCFG(Lp, UseVPlanNativePath)) {
1662 if (DoExtraAnalysis)
1663 Result = false;
1664 else
1665 return false;
1666 }
1667
1668 // Recursively check whether the loop control flow of nested loops is
1669 // understood.
1670 for (Loop *SubLp : *Lp)
1671 if (!canVectorizeLoopNestCFG(SubLp, UseVPlanNativePath)) {
1672 if (DoExtraAnalysis)
1673 Result = false;
1674 else
1675 return false;
1676 }
1677
1678 return Result;
1679}
1680
1681bool LoopVectorizationLegality::isVectorizableEarlyExitLoop() {
1682 BasicBlock *LatchBB = TheLoop->getLoopLatch();
1683 if (!LatchBB) {
1684 reportVectorizationFailure("Loop does not have a latch",
1685 "Cannot vectorize early exit loop",
1686 "NoLatchEarlyExit", ORE, TheLoop);
1687 return false;
1688 }
1689
1690 if (Reductions.size() || FixedOrderRecurrences.size()) {
1692 "Found reductions or recurrences in early-exit loop",
1693 "Cannot vectorize early exit loop with reductions or recurrences",
1694 "RecurrencesInEarlyExitLoop", ORE, TheLoop);
1695 return false;
1696 }
1697
1698 SmallVector<BasicBlock *, 8> ExitingBlocks;
1699 TheLoop->getExitingBlocks(ExitingBlocks);
1700
1701 // Keep a record of all the exiting blocks.
1703 SmallVector<BasicBlock *> UncountableExitingBlocks;
1704 for (BasicBlock *BB : ExitingBlocks) {
1705 const SCEV *EC =
1706 PSE.getSE()->getPredicatedExitCount(TheLoop, BB, &Predicates);
1707 if (isa<SCEVCouldNotCompute>(EC)) {
1708 if (size(successors(BB)) != 2) {
1710 "Early exiting block does not have exactly two successors",
1711 "Incorrect number of successors from early exiting block",
1712 "EarlyExitTooManySuccessors", ORE, TheLoop);
1713 return false;
1714 }
1715
1716 UncountableExitingBlocks.push_back(BB);
1717 } else
1718 CountableExitingBlocks.push_back(BB);
1719 }
1720 // We can safely ignore the predicates here because when vectorizing the loop
1721 // the PredicatatedScalarEvolution class will keep track of all predicates
1722 // for each exiting block anyway. This happens when calling
1723 // PSE.getSymbolicMaxBackedgeTakenCount() below.
1724 Predicates.clear();
1725
1726 if (UncountableExitingBlocks.empty()) {
1727 LLVM_DEBUG(dbgs() << "LV: Could not find any uncountable exits");
1728 return false;
1729 }
1730
1731 // The latch block must have a countable exit.
1733 PSE.getSE()->getPredicatedExitCount(TheLoop, LatchBB, &Predicates))) {
1735 "Cannot determine exact exit count for latch block",
1736 "Cannot vectorize early exit loop",
1737 "UnknownLatchExitCountEarlyExitLoop", ORE, TheLoop);
1738 return false;
1739 }
1740 assert(llvm::is_contained(CountableExitingBlocks, LatchBB) &&
1741 "Latch block not found in list of countable exits!");
1742
1743 // Check to see if there are instructions that could potentially generate
1744 // exceptions or have side-effects.
1745 auto IsSafeOperation = [](Instruction *I) -> bool {
1746 switch (I->getOpcode()) {
1747 case Instruction::Load:
1748 case Instruction::Store:
1749 case Instruction::PHI:
1750 case Instruction::UncondBr:
1751 case Instruction::CondBr:
1752 // These are checked separately.
1753 return true;
1754 default:
1756 }
1757 };
1758
1759 bool HasSideEffects = false;
1760 for (auto *BB : TheLoop->blocks())
1761 for (auto &I : *BB) {
1762 if (I.mayWriteToMemory()) {
1763 if (isa<StoreInst>(&I) && cast<StoreInst>(&I)->isSimple()) {
1764 HasSideEffects = true;
1765 continue;
1766 }
1767
1768 // We don't support complex writes to memory.
1770 "Complex writes to memory unsupported in early exit loops",
1771 "Cannot vectorize early exit loop with complex writes to memory",
1772 "WritesInEarlyExitLoop", ORE, TheLoop);
1773 return false;
1774 }
1775
1776 if (!IsSafeOperation(&I)) {
1777 reportVectorizationFailure("Early exit loop contains operations that "
1778 "cannot be speculatively executed",
1779 "UnsafeOperationsEarlyExitLoop", ORE,
1780 TheLoop);
1781 return false;
1782 }
1783 }
1784
1785 SmallVector<LoadInst *, 4> NonDerefLoads;
1786 // TODO: Handle loops that may fault.
1787 if (!HasSideEffects) {
1788 // Read-only loop.
1789 Predicates.clear();
1790 if (!isReadOnlyLoop(TheLoop, PSE.getSE(), DT, AC, NonDerefLoads,
1791 &Predicates)) {
1793 "Loop may fault", "Cannot vectorize non-read-only early exit loop",
1794 "NonReadOnlyEarlyExitLoop", ORE, TheLoop);
1795 return false;
1796 }
1797 } else {
1798 // Check all uncountable exiting blocks for movable loads.
1799 for (BasicBlock *ExitingBB : UncountableExitingBlocks) {
1800 if (!canUncountableExitConditionLoadBeMoved(ExitingBB))
1801 return false;
1802 }
1803 }
1804
1805 // Check non-dereferenceable loads if any.
1806 for (LoadInst *LI : NonDerefLoads) {
1807 // Only support unit-stride access for now.
1808 int Stride = isConsecutivePtr(LI->getType(), LI->getPointerOperand());
1809 if (Stride != 1) {
1811 "Loop contains potentially faulting strided load",
1812 "Cannot vectorize early exit loop with "
1813 "strided fault-only-first load",
1814 "EarlyExitLoopWithStridedFaultOnlyFirstLoad", ORE, TheLoop);
1815 return false;
1816 }
1817 }
1818
1819 [[maybe_unused]] const SCEV *SymbolicMaxBTC =
1820 PSE.getSymbolicMaxBackedgeTakenCount();
1821 // Since we have an exact exit count for the latch and the early exit
1822 // dominates the latch, then this should guarantee a computed SCEV value.
1823 assert(!isa<SCEVCouldNotCompute>(SymbolicMaxBTC) &&
1824 "Failed to get symbolic expression for backedge taken count");
1825 LLVM_DEBUG(dbgs() << "LV: Found an early exit loop with symbolic max "
1826 "backedge taken count: "
1827 << *SymbolicMaxBTC << '\n');
1828 UncountableExitType = HasSideEffects ? UncountableExitTrait::ReadWrite
1830 return true;
1831}
1832
1833bool LoopVectorizationLegality::canUncountableExitConditionLoadBeMoved(
1834 BasicBlock *ExitingBlock) {
1835 // Try to find a load in the critical path for the uncountable exit condition.
1836 // This is currently matching about the simplest form we can, expecting
1837 // only one in-loop load, the result of which is directly compared against
1838 // a loop-invariant value.
1839 // FIXME: We're insisting on a single use for now, because otherwise we will
1840 // need to make PHI nodes for other users. That can be done once the initial
1841 // transform code lands.
1842 auto *Br = cast<CondBrInst>(ExitingBlock->getTerminator());
1843
1844 using namespace llvm::PatternMatch;
1845 Instruction *L = nullptr;
1846 Value *Ptr = nullptr;
1847 Value *R = nullptr;
1848 if (!match(Br->getCondition(),
1850 m_Value(R))))) {
1852 "Early exit loop with store but no supported condition load",
1853 "NoConditionLoadForEarlyExitLoop", ORE, TheLoop);
1854 return false;
1855 }
1856
1857 // FIXME: Don't rely on operand ordering for the comparison.
1858 if (!TheLoop->isLoopInvariant(R)) {
1860 "Early exit loop with store but no supported condition load",
1861 "NoConditionLoadForEarlyExitLoop", ORE, TheLoop);
1862 return false;
1863 }
1864
1865 // Make sure that the load address is not loop invariant; we want an
1866 // address calculation that we can rotate to the next vector iteration.
1867 const auto *AR = dyn_cast<SCEVAddRecExpr>(PSE.getSE()->getSCEV(Ptr));
1868 if (!AR || AR->getLoop() != TheLoop || !AR->isAffine()) {
1870 "Uncountable exit condition depends on load with an address that is "
1871 "not an add recurrence in the loop",
1872 "EarlyExitLoadInvariantAddress", ORE, TheLoop);
1873 return false;
1874 }
1875
1876 ICFLoopSafetyInfo SafetyInfo;
1877 SafetyInfo.computeLoopSafetyInfo(TheLoop);
1878 LoadInst *Load = cast<LoadInst>(L);
1879 // We need to know that load will be executed before we can hoist a
1880 // copy out to run just before the first iteration.
1881 if (!SafetyInfo.isGuaranteedToExecute(*Load, DT, TheLoop)) {
1883 "Load for uncountable exit not guaranteed to execute",
1884 "ConditionalUncountableExitLoad", ORE, TheLoop);
1885 return false;
1886 }
1887
1888 // Prohibit any potential aliasing with any instruction in the loop which
1889 // might store to memory.
1890 // FIXME: Relax this constraint where possible.
1891 for (auto *BB : TheLoop->blocks()) {
1892 for (auto &I : *BB) {
1893 if (&I == Load)
1894 continue;
1895
1896 if (I.mayWriteToMemory()) {
1897 if (auto *SI = dyn_cast<StoreInst>(&I)) {
1898 AliasResult AR = AA->alias(Ptr, SI->getPointerOperand());
1899 if (AR == AliasResult::NoAlias)
1900 continue;
1901 }
1902
1904 "Cannot determine whether critical uncountable exit load address "
1905 "does not alias with a memory write",
1906 "CantVectorizeAliasWithCriticalUncountableExitLoad", ORE, TheLoop);
1907 return false;
1908 }
1909 }
1910 }
1911
1912 return true;
1913}
1914
1915bool LoopVectorizationLegality::canVectorize(bool UseVPlanNativePath) {
1916 // Store the result and return it at the end instead of exiting early, in case
1917 // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1918 bool Result = true;
1919
1920 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1921 // Check whether the loop-related control flow in the loop nest is expected by
1922 // vectorizer.
1923 if (!canVectorizeLoopNestCFG(TheLoop, UseVPlanNativePath)) {
1924 if (DoExtraAnalysis) {
1925 LLVM_DEBUG(dbgs() << "LV: legality check failed: loop nest");
1926 Result = false;
1927 } else {
1928 return false;
1929 }
1930 }
1931
1932 // We need to have a loop header.
1933 LLVM_DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()
1934 << '\n');
1935
1936 // Specific checks for outer loops. We skip the remaining legal checks at this
1937 // point because they don't support outer loops.
1938 if (!TheLoop->isInnermost()) {
1939 assert(UseVPlanNativePath && "VPlan-native path is not enabled.");
1940
1941 if (!canVectorizeOuterLoop()) {
1942 reportVectorizationFailure("Unsupported outer loop",
1943 "UnsupportedOuterLoop", ORE, TheLoop);
1944 // TODO: Implement DoExtraAnalysis when subsequent legal checks support
1945 // outer loops.
1946 return false;
1947 }
1948
1949 LLVM_DEBUG(dbgs() << "LV: We can vectorize this outer loop!\n");
1950 return Result;
1951 }
1952
1953 assert(TheLoop->isInnermost() && "Inner loop expected.");
1954 // Check if we can if-convert non-single-bb loops.
1955 unsigned NumBlocks = TheLoop->getNumBlocks();
1956 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1957 LLVM_DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1958 if (DoExtraAnalysis)
1959 Result = false;
1960 else
1961 return false;
1962 }
1963
1964 // Check if we can vectorize the instructions and CFG in this loop.
1965 if (!canVectorizeInstrs()) {
1966 LLVM_DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
1967 if (DoExtraAnalysis)
1968 Result = false;
1969 else
1970 return false;
1971 }
1972
1973 if (isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount())) {
1974 if (TheLoop->getExitingBlock()) {
1975 reportVectorizationFailure("Cannot vectorize uncountable loop",
1976 "UnsupportedUncountableLoop", ORE, TheLoop);
1977 if (DoExtraAnalysis)
1978 Result = false;
1979 else
1980 return false;
1981 } else {
1982 if (!isVectorizableEarlyExitLoop()) {
1983 assert(UncountableExitType == UncountableExitTrait::None &&
1984 "Must be false without vectorizable early-exit loop");
1985 if (DoExtraAnalysis)
1986 Result = false;
1987 else
1988 return false;
1989 }
1990 }
1991 }
1992
1993 // Go over each instruction and look at memory deps.
1994 if (!canVectorizeMemory()) {
1995 LLVM_DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
1996 if (DoExtraAnalysis)
1997 Result = false;
1998 else
1999 return false;
2000 }
2001
2002 // Bail out for ReadWrite loops with uncountable exits for now.
2003 if (UncountableExitType == UncountableExitTrait::ReadWrite) {
2005 "Writes to memory unsupported in early exit loops",
2006 "Cannot vectorize early exit loop with writes to memory",
2007 "WritesInEarlyExitLoop", ORE, TheLoop);
2008 return false;
2009 }
2010
2011 if (Result) {
2012 LLVM_DEBUG(dbgs() << "LV: We can vectorize this loop"
2013 << (LAI->getRuntimePointerChecking()->Need
2014 ? " (with a runtime bound check)"
2015 : "")
2016 << "!\n");
2017 }
2018
2019 unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
2020 if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
2021 SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
2022
2023 if (PSE.getPredicate().getComplexity() > SCEVThreshold) {
2024 LLVM_DEBUG(dbgs() << "LV: Vectorization not profitable "
2025 "due to SCEVThreshold");
2026 reportVectorizationFailure("Too many SCEV checks needed",
2027 "Too many SCEV assumptions need to be made and checked at runtime",
2028 "TooManySCEVRunTimeChecks", ORE, TheLoop);
2029 if (DoExtraAnalysis)
2030 Result = false;
2031 else
2032 return false;
2033 }
2034
2035 // Okay! We've done all the tests. If any have failed, return false. Otherwise
2036 // we can vectorize, and at this point we don't have any other mem analysis
2037 // which may limit our maximum vectorization factor, so just return true with
2038 // no restrictions.
2039 return Result;
2040}
2041
2043 // The only loops we can vectorize without a scalar epilogue, are loops with
2044 // a bottom-test and a single exiting block. We'd have to handle the fact
2045 // that not every instruction executes on the last iteration. This will
2046 // require a lane mask which varies through the vector loop body. (TODO)
2047 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
2048 LLVM_DEBUG(
2049 dbgs()
2050 << "LV: Cannot fold tail by masking. Requires a singe latch exit\n");
2051 return false;
2052 }
2053
2054 LLVM_DEBUG(dbgs() << "LV: checking if tail can be folded by masking.\n");
2055
2056 // The list of pointers that we can safely read and write to remains empty.
2057 SmallPtrSet<Value *, 8> SafePointers;
2058
2059 // Check all blocks for predication, including those that ordinarily do not
2060 // need predication such as the header block.
2062 for (BasicBlock *BB : TheLoop->blocks()) {
2063 if (!blockCanBePredicated(BB, SafePointers, TmpMaskedOp)) {
2064 LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking.\n");
2065 return false;
2066 }
2067 }
2068
2069 LLVM_DEBUG(dbgs() << "LV: can fold tail by masking.\n");
2070
2071 return true;
2072}
2073
2075 // The list of pointers that we can safely read and write to remains empty.
2076 SmallPtrSet<Value *, 8> SafePointers;
2077
2078 // Mark all blocks for predication, including those that ordinarily do not
2079 // need predication such as the header block, and collect instructions needing
2080 // predication in TailFoldedMaskedOp.
2081 for (BasicBlock *BB : TheLoop->blocks()) {
2082 [[maybe_unused]] bool R =
2083 blockCanBePredicated(BB, SafePointers, TailFoldedMaskedOp);
2084 assert(R && "Must be able to predicate block when tail-folding.");
2085 }
2086}
2087
2088} // namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
#define DEBUG_TYPE
Hexagon Common GEP
#define LV_NAME
static cl::opt< unsigned > PragmaVectorizeSCEVCheckThreshold("pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden, cl::desc("The maximum number of SCEV checks allowed with a " "vectorize(enable) pragma"))
static cl::opt< bool > HintsAllowReordering("hints-allow-reordering", cl::init(true), cl::Hidden, cl::desc("Allow enabling loop hints to reorder " "FP operations during vectorization."))
static const unsigned MaxInterleaveFactor
Maximum vectorization interleave count.
static cl::opt< bool > AllowStridedPointerIVs("lv-strided-pointer-ivs", cl::init(false), cl::Hidden, cl::desc("Enable recognition of non-constant strided " "pointer induction variables."))
static cl::opt< LoopVectorizeHints::ScalableForceKind > ForceScalableVectorization("scalable-vectorization", cl::init(LoopVectorizeHints::SK_Unspecified), cl::Hidden, cl::desc("Control whether the compiler can use scalable vectors to " "vectorize a loop"), cl::values(clEnumValN(LoopVectorizeHints::SK_FixedWidthOnly, "off", "Scalable vectorization is disabled."), clEnumValN(LoopVectorizeHints::SK_PreferScalable, "preferred", "Scalable vectorization is available and favored when the " "cost is inconclusive."), clEnumValN(LoopVectorizeHints::SK_PreferScalable, "on", "Scalable vectorization is available and favored when the " "cost is inconclusive."), clEnumValN(LoopVectorizeHints::SK_AlwaysScalable, "always", "Scalable vectorization is available and always favored when " "feasible")))
static cl::opt< unsigned > VectorizeSCEVCheckThreshold("vectorize-scev-check-threshold", cl::init(16), cl::Hidden, cl::desc("The maximum number of SCEV checks allowed."))
static cl::opt< bool > EnableHistogramVectorization("enable-histogram-loop-vectorization", cl::init(false), cl::Hidden, cl::desc("Enables autovectorization of some loops containing histograms"))
static cl::opt< bool > EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden, cl::desc("Enable if-conversion during vectorization."))
This file defines the LoopVectorizationLegality class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define H(x, y, z)
Definition MD5.cpp:56
#define T
Contains a collection of routines for determining if a given instruction is guaranteed to execute if ...
static bool isSimple(Instruction *I)
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
Virtual Register Rewriter
static const uint32_t IV[8]
Definition blake3_impl.h:83
@ NoAlias
The two locations do not alias at all.
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
This class represents a function call, abstracting a target machine's calling convention.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
static constexpr ElementCount getScalable(ScalarTy MinVal)
Definition TypeSize.h:312
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:309
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:320
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:873
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
bool isGuaranteedToExecute(const Instruction &Inst, const DominatorTree *DT, const Loop *CurLoop) const override
Returns true if the instruction in a loop is guaranteed to execute at least once (under the assumptio...
void computeLoopSafetyInfo(const Loop *CurLoop) override
Computes safety information for a loop checks loop body & header for the possibility of may throw exc...
A struct for saving information about induction variables.
@ IK_FpInduction
Floating point induction variable.
@ IK_PtrInduction
Pointer induction var. Step = C.
@ IK_IntInduction
Integer induction variable. Step = C.
static LLVM_ABI bool isInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, InductionDescriptor &D, const SCEV *Expr=nullptr, SmallVectorImpl< Instruction * > *CastsToIgnore=nullptr)
Returns true if Phi is an induction in the loop L.
Instruction * getExactFPMathInst()
Returns floating-point induction operator that does not allow reassociation (transforming the inducti...
Class to represent integer types.
An instruction for reading from memory.
const MemoryDepChecker & getDepChecker() const
the Memory Dependence Checker which can determine the loop-independent and loop-carried dependences b...
static LLVM_ABI bool blockNeedsPredication(const BasicBlock *BB, const Loop *TheLoop, const DominatorTree *DT)
Return true if the block BB needs to be predicated in order for the loop to be vectorized.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
unsigned getNumBackEdges() const
Calculate the number of back edges to the loop header.
iterator_range< block_iterator > blocks() const
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
bool isLoopHeader(const BlockT *BB) const
bool isInvariantStoreOfReduction(StoreInst *SI)
Returns True if given store is a final invariant store of one of the reductions found in the loop.
bool isInvariantAddressOfReduction(Value *V)
Returns True if given address is invariant and is used to store recurrent expression.
bool canVectorize(bool UseVPlanNativePath)
Returns true if it is legal to vectorize this loop.
bool blockNeedsPredication(const BasicBlock *BB) const
Return true if the block BB needs to be predicated in order for the loop to be vectorized.
int isConsecutivePtr(Type *AccessTy, Value *Ptr) const
Check if this pointer is consecutive when vectorizing.
bool hasUncountableExitWithSideEffects() const
Returns true if this is an early exit loop with state-changing or potentially-faulting operations and...
bool canVectorizeFPMath(bool EnableStrictReductions)
Returns true if it is legal to vectorize the FP math operations in this loop.
bool isFixedOrderRecurrence(const PHINode *Phi) const
Returns True if Phi is a fixed-order recurrence in this loop.
const InductionDescriptor * getPointerInductionDescriptor(PHINode *Phi) const
Returns a pointer to the induction descriptor, if Phi is pointer induction.
const InductionDescriptor * getIntOrFpInductionDescriptor(PHINode *Phi) const
Returns a pointer to the induction descriptor, if Phi is an integer or floating point induction.
bool isInductionPhi(const Value *V) const
Returns True if V is a Phi node of an induction variable in this loop.
bool isUniform(Value *V, ElementCount VF) const
Returns true if value V is uniform across VF lanes, when VF is provided, and otherwise if V is invari...
const InductionList & getInductionVars() const
Returns the induction variables found in the loop.
bool isInvariant(Value *V) const
Returns true if V is invariant across all loop iterations according to SCEV.
const ReductionList & getReductionVars() const
Returns the reduction variables found in the loop.
bool canFoldTailByMasking() const
Return true if we can vectorize this loop while folding its tail by masking.
void prepareToFoldTailByMasking()
Mark all respective loads/stores for masking.
bool hasUncountableEarlyExit() const
Returns true if the loop has uncountable early exits, i.e.
bool isUniformMemOp(Instruction &I, ElementCount VF) const
A uniform memory op is a load or store which accesses the same memory location on all VF lanes,...
bool isInductionVariable(const Value *V) const
Returns True if V can be considered as an induction variable in this loop.
bool isCastedInductionVariable(const Value *V) const
Returns True if V is a cast that is part of an induction def-use chain, and had been proven to be red...
@ SK_PreferScalable
Vectorize loops using scalable vectors or fixed-width vectors, but favor scalable vectors when the co...
@ SK_AlwaysScalable
Always vectorize loops using scalable vectors if feasible (i.e.
@ SK_FixedWidthOnly
Disables vectorization with scalable vectors.
bool allowVectorization(Function *F, Loop *L, bool VectorizeOnlyWhenForced) const
bool allowReordering() const
When enabling loop hints are provided we allow the vectorizer to change the order of operations that ...
void emitRemarkWithHints() const
Dumps all the hint information.
void setAlreadyVectorized()
Mark the loop L as already vectorized by setting the width to 1.
LoopVectorizeHints(const Loop *L, bool InterleaveOnlyWhenForced, OptimizationRemarkEmitter &ORE, const TargetTransformInfo *TTI=nullptr)
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:67
PHINode * getCanonicalInductionVariable() const
Check to see if the loop has a canonical induction variable: an integer recurrence that starts at 0 a...
Definition LoopInfo.cpp:174
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
Definition LoopInfo.cpp:523
Metadata node.
Definition Metadata.h:1080
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1444
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1442
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1450
Tracking metadata reference owned by Metadata.
Definition Metadata.h:902
A single uniqued string.
Definition Metadata.h:722
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:632
iterator find(const KeyT &Key)
Definition MapVector.h:156
Checks memory dependences among accesses to the same underlying object to determine whether there vec...
const SmallVectorImpl< Dependence > * getDependences() const
Returns the memory dependences.
Root of the metadata hierarchy.
Definition Metadata.h:64
Diagnostic information for optimization analysis remarks.
The optimization diagnostic interface.
bool allowExtraAnalysis(StringRef PassName) const
Whether we allow for extra compile-time budget to perform more analysis to produce fewer false positi...
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for missed-optimization remarks.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
Instruction * getExactFPMathInst() const
Returns 1st non-reassociative FP instruction in the PHI node's use-chain.
static LLVM_ABI bool isFixedOrderRecurrence(PHINode *Phi, Loop *TheLoop, DominatorTree *DT)
Returns true if Phi is a fixed-order recurrence.
bool hasExactFPMath() const
Returns true if the recurrence has floating-point math that requires precise (ordered) operations.
Instruction * getLoopExitInstr() const
static LLVM_ABI bool isReductionPHI(PHINode *Phi, Loop *TheLoop, RecurrenceDescriptor &RedDes, DemandedBits *DB=nullptr, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr, ScalarEvolution *SE=nullptr)
Returns true if Phi is a reduction in TheLoop.
bool hasUsesOutsideReductionChain() const
Returns true if the reduction PHI has any uses outside the reduction chain.
RecurKind getRecurrenceKind() const
bool isOrdered() const
Expose an ordered FP reduction to the instance users.
StoreInst * IntermediateStore
Reductions may store temporary or final result to an invariant address.
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This visitor recursively visits a SCEV expression and re-writes it.
const SCEV * visit(const SCEV *S)
This class represents an analyzed expression in the program.
static constexpr auto FlagAnyWrap
The main scalar evolution driver.
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI const SCEV * getCouldNotCompute()
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Value * getPointerOperand()
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Provides information about what library functions are available for the current target.
void getWidestVF(StringRef ScalarF, ElementCount &FixedVF, ElementCount &ScalableVF) const
Returns the largest vectorization factor used in the list of vector functions.
bool isFunctionVectorizable(StringRef F, const ElementCount &VF) const
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:313
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:284
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:236
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:272
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
Value * getOperand(unsigned i) const
Definition User.h:207
static bool hasMaskedVariant(const CallInst &CI, std::optional< ElementCount > VF=std::nullopt)
Definition VectorUtils.h:87
static SmallVector< VFInfo, 8 > getMappings(const CallInst &CI)
Retrieve all the VFInfo instances associated to the CallInst CI.
Definition VectorUtils.h:76
LLVM Value Representation.
Definition Value.h:75
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:318
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:230
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
constexpr bool isZero() const
Definition TypeSize.h:153
const ParentTy * getParent() const
Definition ilist_node.h:34
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
TwoOps_match< ValueOpTy, PointerOpTy, Instruction::Store > m_Store(const ValueOpTy &ValueOp, const PointerOpTy &PointerOp)
Matches StoreInst.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
IntrinsicID_match m_Intrinsic()
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
auto m_Value()
Match an arbitrary value and ignore it.
match_combine_or< match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > >, OpTy > m_ZExtOrSExtOrSelf(const OpTy &Op)
OneOps_match< OpTy, Instruction::Load > m_Load(const OpTy &Op)
Matches LoadInst.
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:696
Add a small namespace to avoid name clashes with the classes used in the streaming interface.
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
@ Offset
Definition DWP.cpp:558
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1738
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1668
LLVM_ABI Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
static bool isUniformLoopNest(Loop *Lp, Loop *OuterLp)
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2207
static bool isUniformLoop(Loop *Lp, Loop *OuterLp)
LLVM_ABI bool mustSuppressSpeculation(const LoadInst &LI)
Return true if speculation of the given load must be suppressed to avoid ordering or interfering with...
Definition Loads.cpp:432
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1745
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:279
static IntegerType * getWiderInductionTy(const DataLayout &DL, Type *Ty0, Type *Ty1)
static IntegerType * getInductionIntegerTy(const DataLayout &DL, Type *Ty)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI bool hasDisableAllTransformsHint(const Loop *L)
Look for the loop attribute that disables all transformation heuristic.
static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst, SmallPtrSetImpl< Value * > &AllowedExit)
Check that the instruction has outside loop users and is not an identified reduction variable.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI void reportVectorizationFailure(const StringRef DebugMsg, const StringRef OREMsg, const StringRef ORETag, OptimizationRemarkEmitter *ORE, const Loop *TheLoop, Instruction *I=nullptr)
Reports a vectorization failure: print DebugMsg for debugging purposes along with the corresponding o...
static bool storeToSameAddress(ScalarEvolution *SE, StoreInst *A, StoreInst *B)
Returns true if A and B have same pointer operands or same SCEVs addresses.
bool canVectorizeTy(Type *Ty)
Returns true if Ty is a valid vector element type, void, or an unpacked literal struct where all elem...
TargetTransformInfo TTI
LLVM_ABI bool isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID, unsigned ScalarOpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic has a scalar operand.
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isReadOnlyLoop(Loop *L, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, SmallVectorImpl< LoadInst * > &NonDereferenceableAndAlignedLoads, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Returns true if the loop contains read-only memory accesses and doesn't throw.
Definition Loads.cpp:892
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2191
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1946
auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:305
static bool findHistogram(LoadInst *LI, StoreInst *HSt, Loop *TheLoop, const PredicatedScalarEvolution &PSE, SmallVectorImpl< HistogramInfo > &Histograms)
Find histogram operations that match high-level code in loops:
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
static bool isTLIScalarize(const TargetLibraryInfo &TLI, const CallInst &CI)
Checks if a function is scalarizable according to the TLI, in the sense that it should be vectorized ...
LLVM_ABI bool isDereferenceableAndAlignedInLoop(LoadInst *LI, Loop *L, ScalarEvolution &SE, DominatorTree &DT, AssumptionCache *AC=nullptr, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Return true if we can prove that the given load (which is assumed to be within the specified loop) wo...
Definition Loads.cpp:290
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
LLVM_ABI std::optional< int64_t > getPtrStride(PredicatedScalarEvolution &PSE, Type *AccessTy, Value *Ptr, const Loop *Lp, const DominatorTree &DT, const DenseMap< Value *, const SCEV * > &StridesMap=DenseMap< Value *, const SCEV * >(), bool Assume=false, bool ShouldCheckWrap=true)
If the pointer has a constant stride return it in units of the access type size.
SCEVUseT< const SCEV * > SCEVUse
bool SCEVExprContains(const SCEV *Root, PredTy Pred)
Return true if any node in Root satisfies the predicate Pred.
Dependece between memory access instructions.
Instruction * getDestination(const MemoryDepChecker &DepChecker) const
Return the destination instruction of the dependence.
Instruction * getSource(const MemoryDepChecker &DepChecker) const
Return the source instruction of the dependence.
static LLVM_ABI VectorizationSafetyStatus isSafeForVectorization(DepType Type)
Dependence types that don't prevent vectorization.
TODO: The following VectorizationFactor was pulled out of LoopVectorizationCostModel class.
Collection of parameters shared beetween the Loop Vectorizer and the Loop Access Analysis.
static LLVM_ABI const unsigned MaxVectorWidth
Maximum SIMD width.
static LLVM_ABI bool isInterleaveForced()
True if force-vector-interleave was specified by the user.
static LLVM_ABI unsigned VectorizationInterleave
Interleave factor as overridden by the user.