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