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