LLVM 24.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
20#include "llvm/Analysis/Loads.h"
29#include "llvm/IR/Dominators.h"
34
35using namespace llvm;
36using namespace PatternMatch;
37using namespace LoopVectorizationUtils;
38
39#define LV_NAME "loop-vectorize"
40#define DEBUG_TYPE LV_NAME
41
42static cl::opt<bool>
43 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
44 cl::desc("Enable if-conversion during vectorization."));
45
46static cl::opt<bool>
47AllowStridedPointerIVs("lv-strided-pointer-ivs", cl::init(false), cl::Hidden,
48 cl::desc("Enable recognition of non-constant strided "
49 "pointer induction variables."));
50
51static cl::opt<bool>
52 HintsAllowReordering("hints-allow-reordering", cl::init(true), cl::Hidden,
53 cl::desc("Allow enabling loop hints to reorder "
54 "FP operations during vectorization."));
55
58 "scalable-vectorization", cl::init(LoopVectorizeHints::SK_Unspecified),
60 cl::desc("Control whether the compiler can use scalable vectors to "
61 "vectorize a loop"),
64 "Scalable vectorization is disabled."),
67 "Scalable vectorization is available and favored when the "
68 "cost is inconclusive."),
71 "Scalable vectorization is available and favored when the "
72 "cost is inconclusive."),
75 "Scalable vectorization is available and always favored when "
76 "feasible")));
77
79 "enable-histogram-loop-vectorization", cl::init(false), cl::Hidden,
80 cl::desc("Enables autovectorization of some loops containing histograms"));
81
82/// Maximum vectorization interleave count.
83static const unsigned MaxInterleaveFactor = 16;
84
85namespace llvm {
86
87bool LoopVectorizeHints::Hint::validate(unsigned Val) {
88 switch (Kind) {
89 case HK_WIDTH:
91 case HK_INTERLEAVE:
92 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
93 case HK_FORCE:
94 return (Val <= 1);
95 case HK_ISVECTORIZED:
96 case HK_PREDICATE:
97 case HK_SCALABLE:
98 return (Val == 0 || Val == 1);
99 }
100 return false;
101}
102
104 bool InterleaveOnlyWhenForced,
107 : Width("vectorize.width",
108 VectorizerParams::VectorizationFactor.getKnownMinValue(), HK_WIDTH),
109 Interleave("interleave.count", InterleaveOnlyWhenForced, HK_INTERLEAVE),
110 Force("vectorize.enable", FK_Undefined, HK_FORCE),
111 IsVectorized("isvectorized", 0, HK_ISVECTORIZED),
112 Predicate("vectorize.predicate.enable", FK_Undefined, HK_PREDICATE),
113 Scalable("vectorize.scalable.enable", SK_Unspecified, HK_SCALABLE),
114 TheLoop(L), ORE(ORE) {
115 // Populate values with existing loop metadata.
116 getHintsFromMetadata();
117
118 // force-vector-interleave overrides DisableInterleaving.
121
122 // If the metadata doesn't explicitly specify whether to enable scalable
123 // vectorization, then decide based on the following criteria (increasing
124 // level of priority):
125 // - Target default
126 // - Metadata width
127 // - Force option (always overrides)
129 if (TTI)
130 Scalable.Value = TTI->enableScalableVectorization() ? SK_PreferScalable
132
133 if (Width.Value)
134 // If the width is set, but the metadata says nothing about the scalable
135 // property, then assume it concerns only a fixed-width UserVF.
136 // If width is not set, the flag takes precedence.
137 Scalable.Value = SK_FixedWidthOnly;
138 }
139
140 // If the flag is set to force any use of scalable vectors, override the loop
141 // hints.
142 if (ForceScalableVectorization.getValue() !=
144 Scalable.Value = ForceScalableVectorization.getValue();
145
146 // If force-vector-width is scalable, force scalable vectorization.
148 Scalable.Value = SK_AlwaysScalable;
149
150 // Scalable vectorization is disabled if no preference is specified.
152 Scalable.Value = SK_FixedWidthOnly;
153
154 if (IsVectorized.Value != 1)
155 // If the vectorization width and interleaving count are both 1 then
156 // consider the loop to have been already vectorized because there's
157 // nothing more that we can do.
158 IsVectorized.Value =
160 LLVM_DEBUG(if (InterleaveOnlyWhenForced && getInterleave() == 1) dbgs()
161 << "LV: Interleaving disabled by the pass manager\n");
162}
163
165 TheLoop->addIntLoopAttribute("llvm.loop.isvectorized", 1,
166 {Twine(Prefix(), "vectorize.").str(),
167 Twine(Prefix(), "interleave.").str()});
168
169 // Update internal cache.
170 IsVectorized.Value = 1;
171}
172
173void LoopVectorizeHints::reportDisallowedVectorization(
174 const StringRef DebugMsg, const StringRef RemarkName,
175 const StringRef RemarkMsg, const Loop *L) const {
176 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: " << DebugMsg << ".\n");
177 ORE.emit(OptimizationRemarkMissed(LV_NAME, RemarkName, L->getStartLoc(),
178 L->getHeader())
179 << "loop not vectorized: " << RemarkMsg);
180}
181
183 Function *F, Loop *L, bool VectorizeOnlyWhenForced) const {
185 if (Force.Value == LoopVectorizeHints::FK_Disabled) {
186 reportDisallowedVectorization("#pragma vectorize disable",
187 "MissedExplicitlyDisabled",
188 "vectorization is explicitly disabled", L);
189 } else if (hasDisableAllTransformsHint(L)) {
190 reportDisallowedVectorization("loop hasDisableAllTransformsHint",
191 "MissedTransformsDisabled",
192 "loop transformations are disabled", L);
193 } else {
194 llvm_unreachable("loop vect disabled for an unknown reason");
195 }
196 return false;
197 }
198
199 if (VectorizeOnlyWhenForced && getForce() != LoopVectorizeHints::FK_Enabled) {
200 reportDisallowedVectorization(
201 "VectorizeOnlyWhenForced is set, and no #pragma vectorize enable",
202 "MissedForceOnly", "only vectorizing loops that explicitly request it",
203 L);
204 return false;
205 }
206
207 if (getIsVectorized() == 1) {
208 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
209 // FIXME: Add interleave.disable metadata. This will allow
210 // vectorize.disable to be used without disabling the pass and errors
211 // to differentiate between disabled vectorization and a width of 1.
212 ORE.emit([&]() {
213 return OptimizationRemarkAnalysis(LV_NAME, "AllDisabled",
214 L->getStartLoc(), L->getHeader())
215 << "loop not vectorized: vectorization and interleaving are "
216 "explicitly disabled, or the loop has already been "
217 "vectorized";
218 });
219 return false;
220 }
221
222 return true;
223}
224
226 using namespace ore;
227
228 ORE.emit([&]() {
229 if (Force.Value == LoopVectorizeHints::FK_Disabled)
230 return OptimizationRemarkMissed(LV_NAME, "MissedExplicitlyDisabled",
231 TheLoop->getStartLoc(),
232 TheLoop->getHeader())
233 << "loop not vectorized: vectorization is explicitly disabled";
234
235 OptimizationRemarkMissed R(LV_NAME, "MissedDetails", TheLoop->getStartLoc(),
236 TheLoop->getHeader());
237 R << "loop not vectorized";
238 if (Force.Value == LoopVectorizeHints::FK_Enabled) {
239 R << " (Force=" << NV("Force", true);
240 if (Width.Value != 0)
241 R << ", Vector Width=" << NV("VectorWidth", getWidth());
242 if (getInterleave() != 0)
243 R << ", Interleave Count=" << NV("InterleaveCount", getInterleave());
244 R << ")";
245 }
246 return R;
247 });
248}
249
251 // Allow the vectorizer to change the order of operations if enabling
252 // loop hints are provided
253 ElementCount EC = getWidth();
254 return HintsAllowReordering &&
256 EC.getKnownMinValue() > 1);
257}
258
259void LoopVectorizeHints::getHintsFromMetadata() {
260 MDNode *LoopID = TheLoop->getLoopID();
261 if (!LoopID)
262 return;
263
264 // First operand should refer to the loop id itself.
265 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
266 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
267
268 for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
269 const MDString *S = nullptr;
271
272 // The expected hint is either a MDString or a MDNode with the first
273 // operand a MDString.
274 if (const MDNode *MD = dyn_cast<MDNode>(MDO)) {
275 if (!MD || MD->getNumOperands() == 0)
276 continue;
277 S = dyn_cast<MDString>(MD->getOperand(0));
278 for (unsigned Idx = 1; Idx < MD->getNumOperands(); ++Idx)
279 Args.push_back(MD->getOperand(Idx));
280 } else {
281 S = dyn_cast<MDString>(MDO);
282 assert(Args.size() == 0 && "too many arguments for MDString");
283 }
284
285 if (!S)
286 continue;
287
288 // Check if the hint starts with the loop metadata prefix.
289 StringRef Name = S->getString();
290 // The single-operand enable/disable pair carries no argument.
291 if (Args.empty()) {
292 if (Name == "llvm.loop.vectorize.enable")
293 Force.Value = FK_Enabled;
294 else if (Name == "llvm.loop.vectorize.disable")
295 Force.Value = FK_Disabled;
296 continue;
297 }
298 if (Args.size() == 1)
299 setHint(Name, Args[0]);
300 }
301}
302
303void LoopVectorizeHints::setHint(StringRef Name, Metadata *Arg) {
304 if (!Name.consume_front(Prefix()))
305 return;
306
307 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
308 if (!C)
309 return;
310 unsigned Val = C->getZExtValue();
311
312 Hint *Hints[] = {&Width, &Interleave, &Force,
313 &IsVectorized, &Predicate, &Scalable};
314 for (auto *H : Hints) {
315 if (Name == H->Name) {
316 if (H->validate(Val))
317 H->Value = Val;
318 else
319 LLVM_DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
320 break;
321 }
322 }
323}
324
325// Return true if the inner loop \p Lp is uniform with regard to the outer loop
326// \p OuterLp (i.e., if the outer loop is vectorized, all the vector lanes
327// executing the inner loop will execute the same iterations). This check is
328// very constrained for now but it will be relaxed in the future. \p Lp is
329// considered uniform if it meets all the following conditions:
330// 1) it has a canonical IV (starting from 0 and with stride 1),
331// 2) its latch terminator is a conditional branch and,
332// 3) its latch condition is a compare instruction whose operands are the
333// canonical IV and an OuterLp invariant.
334// This check doesn't take into account the uniformity of other conditions not
335// related to the loop latch because they don't affect the loop uniformity.
336//
337// NOTE: We decided to keep all these checks and its associated documentation
338// together so that we can easily have a picture of the current supported loop
339// nests. However, some of the current checks don't depend on \p OuterLp and
340// would be redundantly executed for each \p Lp if we invoked this function for
341// different candidate outer loops. This is not the case for now because we
342// don't currently have the infrastructure to evaluate multiple candidate outer
343// loops and \p OuterLp will be a fixed parameter while we only support explicit
344// outer loop vectorization. It's also very likely that these checks go away
345// before introducing the aforementioned infrastructure. However, if this is not
346// the case, we should move the \p OuterLp independent checks to a separate
347// function that is only executed once for each \p Lp.
348static bool isUniformLoop(Loop *Lp, Loop *OuterLp) {
349 assert(Lp->getLoopLatch() && "Expected loop with a single latch.");
350
351 // If Lp is the outer loop, it's uniform by definition.
352 if (Lp == OuterLp)
353 return true;
354 assert(OuterLp->contains(Lp) && "OuterLp must contain Lp.");
355
356 // 1.
358 if (!IV) {
359 LLVM_DEBUG(dbgs() << "LV: Canonical IV not found.\n");
360 return false;
361 }
362
363 // 2.
364 BasicBlock *Latch = Lp->getLoopLatch();
365 auto *LatchBr = dyn_cast<CondBrInst>(Latch->getTerminator());
366 if (!LatchBr) {
367 LLVM_DEBUG(dbgs() << "LV: Unsupported loop latch branch.\n");
368 return false;
369 }
370
371 // 3.
372 auto *LatchCmp = dyn_cast<CmpInst>(LatchBr->getCondition());
373 if (!LatchCmp) {
375 dbgs() << "LV: Loop latch condition is not a compare instruction.\n");
376 return false;
377 }
378
379 Value *CondOp0 = LatchCmp->getOperand(0);
380 Value *CondOp1 = LatchCmp->getOperand(1);
381 Value *IVUpdate = IV->getIncomingValueForBlock(Latch);
382 if (!(CondOp0 == IVUpdate && OuterLp->isLoopInvariant(CondOp1)) &&
383 !(CondOp1 == IVUpdate && OuterLp->isLoopInvariant(CondOp0))) {
384 LLVM_DEBUG(dbgs() << "LV: Loop latch condition is not uniform.\n");
385 return false;
386 }
387
388 return true;
389}
390
391// Return true if \p Lp and all its nested loops are uniform with regard to \p
392// OuterLp.
393static bool isUniformLoopNest(Loop *Lp, Loop *OuterLp) {
394 if (!isUniformLoop(Lp, OuterLp))
395 return false;
396
397 // Check if nested loops are uniform.
398 for (Loop *SubLp : *Lp)
399 if (!isUniformLoopNest(SubLp, OuterLp))
400 return false;
401
402 return true;
403}
404
406 assert(Ty->isIntOrPtrTy() && "Expected integer or pointer type");
407
408 if (Ty->isPointerTy())
409 return DL.getIntPtrType(Ty->getContext(), Ty->getPointerAddressSpace());
410
411 // It is possible that char's or short's overflow when we ask for the loop's
412 // trip count, work around this by changing the type size.
413 if (Ty->getScalarSizeInBits() < 32)
414 return Type::getInt32Ty(Ty->getContext());
415
416 return cast<IntegerType>(Ty);
417}
418
420 Type *Ty1) {
423 return TyA->getScalarSizeInBits() > TyB->getScalarSizeInBits() ? TyA : TyB;
424}
425
426/// Returns true if A and B have same pointer operands or same SCEVs addresses
428 StoreInst *B) {
429 // Compare store
430 if (A == B)
431 return true;
432
433 // Otherwise Compare pointers
434 Value *APtr = A->getPointerOperand();
435 Value *BPtr = B->getPointerOperand();
436 if (APtr == BPtr)
437 return true;
438
439 // Otherwise compare address SCEVs
440 return SE->getSCEV(APtr) == SE->getSCEV(BPtr);
441}
442
444 if (!AllowRuntimeSCEVChecks || !TheLoop->isInnermost())
445 return;
446
447 for (BasicBlock *BB : TheLoop->blocks())
448 for (Instruction &I : *BB)
451}
452
454 Value *Ptr) const {
455 // FIXME: Currently, the set of symbolic strides is sometimes queried before
456 // it's collected. This happens from canVectorizeWithIfConvert, when the
457 // pointer is checked to reference consecutive elements suitable for a
458 // masked access.
459 // Stride versioning requires adding a SCEV equality predicate; only consult
460 // the symbolic strides when runtime SCEV checks are permitted.
461 const auto &Strides = LAI && AllowRuntimeSCEVChecks
462 ? LAI->getSymbolicStrides()
464 int Stride = getPtrStride(PSE, AccessTy, Ptr, TheLoop, *DT, Strides,
465 AllowRuntimeSCEVChecks, false)
466 .value_or(0);
467 if (Stride == 1 || Stride == -1)
468 return Stride;
469 return 0;
470}
471
473 return LAI->isInvariant(V);
474}
475
476namespace {
477/// A rewriter to build the SCEVs for each of the VF lanes in the expected
478/// vectorized loop, which can then be compared to detect their uniformity. This
479/// is done by replacing the AddRec SCEVs of the original scalar loop (TheLoop)
480/// with new AddRecs where the step is multiplied by StepMultiplier and Offset *
481/// Step is added. Also checks if all sub-expressions are analyzable w.r.t.
482/// uniformity.
483class SCEVAddRecForUniformityRewriter
484 : public SCEVRewriteVisitor<SCEVAddRecForUniformityRewriter> {
485 /// Multiplier to be applied to the step of AddRecs in TheLoop.
486 unsigned StepMultiplier;
487
488 /// Offset to be added to the AddRecs in TheLoop.
489 unsigned Offset;
490
491 /// Loop for which to rewrite AddRecsFor.
492 Loop *TheLoop;
493
494 /// Is any sub-expressions not analyzable w.r.t. uniformity?
495 bool CannotAnalyze = false;
496
497 bool canAnalyze() const { return !CannotAnalyze; }
498
499public:
500 SCEVAddRecForUniformityRewriter(ScalarEvolution &SE, unsigned StepMultiplier,
501 unsigned Offset, Loop *TheLoop)
502 : SCEVRewriteVisitor(SE), StepMultiplier(StepMultiplier), Offset(Offset),
503 TheLoop(TheLoop) {}
504
505 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
506 assert(Expr->getLoop() == TheLoop &&
507 "addrec outside of TheLoop must be invariant and should have been "
508 "handled earlier");
509 // Build a new AddRec by multiplying the step by StepMultiplier and
510 // incrementing the start by Offset * step.
511 Type *Ty = Expr->getType();
512 const SCEV *Step = Expr->getStepRecurrence(SE);
513 if (!SE.isLoopInvariant(Step, TheLoop)) {
514 CannotAnalyze = true;
515 return Expr;
516 }
517 const SCEV *NewStep =
518 SE.getMulExpr(Step, SE.getConstant(Ty, StepMultiplier));
519 const SCEV *ScaledOffset = SE.getMulExpr(Step, SE.getConstant(Ty, Offset));
520 const SCEV *NewStart =
521 SE.getAddExpr(Expr->getStart(), SCEVUse(ScaledOffset));
522 return SE.getAddRecExpr(NewStart, NewStep, TheLoop, SCEV::FlagAnyWrap);
523 }
524
525 const SCEV *visit(const SCEV *S) {
526 if (CannotAnalyze || SE.isLoopInvariant(S, TheLoop))
527 return S;
529 }
530
531 const SCEV *visitUnknown(const SCEVUnknown *S) {
532 if (SE.isLoopInvariant(S, TheLoop))
533 return S;
534 // The value could vary across iterations.
535 CannotAnalyze = true;
536 return S;
537 }
538
539 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *S) {
540 // Could not analyze the expression.
541 CannotAnalyze = true;
542 return S;
543 }
544
545 static const SCEV *rewrite(const SCEV *S, ScalarEvolution &SE,
546 unsigned StepMultiplier, unsigned Offset,
547 Loop *TheLoop) {
548 /// Bail out if the expression does not contain an UDiv expression.
549 /// Uniform values which are not loop invariant require operations to strip
550 /// out the lowest bits. For now just look for UDivs and use it to avoid
551 /// re-writing UDIV-free expressions for other lanes to limit compile time.
552 if (!SCEVExprContains(S,
553 [](const SCEV *S) { return isa<SCEVUDivExpr>(S); }))
554 return SE.getCouldNotCompute();
555
556 SCEVAddRecForUniformityRewriter Rewriter(SE, StepMultiplier, Offset,
557 TheLoop);
558 const SCEV *Result = Rewriter.visit(S);
559
560 if (Rewriter.canAnalyze())
561 return Result;
562 return SE.getCouldNotCompute();
563 }
564};
565
566} // namespace
567
569 Value *V, std::optional<ElementCount> VF) const {
570 if (isInvariant(V))
571 return true;
572 if (!VF || VF->isScalable())
573 return false;
574 if (VF->isScalar())
575 return true;
576
577 // Since we rely on SCEV for uniformity, if the type is not SCEVable, it is
578 // never considered uniform.
579 auto *SE = PSE.getSE();
580 if (!SE->isSCEVable(V->getType()))
581 return false;
582 const SCEV *S = SE->getSCEV(V);
583
584 // Rewrite AddRecs in TheLoop to step by VF and check if the expression for
585 // lane 0 matches the expressions for all other lanes.
586 unsigned FixedVF = VF->getKnownMinValue();
587 const SCEV *FirstLaneExpr =
588 SCEVAddRecForUniformityRewriter::rewrite(S, *SE, FixedVF, 0, TheLoop);
589 if (isa<SCEVCouldNotCompute>(FirstLaneExpr))
590 return false;
591
592 // Make sure the expressions for lanes FixedVF-1..1 match the expression for
593 // lane 0. We check lanes in reverse order for compile-time, as frequently
594 // checking the last lane is sufficient to rule out uniformity.
595 return all_of(reverse(seq<unsigned>(1, FixedVF)), [&](unsigned I) {
596 const SCEV *IthLaneExpr =
597 SCEVAddRecForUniformityRewriter::rewrite(S, *SE, FixedVF, I, TheLoop);
598 return FirstLaneExpr == IthLaneExpr;
599 });
600}
601
603 Instruction &I, std::optional<ElementCount> VF) const {
605 if (!Ptr)
606 return false;
607 // Note: There's nothing inherent which prevents predicated loads and
608 // stores from being uniform. The current lowering simply doesn't handle
609 // it; in particular, the cost model distinguishes scatter/gather from
610 // scalar w/predication, and we currently rely on the scalar path.
611 return isUniform(Ptr, VF) && !blockNeedsPredication(I.getParent());
612}
613
614bool LoopVectorizationLegality::canVectorizeOuterLoop() {
615 assert(!TheLoop->isInnermost() && "We are not vectorizing an outer loop.");
616 // Store the result and return it at the end instead of exiting early, in case
617 // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
618 bool Result = true;
619 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
620
621 for (BasicBlock *BB : TheLoop->blocks()) {
622 // Check whether the BB terminator is a branch. Any other terminator is
623 // not supported yet.
624 Instruction *Term = BB->getTerminator();
627 "Unsupported basic block terminator",
628 "loop control flow is not understood by vectorizer",
629 "CFGNotUnderstood", ORE, TheLoop);
630 if (DoExtraAnalysis)
631 Result = false;
632 else
633 return false;
634 }
635
636 // Check whether the branch is a supported one. Only unconditional
637 // branches, conditional branches with an outer loop invariant condition or
638 // backedges are supported.
639 // FIXME: We skip these checks when VPlan predication is enabled as we
640 // want to allow divergent branches. This whole check will be removed
641 // once VPlan predication is on by default.
642 auto *Br = dyn_cast<CondBrInst>(Term);
643 if (Br && !TheLoop->isLoopInvariant(Br->getCondition()) &&
644 !LI->isLoopHeader(Br->getSuccessor(0)) &&
645 !LI->isLoopHeader(Br->getSuccessor(1))) {
647 "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*/)) {
662 "Outer loop contains divergent loops",
663 "loop control flow is not understood by vectorizer", "CFGNotUnderstood",
664 ORE, TheLoop);
665 if (DoExtraAnalysis)
666 Result = false;
667 else
668 return false;
669 }
670
671 // Check whether we are able to set up outer loop induction.
672 if (!setupOuterLoopInductions()) {
673 reportVectorizationFailure("Unsupported outer loop Phi(s)",
674 "UnsupportedPhi", ORE, TheLoop);
675 if (DoExtraAnalysis)
676 Result = false;
677 else
678 return false;
679 }
680
681 return Result;
682}
683
684void LoopVectorizationLegality::addInductionPhi(PHINode *Phi,
685 const InductionDescriptor &ID) {
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 LLVM_DEBUG(dbgs() << "LV: Found an induction variable.\n");
725}
726
727bool LoopVectorizationLegality::setupOuterLoopInductions() {
728 BasicBlock *Header = TheLoop->getHeader();
729
730 // Returns true if a given Phi is a supported induction.
731 auto IsSupportedPhi = [&](PHINode &Phi) -> bool {
732 InductionDescriptor ID;
733 if (InductionDescriptor::isInductionPHI(&Phi, TheLoop, PSE, ID) &&
735 addInductionPhi(&Phi, ID);
736 return true;
737 }
738 // Bail out for any Phi in the outer loop header that is not a supported
739 // induction.
741 dbgs() << "LV: Found unsupported PHI for outer loop vectorization.\n");
742 return false;
743 };
744
745 return llvm::all_of(Header->phis(), IsSupportedPhi);
746}
747
748/// Checks if a function is scalarizable according to the TLI, in
749/// the sense that it should be vectorized and then expanded in
750/// multiple scalar calls. This is represented in the
751/// TLI via mappings that do not specify a vector name, as in the
752/// following example:
753///
754/// const VecDesc VecIntrinsics[] = {
755/// {"llvm.phx.abs.i32", "", 4}
756/// };
757static bool isTLIScalarize(const TargetLibraryInfo &TLI, const CallInst &CI) {
758 const StringRef ScalarName = CI.getCalledFunction()->getName();
759 bool Scalarize = TLI.isFunctionVectorizable(ScalarName);
760 // Check that all known VFs are not associated to a vector
761 // function, i.e. the vector name is emty.
762 if (Scalarize) {
763 ElementCount WidestFixedVF, WidestScalableVF;
764 TLI.getWidestVF(ScalarName, WidestFixedVF, WidestScalableVF);
766 ElementCount::isKnownLE(VF, WidestFixedVF); VF *= 2)
767 Scalarize &= !TLI.isFunctionVectorizable(ScalarName, VF);
769 ElementCount::isKnownLE(VF, WidestScalableVF); VF *= 2)
770 Scalarize &= !TLI.isFunctionVectorizable(ScalarName, VF);
771 assert((WidestScalableVF.isZero() || !Scalarize) &&
772 "Caller may decide to scalarize a variant using a scalable VF");
773 }
774 return Scalarize;
775}
776
777bool LoopVectorizationLegality::canVectorizeInstrs() {
778 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
779 bool Result = true;
780
781 // For each block in the loop.
782 for (BasicBlock *BB : TheLoop->blocks()) {
783 // Scan the instructions in the block and look for hazards.
784 for (Instruction &I : *BB) {
785 Result &= canVectorizeInstr(I);
786 if (!DoExtraAnalysis && !Result)
787 return false;
788 }
789 }
790
791 if (!PrimaryInduction) {
792 if (Inductions.empty()) {
794 "Did not find one integer induction var",
795 "loop induction variable could not be identified",
796 "NoInductionVariable", ORE, TheLoop);
797 return false;
798 }
799 if (!WidestIndTy) {
801 "Did not find one integer induction var",
802 "integer loop induction variable could not be identified",
803 "NoIntegerInductionVariable", ORE, TheLoop);
804 return false;
805 }
806 LLVM_DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
807 }
808
809 // Now we know the widest induction type, check if our found induction
810 // is the same size. If it's not, unset it here and InnerLoopVectorizer
811 // will create another.
812 if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType())
813 PrimaryInduction = nullptr;
814
815 return Result;
816}
817
818bool LoopVectorizationLegality::canVectorizeInstr(Instruction &I) {
819 BasicBlock *BB = I.getParent();
820 BasicBlock *Header = TheLoop->getHeader();
821
822 if (auto *Phi = dyn_cast<PHINode>(&I)) {
823 Type *PhiTy = Phi->getType();
824 // Check that this PHI type is allowed.
825 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
826 !PhiTy->isPointerTy()) {
828 "Found a non-int non-pointer PHI",
829 "loop control flow is not understood by vectorizer",
830 "CFGNotUnderstood", ORE, TheLoop);
831 return false;
832 }
833
834 // If this PHINode is not in the header block, then we know that we
835 // can convert it to select during if-conversion. No need to check if
836 // the PHIs in this block are induction or reduction variables.
837 if (BB != Header) {
838 // Non-header phi nodes that have outside uses can be vectorized. Unsafe
839 // cyclic dependencies with header phis are identified during legalization
840 // for reduction, induction and fixed order recurrences.
841 return true;
842 }
843
844 // We only allow if-converted PHIs with exactly two incoming values.
845 if (Phi->getNumIncomingValues() != 2) {
847 "Found an invalid PHI",
848 "loop control flow is not understood by vectorizer",
849 "CFGNotUnderstood", ORE, TheLoop, Phi);
850 return false;
851 }
852
853 RecurrenceDescriptor RedDes;
854 if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes, DB, AC, DT,
855 PSE.getSE())) {
856 Requirements->addExactFPMathInst(RedDes.getExactFPMathInst());
857 Reductions[Phi] = std::move(RedDes);
860 RedDes.getRecurrenceKind())) &&
861 "Only min/max recurrences are allowed to have multiple uses "
862 "currently");
863 return true;
864 }
865
866 // We prevent matching non-constant strided pointer IVS to preserve
867 // historical vectorizer behavior after a generalization of the
868 // IVDescriptor code. The intent is to remove this check, but we
869 // have to fix issues around code quality for such loops first.
870 auto IsDisallowedStridedPointerInduction =
871 [](const InductionDescriptor &ID) {
873 return false;
874 return ID.getKind() == InductionDescriptor::IK_PtrInduction &&
875 ID.getConstIntStepValue() == nullptr;
876 };
877
878 InductionDescriptor ID;
879 if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID) &&
880 !IsDisallowedStridedPointerInduction(ID)) {
881 addInductionPhi(Phi, ID);
882 Requirements->addExactFPMathInst(ID.getExactFPMathInst());
883 return true;
884 }
885
886 if (RecurrenceDescriptor::isFixedOrderRecurrence(Phi, TheLoop, DT)) {
887 FixedOrderRecurrences.insert(Phi);
888 return true;
889 }
890
891 // As a last resort, coerce the PHI to a AddRec expression
892 // and re-try classifying it a an induction PHI.
893 if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true) &&
894 !IsDisallowedStridedPointerInduction(ID)) {
895 addInductionPhi(Phi, ID);
896 return true;
897 }
898
899 reportVectorizationFailure("Found an unidentified PHI",
900 "value that could not be identified as "
901 "reduction is used outside the loop",
902 "NonReductionValueUsedOutsideLoop", ORE, TheLoop,
903 Phi);
904 return false;
905 } // end of PHI handling
906
907 // We handle calls that:
908 // * Have a mapping to an IR intrinsic.
909 // * Have a vector version available.
910 auto *CI = dyn_cast<CallInst>(&I);
911
912 if (CI && !getVectorIntrinsicIDForCall(CI, TLI) &&
913 !(CI->getCalledFunction() && TLI &&
914 (!VFDatabase::getMappings(*CI).empty() || isTLIScalarize(*TLI, *CI)))) {
915 // If the call is a recognized math libary call, it is likely that
916 // we can vectorize it given loosened floating-point constraints.
917 LibFunc Func;
918 bool IsMathLibCall =
919 TLI && CI->getCalledFunction() && CI->getType()->isFloatingPointTy() &&
920 TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
921 TLI->hasOptimizedCodeGen(Func);
922
923 if (IsMathLibCall) {
924 // TODO: Ideally, we should not use clang-specific language here,
925 // but it's hard to provide meaningful yet generic advice.
926 // Also, should this be guarded by allowExtraAnalysis() and/or be part
927 // of the returned info from isFunctionVectorizable()?
929 "Found a non-intrinsic callsite",
930 "library call cannot be vectorized. "
931 "Try compiling with -fno-math-errno, -ffast-math, "
932 "or similar flags",
933 "CantVectorizeLibcall", ORE, TheLoop, CI);
934 } else {
935 reportVectorizationFailure("Found a non-intrinsic callsite",
936 "call instruction cannot be vectorized",
937 "CantVectorizeLibcall", ORE, TheLoop, CI);
938 }
939 return false;
940 }
941
942 // Some intrinsics have scalar arguments and should be same in order for
943 // them to be vectorized (i.e. loop invariant).
944 if (CI) {
945 auto *SE = PSE.getSE();
946 Intrinsic::ID IntrinID = getVectorIntrinsicIDForCall(CI, TLI);
947 for (unsigned Idx = 0; Idx < CI->arg_size(); ++Idx)
948 if (isVectorIntrinsicWithScalarOpAtArg(IntrinID, Idx, TTI)) {
949 if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(Idx)), TheLoop)) {
951 "Found unvectorizable intrinsic",
952 "intrinsic instruction cannot be vectorized",
953 "CantVectorizeIntrinsic", ORE, TheLoop, CI);
954 return false;
955 }
956 }
957 }
958
959 // If we found a vectorized variant of a function, note that so LV can
960 // make better decisions about maximum VF.
961 if (CI && !VFDatabase::getMappings(*CI).empty())
962 VecCallVariantsFound = true;
963
964 auto CanWidenInstructionTy = [](Instruction const &Inst) {
965 Type *InstTy = Inst.getType();
966 if (!isa<StructType>(InstTy))
967 return canVectorizeTy(InstTy);
968
969 // For now, we only recognize struct values returned from calls where
970 // all users are extractvalue as vectorizable. All element types of the
971 // struct must be types that can be widened.
972 return isa<CallInst>(Inst) && canVectorizeTy(InstTy) &&
973 all_of(Inst.users(), IsaPred<ExtractValueInst>);
974 };
975
976 // Check that the instruction return type is vectorizable.
977 // We can't vectorize casts from vector type to scalar type.
978 // Also, we can't vectorize extractelement instructions.
979 if (!CanWidenInstructionTy(I) ||
980 (isa<CastInst>(I) &&
981 !VectorType::isValidElementType(I.getOperand(0)->getType())) ||
983 reportVectorizationFailure("Found unvectorizable type",
984 "instruction return type cannot be vectorized",
985 "CantVectorizeInstructionReturnType", ORE,
986 TheLoop, &I);
987 return false;
988 }
989
990 // Check that the stored type is vectorizable.
991 if (auto *ST = dyn_cast<StoreInst>(&I)) {
992 Type *T = ST->getValueOperand()->getType();
994 reportVectorizationFailure("Store instruction cannot be vectorized",
995 "CantVectorizeStore", ORE, TheLoop, ST);
996 return false;
997 }
998
999 // For nontemporal stores, check that a nontemporal vector version is
1000 // supported on the target.
1001 if (ST->getMetadata(LLVMContext::MD_nontemporal)) {
1002 // Arbitrarily try a vector of 2 elements.
1003 auto *VecTy = FixedVectorType::get(T, /*NumElts=*/2);
1004 assert(VecTy && "did not find vectorized version of stored type");
1005 if (!TTI->isLegalNTStore(VecTy, ST->getAlign())) {
1007 "nontemporal store instruction cannot be vectorized",
1008 "CantVectorizeNontemporalStore", ORE, TheLoop, ST);
1009 return false;
1010 }
1011 }
1012
1013 } else if (auto *LD = dyn_cast<LoadInst>(&I)) {
1014 if (LD->getMetadata(LLVMContext::MD_nontemporal)) {
1015 // For nontemporal loads, check that a nontemporal vector version is
1016 // supported on the target (arbitrarily try a vector of 2 elements).
1017 auto *VecTy = FixedVectorType::get(I.getType(), /*NumElts=*/2);
1018 assert(VecTy && "did not find vectorized version of load type");
1019 if (!TTI->isLegalNTLoad(VecTy, LD->getAlign())) {
1021 "nontemporal load instruction cannot be vectorized",
1022 "CantVectorizeNontemporalLoad", ORE, TheLoop, LD);
1023 return false;
1024 }
1025 }
1026
1027 // FP instructions can allow unsafe algebra, thus vectorizable by
1028 // non-IEEE-754 compliant SIMD units.
1029 // This applies to floating-point math operations and calls, not memory
1030 // operations, shuffles, or casts, as they don't change precision or
1031 // semantics.
1032 } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) &&
1033 !I.isFast()) {
1034 LLVM_DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n");
1035 Hints->setPotentiallyUnsafe();
1036 }
1037
1038 return true;
1039}
1040
1041/// Find histogram operations that match high-level code in loops:
1042/// \code
1043/// buckets[indices[i]]+=step;
1044/// \endcode
1045///
1046/// It matches a pattern starting from \p HSt, which Stores to the 'buckets'
1047/// array the computed histogram. It uses a BinOp to sum all counts, storing
1048/// them using a loop-variant index Load from the 'indices' input array.
1049///
1050/// On successful matches it updates the STATISTIC 'HistogramsDetected',
1051/// regardless of hardware support. When there is support, it additionally
1052/// stores the BinOp/Load pairs in \p HistogramCounts, as well the pointers
1053/// used to update histogram in \p HistogramPtrs.
1054static bool findHistogram(LoadInst *LI, StoreInst *HSt, Loop *TheLoop,
1055 const PredicatedScalarEvolution &PSE,
1056 SmallVectorImpl<HistogramInfo> &Histograms) {
1057
1058 // Store value must come from a Binary Operation.
1059 Instruction *HPtrInstr = nullptr;
1060 BinaryOperator *HBinOp = nullptr;
1061 if (!match(HSt, m_Store(m_BinOp(HBinOp), m_Instruction(HPtrInstr))))
1062 return false;
1063
1064 // BinOp must be an Add or a Sub modifying the bucket value by a
1065 // loop invariant amount.
1066 // FIXME: We assume the loop invariant term is on the RHS.
1067 // Fine for an immediate/constant, but maybe not a generic value?
1068 Value *HIncVal = nullptr;
1069 if (!match(HBinOp, m_Add(m_Load(m_Specific(HPtrInstr)), m_Value(HIncVal))) &&
1070 !match(HBinOp, m_Sub(m_Load(m_Specific(HPtrInstr)), m_Value(HIncVal))))
1071 return false;
1072
1073 // Make sure the increment value is loop invariant.
1074 if (!TheLoop->isLoopInvariant(HIncVal))
1075 return false;
1076
1077 // The address to store is calculated through a GEP Instruction.
1079 if (!GEP)
1080 return false;
1081
1082 // Restrict address calculation to constant indices except for the last term.
1083 Value *HIdx = nullptr;
1084 for (Value *Index : GEP->indices()) {
1085 if (HIdx)
1086 return false;
1087 if (!isa<ConstantInt>(Index))
1088 HIdx = Index;
1089 }
1090
1091 if (!HIdx)
1092 return false;
1093
1094 // Check that the index is calculated by loading from another array. Ignore
1095 // any extensions.
1096 // FIXME: Support indices from other sources than a linear load from memory?
1097 // We're currently trying to match an operation looping over an array
1098 // of indices, but there could be additional levels of indirection
1099 // in place, or possibly some additional calculation to form the index
1100 // from the loaded data.
1101 Value *VPtrVal;
1102 if (!match(HIdx, m_ZExtOrSExtOrSelf(m_Load(m_Value(VPtrVal)))))
1103 return false;
1104
1105 // Make sure the index address varies in this loop, not an outer loop.
1106 const auto *AR = dyn_cast<SCEVAddRecExpr>(PSE.getSE()->getSCEV(VPtrVal));
1107 if (!AR || AR->getLoop() != TheLoop)
1108 return false;
1109
1110 // Ensure we'll have the same mask by checking that all parts of the histogram
1111 // (gather load, update, scatter store) are in the same block.
1112 LoadInst *IndexedLoad = cast<LoadInst>(HBinOp->getOperand(0));
1113 BasicBlock *LdBB = IndexedLoad->getParent();
1114 if (LdBB != HBinOp->getParent() || LdBB != HSt->getParent())
1115 return false;
1116
1117 LLVM_DEBUG(dbgs() << "LV: Found histogram for: " << *HSt << "\n");
1118
1119 // Store the operations that make up the histogram.
1120 Histograms.emplace_back(IndexedLoad, HBinOp, HSt);
1121 return true;
1122}
1123
1124bool LoopVectorizationLegality::canVectorizeIndirectUnsafeDependences() {
1125 // For now, we only support an IndirectUnsafe dependency that calculates
1126 // a histogram
1128 return false;
1129
1130 // Find a single IndirectUnsafe dependency.
1131 const MemoryDepChecker::Dependence *IUDep = nullptr;
1132 const MemoryDepChecker &DepChecker = LAI->getDepChecker();
1133 const auto *Deps = DepChecker.getDependences();
1134 // If there were too many dependences, LAA abandons recording them. We can't
1135 // proceed safely if we don't know what the dependences are.
1136 if (!Deps)
1137 return false;
1138
1139 for (const MemoryDepChecker::Dependence &Dep : *Deps) {
1140 // Ignore dependencies that are either known to be safe or can be
1141 // checked at runtime.
1144 continue;
1145
1146 // We're only interested in IndirectUnsafe dependencies here, where the
1147 // address might come from a load from memory. We also only want to handle
1148 // one such dependency, at least for now.
1149 if (Dep.Type != MemoryDepChecker::Dependence::IndirectUnsafe || IUDep)
1150 return false;
1151
1152 IUDep = &Dep;
1153 }
1154 if (!IUDep)
1155 return false;
1156
1157 // For now only normal loads and stores are supported.
1158 LoadInst *LI = dyn_cast<LoadInst>(IUDep->getSource(DepChecker));
1159 StoreInst *SI = dyn_cast<StoreInst>(IUDep->getDestination(DepChecker));
1160
1161 if (!LI || !SI)
1162 return false;
1163
1164 LLVM_DEBUG(dbgs() << "LV: Checking for a histogram on: " << *SI << "\n");
1165 return findHistogram(LI, SI, TheLoop, LAI->getPSE(), Histograms);
1166}
1167
1168bool LoopVectorizationLegality::canVectorizeMemory() {
1169 LAI = &LAIs.getInfo(*TheLoop);
1170 const OptimizationRemarkAnalysis *LAR = LAI->getReport();
1171 if (LAR) {
1172 ORE->emit([&]() {
1173 return OptimizationRemarkAnalysis(LV_NAME, "loop not vectorized: ", *LAR);
1174 });
1175 }
1176
1177 if (!LAI->canVectorizeMemory()) {
1180 "Cannot vectorize unsafe dependencies in uncountable exit loop with "
1181 "side effects",
1182 "CantVectorizeUnsafeDependencyForEELoopWithSideEffects", ORE,
1183 TheLoop);
1184 return false;
1185 }
1186
1187 return canVectorizeIndirectUnsafeDependences();
1188 }
1189
1190 if (LAI->hasLoadStoreDependenceInvolvingLoopInvariantAddress()) {
1191 reportVectorizationFailure("We don't allow storing to uniform addresses",
1192 "write to a loop invariant address could not "
1193 "be vectorized",
1194 "CantVectorizeStoreToLoopInvariantAddress", ORE,
1195 TheLoop);
1196 return false;
1197 }
1198
1199 // We can vectorize stores to invariant address when final reduction value is
1200 // guaranteed to be stored at the end of the loop. Also, if decision to
1201 // vectorize loop is made, runtime checks are added so as to make sure that
1202 // invariant address won't alias with any other objects.
1203 if (!LAI->getStoresToInvariantAddresses().empty()) {
1204 // For each invariant address, check if last stored value is unconditional
1205 // and the address is not calculated inside the loop.
1206 for (StoreInst *SI : LAI->getStoresToInvariantAddresses()) {
1208 continue;
1209
1210 if (blockNeedsPredication(SI->getParent())) {
1212 "We don't allow storing to uniform addresses",
1213 "write of conditional recurring variant value to a loop "
1214 "invariant address could not be vectorized",
1215 "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop);
1216 return false;
1217 }
1218
1219 // Invariant address should be defined outside of loop. LICM pass usually
1220 // makes sure it happens, but in rare cases it does not, we do not want
1221 // to overcomplicate vectorization to support this case.
1222 if (Instruction *Ptr = dyn_cast<Instruction>(SI->getPointerOperand())) {
1223 if (TheLoop->contains(Ptr)) {
1225 "Invariant address is calculated inside the loop",
1226 "write to a loop invariant address could not "
1227 "be vectorized",
1228 "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop);
1229 return false;
1230 }
1231 }
1232 }
1233
1234 if (LAI->hasStoreStoreDependenceInvolvingLoopInvariantAddress()) {
1235 // For each invariant address, check its last stored value is the result
1236 // of one of our reductions.
1237 //
1238 // We do not check if dependence with loads exists because that is already
1239 // checked via hasLoadStoreDependenceInvolvingLoopInvariantAddress.
1240 ScalarEvolution *SE = PSE.getSE();
1241 SmallVector<StoreInst *, 4> UnhandledStores;
1242 for (StoreInst *SI : LAI->getStoresToInvariantAddresses()) {
1244 // Earlier stores to this address are effectively deadcode.
1245 // With opaque pointers it is possible for one pointer to be used with
1246 // different sizes of stored values:
1247 // store i32 0, ptr %x
1248 // store i8 0, ptr %x
1249 // The latest store doesn't complitely overwrite the first one in the
1250 // example. That is why we have to make sure that types of stored
1251 // values are same.
1252 // TODO: Check that bitwidth of unhandled store is smaller then the
1253 // one that overwrites it and add a test.
1254 erase_if(UnhandledStores, [SE, SI](StoreInst *I) {
1255 return storeToSameAddress(SE, SI, I) &&
1256 I->getValueOperand()->getType() ==
1257 SI->getValueOperand()->getType();
1258 });
1259 continue;
1260 }
1261 UnhandledStores.push_back(SI);
1262 }
1263
1264 bool IsOK = UnhandledStores.empty();
1265 // TODO: we should also validate against InvariantMemSets.
1266 if (!IsOK) {
1268 "We don't allow storing to uniform addresses",
1269 "write to a loop invariant address could not "
1270 "be vectorized",
1271 "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop);
1272 return false;
1273 }
1274 }
1275 }
1276
1277 PSE.addPredicate(LAI->getPSE().getPredicate());
1278 return true;
1279}
1280
1282 bool EnableStrictReductions) {
1283
1284 // First check if there is any ExactFP math or if we allow reassociations
1285 if (!Requirements->getExactFPInst() || Hints->allowReordering())
1286 return true;
1287
1288 // If the above is false, we have ExactFPMath & do not allow reordering.
1289 // If the EnableStrictReductions flag is set, first check if we have any
1290 // Exact FP induction vars, which we cannot vectorize.
1291 if (!EnableStrictReductions ||
1292 any_of(getInductionVars(), [&](auto &Induction) -> bool {
1293 InductionDescriptor IndDesc = Induction.second;
1294 return IndDesc.getExactFPMathInst();
1295 }))
1296 return false;
1297
1298 // We can now only vectorize if all reductions with Exact FP math also
1299 // have the isOrdered flag set, which indicates that we can move the
1300 // reduction operations in-loop.
1301 return (all_of(getReductionVars(), [&](auto &Reduction) -> bool {
1302 const RecurrenceDescriptor &RdxDesc = Reduction.second;
1303 return !RdxDesc.hasExactFPMath() || RdxDesc.isOrdered();
1304 }));
1305}
1306
1308 return any_of(getReductionVars(), [&](auto &Reduction) -> bool {
1309 const RecurrenceDescriptor &RdxDesc = Reduction.second;
1310 return RdxDesc.IntermediateStore == SI;
1311 });
1312}
1313
1315 return any_of(getReductionVars(), [&](auto &Reduction) -> bool {
1316 const RecurrenceDescriptor &RdxDesc = Reduction.second;
1317 if (!RdxDesc.IntermediateStore)
1318 return false;
1319
1320 ScalarEvolution *SE = PSE.getSE();
1321 Value *InvariantAddress = RdxDesc.IntermediateStore->getPointerOperand();
1322 return V == InvariantAddress ||
1323 SE->getSCEV(V) == SE->getSCEV(InvariantAddress);
1324 });
1325}
1326
1328 Value *In0 = const_cast<Value *>(V);
1330 if (!PN)
1331 return false;
1332
1333 return Inductions.count(PN);
1334}
1335
1337 const Value *V) const {
1338 auto *Inst = dyn_cast<Instruction>(V);
1339 return (Inst && InductionCastsToIgnore.count(Inst));
1340}
1341
1345
1347 const PHINode *Phi) const {
1348 return FixedOrderRecurrences.count(Phi);
1349}
1350
1352 const BasicBlock *BB) const {
1353 BasicBlock *Latch = TheLoop->getLoopLatch();
1354
1355 // Without a latch, we cannot properly answer blockNeedsPredication,
1356 // return early.
1357 if (!Latch) {
1358 assert(ORE->allowExtraAnalysis(DEBUG_TYPE) &&
1359 !canVectorizeLoopCFG(TheLoop, /*UseVPlanNativePath=*/false) &&
1360 "Loop shape should have been rejected by earlier checks");
1361 return false;
1362 }
1363
1364 // When vectorizing early exits, create predicates for the latch block only.
1365 // For a single early exit, it must be a direct predecessor of the latch.
1366 // For multiple early exits, they form a chain where each exiting block
1367 // dominates all subsequent blocks up to the latch.
1369 return BB == Latch;
1370 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
1371}
1372
1373bool LoopVectorizationLegality::blockCanBePredicated(
1374 BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs,
1375 SmallPtrSetImpl<const Instruction *> &MaskedOp) const {
1376 for (Instruction &I : *BB) {
1377 // We can predicate blocks with calls to assume, as long as we drop them in
1378 // case we flatten the CFG via predication.
1380 MaskedOp.insert(&I);
1381 continue;
1382 }
1383
1384 // Do not let llvm.experimental.noalias.scope.decl block the vectorization.
1385 // TODO: there might be cases that it should block the vectorization. Let's
1386 // ignore those for now.
1388 continue;
1389
1390 // We can allow masked calls if there's at least one vector variant, even
1391 // if we end up scalarizing due to the cost model calculations.
1392 // TODO: Allow other calls if they have appropriate attributes... readonly
1393 // and argmemonly?
1394 if (CallInst *CI = dyn_cast<CallInst>(&I))
1396 MaskedOp.insert(CI);
1397 continue;
1398 }
1399
1400 // Loads are handled via masking (or speculated if safe to do so.)
1401 if (auto *LI = dyn_cast<LoadInst>(&I)) {
1402 if (!SafePtrs.count(LI->getPointerOperand()))
1403 MaskedOp.insert(LI);
1404 continue;
1405 }
1406
1407 // Predicated store requires some form of masking:
1408 // 1) masked store HW instruction,
1409 // 2) emulation via load-blend-store (only if safe and legal to do so,
1410 // be aware on the race conditions), or
1411 // 3) element-by-element predicate check and scalar store.
1412 if (auto *SI = dyn_cast<StoreInst>(&I)) {
1413 MaskedOp.insert(SI);
1414 continue;
1415 }
1416
1417 if (I.mayReadFromMemory() || I.mayWriteToMemory() || I.mayThrow())
1418 return false;
1419 }
1420
1421 return true;
1422}
1423
1424bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1425 if (!EnableIfConversion) {
1426 reportVectorizationFailure("If-conversion is disabled",
1427 "IfConversionDisabled", ORE, TheLoop);
1428 return false;
1429 }
1430
1431 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1432
1433 // A list of pointers which are known to be dereferenceable within scope of
1434 // the loop body for each iteration of the loop which executes. That is,
1435 // the memory pointed to can be dereferenced (with the access size implied by
1436 // the value's type) unconditionally within the loop header without
1437 // introducing a new fault.
1438 SmallPtrSet<Value *, 8> SafePointers;
1439
1440 // Collect safe addresses.
1441 for (BasicBlock *BB : TheLoop->blocks()) {
1442 if (!blockNeedsPredication(BB)) {
1443 for (Instruction &I : *BB)
1444 if (auto *Ptr = getLoadStorePointerOperand(&I))
1445 SafePointers.insert(Ptr);
1446 continue;
1447 }
1448
1449 // For a block which requires predication, a address may be safe to access
1450 // in the loop w/o predication if we can prove dereferenceability facts
1451 // sufficient to ensure it'll never fault within the loop. For the moment,
1452 // we restrict this to loads; stores are more complicated due to
1453 // concurrency restrictions.
1454 ScalarEvolution &SE = *PSE.getSE();
1456 for (Instruction &I : *BB) {
1457 LoadInst *LI = dyn_cast<LoadInst>(&I);
1458
1459 // Make sure we can execute all computations feeding into Ptr in the loop
1460 // w/o triggering UB and that none of the out-of-loop operands are poison.
1461 // We do not need to check if operations inside the loop can produce
1462 // poison due to flags (e.g. due to an inbounds GEP going out of bounds),
1463 // because flags will be dropped when executing them unconditionally.
1464 // TODO: Results could be improved by considering poison-propagation
1465 // properties of visited ops.
1466 auto CanSpeculatePointerOp = [this](Value *Ptr) {
1467 SmallVector<Value *> Worklist = {Ptr};
1468 SmallPtrSet<Value *, 4> Visited;
1469 while (!Worklist.empty()) {
1470 Value *CurrV = Worklist.pop_back_val();
1471 if (!Visited.insert(CurrV).second)
1472 continue;
1473
1474 auto *CurrI = dyn_cast<Instruction>(CurrV);
1475 if (!CurrI || !TheLoop->contains(CurrI)) {
1476 BasicBlock *LoopPred = TheLoop->getLoopPredecessor();
1477 Instruction *CtxI = LoopPred ? LoopPred->getTerminator() : nullptr;
1478 assert((CtxI || ORE->allowExtraAnalysis(DEBUG_TYPE)) &&
1479 "Loop with multiple predecessors should have been rejected "
1480 "early.");
1481 // If operands from outside the loop may be poison then Ptr may also
1482 // be poison.
1483 if (!isGuaranteedNotToBePoison(CurrV, AC, CtxI, DT))
1484 return false;
1485 continue;
1486 }
1487
1488 // A loaded value may be poison, independent of any flags.
1489 if (isa<LoadInst>(CurrI) && !isGuaranteedNotToBePoison(CurrV, AC))
1490 return false;
1491
1492 // For other ops, assume poison can only be introduced via flags,
1493 // which can be dropped.
1494 if (!isa<PHINode>(CurrI) && !isSafeToSpeculativelyExecute(CurrI))
1495 return false;
1496 append_range(Worklist, CurrI->operands());
1497 }
1498 return true;
1499 };
1500 // Pass the Predicates pointer to isDereferenceableAndAlignedInLoop so
1501 // that it will consider loops that need guarding by SCEV checks. The
1502 // vectoriser will generate these checks if we decide to vectorise.
1503 if (LI && !LI->getType()->isVectorTy() && !mustSuppressSpeculation(*LI) &&
1504 CanSpeculatePointerOp(LI->getPointerOperand()) &&
1505 isDereferenceableAndAlignedInLoop(LI, TheLoop, SE, *DT, AC,
1506 &Predicates))
1507 SafePointers.insert(LI->getPointerOperand());
1508 Predicates.clear();
1509 }
1510 }
1511
1512 // Collect the blocks that need predication.
1513 for (BasicBlock *BB : TheLoop->blocks()) {
1514 // We support only branches and switch statements as terminators inside the
1515 // loop.
1516 if (isa<SwitchInst>(BB->getTerminator())) {
1517 if (TheLoop->isLoopExiting(BB)) {
1518 reportVectorizationFailure("Loop contains an unsupported switch",
1519 "LoopContainsUnsupportedSwitch", ORE,
1520 TheLoop, BB->getTerminator());
1521 return false;
1522 }
1523 } else if (!isa<UncondBrInst, CondBrInst>(BB->getTerminator())) {
1524 reportVectorizationFailure("Loop contains an unsupported terminator",
1525 "LoopContainsUnsupportedTerminator", ORE,
1526 TheLoop, BB->getTerminator());
1527 return false;
1528 }
1529
1530 // We must be able to predicate all blocks that need to be predicated.
1531 if (blockNeedsPredication(BB) &&
1532 !blockCanBePredicated(BB, SafePointers, ConditionallyExecutedOps)) {
1534 "Control flow cannot be substituted for a select", "NoCFGForSelect",
1535 ORE, TheLoop, BB->getTerminator());
1536 return false;
1537 }
1538 }
1539
1540 // We can if-convert this loop.
1541 return true;
1542}
1543
1544// Helper function to canVectorizeLoopNestCFG.
1545bool LoopVectorizationLegality::canVectorizeLoopCFG(
1546 Loop *Lp, bool UseVPlanNativePath) const {
1547 assert((UseVPlanNativePath || Lp->isInnermost()) &&
1548 "VPlan-native path is not enabled.");
1549
1550 // TODO: ORE should be improved to show more accurate information when an
1551 // outer loop can't be vectorized because a nested loop is not understood or
1552 // legal. Something like: "outer_loop_location: loop not vectorized:
1553 // (inner_loop_location) loop control flow is not understood by vectorizer".
1554
1555 // Store the result and return it at the end instead of exiting early, in case
1556 // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1557 bool Result = true;
1558 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1559
1560 // We must have a loop in canonical form. Loops with indirectbr in them cannot
1561 // be canonicalized.
1562 if (!Lp->getLoopPreheader()) {
1564 "Loop doesn't have a legal pre-header",
1565 "loop control flow is not understood by vectorizer", "CFGNotUnderstood",
1566 ORE, TheLoop);
1567 if (DoExtraAnalysis)
1568 Result = false;
1569 else
1570 return false;
1571 }
1572
1573 // We must have a single backedge.
1574 if (Lp->getNumBackEdges() != 1) {
1576 "The loop must have a single backedge",
1577 "loop control flow is not understood by vectorizer", "CFGNotUnderstood",
1578 ORE, TheLoop);
1579 if (DoExtraAnalysis)
1580 Result = false;
1581 else
1582 return false;
1583 }
1584
1585 // The latch must be terminated by a branch.
1586 BasicBlock *Latch = Lp->getLoopLatch();
1587 if (Latch && !isa<UncondBrInst, CondBrInst>(Latch->getTerminator())) {
1589 "The loop latch terminator is not a UncondBrInst/CondBrInst",
1590 "loop control flow is not understood by vectorizer", "CFGNotUnderstood",
1591 ORE, TheLoop);
1592 if (DoExtraAnalysis)
1593 Result = false;
1594 else
1595 return false;
1596 }
1597
1598 return Result;
1599}
1600
1601bool LoopVectorizationLegality::canVectorizeLoopNestCFG(
1602 Loop *Lp, bool UseVPlanNativePath) {
1603 // Store the result and return it at the end instead of exiting early, in case
1604 // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1605 bool Result = true;
1606 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1607 if (!canVectorizeLoopCFG(Lp, UseVPlanNativePath)) {
1608 if (DoExtraAnalysis)
1609 Result = false;
1610 else
1611 return false;
1612 }
1613
1614 // Recursively check whether the loop control flow of nested loops is
1615 // understood.
1616 for (Loop *SubLp : *Lp)
1617 if (!canVectorizeLoopNestCFG(SubLp, UseVPlanNativePath)) {
1618 if (DoExtraAnalysis)
1619 Result = false;
1620 else
1621 return false;
1622 }
1623
1624 return Result;
1625}
1626
1627bool LoopVectorizationLegality::isVectorizableEarlyExitLoop() {
1628 BasicBlock *LatchBB = TheLoop->getLoopLatch();
1629 if (!LatchBB) {
1630 reportVectorizationFailure("Loop does not have a latch",
1631 "Cannot vectorize early exit loop",
1632 "NoLatchEarlyExit", ORE, TheLoop);
1633 return false;
1634 }
1635
1636 if (Reductions.size() || FixedOrderRecurrences.size()) {
1638 "Found reductions or recurrences in early-exit loop",
1639 "Cannot vectorize early exit loop with reductions or recurrences",
1640 "RecurrencesInEarlyExitLoop", ORE, TheLoop);
1641 return false;
1642 }
1643
1644 SmallVector<BasicBlock *, 8> ExitingBlocks;
1645 TheLoop->getExitingBlocks(ExitingBlocks);
1646
1647 // Keep a record of all the exiting blocks.
1649 SmallVector<BasicBlock *> UncountableExitingBlocks;
1650 for (BasicBlock *BB : ExitingBlocks) {
1651 const SCEV *EC =
1652 PSE.getSE()->getPredicatedExitCount(TheLoop, BB, &Predicates);
1653 if (isa<SCEVCouldNotCompute>(EC)) {
1654 if (size(successors(BB)) != 2) {
1656 "Early exiting block does not have exactly two successors",
1657 "Incorrect number of successors from early exiting block",
1658 "EarlyExitTooManySuccessors", ORE, TheLoop);
1659 return false;
1660 }
1661
1662 UncountableExitingBlocks.push_back(BB);
1663 } else
1664 CountableExitingBlocks.push_back(BB);
1665 }
1666 // We can safely ignore the predicates here because when vectorizing the loop
1667 // the PredicatatedScalarEvolution class will keep track of all predicates
1668 // for each exiting block anyway. This happens when calling
1669 // PSE.getSymbolicMaxBackedgeTakenCount() below.
1670 Predicates.clear();
1671
1672 if (UncountableExitingBlocks.empty()) {
1673 LLVM_DEBUG(dbgs() << "LV: Could not find any uncountable exits");
1674 return false;
1675 }
1676
1677 // The latch block must have a countable exit.
1679 PSE.getSE()->getPredicatedExitCount(TheLoop, LatchBB, &Predicates))) {
1681 "Cannot determine exact exit count for latch block",
1682 "Cannot vectorize early exit loop",
1683 "UnknownLatchExitCountEarlyExitLoop", ORE, TheLoop);
1684 return false;
1685 }
1686 assert(llvm::is_contained(CountableExitingBlocks, LatchBB) &&
1687 "Latch block not found in list of countable exits!");
1688
1689 // Check to see if there are instructions that could potentially generate
1690 // exceptions or have side-effects.
1691 auto IsSafeOperation = [](Instruction *I) -> bool {
1692 switch (I->getOpcode()) {
1693 case Instruction::Load:
1694 case Instruction::Store:
1695 case Instruction::PHI:
1696 case Instruction::UncondBr:
1697 case Instruction::CondBr:
1698 // These are checked separately.
1699 return true;
1700 default:
1702 }
1703 };
1704
1705 bool HasSideEffects = false;
1706 for (auto *BB : TheLoop->blocks())
1707 for (auto &I : *BB) {
1708 if (I.mayWriteToMemory()) {
1709 if (isa<StoreInst>(&I) && cast<StoreInst>(&I)->isSimple()) {
1710 HasSideEffects = true;
1711 continue;
1712 }
1713
1714 // We don't support complex writes to memory.
1716 "Complex writes to memory unsupported in early exit loops",
1717 "Cannot vectorize early exit loop with complex writes to memory",
1718 "WritesInEarlyExitLoop", ORE, TheLoop);
1719 return false;
1720 }
1721
1722 if (!IsSafeOperation(&I)) {
1723 reportVectorizationFailure("Early exit loop contains operations that "
1724 "cannot be speculatively executed",
1725 "UnsafeOperationsEarlyExitLoop", ORE,
1726 TheLoop);
1727 return false;
1728 }
1729 }
1730
1731 SmallVector<LoadInst *, 4> NonDerefLoads;
1732 // TODO: Handle loops that may fault.
1733 if (!HasSideEffects) {
1734 // Read-only loop.
1735 Predicates.clear();
1736 if (!isReadOnlyLoop(TheLoop, PSE.getSE(), DT, AC, NonDerefLoads,
1737 &Predicates)) {
1739 "Loop may fault", "Cannot vectorize non-read-only early exit loop",
1740 "NonReadOnlyEarlyExitLoop", ORE, TheLoop);
1741 return false;
1742 }
1743 } else {
1744 // Check all uncountable exiting blocks for movable loads.
1745 for (BasicBlock *ExitingBB : UncountableExitingBlocks) {
1746 if (!canUncountableExitConditionLoadBeMoved(ExitingBB))
1747 return false;
1748 }
1749 }
1750
1751 // Check non-dereferenceable loads if any.
1752 for (LoadInst *LI : NonDerefLoads) {
1753 // Only support unit-stride access for now.
1754 int Stride = isConsecutivePtr(LI->getType(), LI->getPointerOperand());
1755 if (Stride != 1) {
1757 "Loop contains potentially faulting strided load",
1758 "Cannot vectorize early exit loop with "
1759 "strided fault-only-first load",
1760 "EarlyExitLoopWithStridedFaultOnlyFirstLoad", ORE, TheLoop);
1761 return false;
1762 }
1763 }
1764
1765 [[maybe_unused]] const SCEV *SymbolicMaxBTC =
1766 PSE.getSymbolicMaxBackedgeTakenCount();
1767 // Since we have an exact exit count for the latch and the early exit
1768 // dominates the latch, then this should guarantee a computed SCEV value.
1769 assert(!isa<SCEVCouldNotCompute>(SymbolicMaxBTC) &&
1770 "Failed to get symbolic expression for backedge taken count");
1771 LLVM_DEBUG(dbgs() << "LV: Found an early exit loop with symbolic max "
1772 "backedge taken count: "
1773 << *SymbolicMaxBTC << '\n');
1774 UncountableExitType = HasSideEffects ? UncountableExitTrait::ReadWrite
1776 return true;
1777}
1778
1779bool LoopVectorizationLegality::canUncountableExitConditionLoadBeMoved(
1780 BasicBlock *ExitingBlock) {
1781 // Try to find a load in the critical path for the uncountable exit condition.
1782 // This is currently matching about the simplest form we can, expecting
1783 // only one in-loop load, the result of which is directly compared against
1784 // a loop-invariant value.
1785 // FIXME: We're insisting on a single use for now, because otherwise we will
1786 // need to make PHI nodes for other users. That can be done once the initial
1787 // transform code lands.
1788 auto *Br = cast<CondBrInst>(ExitingBlock->getTerminator());
1789
1790 using namespace llvm::PatternMatch;
1791 Instruction *L = nullptr;
1792 Value *Ptr = nullptr;
1793 Value *R = nullptr;
1794 // The exit-condition load can appear on either side of the icmp.
1795 if (!match(Br->getCondition(),
1797 m_Value(R))))) {
1799 "Early exit loop with store but no supported condition load",
1800 "NoConditionLoadForEarlyExitLoop", ORE, TheLoop);
1801 return false;
1802 }
1803
1804 if (!TheLoop->isLoopInvariant(R)) {
1806 "Early exit loop with store but no supported condition load",
1807 "NoConditionLoadForEarlyExitLoop", ORE, TheLoop);
1808 return false;
1809 }
1810
1811 // Make sure that the load address is not loop invariant; we want an
1812 // address calculation that we can rotate to the next vector iteration.
1813 const auto *AR = dyn_cast<SCEVAddRecExpr>(PSE.getSE()->getSCEV(Ptr));
1814 if (!AR || AR->getLoop() != TheLoop || !AR->isAffine()) {
1816 "Uncountable exit condition depends on load with an address that is "
1817 "not an add recurrence in the loop",
1818 "EarlyExitLoadInvariantAddress", ORE, TheLoop);
1819 return false;
1820 }
1821
1822 ICFLoopSafetyInfo SafetyInfo;
1823 SafetyInfo.computeLoopSafetyInfo(TheLoop);
1824 LoadInst *Load = cast<LoadInst>(L);
1825 // We need to know that load will be executed before we can hoist a
1826 // copy out to run just before the first iteration.
1827 if (!SafetyInfo.isGuaranteedToExecute(*Load, DT, TheLoop)) {
1829 "Load for uncountable exit not guaranteed to execute",
1830 "ConditionalUncountableExitLoad", ORE, TheLoop);
1831 return false;
1832 }
1833
1834 // Prohibit any potential aliasing with any instruction in the loop which
1835 // might store to memory.
1836 // FIXME: Relax this constraint where possible.
1837 for (auto *BB : TheLoop->blocks()) {
1838 for (auto &I : *BB) {
1839 if (&I == Load)
1840 continue;
1841
1842 if (I.mayReadOrWriteMemory()) {
1843 // We need to mask all other memory ops.
1844 ConditionallyExecutedOps.insert(&I);
1845 if (isa<LoadInst>(&I))
1846 continue;
1847 if (auto *SI = dyn_cast<StoreInst>(&I)) {
1848 AliasResult AR = AA->alias(Ptr, SI->getPointerOperand());
1849 if (AR == AliasResult::NoAlias)
1850 continue;
1851 }
1852
1854 "Cannot determine whether critical uncountable exit load address "
1855 "does not alias with a memory write",
1856 "CantVectorizeAliasWithCriticalUncountableExitLoad", ORE, TheLoop);
1857 return false;
1858 }
1859 }
1860 }
1861
1862 return true;
1863}
1864
1865bool LoopVectorizationLegality::canVectorize(bool UseVPlanNativePath) {
1866 // Store the result and return it at the end instead of exiting early, in case
1867 // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1868 bool Result = true;
1869
1870 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1871 // Check whether the loop-related control flow in the loop nest is expected by
1872 // vectorizer.
1873 if (!canVectorizeLoopNestCFG(TheLoop, UseVPlanNativePath)) {
1874 if (DoExtraAnalysis) {
1875 LLVM_DEBUG(dbgs() << "LV: legality check failed: loop nest");
1876 Result = false;
1877 } else {
1878 return false;
1879 }
1880 }
1881
1882 // We need to have a loop header.
1883 LLVM_DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()
1884 << '\n');
1885
1886 // Specific checks for outer loops. We skip the remaining legal checks at this
1887 // point because they don't support outer loops.
1888 if (!TheLoop->isInnermost()) {
1889 assert(UseVPlanNativePath && "VPlan-native path is not enabled.");
1890
1891 if (!canVectorizeOuterLoop()) {
1892 reportVectorizationFailure("Unsupported outer loop",
1893 "UnsupportedOuterLoop", ORE, TheLoop);
1894 // TODO: Implement DoExtraAnalysis when subsequent legal checks support
1895 // outer loops.
1896 return false;
1897 }
1898
1899 LLVM_DEBUG(dbgs() << "LV: We can vectorize this outer loop!\n");
1900 return Result;
1901 }
1902
1903 assert(TheLoop->isInnermost() && "Inner loop expected.");
1904 // Check if we can if-convert non-single-bb loops.
1905 unsigned NumBlocks = TheLoop->getNumBlocks();
1906 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1907 LLVM_DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1908 if (DoExtraAnalysis)
1909 Result = false;
1910 else
1911 return false;
1912 }
1913
1914 // Check if we can vectorize the instructions and CFG in this loop.
1915 if (!canVectorizeInstrs()) {
1916 LLVM_DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
1917 if (DoExtraAnalysis)
1918 Result = false;
1919 else
1920 return false;
1921 }
1922
1923 if (isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount())) {
1924 if (TheLoop->getExitingBlock()) {
1925 reportVectorizationFailure("Cannot vectorize uncountable loop",
1926 "UnsupportedUncountableLoop", ORE, TheLoop);
1927 if (DoExtraAnalysis)
1928 Result = false;
1929 else
1930 return false;
1931 } else {
1932 if (!isVectorizableEarlyExitLoop()) {
1933 assert(UncountableExitType == UncountableExitTrait::None &&
1934 "Must be false without vectorizable early-exit loop");
1935 if (DoExtraAnalysis)
1936 Result = false;
1937 else
1938 return false;
1939 }
1940 }
1941 }
1942
1943 // Go over each instruction and look at memory deps.
1944 if (!canVectorizeMemory()) {
1945 LLVM_DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
1946 if (DoExtraAnalysis)
1947 Result = false;
1948 else
1949 return false;
1950 }
1951
1952 // TODO: Remove this restriction, should be straightforward to support.
1953 if (UncountableExitType != UncountableExitTrait::None &&
1954 !LAI->getStoresToInvariantAddresses().empty()) {
1955 LLVM_DEBUG(dbgs() << "LV: Cannot vectorize early exit loops with stores to "
1956 "loop-invariant addresses\n");
1957 reportVectorizationFailure("Cannot vectorize early exit loops with stores "
1958 "to loop-invariant addresses",
1959 "LoopInvariantStoresInEELoop", ORE, TheLoop);
1960 return false;
1961 }
1962
1963 if (Result) {
1964 LLVM_DEBUG(dbgs() << "LV: We can vectorize this loop"
1965 << (LAI->getRuntimePointerChecking()->Need
1966 ? " (with a runtime bound check)"
1967 : "")
1968 << "!\n");
1969 }
1970
1971 // Okay! We've done all the tests. If any have failed, return false. Otherwise
1972 // we can vectorize, and at this point we don't have any other mem analysis
1973 // which may limit our maximum vectorization factor, so just return true with
1974 // no restrictions.
1975 return Result;
1976}
1977
1979 // The only loops we can vectorize without a scalar epilogue, are loops with
1980 // a bottom-test and a single exiting block. We'd have to handle the fact
1981 // that not every instruction executes on the last iteration. This will
1982 // require a lane mask which varies through the vector loop body. (TODO)
1983 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
1984 LLVM_DEBUG(
1985 dbgs()
1986 << "LV: Cannot fold tail by masking. Requires a singe latch exit\n");
1987 return false;
1988 }
1989
1990 LLVM_DEBUG(dbgs() << "LV: checking if tail can be folded by masking.\n");
1991
1992 // The list of pointers that we can safely read and write to remains empty.
1993 SmallPtrSet<Value *, 8> SafePointers;
1994
1995 // Check all blocks for predication, including those that ordinarily do not
1996 // need predication such as the header block.
1998 for (BasicBlock *BB : TheLoop->blocks()) {
1999 if (!blockCanBePredicated(BB, SafePointers, TmpMaskedOp)) {
2000 LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking.\n");
2001 return false;
2002 }
2003 }
2004
2005 LLVM_DEBUG(dbgs() << "LV: can fold tail by masking.\n");
2006
2007 return true;
2008}
2009
2011 // The list of pointers that we can safely read and write to remains empty.
2012 SmallPtrSet<Value *, 8> SafePointers;
2013
2014 // Mark all blocks for predication, including those that ordinarily do not
2015 // need predication such as the header block, and collect instructions needing
2016 // predication in TailFoldedMaskedOp.
2017 for (BasicBlock *BB : TheLoop->blocks()) {
2018 [[maybe_unused]] bool R =
2019 blockCanBePredicated(BB, SafePointers, TailFoldedMaskedOp);
2020 assert(R && "Must be able to predicate block when tail-folding.");
2021 }
2022}
2023
2024} // namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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< 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< 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.
This file provides a LoopVectorizationPlanner 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 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
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:867
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.
static LLVM_ABI bool isInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, InductionDescriptor &D, ArrayRef< const SCEVPredicate * > NoWrapPreds={}, const SCEV *Expr=nullptr, SmallVectorImpl< Instruction * > *CastsToIgnore=nullptr)
Returns true if Phi is an induction in the loop L.
@ IK_PtrInduction
Pointer induction var. Step = C.
@ IK_IntInduction
Integer induction variable. Step = C.
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 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
LLVM_ABI bool isInvariantStoreOfReduction(StoreInst *SI)
Returns True if given store is a final invariant store of one of the reductions found in the loop.
LLVM_ABI void collectUnitStridePredicates() const
Add unit stride predicates for memory accesses to PSE, if runtime checks are allowed and an inner loo...
LLVM_ABI bool isInvariantAddressOfReduction(Value *V)
Returns True if given address is invariant and is used to store recurrent expression.
LLVM_ABI bool canVectorize(bool UseVPlanNativePath)
Returns true if it is legal to vectorize this loop.
LLVM_ABI bool blockNeedsPredication(const BasicBlock *BB) const
Return true if the block BB needs to be predicated in order for the loop to be vectorized.
LLVM_ABI 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...
LLVM_ABI bool canVectorizeFPMath(bool EnableStrictReductions)
Returns true if it is legal to vectorize the FP math operations in this loop.
LLVM_ABI bool isFixedOrderRecurrence(const PHINode *Phi) const
Returns True if Phi is a fixed-order recurrence in this loop.
LLVM_ABI bool isInductionPhi(const Value *V) const
Returns True if V is a Phi node of an induction variable in this loop.
const InductionList & getInductionVars() const
Returns the induction variables found in the loop.
LLVM_ABI 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.
LLVM_ABI bool canFoldTailByMasking() const
Return true if we can vectorize this loop while folding its tail by masking.
LLVM_ABI void prepareToFoldTailByMasking()
Mark all respective loads/stores for masking.
bool hasUncountableEarlyExit() const
Returns true if the loop has uncountable early exits, i.e.
LLVM_ABI bool isUniformMemOp(Instruction &I, std::optional< ElementCount > VF) const
A uniform memory op is a load or store which accesses the same memory location on all VF lanes,...
LLVM_ABI bool isUniform(Value *V, std::optional< ElementCount > VF) const
Returns true if value V is uniform across VF lanes, when VF is provided, and otherwise if V is invari...
LLVM_ABI bool isInductionVariable(const Value *V) const
Returns True if V can be considered as an induction variable in this loop.
LLVM_ABI 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.
LLVM_ABI bool allowVectorization(Function *F, Loop *L, bool VectorizeOnlyWhenForced) const
LLVM_ABI bool allowReordering() const
When enabling loop hints are provided we allow the vectorizer to change the order of operations that ...
LLVM_ABI void emitRemarkWithHints() const
Dumps all the hint information.
LLVM_ABI void setAlreadyVectorized()
Mark the loop L as already vectorized by setting the width to 1.
LLVM_ABI 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:533
Metadata node.
Definition Metadata.h:1069
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1426
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1424
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1432
Tracking metadata reference owned by Metadata.
Definition Metadata.h:891
A single uniqued string.
Definition Metadata.h:722
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:633
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.
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
Type * getType() const
Return the LLVM type of this SCEV expression.
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:309
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
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:270
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
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
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 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.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
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...
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.
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
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.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
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
bool isSimple(Instruction *I)
Definition SLPUtils.cpp:547
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:578
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:1739
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:1669
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.
@ Load
The value being inserted comes from a load (InsertElement only).
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:2208
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:445
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 ...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
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:1746
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:280
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.
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
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
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
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:2192
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
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:304
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 ShouldCheckWrap=true, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
If the pointer has a constant stride return it in units of the access type size.
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
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.
static LLVM_ABI ElementCount VectorizationFactor
VF as overridden by the user.