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