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