LLVM 24.0.0git
LoopAccessAnalysis.cpp
Go to the documentation of this file.
1//===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==//
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// The implementation for the loop memory dependence that was originally
10// developed for the loop vectorizer.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/BitVector.h"
17#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/MapVector.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/SetVector.h"
24#include "llvm/ADT/SmallSet.h"
42#include "llvm/IR/BasicBlock.h"
43#include "llvm/IR/Constants.h"
44#include "llvm/IR/DataLayout.h"
45#include "llvm/IR/DebugLoc.h"
48#include "llvm/IR/Dominators.h"
49#include "llvm/IR/Function.h"
50#include "llvm/IR/InstrTypes.h"
51#include "llvm/IR/Instruction.h"
54#include "llvm/IR/PassManager.h"
55#include "llvm/IR/Type.h"
56#include "llvm/IR/Value.h"
57#include "llvm/IR/ValueHandle.h"
60#include "llvm/Support/Debug.h"
64#include <algorithm>
65#include <cassert>
66#include <cstdint>
67#include <iterator>
68#include <utility>
69#include <variant>
70#include <vector>
71
72using namespace llvm;
73using namespace llvm::SCEVPatternMatch;
74
75#define DEBUG_TYPE "loop-accesses"
76
78 VectorizationFactor("force-vector-width", cl::Hidden,
79 cl::desc("Sets the SIMD width. Zero is autoselect."),
82
84VectorizationInterleave("force-vector-interleave", cl::Hidden,
85 cl::desc("Sets the vectorization interleave count. "
86 "Zero is autoselect."),
90
92 "runtime-memory-check-threshold", cl::Hidden,
93 cl::desc("When performing memory disambiguation checks at runtime do not "
94 "generate more than this number of comparisons (default = 8)."),
97
99 "vectorize-memory-check-threshold", cl::Hidden,
100 cl::desc("The maximum allowed number of runtime memory checks"),
102 cl::init(128));
104
105/// The maximum iterations used to merge memory checks
107 "memory-check-merge-threshold", cl::Hidden,
108 cl::desc("Maximum number of comparisons done when trying to merge "
109 "runtime memory checks. (default = 100)"),
110 cl::init(100));
111
113
115 "stencil-runtime-check-merge", cl::Hidden,
116 cl::desc("Control stencil-pattern merging of runtime memory checks"),
120 "Disable stencil merge (default)"),
122 "Enable stencil merge when runtime check count exceeds "
123 "-vectorize-memory-check-threshold"),
125 "Always attempt stencil merge regardless of check "
126 "count")));
127
129 "stencil-merge-max-groups", cl::Hidden,
130 cl::desc(
131 "Skip stencil group merging when the number of runtime checking groups "
132 "exceeds this limit, to bound compile time (default =4096)."),
133 cl::init(4096));
134
135/// Maximum SIMD width.
136const unsigned VectorizerParams::MaxVectorWidth = 64;
137
138/// We collect dependences up to this threshold.
140 MaxDependences("max-dependences", cl::Hidden,
141 cl::desc("Maximum number of dependences collected by "
142 "loop-access analysis (default = 100)"),
143 cl::init(100));
144
145/// This enables versioning on the strides of symbolically striding memory
146/// accesses in code like the following.
147/// for (i = 0; i < N; ++i)
148/// A[i * Stride1] += B[i * Stride2] ...
149///
150/// Will be roughly translated to
151/// if (Stride1 == 1 && Stride2 == 1) {
152/// for (i = 0; i < N; i+=4)
153/// A[i:i+3] += ...
154/// } else
155/// ...
157 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
158 cl::desc("Enable symbolic stride memory access versioning"));
159
160/// Enable store-to-load forwarding conflict detection. This option can
161/// be disabled for correctness testing.
163 "store-to-load-forwarding-conflict-detection", cl::Hidden,
164 cl::desc("Enable conflict detection in loop-access analysis"),
165 cl::init(true));
166
168 "max-forked-scev-depth", cl::Hidden,
169 cl::desc("Maximum recursion depth when finding forked SCEVs (default = 5)"),
170 cl::init(5));
171
173 "laa-speculate-unit-stride", cl::Hidden,
174 cl::desc("Speculate that non-constant strides are unit in LAA"),
175 cl::init(true));
176
178 "hoist-runtime-checks", cl::Hidden,
179 cl::desc(
180 "Hoist inner loop runtime memory checks to outer loop if possible"),
183
185 return ::VectorizationInterleave.getNumOccurrences() > 0;
186}
187
189 PredicatedScalarEvolution &PSE, const Loop *Lp,
190 const SymbolicStrideMap &PtrToStride, Value *Ptr,
192 const SCEV *OrigSCEV = PSE.getSCEV(Ptr);
193
194 // If there is an entry in the map return the SCEV of the pointer with the
195 // symbolic stride replaced by one.
196 const SCEVUnknown *StrideSCEV = PtrToStride.lookup(Ptr);
197 if (!StrideSCEV)
198 // For a non-symbolic stride, just return the original expression.
199 return OrigSCEV;
200
201 ScalarEvolution *SE = PSE.getSE();
202 const SCEV *CT = SE->getOne(StrideSCEV->getType());
203 const SCEV *Expr;
204 const SCEVPredicate *EqPred = SE->getEqualPredicate(StrideSCEV, CT);
205 if (Predicates) {
206 Predicates->push_back(EqPred);
207 Expr = SE->rewriteUsingPredicate(OrigSCEV, Lp,
208 SCEVUnionPredicate(*Predicates, *SE));
209 } else {
210 PSE.addPredicate(*EqPred);
211 Expr = PSE.getSCEV(Ptr);
212 }
213 LLVM_DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *Expr
214 << "\n");
215 return Expr;
216}
217
219 unsigned Index, const RuntimePointerChecking &RtCheck)
220 : High(RtCheck.Pointers[Index].End), Low(RtCheck.Pointers[Index].Start),
221 AddressSpace(RtCheck.Pointers[Index]
222 .PointerValue->getType()
224 NeedsFreeze(RtCheck.Pointers[Index].NeedsFreeze) {
225 Members.push_back(Index);
226}
227
228/// Returns \p A + \p B, if it is guaranteed not to unsigned wrap. Otherwise
229/// return nullptr. \p A and \p B must have the same type.
230static const SCEV *addSCEVNoOverflow(const SCEV *A, const SCEV *B,
231 ScalarEvolution &SE) {
232 if (!SE.willNotOverflow(Instruction::Add, /*IsSigned=*/false, A, B))
233 return nullptr;
234 return SE.getAddExpr(A, B);
235}
236
237/// Returns \p A * \p B, if it is guaranteed not to unsigned wrap. Otherwise
238/// return nullptr. \p A and \p B must have the same type.
239static const SCEV *mulSCEVNoOverflow(const SCEV *A, const SCEV *B,
240 ScalarEvolution &SE) {
241 if (!SE.willNotOverflow(Instruction::Mul, /*IsSigned=*/false, A, B))
242 return nullptr;
243 return SE.getMulExpr(A, B);
244}
245
246/// Return true, if evaluating \p AR at \p MaxBTC cannot wrap, because \p AR at
247/// \p MaxBTC is guaranteed inbounds of the accessed object.
249 const SCEVAddRecExpr *AR, const SCEV *MaxBTC, const SCEV *EltSize,
251 AssumptionCache *AC,
252 std::optional<ScalarEvolution::LoopGuards> &LoopGuards) {
253 auto *PointerBase = SE.getPointerBase(AR->getStart());
254 auto *StartPtr = dyn_cast<SCEVUnknown>(PointerBase);
255 if (!StartPtr)
256 return false;
257 const Loop *L = AR->getLoop();
258 bool CheckForNonNull;
259 Value *StartPtrV = StartPtr->getValue();
260 // We can ignore frees, as the fact that an object of a certain size existed
261 // at the location *at some point* is sufficient to derive the nowrap fact.
262 uint64_t DerefBytes = StartPtrV->getPointerDereferenceableBytes(
263 DL, CheckForNonNull, /*CanBeFreed=*/nullptr);
264
265 // If the deref size is only known when the pointer is non-null, ignore it
266 // here and fall back to a dereferenceable assumption below.
267 if (DerefBytes && CheckForNonNull)
268 DerefBytes = 0;
269
270 const SCEV *Step = AR->getStepRecurrence(SE);
271 Type *WiderTy = SE.getWiderType(MaxBTC->getType(), Step->getType());
272 const SCEV *DerefBytesSCEV = SE.getConstant(WiderTy, DerefBytes);
273
274 // Check if we have a suitable dereferencable assumption we can use.
275 Instruction *CtxI = &*L->getHeader()->getFirstNonPHIIt();
276 if (BasicBlock *LoopPred = L->getLoopPredecessor()) {
277 if (isa<UncondBrInst, CondBrInst>(LoopPred->getTerminator()))
278 CtxI = LoopPred->getTerminator();
279 }
281 StartPtrV, Attribute::Dereferenceable, *AC,
282 [&](RetainedKnowledge RK, Instruction *Assume, auto) {
283 if (!isValidAssumeForContext(Assume, CtxI, DT))
284 return false;
285 const SCEV *DerefRKSCEV = SE.getSCEV(RK.IRArgValue);
286 Type *CommonTy =
287 SE.getWiderType(DerefBytesSCEV->getType(), DerefRKSCEV->getType());
288 DerefBytesSCEV = SE.getNoopOrZeroExtend(DerefBytesSCEV, CommonTy);
289 DerefRKSCEV = SE.getNoopOrZeroExtend(DerefRKSCEV, CommonTy);
290 DerefBytesSCEV = SE.getUMaxExpr(DerefBytesSCEV, DerefRKSCEV);
291 // Continue with other assumptions.
292 return false;
293 });
294
295 if (DerefBytesSCEV->isZero())
296 return false;
297
298 bool IsKnownNonNegative = SE.isKnownNonNegative(Step);
299 if (!IsKnownNonNegative && !SE.isKnownNegative(Step))
300 return false;
301
302 WiderTy = SE.getWiderType(WiderTy, DerefBytesSCEV->getType());
303 Step = SE.getNoopOrSignExtend(Step, WiderTy);
304 MaxBTC = SE.getNoopOrZeroExtend(MaxBTC, WiderTy);
305
306 // For the computations below, make sure they don't unsigned wrap.
307 // FIXME: for a negative step the lowest accessed address is not
308 // AR->getStart() but AR->evaluateAtIteration(MaxBTC, SE); the check below
309 // therefore compares StartPtr against the highest accessed address instead
310 // of the lowest.
311 if (!SE.isKnownPredicate(CmpInst::ICMP_UGE, AR->getStart(), StartPtr))
312 return false;
313 const SCEV *StartOffset = SE.getNoopOrZeroExtend(
314 SE.getMinusSCEV(AR->getStart(), StartPtr), WiderTy);
315
316 if (!LoopGuards)
317 LoopGuards.emplace(ScalarEvolution::LoopGuards::collect(AR->getLoop(), SE));
318 MaxBTC = SE.applyLoopGuards(MaxBTC, *LoopGuards);
319
320 const SCEV *AbsStep = SE.getAbsExpr(Step, /*IsNSW=*/false);
321 // Total distance (in bytes) between the first and the last
322 // accessed pointer.
323 const SCEV *DistToLastIter = mulSCEVNoOverflow(MaxBTC, AbsStep, SE);
324 if (!DistToLastIter) {
325 // Re-try with constant max backedge-taken count if using the symbolic one
326 // failed.
327 MaxBTC = SE.getConstantMaxBackedgeTakenCount(AR->getLoop());
328 if (isa<SCEVCouldNotCompute>(MaxBTC))
329 return false;
330 MaxBTC = SE.getNoopOrZeroExtend(MaxBTC, WiderTy);
331 DistToLastIter = mulSCEVNoOverflow(MaxBTC, AbsStep, SE);
332 if (!DistToLastIter)
333 return false;
334 }
335
336 // Total length in bytes of the accessed range (from the first accessed
337 // byte through the end of the last access).
338 const SCEV *AccessedBytes = addSCEVNoOverflow(
339 DistToLastIter, SE.getNoopOrZeroExtend(EltSize, WiderTy), SE);
340 if (!AccessedBytes)
341 return false;
342
343 // Compute MaxOffset per direction: exclusive upper offset of the
344 // accessed range.
345 const SCEV *MaxOffset;
346 if (IsKnownNonNegative) {
347 MaxOffset = addSCEVNoOverflow(StartOffset, AccessedBytes, SE);
348 if (!MaxOffset)
349 return false;
350 DerefBytesSCEV = SE.applyLoopGuards(DerefBytesSCEV, *LoopGuards);
351 } else {
352 // FIXME: two independent off-by-EltSize bugs on this branch:
353 // 1. StartOffset here is actually the HIGHEST offset, because it is
354 // computed from AR->getStart() rather than
355 // AR->evaluateAtIteration(MaxBTC, SE) (see FIXME above).
356 // 2. The lower check is over-strict by EltSize and the upper is
357 // under-counted by EltSize.
358 assert(SE.isKnownNegative(Step) && "must be known negative");
359 if (!SE.isKnownPredicate(CmpInst::ICMP_SGE, StartOffset, AccessedBytes))
360 return false;
361 MaxOffset = StartOffset;
362 }
363 // MaxOffset must not exceed the deref-region end.
364 return SE.isKnownPredicate(CmpInst::ICMP_ULE, MaxOffset, DerefBytesSCEV);
365}
366
367/// Return true if \p S is known to be monotonically non-decreasing
368/// (in the unsigned sense, without unsigned wrap) across iterations of \p L.
369static bool isKnownNonDecreasingInLoop(const SCEV *S, const Loop *L,
370 ScalarEvolution &SE) {
371 if (SE.isLoopInvariant(S, L))
372 return true;
373
374 switch (S->getSCEVType()) {
375 case scUDivExpr: {
376 // Non-decreasing in the numerator when the divisor is loop-invariant.
377 const auto *UDiv = cast<SCEVUDivExpr>(S);
378 return SE.isLoopInvariant(UDiv->getRHS(), L) &&
379 isKnownNonDecreasingInLoop(UDiv->getLHS(), L, SE);
380 }
381 case scAddRecExpr: {
382 auto *AR = cast<SCEVAddRecExpr>(S);
383 assert(AR->getLoop() == L &&
384 "trying to check for AddRec in different loop");
387 }
388 case scAddExpr:
389 case scMulExpr: {
390 const auto *NAry = cast<SCEVNAryExpr>(S);
391 if (!NAry->hasNoUnsignedWrap())
392 return false;
393 // With NUW, the exact sum or product fits in the type, so it is
394 // non-decreasing if every operandis.
395 return all_of(NAry->operands(), [&](const SCEV *Op) {
396 return isKnownNonDecreasingInLoop(Op, L, SE);
397 });
398 }
399 default:
400 return false;
401 }
402}
403
404/// Try to bound a loop-variant pointer that is not an affine AddRec.
405///
406/// If the offset is provably monotonically non-decreasing the accessed range is
407/// bounded by the offset's value at the first iteration (via
408/// SplitIntoInitAndPostInc) and last iteration (via getSCEVAtScope). The
409/// returned range is half-open: \p EltSizeSCEV is added to the address of the
410/// last accessed element to form the end.
411///
412/// Returns {nullptr, nullptr} if no such bound can be formed.
413static std::pair<const SCEV *, const SCEV *>
414getNonAffineMonotonicBounds(const Loop *Lp, const SCEV *PtrExpr,
415 const SCEV *EltSizeSCEV, ScalarEvolution *SE) {
416 const auto *PtrAdd = dyn_cast<SCEVAddExpr>(PtrExpr);
417 if (!PtrAdd || !PtrAdd->hasNoUnsignedWrap())
418 return {nullptr, nullptr};
419
420 const SCEV *Base = *find_if(PtrAdd->operands(), [](const auto &Op) {
421 return Op->getType()->isPointerTy();
422 });
424 return {nullptr, nullptr};
425
426 const SCEV *Offset = SE->getMinusSCEV(PtrExpr, Base);
429 return {nullptr, nullptr};
430
431 const SCEV *OffStart = SE->SplitIntoInitAndPostInc(Lp, Offset).first;
432 const SCEV *OffEnd = SE->getSCEVAtScope(Offset, Lp->getParentLoop());
433 if (isa<SCEVCouldNotCompute>(OffStart) || isa<SCEVCouldNotCompute>(OffEnd) ||
434 !SE->isLoopInvariant(OffStart, Lp) || !SE->isLoopInvariant(OffEnd, Lp))
435 return {nullptr, nullptr};
436
437 return {SE->getAddExpr(Base, OffStart),
438 SE->getAddExpr(Base, OffEnd, EltSizeSCEV)};
439}
440
441std::pair<const SCEV *, const SCEV *> llvm::getStartAndEndForAccess(
442 const Loop *Lp, const SCEV *PtrExpr, Type *AccessTy, const SCEV *BTC,
443 const SCEV *MaxBTC, ScalarEvolution *SE,
444 DenseMap<std::pair<const SCEV *, const SCEV *>,
445 std::pair<const SCEV *, const SCEV *>> *PointerBounds,
447 std::optional<ScalarEvolution::LoopGuards> &LoopGuards) {
448 auto &DL = Lp->getHeader()->getDataLayout();
449 Type *IdxTy = DL.getIndexType(PtrExpr->getType());
450 const SCEV *EltSizeSCEV = SE->getStoreSizeOfExpr(IdxTy, AccessTy);
451
452 // Delegate to the SCEV-based overload, passing through the cache.
453 return getStartAndEndForAccess(Lp, PtrExpr, EltSizeSCEV, BTC, MaxBTC, SE,
454 PointerBounds, DT, AC, LoopGuards);
455}
456
457std::pair<const SCEV *, const SCEV *> llvm::getStartAndEndForAccess(
458 const Loop *Lp, const SCEV *PtrExpr, const SCEV *EltSizeSCEV,
459 const SCEV *BTC, const SCEV *MaxBTC, ScalarEvolution *SE,
460 DenseMap<std::pair<const SCEV *, const SCEV *>,
461 std::pair<const SCEV *, const SCEV *>> *PointerBounds,
463 std::optional<ScalarEvolution::LoopGuards> &LoopGuards) {
464 std::pair<const SCEV *, const SCEV *> *PtrBoundsPair;
465 if (PointerBounds) {
466 auto [Iter, Ins] = PointerBounds->insert(
467 {{PtrExpr, EltSizeSCEV},
468 {SE->getCouldNotCompute(), SE->getCouldNotCompute()}});
469 if (!Ins)
470 return Iter->second;
471 PtrBoundsPair = &Iter->second;
472 }
473
474 // ScStart is the lowest accessed address; ScEnd is the highest one plus the
475 // size of the accessed element.
476 const SCEV *ScStart;
477 const SCEV *ScEnd;
478
479 auto &DL = Lp->getHeader()->getDataLayout();
480 if (SE->isLoopInvariant(PtrExpr, Lp)) {
481 ScStart = PtrExpr;
482 ScEnd = SE->getAddExpr(PtrExpr, EltSizeSCEV);
483 } else if (auto *AR = dyn_cast<SCEVAddRecExpr>(PtrExpr)) {
484 const SCEV *Step = AR->getStepRecurrence(*SE);
485 // The address of the last accessed element, if it can be computed
486 // precisely.
487 const SCEV *LastAddr = nullptr;
488 if (!isa<SCEVCouldNotCompute>(BTC)) {
489 // Evaluating AR at an exact BTC is safe: LAA separately checks that
490 // accesses cannot wrap in the loop. If evaluating AR at BTC wraps, then
491 // the loop either triggers UB when executing a memory access with a
492 // poison pointer or the wrapping/poisoned pointer is not used.
493 LastAddr = AR->evaluateAtIteration(BTC, *SE);
495 AR, MaxBTC, EltSizeSCEV, *SE, DL, DT, AC, LoopGuards)) {
496 LastAddr = AR->evaluateAtIteration(MaxBTC, *SE);
497 }
498 const SCEV *Start = AR->getStart();
499 Type *PtrTy = AR->getType();
500 if (SE->isKnownNegative(Step)) {
501 ScStart =
502 LastAddr
503 ? LastAddr
505 Constant::getNullValue(DL.getIndexType(PtrTy)), PtrTy));
506 ScEnd = SE->getAddExpr(Start, EltSizeSCEV);
507 } else if (SE->isKnownNonNegative(Step)) {
508 ScStart = Start;
509 // The highest address for the type saturates; adding EltSize to it would
510 // wrap to the start of the address space.
511 if (LastAddr)
512 ScEnd = SE->getAddExpr(LastAddr, EltSizeSCEV);
513 else
515 Constant::getAllOnesValue(DL.getIndexType(PtrTy)), PtrTy));
516 } else {
517 if (!LastAddr)
518 return {SE->getCouldNotCompute(), SE->getCouldNotCompute()};
519 // Fallback case: the step is not constant, but we can still
520 // get the upper and lower bounds of the interval by using min/max
521 // expressions.
522 ScStart = SE->getUMinExpr(Start, LastAddr);
523 ScEnd = SE->getAddExpr(SE->getUMaxExpr(Start, LastAddr), EltSizeSCEV);
524 }
525 } else {
526 // The pointer is loop-variant but not an affine AddRec. Try to form a
527 // tight bound for a monotonic offset (see getNonAffineMonotonicBounds).
528 std::tie(ScStart, ScEnd) =
529 getNonAffineMonotonicBounds(Lp, PtrExpr, EltSizeSCEV, SE);
530 if (!ScStart)
531 return {SE->getCouldNotCompute(), SE->getCouldNotCompute()};
532 }
533
534 assert(SE->isLoopInvariant(ScStart, Lp) && "ScStart needs to be invariant");
535 assert(SE->isLoopInvariant(ScEnd, Lp) && "ScEnd needs to be invariant");
536
537 std::pair<const SCEV *, const SCEV *> Res = {ScStart, ScEnd};
538 if (PointerBounds)
539 *PtrBoundsPair = Res;
540 return Res;
541}
542
543/// Calculate Start and End points of memory access using
544/// getStartAndEndForAccess.
545bool RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, const SCEV *PtrExpr,
546 Type *AccessTy, bool WritePtr,
547 unsigned DepSetId, unsigned ASId,
549 bool NeedsFreeze, bool IsForked) {
550 const SCEV *SymbolicMaxBTC = PSE.getSymbolicMaxBackedgeTakenCount();
551 const SCEV *BTC = PSE.getBackedgeTakenCount();
552 const auto &[ScStart, ScEnd] = getStartAndEndForAccess(
553 Lp, PtrExpr, AccessTy, BTC, SymbolicMaxBTC, PSE.getSE(),
554 &DC.getPointerBounds(), DC.getDT(), DC.getAC(), LoopGuards);
556 return false;
557 Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, PtrExpr,
558 NeedsFreeze, IsForked);
559 return true;
560}
561
562bool RuntimePointerChecking::tryToCreateDiffCheck(
563 const RuntimeCheckingPtrGroup &CGI, const RuntimeCheckingPtrGroup &CGJ) {
564 // If either group contains multiple different pointers, bail out.
565 // TODO: Support multiple pointers by using the minimum or maximum pointer,
566 // depending on src & sink.
567 if (CGI.Members.size() != 1 || CGJ.Members.size() != 1)
568 return false;
569
570 const PointerInfo *Src = &Pointers[CGI.Members[0]];
571 const PointerInfo *Sink = &Pointers[CGJ.Members[0]];
572
573 // If either pointer is read and written, multiple checks may be needed. Bail
574 // out.
575 if (!DC.getOrderForAccess(Src->PointerValue, !Src->IsWritePtr).empty() ||
576 !DC.getOrderForAccess(Sink->PointerValue, !Sink->IsWritePtr).empty())
577 return false;
578
579 ArrayRef<unsigned> AccSrc =
580 DC.getOrderForAccess(Src->PointerValue, Src->IsWritePtr);
581 ArrayRef<unsigned> AccSink =
582 DC.getOrderForAccess(Sink->PointerValue, Sink->IsWritePtr);
583 // If either pointer is accessed multiple times, there may not be a clear
584 // src/sink relation. Bail out for now.
585 if (AccSrc.size() != 1 || AccSink.size() != 1)
586 return false;
587
588 // If the sink is accessed before src, swap src/sink.
589 if (AccSink[0] < AccSrc[0])
590 std::swap(Src, Sink);
591
592 const SCEVConstant *Step;
593 const SCEV *SrcStart;
594 const SCEV *SinkStart;
595 const Loop *InnerLoop = DC.getInnermostLoop();
596 if (!match(Src->Expr,
598 m_SpecificLoop(InnerLoop))) ||
599 !match(Sink->Expr,
601 m_SpecificLoop(InnerLoop))))
602 return false;
603
605 DC.getInstructionsForAccess(Src->PointerValue, Src->IsWritePtr);
607 DC.getInstructionsForAccess(Sink->PointerValue, Sink->IsWritePtr);
608 Type *SrcTy = getLoadStoreType(SrcInsts[0]);
609 Type *DstTy = getLoadStoreType(SinkInsts[0]);
611 return false;
612
613 const DataLayout &DL = InnerLoop->getHeader()->getDataLayout();
614 unsigned AllocSize =
615 std::max(DL.getTypeAllocSize(SrcTy), DL.getTypeAllocSize(DstTy));
616
617 // Only matching constant steps matching the AllocSize are supported at the
618 // moment. This simplifies the difference computation. Can be extended in the
619 // future.
620 if (Step->getAPInt().abs() != AllocSize)
621 return false;
622
623 // When counting down, the dependence distance needs to be swapped.
624 if (Step->getValue()->isNegative())
625 std::swap(SinkStart, SrcStart);
626
627 const SCEV *SinkStartInt = SE->getPtrToAddrExpr(SinkStart);
628 const SCEV *SrcStartInt = SE->getPtrToAddrExpr(SrcStart);
629 if (isa<SCEVCouldNotCompute>(SinkStartInt) ||
630 isa<SCEVCouldNotCompute>(SrcStartInt))
631 return false;
632
633 // If the start values for both Src and Sink also vary according to an outer
634 // loop, then it's probably better to avoid creating diff checks because
635 // they may not be hoisted. We should instead let llvm::addRuntimeChecks
636 // do the expanded full range overlap checks, which can be hoisted.
637 if (HoistRuntimeChecks && InnerLoop->getParentLoop() &&
638 isa<SCEVAddRecExpr>(SinkStartInt) && isa<SCEVAddRecExpr>(SrcStartInt)) {
639 auto *SrcStartAR = cast<SCEVAddRecExpr>(SrcStartInt);
640 auto *SinkStartAR = cast<SCEVAddRecExpr>(SinkStartInt);
641 const Loop *StartARLoop = SrcStartAR->getLoop();
642 if (StartARLoop == SinkStartAR->getLoop() &&
643 StartARLoop == InnerLoop->getParentLoop() &&
644 // If the diff check would already be loop invariant (due to the
645 // recurrences being the same), then we prefer to keep the diff checks
646 // because they are cheaper.
647 SrcStartAR->getStepRecurrence(*SE) !=
648 SinkStartAR->getStepRecurrence(*SE)) {
649 LLVM_DEBUG(dbgs() << "LAA: Not creating diff runtime check, since these "
650 "cannot be hoisted out of the outer loop\n");
651 return false;
652 }
653 }
654
655 LLVM_DEBUG(dbgs() << "LAA: Creating diff runtime check for:\n"
656 << "SrcStart: " << *SrcStartInt << '\n'
657 << "SinkStartInt: " << *SinkStartInt << '\n');
658 DiffChecks.emplace_back(SrcStartInt, SinkStartInt, AllocSize,
659 Src->NeedsFreeze || Sink->NeedsFreeze);
660 return true;
661}
662
664 SmallVector<RuntimePointerCheck, 4> Checks;
665
666 for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
667 for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) {
670
671 if (needsChecking(CGI, CGJ)) {
672 CanUseDiffCheck = CanUseDiffCheck && tryToCreateDiffCheck(CGI, CGJ);
673 Checks.emplace_back(&CGI, &CGJ);
674 }
675 }
676 }
677 return Checks;
678}
679
682 assert(Checks.empty() && "Checks is not empty");
683 groupChecks(DepCands);
684 mergeStencilGroups();
685 Checks = generateChecks();
686}
687
689 const RuntimeCheckingPtrGroup &M, const RuntimeCheckingPtrGroup &N) const {
690 for (const auto &I : M.Members)
691 for (const auto &J : N.Members)
692 if (needsChecking(I, J))
693 return true;
694 return false;
695}
696
697/// Compare \p I and \p J and return the minimum.
698/// Return nullptr in case we couldn't find an answer.
699static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
700 ScalarEvolution *SE) {
701 std::optional<APInt> Diff = SE->computeConstantDifference(J, I);
702 if (!Diff)
703 return nullptr;
704 return Diff->isNegative() ? J : I;
705}
706
708 unsigned Index, const RuntimePointerChecking &RtCheck) {
709 return addPointer(
710 Index, RtCheck.Pointers[Index].Start, RtCheck.Pointers[Index].End,
711 RtCheck.Pointers[Index].PointerValue->getType()->getPointerAddressSpace(),
712 RtCheck.Pointers[Index].NeedsFreeze, *RtCheck.SE);
713}
714
715bool RuntimeCheckingPtrGroup::addPointer(unsigned Index, const SCEV *Start,
716 const SCEV *End, unsigned AS,
717 bool NeedsFreeze,
718 ScalarEvolution &SE) {
719 assert(AddressSpace == AS &&
720 "all pointers in a checking group must be in the same address space");
721
722 // Compare the starts and ends with the known minimum and maximum
723 // of this set. We need to know how we compare against the min/max
724 // of the set in order to be able to emit memchecks.
725 const SCEV *Min0 = getMinFromExprs(Start, Low, &SE);
726 if (!Min0)
727 return false;
728
729 const SCEV *Min1 = getMinFromExprs(End, High, &SE);
730 if (!Min1)
731 return false;
732
733 // Update the low bound expression if we've found a new min value.
734 if (Min0 == Start)
735 Low = Start;
736
737 // Update the high bound expression if we've found a new max value.
738 if (Min1 != End)
739 High = End;
740
741 Members.push_back(Index);
742 this->NeedsFreeze |= NeedsFreeze;
743 return true;
744}
745
746void RuntimePointerChecking::groupChecks(
748 // We build the groups from dependency candidates equivalence classes
749 // because:
750 // - We know that pointers in the same equivalence class share
751 // the same underlying object and therefore there is a chance
752 // that we can compare pointers
753 // - We wouldn't be able to merge two pointers for which we need
754 // to emit a memcheck. The classes in DepCands are already
755 // conveniently built such that no two pointers in the same
756 // class need checking against each other.
757
758 // We use the following (greedy) algorithm to construct the groups
759 // For every pointer in the equivalence class:
760 // For each existing group:
761 // - if the difference between this pointer and the min/max bounds
762 // of the group is a constant, then make the pointer part of the
763 // group and update the min/max bounds of that group as required.
764
765 CheckingGroups.clear();
766
767 // If we need to check two pointers to the same underlying object
768 // with a non-constant difference, we shouldn't perform any pointer
769 // grouping with those pointers. This is because we can easily get
770 // into cases where the resulting check would return false, even when
771 // the accesses are safe.
772 //
773 // The following example shows this:
774 // for (i = 0; i < 1000; ++i)
775 // a[5000 + i * m] = a[i] + a[i + 9000]
776 //
777 // Here grouping gives a check of (5000, 5000 + 1000 * m) against
778 // (0, 10000) which is always false. However, if m is 1, there is no
779 // dependence. Not grouping the checks for a[i] and a[i + 9000] allows
780 // us to perform an accurate check in this case.
781 //
782 // In the above case, we have a non-constant distance and an Unknown
783 // dependence between accesses to the same underlying object, and could retry
784 // with runtime checks without dependency information being available. In this
785 // case we will use the fallback path and create separate checking groups for
786 // accesses not present in DepCands.
787
788 unsigned TotalComparisons = 0;
789
791 for (unsigned Index = 0; Index < Pointers.size(); ++Index)
792 PositionMap[{Pointers[Index].PointerValue, Pointers[Index].IsWritePtr}]
793 .push_back(Index);
794
795 // We need to keep track of what pointers we've already seen so we
796 // don't process them twice.
798
799 // Go through all equivalence classes, get the "pointer check groups"
800 // and add them to the overall solution. We use the order in which accesses
801 // appear in 'Pointers' to enforce determinism.
802 for (unsigned I = 0; I < Pointers.size(); ++I) {
803 // We've seen this pointer before, and therefore already processed
804 // its equivalence class.
805 if (Seen.contains(I))
806 continue;
807
809 Pointers[I].IsWritePtr);
810
811 // If there is no entry in the dependency partition, there are no potential
812 // accesses to merge; simply add a new pointer checking group.
813 if (!DepCands.contains(Access)) {
814 CheckingGroups.push_back(RuntimeCheckingPtrGroup(I, *this));
815 continue;
816 }
817
819
820 // Because DepCands is constructed by visiting accesses in the order in
821 // which they appear in alias sets (which is deterministic) and the
822 // iteration order within an equivalence class member is only dependent on
823 // the order in which unions and insertions are performed on the
824 // equivalence class, the iteration order is deterministic.
825 for (auto M : DepCands.members(Access)) {
826 for (unsigned Pointer : PositionMap.lookup(M)) {
827 assert(!Seen.contains(Pointer) && "pointer already processed");
828 Seen.insert(Pointer);
829 bool Merged = false;
830
831 // Go through all the existing sets and see if we can find one
832 // which can include this pointer.
833 for (RuntimeCheckingPtrGroup &Group : Groups) {
834 // Don't perform more than a certain amount of comparisons.
835 // This should limit the cost of grouping the pointers to something
836 // reasonable. If we do end up hitting this threshold, the algorithm
837 // will create separate groups for all remaining pointers.
838 if (TotalComparisons > MemoryCheckMergeThreshold)
839 break;
840
841 TotalComparisons++;
842
843 if (Group.addPointer(Pointer, *this)) {
844 Merged = true;
845 break;
846 }
847 }
848
849 if (!Merged)
850 // We couldn't add this pointer to any existing set or the threshold
851 // for the number of comparisons has been reached. Create a new group
852 // to hold the current pointer.
853 Groups.emplace_back(Pointer, *this);
854 }
855 }
856
857 // We've computed the grouped checks for this partition.
858 // Save the results and continue with the next one.
860 }
861}
862
863/// Result of decomposing a SCEV expression into stencil offset form:
864/// Offset = Constant + sum(Coefficients[stride] * stride)
865/// where each stride is a loop-invariant SCEV expression.
867 int64_t Constant = 0;
868 /// Map from loop-invariant stride SCEV to its integer coefficient.
870};
871
872/// Recursion cap for addScaledStencilTerm. Depth counts how deep a term
873/// sits inside the offset expression. For example, the offset
874/// 8 + (64 * (s1 + s2 + (4 * s3)))
875/// is visited like this:
876/// depth 0: the whole add
877/// depth 1: its operands 8 and (64 * (s1 + s2 + (4 * s3)))
878/// depth 2: (s1 + s2 + (4 * s3)), the operand of the multiply
879/// depth 3: s1, s2 and (4 * s3), the operands of that add
880/// At depth 3 addScaledStencilTerm stops going deeper. s1 and s2 are plain
881/// strides anyway. (4 * s3) is not split into 4 times s3: it becomes one
882/// stride key as it is, with coefficient 64. The result is Constant = 8
883/// and coefficients {s1: 64, s2: 64, (4 * s3): 64}.
884/// Three levels cover the stencil offsets we care about: a top-level add,
885/// a constant times a sum inside it, and the strides in that sum. A deeper
886/// term is kept whole as one stride key. The merge does not care what is
887/// inside a key. It only needs a loop-invariant value with a
888/// positive-stride predicate, and a whole term has both. The only cost is
889/// precision, when another member uses a part of that term, here s3 alone,
890/// as a key of its own. isNeverAbove sees two unrelated keys, so a member
891/// that is in fact always lower or higher may stay a candidate.
892constexpr unsigned MaxStencilDecomposeDepth = 3;
893
894/// Add one term of a stencil offset to \p D. \p Mult is the factor in
895/// front of the term; the top-level call passes 1.
896/// Example: the offset 8 + (-64 * (s1 + s2)) + (-32 * s1), Mult = 1. It is
897/// an add, so each operand is visited in turn with the same Mult = 1:
898/// 8 a constant: D.Constant += 1 * 8
899/// (-64 * (s1 + s2)) a constant times X: visit X = (s1 + s2) with
900/// Mult = 1 * -64. X is an add, so each operand is
901/// visited with Mult = -64:
902/// s1 a stride: D.Coefficients[s1] += -64
903/// s2 a stride: D.Coefficients[s2] += -64
904/// (-32 * s1) a constant times X: visit X = s1 with Mult = -32:
905/// s1 a stride: D.Coefficients[s1] += -32
906/// Result: Constant = 8, Coefficients {s1: -96, s2: -64}. The -64 and the
907/// -32 for s1 come from two different terms and add up in the map.
908/// So, by the kind of term:
909/// constant K D.Constant += Mult * K
910/// (K * X) visit X with Mult * K
911/// (a + b + ...) visit a, b, ... each with this same Mult
912/// anything else a stride key: D.Coefficients[Term] += Mult
913/// The two recursive cases only fire while Depth is below
914/// MaxStencilDecomposeDepth. At the cap, (K * X) and (a + b + ...) are
915/// stride keys like anything else; that is not a bailout.
916/// Returns false when a constant does not fit in int64_t or an update
917/// overflows. The caller then drops the whole decomposition.
918static bool addScaledStencilTerm(const SCEV *Term, int64_t Mult, unsigned Depth,
920 const SCEVConstant *C;
921 // A constant folds into the running constant at any depth.
922 if (match(Term, m_SCEVConstant(C))) {
923 std::optional<int64_t> V = C->getAPInt().trySExtValue();
924 int64_t Scaled;
925 return V && !MulOverflow(Mult, *V, Scaled) &&
926 !AddOverflow(D.Constant, Scaled, D.Constant);
927 }
928
930 const SCEV *Inner;
931 if (match(Term, m_scev_Mul(m_SCEVConstant(C), m_SCEV(Inner)))) {
932 std::optional<int64_t> V = C->getAPInt().trySExtValue();
933 int64_t NewMult;
934 return V && !MulOverflow(Mult, *V, NewMult) &&
935 addScaledStencilTerm(Inner, NewMult, Depth + 1, D);
936 }
937 if (auto *Add = dyn_cast<SCEVAddExpr>(Term))
938 return all_of(Add->operands(), [&](const SCEV *Op) {
939 return addScaledStencilTerm(Op, Mult, Depth + 1, D);
940 });
941 }
942
943 // Anything else is one stride key.
944 int64_t &Coeff = D.Coefficients[Term];
945 return !AddOverflow(Coeff, Mult, Coeff);
946}
947
948/// Try to decompose \p Expr into a stencil offset function of loop-invariant
949/// strides: C + a1*s1 + a2*s2 + ...
950/// \p Expr is the difference of two access "Start" SCEVs (Start_member -
951/// Start_base). A "Start" is the low bound of a memory access range as computed
952/// by getStartAndEndForAccess: the address of the first byte the access can
953/// touch. The result describes where one member's range sits relative to the
954/// base member's range.
955/// Constant factors are distributed over sums. SCEV can keep a factored form:
956/// -64*s1 + -64*s2 is stored as (-64 * (s1 + s2)). Distributing the -64 gives
957/// the coefficients {s1: -64, s2: -64}, so every member of a group is keyed
958/// on the same base strides.
959/// Relies on SCEV's canonical form: AddExpr operands are flattened (N-ary),
960/// MulExpr has the constant operand first when present.
961/// Returns std::nullopt if a constant, multiplier, or coefficient update does
962/// not fit in int64_t.
963static std::optional<StencilDecomposition>
964decomposeStencilOffset(const SCEV *Expr, ScalarEvolution &SE, const Loop &L) {
965 // A "Start" is always loop-invariant (getStartAndEndForAccess asserts it), so
966 // the difference Expr passed in by the caller is loop-invariant too, and so
967 // is every term addScaledStencilTerm visits.
968 assert(SE.isLoopInvariant(Expr, &L) && "expected a loop-invariant offset");
969
971 if (!addScaledStencilTerm(Expr, /*Mult=*/1, /*Depth=*/0, D))
972 return std::nullopt;
973 return D;
974}
975
976/// Find a common upper limit M for the positive strides in D. If every stride
977/// is between 1 and M, the decomposed offset fits in the signed index type.
978/// This lets isNeverAbove compare offsets as ordinary signed integers.
979///
980/// Subtract abs(Constant) from SignedMax, then divide the remaining budget by
981/// the sum of absolute coefficients:
982/// M = (SignedMax - abs(Constant)) / sum(abs(Coefficient)).
983/// For example, both 8 + 4*s and 8 - 4*s get M = (SignedMax - 8) / 4.
984///
985/// Return nullopt if abs(Constant) exceeds SignedMax or no positive stride
986/// fits. Otherwise, if all coefficients are zero, no stride limit is needed;
987/// return SignedMax.
988static std::optional<APInt>
990 uint64_t SignedMax = maxIntN(BitWidth);
991 uint64_t AbsConstant = AbsoluteValue(D.Constant);
992 if (AbsConstant > SignedMax)
993 return std::nullopt;
994 uint64_t Budget = SignedMax - AbsConstant;
995 uint64_t CoeffSum = 0;
996 for (const auto &[Stride, Coeff] : D.Coefficients) {
997 uint64_t AbsCoeff = AbsoluteValue(Coeff);
998 if (AbsCoeff > Budget - CoeffSum)
999 return std::nullopt;
1000 CoeffSum += AbsCoeff;
1001 }
1002 return APInt(BitWidth, CoeffSum ? Budget / CoeffSum : SignedMax);
1003}
1004
1005namespace {
1006/// The runtime checks the merge needs on each stride.
1007/// Example:
1008/// s1: {NeedsPositive = true, Max = 1000} means the checks 1 <= s1 <= 1000
1009/// s2: {Max = 50} means the check s2 <= 50
1010/// The lower limit is always 1, so a flag is enough for it.
1011/// Several members can each ask for an upper limit on the same stride, but only
1012/// the smallest one is kept.
1013class StrideLimits {
1014 struct Limit {
1015 bool NeedsPositive = false;
1016 std::optional<APInt> Max;
1017 };
1018 SmallMapVector<const SCEV *, Limit, 4> Limits;
1019
1020public:
1021 void requireLowerLimit(const SCEV *Stride) {
1022 Limits[Stride].NeedsPositive = true;
1023 }
1024
1025 void requireUpperLimit(const SCEV *Stride, const APInt &Max) {
1026 std::optional<APInt> &Current = Limits[Stride].Max;
1027 if (!Current || Max.ult(*Current))
1028 Current = Max;
1029 }
1030
1031 /// Add every new or more strict check in \p Other to this set.
1032 void addFrom(const StrideLimits &Other) {
1033 for (const auto &[Stride, L] : Other.Limits) {
1034 if (L.NeedsPositive)
1035 requireLowerLimit(Stride);
1036 if (L.Max)
1037 requireUpperLimit(Stride, *L.Max);
1038 }
1039 }
1040
1041 /// Count the strides that have no check in \p Committed yet.
1042 unsigned countNew(const StrideLimits &Committed) const {
1043 return count_if(Limits, [&](const auto &Entry) {
1044 return !Committed.Limits.contains(Entry.first);
1045 });
1046 }
1047
1048 /// Add the checks to \p PSE as SCEV predicates.
1049 void addPredicates(PredicatedScalarEvolution &PSE) const {
1050 ScalarEvolution &SE = *PSE.getSE();
1051 for (const auto &[Stride, L] : Limits) {
1052 if (L.NeedsPositive) {
1053 const SCEV *Zero = SE.getZero(Stride->getType());
1054 PSE.addPredicate(
1055 *SE.getComparePredicate(ICmpInst::ICMP_SGT, Stride, Zero));
1056 LLVM_DEBUG(dbgs() << "LAA: Adding positive-stride predicate for "
1057 << *Stride << "\n");
1058 }
1059 if (L.Max) {
1060 PSE.addPredicate(*SE.getComparePredicate(ICmpInst::ICMP_SLE, Stride,
1061 SE.getConstant(*L.Max)));
1062 LLVM_DEBUG(dbgs() << "LAA: Adding stride upper-limit predicate "
1063 << *Stride << " <= " << *L.Max << "\n");
1064 }
1065 }
1066 }
1067};
1068} // namespace
1069
1070/// Add to \p Limits the checks each stride s of \p D needs:
1071/// 1 <= s isNeverAbove assumes every stride is 1 or more.
1072/// s <= Max Max is from getStencilStrideUpperLimit.
1073/// A check is skipped when SCEV already proves it.
1074/// Returns false if getStencilStrideUpperLimit finds no Max, or if SCEV proves
1075/// that a check always fails. Example: s = smin(x, -1) can never pass 1 <= s,
1076/// so a merge would send every run to the scalar loop.
1078 unsigned BitWidth, ScalarEvolution &SE,
1079 StrideLimits &Limits) {
1080 std::optional<APInt> UpperLimit = getStencilStrideUpperLimit(D, BitWidth);
1081 if (!UpperLimit)
1082 return false;
1083
1084 const SCEV *Max = SE.getConstant(*UpperLimit);
1085 for (const auto &[Stride, Coeff] : D.Coefficients) {
1086 if (SE.isKnownNonPositive(Stride) ||
1087 SE.isKnownPredicate(ICmpInst::ICMP_SGT, Stride, Max))
1088 return false;
1089 if (!SE.isKnownPositive(Stride))
1090 Limits.requireLowerLimit(Stride);
1091 if (!SE.isKnownPredicate(ICmpInst::ICMP_SLE, Stride, Max))
1092 Limits.requireUpperLimit(Stride, *UpperLimit);
1093 }
1094 return true;
1095}
1096
1097/// Return true if offset A is never higher than offset B.
1098/// A and B are these sums:
1099/// A = A.Constant + CoefA_1 * stride_1 + CoefA_2 * stride_2 + ...
1100/// B = B.Constant + CoefB_1 * stride_1 + CoefB_2 * stride_2 + ...
1101/// A stride missing from a member's map has coefficient 0. Every stride
1102/// is 1 or more: the caller proves or predicates each stride to be positive
1103/// and that the whole expression does not overflow.
1104/// Example:
1105/// A: 0 - 80*s1
1106/// B: -40 - 40*s1
1107/// At s1 = 1 both are -80. For bigger s1, A goes down faster. So A is
1108/// never above B.
1109/// The rule checks two things:
1110/// 1. CoefA_i <= CoefB_i for every stride. So when a stride grows, B - A
1111/// grows too, or stays the same.
1112/// 2. B - A >= 0 when every stride is 1. That is ACorner <= BCorner, with
1113/// ACorner = A.Constant + the sum of all CoefA_i, same for BCorner.
1114/// B - A starts at or above zero and never goes down, so B - A >= 0 for
1115/// all stride values.
1116/// Offsets are signed and addresses are unsigned, but both members read
1117/// one object, and an object does not wrap around the address space, so
1118/// the smaller offset is the smaller address.
1119/// Returns false when ACorner or BCorner overflows int64_t. The caller
1120/// then keeps the member, which is the safe side.
1122 const StencilDecomposition &B) {
1123 int64_t ACorner = A.Constant, BCorner = B.Constant;
1124 for (const auto &[Stride, ACoeff] : A.Coefficients) {
1125 if (ACoeff > B.Coefficients.lookup(Stride))
1126 return false;
1127 if (AddOverflow(ACorner, ACoeff, ACorner))
1128 return false;
1129 }
1130 for (const auto &[Stride, BCoeff] : B.Coefficients) {
1131 if (A.Coefficients.lookup(Stride) > BCoeff)
1132 return false;
1133 if (AddOverflow(BCorner, BCoeff, BCorner))
1134 return false;
1135 }
1136 return ACorner <= BCorner;
1137}
1138
1139/// Find the members that can define the merged bound on one side.
1140/// Example for the minimum side (\p ForMin == true), two members:
1141/// A: 0 - 80*s1
1142/// B: -40 - 40*s1
1143/// For every s1 >= 1, A sits at or below B, so B can never be the lowest
1144/// member: A beats B. The members nobody beats are the candidates.
1145/// The maximum side works the same way with the comparison flipped.
1146/// When two members have equal offsets, only the first one is kept.
1147/// In other words: "beats" is a partial order on the offsets, and the
1148/// candidates are its minimal elements.
1149/// Returns indices into \p Offsets.
1150/// TODO: Worst case compares every pair of members: O(N^2). Fine for real
1151/// stencils.
1154 // A beats B when A always bounds at least as well as B: for the minimum
1155 // side A is never above B, for the maximum side A is never below B.
1156 auto Beats = [&](unsigned A, unsigned B) {
1157 return ForMin ? isNeverAbove(Offsets[A], Offsets[B])
1158 : isNeverAbove(Offsets[B], Offsets[A]);
1159 };
1160 // Skipping a beaten member loses nothing: Beats is transitive, so
1161 // whoever beat it also beats anyone it would have beaten.
1162 BitVector Beaten(Offsets.size());
1163 for (unsigned K = 0; K < Offsets.size(); ++K) {
1164 if (Beaten.test(K))
1165 continue;
1166 // Walk J = K + 1 .. N to avoid checking the same pair twice, as
1167 // (K, J) and again as (J, K). The order in a pair does not matter.
1168 for (unsigned J = K + 1; J < Offsets.size(); ++J) {
1169 if (Beaten.test(J))
1170 continue;
1171 // Checking K first settles ties: on equal offsets K survives.
1172 if (Beats(K, J)) {
1173 Beaten.set(J);
1174 } else if (Beats(J, K)) {
1175 Beaten.set(K);
1176 break;
1177 }
1178 }
1179 }
1180 SmallVector<unsigned, 4> Candidates;
1181 for (unsigned K = 0; K < Offsets.size(); ++K)
1182 if (!Beaten.test(K))
1183 Candidates.push_back(K);
1184 return Candidates;
1185}
1186
1187/// Local cost model: count the runtime checks required before and after
1188/// replacing one DepSet's groups (\p GroupIndices) with the single merged
1189/// group. Everything is counted in the same unit, one check, even though a
1190/// stride predicate or an extra umin/umax operand is cheaper at runtime
1191/// than a full group-pair check. The cheaper items only appear on the
1192/// After side, and we merge only when After < Before, so the rounding
1193/// always errs toward not merging.
1194///
1195/// Before = NumGroups * NumExternalChecks, where NumExternalChecks is the
1196/// number of groups outside this DepSet that need a check against it. The
1197/// product is exact: needsChecking() looks only at (DependencySetId,
1198/// AliasSetId) and at whether a group writes, and all groups in this
1199/// DepSet agree on those, so an external group is checked against all of
1200/// them or against none.
1201///
1202/// After = NumExternalChecks + NewPredicates + NumBoundOperands:
1203/// - the merged group keeps the same IDs, so it is checked against exactly
1204/// the same external groups;
1205/// - one check per stride needing a lower or upper limit, unless an earlier
1206/// DepSet already paid for either limit;
1207/// - a umin over k members costs k-1 compare+selects, same for the umax.
1208/// \p NumBoundOperands is the sum of the two. A single candidate costs
1209/// nothing: the bound is that member's own address.
1210///
1211/// Returns {ChecksBefore, ChecksAfter}.
1212static std::pair<unsigned, unsigned> computeStencilMergeCost(
1213 const RuntimePointerChecking &RtCheck, ArrayRef<unsigned> GroupIndices,
1214 const StrideLimits &Local, const StrideLimits &Committed,
1215 unsigned NumBoundOperands) {
1216 unsigned NumGroups = GroupIndices.size();
1217 unsigned NumExternalChecks =
1218 count_if(RtCheck.CheckingGroups, [&](const RuntimeCheckingPtrGroup &G) {
1219 return any_of(GroupIndices, [&](unsigned GI) {
1220 return RtCheck.needsChecking(RtCheck.CheckingGroups[GI], G);
1221 });
1222 });
1223
1224 unsigned NewPredicates = Local.countNew(Committed);
1225
1226 LLVM_DEBUG(dbgs() << "LAA: Cost model: NumGroups=" << NumGroups
1227 << ", NumExternalChecks=" << NumExternalChecks
1228 << ", predicates=" << NewPredicates
1229 << ", bound operands=" << NumBoundOperands << ", checks "
1230 << NumGroups * NumExternalChecks << "->"
1231 << NumExternalChecks + NewPredicates + NumBoundOperands
1232 << "\n");
1233
1234 return {NumGroups * NumExternalChecks,
1235 NumExternalChecks + NewPredicates + NumBoundOperands};
1236}
1237
1238/// Build the merged stencil group for one DepSet, after the cost model has
1239/// decided the merge is profitable. Constructs the bounding group over
1240/// \p AllMembers with bounds [\p MergedLow, \p MergedHigh]. Returns the new
1241/// group.
1244 ArrayRef<unsigned> AllMembers, const SCEV *MergedLow,
1245 const SCEV *MergedHigh,
1246 ArrayRef<unsigned> GroupIndices) {
1247 RuntimeCheckingPtrGroup CandidateGroup(AllMembers[0], RtCheck);
1248 CandidateGroup.Low = MergedLow;
1249 CandidateGroup.High = MergedHigh;
1250 append_range(CandidateGroup.Members, drop_begin(AllMembers));
1251 CandidateGroup.NeedsFreeze = any_of(GroupIndices, [&](unsigned GI) {
1252 return RtCheck.CheckingGroups[GI].NeedsFreeze;
1253 });
1254 return CandidateGroup;
1255}
1256
1257void RuntimePointerChecking::mergeStencilGroups() {
1258 LLVM_DEBUG(dbgs() << "LAA: Attempting stencil group merging on "
1259 << CheckingGroups.size() << " groups\n");
1260
1261 if (CheckingGroups.size() < 2)
1262 return;
1263
1264 // groupChecks merges two pointers only when their bounds differ by a
1265 // compile-time constant, because only then it can tell which bound is
1266 // lower or higher. A stencil kernel reads one object at several
1267 // loop-invariant offsets, so its bounds differ by expressions like
1268 // -40 - 40*s1, and every such pointer stays in its own group - often
1269 // too many checks. Here we merge those groups anyway: what we cannot
1270 // compare at compile time we compare at runtime, with a umin/umax over
1271 // the few members that can be lowest or highest. The cost: the merged
1272 // range also covers the gaps between the members, so the merged check
1273 // can report a conflict where the per-group checks would not.
1274 //
1275 // We only merge ranges for reads that happen on every loop iteration.
1276 // These reads must stay inside the array; otherwise, the original loop
1277 // already has undefined behaviour. We choose the merged bounds from
1278 // these ranges.
1279 //
1280 // We use the following algorithm to construct a merged stencil group:
1281 // - collect checking groups that share both DependencySetId and AliasSetId;
1282 // - reject groups with writes, predicated accesses, forked pointers,
1283 // different access ranges, or different recurrence steps;
1284 // - use one member as the base and decompose each other member's offset
1285 // from that base as C + sum(Coeff[Stride] * Stride), where Stride is
1286 // loop-invariant;
1287 // - keep the members that can hold the lowest or the highest address at
1288 // runtime (the candidate members), and build the merged bounds as a
1289 // umin over their Start values and a umax over their End values,
1290 // adding predicates for strides not already known positive and within
1291 // their limits;
1292 // - commit the merge only if the local cost model reduces the number of
1293 // checks after accounting for any new predicates.
1294
1295 // Stencil merging runs when either:
1296 // - the flag is set to 'force' (-stencil-runtime-check-merge=force), or
1297 // - the flag is set to 'auto' (-stencil-runtime-check-merge=auto) AND the
1298 // current check count exceeds the auto-trigger threshold, which defaults
1299 // to the vectorizer's own runtime-check cutoff
1300 // (-vectorize-memory-check-threshold). Above it the vectorizer would
1301 // otherwise reject the loop for having too many runtime checks. In that
1302 // case the merge can only improve things: at worst we decline to merge
1303 // and behave as before.
1305 LLVM_DEBUG(dbgs() << "LAA: stencil merge disabled\n");
1306 return;
1307 }
1308
1309 const Loop &L = *DC.getInnermostLoop();
1310
1311 // visitPointers expands non-header pointer PHIs before runtime checks are
1312 // created, so their alternatives are not marked IsForked. An unused
1313 // alternative may wrap and make the merged bounds miss a real overlap.
1314 for (BasicBlock *BB : L.blocks())
1315 if (BB != L.getHeader())
1316 for (PHINode &PN : BB->phis())
1317 if (PN.getType()->isPointerTy())
1318 return;
1319
1320 // For each checking group this pass decomposes each member's offset into
1321 // stencil form, keeps the candidate members (the ones that can hold the
1322 // lowest or highest address at runtime), and builds the merged bounds from
1323 // their own Start and End values. That extra SCEV work adds up on a loop
1324 // with very many groups, so bail out above a configurable limit as a
1325 // safety net against pathological inputs.
1327 LLVM_DEBUG(
1328 dbgs() << "LAA: " << CheckingGroups.size()
1329 << " groups exceeds stencil-merge-max-groups, skipping\n");
1330 return;
1331 }
1332
1334 unsigned TotalChecks = 0;
1335 for (unsigned I = 0; I < CheckingGroups.size(); ++I)
1336 for (unsigned J = I + 1; J < CheckingGroups.size(); ++J)
1338 ++TotalChecks;
1339
1340 // Above this many checks the vectorizer gives up on the loop, so that is
1341 // where merging starts to matter.
1343 LLVM_DEBUG(dbgs() << "LAA: " << TotalChecks
1344 << " checks <= threshold, skipping stencil merge\n");
1345 return;
1346 }
1347 LLVM_DEBUG(
1348 dbgs() << "LAA: " << TotalChecks
1349 << " checks > threshold, proceeding with stencil merge\n");
1350 } else {
1351 LLVM_DEBUG(dbgs() << "LAA: stencil merge forced via flag\n");
1352 }
1353
1354 // Group CheckingGroups by (DependencySetId, AliasSetId) pair.
1355 // DependencySetId alone is not unique: it resets per alias set, so
1356 // pointers in different alias sets can share the same DependencySetId.
1357 // Use MapVector for deterministic iteration order across platforms.
1358 using DepAliasKey = std::pair<unsigned, unsigned>;
1359 MapVector<DepAliasKey, SmallVector<unsigned, 4>> DepSetToGroups;
1360 for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
1361 const auto &P = Pointers[CheckingGroups[I].Members[0]];
1362 DepSetToGroups[{P.DependencySetId, P.AliasSetId}].push_back(I);
1363 }
1364
1365 SmallDenseSet<unsigned, 4> MergedGroupIndices;
1367 // Stride checks from the accepted DepSets. A later DepSet can lower an
1368 // upper limit, so the predicates are added only after the last DepSet.
1369 StrideLimits CommittedStrideLimits;
1370
1371 for (auto &[DepAliasKey, GroupIndices] : DepSetToGroups) {
1372 [[maybe_unused]] auto [DepId, ASId] = DepAliasKey;
1373 if (GroupIndices.size() < 2)
1374 continue;
1375
1376 // Collect all member pointers across these groups. Only merge read-only
1377 // groups: stencil patterns read an array at multiple offsets and write to a
1378 // different array (a different DepSet). Mixing reads and writes within a
1379 // merged group complicates the cost model and doesn't match known stencil
1380 // patterns, so stop and skip the whole DepSet as soon as we see a write.
1381 SmallVector<unsigned, 8> AllMembers;
1382 bool CanMerge = true;
1383 for (unsigned GI : GroupIndices) {
1384 ArrayRef<unsigned> Members = CheckingGroups[GI].Members;
1385 if (any_of(Members,
1386 [&](unsigned Idx) { return Pointers[Idx].IsWritePtr; })) {
1387 LLVM_DEBUG(dbgs() << "LAA: Skipping DepSet(" << DepId << "," << ASId
1388 << ") with write access\n");
1389 CanMerge = false;
1390 break;
1391 }
1392 // For a forked pointer, LAA considers both possible addresses, even if
1393 // the loop only uses one of them. The unused address can be outside the
1394 // array. Its bounds can underflow or overflow, so merging them can hide
1395 // an overlap and allow unsafe vectorization.
1396 if (any_of(Members,
1397 [&](unsigned Idx) { return Pointers[Idx].IsForked; })) {
1398 LLVM_DEBUG(dbgs() << "LAA: Skipping DepSet(" << DepId << "," << ASId
1399 << ") with forked pointer\n");
1400 CanMerge = false;
1401 break;
1402 }
1403 append_range(AllMembers, Members);
1404 }
1405 if (!CanMerge)
1406 continue;
1407
1408 // A predicated access does not happen in every iteration. In the skipped
1409 // iterations its address can be outside the array. Its bounds can
1410 // underflow or overflow, so merging them can hide an overlap and allow
1411 // unsafe vectorization.
1412 // Look at the block of the actual load/store, not of the pointer: a
1413 // loop-invariant address is computed in the preheader, outside the loop.
1414 if (any_of(AllMembers, [&](unsigned Idx) {
1415 const PointerInfo &P = Pointers[Idx];
1416 assert(!P.IsWritePtr && "only read members reach this point");
1417 return any_of(
1418 DC.getInstructionsForAccess(P.PointerValue, /*isWrite=*/false),
1419 [&](Instruction *I) {
1420 return LoopAccessInfo::blockNeedsPredication(I->getParent(), &L,
1421 DC.getDT());
1422 });
1423 })) {
1424 LLVM_DEBUG(dbgs() << "LAA: Skipping DepSet(" << DepId << "," << ASId
1425 << ") with predicated access\n");
1426 continue;
1427 }
1428
1429 // Use the first member as the reference for decomposition. All offsets
1430 // are computed relative to BaseLow. BaseHigh is only used to check that
1431 // every member covers the same range. The merged bounds are built later
1432 // from the members' own Start and End values.
1433 unsigned Member0 = AllMembers[0];
1434 const SCEV *BaseLow = Pointers[Member0].Start;
1435 const SCEV *BaseHigh = Pointers[Member0].End;
1436
1437 // Keep stencil decomposition and stride-limit arithmetic within 64 bits.
1438 // All offsets relative to BaseLow have the same index width.
1439 if (SE->getTypeSizeInBits(BaseLow->getType()) > 64)
1440 continue;
1441
1442 LLVM_DEBUG(dbgs() << "LAA: Analyzing DepSet(" << DepId << "," << ASId
1443 << ") with " << AllMembers.size()
1444 << " members, base: " << *BaseLow << "\n");
1445
1446 auto GetStepForPointer = [&](unsigned Idx) -> const SCEV * {
1447 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(Pointers[Idx].Expr))
1448 if (AR->getLoop() == &L)
1449 return AR->getStepRecurrence(*SE);
1450 return nullptr;
1451 };
1452
1453 const SCEV *BaseStep = GetStepForPointer(Member0);
1454 if (!BaseStep)
1455 continue;
1456
1457 // Verify all members have the same access range (End - Start). The
1458 // merged upper bound is a umax over the members' own End values. The
1459 // same decompositions order both the Start and the End values
1460 // only when End = Start + Range with one shared Range for every member.
1461 // That is what this check enforces.
1462 // Compare each member's range (End - Start) and test Range - BaseRange ==
1463 // 0, rather than Range == BaseRange, so algebraically equal but
1464 // non-identical SCEVs still match. Bail out if any subtraction produces
1465 // SCEVCouldNotCompute.
1466 const SCEV *BaseRange = SE->getMinusSCEV(BaseHigh, BaseLow);
1467 if (isa<SCEVCouldNotCompute>(BaseRange)) {
1468 LLVM_DEBUG(dbgs() << "LAA: Base access range not computable, "
1469 "skipping DepSet\n");
1470 continue;
1471 }
1472 if (any_of(drop_begin(AllMembers), [&](unsigned Idx) {
1473 const SCEV *Range =
1474 SE->getMinusSCEV(Pointers[Idx].End, Pointers[Idx].Start);
1476 return true;
1477 if (Range == BaseRange)
1478 return false;
1479 const SCEV *RangeDiff = SE->getMinusSCEV(Range, BaseRange);
1480 return isa<SCEVCouldNotCompute>(RangeDiff) || !RangeDiff->isZero();
1481 })) {
1482 LLVM_DEBUG(
1483 dbgs() << "LAA: Member with different or not computable access "
1484 "range, skipping DepSet\n");
1485 continue;
1486 }
1487
1488 // Require all members to have the same recurrence step. Equal ranges
1489 // (checked above) are what the merged bounds actually need, and a different
1490 // step usually means a different range. But ranges can be equal by accident
1491 // - e.g. an invariant access whose range matches the stride, or a loop with
1492 // a single iteration. The base member is picked arbitrarily, so together
1493 // with the BaseStep check above this keeps the decision the same no matter
1494 // which member comes first: we only merge recurrences with one common step.
1495 if (any_of(drop_begin(AllMembers), [&](unsigned Idx) {
1496 return GetStepForPointer(Idx) != BaseStep;
1497 })) {
1498 LLVM_DEBUG(dbgs() << "LAA: Member with different step, "
1499 "skipping DepSet\n");
1500 continue;
1501 }
1502 // One decomposition per member, in AllMembers order. Each entry holds the
1503 // member's constant offset and its coefficient for each stride, all
1504 // relative to BaseLow.
1506 MemberOffsets.reserve(AllMembers.size());
1507 // The base member's offset from itself is zero: Constant 0, no strides.
1508 MemberOffsets.emplace_back();
1509 // Stride checks this DepSet needs if it is merged.
1510 StrideLimits LocalStrideLimits;
1511
1512 // Decompose one member's offset (relative to BaseLow) and append it to
1513 // MemberOffsets. Returns false if the offset is not in stencil form (so
1514 // the whole DepSet is skipped).
1515 const auto CollectOffset = [&](unsigned Idx) -> bool {
1516 const SCEV *LowOffset = SE->getMinusSCEV(Pointers[Idx].Start, BaseLow);
1517 if (isa<SCEVCouldNotCompute>(LowOffset))
1518 return false;
1519 auto DLow = decomposeStencilOffset(LowOffset, *SE, L);
1520 if (!DLow) {
1521 LLVM_DEBUG(dbgs() << "LAA: Member " << Idx
1522 << " NOT decomposable: " << *LowOffset << "\n");
1523 return false;
1524 }
1525 if (!collectStrideLimits(*DLow,
1526 SE->getTypeSizeInBits(LowOffset->getType()), *SE,
1527 LocalStrideLimits))
1528 return false;
1529
1530 LLVM_DEBUG(dbgs() << "LAA: Member " << Idx
1531 << ": Const=" << DLow->Constant
1532 << ", strides=" << DLow->Coefficients.size() << "\n");
1533 MemberOffsets.push_back(std::move(*DLow));
1534 return true;
1535 };
1536
1537 if (!all_of(drop_begin(AllMembers), CollectOffset))
1538 continue;
1539
1540 SmallVector<unsigned, 4> MinCandidates =
1541 collectCandidateMembers(MemberOffsets, /*ForMin=*/true);
1542 SmallVector<unsigned, 4> MaxCandidates =
1543 collectCandidateMembers(MemberOffsets, /*ForMin=*/false);
1544 assert(!MinCandidates.empty() && !MaxCandidates.empty() &&
1545 "a non-empty member list always has a candidate");
1546 LLVM_DEBUG(dbgs() << "LAA: Candidate members: min="
1547 << MinCandidates.size()
1548 << ", max=" << MaxCandidates.size() << " of "
1549 << MemberOffsets.size() << "\n");
1550
1551 // Extra bound operands: one compare-and-select per operand past the first
1552 // in the merged umin, and the same for the umax.
1553 unsigned NumBoundOperands =
1554 (MinCandidates.size() - 1) + (MaxCandidates.size() - 1);
1555
1556 // Local cost model: decide whether replacing this DepSet's groups with the
1557 // single merged group actually reduces the number of runtime checks. Run
1558 // it before building the merged bounds: a rejected DepSet then creates no
1559 // umin/umax expressions that would only be thrown away.
1560 auto [ChecksBefore, ChecksAfter] =
1561 computeStencilMergeCost(*this, GroupIndices, LocalStrideLimits,
1562 CommittedStrideLimits, NumBoundOperands);
1563 if (ChecksAfter >= ChecksBefore) {
1564 LLVM_DEBUG(dbgs() << "LAA: Not beneficial, skipping DepSet\n");
1565 continue;
1566 }
1567
1568 // Build one side of the merged bounds from its candidate members.
1569 // With one candidate the bound is that member's own Start (or End): the
1570 // exact value the member's own check used before the merge. With several
1571 // candidates the bound is a umin (umax) over their Starts (Ends). Either
1572 // way every value is a real member address, so the merge computes no new
1573 // address and no new overflow is possible.
1574 // The umin/umax are on pointers. The expander turns them into the same
1575 // icmp and select that a plain check uses, so no address conversion is
1576 // needed.
1577 const auto BuildBound = [&](ArrayRef<unsigned> Candidates, bool IsLow) {
1579 for (unsigned K : Candidates) {
1580 const PointerInfo &P = Pointers[AllMembers[K]];
1581 Ops.push_back(IsLow ? P.Start : P.End);
1582 }
1583 return IsLow ? SE->getUMinExpr(Ops) : SE->getUMaxExpr(Ops);
1584 };
1585
1586 const SCEV *MergedLow = BuildBound(MinCandidates, /*IsLow=*/true);
1587 const SCEV *MergedHigh = BuildBound(MaxCandidates, /*IsLow=*/false);
1588
1589 LLVM_DEBUG(dbgs() << "LAA: Merged bounds: Low=" << *MergedLow
1590 << ", High=" << *MergedHigh << "\n");
1591 LLVM_DEBUG(dbgs() << "LAA: Merging, net saving "
1592 << ChecksBefore - ChecksAfter << "\n");
1593
1594 NewMergedGroups.push_back(buildMergedStencilGroup(
1595 *this, AllMembers, MergedLow, MergedHigh, GroupIndices));
1596 CommittedStrideLimits.addFrom(LocalStrideLimits);
1597 MergedGroupIndices.insert(GroupIndices.begin(), GroupIndices.end());
1598 }
1599
1600 CommittedStrideLimits.addPredicates(DC.getPSE());
1601
1602 // Rebuild CheckingGroups if we merged anything.
1603 if (!NewMergedGroups.empty()) {
1605 for (unsigned I = 0; I < CheckingGroups.size(); ++I)
1606 if (!MergedGroupIndices.contains(I))
1607 FinalGroups.push_back(std::move(CheckingGroups[I]));
1608 FinalGroups.append(std::make_move_iterator(NewMergedGroups.begin()),
1609 std::make_move_iterator(NewMergedGroups.end()));
1610 CheckingGroups = std::move(FinalGroups);
1611
1612 LLVM_DEBUG(dbgs() << "LAA: After stencil merging: " << CheckingGroups.size()
1613 << " groups\n");
1614 }
1615}
1616
1618 const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
1619 unsigned PtrIdx2) {
1620 return (PtrToPartition[PtrIdx1] != -1 &&
1621 PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
1622}
1623
1624bool RuntimePointerChecking::needsChecking(unsigned I, unsigned J) const {
1625 const PointerInfo &PointerI = Pointers[I];
1626 const PointerInfo &PointerJ = Pointers[J];
1627
1628 // No need to check if two readonly pointers intersect.
1629 if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
1630 return false;
1631
1632 // Only need to check pointers between two different dependency sets.
1633 if (PointerI.DependencySetId == PointerJ.DependencySetId)
1634 return false;
1635
1636 // Only need to check pointers in the same alias set.
1637 return PointerI.AliasSetId == PointerJ.AliasSetId;
1638}
1639
1640/// Assign each RuntimeCheckingPtrGroup pointer an index for stable UTC output.
1644 for (const auto &[Idx, CG] : enumerate(CheckingGroups))
1645 PtrIndices[&CG] = Idx;
1646 return PtrIndices;
1647}
1648
1651 unsigned Depth) const {
1652 unsigned N = 0;
1653 auto PtrIndices = getPtrToIdxMap(CheckingGroups);
1654 for (const auto &[Check1, Check2] : Checks) {
1655 const auto &First = Check1->Members, &Second = Check2->Members;
1656 OS.indent(Depth) << "Check " << N++ << ":\n";
1657 OS.indent(Depth + 2) << "Comparing group GRP" << PtrIndices.at(Check1)
1658 << ":\n";
1659 for (unsigned K : First)
1660 OS.indent(Depth + 2) << *Pointers[K].PointerValue << "\n";
1661 OS.indent(Depth + 2) << "Against group GRP" << PtrIndices.at(Check2)
1662 << ":\n";
1663 for (unsigned K : Second)
1664 OS.indent(Depth + 2) << *Pointers[K].PointerValue << "\n";
1665 }
1666}
1667
1669
1670 OS.indent(Depth) << "Run-time memory checks:\n";
1671 printChecks(OS, Checks, Depth);
1672
1673 OS.indent(Depth) << "Grouped accesses:\n";
1674 auto PtrIndices = getPtrToIdxMap(CheckingGroups);
1675 for (const auto &CG : CheckingGroups) {
1676 OS.indent(Depth + 2) << "Group GRP" << PtrIndices.at(&CG) << ":\n";
1677 OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High
1678 << ")\n";
1679 for (unsigned Member : CG.Members) {
1680 OS.indent(Depth + 6) << "Member: " << *Pointers[Member].Expr << "\n";
1681 }
1682 }
1683}
1684
1685namespace {
1686
1687/// Analyses memory accesses in a loop.
1688///
1689/// Checks whether run time pointer checks are needed and builds sets for data
1690/// dependence checking.
1691class AccessAnalysis {
1692public:
1693 using MemAccessInfo =
1694 PointerIntPair<Value * /* AccessPtr */, 1, bool /* IsWrite */>;
1695
1696 AccessAnalysis(const Loop *TheLoop, AAResults *AA, const LoopInfo *LI,
1699 SmallPtrSetImpl<MDNode *> &LoopAliasScopes)
1700 : TheLoop(TheLoop), BAA(*AA), AST(BAA), LI(LI), DT(DT), DepCands(DA),
1701 PSE(PSE), LoopAliasScopes(LoopAliasScopes) {
1702 // We're analyzing dependences across loop iterations.
1703 BAA.enableCrossIterationMode();
1704 }
1705
1706 /// Register a load and whether it is only read from.
1707 void addLoad(const MemoryLocation &Loc, Type *AccessTy, bool IsReadOnly) {
1708 Value *Ptr = const_cast<Value *>(Loc.Ptr);
1709 AST.add(adjustLoc(Loc));
1710 Accesses[MemAccessInfo(Ptr, false)].insert(AccessTy);
1711 if (IsReadOnly)
1712 ReadOnlyPtr.insert(Ptr);
1713 }
1714
1715 /// Register a store.
1716 void addStore(const MemoryLocation &Loc, Type *AccessTy) {
1717 Value *Ptr = const_cast<Value *>(Loc.Ptr);
1718 AST.add(adjustLoc(Loc));
1719 Accesses[MemAccessInfo(Ptr, true)].insert(AccessTy);
1720 }
1721
1722 /// Check if we can emit a run-time no-alias check for \p Access.
1723 ///
1724 /// Returns true if we can emit a run-time no alias check for \p Access.
1725 /// If we can check this access, this also adds it to a dependence set and
1726 /// adds a run-time to check for it to \p RtCheck. If \p Assume is true,
1727 /// we will attempt to use additional run-time checks in order to get
1728 /// the bounds of the pointer.
1729 bool createCheckForAccess(RuntimePointerChecking &RtCheck,
1730 MemAccessInfo Access, Type *AccessTy,
1731 const SymbolicStrideMap &Strides,
1732 DenseMap<Value *, unsigned> &DepSetId,
1733 Loop *TheLoop, unsigned &RunningDepId,
1734 unsigned ASId, bool Assume);
1735
1736 /// Check whether we can check the pointers at runtime for
1737 /// non-intersection.
1738 ///
1739 /// Returns true if we need no check or if we do and we can generate them
1740 /// (i.e. the pointers have computable bounds). A return value of false means
1741 /// we couldn't analyze and generate runtime checks for all pointers in the
1742 /// loop, but if \p AllowPartial is set then we will have checks for those
1743 /// pointers we could analyze. \p DepChecker is used to remove unknown
1744 /// dependences from DepCands.
1745 bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, Loop *TheLoop,
1746 const SymbolicStrideMap &Strides,
1747 Value *&UncomputablePtr, bool AllowPartial,
1748 const MemoryDepChecker &DepChecker);
1749
1750 /// Goes over all memory accesses, checks whether a RT check is needed
1751 /// and builds sets of dependent accesses.
1752 void buildDependenceSets();
1753
1754 /// Initial processing of memory accesses determined that we need to
1755 /// perform dependency checking.
1756 ///
1757 /// Note that this can later be cleared if we retry memcheck analysis without
1758 /// dependency checking (i.e. ShouldRetryWithRuntimeChecks).
1759 bool isDependencyCheckNeeded() const { return !CheckDeps.empty(); }
1760
1761 /// We decided that no dependence analysis would be used. Reset the state.
1762 void resetDepChecks(MemoryDepChecker &DepChecker) {
1763 CheckDeps.clear();
1764 DepChecker.clearDependences();
1765 }
1766
1767 ArrayRef<MemAccessInfo> getDependenciesToCheck() const { return CheckDeps; }
1768
1769private:
1770 using PtrAccessMap = MapVector<MemAccessInfo, SmallSetVector<Type *, 1>>;
1771
1772 /// Adjust the MemoryLocation so that it represents accesses to this
1773 /// location across all iterations, rather than a single one.
1774 MemoryLocation adjustLoc(MemoryLocation Loc) const {
1775 // The accessed location varies within the loop, but remains within the
1776 // underlying object.
1778 Loc.AATags.Scope = adjustAliasScopeList(Loc.AATags.Scope);
1779 Loc.AATags.NoAlias = adjustAliasScopeList(Loc.AATags.NoAlias);
1780 return Loc;
1781 }
1782
1783 /// Drop alias scopes that are only valid within a single loop iteration.
1784 MDNode *adjustAliasScopeList(MDNode *ScopeList) const {
1785 if (!ScopeList)
1786 return nullptr;
1787
1788 // For the sake of simplicity, drop the whole scope list if any scope is
1789 // iteration-local.
1790 if (any_of(ScopeList->operands(), [&](Metadata *Scope) {
1791 return LoopAliasScopes.contains(cast<MDNode>(Scope));
1792 }))
1793 return nullptr;
1794
1795 return ScopeList;
1796 }
1797
1798 /// Map of all accesses. Values are the types used to access memory pointed to
1799 /// by the pointer.
1800 PtrAccessMap Accesses;
1801
1802 /// The loop being checked.
1803 const Loop *TheLoop;
1804
1805 /// List of accesses that need a further dependence check.
1807
1808 /// Set of pointers that are read only.
1809 SmallPtrSet<Value*, 16> ReadOnlyPtr;
1810
1811 /// Batched alias analysis results.
1812 BatchAAResults BAA;
1813
1814 /// An alias set tracker to partition the access set by underlying object and
1815 //intrinsic property (such as TBAA metadata).
1816 AliasSetTracker AST;
1817
1818 /// The LoopInfo of the loop being checked.
1819 const LoopInfo *LI;
1820
1821 /// The dominator tree of the function.
1822 DominatorTree &DT;
1823
1824 /// Sets of potentially dependent accesses - members of one set share an
1825 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
1826 /// dependence check.
1828
1829 /// Initial processing of memory accesses determined that we may need
1830 /// to add memchecks. Perform the analysis to determine the necessary checks.
1831 ///
1832 /// Note that, this is different from isDependencyCheckNeeded. When we retry
1833 /// memcheck analysis without dependency checking
1834 /// (i.e. ShouldRetryWithRuntimeChecks), isDependencyCheckNeeded is
1835 /// cleared while this remains set if we have potentially dependent accesses.
1836 bool IsRTCheckAnalysisNeeded = false;
1837
1838 /// The SCEV predicate containing all the SCEV-related assumptions.
1839 PredicatedScalarEvolution &PSE;
1840
1841 DenseMap<Value *, SmallVector<const Value *, 16>> UnderlyingObjects;
1842
1843 /// Alias scopes that are declared inside the loop, and as such not valid
1844 /// across iterations.
1845 SmallPtrSetImpl<MDNode *> &LoopAliasScopes;
1846};
1847
1848} // end anonymous namespace
1849
1850std::optional<int64_t>
1852 Type *AccessTy, Value *Ptr,
1854 if (isa<ScalableVectorType>(AccessTy)) {
1855 LLVM_DEBUG(dbgs() << "LAA: Bad stride - Scalable object: " << *AccessTy
1856 << "\n");
1857 return std::nullopt;
1858 }
1859
1860 // The access function must stride over the innermost loop.
1861 if (Lp != AR->getLoop()) {
1862 LLVM_DEBUG({
1863 dbgs() << "LAA: Bad stride - Not striding over innermost loop ";
1864 if (Ptr)
1865 dbgs() << *Ptr << " ";
1866
1867 dbgs() << "SCEV: " << *AR << "\n";
1868 });
1869 return std::nullopt;
1870 }
1871
1872 // Check the step is constant.
1873 const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
1874
1875 // Calculate the pointer stride and check if it is constant.
1876 const APInt *APStepVal;
1877 if (!match(Step, m_scev_APInt(APStepVal))) {
1878 LLVM_DEBUG({
1879 dbgs() << "LAA: Bad stride - Not a constant strided ";
1880 if (Ptr)
1881 dbgs() << *Ptr << " ";
1882 dbgs() << "SCEV: " << *AR << "\n";
1883 });
1884 return std::nullopt;
1885 }
1886
1887 const auto &DL = Lp->getHeader()->getDataLayout();
1888 TypeSize AllocSize = DL.getTypeAllocSize(AccessTy);
1889 int64_t Size = AllocSize.getFixedValue();
1890
1891 // Huge step value - give up.
1892 std::optional<int64_t> StepVal = APStepVal->trySExtValue();
1893 if (!StepVal)
1894 return std::nullopt;
1895
1896 // Strided access.
1897 return *StepVal % Size ? std::nullopt : std::make_optional(*StepVal / Size);
1898}
1899
1900/// Check whether \p AR is a non-wrapping AddRec. If \p Ptr is not nullptr, use
1901/// information from the IR pointer value to determine no-wrap. If \p Predicates
1902/// is not nullptr add no-wrap assumptions if needed.
1903static bool
1905 Type *AccessTy, const Loop *L, const DominatorTree &DT,
1906 std::optional<int64_t> Stride = std::nullopt,
1907 SmallVectorImpl<const SCEVPredicate *> *Predicates = nullptr) {
1908 // FIXME: This should probably only return true for NUW.
1909 if (any(AR->getNoWrapFlags()))
1910 return true;
1911
1912 // An nusw getelementptr that is an AddRec cannot wrap. If it would wrap,
1913 // the distance between the previously accessed location and the wrapped
1914 // location will be larger than half the pointer index type space. In that
1915 // case, the GEP would be poison and any memory access dependent on it would
1916 // be immediate UB when executed.
1918 GEP && GEP->hasNoUnsignedSignedWrap()) {
1919 // For the above reasoning to apply, the pointer must be dereferenced in
1920 // every iteration.
1921 if (L->getHeader() == L->getLoopLatch() ||
1922 any_of(GEP->users(), [L, &DT, GEP](User *U) {
1923 if (getLoadStorePointerOperand(U) != GEP)
1924 return false;
1925 BasicBlock *UserBB = cast<Instruction>(U)->getParent();
1926 if (!L->contains(UserBB))
1927 return false;
1928 return !LoopAccessInfo::blockNeedsPredication(UserBB, L, &DT);
1929 }))
1930 return true;
1931 }
1932
1933 if (!Stride)
1934 Stride = getStrideFromAddRec(AR, L, AccessTy, Ptr, PSE);
1935 if (Stride) {
1936 // If the null pointer is undefined, then a access sequence which would
1937 // otherwise access it can be assumed not to unsigned wrap. Note that this
1938 // assumes the object in memory is aligned to the natural alignment.
1939 unsigned AddrSpace = AR->getType()->getPointerAddressSpace();
1940 if (!NullPointerIsDefined(L->getHeader()->getParent(), AddrSpace) &&
1941 (Stride == 1 || Stride == -1))
1942 return true;
1943 }
1944
1945 ScalarEvolution &SE = *PSE.getSE();
1946 const SCEVPredicate *WrapPred =
1948 if (Ptr && Predicates) {
1949 Predicates->push_back(WrapPred);
1950 LLVM_DEBUG(dbgs() << "LAA: Pointer may wrap:\n"
1951 << "LAA: Pointer: " << *Ptr << "\n"
1952 << "LAA: SCEV: " << *AR << "\n"
1953 << "LAA: Added an overflow assumption\n");
1954 return true;
1955 }
1956
1957 // Without adding a new predicate, AR may still be known not to wrap if the
1958 // predicates of PSE already imply it, e.g. because a wrap predicate for AR
1959 // was added while analyzing the dependences of the loop.
1960 return PSE.getPredicate().implies(WrapPred, SE);
1961}
1962
1963static void visitPointers(Value *StartPtr, const Loop &InnermostLoop,
1964 function_ref<void(Value *)> AddPointer) {
1966 SmallVector<Value *> WorkList;
1967 WorkList.push_back(StartPtr);
1968
1969 while (!WorkList.empty()) {
1970 Value *Ptr = WorkList.pop_back_val();
1971 if (!Visited.insert(Ptr).second)
1972 continue;
1973 auto *PN = dyn_cast<PHINode>(Ptr);
1974 // SCEV does not look through non-header PHIs inside the loop. Such phis
1975 // can be analyzed by adding separate accesses for each incoming pointer
1976 // value.
1977 if (PN && InnermostLoop.contains(PN->getParent()) &&
1978 PN->getParent() != InnermostLoop.getHeader()) {
1979 llvm::append_range(WorkList, PN->incoming_values());
1980 } else
1981 AddPointer(Ptr);
1982 }
1983}
1984
1985// Walk back through the IR for a pointer, looking for a select like the
1986// following:
1987//
1988// %offset = select i1 %cmp, i64 %a, i64 %b
1989// %addr = getelementptr double, double* %base, i64 %offset
1990// %ld = load double, double* %addr, align 8
1991//
1992// We won't be able to form a single SCEVAddRecExpr from this since the
1993// address for each loop iteration depends on %cmp. We could potentially
1994// produce multiple valid SCEVAddRecExprs, though, and check all of them for
1995// memory safety/aliasing if needed.
1996//
1997// If we encounter some IR we don't yet handle, or something obviously fine
1998// like a constant, then we just add the SCEV for that term to the list passed
1999// in by the caller. If we have a node that may potentially yield a valid
2000// SCEVAddRecExpr then we decompose it into parts and build the SCEV terms
2001// ourselves before adding to the list.
2003 ScalarEvolution *SE, const Loop *L, Value *Ptr,
2005 unsigned Depth) {
2006 // If our Value is a SCEVAddRecExpr, loop invariant, not an instruction, or
2007 // we've exceeded our limit on recursion, just return whatever we have
2008 // regardless of whether it can be used for a forked pointer or not, along
2009 // with an indication of whether it might be a poison or undef value.
2010 const SCEV *Scev = SE->getSCEV(Ptr);
2011 if (isa<SCEVAddRecExpr>(Scev) || L->isLoopInvariant(Ptr) ||
2012 !isa<Instruction>(Ptr) || Depth == 0) {
2013 ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
2014 return;
2015 }
2016
2017 Depth--;
2018
2019 auto UndefPoisonCheck = [](PointerIntPair<const SCEV *, 1, bool> S) {
2020 return get<1>(S);
2021 };
2022
2023 auto GetBinOpExpr = [&SE](unsigned Opcode, const SCEV *L,
2024 const SCEV *R) -> const SCEV * {
2025 switch (Opcode) {
2026 case Instruction::Add:
2027 return SE->getAddExpr(L, R);
2028 case Instruction::Sub:
2029 return SE->getMinusSCEV(L, R);
2030 default:
2031 llvm_unreachable("Unexpected binary operator when walking ForkedPtrs");
2032 }
2033 };
2034
2036 unsigned Opcode = I->getOpcode();
2037 switch (Opcode) {
2038 case Instruction::GetElementPtr: {
2039 auto *GEP = cast<GetElementPtrInst>(I);
2040 Type *SourceTy = GEP->getSourceElementType();
2041 // We only handle base + single offset GEPs here for now.
2042 // Not dealing with preexisting gathers yet, so no vectors.
2043 if (I->getNumOperands() != 2 || SourceTy->isVectorTy()) {
2044 ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(GEP));
2045 break;
2046 }
2049 findForkedSCEVs(SE, L, I->getOperand(0), BaseScevs, Depth);
2050 findForkedSCEVs(SE, L, I->getOperand(1), OffsetScevs, Depth);
2051
2052 // See if we need to freeze our fork...
2053 bool NeedsFreeze = any_of(BaseScevs, UndefPoisonCheck) ||
2054 any_of(OffsetScevs, UndefPoisonCheck);
2055
2056 // Check that we only have a single fork, on either the base or the offset.
2057 // Copy the SCEV across for the one without a fork in order to generate
2058 // the full SCEV for both sides of the GEP.
2059 if (OffsetScevs.size() == 2 && BaseScevs.size() == 1)
2060 BaseScevs.push_back(BaseScevs[0]);
2061 else if (BaseScevs.size() == 2 && OffsetScevs.size() == 1)
2062 OffsetScevs.push_back(OffsetScevs[0]);
2063 else {
2064 ScevList.emplace_back(Scev, NeedsFreeze);
2065 break;
2066 }
2067
2068 Type *IntPtrTy = SE->getEffectiveSCEVType(GEP->getPointerOperandType());
2069
2070 // Find the size of the type being pointed to. We only have a single
2071 // index term (guarded above) so we don't need to index into arrays or
2072 // structures, just get the size of the scalar value.
2073 const SCEV *Size = SE->getSizeOfExpr(IntPtrTy, SourceTy);
2074
2075 for (auto [B, O] : zip(BaseScevs, OffsetScevs)) {
2076 const SCEV *Base = get<0>(B);
2077 const SCEV *Offset = get<0>(O);
2078
2079 // Scale up the offsets by the size of the type, then add to the bases.
2080 const SCEV *Scaled =
2082 ScevList.emplace_back(SE->getAddExpr(Base, Scaled), NeedsFreeze);
2083 }
2084 break;
2085 }
2086 case Instruction::Select: {
2088 // A select means we've found a forked pointer, but we currently only
2089 // support a single select per pointer so if there's another behind this
2090 // then we just bail out and return the generic SCEV.
2091 findForkedSCEVs(SE, L, I->getOperand(1), ChildScevs, Depth);
2092 findForkedSCEVs(SE, L, I->getOperand(2), ChildScevs, Depth);
2093 if (ChildScevs.size() == 2)
2094 append_range(ScevList, ChildScevs);
2095 else
2096 ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
2097 break;
2098 }
2099 case Instruction::PHI: {
2101 // A phi means we've found a forked pointer, but we currently only
2102 // support a single phi per pointer so if there's another behind this
2103 // then we just bail out and return the generic SCEV.
2104 if (I->getNumOperands() == 2) {
2105 findForkedSCEVs(SE, L, I->getOperand(0), ChildScevs, Depth);
2106 findForkedSCEVs(SE, L, I->getOperand(1), ChildScevs, Depth);
2107 }
2108 if (ChildScevs.size() == 2)
2109 append_range(ScevList, ChildScevs);
2110 else
2111 ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
2112 break;
2113 }
2114 case Instruction::Add:
2115 case Instruction::Sub: {
2118 findForkedSCEVs(SE, L, I->getOperand(0), LScevs, Depth);
2119 findForkedSCEVs(SE, L, I->getOperand(1), RScevs, Depth);
2120
2121 // See if we need to freeze our fork...
2122 bool NeedsFreeze =
2123 any_of(LScevs, UndefPoisonCheck) || any_of(RScevs, UndefPoisonCheck);
2124
2125 // Check that we only have a single fork, on either the left or right side.
2126 // Copy the SCEV across for the one without a fork in order to generate
2127 // the full SCEV for both sides of the BinOp.
2128 if (LScevs.size() == 2 && RScevs.size() == 1)
2129 RScevs.push_back(RScevs[0]);
2130 else if (RScevs.size() == 2 && LScevs.size() == 1)
2131 LScevs.push_back(LScevs[0]);
2132 else {
2133 ScevList.emplace_back(Scev, NeedsFreeze);
2134 break;
2135 }
2136
2137 for (auto [L, R] : zip(LScevs, RScevs))
2138 ScevList.emplace_back(GetBinOpExpr(Opcode, get<0>(L), get<0>(R)),
2139 NeedsFreeze);
2140 break;
2141 }
2142 default:
2143 // Just return the current SCEV if we haven't handled the instruction yet.
2144 LLVM_DEBUG(dbgs() << "ForkedPtr unhandled instruction: " << *I << "\n");
2145 ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
2146 break;
2147 }
2148}
2149
2150bool AccessAnalysis::createCheckForAccess(RuntimePointerChecking &RtCheck,
2151 MemAccessInfo Access, Type *AccessTy,
2152 const SymbolicStrideMap &StridesMap,
2154 Loop *TheLoop, unsigned &RunningDepId,
2155 unsigned ASId, bool Assume) {
2156 Value *Ptr = Access.getPointer();
2157 ScalarEvolution *SE = PSE.getSE();
2158 const DataLayout &DL = TheLoop->getHeader()->getDataLayout();
2159 assert(SE->isSCEVable(Ptr->getType()) && "Value is not SCEVable!");
2160
2162 findForkedSCEVs(SE, TheLoop, Ptr, RTCheckPtrs, MaxForkedSCEVDepth);
2163 assert(!RTCheckPtrs.empty() &&
2164 "Must have some runtime-check pointer candidates");
2165
2166 // RTCheckPtrs must have size 2 if there are forked pointers. Otherwise, there
2167 // are no forked pointers; replaceSymbolicStridesSCEV in this case.
2168 auto IsLoopInvariantOrAR =
2169 [&SE, &TheLoop](const PointerIntPair<const SCEV *, 1, bool> &P) {
2170 return SE->isLoopInvariant(P.getPointer(), TheLoop) ||
2171 isa<SCEVAddRecExpr>(P.getPointer());
2172 };
2173 if (RTCheckPtrs.size() == 2 && all_of(RTCheckPtrs, IsLoopInvariantOrAR)) {
2174 LLVM_DEBUG(dbgs() << "LAA: Found forked pointer: " << *Ptr << "\n";
2175 for (const auto &[Idx, Q] : enumerate(RTCheckPtrs)) dbgs()
2176 << "\t(" << Idx << ") " << *Q.getPointer() << "\n");
2177 } else {
2178 RTCheckPtrs = {
2179 {replaceSymbolicStrideSCEV(PSE, TheLoop, StridesMap, Ptr), false}};
2180 }
2181
2182 /// Check whether all pointers can participate in a runtime bounds check. They
2183 /// must either be invariant or non-wrapping affine AddRecs.
2185 for (auto &P : RTCheckPtrs) {
2186 // The bounds for loop-invariant pointer is trivial.
2187 if (SE->isLoopInvariant(P.getPointer(), TheLoop))
2188 continue;
2189
2190 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(P.getPointer());
2191 if (!AR && Assume)
2192 AR = PSE.getAsAddRec(Ptr, &Predicates);
2193 if (!AR || !AR->isAffine()) {
2194 // Check if bounds for non-affine monotonic expressions can be formed.
2195 const SCEV *EltSizeSCEV = SE->getStoreSizeOfExpr(
2196 DL.getIndexType(P.getPointer()->getType()), AccessTy);
2197 if (!Assume ||
2198 !getNonAffineMonotonicBounds(TheLoop, P.getPointer(), EltSizeSCEV, SE)
2199 .first)
2200 return false;
2201 continue;
2202 }
2203
2204 // If there's only one option for Ptr, commit the predicates collected by
2205 // getAsAddRec and look Ptr up again afterwards: the lookup below reads the
2206 // assumptions back from PSE, so they need to be committed first.
2207 if (RTCheckPtrs.size() == 1) {
2208 PSE.addPredicates(Predicates);
2209 Predicates.clear();
2210 if (auto *StrideAR = dyn_cast<SCEVAddRecExpr>(
2211 replaceSymbolicStrideSCEV(PSE, TheLoop, StridesMap, Ptr)))
2212 AR = StrideAR;
2213 P.setPointer(AR);
2214 }
2215
2216 if (!isNoWrap(PSE, AR, RTCheckPtrs.size() == 1 ? Ptr : nullptr, AccessTy,
2217 TheLoop, DT, /*Stride=*/std::nullopt,
2218 Assume ? &Predicates : nullptr))
2219 return false;
2220 }
2221 PSE.addPredicates(Predicates);
2222
2223 // Remember the number of pointers inserted so far, to remove the pointers of
2224 // this access again if the bounds of any of them cannot be computed, to avoid
2225 // partial inserts.
2226 unsigned NumPointers = RtCheck.Pointers.size();
2227 for (const auto &[PtrExpr, NeedsFreeze] : RTCheckPtrs) {
2228 // The id of the dependence set.
2229 unsigned DepId;
2230
2231 if (DepCands.contains(Access)) {
2232 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
2233 unsigned &LeaderId = DepSetId[Leader];
2234 if (!LeaderId)
2235 LeaderId = RunningDepId++;
2236 DepId = LeaderId;
2237 } else
2238 // Each access has its own dependence set.
2239 DepId = RunningDepId++;
2240
2241 bool IsWrite = Access.getInt();
2242 if (!RtCheck.insert(TheLoop, Ptr, PtrExpr, AccessTy, IsWrite, DepId, ASId,
2243 PSE, NeedsFreeze,
2244 /*IsForked=*/RTCheckPtrs.size() > 1)) {
2245 RtCheck.Pointers.truncate(NumPointers);
2246 return false;
2247 }
2248 LLVM_DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
2249 }
2250
2251 return true;
2252}
2253
2254bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
2255 Loop *TheLoop,
2256 const SymbolicStrideMap &StridesMap,
2257 Value *&UncomputablePtr, bool AllowPartial,
2258 const MemoryDepChecker &DepChecker) {
2259 // Find pointers with computable bounds. We are going to use this information
2260 // to place a runtime bound check.
2261 bool CanDoRT = true;
2262
2263 bool MayNeedRTCheck = false;
2264 if (!IsRTCheckAnalysisNeeded) return true;
2265
2266 if (auto *Deps = DepChecker.getDependences()) {
2267 // If there are unknown dependences, this means runtime checks are needed to
2268 // ensure there's no overlap between accesses to the same underlying object.
2269 // Remove the equivalence classes containing both source and destination
2270 // accesses from DepCands. This ensures runtime checks will be generated
2271 // between those accesses and prevents them from being grouped together.
2272 for (const auto &Dep : *Deps) {
2273 if (Dep.Type != MemoryDepChecker::Dependence::Unknown) {
2276 "Should only skip safe dependences");
2277 continue;
2278 }
2279 Instruction *Src = Dep.getSource(DepChecker);
2280 Instruction *Dst = Dep.getDestination(DepChecker);
2281 DepCands.eraseClass({getPointerOperand(Src), Src->mayWriteToMemory()});
2282 DepCands.eraseClass({getPointerOperand(Dst), Dst->mayWriteToMemory()});
2283 }
2284 } else {
2285 CheckDeps.clear();
2286 DepCands = {};
2287 }
2288
2289 // We assign a consecutive id to access from different alias sets.
2290 // Accesses between different groups doesn't need to be checked.
2291 unsigned ASId = 0;
2292 for (const auto &AS : AST) {
2293 int NumReadPtrChecks = 0;
2294 int NumWritePtrChecks = 0;
2295 bool CanDoAliasSetRT = true;
2296 ++ASId;
2297 auto ASPointers = AS.getPointers();
2298
2299 // We assign consecutive id to access from different dependence sets.
2300 // Accesses within the same set don't need a runtime check.
2301 unsigned RunningDepId = 1;
2303
2305
2306 // First, count how many write and read accesses are in the alias set. Also
2307 // collect MemAccessInfos for later.
2309 for (const Value *ConstPtr : ASPointers) {
2310 Value *Ptr = const_cast<Value *>(ConstPtr);
2311 bool IsWrite = Accesses.contains(MemAccessInfo(Ptr, true));
2312 if (IsWrite)
2313 ++NumWritePtrChecks;
2314 else
2315 ++NumReadPtrChecks;
2316 AccessInfos.emplace_back(Ptr, IsWrite);
2317 }
2318
2319 // We do not need runtime checks for this alias set, if there are no writes
2320 // or a single write and no reads.
2321 if (NumWritePtrChecks == 0 ||
2322 (NumWritePtrChecks == 1 && NumReadPtrChecks == 0)) {
2323 assert((ASPointers.size() <= 1 ||
2324 all_of(ASPointers,
2325 [this](const Value *Ptr) {
2326 MemAccessInfo AccessWrite(const_cast<Value *>(Ptr),
2327 true);
2328 return !DepCands.contains(AccessWrite);
2329 })) &&
2330 "Can only skip updating CanDoRT below, if all entries in AS "
2331 "are reads or there is at most 1 entry");
2332 continue;
2333 }
2334
2335 for (auto &Access : AccessInfos) {
2336 for (const auto &AccessTy : Accesses[Access]) {
2337 if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap,
2338 DepSetId, TheLoop, RunningDepId, ASId,
2339 false)) {
2340 LLVM_DEBUG(dbgs() << "LAA: Can't find bounds for ptr:"
2341 << *Access.getPointer() << '\n');
2342 Retries.emplace_back(Access, AccessTy);
2343 CanDoAliasSetRT = false;
2344 }
2345 }
2346 }
2347
2348 // Note that this function computes CanDoRT and MayNeedRTCheck
2349 // independently. For example CanDoRT=false, MayNeedRTCheck=false means that
2350 // we have a pointer for which we couldn't find the bounds but we don't
2351 // actually need to emit any checks so it does not matter.
2352 //
2353 // We need runtime checks for this alias set, if there are at least 2
2354 // dependence sets (in which case RunningDepId > 2) or if we need to re-try
2355 // any bound checks (because in that case the number of dependence sets is
2356 // incomplete).
2357 bool NeedsAliasSetRTCheck = RunningDepId > 2 || !Retries.empty();
2358
2359 // We need to perform run-time alias checks, but some pointers had bounds
2360 // that couldn't be checked.
2361 if (NeedsAliasSetRTCheck && !CanDoAliasSetRT) {
2362 // Reset the CanDoSetRt flag and retry all accesses that have failed.
2363 // We know that we need these checks, so we can now be more aggressive
2364 // and add further checks if required (overflow checks).
2365 CanDoAliasSetRT = true;
2366 for (const auto &[Access, AccessTy] : Retries) {
2367 if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap,
2368 DepSetId, TheLoop, RunningDepId, ASId,
2369 /*Assume=*/true)) {
2370 CanDoAliasSetRT = false;
2371 UncomputablePtr = Access.getPointer();
2372 if (!AllowPartial)
2373 break;
2374 }
2375 }
2376 }
2377
2378 CanDoRT &= CanDoAliasSetRT;
2379 MayNeedRTCheck |= NeedsAliasSetRTCheck;
2380 ++ASId;
2381 }
2382
2383 // If the pointers that we would use for the bounds comparison have different
2384 // address spaces, assume the values aren't directly comparable, so we can't
2385 // use them for the runtime check. We also have to assume they could
2386 // overlap. In the future there should be metadata for whether address spaces
2387 // are disjoint.
2388 unsigned NumPointers = RtCheck.Pointers.size();
2389 for (unsigned i = 0; i < NumPointers; ++i) {
2390 for (unsigned j = i + 1; j < NumPointers; ++j) {
2391 // Only need to check pointers between two different dependency sets.
2392 if (RtCheck.Pointers[i].DependencySetId ==
2393 RtCheck.Pointers[j].DependencySetId)
2394 continue;
2395 // Only need to check pointers in the same alias set.
2396 if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
2397 continue;
2398
2399 Value *PtrI = RtCheck.Pointers[i].PointerValue;
2400 Value *PtrJ = RtCheck.Pointers[j].PointerValue;
2401
2402 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
2403 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
2404 if (ASi != ASj) {
2405 LLVM_DEBUG(
2406 dbgs() << "LAA: Runtime check would require comparison between"
2407 " different address spaces\n");
2408 return false;
2409 }
2410 }
2411 }
2412
2413 if (MayNeedRTCheck && (CanDoRT || AllowPartial))
2414 RtCheck.generateChecks(DepCands);
2415
2416 LLVM_DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks()
2417 << " pointer comparisons.\n");
2418
2419 // If we can do run-time checks, but there are no checks, no runtime checks
2420 // are needed. This can happen when all pointers point to the same underlying
2421 // object for example.
2422 RtCheck.Need = CanDoRT ? RtCheck.getNumberOfChecks() != 0 : MayNeedRTCheck;
2423
2424 bool CanDoRTIfNeeded = !RtCheck.Need || CanDoRT;
2425 assert(CanDoRTIfNeeded == (CanDoRT || !MayNeedRTCheck) &&
2426 "CanDoRTIfNeeded depends on RtCheck.Need");
2427 if (!CanDoRTIfNeeded && !AllowPartial)
2428 RtCheck.reset();
2429 return CanDoRTIfNeeded;
2430}
2431
2432void AccessAnalysis::buildDependenceSets() {
2433 // We process the set twice: first we process read-write pointers, last we
2434 // process read-only pointers. This allows us to skip dependence tests for
2435 // read-only pointers.
2436
2437 LLVM_DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
2438 LLVM_DEBUG(dbgs() << " AST: "; AST.dump());
2439 LLVM_DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n");
2440 LLVM_DEBUG({
2441 for (const auto &[A, _] : Accesses)
2442 dbgs() << "\t" << *A.getPointer() << " ("
2443 << (A.getInt()
2444 ? "write"
2445 : (ReadOnlyPtr.contains(A.getPointer()) ? "read-only"
2446 : "read"))
2447 << ")\n";
2448 });
2449
2450 // The AliasSetTracker has nicely partitioned our pointers by metadata
2451 // compatibility and potential for underlying-object overlap. As a result, we
2452 // only need to check for potential pointer dependencies within each alias
2453 // set.
2454 for (const auto &AS : AST) {
2455 bool AliasSetHasWrite = false;
2456
2457 // Map of (pointer to underlying objects, accessed address space) to last
2458 // access encountered.
2459 using UnderlyingObjToAccessMap =
2461 UnderlyingObjToAccessMap ObjToLastAccess;
2462
2463 // Set of access to check after all writes have been processed.
2464 PtrAccessMap DeferredAccesses;
2465
2466 // Iterate over each alias set twice, once to process read/write pointers,
2467 // and then to process read-only pointers.
2468
2469 auto ProcessAccesses = [&](bool UseDeferred) {
2470 PtrAccessMap &S = UseDeferred ? DeferredAccesses : Accesses;
2471
2472 // Note that both the alias-set tracker and the alias sets themselves used
2473 // ordered collections internally and so the iteration order here is
2474 // deterministic.
2475 for (const Value *ConstPtr : AS.getPointers()) {
2476 Value *Ptr = const_cast<Value *>(ConstPtr);
2477
2478 // For a single memory access in AliasSetTracker, Accesses may contain
2479 // both read and write, and they both need to be handled for CheckDeps.
2480 for (auto [AccessPtr, IsWrite] : S.keys()) {
2481 if (AccessPtr != Ptr)
2482 continue;
2483
2484 // If we're using the deferred access set, then it contains only
2485 // reads.
2486 bool IsReadOnlyPtr = ReadOnlyPtr.contains(Ptr) && !IsWrite;
2487 if (UseDeferred && !IsReadOnlyPtr)
2488 continue;
2489 // Otherwise, the pointer must be in the PtrAccessSet, either as a
2490 // read or a write.
2491 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
2492 S.contains(MemAccessInfo(Ptr, false))) &&
2493 "Alias-set pointer not in the access set?");
2494
2495 MemAccessInfo Access(Ptr, IsWrite);
2496 DepCands.insert(Access);
2497
2498 // Memorize read-only pointers for later processing and skip them in
2499 // the first round (they need to be checked after we have seen all
2500 // write pointers). Note: we also mark pointer that are not
2501 // consecutive as "read-only" pointers (so that we check
2502 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
2503 if (!UseDeferred && IsReadOnlyPtr) {
2504 // We only use the pointer keys, the types vector values don't
2505 // matter.
2506 DeferredAccesses.insert({Access, {}});
2507 continue;
2508 }
2509
2510 // If this is a write - check other reads and writes for conflicts. If
2511 // this is a read only check other writes for conflicts (but only if
2512 // there is no other write to the ptr - this is an optimization to
2513 // catch "a[i] = a[i] + " without having to do a dependence check).
2514 if ((IsWrite || IsReadOnlyPtr) && AliasSetHasWrite) {
2515 CheckDeps.push_back(Access);
2516 IsRTCheckAnalysisNeeded = true;
2517 }
2518
2519 if (IsWrite)
2520 AliasSetHasWrite = true;
2521
2522 // Create sets of pointers connected by a shared alias set and
2523 // underlying object.
2524 SmallVector<const Value *, 16> &UOs = UnderlyingObjects[Ptr];
2525 UOs = {};
2526 ::getUnderlyingObjects(Ptr, UOs, LI);
2528 << "Underlying objects for pointer " << *Ptr << "\n");
2529 for (const Value *UnderlyingObj : UOs) {
2530 // nullptr never alias, don't join sets for pointer that have "null"
2531 // in their UnderlyingObjects list.
2532 if (isa<ConstantPointerNull>(UnderlyingObj) &&
2534 TheLoop->getHeader()->getParent(),
2535 UnderlyingObj->getType()->getPointerAddressSpace()))
2536 continue;
2537
2538 auto [It, Inserted] = ObjToLastAccess.try_emplace(
2539 {UnderlyingObj,
2540 cast<PointerType>(Ptr->getType())->getAddressSpace()},
2541 Access);
2542 if (!Inserted) {
2543 DepCands.unionSets(Access, It->second);
2544 It->second = Access;
2545 }
2546
2547 LLVM_DEBUG(dbgs() << " " << *UnderlyingObj << "\n");
2548 }
2549 }
2550 }
2551 };
2552
2553 ProcessAccesses(false);
2554 ProcessAccesses(true);
2555 }
2556}
2557
2558/// Check whether the access through \p Ptr has a constant stride.
2559std::optional<int64_t>
2561 const Loop *Lp, const DominatorTree &DT,
2562 const SymbolicStrideMap &StridesMap, bool ShouldCheckWrap,
2564 const SCEV *PtrScev =
2565 replaceSymbolicStrideSCEV(PSE, Lp, StridesMap, Ptr, Predicates);
2566 if (PSE.getSE()->isLoopInvariant(PtrScev, Lp))
2567 return 0;
2568
2569 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
2570
2571 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
2572 if (Predicates && !AR) {
2573 AR = PSE.getSE()->convertSCEVToAddRecWithPredicates(PtrScev, Lp,
2574 *Predicates);
2575 }
2576
2577 if (!AR) {
2578 LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer " << *Ptr
2579 << " SCEV: " << *PtrScev << "\n");
2580 return std::nullopt;
2581 }
2582
2583 std::optional<int64_t> Stride =
2584 getStrideFromAddRec(AR, Lp, AccessTy, Ptr, PSE);
2585 if (!ShouldCheckWrap || !Stride)
2586 return Stride;
2587
2588 if (isNoWrap(PSE, AR, Ptr, AccessTy, Lp, DT, Stride, Predicates))
2589 return Stride;
2590
2591 LLVM_DEBUG(
2592 dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
2593 << *Ptr << " SCEV: " << *AR << "\n");
2594 return std::nullopt;
2595}
2596
2597std::optional<int64_t> llvm::getPointersDiff(Type *ElemTyA, Value *PtrA,
2598 Type *ElemTyB, Value *PtrB,
2599 const DataLayout &DL,
2600 ScalarEvolution &SE,
2601 bool StrictCheck, bool CheckType) {
2602 assert(PtrA && PtrB && "Expected non-nullptr pointers.");
2603
2604 // Make sure that A and B are different pointers.
2605 if (PtrA == PtrB)
2606 return 0;
2607
2608 // Make sure that the element types are the same if required.
2609 if (CheckType && ElemTyA != ElemTyB)
2610 return std::nullopt;
2611
2612 unsigned ASA = PtrA->getType()->getPointerAddressSpace();
2613 unsigned ASB = PtrB->getType()->getPointerAddressSpace();
2614
2615 // Check that the address spaces match.
2616 if (ASA != ASB)
2617 return std::nullopt;
2618 unsigned IdxWidth = DL.getIndexSizeInBits(ASA);
2619
2620 APInt OffsetA(IdxWidth, 0), OffsetB(IdxWidth, 0);
2621 const Value *PtrA1 = PtrA->stripAndAccumulateConstantOffsets(
2622 DL, OffsetA, /*AllowNonInbounds=*/true);
2623 const Value *PtrB1 = PtrB->stripAndAccumulateConstantOffsets(
2624 DL, OffsetB, /*AllowNonInbounds=*/true);
2625
2626 std::optional<int64_t> Val;
2627 if (PtrA1 == PtrB1) {
2628 // Retrieve the address space again as pointer stripping now tracks through
2629 // `addrspacecast`.
2630 ASA = cast<PointerType>(PtrA1->getType())->getAddressSpace();
2631 ASB = cast<PointerType>(PtrB1->getType())->getAddressSpace();
2632 // Check that the address spaces match and that the pointers are valid.
2633 if (ASA != ASB)
2634 return std::nullopt;
2635
2636 IdxWidth = DL.getIndexSizeInBits(ASA);
2637 OffsetA = OffsetA.sextOrTrunc(IdxWidth);
2638 OffsetB = OffsetB.sextOrTrunc(IdxWidth);
2639
2640 OffsetB -= OffsetA;
2641 Val = OffsetB.trySExtValue();
2642 } else {
2643 // Otherwise compute the distance with SCEV between the base pointers.
2644 const SCEV *PtrSCEVA = SE.getSCEV(PtrA);
2645 const SCEV *PtrSCEVB = SE.getSCEV(PtrB);
2646 std::optional<APInt> Diff =
2647 SE.computeConstantDifference(PtrSCEVB, PtrSCEVA);
2648 if (!Diff)
2649 return std::nullopt;
2650 Val = Diff->trySExtValue();
2651 }
2652
2653 if (!Val)
2654 return std::nullopt;
2655
2656 int64_t Size = DL.getTypeStoreSize(ElemTyA);
2657 int64_t Dist = *Val / Size;
2658
2659 // Ensure that the calculated distance matches the type-based one after all
2660 // the bitcasts removal in the provided pointers.
2661 if (!StrictCheck || Dist * Size == Val)
2662 return Dist;
2663 return std::nullopt;
2664}
2665
2667 const DataLayout &DL, ScalarEvolution &SE,
2668 SmallVectorImpl<unsigned> &SortedIndices) {
2670 VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&
2671 "Expected list of pointer operands.");
2672 // Walk over the pointers, and map each of them to an offset relative to
2673 // first pointer in the array.
2674 Value *Ptr0 = VL[0];
2675
2676 using DistOrdPair = std::pair<int64_t, unsigned>;
2677 auto Compare = llvm::less_first();
2678 std::set<DistOrdPair, decltype(Compare)> Offsets(Compare);
2679 Offsets.emplace(0, 0);
2680 bool IsConsecutive = true;
2681 for (auto [Idx, Ptr] : drop_begin(enumerate(VL))) {
2682 std::optional<int64_t> Diff =
2683 getPointersDiff(ElemTy, Ptr0, ElemTy, Ptr, DL, SE,
2684 /*StrictCheck=*/true);
2685 if (!Diff)
2686 return false;
2687
2688 // Check if the pointer with the same offset is found.
2689 int64_t Offset = *Diff;
2690 auto [It, IsInserted] = Offsets.emplace(Offset, Idx);
2691 if (!IsInserted)
2692 return false;
2693 // Consecutive order if the inserted element is the last one.
2694 IsConsecutive &= std::next(It) == Offsets.end();
2695 }
2696 SortedIndices.clear();
2697 if (!IsConsecutive) {
2698 // Fill SortedIndices array only if it is non-consecutive.
2699 SortedIndices.resize(VL.size());
2700 for (auto [Idx, Off] : enumerate(Offsets))
2701 SortedIndices[Idx] = Off.second;
2702 }
2703 return true;
2704}
2705
2706/// Returns true if the memory operations \p A and \p B are consecutive.
2708 ScalarEvolution &SE, bool CheckType) {
2711 if (!PtrA || !PtrB)
2712 return false;
2713 Type *ElemTyA = getLoadStoreType(A);
2714 Type *ElemTyB = getLoadStoreType(B);
2715 std::optional<int64_t> Diff =
2716 getPointersDiff(ElemTyA, PtrA, ElemTyB, PtrB, DL, SE,
2717 /*StrictCheck=*/true, CheckType);
2718 return Diff == 1;
2719}
2720
2722 visitPointers(SI->getPointerOperand(), *InnermostLoop,
2723 [this, SI](Value *Ptr) {
2724 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
2725 InstMap.push_back(SI);
2726 ++AccessIdx;
2727 });
2728}
2729
2731 visitPointers(LI->getPointerOperand(), *InnermostLoop,
2732 [this, LI](Value *Ptr) {
2733 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
2734 InstMap.push_back(LI);
2735 ++AccessIdx;
2736 });
2737}
2738
2758
2760 switch (Type) {
2761 case NoDep:
2762 case Forward:
2764 case Unknown:
2765 case IndirectUnsafe:
2766 case InvariantUnsafe:
2767 return false;
2768
2770 case Backward:
2772 return true;
2773 }
2774 llvm_unreachable("unexpected DepType!");
2775}
2776
2781
2783 switch (Type) {
2784 case Forward:
2786 return true;
2787
2788 case NoDep:
2789 case Unknown:
2791 case Backward:
2793 case IndirectUnsafe:
2794 case InvariantUnsafe:
2795 return false;
2796 }
2797 llvm_unreachable("unexpected DepType!");
2798}
2799
2800bool MemoryDepChecker::couldPreventStoreLoadForward(uint64_t Distance,
2801 uint64_t TypeByteSize,
2802 unsigned CommonStride) {
2803 // If loads occur at a distance that is not a multiple of a feasible vector
2804 // factor store-load forwarding does not take place.
2805 // Positive dependences might cause troubles because vectorizing them might
2806 // prevent store-load forwarding making vectorized code run a lot slower.
2807 // a[i] = a[i-3] ^ a[i-8];
2808 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
2809 // hence on your typical architecture store-load forwarding does not take
2810 // place. Vectorizing in such cases does not make sense.
2811 // Store-load forwarding distance.
2812
2813 // Maximum vector factor.
2814 uint64_t MaxVFWithoutSLForwardIssuesPowerOf2 =
2815 std::min(VectorizerParams::MaxVectorWidth * TypeByteSize,
2816 MaxStoreLoadForwardSafeDistanceInBits);
2817
2818 // Compute the smallest VF at which the store and load would be misaligned
2819 // and recent enough to still be in the store buffer.
2820 for (uint64_t VF = 2 * TypeByteSize;
2821 VF <= MaxVFWithoutSLForwardIssuesPowerOf2; VF *= 2) {
2822 if (isStoreLoadForwardingConflict(Distance, VF, TypeByteSize, VF)) {
2823 MaxVFWithoutSLForwardIssuesPowerOf2 = (VF >> 1);
2824 break;
2825 }
2826 }
2827
2828 if (MaxVFWithoutSLForwardIssuesPowerOf2 < 2 * TypeByteSize) {
2829 LLVM_DEBUG(
2830 dbgs() << "LAA: Distance " << Distance
2831 << " that could cause a store-load forwarding conflict\n");
2832 return true;
2833 }
2834
2835 if (CommonStride &&
2836 MaxVFWithoutSLForwardIssuesPowerOf2 <
2837 MaxStoreLoadForwardSafeDistanceInBits &&
2838 MaxVFWithoutSLForwardIssuesPowerOf2 !=
2839 VectorizerParams::MaxVectorWidth * TypeByteSize) {
2840 uint64_t MaxVF =
2841 bit_floor(MaxVFWithoutSLForwardIssuesPowerOf2 / CommonStride);
2842 uint64_t MaxVFInBits = MaxVF * TypeByteSize * 8;
2843 MaxStoreLoadForwardSafeDistanceInBits =
2844 std::min(MaxStoreLoadForwardSafeDistanceInBits, MaxVFInBits);
2845
2846 if (MaxVF < 2) {
2847 LLVM_DEBUG(
2848 dbgs() << "LAA: strided access with Distance " << Distance
2849 << " that could cause a store-load forwarding conflict\n");
2850 return true;
2851 }
2852 }
2853 return false;
2854}
2855
2856void MemoryDepChecker::mergeInStatus(VectorizationSafetyStatus S) {
2857 if (Status < S)
2858 Status = S;
2859}
2860
2861/// Given a dependence-distance \p Dist between two memory accesses, that have
2862/// strides in the same direction whose absolute value of the maximum stride is
2863/// given in \p MaxStride, in a loop whose maximum backedge taken count is \p
2864/// MaxBTC, check if it is possible to prove statically that the dependence
2865/// distance is larger than the range that the accesses will travel through the
2866/// execution of the loop. If so, return true; false otherwise. This is useful
2867/// for example in loops such as the following (PR31098):
2868///
2869/// for (i = 0; i < D; ++i) {
2870/// = out[i];
2871/// out[i+D] =
2872/// }
2874 const SCEV &MaxBTC, const SCEV &Dist,
2875 uint64_t MaxStride) {
2876
2877 // If we can prove that
2878 // (**) |Dist| > MaxBTC * Step
2879 // where Step is the absolute stride of the memory accesses in bytes,
2880 // then there is no dependence.
2881 //
2882 // Rationale:
2883 // We basically want to check if the absolute distance (|Dist/Step|)
2884 // is >= the loop iteration count (or > MaxBTC).
2885 // This is equivalent to the Strong SIV Test (Practical Dependence Testing,
2886 // Section 4.2.1); Note, that for vectorization it is sufficient to prove
2887 // that the dependence distance is >= VF; This is checked elsewhere.
2888 // But in some cases we can prune dependence distances early, and
2889 // even before selecting the VF, and without a runtime test, by comparing
2890 // the distance against the loop iteration count. Since the vectorized code
2891 // will be executed only if LoopCount >= VF, proving distance >= LoopCount
2892 // also guarantees that distance >= VF.
2893 //
2894 const SCEV *Step = SE.getConstant(MaxBTC.getType(), MaxStride);
2895 const SCEV *Product = SE.getMulExpr(&MaxBTC, Step);
2896
2897 const SCEV *CastedDist = &Dist;
2898 const SCEV *CastedProduct = Product;
2899 uint64_t DistTypeSizeBits = DL.getTypeSizeInBits(Dist.getType());
2900 uint64_t ProductTypeSizeBits = DL.getTypeSizeInBits(Product->getType());
2901
2902 // The dependence distance can be positive/negative, so we sign extend Dist;
2903 // The multiplication of the absolute stride in bytes and the
2904 // backedgeTakenCount is non-negative, so we zero extend Product.
2905 if (DistTypeSizeBits > ProductTypeSizeBits)
2906 CastedProduct = SE.getZeroExtendExpr(Product, Dist.getType());
2907 else
2908 CastedDist = SE.getNoopOrSignExtend(&Dist, Product->getType());
2909
2910 // Is Dist - (MaxBTC * Step) > 0 ?
2911 // (If so, then we have proven (**) because |Dist| >= Dist)
2912 const SCEV *Minus = SE.getMinusSCEV(CastedDist, CastedProduct);
2913 if (SE.isKnownPositive(Minus))
2914 return true;
2915
2916 // Second try: Is -Dist - (MaxBTC * Step) > 0 ?
2917 // (If so, then we have proven (**) because |Dist| >= -1*Dist)
2918 const SCEV *NegDist = SE.getNegativeSCEV(CastedDist);
2919 Minus = SE.getMinusSCEV(NegDist, CastedProduct);
2920 return SE.isKnownPositive(Minus);
2921}
2922
2923/// Check the dependence for two accesses with the same stride \p Stride.
2924/// \p Distance is the positive distance in bytes, and \p TypeByteSize is type
2925/// size in bytes.
2926///
2927/// \returns true if they are independent.
2929 uint64_t TypeByteSize) {
2930 assert(Stride > 1 && "The stride must be greater than 1");
2931 assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
2932 assert(Distance > 0 && "The distance must be non-zero");
2933
2934 // Skip if the distance is not multiple of type byte size.
2935 if (Distance % TypeByteSize)
2936 return false;
2937
2938 // No dependence if the distance is not multiple of the stride.
2939 // E.g.
2940 // for (i = 0; i < 1024 ; i += 4)
2941 // A[i+2] = A[i] + 1;
2942 //
2943 // Two accesses in memory (distance is 2, stride is 4):
2944 // | A[0] | | | | A[4] | | | |
2945 // | | | A[2] | | | | A[6] | |
2946 //
2947 // E.g.
2948 // for (i = 0; i < 1024 ; i += 3)
2949 // A[i+4] = A[i] + 1;
2950 //
2951 // Two accesses in memory (distance is 4, stride is 3):
2952 // | A[0] | | | A[3] | | | A[6] | | |
2953 // | | | | | A[4] | | | A[7] | |
2954 return Distance % Stride;
2955}
2956
2957bool MemoryDepChecker::areAccessesCompletelyBeforeOrAfter(const SCEV *Src,
2958 Type *SrcTy,
2959 const SCEV *Sink,
2960 Type *SinkTy) {
2961 const SCEV *BTC = PSE.getBackedgeTakenCount();
2962 const SCEV *SymbolicMaxBTC = PSE.getSymbolicMaxBackedgeTakenCount();
2963 ScalarEvolution &SE = *PSE.getSE();
2964 const auto &[SrcStart_, SrcEnd_] =
2965 getStartAndEndForAccess(InnermostLoop, Src, SrcTy, BTC, SymbolicMaxBTC,
2966 &SE, &PointerBounds, DT, AC, LoopGuards);
2967 if (isa<SCEVCouldNotCompute>(SrcStart_) || isa<SCEVCouldNotCompute>(SrcEnd_))
2968 return false;
2969
2970 const auto &[SinkStart_, SinkEnd_] =
2971 getStartAndEndForAccess(InnermostLoop, Sink, SinkTy, BTC, SymbolicMaxBTC,
2972 &SE, &PointerBounds, DT, AC, LoopGuards);
2973 if (isa<SCEVCouldNotCompute>(SinkStart_) ||
2974 isa<SCEVCouldNotCompute>(SinkEnd_))
2975 return false;
2976
2977 if (!LoopGuards)
2978 LoopGuards.emplace(ScalarEvolution::LoopGuards::collect(InnermostLoop, SE));
2979
2980 auto SrcEnd = SE.applyLoopGuards(SrcEnd_, *LoopGuards);
2981 auto SinkStart = SE.applyLoopGuards(SinkStart_, *LoopGuards);
2982 if (SE.isKnownPredicate(CmpInst::ICMP_ULE, SrcEnd, SinkStart))
2983 return true;
2984
2985 auto SinkEnd = SE.applyLoopGuards(SinkEnd_, *LoopGuards);
2986 auto SrcStart = SE.applyLoopGuards(SrcStart_, *LoopGuards);
2987 return SE.isKnownPredicate(CmpInst::ICMP_ULE, SinkEnd, SrcStart);
2988}
2989
2991 MemoryDepChecker::DepDistanceStrideAndSizeInfo>
2992MemoryDepChecker::getDependenceDistanceStrideAndSize(
2993 const AccessAnalysis::MemAccessInfo &A, Instruction *AInst,
2994 const AccessAnalysis::MemAccessInfo &B, Instruction *BInst) {
2995 const auto &DL = InnermostLoop->getHeader()->getDataLayout();
2996 auto &SE = *PSE.getSE();
2997 const auto &[APtr, AIsWrite] = A;
2998 const auto &[BPtr, BIsWrite] = B;
2999
3000 // Two reads are independent.
3001 if (!AIsWrite && !BIsWrite)
3003
3004 Type *ATy = getLoadStoreType(AInst);
3005 Type *BTy = getLoadStoreType(BInst);
3006
3007 // We cannot check pointers in different address spaces.
3008 if (APtr->getType()->getPointerAddressSpace() !=
3009 BPtr->getType()->getPointerAddressSpace())
3011
3013 std::optional<int64_t> StrideAPtr =
3014 getPtrStride(PSE, ATy, APtr, InnermostLoop, *DT, SymbolicStrides,
3015 /*ShouldCheckWrap=*/true, &Predicates);
3016 std::optional<int64_t> StrideBPtr =
3017 getPtrStride(PSE, BTy, BPtr, InnermostLoop, *DT, SymbolicStrides,
3018 /*ShouldCheckWrap=*/true, &Predicates);
3019 PSE.addPredicates(Predicates);
3020
3021 const SCEV *Src = PSE.getSCEV(APtr);
3022 const SCEV *Sink = PSE.getSCEV(BPtr);
3023
3024 // If the induction step is negative we have to invert source and sink of the
3025 // dependence when measuring the distance between them. We should not swap
3026 // AIsWrite with BIsWrite, as their uses expect them in program order.
3027 if (StrideAPtr && *StrideAPtr < 0) {
3028 std::swap(Src, Sink);
3029 std::swap(AInst, BInst);
3030 std::swap(ATy, BTy);
3031 std::swap(StrideAPtr, StrideBPtr);
3032 }
3033
3034 const SCEV *Dist = SE.getMinusSCEV(Sink, Src);
3035
3036 LLVM_DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
3037 << "\n");
3038 LLVM_DEBUG(dbgs() << "LAA: Distance for " << *AInst << " to " << *BInst
3039 << ": " << *Dist << "\n");
3040
3041 // Need accesses with constant strides and the same direction for further
3042 // dependence analysis. We don't want to vectorize "A[B[i]] += ..." and
3043 // similar code or pointer arithmetic that could wrap in the address space.
3044
3045 // If either Src or Sink are not strided (i.e. not a non-wrapping AddRec) and
3046 // not loop-invariant (stride will be 0 in that case), we cannot analyze the
3047 // dependence further and also cannot generate runtime checks.
3048 if (!StrideAPtr || !StrideBPtr) {
3049 LLVM_DEBUG(dbgs() << "Pointer access with non-constant stride\n");
3051 }
3052
3053 int64_t StrideAPtrInt = *StrideAPtr;
3054 int64_t StrideBPtrInt = *StrideBPtr;
3055 LLVM_DEBUG(dbgs() << "LAA: Src induction step: " << StrideAPtrInt
3056 << " Sink induction step: " << StrideBPtrInt << "\n");
3057 // At least Src or Sink are loop invariant and the other is strided or
3058 // invariant.
3059 if (!StrideAPtrInt || !StrideBPtrInt) {
3060 // If both are loop-invariant and access the same location, we cannot
3061 // vectorize.
3062 if (!StrideAPtrInt && !StrideBPtrInt && Dist->isZero())
3064 // Otherwise, we can generate a runtime check to disambiguate the accesses.
3066 }
3067
3068 // Both Src and Sink have a constant stride, check if they are in the same
3069 // direction.
3070 if ((StrideAPtrInt > 0) != (StrideBPtrInt > 0)) {
3071 LLVM_DEBUG(
3072 dbgs() << "Pointer access with strides in different directions\n");
3074 }
3075
3076 TypeSize AStoreSz = DL.getTypeStoreSize(ATy);
3077 TypeSize BStoreSz = DL.getTypeStoreSize(BTy);
3078
3079 // If store sizes are not the same, set TypeByteSize to zero, so we can check
3080 // it in the caller isDependent.
3081 uint64_t ASz = DL.getTypeAllocSize(ATy);
3082 uint64_t BSz = DL.getTypeAllocSize(BTy);
3083 uint64_t TypeByteSize = (AStoreSz == BStoreSz) ? BSz : 0;
3084
3085 uint64_t StrideAScaled = AbsoluteValue(StrideAPtrInt) * ASz;
3086 uint64_t StrideBScaled = AbsoluteValue(StrideBPtrInt) * BSz;
3087
3088 uint64_t MaxStride = std::max(StrideAScaled, StrideBScaled);
3089
3090 std::optional<uint64_t> CommonStride;
3091 if (StrideAScaled == StrideBScaled)
3092 CommonStride = StrideAScaled;
3093
3094 // TODO: Historically, we didn't retry with runtime checks when (unscaled)
3095 // strides were different but there is no inherent reason to.
3096 if (!isa<SCEVConstant>(Dist))
3097 ShouldRetryWithRuntimeChecks |= StrideAPtrInt == StrideBPtrInt;
3098
3099 // If distance is a SCEVCouldNotCompute, return Unknown immediately.
3100 if (isa<SCEVCouldNotCompute>(Dist)) {
3101 LLVM_DEBUG(dbgs() << "LAA: Uncomputable distance.\n");
3102 return Dependence::Unknown;
3103 }
3104
3105 return DepDistanceStrideAndSizeInfo(Dist, MaxStride, CommonStride,
3106 TypeByteSize, AIsWrite, BIsWrite);
3107}
3108
3110MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
3111 const MemAccessInfo &B, unsigned BIdx) {
3112 assert(AIdx < BIdx && "Must pass arguments in program order");
3113
3114 // Check if we can prove that Sink only accesses memory after Src's end or
3115 // vice versa. The helper is used to perform the checks only on the exit paths
3116 // where it helps to improve the analysis result.
3117 auto CheckCompletelyBeforeOrAfter = [&]() {
3118 auto *APtr = A.getPointer();
3119 auto *BPtr = B.getPointer();
3120 Type *ATy = getLoadStoreType(InstMap[AIdx]);
3121 Type *BTy = getLoadStoreType(InstMap[BIdx]);
3122 const SCEV *Src = PSE.getSCEV(APtr);
3123 const SCEV *Sink = PSE.getSCEV(BPtr);
3124 return areAccessesCompletelyBeforeOrAfter(Src, ATy, Sink, BTy);
3125 };
3126
3127 // Get the dependence distance, stride, type size and what access writes for
3128 // the dependence between A and B.
3129 auto Res =
3130 getDependenceDistanceStrideAndSize(A, InstMap[AIdx], B, InstMap[BIdx]);
3131 if (std::holds_alternative<Dependence::DepType>(Res)) {
3132 if (std::get<Dependence::DepType>(Res) == Dependence::Unknown &&
3133 CheckCompletelyBeforeOrAfter())
3134 return Dependence::NoDep;
3135 return std::get<Dependence::DepType>(Res);
3136 }
3137
3138 auto &[Dist, MaxStride, CommonStride, TypeByteSize, AIsWrite, BIsWrite] =
3139 std::get<DepDistanceStrideAndSizeInfo>(Res);
3140 bool HasSameSize = TypeByteSize > 0;
3141
3142 ScalarEvolution &SE = *PSE.getSE();
3143 auto &DL = InnermostLoop->getHeader()->getDataLayout();
3144
3145 // If the distance between the acecsses is larger than their maximum absolute
3146 // stride multiplied by the symbolic maximum backedge taken count (which is an
3147 // upper bound of the number of iterations), the accesses are independet, i.e.
3148 // they are far enough appart that accesses won't access the same location
3149 // across all loop ierations.
3150 if (HasSameSize &&
3152 DL, SE, *(PSE.getSymbolicMaxBackedgeTakenCount()), *Dist, MaxStride))
3153 return Dependence::NoDep;
3154
3155 const APInt *APDist = nullptr;
3156 uint64_t ConstDist = 0;
3157 if (match(Dist, m_scev_APInt(APDist))) {
3158 std::optional<uint64_t> Val = APDist->abs().tryZExtValue();
3159 if (!Val) {
3160 LLVM_DEBUG(dbgs() << "LAA: Constant distance does not fit in 64 bits.\n");
3161 return Dependence::Unknown;
3162 }
3163 ConstDist = *Val;
3164 }
3165
3166 // Attempt to prove strided accesses independent.
3167 if (APDist) {
3168 // If the distance between accesses and their strides are known constants,
3169 // check whether the accesses interlace each other.
3170 if (ConstDist > 0 && CommonStride && CommonStride > 1 && HasSameSize &&
3171 areStridedAccessesIndependent(ConstDist, *CommonStride, TypeByteSize)) {
3172 LLVM_DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
3173 return Dependence::NoDep;
3174 }
3175 } else {
3176 if (!LoopGuards)
3177 LoopGuards.emplace(
3178 ScalarEvolution::LoopGuards::collect(InnermostLoop, SE));
3179 Dist = SE.applyLoopGuards(Dist, *LoopGuards);
3180 }
3181
3182 // Negative distances are not plausible dependencies.
3183 if (SE.isKnownNonPositive(Dist)) {
3184 if (SE.isKnownNonNegative(Dist)) {
3185 // Equal-sized accesses to the same location are forward.
3186 if (HasSameSize)
3187 return Dependence::Forward;
3188
3189 if (CommonStride) {
3190 // For mixed sizes, CommonStride is asserted to cover both accesses when
3191 // computed in getDependenceDistanceStrideAndSize, so different
3192 // iterations cannot overlap.
3193 [[maybe_unused]] uint64_t ASz =
3194 DL.getTypeAllocSize(getLoadStoreType(InstMap[AIdx]));
3195 [[maybe_unused]] uint64_t BSz =
3196 DL.getTypeAllocSize(getLoadStoreType(InstMap[BIdx]));
3197 assert(*CommonStride >= std::max(ASz, BSz) &&
3198 "Invariant from getDependenceDistanceStrideAndSize broken!");
3199 return Dependence::Forward;
3200 }
3201 LLVM_DEBUG(dbgs() << "LAA: possibly zero dependence difference but "
3202 "different type sizes\n");
3203 return Dependence::Unknown;
3204 }
3205
3206 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
3207 // Check if the first access writes to a location that is read in a later
3208 // iteration, where the distance between them is not a multiple of a vector
3209 // factor and relatively small.
3210 //
3211 // NOTE: There is no need to update MaxSafeVectorWidthInBits after call to
3212 // couldPreventStoreLoadForward, even if it changed MinDepDistBytes, since a
3213 // forward dependency will allow vectorization using any width.
3214
3215 if (IsTrueDataDependence && EnableForwardingConflictDetection) {
3216 if (!ConstDist) {
3217 return CheckCompletelyBeforeOrAfter() ? Dependence::NoDep
3219 }
3220 if (!HasSameSize ||
3221 couldPreventStoreLoadForward(ConstDist, TypeByteSize)) {
3222 LLVM_DEBUG(
3223 dbgs() << "LAA: Forward but may prevent st->ld forwarding\n");
3225 }
3226 }
3227
3228 LLVM_DEBUG(dbgs() << "LAA: Dependence is negative\n");
3229 return Dependence::Forward;
3230 }
3231
3232 std::optional<int64_t> MinDistanceOpt =
3234 if (!MinDistanceOpt) {
3235 LLVM_DEBUG(dbgs() << "LAA: Minimum distance does not fit in 64 bits.\n");
3236 return Dependence::Unknown;
3237 }
3238 int64_t MinDistance = *MinDistanceOpt;
3239 // Below we only handle strictly positive distances.
3240 if (MinDistance <= 0) {
3241 return CheckCompletelyBeforeOrAfter() ? Dependence::NoDep
3243 }
3244
3245 if (!HasSameSize) {
3246 if (CheckCompletelyBeforeOrAfter())
3247 return Dependence::NoDep;
3248 LLVM_DEBUG(dbgs() << "LAA: ReadWrite-Write positive dependency with "
3249 "different type sizes\n");
3250 return Dependence::Unknown;
3251 }
3252 // Bail out early if passed-in parameters make vectorization not feasible.
3253 unsigned MinForcedFactor =
3254 std::max(1U, VectorizerParams::VectorizationFactor.getKnownMinValue());
3255 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
3257 // The minimum number of iterations for a vectorized/unrolled version.
3258 unsigned MinNumIter = std::max(MinForcedFactor * ForcedUnroll, 2U);
3259
3260 // It's not vectorizable if the distance is smaller than the minimum distance
3261 // needed for a vectroized/unrolled version. Vectorizing one iteration in
3262 // front needs MaxStride. Vectorizing the last iteration needs TypeByteSize.
3263 // (No need to plus the last gap distance).
3264 //
3265 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
3266 // foo(int *A) {
3267 // int *B = (int *)((char *)A + 14);
3268 // for (i = 0 ; i < 1024 ; i += 2)
3269 // B[i] = A[i] + 1;
3270 // }
3271 //
3272 // Two accesses in memory (stride is 4 * 2):
3273 // | A[0] | | A[2] | | A[4] | | A[6] | |
3274 // | B[0] | | B[2] | | B[4] |
3275 //
3276 // MinDistance needs for vectorizing iterations except the last iteration:
3277 // 4 * 2 * (MinNumIter - 1). MinDistance needs for the last iteration: 4.
3278 // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
3279 //
3280 // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
3281 // 12, which is less than distance.
3282 //
3283 // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
3284 // the minimum distance needed is 28, which is greater than distance. It is
3285 // not safe to do vectorization.
3286 //
3287 // We use MaxStride (maximum of src and sink strides) to get a conservative
3288 // lower bound on the MinDistanceNeeded in case of different strides.
3289
3290 // We know that Dist is positive, but it may not be constant. Use the signed
3291 // minimum for computations below, as this ensures we compute the closest
3292 // possible dependence distance.
3293 uint64_t MinDistanceNeeded = MaxStride * (MinNumIter - 1) + TypeByteSize;
3294 if (MinDistanceNeeded > static_cast<uint64_t>(MinDistance)) {
3295 if (!ConstDist) {
3296 // For non-constant distances, we checked the lower bound of the
3297 // dependence distance and the distance may be larger at runtime (and safe
3298 // for vectorization). Classify it as Unknown, so we re-try with runtime
3299 // checks, unless we can prove both accesses cannot overlap.
3300 return CheckCompletelyBeforeOrAfter() ? Dependence::NoDep
3302 }
3303 LLVM_DEBUG(dbgs() << "LAA: Failure because of positive minimum distance "
3304 << MinDistance << '\n');
3305 return Dependence::Backward;
3306 }
3307
3308 // Unsafe if the minimum distance needed is greater than smallest dependence
3309 // distance distance.
3310 if (MinDistanceNeeded > MinDepDistBytes) {
3311 LLVM_DEBUG(dbgs() << "LAA: Failure because it needs at least "
3312 << MinDistanceNeeded << " size in bytes\n");
3313 return Dependence::Backward;
3314 }
3315
3316 MinDepDistBytes =
3317 std::min(static_cast<uint64_t>(MinDistance), MinDepDistBytes);
3318
3319 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
3320 if (IsTrueDataDependence && EnableForwardingConflictDetection && ConstDist &&
3321 couldPreventStoreLoadForward(MinDistance, TypeByteSize, *CommonStride))
3323
3324 uint64_t MaxVF = MinDepDistBytes / MaxStride;
3325 LLVM_DEBUG(dbgs() << "LAA: Positive min distance " << MinDistance
3326 << " with max VF = " << MaxVF << '\n');
3327
3328 uint64_t MaxVFInBits = MaxVF * TypeByteSize * 8;
3329 if (!ConstDist && MaxVFInBits < MaxTargetVectorWidthInBits) {
3330 // For non-constant distances, we checked the lower bound of the dependence
3331 // distance and the distance may be larger at runtime (and safe for
3332 // vectorization). Classify it as Unknown, so we re-try with runtime checks,
3333 // unless we can prove both accesses cannot overlap.
3334 return CheckCompletelyBeforeOrAfter() ? Dependence::NoDep
3336 }
3337
3338 if (CheckCompletelyBeforeOrAfter())
3339 return Dependence::NoDep;
3340
3341 MaxSafeVectorWidthInBits = std::min(MaxSafeVectorWidthInBits, MaxVFInBits);
3343}
3344
3346 ArrayRef<MemAccessInfo> CheckDeps) {
3347
3348 MinDepDistBytes = -1;
3350 for (MemAccessInfo CurAccess : CheckDeps) {
3351 if (Visited.contains(CurAccess))
3352 continue;
3353
3354 // Check accesses within this set.
3356 DepCands.findLeader(CurAccess);
3358 DepCands.member_end();
3359
3360 // Check every access pair.
3361 while (AI != AE) {
3362 Visited.insert(*AI);
3363 bool AIIsWrite = AI->getInt();
3364 // Reads from the same pointer don't create extra hazards, but multiple
3365 // stores do (WAW), so start from AI for writes and next(AI) for reads.
3367 (AIIsWrite ? AI : std::next(AI));
3368 while (OI != AE) {
3369 // Check every accessing instruction pair in program order.
3370 auto &Acc = Accesses[*AI];
3371 for (std::vector<unsigned>::iterator I1 = Acc.begin(), I1E = Acc.end();
3372 I1 != I1E; ++I1)
3373 // When checking for WAW (OI == AI) caused by multiple writes to the
3374 // same pointer, start I2 at the next access past I1 to avoid
3375 // self-comparison.
3376 for (std::vector<unsigned>::iterator
3377 I2 = (OI == AI ? std::next(I1) : Accesses[*OI].begin()),
3378 I2E = (OI == AI ? I1E : Accesses[*OI].end());
3379 I2 != I2E; ++I2) {
3380 auto A = std::make_pair(&*AI, *I1);
3381 auto B = std::make_pair(&*OI, *I2);
3382
3383 assert(*I1 != *I2);
3384 if (*I1 > *I2)
3385 std::swap(A, B);
3386
3388 isDependent(*A.first, A.second, *B.first, B.second);
3390
3391 // Gather dependences unless we accumulated MaxDependences
3392 // dependences. In that case return as soon as we find the first
3393 // unsafe dependence. This puts a limit on this quadratic
3394 // algorithm.
3395 if (RecordDependences) {
3396 if (Type != Dependence::NoDep)
3397 Dependences.emplace_back(A.second, B.second, Type);
3398
3399 if (Dependences.size() >= MaxDependences) {
3400 RecordDependences = false;
3401 Dependences.clear();
3403 << "Too many dependences, stopped recording\n");
3404 }
3405 }
3406 if (!RecordDependences && !isSafeForVectorization())
3407 return false;
3408 }
3409 ++OI;
3410 }
3411 ++AI;
3412 }
3413 }
3414
3415 LLVM_DEBUG(dbgs() << "Total Dependences: " << Dependences.size() << "\n");
3416 return isSafeForVectorization();
3417}
3418
3421 MemAccessInfo Access(Ptr, IsWrite);
3422 auto I = Accesses.find(Access);
3424 if (I != Accesses.end()) {
3425 transform(I->second, std::back_inserter(Insts),
3426 [&](unsigned Idx) { return this->InstMap[Idx]; });
3427 }
3428
3429 return Insts;
3430}
3431
3433 "NoDep",
3434 "Unknown",
3435 "IndirectUnsafe",
3436 "InvariantUnsafe",
3437 "Forward",
3438 "ForwardButPreventsForwarding",
3439 "Backward",
3440 "BackwardVectorizable",
3441 "BackwardVectorizableButPreventsForwarding"};
3442
3444 raw_ostream &OS, unsigned Depth,
3445 const SmallVectorImpl<Instruction *> &Instrs) const {
3446 OS.indent(Depth) << DepName[Type] << ":\n";
3447 OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
3448 OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
3449}
3450
3451bool LoopAccessInfo::canAnalyzeLoop() {
3452 // We need to have a loop header.
3453 LLVM_DEBUG(dbgs() << "\nLAA: Checking a loop in '"
3454 << TheLoop->getHeader()->getParent()->getName() << "' from "
3455 << TheLoop->getLocStr() << "\n");
3456
3457 // We can only analyze innermost loops.
3458 if (!TheLoop->isInnermost()) {
3459 LLVM_DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
3460 recordAnalysis("NotInnerMostLoop") << "loop is not the innermost loop";
3461 return false;
3462 }
3463
3464 // We must have a single backedge.
3465 if (TheLoop->getNumBackEdges() != 1) {
3466 LLVM_DEBUG(
3467 dbgs() << "LAA: loop control flow is not understood by analyzer\n");
3468 recordAnalysis("CFGNotUnderstood")
3469 << "loop control flow is not understood by analyzer";
3470 return false;
3471 }
3472
3473 // ScalarEvolution needs to be able to find the symbolic max backedge taken
3474 // count, which is an upper bound on the number of loop iterations. The loop
3475 // may execute fewer iterations, if it exits via an uncountable exit.
3476 const SCEV *ExitCount = PSE->getSymbolicMaxBackedgeTakenCount();
3477 if (isa<SCEVCouldNotCompute>(ExitCount)) {
3478 recordAnalysis("CantComputeNumberOfIterations")
3479 << "could not determine number of loop iterations";
3480 LLVM_DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
3481 return false;
3482 }
3483
3484 LLVM_DEBUG(dbgs() << "LAA: Found an analyzable loop: "
3485 << TheLoop->getHeader()->getName() << "\n");
3486 return true;
3487}
3488
3489bool LoopAccessInfo::analyzeLoop(AAResults *AA, const LoopInfo *LI,
3490 const TargetLibraryInfo *TLI,
3491 DominatorTree *DT) {
3492 // Holds the Load and Store instructions.
3495 SmallPtrSet<MDNode *, 8> LoopAliasScopes;
3496
3497 // Holds all the different accesses in the loop.
3498 unsigned NumReads = 0;
3499 unsigned NumReadWrites = 0;
3500
3501 bool HasComplexMemInst = false;
3502
3503 // A runtime check is only legal to insert if there are no convergent calls.
3504 HasConvergentOp = false;
3505
3506 PtrRtChecking->Pointers.clear();
3507 PtrRtChecking->Need = false;
3508
3509 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
3510
3511 const bool EnableMemAccessVersioningOfLoop =
3513 !TheLoop->getHeader()->getParent()->hasOptSize();
3514
3515 // Traverse blocks in fixed RPOT order, regardless of their storage in the
3516 // loop info, as it may be arbitrary.
3517 LoopBlocksRPO RPOT(TheLoop);
3518 RPOT.perform(LI);
3519
3520 // Don't return early as soon as we found a memory access that cannot be
3521 // vectorize - HasConvergentOp must still be computed as it is part of LAI's
3522 // public API (used by LoopDistribute).
3523 for (BasicBlock *BB : RPOT) {
3524 // Scan the BB and collect legal loads and stores. Also detect any
3525 // convergent instructions.
3526 for (Instruction &I : *BB) {
3527 if (auto *Call = dyn_cast<CallBase>(&I)) {
3528 if (Call->isConvergent())
3529 HasConvergentOp = true;
3530 }
3531
3532 // Unsafe to vectorize and we already found a convergent operation, can
3533 // early return now.
3534 if (HasComplexMemInst && HasConvergentOp)
3535 return false;
3536
3537 // Already unsafe to vectorize; keep scanning for convergent ops.
3538 if (HasComplexMemInst)
3539 continue;
3540
3541 // Record alias scopes defined inside the loop.
3542 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
3543 for (Metadata *Op : Decl->getScopeList()->operands())
3544 LoopAliasScopes.insert(cast<MDNode>(Op));
3545
3546 // Many math library functions read the rounding mode. We will only
3547 // vectorize a loop if it contains known function calls that don't set
3548 // the flag. Therefore, it is safe to ignore this read from memory.
3549 auto *Call = dyn_cast<CallInst>(&I);
3551 continue;
3552
3553 // If this is a load, save it. If this instruction can read from memory
3554 // but is not a load, we only allow it if it's a call to a function with a
3555 // vector mapping and no pointer arguments.
3556 if (I.mayReadFromMemory()) {
3557 auto hasPointerArgs = [](CallBase *CB) {
3558 return any_of(CB->args(), [](Value const *Arg) {
3559 return Arg->getType()->isPointerTy();
3560 });
3561 };
3562
3563 // If the function has an explicit vectorized counterpart, and does not
3564 // take output/input pointers, we can safely assume that it can be
3565 // vectorized.
3566 if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
3567 !hasPointerArgs(Call) && !VFDatabase::getMappings(*Call).empty())
3568 continue;
3569
3570 auto *Ld = dyn_cast<LoadInst>(&I);
3571 if (!Ld) {
3572 recordAnalysis("CantVectorizeInstruction", &I)
3573 << "instruction cannot be vectorized";
3574 HasComplexMemInst = true;
3575 continue;
3576 }
3577 if (!Ld->isSimple() && !IsAnnotatedParallel) {
3578 recordAnalysis("NonSimpleLoad", Ld)
3579 << "read with atomic ordering or volatile read";
3580 LLVM_DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
3581 HasComplexMemInst = true;
3582 continue;
3583 }
3584 Loads.push_back(Ld);
3585 DepChecker->addAccess(Ld);
3586 if (EnableMemAccessVersioningOfLoop)
3587 collectStridedAccess(Ld);
3588 continue;
3589 }
3590
3591 // Save 'store' instructions. Abort if other instructions write to memory.
3592 if (I.mayWriteToMemory()) {
3593 auto *St = dyn_cast<StoreInst>(&I);
3594 if (!St) {
3595 recordAnalysis("CantVectorizeInstruction", &I)
3596 << "instruction cannot be vectorized";
3597 HasComplexMemInst = true;
3598 continue;
3599 }
3600 if (!St->isSimple() && !IsAnnotatedParallel) {
3601 recordAnalysis("NonSimpleStore", St)
3602 << "write with atomic ordering or volatile write";
3603 LLVM_DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
3604 HasComplexMemInst = true;
3605 continue;
3606 }
3607 Stores.push_back(St);
3608 DepChecker->addAccess(St);
3609 if (EnableMemAccessVersioningOfLoop)
3610 collectStridedAccess(St);
3611 }
3612 } // Next instr.
3613 } // Next block.
3614
3615 if (HasComplexMemInst)
3616 return false;
3617
3618 // Now we have two lists that hold the loads and the stores.
3619 // Next, we find the pointers that they use.
3620
3621 // Check if we see any stores. If there are no stores, then we don't
3622 // care if the pointers are *restrict*.
3623 if (!Stores.size()) {
3624 LLVM_DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
3625 return true;
3626 }
3627
3629 AccessAnalysis Accesses(TheLoop, AA, LI, *DT, DepCands, *PSE,
3630 LoopAliasScopes);
3631
3632 // Holds the analyzed pointers. We don't want to call getUnderlyingObjects
3633 // multiple times on the same object. If the ptr is accessed twice, once
3634 // for read and once for write, it will only appear once (on the write
3635 // list). This is okay, since we are going to check for conflicts between
3636 // writes and between reads and writes, but not between reads and reads.
3637 SmallSet<std::pair<Value *, Type *>, 16> Seen;
3638
3639 // Record uniform store addresses to identify if we have multiple stores
3640 // to the same address.
3641 SmallPtrSet<Value *, 16> UniformStores;
3642
3643 for (StoreInst *ST : Stores) {
3644 Value *Ptr = ST->getPointerOperand();
3645
3646 if (isInvariant(Ptr)) {
3647 // Record store instructions to loop invariant addresses
3648 StoresToInvariantAddresses.push_back(ST);
3649 HasStoreStoreDependenceInvolvingLoopInvariantAddress |=
3650 !UniformStores.insert(Ptr).second;
3651 }
3652
3653 // If we did *not* see this pointer before, insert it to the read-write
3654 // list. At this phase it is only a 'write' list.
3655 Type *AccessTy = getLoadStoreType(ST);
3656 if (Seen.insert({Ptr, AccessTy}).second) {
3657 ++NumReadWrites;
3658
3659 MemoryLocation Loc = MemoryLocation::get(ST);
3660 // The TBAA metadata could have a control dependency on the predication
3661 // condition, so we cannot rely on it when determining whether or not we
3662 // need runtime pointer checks.
3663 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
3664 Loc.AATags.TBAA = nullptr;
3665
3666 // Expand forked pointers (i.e., a phi of multiple strided pointers) into
3667 // all alternatives.
3668 visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop,
3669 [&Accesses, AccessTy, Loc](Value *Ptr) {
3670 MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr);
3671 Accesses.addStore(NewLoc, AccessTy);
3672 });
3673 }
3674 }
3675
3676 if (IsAnnotatedParallel) {
3677 LLVM_DEBUG(
3678 dbgs() << "LAA: A loop annotated parallel, ignore memory dependency "
3679 << "checks.\n");
3680 return true;
3681 }
3682
3683 for (LoadInst *LD : Loads) {
3684 Value *Ptr = LD->getPointerOperand();
3685 // If we did *not* see this pointer before, insert it to the read list. If
3686 // we *did* see it before, then it is already in the read-write list. This
3687 // allows us to vectorize expressions such as A[i] += x; Because the address
3688 // of A[i] is a read-write pointer. This only works if the index of A[i] is
3689 // strictly monotonic, which we approximate (conservatively) via
3690 // getPtrStride. If the address is unknown (e.g. A[B[i]]) then we may read,
3691 // modify, and write overlapping words. Note that "zero stride" is unsafe
3692 // and is being handled below.
3693 bool IsReadOnlyPtr = false;
3694 Type *AccessTy = getLoadStoreType(LD);
3695 if (Seen.insert({Ptr, AccessTy}).second ||
3696 !getPtrStride(*PSE, AccessTy, Ptr, TheLoop, *DT, SymbolicStrides,
3697 true)) {
3698 ++NumReads;
3699 IsReadOnlyPtr = true;
3700 }
3701
3702 // See if there is an unsafe dependency between a load to a uniform address and
3703 // store to the same uniform address.
3704 if (UniformStores.contains(Ptr)) {
3705 LLVM_DEBUG(dbgs() << "LAA: Found an unsafe dependency between a uniform "
3706 "load and uniform store to the same address!\n");
3707 HasLoadStoreDependenceInvolvingLoopInvariantAddress = true;
3708 }
3709
3710 MemoryLocation Loc = MemoryLocation::get(LD);
3711 // The TBAA metadata could have a control dependency on the predication
3712 // condition, so we cannot rely on it when determining whether or not we
3713 // need runtime pointer checks.
3714 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
3715 Loc.AATags.TBAA = nullptr;
3716
3717 // Expand forked pointers (i.e., a phi of multiple strided pointers) into
3718 // all alternatives.
3719 visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop,
3720 [&Accesses, AccessTy, Loc, IsReadOnlyPtr](Value *Ptr) {
3721 MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr);
3722 Accesses.addLoad(NewLoc, AccessTy, IsReadOnlyPtr);
3723 });
3724 }
3725
3726 // If we write (or read-write) to a single destination and there are no other
3727 // reads in this loop then is it safe to vectorize: the vectorized stores
3728 // preserve ordering via replication or order-preserving @llvm.masked.scatter.
3729 if (NumReadWrites == 1 && NumReads == 0) {
3730 LLVM_DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
3731 return true;
3732 }
3733
3734 // Build dependence sets and check whether we need a runtime pointer bounds
3735 // check.
3736 Accesses.buildDependenceSets();
3737
3738 // Find pointers with computable bounds. We are going to use this information
3739 // to place a runtime bound check.
3740 Value *UncomputablePtr = nullptr;
3741 HasCompletePtrRtChecking =
3742 Accesses.canCheckPtrAtRT(*PtrRtChecking, TheLoop, SymbolicStrides,
3743 UncomputablePtr, AllowPartial, getDepChecker());
3744 if (!HasCompletePtrRtChecking) {
3745 const auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr);
3746 recordAnalysis("CantIdentifyArrayBounds", I)
3747 << "cannot identify array bounds";
3748 LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
3749 << "the array bounds.\n");
3750 return false;
3751 }
3752
3753 LLVM_DEBUG(
3754 dbgs() << "LAA: May be able to perform a memory runtime check if needed.\n");
3755
3756 bool DepsAreSafe = true;
3757 if (Accesses.isDependencyCheckNeeded()) {
3758 LLVM_DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
3759 DepsAreSafe =
3760 DepChecker->areDepsSafe(DepCands, Accesses.getDependenciesToCheck());
3761
3762 if (!DepsAreSafe && DepChecker->shouldRetryWithRuntimeChecks()) {
3763 LLVM_DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
3764
3765 PtrRtChecking->reset();
3766 PtrRtChecking->Need = true;
3767
3768 UncomputablePtr = nullptr;
3769 HasCompletePtrRtChecking = Accesses.canCheckPtrAtRT(
3770 *PtrRtChecking, TheLoop, SymbolicStrides, UncomputablePtr,
3771 AllowPartial, getDepChecker());
3772
3773 // Check that we found the bounds for the pointer.
3774 if (!HasCompletePtrRtChecking) {
3775 auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr);
3776 recordAnalysis("CantCheckMemDepsAtRunTime", I)
3777 << "cannot check memory dependencies at runtime";
3778 LLVM_DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
3779 return false;
3780 }
3781
3782 // Clear the dependency checks. They are no longer needed.
3783 Accesses.resetDepChecks(*DepChecker);
3784
3785 DepsAreSafe = true;
3786 }
3787 }
3788
3789 // Update the invariant address dependence flags based on dependences found
3790 // by the dep checker. Even if dependences were not recorded (too many to
3791 // track), any InvariantUnsafe dep would still have set the status to Unsafe
3792 if (const auto *Deps = DepChecker->getDependences()) {
3793 for (const auto &Dep : *Deps) {
3795 continue;
3796 Instruction *Src = Dep.getSource(*DepChecker);
3797 Instruction *Dst = Dep.getDestination(*DepChecker);
3798 if (isa<LoadInst>(Src) != isa<LoadInst>(Dst)) {
3799 HasLoadStoreDependenceInvolvingLoopInvariantAddress = true;
3800 } else {
3801 assert(isa<StoreInst>(Src) && isa<StoreInst>(Dst) &&
3802 "Expected both to be stores");
3803 HasStoreStoreDependenceInvolvingLoopInvariantAddress = true;
3804 }
3805 }
3806 }
3807
3808 if (HasConvergentOp) {
3809 recordAnalysis("CantInsertRuntimeCheckWithConvergent")
3810 << "cannot add control dependency to convergent operation";
3811 LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because a runtime check "
3812 "would be needed with a convergent operation\n");
3813 return false;
3814 }
3815
3816 if (DepsAreSafe) {
3817 LLVM_DEBUG(
3818 dbgs() << "LAA: No unsafe dependent memory operations in loop. We"
3819 << (PtrRtChecking->Need ? "" : " don't")
3820 << " need runtime memory checks.\n");
3821 return true;
3822 }
3823
3824 emitUnsafeDependenceRemark();
3825 return false;
3826}
3827
3828void LoopAccessInfo::emitUnsafeDependenceRemark() {
3829 const auto *Deps = getDepChecker().getDependences();
3830 if (!Deps)
3831 return;
3832 const auto *Found =
3833 llvm::find_if(*Deps, [](const MemoryDepChecker::Dependence &D) {
3836 });
3837 if (Found == Deps->end())
3838 return;
3839 MemoryDepChecker::Dependence Dep = *Found;
3840
3841 LLVM_DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
3842
3843 // Emit remark for first unsafe dependence
3844 bool HasForcedDistribution =
3845 getBooleanLoopAttribute(TheLoop, "llvm.loop.distribute.enable");
3846
3847 const std::string Info =
3848 HasForcedDistribution
3849 ? "unsafe dependent memory operations in loop."
3850 : "unsafe dependent memory operations in loop. Use "
3851 "#pragma clang loop distribute(enable) to allow loop distribution "
3852 "to attempt to isolate the offending operations into a separate "
3853 "loop";
3854 OptimizationRemarkAnalysis &R =
3855 recordAnalysis("UnsafeDep", Dep.getDestination(getDepChecker())) << Info;
3856
3857 switch (Dep.Type) {
3861 llvm_unreachable("Unexpected dependence");
3863 R << "\nBackward loop carried data dependence.";
3864 break;
3866 R << "\nForward loop carried data dependence that prevents "
3867 "store-to-load forwarding.";
3868 break;
3870 R << "\nBackward loop carried data dependence that prevents "
3871 "store-to-load forwarding.";
3872 break;
3874 R << "\nUnsafe indirect dependence.";
3875 break;
3877 R << "\nUnsafe dependence on loop-invariant address.";
3878 break;
3880 R << "\nUnknown data dependence.";
3881 break;
3882 }
3883
3884 if (Instruction *I = Dep.getSource(getDepChecker())) {
3885 DebugLoc SourceLoc = I->getDebugLoc();
3887 SourceLoc = DD->getDebugLoc();
3888 if (SourceLoc)
3889 R << " Memory location is the same as accessed at "
3890 << ore::NV("Location", SourceLoc);
3891 }
3892}
3893
3895 const Loop *TheLoop,
3896 const DominatorTree *DT) {
3897 assert(TheLoop->contains(BB) && "Unknown block used");
3898
3899 // Blocks that do not dominate the latch need predication.
3900 const BasicBlock *Latch = TheLoop->getLoopLatch();
3901 assert(Latch && "Loop expected to have a single latch.");
3902 return !DT->dominates(BB, Latch);
3903}
3904
3906LoopAccessInfo::recordAnalysis(StringRef RemarkName, const Instruction *I) {
3907 assert(!Report && "Multiple reports generated");
3908
3909 const BasicBlock *CodeRegion = TheLoop->getHeader();
3910 DebugLoc DL = TheLoop->getStartLoc();
3911
3912 if (I) {
3913 CodeRegion = I->getParent();
3914 // If there is no debug location attached to the instruction, revert back to
3915 // using the loop's.
3916 if (I->getDebugLoc())
3917 DL = I->getDebugLoc();
3918 }
3919
3920 Report = std::make_unique<OptimizationRemarkAnalysis>(DEBUG_TYPE, RemarkName,
3921 DL, CodeRegion);
3922 return *Report;
3923}
3924
3926 auto *SE = PSE->getSE();
3927 if (TheLoop->isLoopInvariant(V))
3928 return true;
3929 if (!SE->isSCEVable(V->getType()))
3930 return false;
3931 const SCEV *S = SE->getSCEV(V);
3932 return SE->isLoopInvariant(S, TheLoop);
3933}
3934
3935/// If \p Ptr is a GEP, which has a loop-variant operand, return that operand.
3936/// Otherwise, return \p Ptr.
3938 Loop *Lp) {
3939 auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3940 if (!GEP)
3941 return Ptr;
3942
3943 Value *V = Ptr;
3944 for (const Use &U : GEP->operands()) {
3945 if (!SE->isLoopInvariant(SE->getSCEV(U), Lp)) {
3946 if (V == Ptr)
3947 V = U;
3948 else
3949 // There must be exactly one loop-variant operand.
3950 return Ptr;
3951 }
3952 }
3953 return V;
3954}
3955
3956/// Get the stride of a pointer access in a loop. Looks for symbolic
3957/// strides "a[i*stride]". Returns the symbolic stride, or null otherwise.
3958static const SCEV *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
3959 auto *PtrTy = dyn_cast<PointerType>(Ptr->getType());
3960 if (!PtrTy)
3961 return nullptr;
3962
3963 // Try to remove a gep instruction to make the pointer (actually index at this
3964 // point) easier analyzable. If OrigPtr is equal to Ptr we are analyzing the
3965 // pointer, otherwise, we are analyzing the index.
3966 Value *OrigPtr = Ptr;
3967
3968 Ptr = getLoopVariantGEPOperand(Ptr, SE, Lp);
3969 const SCEV *V = SE->getSCEV(Ptr);
3970
3971 if (Ptr != OrigPtr)
3972 // Strip off casts.
3973 while (auto *C = dyn_cast<SCEVIntegralCastExpr>(V))
3974 V = C->getOperand();
3975
3977 return nullptr;
3978
3979 // Note that the restriction after this loop invariant check are only
3980 // profitability restrictions.
3981 if (!SE->isLoopInvariant(V, Lp))
3982 return nullptr;
3983
3984 // Look for the loop invariant symbolic value.
3985 if (isa<SCEVUnknown>(V))
3986 return V;
3987
3988 // Look through multiplies that scale a stride by a constant.
3990 if (auto *C = dyn_cast<SCEVIntegralCastExpr>(V))
3991 if (isa<SCEVUnknown>(C->getOperand()))
3992 return V;
3993
3994 return nullptr;
3995}
3996
3997void LoopAccessInfo::collectStridedAccess(Value *MemAccess) {
3998 Value *Ptr = getLoadStorePointerOperand(MemAccess);
3999 if (!Ptr)
4000 return;
4001
4002 // Note: getStrideFromPointer is a *profitability* heuristic. We
4003 // could broaden the scope of values returned here - to anything
4004 // which happens to be loop invariant and contributes to the
4005 // computation of an interesting IV - but we chose not to as we
4006 // don't have a cost model here, and broadening the scope exposes
4007 // far too many unprofitable cases.
4008 const SCEV *StrideExpr = getStrideFromPointer(Ptr, PSE->getSE(), TheLoop);
4009 if (!StrideExpr)
4010 return;
4011
4012 if (match(StrideExpr, m_scev_UndefOrPoison()))
4013 return;
4014
4015 LLVM_DEBUG(dbgs() << "LAA: Found a strided access that is a candidate for "
4016 "versioning:");
4017 LLVM_DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *StrideExpr << "\n");
4018
4019 if (!SpeculateUnitStride) {
4020 LLVM_DEBUG(dbgs() << " Chose not to due to -laa-speculate-unit-stride\n");
4021 return;
4022 }
4023
4024 // Avoid adding the "Stride == 1" predicate when we know that
4025 // Stride >= Trip-Count. Such a predicate will effectively optimize a single
4026 // or zero iteration loop, as Trip-Count <= Stride == 1.
4027 //
4028 // TODO: We are currently not making a very informed decision on when it is
4029 // beneficial to apply stride versioning. It might make more sense that the
4030 // users of this analysis (such as the vectorizer) will trigger it, based on
4031 // their specific cost considerations; For example, in cases where stride
4032 // versioning does not help resolving memory accesses/dependences, the
4033 // vectorizer should evaluate the cost of the runtime test, and the benefit
4034 // of various possible stride specializations, considering the alternatives
4035 // of using gather/scatters (if available).
4036
4037 const SCEV *MaxBTC = PSE->getSymbolicMaxBackedgeTakenCount();
4038
4039 // Match the types so we can compare the stride and the MaxBTC.
4040 // The Stride can be positive/negative, so we sign extend Stride;
4041 // The backedgeTakenCount is non-negative, so we zero extend MaxBTC.
4042 const DataLayout &DL = TheLoop->getHeader()->getDataLayout();
4043 uint64_t StrideTypeSizeBits = DL.getTypeSizeInBits(StrideExpr->getType());
4044 uint64_t BETypeSizeBits = DL.getTypeSizeInBits(MaxBTC->getType());
4045 const SCEV *CastedStride = StrideExpr;
4046 const SCEV *CastedBECount = MaxBTC;
4047 ScalarEvolution *SE = PSE->getSE();
4048 if (BETypeSizeBits >= StrideTypeSizeBits)
4049 CastedStride = SE->getNoopOrSignExtend(StrideExpr, MaxBTC->getType());
4050 else
4051 CastedBECount = SE->getZeroExtendExpr(MaxBTC, StrideExpr->getType());
4052 const SCEV *StrideMinusBETaken = SE->getMinusSCEV(CastedStride, CastedBECount);
4053 // Since TripCount == BackEdgeTakenCount + 1, checking:
4054 // "Stride >= TripCount" is equivalent to checking:
4055 // Stride - MaxBTC> 0
4056 if (SE->isKnownPositive(StrideMinusBETaken)) {
4057 LLVM_DEBUG(
4058 dbgs() << "LAA: Stride>=TripCount; No point in versioning as the "
4059 "Stride==1 predicate will imply that the loop executes "
4060 "at most once.\n");
4061 return;
4062 }
4063 LLVM_DEBUG(dbgs() << "LAA: Found a strided access that we can version.\n");
4064
4065 // Strip back off the integer cast, and check that our result is a
4066 // SCEVUnknown as we expect.
4067 const SCEV *StrideBase = StrideExpr;
4068 if (const auto *C = dyn_cast<SCEVIntegralCastExpr>(StrideBase))
4069 StrideBase = C->getOperand();
4070 assert(SE->isLoopInvariant(StrideBase, TheLoop) &&
4071 "users of the map rely on the stride being loop invariant");
4072 SymbolicStrides[Ptr] = cast<SCEVUnknown>(StrideBase);
4073}
4074
4076 const TargetTransformInfo *TTI,
4077 const TargetLibraryInfo *TLI, AAResults *AA,
4078 DominatorTree *DT, LoopInfo *LI,
4079 AssumptionCache *AC, bool AllowPartial)
4080 : PSE(std::make_unique<PredicatedScalarEvolution>(*SE, *L)),
4081 PtrRtChecking(nullptr), TheLoop(L), AllowPartial(AllowPartial) {
4082 unsigned MaxTargetVectorWidthInBits = std::numeric_limits<unsigned>::max();
4083 if (TTI && !TTI->enableScalableVectorization())
4084 // Scale the vector width by 2 as rough estimate to also consider
4085 // interleaving.
4086 MaxTargetVectorWidthInBits =
4087 TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector) * 2;
4088
4089 DepChecker = std::make_unique<MemoryDepChecker>(
4090 *PSE, AC, DT, L, SymbolicStrides, MaxTargetVectorWidthInBits, LoopGuards);
4091 PtrRtChecking =
4092 std::make_unique<RuntimePointerChecking>(*DepChecker, SE, LoopGuards);
4093 if (canAnalyzeLoop())
4094 CanVecMem = analyzeLoop(AA, LI, TLI, DT);
4095}
4096
4097void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
4098 if (CanVecMem) {
4099 OS.indent(Depth) << "Memory dependences are safe";
4100 const MemoryDepChecker &DC = getDepChecker();
4101 if (!DC.isSafeForAnyVectorWidth())
4102 OS << " with a maximum safe vector width of "
4103 << DC.getMaxSafeVectorWidthInBits() << " bits";
4105 uint64_t SLDist = DC.getStoreLoadForwardSafeDistanceInBits();
4106 OS << ", with a maximum safe store-load forward width of " << SLDist
4107 << " bits";
4108 }
4109 if (PtrRtChecking->Need)
4110 OS << " with run-time checks";
4111 OS << "\n";
4112 }
4113
4114 if (HasConvergentOp)
4115 OS.indent(Depth) << "Has convergent operation in loop\n";
4116
4117 if (Report)
4118 OS.indent(Depth) << "Report: " << Report->getMsg() << "\n";
4119
4120 if (auto *Dependences = DepChecker->getDependences()) {
4121 OS.indent(Depth) << "Dependences:\n";
4122 for (const auto &Dep : *Dependences) {
4123 Dep.print(OS, Depth + 2, DepChecker->getMemoryInstructions());
4124 OS << "\n";
4125 }
4126 } else
4127 OS.indent(Depth) << "Too many dependences, not recorded\n";
4128
4129 // List the pair of accesses need run-time checks to prove independence.
4130 PtrRtChecking->print(OS, Depth);
4131 if (PtrRtChecking->Need && !HasCompletePtrRtChecking)
4132 OS.indent(Depth) << "Generated run-time checks are incomplete\n";
4133 OS << "\n";
4134
4135 OS.indent(Depth)
4136 << "Non vectorizable stores to invariant address were "
4137 << (HasStoreStoreDependenceInvolvingLoopInvariantAddress ||
4138 HasLoadStoreDependenceInvolvingLoopInvariantAddress
4139 ? ""
4140 : "not ")
4141 << "found in loop.\n";
4142
4143 OS.indent(Depth) << "SCEV assumptions:\n";
4144 PSE->getPredicate().print(OS, Depth);
4145
4146 OS << "\n";
4147
4148 OS.indent(Depth) << "Expressions re-written:\n";
4149 PSE->print(OS, Depth);
4150}
4151
4153 bool AllowPartial) {
4154 const auto &[It, Inserted] = LoopAccessInfoMap.try_emplace(&L);
4155
4156 // We need to create the LoopAccessInfo if either we don't already have one,
4157 // or if it was created with a different value of AllowPartial.
4158 if (Inserted || It->second->hasAllowPartial() != AllowPartial)
4159 It->second = std::make_unique<LoopAccessInfo>(&L, &SE, TTI, TLI, &AA, &DT,
4160 &LI, AC, AllowPartial);
4161
4162 return *It->second;
4163}
4165 // Collect LoopAccessInfo entries that may keep references to IR outside the
4166 // analyzed loop or SCEVs that may have been modified or invalidated. At the
4167 // moment, that is loops requiring memory or SCEV runtime checks, as those cache
4168 // SCEVs, e.g. for pointer expressions.
4169 LoopAccessInfoMap.remove_if([](const auto &Entry) {
4170 const auto &LAI = Entry.second;
4171 return !(LAI->getRuntimePointerChecking()->getChecks().empty() &&
4172 LAI->getPSE().getPredicate().isAlwaysTrue());
4173 });
4174}
4175
4177 Function &F, const PreservedAnalyses &PA,
4178 FunctionAnalysisManager::Invalidator &Inv) {
4179 // Check whether our analysis is preserved.
4180 auto PAC = PA.getChecker<LoopAccessAnalysis>();
4181 if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>())
4182 // If not, give up now.
4183 return true;
4184
4185 // Check whether the analyses we depend on became invalid for any reason.
4186 // Skip checking TargetLibraryAnalysis as it is immutable and can't become
4187 // invalid.
4188 return Inv.invalidate<AAManager>(F, PA) ||
4189 Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) ||
4190 Inv.invalidate<LoopAnalysis>(F, PA) ||
4191 Inv.invalidate<DominatorTreeAnalysis>(F, PA);
4192}
4193
4196 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
4197 auto &AA = FAM.getResult<AAManager>(F);
4198 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
4199 auto &LI = FAM.getResult<LoopAnalysis>(F);
4200 auto &TTI = FAM.getResult<TargetIRAnalysis>(F);
4201 auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
4202 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
4203 return LoopAccessInfoManager(SE, AA, DT, LI, &TTI, &TLI, &AC);
4204}
4205
4206AnalysisKey LoopAccessAnalysis::Key;
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
This file implements a class to represent arbitrary precision integral constant values and operations...
@ Scaled
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file implements the BitVector class.
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< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
CanMerge
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Forward Handle Accesses
DXIL Resource Access
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
Generic implementation of equivalence classes through the use Tarjan's efficient union-find algorithm...
#define DEBUG_TYPE
Hexagon Common GEP
#define _
This header defines various interfaces for pass management in LLVM.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static cl::opt< StencilMergePolicy > StencilMerge("stencil-runtime-check-merge", cl::Hidden, cl::desc("Control stencil-pattern merging of runtime memory checks"), cl::init(StencilMergePolicy::Off), cl::values(clEnumValN(StencilMergePolicy::Off, "off", "Disable stencil merge (default)"), clEnumValN(StencilMergePolicy::Auto, "auto", "Enable stencil merge when runtime check count exceeds " "-vectorize-memory-check-threshold"), clEnumValN(StencilMergePolicy::Force, "force", "Always attempt stencil merge regardless of check " "count")))
static cl::opt< unsigned > MaxDependences("max-dependences", cl::Hidden, cl::desc("Maximum number of dependences collected by " "loop-access analysis (default = 100)"), cl::init(100))
We collect dependences up to this threshold.
static cl::opt< bool > EnableForwardingConflictDetection("store-to-load-forwarding-conflict-detection", cl::Hidden, cl::desc("Enable conflict detection in loop-access analysis"), cl::init(true))
Enable store-to-load forwarding conflict detection.
static void findForkedSCEVs(ScalarEvolution *SE, const Loop *L, Value *Ptr, SmallVectorImpl< PointerIntPair< const SCEV *, 1, bool > > &ScevList, unsigned Depth)
static const SCEV * mulSCEVNoOverflow(const SCEV *A, const SCEV *B, ScalarEvolution &SE)
Returns A * B, if it is guaranteed not to unsigned wrap.
static bool isNoWrap(PredicatedScalarEvolution &PSE, const SCEVAddRecExpr *AR, Value *Ptr, Type *AccessTy, const Loop *L, const DominatorTree &DT, std::optional< int64_t > Stride=std::nullopt, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Check whether AR is a non-wrapping AddRec.
static cl::opt< unsigned > MemoryCheckMergeThreshold("memory-check-merge-threshold", cl::Hidden, cl::desc("Maximum number of comparisons done when trying to merge " "runtime memory checks. (default = 100)"), cl::init(100))
The maximum iterations used to merge memory checks.
static RuntimeCheckingPtrGroup buildMergedStencilGroup(const RuntimePointerChecking &RtCheck, ArrayRef< unsigned > AllMembers, const SCEV *MergedLow, const SCEV *MergedHigh, ArrayRef< unsigned > GroupIndices)
Build the merged stencil group for one DepSet, after the cost model has decided the merge is profitab...
static bool isNeverAbove(const StencilDecomposition &A, const StencilDecomposition &B)
Return true if offset A is never higher than offset B.
static std::optional< APInt > getStencilStrideUpperLimit(const StencilDecomposition &D, unsigned BitWidth)
Find a common upper limit M for the positive strides in D.
static const SCEV * getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp)
Get the stride of a pointer access in a loop.
static bool isKnownNonDecreasingInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE)
Return true if S is known to be monotonically non-decreasing (in the unsigned sense,...
static cl::opt< ElementCount, true > VectorizationFactor("force-vector-width", cl::Hidden, cl::desc("Sets the SIMD width. Zero is autoselect."), cl::location(VectorizerParams::VectorizationFactor))
static bool evaluatePtrAddRecAtMaxBTCWillNotWrap(const SCEVAddRecExpr *AR, const SCEV *MaxBTC, const SCEV *EltSize, ScalarEvolution &SE, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC, std::optional< ScalarEvolution::LoopGuards > &LoopGuards)
Return true, if evaluating AR at MaxBTC cannot wrap, because AR at MaxBTC is guaranteed inbounds of t...
static cl::opt< unsigned, true > VectorizationInterleave("force-vector-interleave", cl::Hidden, cl::desc("Sets the vectorization interleave count. " "Zero is autoselect."), cl::location(VectorizerParams::VectorizationInterleave))
static cl::opt< unsigned > StencilMergeMaxGroups("stencil-merge-max-groups", cl::Hidden, cl::desc("Skip stencil group merging when the number of runtime checking groups " "exceeds this limit, to bound compile time (default =4096)."), cl::init(4096))
static cl::opt< bool, true > HoistRuntimeChecks("hoist-runtime-checks", cl::Hidden, cl::desc("Hoist inner loop runtime memory checks to outer loop if possible"), cl::location(VectorizerParams::HoistRuntimeChecks), cl::init(true))
static DenseMap< const RuntimeCheckingPtrGroup *, unsigned > getPtrToIdxMap(ArrayRef< RuntimeCheckingPtrGroup > CheckingGroups)
Assign each RuntimeCheckingPtrGroup pointer an index for stable UTC output.
static cl::opt< unsigned, true > RuntimeMemoryCheckThreshold("runtime-memory-check-threshold", cl::Hidden, cl::desc("When performing memory disambiguation checks at runtime do not " "generate more than this number of comparisons (default = 8)."), cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8))
static void visitPointers(Value *StartPtr, const Loop &InnermostLoop, function_ref< void(Value *)> AddPointer)
static bool isSafeDependenceDistance(const DataLayout &DL, ScalarEvolution &SE, const SCEV &MaxBTC, const SCEV &Dist, uint64_t MaxStride)
Given a dependence-distance Dist between two memory accesses, that have strides in the same direction...
constexpr unsigned MaxStencilDecomposeDepth
Recursion cap for addScaledStencilTerm.
static SmallVector< unsigned, 4 > collectCandidateMembers(ArrayRef< StencilDecomposition > Offsets, bool ForMin)
Find the members that can define the merged bound on one side.
static bool addScaledStencilTerm(const SCEV *Term, int64_t Mult, unsigned Depth, StencilDecomposition &D)
Add one term of a stencil offset to D.
static cl::opt< unsigned, true > VectorizeMemoryCheckThreshold("vectorize-memory-check-threshold", cl::Hidden, cl::desc("The maximum allowed number of runtime memory checks"), cl::location(VectorizerParams::VectorizeMemoryCheckThreshold), cl::init(128))
static bool areStridedAccessesIndependent(uint64_t Distance, uint64_t Stride, uint64_t TypeByteSize)
Check the dependence for two accesses with the same stride Stride.
static const SCEV * getMinFromExprs(const SCEV *I, const SCEV *J, ScalarEvolution *SE)
Compare I and J and return the minimum.
static bool collectStrideLimits(const StencilDecomposition &D, unsigned BitWidth, ScalarEvolution &SE, StrideLimits &Limits)
Add to Limits the checks each stride s of D needs: 1 <= s isNeverAbove assumes every stride is 1 or m...
static std::pair< unsigned, unsigned > computeStencilMergeCost(const RuntimePointerChecking &RtCheck, ArrayRef< unsigned > GroupIndices, const StrideLimits &Local, const StrideLimits &Committed, unsigned NumBoundOperands)
Local cost model: count the runtime checks required before and after replacing one DepSet's groups (G...
static std::pair< const SCEV *, const SCEV * > getNonAffineMonotonicBounds(const Loop *Lp, const SCEV *PtrExpr, const SCEV *EltSizeSCEV, ScalarEvolution *SE)
Try to bound a loop-variant pointer that is not an affine AddRec.
static Value * getLoopVariantGEPOperand(Value *Ptr, ScalarEvolution *SE, Loop *Lp)
If Ptr is a GEP, which has a loop-variant operand, return that operand.
static cl::opt< unsigned > MaxForkedSCEVDepth("max-forked-scev-depth", cl::Hidden, cl::desc("Maximum recursion depth when finding forked SCEVs (default = 5)"), cl::init(5))
static std::optional< StencilDecomposition > decomposeStencilOffset(const SCEV *Expr, ScalarEvolution &SE, const Loop &L)
Try to decompose Expr into a stencil offset function of loop-invariant strides: C + a1*s1 + a2*s2 + ....
static cl::opt< bool > SpeculateUnitStride("laa-speculate-unit-stride", cl::Hidden, cl::desc("Speculate that non-constant strides are unit in LAA"), cl::init(true))
static cl::opt< bool > EnableMemAccessVersioning("enable-mem-access-versioning", cl::init(true), cl::Hidden, cl::desc("Enable symbolic stride memory access versioning"))
This enables versioning on the strides of symbolically striding memory accesses in code like the foll...
static const SCEV * addSCEVNoOverflow(const SCEV *A, const SCEV *B, ScalarEvolution &SE)
Returns A + B, if it is guaranteed not to unsigned wrap.
This header provides classes for managing per-loop analyses.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
This file implements a map that provides insertion order iteration.
This file provides utility analysis objects describing memory locations.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
FunctionAnalysisManager FAM
This file defines the PointerIntPair class.
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This pass exposes codegen information to IR-level passes.
static const X86InstrFMA3Group Groups[]
A manager for alias analyses.
Class for arbitrary precision integers.
Definition APInt.h:78
std::optional< uint64_t > tryZExtValue() const
Get zero extended value if possible.
Definition APInt.h:1572
APInt abs() const
Get the absolute value.
Definition APInt.h:1815
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1086
std::optional< int64_t > trySExtValue() const
Get sign extended value if possible.
Definition APInt.h:1594
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool isConvergent() const
Determine if the invoke is convergent.
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
bool isNegative() const
Definition Constants.h:214
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A debug info location.
Definition DebugLoc.h:126
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:794
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
iterator_range< member_iterator > members(const ECValue &ECV) const
bool contains(const ElemTy &V) const
Returns true if V is contained an equivalence class.
const ECValue & insert(const ElemTy &Data)
Insert a new value into the union/find set, ignoring the request if the value already exists.
member_iterator member_end() const
const ElemTy & getLeaderValue(const ElemTy &V) const
Return the leader for the specified value that is in the set.
member_iterator findLeader(const ElemTy &V) const
Given a value in the set, return a member iterator for the equivalence class it is in.
void eraseClass(const ElemTy &V)
Erase the class containing V, i.e.
member_iterator unionSets(const ElemTy &V1, const ElemTy &V2)
Merge the two equivalence sets for the specified values, inserting them if they do not already exist ...
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition Function.h:699
bool empty() const
Definition Function.h:844
PointerType * getType() const
Global values are always pointers.
An instruction for reading from memory.
Value * getPointerOperand()
static constexpr LocationSize beforeOrAfterPointer()
Any location before or after the base pointer (but still within the underlying object).
This analysis provides dependence information for the memory accesses of a loop.
LLVM_ABI Result run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
LLVM_ABI const LoopAccessInfo & getInfo(Loop &L, bool AllowPartial=false)
Drive the analysis of memory accesses in the loop.
const MemoryDepChecker & getDepChecker() const
the Memory Dependence Checker which can determine the loop-independent and loop-carried dependences b...
LLVM_ABI bool isInvariant(Value *V) const
Returns true if value V is loop invariant.
LLVM_ABI void print(raw_ostream &OS, unsigned Depth=0) const
Print the information about the memory accesses in the loop.
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.
LLVM_ABI LoopAccessInfo(Loop *L, ScalarEvolution *SE, const TargetTransformInfo *TTI, const TargetLibraryInfo *TLI, AAResults *AA, DominatorTree *DT, LoopInfo *LI, AssumptionCache *AC, bool AllowPartial=false)
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
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.
BlockT * getHeader() const
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
std::string getLocStr() const
Return a string containing the debug location of the loop (file name + line number if present,...
Definition LoopInfo.cpp:730
bool isAnnotatedParallel() const
Returns true if the loop is annotated parallel.
Definition LoopInfo.cpp:628
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
Definition LoopInfo.cpp:695
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1435
Checks memory dependences among accesses to the same underlying object to determine whether there vec...
ArrayRef< unsigned > getOrderForAccess(Value *Ptr, bool IsWrite) const
Return the program order indices for the access location (Ptr, IsWrite).
bool isSafeForAnyStoreLoadForwardDistances() const
Return true if there are no store-load forwarding dependencies.
LLVM_ABI bool areDepsSafe(const DepCandidates &AccessSets, ArrayRef< MemAccessInfo > CheckDeps)
Check whether the dependencies between the accesses are safe, and records the dependence information ...
bool isSafeForAnyVectorWidth() const
Return true if the number of elements that are safe to operate on simultaneously is not bounded.
static bool isStoreLoadForwardingConflict(uint64_t Distance, uint64_t VectorStoreSize, uint64_t TypeByteSize, uint64_t LoadElementSize=0)
Returns true if a memory dependence at byte distance Distance between a store (with element size Type...
PointerIntPair< Value *, 1, bool > MemAccessInfo
EquivalenceClasses< MemAccessInfo > DepCandidates
Set of potential dependent memory accesses.
bool shouldRetryWithRuntimeChecks() const
In same cases when the dependency check fails we can still vectorize the loop with a dynamic array ac...
const Loop * getInnermostLoop() const
uint64_t getMaxSafeVectorWidthInBits() const
Return the number of elements that are safe to operate on simultaneously, multiplied by the size of t...
bool isSafeForVectorization() const
No memory dependence was encountered that would inhibit vectorization.
const SmallVectorImpl< Dependence > * getDependences() const
Returns the memory dependences.
LLVM_ABI SmallVector< Instruction *, 4 > getInstructionsForAccess(Value *Ptr, bool isWrite) const
Find the set of instructions that read or write via Ptr.
VectorizationSafetyStatus
Type to keep track of the status of the dependence check.
LLVM_ABI void addAccess(StoreInst *SI)
Register the location (instructions are given increasing numbers) of a write access.
uint64_t getStoreLoadForwardSafeDistanceInBits() const
Return safe power-of-2 number of elements, which do not prevent store-load forwarding,...
Representation for a specific memory location.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
LocationSize Size
The maximum size of the location, in address-units, or UnknownSize if the size is not known.
AAMDNodes AATags
The metadata nodes which describes the aliasing of the location (each member is null if that kind of ...
const Value * Ptr
The address of the start of the location.
Diagnostic information for optimization analysis remarks.
PointerIntPair - This class implements a pair of a pointer and small integer.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
LLVM_ABI void addPredicate(const SCEVPredicate &Pred)
Adds a new predicate.
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
LLVM_ABI const SCEVPredicate & getPredicate() const
LLVM_ABI const SCEVAddRecExpr * getAsAddRec(Value *V, SmallVectorImpl< const SCEVPredicate * > *WrapPredsAdded=nullptr)
Attempts to produce an AddRecExpr for V by adding additional SCEV predicates.
LLVM_ABI void addPredicates(ArrayRef< const SCEVPredicate * > Preds)
Adds all predicates in Preds.
LLVM_ABI const SCEV * getBackedgeTakenCount()
Get the (predicated) backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSymbolicMaxBackedgeTakenCount()
Get the (predicated) symbolic max backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
Holds information about the memory runtime legality checks to verify that a group of pointers do not ...
bool Need
This flag indicates if we need to add the runtime check.
void reset()
Reset the state of the pointer runtime information.
unsigned getNumberOfChecks() const
Returns the number of run-time checks required according to needsChecking.
LLVM_ABI void printChecks(raw_ostream &OS, const SmallVectorImpl< RuntimePointerCheck > &Checks, unsigned Depth=0) const
Print Checks.
LLVM_ABI bool insert(Loop *Lp, Value *Ptr, const SCEV *PtrExpr, Type *AccessTy, bool WritePtr, unsigned DepSetId, unsigned ASId, PredicatedScalarEvolution &PSE, bool NeedsFreeze, bool IsForked)
Insert a pointer and calculate the start and end SCEVs.
LLVM_ABI bool needsChecking(const RuntimeCheckingPtrGroup &M, const RuntimeCheckingPtrGroup &N) const
Decide if we need to add a check between two groups of pointers, according to needsChecking.
LLVM_ABI void print(raw_ostream &OS, unsigned Depth=0) const
Print the list run-time memory checks necessary.
SmallVector< RuntimeCheckingPtrGroup, 2 > CheckingGroups
Holds a partitioning of pointers into "check groups".
static LLVM_ABI bool arePointersInSamePartition(const SmallVectorImpl< int > &PtrToPartition, unsigned PtrIdx1, unsigned PtrIdx2)
Check if pointers are in the same partition.
LLVM_ABI void generateChecks(MemoryDepChecker::DepCandidates &DepCands)
Generate the checks and store it.
SmallVector< PointerInfo, 2 > Pointers
Information about the pointers that may require checking.
This node represents a polynomial recurrence on the trip count of the specified loop.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This class represents a constant integer value.
ConstantInt * getValue() const
const APInt & getAPInt() const
SCEVFlags getNoWrapFlags(SCEVFlags Mask=FlagsNoWrapMask) const
This class represents an assumption made using SCEV expressions which can be checked at run-time.
virtual bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const =0
Returns true if this predicate implies N.
This class represents a composition of other SCEV predicates, and is the class that most clients will...
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
This class represents an analyzed expression in the program.
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
Type * getType() const
Return the LLVM type of this SCEV expression.
SCEVTypes getSCEVType() const
Analysis pass that exposes the ScalarEvolution for a function.
static LLVM_ABI LoopGuards collect(const Loop *L, ScalarEvolution &SE)
Collect rewrite map for loop guards for loop L, together with flags indicating if NUW and NSW can be ...
The main scalar evolution driver.
const SCEV * getConstantMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
LLVM_ABI bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
LLVM_ABI const SCEV * getZeroExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI Type * getWiderType(Type *Ty1, Type *Ty2) const
LLVM_ABI const SCEV * getAbsExpr(const SCEV *Op, bool IsNSW)
LLVM_ABI bool isKnownNonPositive(const SCEV *S)
Test if the given expression is known to be non-positive.
LLVM_ABI bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
LLVM_ABI bool willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI=nullptr)
Is operation BinOp between LHS and RHS provably does not have a signed/unsigned overflow (Signed)?
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI const SCEVPredicate * getEqualPredicate(const SCEV *LHS, const SCEV *RHS)
LLVM_ABI SCEVUse getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI const SCEV * getNoopOrSignExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
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 isKnownPositive(const SCEV *S)
Test if the given expression is known to be positive.
LLVM_ABI SCEVUse getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI Type * getEffectiveSCEVType(Type *Ty) const
Return a type with the same bitwidth as the given type and which represents how SCEV will treat the g...
LLVM_ABI const SCEVPredicate * getComparePredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
APInt getSignedRangeMin(const SCEV *S)
Determine the min of the signed range for a particular SCEV.
LLVM_ABI const SCEV * getUMaxExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI const SCEV * getStoreSizeOfExpr(Type *IntTy, Type *StoreTy)
Return an expression for the store size of StoreTy that is type IntTy.
LLVM_ABI const SCEVPredicate * getWrapPredicate(const SCEVAddRecExpr *AR, SCEVWrapPredicate::IncrementWrapFlags AddedFlags)
LLVM_ABI const SCEV * getNoopOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI std::optional< MonotonicPredicateType > getMonotonicPredicateType(const SCEVAddRecExpr *LHS, ICmpInst::Predicate Pred)
If, for all loop invariant X, the predicate "LHS `Pred` X" is monotonically increasing or decreasing,...
LLVM_ABI const SCEV * getCouldNotCompute()
LLVM_ABI SCEVUse getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
LLVM_ABI const SCEV * getPointerBase(const SCEV *V)
Transitively follow the chain of pointer-type operands until reaching a SCEV that does not have a sin...
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
LLVM_ABI const SCEV * getPtrToAddrExpr(const SCEV *Op)
LLVM_ABI const SCEVAddRecExpr * convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Preds)
Tries to convert the S expression to an AddRec expression, adding additional predicates to Preds as r...
LLVM_ABI const SCEV * getSizeOfExpr(Type *IntTy, TypeSize Size)
Return an expression for a TypeSize.
LLVM_ABI std::optional< APInt > computeConstantDifference(const SCEV *LHS, const SCEV *RHS)
Compute LHS - RHS and returns the result as an APInt if it is a constant, and std::nullopt if it isn'...
LLVM_ABI const SCEV * getNegativeSCEV(const SCEV *V, SCEVFlags Flags=SCEV::FlagNone)
Return the SCEV object corresponding to -V.
LLVM_ABI const SCEV * rewriteUsingPredicate(const SCEV *S, const Loop *L, const SCEVPredicate &A)
Re-writes the SCEV according to the Predicates in A.
LLVM_ABI std::pair< const SCEV *, const SCEV * > SplitIntoInitAndPostInc(const Loop *L, const SCEV *S)
Splits SCEV expression S into two SCEVs.
LLVM_ABI const SCEV * getUMinExpr(SCEVUse LHS, SCEVUse RHS, bool Sequential=false)
LLVM_ABI const SCEV * getTruncateOrSignExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
bool contains(const T &V) const
Check if the SmallSet contains the given element.
Definition SmallSet.h:229
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void resize(size_type N)
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.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
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
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI uint64_t getPointerDereferenceableBytes(const DataLayout &DL, bool &CanBeNull, bool *CanBeFreed) const
Returns the number of bytes known to be dereferenceable for the pointer value.
Definition Value.cpp:918
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:182
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:165
@ Entry
Definition COFF.h:862
bool match(Val *V, const Pattern &P)
bind_cst_ty m_scev_APInt(const APInt *&C)
Match an SCEV constant and bind it to an APInt.
is_undef_or_poison m_scev_UndefOrPoison()
Match an SCEVUnknown wrapping undef or poison.
specificloop_ty m_SpecificLoop(const Loop *L)
match_bind< const SCEVMulExpr > m_scev_Mul(const SCEVMulExpr *&V)
specificscev_ty m_scev_Specific(const SCEV *S)
Match if we have a specific specified SCEV.
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)
LocationClass< Ty > location(Ty &L)
DiagnosticInfoOptimizationBase::Argument NV
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI std::pair< const SCEV *, const SCEV * > getStartAndEndForAccess(const Loop *Lp, const SCEV *PtrExpr, Type *AccessTy, const SCEV *BTC, const SCEV *MaxBTC, ScalarEvolution *SE, DenseMap< std::pair< const SCEV *, const SCEV * >, std::pair< const SCEV *, const SCEV * > > *PointerBounds, DominatorTree *DT, AssumptionCache *AC, std::optional< ScalarEvolution::LoopGuards > &LoopGuards)
Calculate Start and End points of memory access using exact backedge taken count BTC if computable or...
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
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
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
LLVM_ABI RetainedKnowledge getKnowledgeForValue(const Value *V, ArrayRef< Attribute::AttrKind > AttrKinds, AssumptionCache &AC, function_ref< bool(RetainedKnowledge, Instruction *, const CallBase::BundleOpInfo *)> Filter=[](auto...) { return true;})
Return a valid Knowledge associated to the Value V if its Attribute kind is in AttrKinds and it match...
LLVM_ABI bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name)
Returns true if Name is applied to TheLoop and enabled.
LLVM_ABI Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
unsigned getPointerAddressSpace(const Type *T)
Definition SPIRVUtils.h:395
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
LLVM_ABI const SCEV * replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE, const Loop *Lp, const SymbolicStrideMap &PtrToStride, Value *Ptr, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Return the SCEV corresponding to a pointer with the symbolic stride replaced with constant one,...
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
constexpr std::enable_if_t< std::is_signed_v< T >, std::pair< T, bool > > AddOverflow(T X, T Y)
Add two signed integers, computing the two's complement truncated result, returning a pair {result,...
Definition MathExtras.h:698
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.
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CtxI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition STLExtras.h:2042
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
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
DenseMap< Value *, const SCEVUnknown * > SymbolicStrideMap
Maps a pointer to its symbolic (non-constant) stride.
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI std::optional< int64_t > getPointersDiff(Type *ElemTyA, Value *PtrA, Type *ElemTyB, Value *PtrB, const DataLayout &DL, ScalarEvolution &SE, bool StrictCheck=false, bool CheckType=true)
Returns the distance between the pointers PtrA and PtrB iff they are compatible and it is possible to...
LLVM_ABI bool sortPtrAccesses(ArrayRef< Value * > VL, Type *ElemTy, const DataLayout &DL, ScalarEvolution &SE, SmallVectorImpl< unsigned > &SortedIndices)
Attempt to sort the pointers in VL and return the sorted indices in SortedIndices,...
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
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
TargetTransformInfo TTI
@ Add
Sum of integers.
LLVM_ABI bool isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL, ScalarEvolution &SE, bool CheckType=true)
Returns true if the memory operations A and B are consecutive.
IntPtrTy
Definition InstrProf.h:82
DWARFExpression::Operation Op
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr U AbsoluteValue(T X)
Return the absolute value of a signed integer, converted to the corresponding unsigned integer type.
Definition MathExtras.h:587
constexpr int64_t maxIntN(int64_t N)
Gets the maximum value for a N-bit signed integer.
Definition MathExtras.h:233
constexpr unsigned BitWidth
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
constexpr std::enable_if_t< std::is_signed_v< T >, std::pair< T, bool > > MulOverflow(T X, T Y)
Multiply two signed integers, computing the two's complement truncated result, returning a pair {resu...
Definition MathExtras.h:772
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI std::optional< int64_t > getStrideFromAddRec(const SCEVAddRecExpr *AR, const Loop *Lp, Type *AccessTy, Value *Ptr, PredicatedScalarEvolution &PSE)
If AR is an affine AddRec for Lp with a constant step, return the step in units of AccessTy's allocat...
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Definition bit.h:347
LLVM_ABI void getUnderlyingObjects(const Value *V, SmallVectorImpl< const Value * > &Objects, const LoopInfo *LI=nullptr, unsigned MaxLookup=MaxLookupSearchDepth)
This method is similar to getUnderlyingObject except that it can look through phi and select instruct...
@ Auto
Determine whether to use color based on the command line argument and the raw_ostream.
Definition WithColor.h:43
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
IR Values for the lower and upper bounds of a pointer evolution.
Result of decomposing a SCEV expression into stencil offset form: Offset = Constant + sum(Coefficient...
SmallMapVector< const SCEV *, int64_t, 4 > Coefficients
Map from loop-invariant stride SCEV to its integer coefficient.
MDNode * Scope
The tag for alias scope specification (used with noalias).
Definition Metadata.h:797
MDNode * TBAA
The tag for type-based alias analysis.
Definition Metadata.h:791
MDNode * NoAlias
The tag specifying the noalias scope.
Definition Metadata.h:800
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
Instruction * getDestination(const MemoryDepChecker &DepChecker) const
Return the destination instruction of the dependence.
DepType Type
The type of the dependence.
unsigned Destination
Index of the destination of the dependence in the InstMap vector.
LLVM_ABI bool isPossiblyBackward() const
May be a lexically backward dependence type (includes Unknown).
Instruction * getSource(const MemoryDepChecker &DepChecker) const
Return the source instruction of the dependence.
LLVM_ABI bool isForward() const
Lexically forward dependence.
LLVM_ABI bool isBackward() const
Lexically backward dependence.
LLVM_ABI void print(raw_ostream &OS, unsigned Depth, const SmallVectorImpl< Instruction * > &Instrs) const
Print the dependence.
unsigned Source
Index of the source of the dependence in the InstMap vector.
DepType
The type of the dependence.
static LLVM_ABI const char * DepName[]
String version of the types.
static LLVM_ABI VectorizationSafetyStatus isSafeForVectorization(DepType Type)
Dependence types that don't prevent vectorization.
Represent one information held inside an operand bundle of an llvm.assume.
unsigned AddressSpace
Address space of the involved pointers.
LLVM_ABI bool addPointer(unsigned Index, const RuntimePointerChecking &RtCheck)
Tries to add the pointer recorded in RtCheck at index Index to this pointer checking group.
bool NeedsFreeze
Whether the pointer needs to be frozen after expansion, e.g.
LLVM_ABI RuntimeCheckingPtrGroup(unsigned Index, const RuntimePointerChecking &RtCheck)
Create a new pointer checking group containing a single pointer, with index Index in RtCheck.
const SCEV * High
The SCEV expression which represents the upper bound of all the pointers in this group.
SmallVector< unsigned, 2 > Members
Indices of all the pointers that constitute this grouping.
const SCEV * Low
The SCEV expression which represents the lower bound of all the pointers in this group.
bool IsWritePtr
Holds the information if this pointer is used for writing to memory.
unsigned DependencySetId
Holds the id of the set of pointers that could be dependent because of a shared underlying object.
unsigned AliasSetId
Holds the id of the disjoint alias set to which this pointer belongs.
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:342
static LLVM_ABI const unsigned MaxVectorWidth
Maximum SIMD width.
static LLVM_ABI unsigned VectorizeMemoryCheckThreshold
The maximum allowed number of runtime memory checks.
static LLVM_ABI unsigned RuntimeMemoryCheckThreshold
\When performing memory disambiguation checks at runtime do not make more than this number of compari...
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.
static LLVM_ABI bool HoistRuntimeChecks
Function object to check whether the first component of a container supported by std::get (like std::...
Definition STLExtras.h:1455