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/DenseMap.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SetVector.h"
22#include "llvm/ADT/SmallSet.h"
40#include "llvm/IR/BasicBlock.h"
41#include "llvm/IR/Constants.h"
42#include "llvm/IR/DataLayout.h"
43#include "llvm/IR/DebugLoc.h"
46#include "llvm/IR/Dominators.h"
47#include "llvm/IR/Function.h"
48#include "llvm/IR/InstrTypes.h"
49#include "llvm/IR/Instruction.h"
52#include "llvm/IR/PassManager.h"
53#include "llvm/IR/Type.h"
54#include "llvm/IR/Value.h"
55#include "llvm/IR/ValueHandle.h"
58#include "llvm/Support/Debug.h"
62#include <algorithm>
63#include <cassert>
64#include <cstdint>
65#include <iterator>
66#include <utility>
67#include <variant>
68#include <vector>
69
70using namespace llvm;
71using namespace llvm::SCEVPatternMatch;
72
73#define DEBUG_TYPE "loop-accesses"
74
76 VectorizationFactor("force-vector-width", cl::Hidden,
77 cl::desc("Sets the SIMD width. Zero is autoselect."),
80
82VectorizationInterleave("force-vector-interleave", cl::Hidden,
83 cl::desc("Sets the vectorization interleave count. "
84 "Zero is autoselect."),
88
90 "runtime-memory-check-threshold", cl::Hidden,
91 cl::desc("When performing memory disambiguation checks at runtime do not "
92 "generate more than this number of comparisons (default = 8)."),
95
96/// The maximum iterations used to merge memory checks
98 "memory-check-merge-threshold", cl::Hidden,
99 cl::desc("Maximum number of comparisons done when trying to merge "
100 "runtime memory checks. (default = 100)"),
101 cl::init(100));
102
103/// Maximum SIMD width.
104const unsigned VectorizerParams::MaxVectorWidth = 64;
105
106/// We collect dependences up to this threshold.
108 MaxDependences("max-dependences", cl::Hidden,
109 cl::desc("Maximum number of dependences collected by "
110 "loop-access analysis (default = 100)"),
111 cl::init(100));
112
113/// This enables versioning on the strides of symbolically striding memory
114/// accesses in code like the following.
115/// for (i = 0; i < N; ++i)
116/// A[i * Stride1] += B[i * Stride2] ...
117///
118/// Will be roughly translated to
119/// if (Stride1 == 1 && Stride2 == 1) {
120/// for (i = 0; i < N; i+=4)
121/// A[i:i+3] += ...
122/// } else
123/// ...
125 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
126 cl::desc("Enable symbolic stride memory access versioning"));
127
128/// Enable store-to-load forwarding conflict detection. This option can
129/// be disabled for correctness testing.
131 "store-to-load-forwarding-conflict-detection", cl::Hidden,
132 cl::desc("Enable conflict detection in loop-access analysis"),
133 cl::init(true));
134
136 "max-forked-scev-depth", cl::Hidden,
137 cl::desc("Maximum recursion depth when finding forked SCEVs (default = 5)"),
138 cl::init(5));
139
141 "laa-speculate-unit-stride", cl::Hidden,
142 cl::desc("Speculate that non-constant strides are unit in LAA"),
143 cl::init(true));
144
146 "hoist-runtime-checks", cl::Hidden,
147 cl::desc(
148 "Hoist inner loop runtime memory checks to outer loop if possible"),
151
153 return ::VectorizationInterleave.getNumOccurrences() > 0;
154}
155
156const SCEV *
158 const SymbolicStrideMap &PtrToStride,
159 Value *Ptr) {
160 const SCEV *OrigSCEV = PSE.getSCEV(Ptr);
161
162 // If there is an entry in the map return the SCEV of the pointer with the
163 // symbolic stride replaced by one.
164 const SCEVUnknown *StrideSCEV = PtrToStride.lookup(Ptr);
165 if (!StrideSCEV)
166 // For a non-symbolic stride, just return the original expression.
167 return OrigSCEV;
168
169 ScalarEvolution *SE = PSE.getSE();
170 const SCEV *CT = SE->getOne(StrideSCEV->getType());
171 PSE.addPredicate(*SE->getEqualPredicate(StrideSCEV, CT));
172 const SCEV *Expr = PSE.getSCEV(Ptr);
173
174 LLVM_DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV
175 << " by: " << *Expr << "\n");
176 return Expr;
177}
178
180 unsigned Index, const RuntimePointerChecking &RtCheck)
181 : High(RtCheck.Pointers[Index].End), Low(RtCheck.Pointers[Index].Start),
182 AddressSpace(RtCheck.Pointers[Index]
183 .PointerValue->getType()
185 NeedsFreeze(RtCheck.Pointers[Index].NeedsFreeze) {
186 Members.push_back(Index);
187}
188
189/// Returns \p A + \p B, if it is guaranteed not to unsigned wrap. Otherwise
190/// return nullptr. \p A and \p B must have the same type.
191static const SCEV *addSCEVNoOverflow(const SCEV *A, const SCEV *B,
192 ScalarEvolution &SE) {
193 if (!SE.willNotOverflow(Instruction::Add, /*IsSigned=*/false, A, B))
194 return nullptr;
195 return SE.getAddExpr(A, B);
196}
197
198/// Returns \p A * \p B, if it is guaranteed not to unsigned wrap. Otherwise
199/// return nullptr. \p A and \p B must have the same type.
200static const SCEV *mulSCEVNoOverflow(const SCEV *A, const SCEV *B,
201 ScalarEvolution &SE) {
202 if (!SE.willNotOverflow(Instruction::Mul, /*IsSigned=*/false, A, B))
203 return nullptr;
204 return SE.getMulExpr(A, B);
205}
206
207/// Return true, if evaluating \p AR at \p MaxBTC cannot wrap, because \p AR at
208/// \p MaxBTC is guaranteed inbounds of the accessed object.
210 const SCEVAddRecExpr *AR, const SCEV *MaxBTC, const SCEV *EltSize,
212 AssumptionCache *AC,
213 std::optional<ScalarEvolution::LoopGuards> &LoopGuards) {
214 auto *PointerBase = SE.getPointerBase(AR->getStart());
215 auto *StartPtr = dyn_cast<SCEVUnknown>(PointerBase);
216 if (!StartPtr)
217 return false;
218 const Loop *L = AR->getLoop();
219 bool CheckForNonNull;
220 Value *StartPtrV = StartPtr->getValue();
221 // We can ignore frees, as the fact that an object of a certain size existed
222 // at the location *at some point* is sufficient to derive the nowrap fact.
223 uint64_t DerefBytes = StartPtrV->getPointerDereferenceableBytes(
224 DL, CheckForNonNull, /*CanBeFreed=*/nullptr);
225
226 // If the deref size is only known when the pointer is non-null, ignore it
227 // here and fall back to a dereferenceable assumption below.
228 if (DerefBytes && CheckForNonNull)
229 DerefBytes = 0;
230
231 const SCEV *Step = AR->getStepRecurrence(SE);
232 Type *WiderTy = SE.getWiderType(MaxBTC->getType(), Step->getType());
233 const SCEV *DerefBytesSCEV = SE.getConstant(WiderTy, DerefBytes);
234
235 // Check if we have a suitable dereferencable assumption we can use.
236 Instruction *CtxI = &*L->getHeader()->getFirstNonPHIIt();
237 if (BasicBlock *LoopPred = L->getLoopPredecessor()) {
238 if (isa<UncondBrInst, CondBrInst>(LoopPred->getTerminator()))
239 CtxI = LoopPred->getTerminator();
240 }
242 StartPtrV, Attribute::Dereferenceable, *AC,
243 [&](RetainedKnowledge RK, Instruction *Assume, auto) {
244 if (!isValidAssumeForContext(Assume, CtxI, DT))
245 return false;
246 const SCEV *DerefRKSCEV = SE.getSCEV(RK.IRArgValue);
247 Type *CommonTy =
248 SE.getWiderType(DerefBytesSCEV->getType(), DerefRKSCEV->getType());
249 DerefBytesSCEV = SE.getNoopOrZeroExtend(DerefBytesSCEV, CommonTy);
250 DerefRKSCEV = SE.getNoopOrZeroExtend(DerefRKSCEV, CommonTy);
251 DerefBytesSCEV = SE.getUMaxExpr(DerefBytesSCEV, DerefRKSCEV);
252 // Continue with other assumptions.
253 return false;
254 });
255
256 if (DerefBytesSCEV->isZero())
257 return false;
258
259 bool IsKnownNonNegative = SE.isKnownNonNegative(Step);
260 if (!IsKnownNonNegative && !SE.isKnownNegative(Step))
261 return false;
262
263 WiderTy = SE.getWiderType(WiderTy, DerefBytesSCEV->getType());
264 Step = SE.getNoopOrSignExtend(Step, WiderTy);
265 MaxBTC = SE.getNoopOrZeroExtend(MaxBTC, WiderTy);
266
267 // For the computations below, make sure they don't unsigned wrap.
268 // FIXME: for a negative step the lowest accessed address is not
269 // AR->getStart() but AR->evaluateAtIteration(MaxBTC, SE); the check below
270 // therefore compares StartPtr against the highest accessed address instead
271 // of the lowest.
272 if (!SE.isKnownPredicate(CmpInst::ICMP_UGE, AR->getStart(), StartPtr))
273 return false;
274 const SCEV *StartOffset = SE.getNoopOrZeroExtend(
275 SE.getMinusSCEV(AR->getStart(), StartPtr), WiderTy);
276
277 if (!LoopGuards)
278 LoopGuards.emplace(ScalarEvolution::LoopGuards::collect(AR->getLoop(), SE));
279 MaxBTC = SE.applyLoopGuards(MaxBTC, *LoopGuards);
280
281 const SCEV *AbsStep = SE.getAbsExpr(Step, /*IsNSW=*/false);
282 // Total distance (in bytes) between the first and the last
283 // accessed pointer.
284 const SCEV *DistToLastIter = mulSCEVNoOverflow(MaxBTC, AbsStep, SE);
285 if (!DistToLastIter) {
286 // Re-try with constant max backedge-taken count if using the symbolic one
287 // failed.
288 MaxBTC = SE.getConstantMaxBackedgeTakenCount(AR->getLoop());
289 if (isa<SCEVCouldNotCompute>(MaxBTC))
290 return false;
291 MaxBTC = SE.getNoopOrZeroExtend(MaxBTC, WiderTy);
292 DistToLastIter = mulSCEVNoOverflow(MaxBTC, AbsStep, SE);
293 if (!DistToLastIter)
294 return false;
295 }
296
297 // Total length in bytes of the accessed range (from the first accessed
298 // byte through the end of the last access).
299 const SCEV *AccessedBytes = addSCEVNoOverflow(
300 DistToLastIter, SE.getNoopOrZeroExtend(EltSize, WiderTy), SE);
301 if (!AccessedBytes)
302 return false;
303
304 // Compute MaxOffset per direction: exclusive upper offset of the
305 // accessed range.
306 const SCEV *MaxOffset;
307 if (IsKnownNonNegative) {
308 MaxOffset = addSCEVNoOverflow(StartOffset, AccessedBytes, SE);
309 if (!MaxOffset)
310 return false;
311 DerefBytesSCEV = SE.applyLoopGuards(DerefBytesSCEV, *LoopGuards);
312 } else {
313 // FIXME: two independent off-by-EltSize bugs on this branch:
314 // 1. StartOffset here is actually the HIGHEST offset, because it is
315 // computed from AR->getStart() rather than
316 // AR->evaluateAtIteration(MaxBTC, SE) (see FIXME above).
317 // 2. The lower check is over-strict by EltSize and the upper is
318 // under-counted by EltSize.
319 assert(SE.isKnownNegative(Step) && "must be known negative");
320 if (!SE.isKnownPredicate(CmpInst::ICMP_SGE, StartOffset, AccessedBytes))
321 return false;
322 MaxOffset = StartOffset;
323 }
324 // MaxOffset must not exceed the deref-region end.
325 return SE.isKnownPredicate(CmpInst::ICMP_ULE, MaxOffset, DerefBytesSCEV);
326}
327
328/// Return true if \p S is known to be monotonically non-decreasing
329/// (in the unsigned sense, without unsigned wrap) across iterations of \p L.
330static bool isKnownNonDecreasingInLoop(const SCEV *S, const Loop *L,
331 ScalarEvolution &SE) {
332 if (SE.isLoopInvariant(S, L))
333 return true;
334
335 switch (S->getSCEVType()) {
336 case scUDivExpr: {
337 // Non-decreasing in the numerator when the divisor is loop-invariant.
338 const auto *UDiv = cast<SCEVUDivExpr>(S);
339 return SE.isLoopInvariant(UDiv->getRHS(), L) &&
340 isKnownNonDecreasingInLoop(UDiv->getLHS(), L, SE);
341 }
342 case scAddRecExpr: {
343 auto *AR = cast<SCEVAddRecExpr>(S);
344 assert(AR->getLoop() == L &&
345 "trying to check for AddRec in different loop");
348 }
349 default:
350 return false;
351 }
352}
353
354/// Try to bound a loop-variant pointer that is not an affine AddRec.
355///
356/// If the offset is provably monotonically non-decreasing the accessed range is
357/// bounded by the offset's value at the first iteration (via
358/// SplitIntoInitAndPostInc) and last iteration (via getSCEVAtScope)
359///
360/// Returns {nullptr, nullptr} if no such bound can be formed.
361static std::pair<const SCEV *, const SCEV *>
362getNonAffineMonotonicBounds(const Loop *Lp, const SCEV *PtrExpr,
363 ScalarEvolution *SE) {
364 const auto *PtrAdd = dyn_cast<SCEVAddExpr>(PtrExpr);
365 if (!PtrAdd || !PtrAdd->hasNoUnsignedWrap())
366 return {nullptr, nullptr};
367
368 const SCEV *Base = *find_if(PtrAdd->operands(), [](const auto &Op) {
369 return Op->getType()->isPointerTy();
370 });
372 return {nullptr, nullptr};
373
374 const SCEV *Offset = SE->getMinusSCEV(PtrExpr, Base);
377 return {nullptr, nullptr};
378
379 const SCEV *OffStart = SE->SplitIntoInitAndPostInc(Lp, Offset).first;
380 const SCEV *OffEnd = SE->getSCEVAtScope(Offset, Lp->getParentLoop());
381 if (isa<SCEVCouldNotCompute>(OffStart) || isa<SCEVCouldNotCompute>(OffEnd) ||
382 !SE->isLoopInvariant(OffStart, Lp) || !SE->isLoopInvariant(OffEnd, Lp))
383 return {nullptr, nullptr};
384
385 assert(SE->isKnownPredicate(CmpInst::ICMP_ULE, OffStart, OffEnd) &&
386 "Start must be provably <= End for monotonic expressions");
387
388 return {SE->getAddExpr(Base, OffStart), SE->getAddExpr(Base, OffEnd)};
389}
390
391std::pair<const SCEV *, const SCEV *> llvm::getStartAndEndForAccess(
392 const Loop *Lp, const SCEV *PtrExpr, Type *AccessTy, const SCEV *BTC,
393 const SCEV *MaxBTC, ScalarEvolution *SE,
394 DenseMap<std::pair<const SCEV *, const SCEV *>,
395 std::pair<const SCEV *, const SCEV *>> *PointerBounds,
397 std::optional<ScalarEvolution::LoopGuards> &LoopGuards) {
398 auto &DL = Lp->getHeader()->getDataLayout();
399 Type *IdxTy = DL.getIndexType(PtrExpr->getType());
400 const SCEV *EltSizeSCEV = SE->getStoreSizeOfExpr(IdxTy, AccessTy);
401
402 // Delegate to the SCEV-based overload, passing through the cache.
403 return getStartAndEndForAccess(Lp, PtrExpr, EltSizeSCEV, BTC, MaxBTC, SE,
404 PointerBounds, DT, AC, LoopGuards);
405}
406
407std::pair<const SCEV *, const SCEV *> llvm::getStartAndEndForAccess(
408 const Loop *Lp, const SCEV *PtrExpr, const SCEV *EltSizeSCEV,
409 const SCEV *BTC, const SCEV *MaxBTC, ScalarEvolution *SE,
410 DenseMap<std::pair<const SCEV *, const SCEV *>,
411 std::pair<const SCEV *, const SCEV *>> *PointerBounds,
413 std::optional<ScalarEvolution::LoopGuards> &LoopGuards) {
414 std::pair<const SCEV *, const SCEV *> *PtrBoundsPair;
415 if (PointerBounds) {
416 auto [Iter, Ins] = PointerBounds->insert(
417 {{PtrExpr, EltSizeSCEV},
418 {SE->getCouldNotCompute(), SE->getCouldNotCompute()}});
419 if (!Ins)
420 return Iter->second;
421 PtrBoundsPair = &Iter->second;
422 }
423
424 const SCEV *ScStart;
425 const SCEV *ScEnd;
426
427 auto &DL = Lp->getHeader()->getDataLayout();
428 if (SE->isLoopInvariant(PtrExpr, Lp)) {
429 ScStart = ScEnd = PtrExpr;
430 } else if (auto *AR = dyn_cast<SCEVAddRecExpr>(PtrExpr)) {
431 ScStart = AR->getStart();
432 if (!isa<SCEVCouldNotCompute>(BTC))
433 // Evaluating AR at an exact BTC is safe: LAA separately checks that
434 // accesses cannot wrap in the loop. If evaluating AR at BTC wraps, then
435 // the loop either triggers UB when executing a memory access with a
436 // poison pointer or the wrapping/poisoned pointer is not used.
437 ScEnd = AR->evaluateAtIteration(BTC, *SE);
438 else {
439 // Evaluating AR at MaxBTC may wrap and create an expression that is less
440 // than the start of the AddRec due to wrapping (for example consider
441 // MaxBTC = -2). If that's the case, set ScEnd to -(EltSize + 1). ScEnd
442 // will get incremented by EltSize before returning, so this effectively
443 // sets ScEnd to the maximum unsigned value for the type. Note that LAA
444 // separately checks that accesses cannot not wrap, so unsigned max
445 // represents an upper bound.
446 if (evaluatePtrAddRecAtMaxBTCWillNotWrap(AR, MaxBTC, EltSizeSCEV, *SE, DL,
447 DT, AC, LoopGuards)) {
448 ScEnd = AR->evaluateAtIteration(MaxBTC, *SE);
449 } else {
450 ScEnd = SE->getAddExpr(
451 SE->getNegativeSCEV(EltSizeSCEV),
454 AR->getType())));
455 }
456 }
457 const SCEV *Step = AR->getStepRecurrence(*SE);
458
459 // For expressions with negative step, the upper bound is ScStart and the
460 // lower bound is ScEnd.
461 if (const auto *CStep = dyn_cast<SCEVConstant>(Step)) {
462 if (CStep->getValue()->isNegative())
463 std::swap(ScStart, ScEnd);
464 } else {
465 // Fallback case: the step is not constant, but we can still
466 // get the upper and lower bounds of the interval by using min/max
467 // expressions.
468 ScStart = SE->getUMinExpr(ScStart, ScEnd);
469 ScEnd = SE->getUMaxExpr(AR->getStart(), ScEnd);
470 }
471 } else {
472 // The pointer is loop-variant but not an affine AddRec. Try to form a
473 // tight bound for a monotonic offset (see getNonAffineMonotonicBounds).
474 std::tie(ScStart, ScEnd) = getNonAffineMonotonicBounds(Lp, PtrExpr, SE);
475 if (!ScStart)
476 return {SE->getCouldNotCompute(), SE->getCouldNotCompute()};
477 }
478
479 assert(SE->isLoopInvariant(ScStart, Lp) && "ScStart needs to be invariant");
480 assert(SE->isLoopInvariant(ScEnd, Lp) && "ScEnd needs to be invariant");
481
482 // Add the size of the pointed element to ScEnd.
483 ScEnd = SE->getAddExpr(ScEnd, EltSizeSCEV);
484
485 std::pair<const SCEV *, const SCEV *> Res = {ScStart, ScEnd};
486 if (PointerBounds)
487 *PtrBoundsPair = Res;
488 return Res;
489}
490
491/// Calculate Start and End points of memory access using
492/// getStartAndEndForAccess.
493void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, const SCEV *PtrExpr,
494 Type *AccessTy, bool WritePtr,
495 unsigned DepSetId, unsigned ASId,
497 bool NeedsFreeze) {
498 const SCEV *SymbolicMaxBTC = PSE.getSymbolicMaxBackedgeTakenCount();
499 const SCEV *BTC = PSE.getBackedgeTakenCount();
500 const auto &[ScStart, ScEnd] = getStartAndEndForAccess(
501 Lp, PtrExpr, AccessTy, BTC, SymbolicMaxBTC, PSE.getSE(),
502 &DC.getPointerBounds(), DC.getDT(), DC.getAC(), LoopGuards);
504 !isa<SCEVCouldNotCompute>(ScEnd) &&
505 "must be able to compute both start and end expressions");
506 Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, PtrExpr,
507 NeedsFreeze);
508}
509
510bool RuntimePointerChecking::tryToCreateDiffCheck(
511 const RuntimeCheckingPtrGroup &CGI, const RuntimeCheckingPtrGroup &CGJ) {
512 // If either group contains multiple different pointers, bail out.
513 // TODO: Support multiple pointers by using the minimum or maximum pointer,
514 // depending on src & sink.
515 if (CGI.Members.size() != 1 || CGJ.Members.size() != 1)
516 return false;
517
518 const PointerInfo *Src = &Pointers[CGI.Members[0]];
519 const PointerInfo *Sink = &Pointers[CGJ.Members[0]];
520
521 // If either pointer is read and written, multiple checks may be needed. Bail
522 // out.
523 if (!DC.getOrderForAccess(Src->PointerValue, !Src->IsWritePtr).empty() ||
524 !DC.getOrderForAccess(Sink->PointerValue, !Sink->IsWritePtr).empty())
525 return false;
526
527 ArrayRef<unsigned> AccSrc =
528 DC.getOrderForAccess(Src->PointerValue, Src->IsWritePtr);
529 ArrayRef<unsigned> AccSink =
530 DC.getOrderForAccess(Sink->PointerValue, Sink->IsWritePtr);
531 // If either pointer is accessed multiple times, there may not be a clear
532 // src/sink relation. Bail out for now.
533 if (AccSrc.size() != 1 || AccSink.size() != 1)
534 return false;
535
536 // If the sink is accessed before src, swap src/sink.
537 if (AccSink[0] < AccSrc[0])
538 std::swap(Src, Sink);
539
540 const SCEVConstant *Step;
541 const SCEV *SrcStart;
542 const SCEV *SinkStart;
543 const Loop *InnerLoop = DC.getInnermostLoop();
544 if (!match(Src->Expr,
546 m_SpecificLoop(InnerLoop))) ||
547 !match(Sink->Expr,
549 m_SpecificLoop(InnerLoop))))
550 return false;
551
553 DC.getInstructionsForAccess(Src->PointerValue, Src->IsWritePtr);
555 DC.getInstructionsForAccess(Sink->PointerValue, Sink->IsWritePtr);
556 Type *SrcTy = getLoadStoreType(SrcInsts[0]);
557 Type *DstTy = getLoadStoreType(SinkInsts[0]);
559 return false;
560
561 const DataLayout &DL = InnerLoop->getHeader()->getDataLayout();
562 unsigned AllocSize =
563 std::max(DL.getTypeAllocSize(SrcTy), DL.getTypeAllocSize(DstTy));
564
565 // Only matching constant steps matching the AllocSize are supported at the
566 // moment. This simplifies the difference computation. Can be extended in the
567 // future.
568 if (Step->getAPInt().abs() != AllocSize)
569 return false;
570
571 // When counting down, the dependence distance needs to be swapped.
572 if (Step->getValue()->isNegative())
573 std::swap(SinkStart, SrcStart);
574
575 const SCEV *SinkStartInt = SE->getPtrToAddrExpr(SinkStart);
576 const SCEV *SrcStartInt = SE->getPtrToAddrExpr(SrcStart);
577 if (isa<SCEVCouldNotCompute>(SinkStartInt) ||
578 isa<SCEVCouldNotCompute>(SrcStartInt))
579 return false;
580
581 // If the start values for both Src and Sink also vary according to an outer
582 // loop, then it's probably better to avoid creating diff checks because
583 // they may not be hoisted. We should instead let llvm::addRuntimeChecks
584 // do the expanded full range overlap checks, which can be hoisted.
585 if (HoistRuntimeChecks && InnerLoop->getParentLoop() &&
586 isa<SCEVAddRecExpr>(SinkStartInt) && isa<SCEVAddRecExpr>(SrcStartInt)) {
587 auto *SrcStartAR = cast<SCEVAddRecExpr>(SrcStartInt);
588 auto *SinkStartAR = cast<SCEVAddRecExpr>(SinkStartInt);
589 const Loop *StartARLoop = SrcStartAR->getLoop();
590 if (StartARLoop == SinkStartAR->getLoop() &&
591 StartARLoop == InnerLoop->getParentLoop() &&
592 // If the diff check would already be loop invariant (due to the
593 // recurrences being the same), then we prefer to keep the diff checks
594 // because they are cheaper.
595 SrcStartAR->getStepRecurrence(*SE) !=
596 SinkStartAR->getStepRecurrence(*SE)) {
597 LLVM_DEBUG(dbgs() << "LAA: Not creating diff runtime check, since these "
598 "cannot be hoisted out of the outer loop\n");
599 return false;
600 }
601 }
602
603 LLVM_DEBUG(dbgs() << "LAA: Creating diff runtime check for:\n"
604 << "SrcStart: " << *SrcStartInt << '\n'
605 << "SinkStartInt: " << *SinkStartInt << '\n');
606 DiffChecks.emplace_back(SrcStartInt, SinkStartInt, AllocSize,
607 Src->NeedsFreeze || Sink->NeedsFreeze);
608 return true;
609}
610
612 SmallVector<RuntimePointerCheck, 4> Checks;
613
614 for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
615 for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) {
618
619 if (needsChecking(CGI, CGJ)) {
620 CanUseDiffCheck = CanUseDiffCheck && tryToCreateDiffCheck(CGI, CGJ);
621 Checks.emplace_back(&CGI, &CGJ);
622 }
623 }
624 }
625 return Checks;
626}
627
630 assert(Checks.empty() && "Checks is not empty");
631 groupChecks(DepCands);
632 Checks = generateChecks();
633}
634
636 const RuntimeCheckingPtrGroup &M, const RuntimeCheckingPtrGroup &N) const {
637 for (const auto &I : M.Members)
638 for (const auto &J : N.Members)
639 if (needsChecking(I, J))
640 return true;
641 return false;
642}
643
644/// Compare \p I and \p J and return the minimum.
645/// Return nullptr in case we couldn't find an answer.
646static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
647 ScalarEvolution *SE) {
648 std::optional<APInt> Diff = SE->computeConstantDifference(J, I);
649 if (!Diff)
650 return nullptr;
651 return Diff->isNegative() ? J : I;
652}
653
655 unsigned Index, const RuntimePointerChecking &RtCheck) {
656 return addPointer(
657 Index, RtCheck.Pointers[Index].Start, RtCheck.Pointers[Index].End,
658 RtCheck.Pointers[Index].PointerValue->getType()->getPointerAddressSpace(),
659 RtCheck.Pointers[Index].NeedsFreeze, *RtCheck.SE);
660}
661
662bool RuntimeCheckingPtrGroup::addPointer(unsigned Index, const SCEV *Start,
663 const SCEV *End, unsigned AS,
664 bool NeedsFreeze,
665 ScalarEvolution &SE) {
666 assert(AddressSpace == AS &&
667 "all pointers in a checking group must be in the same address space");
668
669 // Compare the starts and ends with the known minimum and maximum
670 // of this set. We need to know how we compare against the min/max
671 // of the set in order to be able to emit memchecks.
672 const SCEV *Min0 = getMinFromExprs(Start, Low, &SE);
673 if (!Min0)
674 return false;
675
676 const SCEV *Min1 = getMinFromExprs(End, High, &SE);
677 if (!Min1)
678 return false;
679
680 // Update the low bound expression if we've found a new min value.
681 if (Min0 == Start)
682 Low = Start;
683
684 // Update the high bound expression if we've found a new max value.
685 if (Min1 != End)
686 High = End;
687
688 Members.push_back(Index);
689 this->NeedsFreeze |= NeedsFreeze;
690 return true;
691}
692
693void RuntimePointerChecking::groupChecks(
695 // We build the groups from dependency candidates equivalence classes
696 // because:
697 // - We know that pointers in the same equivalence class share
698 // the same underlying object and therefore there is a chance
699 // that we can compare pointers
700 // - We wouldn't be able to merge two pointers for which we need
701 // to emit a memcheck. The classes in DepCands are already
702 // conveniently built such that no two pointers in the same
703 // class need checking against each other.
704
705 // We use the following (greedy) algorithm to construct the groups
706 // For every pointer in the equivalence class:
707 // For each existing group:
708 // - if the difference between this pointer and the min/max bounds
709 // of the group is a constant, then make the pointer part of the
710 // group and update the min/max bounds of that group as required.
711
712 CheckingGroups.clear();
713
714 // If we need to check two pointers to the same underlying object
715 // with a non-constant difference, we shouldn't perform any pointer
716 // grouping with those pointers. This is because we can easily get
717 // into cases where the resulting check would return false, even when
718 // the accesses are safe.
719 //
720 // The following example shows this:
721 // for (i = 0; i < 1000; ++i)
722 // a[5000 + i * m] = a[i] + a[i + 9000]
723 //
724 // Here grouping gives a check of (5000, 5000 + 1000 * m) against
725 // (0, 10000) which is always false. However, if m is 1, there is no
726 // dependence. Not grouping the checks for a[i] and a[i + 9000] allows
727 // us to perform an accurate check in this case.
728 //
729 // In the above case, we have a non-constant distance and an Unknown
730 // dependence between accesses to the same underlying object, and could retry
731 // with runtime checks without dependency information being available. In this
732 // case we will use the fallback path and create separate checking groups for
733 // accesses not present in DepCands.
734
735 unsigned TotalComparisons = 0;
736
738 for (unsigned Index = 0; Index < Pointers.size(); ++Index)
739 PositionMap[Pointers[Index].PointerValue].push_back(Index);
740
741 // We need to keep track of what pointers we've already seen so we
742 // don't process them twice.
744
745 // Go through all equivalence classes, get the "pointer check groups"
746 // and add them to the overall solution. We use the order in which accesses
747 // appear in 'Pointers' to enforce determinism.
748 for (unsigned I = 0; I < Pointers.size(); ++I) {
749 // We've seen this pointer before, and therefore already processed
750 // its equivalence class.
751 if (Seen.contains(I))
752 continue;
753
755 Pointers[I].IsWritePtr);
756
757 // If there is no entry in the dependency partition, there are no potential
758 // accesses to merge; simply add a new pointer checking group.
759 if (!DepCands.contains(Access)) {
760 CheckingGroups.push_back(RuntimeCheckingPtrGroup(I, *this));
761 continue;
762 }
763
765
766 // Because DepCands is constructed by visiting accesses in the order in
767 // which they appear in alias sets (which is deterministic) and the
768 // iteration order within an equivalence class member is only dependent on
769 // the order in which unions and insertions are performed on the
770 // equivalence class, the iteration order is deterministic.
771 for (auto M : DepCands.members(Access)) {
772 auto PointerI = PositionMap.find(M.getPointer());
773 // If we can't find the pointer in PositionMap that means we can't
774 // generate a memcheck for it.
775 if (PointerI == PositionMap.end())
776 continue;
777 for (unsigned Pointer : PointerI->second) {
778 bool Merged = false;
779 // Mark this pointer as seen.
780 Seen.insert(Pointer);
781
782 // Go through all the existing sets and see if we can find one
783 // which can include this pointer.
784 for (RuntimeCheckingPtrGroup &Group : Groups) {
785 // Don't perform more than a certain amount of comparisons.
786 // This should limit the cost of grouping the pointers to something
787 // reasonable. If we do end up hitting this threshold, the algorithm
788 // will create separate groups for all remaining pointers.
789 if (TotalComparisons > MemoryCheckMergeThreshold)
790 break;
791
792 TotalComparisons++;
793
794 if (Group.addPointer(Pointer, *this)) {
795 Merged = true;
796 break;
797 }
798 }
799
800 if (!Merged)
801 // We couldn't add this pointer to any existing set or the threshold
802 // for the number of comparisons has been reached. Create a new group
803 // to hold the current pointer.
804 Groups.emplace_back(Pointer, *this);
805 }
806 }
807
808 // We've computed the grouped checks for this partition.
809 // Save the results and continue with the next one.
811 }
812}
813
815 const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
816 unsigned PtrIdx2) {
817 return (PtrToPartition[PtrIdx1] != -1 &&
818 PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
819}
820
821bool RuntimePointerChecking::needsChecking(unsigned I, unsigned J) const {
822 const PointerInfo &PointerI = Pointers[I];
823 const PointerInfo &PointerJ = Pointers[J];
824
825 // No need to check if two readonly pointers intersect.
826 if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
827 return false;
828
829 // Only need to check pointers between two different dependency sets.
830 if (PointerI.DependencySetId == PointerJ.DependencySetId)
831 return false;
832
833 // Only need to check pointers in the same alias set.
834 return PointerI.AliasSetId == PointerJ.AliasSetId;
835}
836
837/// Assign each RuntimeCheckingPtrGroup pointer an index for stable UTC output.
841 for (const auto &[Idx, CG] : enumerate(CheckingGroups))
842 PtrIndices[&CG] = Idx;
843 return PtrIndices;
844}
845
848 unsigned Depth) const {
849 unsigned N = 0;
850 auto PtrIndices = getPtrToIdxMap(CheckingGroups);
851 for (const auto &[Check1, Check2] : Checks) {
852 const auto &First = Check1->Members, &Second = Check2->Members;
853 OS.indent(Depth) << "Check " << N++ << ":\n";
854 OS.indent(Depth + 2) << "Comparing group GRP" << PtrIndices.at(Check1)
855 << ":\n";
856 for (unsigned K : First)
857 OS.indent(Depth + 2) << *Pointers[K].PointerValue << "\n";
858 OS.indent(Depth + 2) << "Against group GRP" << PtrIndices.at(Check2)
859 << ":\n";
860 for (unsigned K : Second)
861 OS.indent(Depth + 2) << *Pointers[K].PointerValue << "\n";
862 }
863}
864
866
867 OS.indent(Depth) << "Run-time memory checks:\n";
868 printChecks(OS, Checks, Depth);
869
870 OS.indent(Depth) << "Grouped accesses:\n";
871 auto PtrIndices = getPtrToIdxMap(CheckingGroups);
872 for (const auto &CG : CheckingGroups) {
873 OS.indent(Depth + 2) << "Group GRP" << PtrIndices.at(&CG) << ":\n";
874 OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High
875 << ")\n";
876 for (unsigned Member : CG.Members) {
877 OS.indent(Depth + 6) << "Member: " << *Pointers[Member].Expr << "\n";
878 }
879 }
880}
881
882namespace {
883
884/// Analyses memory accesses in a loop.
885///
886/// Checks whether run time pointer checks are needed and builds sets for data
887/// dependence checking.
888class AccessAnalysis {
889public:
890 using MemAccessInfo =
891 PointerIntPair<Value * /* AccessPtr */, 1, bool /* IsWrite */>;
892
893 AccessAnalysis(const Loop *TheLoop, AAResults *AA, const LoopInfo *LI,
896 SmallPtrSetImpl<MDNode *> &LoopAliasScopes)
897 : TheLoop(TheLoop), BAA(*AA), AST(BAA), LI(LI), DT(DT), DepCands(DA),
898 PSE(PSE), LoopAliasScopes(LoopAliasScopes) {
899 // We're analyzing dependences across loop iterations.
900 BAA.enableCrossIterationMode();
901 }
902
903 /// Register a load and whether it is only read from.
904 void addLoad(const MemoryLocation &Loc, Type *AccessTy, bool IsReadOnly) {
905 Value *Ptr = const_cast<Value *>(Loc.Ptr);
906 AST.add(adjustLoc(Loc));
907 Accesses[MemAccessInfo(Ptr, false)].insert(AccessTy);
908 if (IsReadOnly)
909 ReadOnlyPtr.insert(Ptr);
910 }
911
912 /// Register a store.
913 void addStore(const MemoryLocation &Loc, Type *AccessTy) {
914 Value *Ptr = const_cast<Value *>(Loc.Ptr);
915 AST.add(adjustLoc(Loc));
916 Accesses[MemAccessInfo(Ptr, true)].insert(AccessTy);
917 }
918
919 /// Check if we can emit a run-time no-alias check for \p Access.
920 ///
921 /// Returns true if we can emit a run-time no alias check for \p Access.
922 /// If we can check this access, this also adds it to a dependence set and
923 /// adds a run-time to check for it to \p RtCheck. If \p Assume is true,
924 /// we will attempt to use additional run-time checks in order to get
925 /// the bounds of the pointer.
926 bool createCheckForAccess(RuntimePointerChecking &RtCheck,
927 MemAccessInfo Access, Type *AccessTy,
928 const SymbolicStrideMap &Strides,
929 DenseMap<Value *, unsigned> &DepSetId,
930 Loop *TheLoop, unsigned &RunningDepId,
931 unsigned ASId, bool Assume);
932
933 /// Check whether we can check the pointers at runtime for
934 /// non-intersection.
935 ///
936 /// Returns true if we need no check or if we do and we can generate them
937 /// (i.e. the pointers have computable bounds). A return value of false means
938 /// we couldn't analyze and generate runtime checks for all pointers in the
939 /// loop, but if \p AllowPartial is set then we will have checks for those
940 /// pointers we could analyze. \p DepChecker is used to remove unknown
941 /// dependences from DepCands.
942 bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, Loop *TheLoop,
943 const SymbolicStrideMap &Strides,
944 Value *&UncomputablePtr, bool AllowPartial,
945 const MemoryDepChecker &DepChecker);
946
947 /// Goes over all memory accesses, checks whether a RT check is needed
948 /// and builds sets of dependent accesses.
949 void buildDependenceSets();
950
951 /// Initial processing of memory accesses determined that we need to
952 /// perform dependency checking.
953 ///
954 /// Note that this can later be cleared if we retry memcheck analysis without
955 /// dependency checking (i.e. ShouldRetryWithRuntimeChecks).
956 bool isDependencyCheckNeeded() const { return !CheckDeps.empty(); }
957
958 /// We decided that no dependence analysis would be used. Reset the state.
959 void resetDepChecks(MemoryDepChecker &DepChecker) {
960 CheckDeps.clear();
961 DepChecker.clearDependences();
962 }
963
964 ArrayRef<MemAccessInfo> getDependenciesToCheck() const { return CheckDeps; }
965
966private:
967 using PtrAccessMap = MapVector<MemAccessInfo, SmallSetVector<Type *, 1>>;
968
969 /// Adjust the MemoryLocation so that it represents accesses to this
970 /// location across all iterations, rather than a single one.
971 MemoryLocation adjustLoc(MemoryLocation Loc) const {
972 // The accessed location varies within the loop, but remains within the
973 // underlying object.
975 Loc.AATags.Scope = adjustAliasScopeList(Loc.AATags.Scope);
976 Loc.AATags.NoAlias = adjustAliasScopeList(Loc.AATags.NoAlias);
977 return Loc;
978 }
979
980 /// Drop alias scopes that are only valid within a single loop iteration.
981 MDNode *adjustAliasScopeList(MDNode *ScopeList) const {
982 if (!ScopeList)
983 return nullptr;
984
985 // For the sake of simplicity, drop the whole scope list if any scope is
986 // iteration-local.
987 if (any_of(ScopeList->operands(), [&](Metadata *Scope) {
988 return LoopAliasScopes.contains(cast<MDNode>(Scope));
989 }))
990 return nullptr;
991
992 return ScopeList;
993 }
994
995 /// Map of all accesses. Values are the types used to access memory pointed to
996 /// by the pointer.
997 PtrAccessMap Accesses;
998
999 /// The loop being checked.
1000 const Loop *TheLoop;
1001
1002 /// List of accesses that need a further dependence check.
1004
1005 /// Set of pointers that are read only.
1006 SmallPtrSet<Value*, 16> ReadOnlyPtr;
1007
1008 /// Batched alias analysis results.
1009 BatchAAResults BAA;
1010
1011 /// An alias set tracker to partition the access set by underlying object and
1012 //intrinsic property (such as TBAA metadata).
1013 AliasSetTracker AST;
1014
1015 /// The LoopInfo of the loop being checked.
1016 const LoopInfo *LI;
1017
1018 /// The dominator tree of the function.
1019 DominatorTree &DT;
1020
1021 /// Sets of potentially dependent accesses - members of one set share an
1022 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
1023 /// dependence check.
1025
1026 /// Initial processing of memory accesses determined that we may need
1027 /// to add memchecks. Perform the analysis to determine the necessary checks.
1028 ///
1029 /// Note that, this is different from isDependencyCheckNeeded. When we retry
1030 /// memcheck analysis without dependency checking
1031 /// (i.e. ShouldRetryWithRuntimeChecks), isDependencyCheckNeeded is
1032 /// cleared while this remains set if we have potentially dependent accesses.
1033 bool IsRTCheckAnalysisNeeded = false;
1034
1035 /// The SCEV predicate containing all the SCEV-related assumptions.
1036 PredicatedScalarEvolution &PSE;
1037
1038 DenseMap<Value *, SmallVector<const Value *, 16>> UnderlyingObjects;
1039
1040 /// Alias scopes that are declared inside the loop, and as such not valid
1041 /// across iterations.
1042 SmallPtrSetImpl<MDNode *> &LoopAliasScopes;
1043};
1044
1045} // end anonymous namespace
1046
1047std::optional<int64_t>
1049 Type *AccessTy, Value *Ptr,
1051 if (isa<ScalableVectorType>(AccessTy)) {
1052 LLVM_DEBUG(dbgs() << "LAA: Bad stride - Scalable object: " << *AccessTy
1053 << "\n");
1054 return std::nullopt;
1055 }
1056
1057 // The access function must stride over the innermost loop.
1058 if (Lp != AR->getLoop()) {
1059 LLVM_DEBUG({
1060 dbgs() << "LAA: Bad stride - Not striding over innermost loop ";
1061 if (Ptr)
1062 dbgs() << *Ptr << " ";
1063
1064 dbgs() << "SCEV: " << *AR << "\n";
1065 });
1066 return std::nullopt;
1067 }
1068
1069 // Check the step is constant.
1070 const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
1071
1072 // Calculate the pointer stride and check if it is constant.
1073 const APInt *APStepVal;
1074 if (!match(Step, m_scev_APInt(APStepVal))) {
1075 LLVM_DEBUG({
1076 dbgs() << "LAA: Bad stride - Not a constant strided ";
1077 if (Ptr)
1078 dbgs() << *Ptr << " ";
1079 dbgs() << "SCEV: " << *AR << "\n";
1080 });
1081 return std::nullopt;
1082 }
1083
1084 const auto &DL = Lp->getHeader()->getDataLayout();
1085 TypeSize AllocSize = DL.getTypeAllocSize(AccessTy);
1086 int64_t Size = AllocSize.getFixedValue();
1087
1088 // Huge step value - give up.
1089 std::optional<int64_t> StepVal = APStepVal->trySExtValue();
1090 if (!StepVal)
1091 return std::nullopt;
1092
1093 // Strided access.
1094 return *StepVal % Size ? std::nullopt : std::make_optional(*StepVal / Size);
1095}
1096
1097/// Check whether \p AR is a non-wrapping AddRec. If \p Ptr is not nullptr, use
1098/// information from the IR pointer value to determine no-wrap. If \p Predicates
1099/// is not nullptr add no-wrap assumptions if needed.
1100static bool
1102 Type *AccessTy, const Loop *L, const DominatorTree &DT,
1103 std::optional<int64_t> Stride = std::nullopt,
1104 SmallVectorImpl<const SCEVPredicate *> *Predicates = nullptr) {
1105 // FIXME: This should probably only return true for NUW.
1106 if (any(AR->getNoWrapFlags(SCEV::NoWrapMask)))
1107 return true;
1108
1110 return true;
1111
1112 // An nusw getelementptr that is an AddRec cannot wrap. If it would wrap,
1113 // the distance between the previously accessed location and the wrapped
1114 // location will be larger than half the pointer index type space. In that
1115 // case, the GEP would be poison and any memory access dependent on it would
1116 // be immediate UB when executed.
1118 GEP && GEP->hasNoUnsignedSignedWrap()) {
1119 // For the above reasoning to apply, the pointer must be dereferenced in
1120 // every iteration.
1121 if (L->getHeader() == L->getLoopLatch() ||
1122 any_of(GEP->users(), [L, &DT, GEP](User *U) {
1123 if (getLoadStorePointerOperand(U) != GEP)
1124 return false;
1125 BasicBlock *UserBB = cast<Instruction>(U)->getParent();
1126 if (!L->contains(UserBB))
1127 return false;
1128 return !LoopAccessInfo::blockNeedsPredication(UserBB, L, &DT);
1129 }))
1130 return true;
1131 }
1132
1133 if (!Stride)
1134 Stride = getStrideFromAddRec(AR, L, AccessTy, Ptr, PSE);
1135 if (Stride) {
1136 // If the null pointer is undefined, then a access sequence which would
1137 // otherwise access it can be assumed not to unsigned wrap. Note that this
1138 // assumes the object in memory is aligned to the natural alignment.
1139 unsigned AddrSpace = AR->getType()->getPointerAddressSpace();
1140 if (!NullPointerIsDefined(L->getHeader()->getParent(), AddrSpace) &&
1141 (Stride == 1 || Stride == -1))
1142 return true;
1143 }
1144
1145 if (Ptr && Predicates) {
1146 ScalarEvolution &SE = *PSE.getSE();
1150 Predicates->push_back(SE.getWrapPredicate(AR, Flags));
1151 LLVM_DEBUG(dbgs() << "LAA: Pointer may wrap:\n"
1152 << "LAA: Pointer: " << *Ptr << "\n"
1153 << "LAA: SCEV: " << *AR << "\n"
1154 << "LAA: Added an overflow assumption\n");
1155 return true;
1156 }
1157
1158 return false;
1159}
1160
1161static void visitPointers(Value *StartPtr, const Loop &InnermostLoop,
1162 function_ref<void(Value *)> AddPointer) {
1164 SmallVector<Value *> WorkList;
1165 WorkList.push_back(StartPtr);
1166
1167 while (!WorkList.empty()) {
1168 Value *Ptr = WorkList.pop_back_val();
1169 if (!Visited.insert(Ptr).second)
1170 continue;
1171 auto *PN = dyn_cast<PHINode>(Ptr);
1172 // SCEV does not look through non-header PHIs inside the loop. Such phis
1173 // can be analyzed by adding separate accesses for each incoming pointer
1174 // value.
1175 if (PN && InnermostLoop.contains(PN->getParent()) &&
1176 PN->getParent() != InnermostLoop.getHeader()) {
1177 llvm::append_range(WorkList, PN->incoming_values());
1178 } else
1179 AddPointer(Ptr);
1180 }
1181}
1182
1183// Walk back through the IR for a pointer, looking for a select like the
1184// following:
1185//
1186// %offset = select i1 %cmp, i64 %a, i64 %b
1187// %addr = getelementptr double, double* %base, i64 %offset
1188// %ld = load double, double* %addr, align 8
1189//
1190// We won't be able to form a single SCEVAddRecExpr from this since the
1191// address for each loop iteration depends on %cmp. We could potentially
1192// produce multiple valid SCEVAddRecExprs, though, and check all of them for
1193// memory safety/aliasing if needed.
1194//
1195// If we encounter some IR we don't yet handle, or something obviously fine
1196// like a constant, then we just add the SCEV for that term to the list passed
1197// in by the caller. If we have a node that may potentially yield a valid
1198// SCEVAddRecExpr then we decompose it into parts and build the SCEV terms
1199// ourselves before adding to the list.
1201 ScalarEvolution *SE, const Loop *L, Value *Ptr,
1203 unsigned Depth) {
1204 // If our Value is a SCEVAddRecExpr, loop invariant, not an instruction, or
1205 // we've exceeded our limit on recursion, just return whatever we have
1206 // regardless of whether it can be used for a forked pointer or not, along
1207 // with an indication of whether it might be a poison or undef value.
1208 const SCEV *Scev = SE->getSCEV(Ptr);
1209 if (isa<SCEVAddRecExpr>(Scev) || L->isLoopInvariant(Ptr) ||
1210 !isa<Instruction>(Ptr) || Depth == 0) {
1211 ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
1212 return;
1213 }
1214
1215 Depth--;
1216
1217 auto UndefPoisonCheck = [](PointerIntPair<const SCEV *, 1, bool> S) {
1218 return get<1>(S);
1219 };
1220
1221 auto GetBinOpExpr = [&SE](unsigned Opcode, const SCEV *L, const SCEV *R) {
1222 switch (Opcode) {
1223 case Instruction::Add:
1224 return SE->getAddExpr(L, R);
1225 case Instruction::Sub:
1226 return SE->getMinusSCEV(L, R);
1227 default:
1228 llvm_unreachable("Unexpected binary operator when walking ForkedPtrs");
1229 }
1230 };
1231
1233 unsigned Opcode = I->getOpcode();
1234 switch (Opcode) {
1235 case Instruction::GetElementPtr: {
1236 auto *GEP = cast<GetElementPtrInst>(I);
1237 Type *SourceTy = GEP->getSourceElementType();
1238 // We only handle base + single offset GEPs here for now.
1239 // Not dealing with preexisting gathers yet, so no vectors.
1240 if (I->getNumOperands() != 2 || SourceTy->isVectorTy()) {
1241 ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(GEP));
1242 break;
1243 }
1246 findForkedSCEVs(SE, L, I->getOperand(0), BaseScevs, Depth);
1247 findForkedSCEVs(SE, L, I->getOperand(1), OffsetScevs, Depth);
1248
1249 // See if we need to freeze our fork...
1250 bool NeedsFreeze = any_of(BaseScevs, UndefPoisonCheck) ||
1251 any_of(OffsetScevs, UndefPoisonCheck);
1252
1253 // Check that we only have a single fork, on either the base or the offset.
1254 // Copy the SCEV across for the one without a fork in order to generate
1255 // the full SCEV for both sides of the GEP.
1256 if (OffsetScevs.size() == 2 && BaseScevs.size() == 1)
1257 BaseScevs.push_back(BaseScevs[0]);
1258 else if (BaseScevs.size() == 2 && OffsetScevs.size() == 1)
1259 OffsetScevs.push_back(OffsetScevs[0]);
1260 else {
1261 ScevList.emplace_back(Scev, NeedsFreeze);
1262 break;
1263 }
1264
1265 Type *IntPtrTy = SE->getEffectiveSCEVType(GEP->getPointerOperandType());
1266
1267 // Find the size of the type being pointed to. We only have a single
1268 // index term (guarded above) so we don't need to index into arrays or
1269 // structures, just get the size of the scalar value.
1270 const SCEV *Size = SE->getSizeOfExpr(IntPtrTy, SourceTy);
1271
1272 for (auto [B, O] : zip(BaseScevs, OffsetScevs)) {
1273 const SCEV *Base = get<0>(B);
1274 const SCEV *Offset = get<0>(O);
1275
1276 // Scale up the offsets by the size of the type, then add to the bases.
1277 const SCEV *Scaled =
1279 ScevList.emplace_back(SE->getAddExpr(Base, Scaled), NeedsFreeze);
1280 }
1281 break;
1282 }
1283 case Instruction::Select: {
1285 // A select means we've found a forked pointer, but we currently only
1286 // support a single select per pointer so if there's another behind this
1287 // then we just bail out and return the generic SCEV.
1288 findForkedSCEVs(SE, L, I->getOperand(1), ChildScevs, Depth);
1289 findForkedSCEVs(SE, L, I->getOperand(2), ChildScevs, Depth);
1290 if (ChildScevs.size() == 2)
1291 append_range(ScevList, ChildScevs);
1292 else
1293 ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
1294 break;
1295 }
1296 case Instruction::PHI: {
1298 // A phi means we've found a forked pointer, but we currently only
1299 // support a single phi per pointer so if there's another behind this
1300 // then we just bail out and return the generic SCEV.
1301 if (I->getNumOperands() == 2) {
1302 findForkedSCEVs(SE, L, I->getOperand(0), ChildScevs, Depth);
1303 findForkedSCEVs(SE, L, I->getOperand(1), ChildScevs, Depth);
1304 }
1305 if (ChildScevs.size() == 2)
1306 append_range(ScevList, ChildScevs);
1307 else
1308 ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
1309 break;
1310 }
1311 case Instruction::Add:
1312 case Instruction::Sub: {
1315 findForkedSCEVs(SE, L, I->getOperand(0), LScevs, Depth);
1316 findForkedSCEVs(SE, L, I->getOperand(1), RScevs, Depth);
1317
1318 // See if we need to freeze our fork...
1319 bool NeedsFreeze =
1320 any_of(LScevs, UndefPoisonCheck) || any_of(RScevs, UndefPoisonCheck);
1321
1322 // Check that we only have a single fork, on either the left or right side.
1323 // Copy the SCEV across for the one without a fork in order to generate
1324 // the full SCEV for both sides of the BinOp.
1325 if (LScevs.size() == 2 && RScevs.size() == 1)
1326 RScevs.push_back(RScevs[0]);
1327 else if (RScevs.size() == 2 && LScevs.size() == 1)
1328 LScevs.push_back(LScevs[0]);
1329 else {
1330 ScevList.emplace_back(Scev, NeedsFreeze);
1331 break;
1332 }
1333
1334 for (auto [L, R] : zip(LScevs, RScevs))
1335 ScevList.emplace_back(GetBinOpExpr(Opcode, get<0>(L), get<0>(R)),
1336 NeedsFreeze);
1337 break;
1338 }
1339 default:
1340 // Just return the current SCEV if we haven't handled the instruction yet.
1341 LLVM_DEBUG(dbgs() << "ForkedPtr unhandled instruction: " << *I << "\n");
1342 ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
1343 break;
1344 }
1345}
1346
1347bool AccessAnalysis::createCheckForAccess(RuntimePointerChecking &RtCheck,
1348 MemAccessInfo Access, Type *AccessTy,
1349 const SymbolicStrideMap &StridesMap,
1351 Loop *TheLoop, unsigned &RunningDepId,
1352 unsigned ASId, bool Assume) {
1353 Value *Ptr = Access.getPointer();
1354 ScalarEvolution *SE = PSE.getSE();
1355 assert(SE->isSCEVable(Ptr->getType()) && "Value is not SCEVable!");
1356
1358 findForkedSCEVs(SE, TheLoop, Ptr, RTCheckPtrs, MaxForkedSCEVDepth);
1359 assert(!RTCheckPtrs.empty() &&
1360 "Must have some runtime-check pointer candidates");
1361
1362 // RTCheckPtrs must have size 2 if there are forked pointers. Otherwise, there
1363 // are no forked pointers; replaceSymbolicStridesSCEV in this case.
1364 auto IsLoopInvariantOrAR =
1365 [&SE, &TheLoop](const PointerIntPair<const SCEV *, 1, bool> &P) {
1366 return SE->isLoopInvariant(P.getPointer(), TheLoop) ||
1367 isa<SCEVAddRecExpr>(P.getPointer());
1368 };
1369 if (RTCheckPtrs.size() == 2 && all_of(RTCheckPtrs, IsLoopInvariantOrAR)) {
1370 LLVM_DEBUG(dbgs() << "LAA: Found forked pointer: " << *Ptr << "\n";
1371 for (const auto &[Idx, Q] : enumerate(RTCheckPtrs)) dbgs()
1372 << "\t(" << Idx << ") " << *Q.getPointer() << "\n");
1373 } else {
1374 RTCheckPtrs = {{replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr), false}};
1375 }
1376
1377 /// Check whether all pointers can participate in a runtime bounds check. They
1378 /// must either be invariant or non-wrapping affine AddRecs.
1380 for (auto &P : RTCheckPtrs) {
1381 // The bounds for loop-invariant pointer is trivial.
1382 if (SE->isLoopInvariant(P.getPointer(), TheLoop))
1383 continue;
1384
1385 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(P.getPointer());
1386 if (!AR && Assume)
1387 AR = PSE.getAsAddRec(Ptr, &Predicates);
1388 if (!AR || !AR->isAffine()) {
1389 // Check if bounds for non-affine monotonic expressions can be formed.
1390 if (!Assume ||
1391 !getNonAffineMonotonicBounds(TheLoop, P.getPointer(), SE).first)
1392 return false;
1393 continue;
1394 }
1395
1396 // If there's only one option for Ptr, commit the predicates collected by
1397 // getAsAddRec and look Ptr up again afterwards: the lookup below reads the
1398 // assumptions back from PSE, so they need to be committed first.
1399 if (RTCheckPtrs.size() == 1) {
1400 PSE.addPredicates(Predicates);
1401 Predicates.clear();
1402 if (auto *StrideAR = dyn_cast<SCEVAddRecExpr>(
1403 replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr)))
1404 AR = StrideAR;
1405 P.setPointer(AR);
1406 }
1407
1408 if (!isNoWrap(PSE, AR, RTCheckPtrs.size() == 1 ? Ptr : nullptr, AccessTy,
1409 TheLoop, DT, /*Stride=*/std::nullopt,
1410 Assume ? &Predicates : nullptr))
1411 return false;
1412 }
1413 PSE.addPredicates(Predicates);
1414
1415 for (const auto &[PtrExpr, NeedsFreeze] : RTCheckPtrs) {
1416 // The id of the dependence set.
1417 unsigned DepId;
1418
1419 if (DepCands.contains(Access)) {
1420 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
1421 unsigned &LeaderId = DepSetId[Leader];
1422 if (!LeaderId)
1423 LeaderId = RunningDepId++;
1424 DepId = LeaderId;
1425 } else
1426 // Each access has its own dependence set.
1427 DepId = RunningDepId++;
1428
1429 bool IsWrite = Access.getInt();
1430 RtCheck.insert(TheLoop, Ptr, PtrExpr, AccessTy, IsWrite, DepId, ASId, PSE,
1431 NeedsFreeze);
1432 LLVM_DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
1433 }
1434
1435 return true;
1436}
1437
1438bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
1439 Loop *TheLoop,
1440 const SymbolicStrideMap &StridesMap,
1441 Value *&UncomputablePtr, bool AllowPartial,
1442 const MemoryDepChecker &DepChecker) {
1443 // Find pointers with computable bounds. We are going to use this information
1444 // to place a runtime bound check.
1445 bool CanDoRT = true;
1446
1447 bool MayNeedRTCheck = false;
1448 if (!IsRTCheckAnalysisNeeded) return true;
1449
1450 if (auto *Deps = DepChecker.getDependences()) {
1451 // If there are unknown dependences, this means runtime checks are needed to
1452 // ensure there's no overlap between accesses to the same underlying object.
1453 // Remove the equivalence classes containing both source and destination
1454 // accesses from DepCands. This ensures runtime checks will be generated
1455 // between those accesses and prevents them from being grouped together.
1456 for (const auto &Dep : *Deps) {
1457 if (Dep.Type != MemoryDepChecker::Dependence::Unknown) {
1460 "Should only skip safe dependences");
1461 continue;
1462 }
1463 Instruction *Src = Dep.getSource(DepChecker);
1464 Instruction *Dst = Dep.getDestination(DepChecker);
1465 DepCands.eraseClass({getPointerOperand(Src), Src->mayWriteToMemory()});
1466 DepCands.eraseClass({getPointerOperand(Dst), Dst->mayWriteToMemory()});
1467 }
1468 } else {
1469 CheckDeps.clear();
1470 DepCands = {};
1471 }
1472
1473 // We assign a consecutive id to access from different alias sets.
1474 // Accesses between different groups doesn't need to be checked.
1475 unsigned ASId = 0;
1476 for (const auto &AS : AST) {
1477 int NumReadPtrChecks = 0;
1478 int NumWritePtrChecks = 0;
1479 bool CanDoAliasSetRT = true;
1480 ++ASId;
1481 auto ASPointers = AS.getPointers();
1482
1483 // We assign consecutive id to access from different dependence sets.
1484 // Accesses within the same set don't need a runtime check.
1485 unsigned RunningDepId = 1;
1487
1489
1490 // First, count how many write and read accesses are in the alias set. Also
1491 // collect MemAccessInfos for later.
1493 for (const Value *ConstPtr : ASPointers) {
1494 Value *Ptr = const_cast<Value *>(ConstPtr);
1495 bool IsWrite = Accesses.contains(MemAccessInfo(Ptr, true));
1496 if (IsWrite)
1497 ++NumWritePtrChecks;
1498 else
1499 ++NumReadPtrChecks;
1500 AccessInfos.emplace_back(Ptr, IsWrite);
1501 }
1502
1503 // We do not need runtime checks for this alias set, if there are no writes
1504 // or a single write and no reads.
1505 if (NumWritePtrChecks == 0 ||
1506 (NumWritePtrChecks == 1 && NumReadPtrChecks == 0)) {
1507 assert((ASPointers.size() <= 1 ||
1508 all_of(ASPointers,
1509 [this](const Value *Ptr) {
1510 MemAccessInfo AccessWrite(const_cast<Value *>(Ptr),
1511 true);
1512 return !DepCands.contains(AccessWrite);
1513 })) &&
1514 "Can only skip updating CanDoRT below, if all entries in AS "
1515 "are reads or there is at most 1 entry");
1516 continue;
1517 }
1518
1519 for (auto &Access : AccessInfos) {
1520 for (const auto &AccessTy : Accesses[Access]) {
1521 if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap,
1522 DepSetId, TheLoop, RunningDepId, ASId,
1523 false)) {
1524 LLVM_DEBUG(dbgs() << "LAA: Can't find bounds for ptr:"
1525 << *Access.getPointer() << '\n');
1526 Retries.emplace_back(Access, AccessTy);
1527 CanDoAliasSetRT = false;
1528 }
1529 }
1530 }
1531
1532 // Note that this function computes CanDoRT and MayNeedRTCheck
1533 // independently. For example CanDoRT=false, MayNeedRTCheck=false means that
1534 // we have a pointer for which we couldn't find the bounds but we don't
1535 // actually need to emit any checks so it does not matter.
1536 //
1537 // We need runtime checks for this alias set, if there are at least 2
1538 // dependence sets (in which case RunningDepId > 2) or if we need to re-try
1539 // any bound checks (because in that case the number of dependence sets is
1540 // incomplete).
1541 bool NeedsAliasSetRTCheck = RunningDepId > 2 || !Retries.empty();
1542
1543 // We need to perform run-time alias checks, but some pointers had bounds
1544 // that couldn't be checked.
1545 if (NeedsAliasSetRTCheck && !CanDoAliasSetRT) {
1546 // Reset the CanDoSetRt flag and retry all accesses that have failed.
1547 // We know that we need these checks, so we can now be more aggressive
1548 // and add further checks if required (overflow checks).
1549 CanDoAliasSetRT = true;
1550 for (const auto &[Access, AccessTy] : Retries) {
1551 if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap,
1552 DepSetId, TheLoop, RunningDepId, ASId,
1553 /*Assume=*/true)) {
1554 CanDoAliasSetRT = false;
1555 UncomputablePtr = Access.getPointer();
1556 if (!AllowPartial)
1557 break;
1558 }
1559 }
1560 }
1561
1562 CanDoRT &= CanDoAliasSetRT;
1563 MayNeedRTCheck |= NeedsAliasSetRTCheck;
1564 ++ASId;
1565 }
1566
1567 // If the pointers that we would use for the bounds comparison have different
1568 // address spaces, assume the values aren't directly comparable, so we can't
1569 // use them for the runtime check. We also have to assume they could
1570 // overlap. In the future there should be metadata for whether address spaces
1571 // are disjoint.
1572 unsigned NumPointers = RtCheck.Pointers.size();
1573 for (unsigned i = 0; i < NumPointers; ++i) {
1574 for (unsigned j = i + 1; j < NumPointers; ++j) {
1575 // Only need to check pointers between two different dependency sets.
1576 if (RtCheck.Pointers[i].DependencySetId ==
1577 RtCheck.Pointers[j].DependencySetId)
1578 continue;
1579 // Only need to check pointers in the same alias set.
1580 if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
1581 continue;
1582
1583 Value *PtrI = RtCheck.Pointers[i].PointerValue;
1584 Value *PtrJ = RtCheck.Pointers[j].PointerValue;
1585
1586 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
1587 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
1588 if (ASi != ASj) {
1589 LLVM_DEBUG(
1590 dbgs() << "LAA: Runtime check would require comparison between"
1591 " different address spaces\n");
1592 return false;
1593 }
1594 }
1595 }
1596
1597 if (MayNeedRTCheck && (CanDoRT || AllowPartial))
1598 RtCheck.generateChecks(DepCands);
1599
1600 LLVM_DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks()
1601 << " pointer comparisons.\n");
1602
1603 // If we can do run-time checks, but there are no checks, no runtime checks
1604 // are needed. This can happen when all pointers point to the same underlying
1605 // object for example.
1606 RtCheck.Need = CanDoRT ? RtCheck.getNumberOfChecks() != 0 : MayNeedRTCheck;
1607
1608 bool CanDoRTIfNeeded = !RtCheck.Need || CanDoRT;
1609 assert(CanDoRTIfNeeded == (CanDoRT || !MayNeedRTCheck) &&
1610 "CanDoRTIfNeeded depends on RtCheck.Need");
1611 if (!CanDoRTIfNeeded && !AllowPartial)
1612 RtCheck.reset();
1613 return CanDoRTIfNeeded;
1614}
1615
1616void AccessAnalysis::buildDependenceSets() {
1617 // We process the set twice: first we process read-write pointers, last we
1618 // process read-only pointers. This allows us to skip dependence tests for
1619 // read-only pointers.
1620
1621 LLVM_DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
1622 LLVM_DEBUG(dbgs() << " AST: "; AST.dump());
1623 LLVM_DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n");
1624 LLVM_DEBUG({
1625 for (const auto &[A, _] : Accesses)
1626 dbgs() << "\t" << *A.getPointer() << " ("
1627 << (A.getInt()
1628 ? "write"
1629 : (ReadOnlyPtr.contains(A.getPointer()) ? "read-only"
1630 : "read"))
1631 << ")\n";
1632 });
1633
1634 // The AliasSetTracker has nicely partitioned our pointers by metadata
1635 // compatibility and potential for underlying-object overlap. As a result, we
1636 // only need to check for potential pointer dependencies within each alias
1637 // set.
1638 for (const auto &AS : AST) {
1639 bool AliasSetHasWrite = false;
1640
1641 // Map of (pointer to underlying objects, accessed address space) to last
1642 // access encountered.
1643 using UnderlyingObjToAccessMap =
1645 UnderlyingObjToAccessMap ObjToLastAccess;
1646
1647 // Set of access to check after all writes have been processed.
1648 PtrAccessMap DeferredAccesses;
1649
1650 // Iterate over each alias set twice, once to process read/write pointers,
1651 // and then to process read-only pointers.
1652
1653 auto ProcessAccesses = [&](bool UseDeferred) {
1654 PtrAccessMap &S = UseDeferred ? DeferredAccesses : Accesses;
1655
1656 // Note that both the alias-set tracker and the alias sets themselves used
1657 // ordered collections internally and so the iteration order here is
1658 // deterministic.
1659 for (const Value *ConstPtr : AS.getPointers()) {
1660 Value *Ptr = const_cast<Value *>(ConstPtr);
1661
1662 // For a single memory access in AliasSetTracker, Accesses may contain
1663 // both read and write, and they both need to be handled for CheckDeps.
1664 for (auto [AccessPtr, IsWrite] : S.keys()) {
1665 if (AccessPtr != Ptr)
1666 continue;
1667
1668 // If we're using the deferred access set, then it contains only
1669 // reads.
1670 bool IsReadOnlyPtr = ReadOnlyPtr.contains(Ptr) && !IsWrite;
1671 if (UseDeferred && !IsReadOnlyPtr)
1672 continue;
1673 // Otherwise, the pointer must be in the PtrAccessSet, either as a
1674 // read or a write.
1675 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
1676 S.contains(MemAccessInfo(Ptr, false))) &&
1677 "Alias-set pointer not in the access set?");
1678
1679 MemAccessInfo Access(Ptr, IsWrite);
1680 DepCands.insert(Access);
1681
1682 // Memorize read-only pointers for later processing and skip them in
1683 // the first round (they need to be checked after we have seen all
1684 // write pointers). Note: we also mark pointer that are not
1685 // consecutive as "read-only" pointers (so that we check
1686 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
1687 if (!UseDeferred && IsReadOnlyPtr) {
1688 // We only use the pointer keys, the types vector values don't
1689 // matter.
1690 DeferredAccesses.insert({Access, {}});
1691 continue;
1692 }
1693
1694 // If this is a write - check other reads and writes for conflicts. If
1695 // this is a read only check other writes for conflicts (but only if
1696 // there is no other write to the ptr - this is an optimization to
1697 // catch "a[i] = a[i] + " without having to do a dependence check).
1698 if ((IsWrite || IsReadOnlyPtr) && AliasSetHasWrite) {
1699 CheckDeps.push_back(Access);
1700 IsRTCheckAnalysisNeeded = true;
1701 }
1702
1703 if (IsWrite)
1704 AliasSetHasWrite = true;
1705
1706 // Create sets of pointers connected by a shared alias set and
1707 // underlying object.
1708 SmallVector<const Value *, 16> &UOs = UnderlyingObjects[Ptr];
1709 UOs = {};
1710 ::getUnderlyingObjects(Ptr, UOs, LI);
1712 << "Underlying objects for pointer " << *Ptr << "\n");
1713 for (const Value *UnderlyingObj : UOs) {
1714 // nullptr never alias, don't join sets for pointer that have "null"
1715 // in their UnderlyingObjects list.
1716 if (isa<ConstantPointerNull>(UnderlyingObj) &&
1718 TheLoop->getHeader()->getParent(),
1719 UnderlyingObj->getType()->getPointerAddressSpace()))
1720 continue;
1721
1722 auto [It, Inserted] = ObjToLastAccess.try_emplace(
1723 {UnderlyingObj,
1724 cast<PointerType>(Ptr->getType())->getAddressSpace()},
1725 Access);
1726 if (!Inserted) {
1727 DepCands.unionSets(Access, It->second);
1728 It->second = Access;
1729 }
1730
1731 LLVM_DEBUG(dbgs() << " " << *UnderlyingObj << "\n");
1732 }
1733 }
1734 }
1735 };
1736
1737 ProcessAccesses(false);
1738 ProcessAccesses(true);
1739 }
1740}
1741
1742/// Check whether the access through \p Ptr has a constant stride.
1743std::optional<int64_t>
1745 const Loop *Lp, const DominatorTree &DT,
1746 const SymbolicStrideMap &StridesMap, bool ShouldCheckWrap,
1748 const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr);
1749 if (PSE.getSE()->isLoopInvariant(PtrScev, Lp))
1750 return 0;
1751
1752 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1753
1754 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
1755 if (Predicates && !AR) {
1756 AR = PSE.getSE()->convertSCEVToAddRecWithPredicates(PtrScev, Lp,
1757 *Predicates);
1758 }
1759
1760 if (!AR) {
1761 LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer " << *Ptr
1762 << " SCEV: " << *PtrScev << "\n");
1763 return std::nullopt;
1764 }
1765
1766 std::optional<int64_t> Stride =
1767 getStrideFromAddRec(AR, Lp, AccessTy, Ptr, PSE);
1768 if (!ShouldCheckWrap || !Stride)
1769 return Stride;
1770
1771 if (isNoWrap(PSE, AR, Ptr, AccessTy, Lp, DT, Stride, Predicates))
1772 return Stride;
1773
1774 LLVM_DEBUG(
1775 dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
1776 << *Ptr << " SCEV: " << *AR << "\n");
1777 return std::nullopt;
1778}
1779
1780/// Check whether the access through \p Ptr has a constant stride.
1782 Type *AccessTy, Value *Ptr,
1783 const Loop *Lp,
1784 const DominatorTree &DT,
1785 const SymbolicStrideMap &StridesMap,
1786 bool Assume, bool ShouldCheckWrap) {
1788 std::optional<int64_t> Stride =
1789 getPtrStride(PSE, AccessTy, Ptr, Lp, DT, StridesMap, ShouldCheckWrap,
1790 Assume ? &Predicates : nullptr);
1791 PSE.addPredicates(Predicates);
1792 return Stride;
1793}
1794
1795std::optional<int64_t> llvm::getPointersDiff(Type *ElemTyA, Value *PtrA,
1796 Type *ElemTyB, Value *PtrB,
1797 const DataLayout &DL,
1798 ScalarEvolution &SE,
1799 bool StrictCheck, bool CheckType) {
1800 assert(PtrA && PtrB && "Expected non-nullptr pointers.");
1801
1802 // Make sure that A and B are different pointers.
1803 if (PtrA == PtrB)
1804 return 0;
1805
1806 // Make sure that the element types are the same if required.
1807 if (CheckType && ElemTyA != ElemTyB)
1808 return std::nullopt;
1809
1810 unsigned ASA = PtrA->getType()->getPointerAddressSpace();
1811 unsigned ASB = PtrB->getType()->getPointerAddressSpace();
1812
1813 // Check that the address spaces match.
1814 if (ASA != ASB)
1815 return std::nullopt;
1816 unsigned IdxWidth = DL.getIndexSizeInBits(ASA);
1817
1818 APInt OffsetA(IdxWidth, 0), OffsetB(IdxWidth, 0);
1819 const Value *PtrA1 = PtrA->stripAndAccumulateConstantOffsets(
1820 DL, OffsetA, /*AllowNonInbounds=*/true);
1821 const Value *PtrB1 = PtrB->stripAndAccumulateConstantOffsets(
1822 DL, OffsetB, /*AllowNonInbounds=*/true);
1823
1824 std::optional<int64_t> Val;
1825 if (PtrA1 == PtrB1) {
1826 // Retrieve the address space again as pointer stripping now tracks through
1827 // `addrspacecast`.
1828 ASA = cast<PointerType>(PtrA1->getType())->getAddressSpace();
1829 ASB = cast<PointerType>(PtrB1->getType())->getAddressSpace();
1830 // Check that the address spaces match and that the pointers are valid.
1831 if (ASA != ASB)
1832 return std::nullopt;
1833
1834 IdxWidth = DL.getIndexSizeInBits(ASA);
1835 OffsetA = OffsetA.sextOrTrunc(IdxWidth);
1836 OffsetB = OffsetB.sextOrTrunc(IdxWidth);
1837
1838 OffsetB -= OffsetA;
1839 Val = OffsetB.trySExtValue();
1840 } else {
1841 // Otherwise compute the distance with SCEV between the base pointers.
1842 const SCEV *PtrSCEVA = SE.getSCEV(PtrA);
1843 const SCEV *PtrSCEVB = SE.getSCEV(PtrB);
1844 std::optional<APInt> Diff =
1845 SE.computeConstantDifference(PtrSCEVB, PtrSCEVA);
1846 if (!Diff)
1847 return std::nullopt;
1848 Val = Diff->trySExtValue();
1849 }
1850
1851 if (!Val)
1852 return std::nullopt;
1853
1854 int64_t Size = DL.getTypeStoreSize(ElemTyA);
1855 int64_t Dist = *Val / Size;
1856
1857 // Ensure that the calculated distance matches the type-based one after all
1858 // the bitcasts removal in the provided pointers.
1859 if (!StrictCheck || Dist * Size == Val)
1860 return Dist;
1861 return std::nullopt;
1862}
1863
1865 const DataLayout &DL, ScalarEvolution &SE,
1866 SmallVectorImpl<unsigned> &SortedIndices) {
1868 VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&
1869 "Expected list of pointer operands.");
1870 // Walk over the pointers, and map each of them to an offset relative to
1871 // first pointer in the array.
1872 Value *Ptr0 = VL[0];
1873
1874 using DistOrdPair = std::pair<int64_t, unsigned>;
1875 auto Compare = llvm::less_first();
1876 std::set<DistOrdPair, decltype(Compare)> Offsets(Compare);
1877 Offsets.emplace(0, 0);
1878 bool IsConsecutive = true;
1879 for (auto [Idx, Ptr] : drop_begin(enumerate(VL))) {
1880 std::optional<int64_t> Diff =
1881 getPointersDiff(ElemTy, Ptr0, ElemTy, Ptr, DL, SE,
1882 /*StrictCheck=*/true);
1883 if (!Diff)
1884 return false;
1885
1886 // Check if the pointer with the same offset is found.
1887 int64_t Offset = *Diff;
1888 auto [It, IsInserted] = Offsets.emplace(Offset, Idx);
1889 if (!IsInserted)
1890 return false;
1891 // Consecutive order if the inserted element is the last one.
1892 IsConsecutive &= std::next(It) == Offsets.end();
1893 }
1894 SortedIndices.clear();
1895 if (!IsConsecutive) {
1896 // Fill SortedIndices array only if it is non-consecutive.
1897 SortedIndices.resize(VL.size());
1898 for (auto [Idx, Off] : enumerate(Offsets))
1899 SortedIndices[Idx] = Off.second;
1900 }
1901 return true;
1902}
1903
1904/// Returns true if the memory operations \p A and \p B are consecutive.
1906 ScalarEvolution &SE, bool CheckType) {
1909 if (!PtrA || !PtrB)
1910 return false;
1911 Type *ElemTyA = getLoadStoreType(A);
1912 Type *ElemTyB = getLoadStoreType(B);
1913 std::optional<int64_t> Diff =
1914 getPointersDiff(ElemTyA, PtrA, ElemTyB, PtrB, DL, SE,
1915 /*StrictCheck=*/true, CheckType);
1916 return Diff == 1;
1917}
1918
1920 visitPointers(SI->getPointerOperand(), *InnermostLoop,
1921 [this, SI](Value *Ptr) {
1922 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
1923 InstMap.push_back(SI);
1924 ++AccessIdx;
1925 });
1926}
1927
1929 visitPointers(LI->getPointerOperand(), *InnermostLoop,
1930 [this, LI](Value *Ptr) {
1931 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
1932 InstMap.push_back(LI);
1933 ++AccessIdx;
1934 });
1935}
1936
1956
1958 switch (Type) {
1959 case NoDep:
1960 case Forward:
1962 case Unknown:
1963 case IndirectUnsafe:
1964 case InvariantUnsafe:
1965 return false;
1966
1968 case Backward:
1970 return true;
1971 }
1972 llvm_unreachable("unexpected DepType!");
1973}
1974
1979
1981 switch (Type) {
1982 case Forward:
1984 return true;
1985
1986 case NoDep:
1987 case Unknown:
1989 case Backward:
1991 case IndirectUnsafe:
1992 case InvariantUnsafe:
1993 return false;
1994 }
1995 llvm_unreachable("unexpected DepType!");
1996}
1997
1998bool MemoryDepChecker::couldPreventStoreLoadForward(uint64_t Distance,
1999 uint64_t TypeByteSize,
2000 unsigned CommonStride) {
2001 // If loads occur at a distance that is not a multiple of a feasible vector
2002 // factor store-load forwarding does not take place.
2003 // Positive dependences might cause troubles because vectorizing them might
2004 // prevent store-load forwarding making vectorized code run a lot slower.
2005 // a[i] = a[i-3] ^ a[i-8];
2006 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
2007 // hence on your typical architecture store-load forwarding does not take
2008 // place. Vectorizing in such cases does not make sense.
2009 // Store-load forwarding distance.
2010
2011 // Maximum vector factor.
2012 uint64_t MaxVFWithoutSLForwardIssuesPowerOf2 =
2013 std::min(VectorizerParams::MaxVectorWidth * TypeByteSize,
2014 MaxStoreLoadForwardSafeDistanceInBits);
2015
2016 // Compute the smallest VF at which the store and load would be misaligned
2017 // and recent enough to still be in the store buffer.
2018 for (uint64_t VF = 2 * TypeByteSize;
2019 VF <= MaxVFWithoutSLForwardIssuesPowerOf2; VF *= 2) {
2020 if (isStoreLoadForwardingConflict(Distance, VF, TypeByteSize, VF)) {
2021 MaxVFWithoutSLForwardIssuesPowerOf2 = (VF >> 1);
2022 break;
2023 }
2024 }
2025
2026 if (MaxVFWithoutSLForwardIssuesPowerOf2 < 2 * TypeByteSize) {
2027 LLVM_DEBUG(
2028 dbgs() << "LAA: Distance " << Distance
2029 << " that could cause a store-load forwarding conflict\n");
2030 return true;
2031 }
2032
2033 if (CommonStride &&
2034 MaxVFWithoutSLForwardIssuesPowerOf2 <
2035 MaxStoreLoadForwardSafeDistanceInBits &&
2036 MaxVFWithoutSLForwardIssuesPowerOf2 !=
2037 VectorizerParams::MaxVectorWidth * TypeByteSize) {
2038 uint64_t MaxVF =
2039 bit_floor(MaxVFWithoutSLForwardIssuesPowerOf2 / CommonStride);
2040 uint64_t MaxVFInBits = MaxVF * TypeByteSize * 8;
2041 MaxStoreLoadForwardSafeDistanceInBits =
2042 std::min(MaxStoreLoadForwardSafeDistanceInBits, MaxVFInBits);
2043
2044 if (MaxVF < 2) {
2045 LLVM_DEBUG(
2046 dbgs() << "LAA: strided access with Distance " << Distance
2047 << " that could cause a store-load forwarding conflict\n");
2048 return true;
2049 }
2050 }
2051 return false;
2052}
2053
2054void MemoryDepChecker::mergeInStatus(VectorizationSafetyStatus S) {
2055 if (Status < S)
2056 Status = S;
2057}
2058
2059/// Given a dependence-distance \p Dist between two memory accesses, that have
2060/// strides in the same direction whose absolute value of the maximum stride is
2061/// given in \p MaxStride, in a loop whose maximum backedge taken count is \p
2062/// MaxBTC, check if it is possible to prove statically that the dependence
2063/// distance is larger than the range that the accesses will travel through the
2064/// execution of the loop. If so, return true; false otherwise. This is useful
2065/// for example in loops such as the following (PR31098):
2066///
2067/// for (i = 0; i < D; ++i) {
2068/// = out[i];
2069/// out[i+D] =
2070/// }
2072 const SCEV &MaxBTC, const SCEV &Dist,
2073 uint64_t MaxStride) {
2074
2075 // If we can prove that
2076 // (**) |Dist| > MaxBTC * Step
2077 // where Step is the absolute stride of the memory accesses in bytes,
2078 // then there is no dependence.
2079 //
2080 // Rationale:
2081 // We basically want to check if the absolute distance (|Dist/Step|)
2082 // is >= the loop iteration count (or > MaxBTC).
2083 // This is equivalent to the Strong SIV Test (Practical Dependence Testing,
2084 // Section 4.2.1); Note, that for vectorization it is sufficient to prove
2085 // that the dependence distance is >= VF; This is checked elsewhere.
2086 // But in some cases we can prune dependence distances early, and
2087 // even before selecting the VF, and without a runtime test, by comparing
2088 // the distance against the loop iteration count. Since the vectorized code
2089 // will be executed only if LoopCount >= VF, proving distance >= LoopCount
2090 // also guarantees that distance >= VF.
2091 //
2092 const SCEV *Step = SE.getConstant(MaxBTC.getType(), MaxStride);
2093 const SCEV *Product = SE.getMulExpr(&MaxBTC, Step);
2094
2095 const SCEV *CastedDist = &Dist;
2096 const SCEV *CastedProduct = Product;
2097 uint64_t DistTypeSizeBits = DL.getTypeSizeInBits(Dist.getType());
2098 uint64_t ProductTypeSizeBits = DL.getTypeSizeInBits(Product->getType());
2099
2100 // The dependence distance can be positive/negative, so we sign extend Dist;
2101 // The multiplication of the absolute stride in bytes and the
2102 // backedgeTakenCount is non-negative, so we zero extend Product.
2103 if (DistTypeSizeBits > ProductTypeSizeBits)
2104 CastedProduct = SE.getZeroExtendExpr(Product, Dist.getType());
2105 else
2106 CastedDist = SE.getNoopOrSignExtend(&Dist, Product->getType());
2107
2108 // Is Dist - (MaxBTC * Step) > 0 ?
2109 // (If so, then we have proven (**) because |Dist| >= Dist)
2110 const SCEV *Minus = SE.getMinusSCEV(CastedDist, CastedProduct);
2111 if (SE.isKnownPositive(Minus))
2112 return true;
2113
2114 // Second try: Is -Dist - (MaxBTC * Step) > 0 ?
2115 // (If so, then we have proven (**) because |Dist| >= -1*Dist)
2116 const SCEV *NegDist = SE.getNegativeSCEV(CastedDist);
2117 Minus = SE.getMinusSCEV(NegDist, CastedProduct);
2118 return SE.isKnownPositive(Minus);
2119}
2120
2121/// Check the dependence for two accesses with the same stride \p Stride.
2122/// \p Distance is the positive distance in bytes, and \p TypeByteSize is type
2123/// size in bytes.
2124///
2125/// \returns true if they are independent.
2127 uint64_t TypeByteSize) {
2128 assert(Stride > 1 && "The stride must be greater than 1");
2129 assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
2130 assert(Distance > 0 && "The distance must be non-zero");
2131
2132 // Skip if the distance is not multiple of type byte size.
2133 if (Distance % TypeByteSize)
2134 return false;
2135
2136 // No dependence if the distance is not multiple of the stride.
2137 // E.g.
2138 // for (i = 0; i < 1024 ; i += 4)
2139 // A[i+2] = A[i] + 1;
2140 //
2141 // Two accesses in memory (distance is 2, stride is 4):
2142 // | A[0] | | | | A[4] | | | |
2143 // | | | A[2] | | | | A[6] | |
2144 //
2145 // E.g.
2146 // for (i = 0; i < 1024 ; i += 3)
2147 // A[i+4] = A[i] + 1;
2148 //
2149 // Two accesses in memory (distance is 4, stride is 3):
2150 // | A[0] | | | A[3] | | | A[6] | | |
2151 // | | | | | A[4] | | | A[7] | |
2152 return Distance % Stride;
2153}
2154
2155bool MemoryDepChecker::areAccessesCompletelyBeforeOrAfter(const SCEV *Src,
2156 Type *SrcTy,
2157 const SCEV *Sink,
2158 Type *SinkTy) {
2159 const SCEV *BTC = PSE.getBackedgeTakenCount();
2160 const SCEV *SymbolicMaxBTC = PSE.getSymbolicMaxBackedgeTakenCount();
2161 ScalarEvolution &SE = *PSE.getSE();
2162 const auto &[SrcStart_, SrcEnd_] =
2163 getStartAndEndForAccess(InnermostLoop, Src, SrcTy, BTC, SymbolicMaxBTC,
2164 &SE, &PointerBounds, DT, AC, LoopGuards);
2165 if (isa<SCEVCouldNotCompute>(SrcStart_) || isa<SCEVCouldNotCompute>(SrcEnd_))
2166 return false;
2167
2168 const auto &[SinkStart_, SinkEnd_] =
2169 getStartAndEndForAccess(InnermostLoop, Sink, SinkTy, BTC, SymbolicMaxBTC,
2170 &SE, &PointerBounds, DT, AC, LoopGuards);
2171 if (isa<SCEVCouldNotCompute>(SinkStart_) ||
2172 isa<SCEVCouldNotCompute>(SinkEnd_))
2173 return false;
2174
2175 if (!LoopGuards)
2176 LoopGuards.emplace(ScalarEvolution::LoopGuards::collect(InnermostLoop, SE));
2177
2178 auto SrcEnd = SE.applyLoopGuards(SrcEnd_, *LoopGuards);
2179 auto SinkStart = SE.applyLoopGuards(SinkStart_, *LoopGuards);
2180 if (SE.isKnownPredicate(CmpInst::ICMP_ULE, SrcEnd, SinkStart))
2181 return true;
2182
2183 auto SinkEnd = SE.applyLoopGuards(SinkEnd_, *LoopGuards);
2184 auto SrcStart = SE.applyLoopGuards(SrcStart_, *LoopGuards);
2185 return SE.isKnownPredicate(CmpInst::ICMP_ULE, SinkEnd, SrcStart);
2186}
2187
2189 MemoryDepChecker::DepDistanceStrideAndSizeInfo>
2190MemoryDepChecker::getDependenceDistanceStrideAndSize(
2191 const AccessAnalysis::MemAccessInfo &A, Instruction *AInst,
2192 const AccessAnalysis::MemAccessInfo &B, Instruction *BInst) {
2193 const auto &DL = InnermostLoop->getHeader()->getDataLayout();
2194 auto &SE = *PSE.getSE();
2195 const auto &[APtr, AIsWrite] = A;
2196 const auto &[BPtr, BIsWrite] = B;
2197
2198 // Two reads are independent.
2199 if (!AIsWrite && !BIsWrite)
2201
2202 Type *ATy = getLoadStoreType(AInst);
2203 Type *BTy = getLoadStoreType(BInst);
2204
2205 // We cannot check pointers in different address spaces.
2206 if (APtr->getType()->getPointerAddressSpace() !=
2207 BPtr->getType()->getPointerAddressSpace())
2209
2211 std::optional<int64_t> StrideAPtr =
2212 getPtrStride(PSE, ATy, APtr, InnermostLoop, *DT, SymbolicStrides,
2213 /*ShouldCheckWrap=*/true, &Predicates);
2214 std::optional<int64_t> StrideBPtr =
2215 getPtrStride(PSE, BTy, BPtr, InnermostLoop, *DT, SymbolicStrides,
2216 /*ShouldCheckWrap=*/true, &Predicates);
2217 PSE.addPredicates(Predicates);
2218
2219 const SCEV *Src = PSE.getSCEV(APtr);
2220 const SCEV *Sink = PSE.getSCEV(BPtr);
2221
2222 // If the induction step is negative we have to invert source and sink of the
2223 // dependence when measuring the distance between them. We should not swap
2224 // AIsWrite with BIsWrite, as their uses expect them in program order.
2225 if (StrideAPtr && *StrideAPtr < 0) {
2226 std::swap(Src, Sink);
2227 std::swap(AInst, BInst);
2228 std::swap(ATy, BTy);
2229 std::swap(StrideAPtr, StrideBPtr);
2230 }
2231
2232 const SCEV *Dist = SE.getMinusSCEV(Sink, Src);
2233
2234 LLVM_DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
2235 << "\n");
2236 LLVM_DEBUG(dbgs() << "LAA: Distance for " << *AInst << " to " << *BInst
2237 << ": " << *Dist << "\n");
2238
2239 // Need accesses with constant strides and the same direction for further
2240 // dependence analysis. We don't want to vectorize "A[B[i]] += ..." and
2241 // similar code or pointer arithmetic that could wrap in the address space.
2242
2243 // If either Src or Sink are not strided (i.e. not a non-wrapping AddRec) and
2244 // not loop-invariant (stride will be 0 in that case), we cannot analyze the
2245 // dependence further and also cannot generate runtime checks.
2246 if (!StrideAPtr || !StrideBPtr) {
2247 LLVM_DEBUG(dbgs() << "Pointer access with non-constant stride\n");
2249 }
2250
2251 int64_t StrideAPtrInt = *StrideAPtr;
2252 int64_t StrideBPtrInt = *StrideBPtr;
2253 LLVM_DEBUG(dbgs() << "LAA: Src induction step: " << StrideAPtrInt
2254 << " Sink induction step: " << StrideBPtrInt << "\n");
2255 // At least Src or Sink are loop invariant and the other is strided or
2256 // invariant.
2257 if (!StrideAPtrInt || !StrideBPtrInt) {
2258 // If both are loop-invariant and access the same location, we cannot
2259 // vectorize.
2260 if (!StrideAPtrInt && !StrideBPtrInt && Dist->isZero())
2262 // Otherwise, we can generate a runtime check to disambiguate the accesses.
2264 }
2265
2266 // Both Src and Sink have a constant stride, check if they are in the same
2267 // direction.
2268 if ((StrideAPtrInt > 0) != (StrideBPtrInt > 0)) {
2269 LLVM_DEBUG(
2270 dbgs() << "Pointer access with strides in different directions\n");
2272 }
2273
2274 TypeSize AStoreSz = DL.getTypeStoreSize(ATy);
2275 TypeSize BStoreSz = DL.getTypeStoreSize(BTy);
2276
2277 // If store sizes are not the same, set TypeByteSize to zero, so we can check
2278 // it in the caller isDependent.
2279 uint64_t ASz = DL.getTypeAllocSize(ATy);
2280 uint64_t BSz = DL.getTypeAllocSize(BTy);
2281 uint64_t TypeByteSize = (AStoreSz == BStoreSz) ? BSz : 0;
2282
2283 uint64_t StrideAScaled = AbsoluteValue(StrideAPtrInt) * ASz;
2284 uint64_t StrideBScaled = AbsoluteValue(StrideBPtrInt) * BSz;
2285
2286 uint64_t MaxStride = std::max(StrideAScaled, StrideBScaled);
2287
2288 std::optional<uint64_t> CommonStride;
2289 if (StrideAScaled == StrideBScaled)
2290 CommonStride = StrideAScaled;
2291
2292 // TODO: Historically, we didn't retry with runtime checks when (unscaled)
2293 // strides were different but there is no inherent reason to.
2294 if (!isa<SCEVConstant>(Dist))
2295 ShouldRetryWithRuntimeChecks |= StrideAPtrInt == StrideBPtrInt;
2296
2297 // If distance is a SCEVCouldNotCompute, return Unknown immediately.
2298 if (isa<SCEVCouldNotCompute>(Dist)) {
2299 LLVM_DEBUG(dbgs() << "LAA: Uncomputable distance.\n");
2300 return Dependence::Unknown;
2301 }
2302
2303 return DepDistanceStrideAndSizeInfo(Dist, MaxStride, CommonStride,
2304 TypeByteSize, AIsWrite, BIsWrite);
2305}
2306
2308MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
2309 const MemAccessInfo &B, unsigned BIdx) {
2310 assert(AIdx < BIdx && "Must pass arguments in program order");
2311
2312 // Check if we can prove that Sink only accesses memory after Src's end or
2313 // vice versa. The helper is used to perform the checks only on the exit paths
2314 // where it helps to improve the analysis result.
2315 auto CheckCompletelyBeforeOrAfter = [&]() {
2316 auto *APtr = A.getPointer();
2317 auto *BPtr = B.getPointer();
2318 Type *ATy = getLoadStoreType(InstMap[AIdx]);
2319 Type *BTy = getLoadStoreType(InstMap[BIdx]);
2320 const SCEV *Src = PSE.getSCEV(APtr);
2321 const SCEV *Sink = PSE.getSCEV(BPtr);
2322 return areAccessesCompletelyBeforeOrAfter(Src, ATy, Sink, BTy);
2323 };
2324
2325 // Get the dependence distance, stride, type size and what access writes for
2326 // the dependence between A and B.
2327 auto Res =
2328 getDependenceDistanceStrideAndSize(A, InstMap[AIdx], B, InstMap[BIdx]);
2329 if (std::holds_alternative<Dependence::DepType>(Res)) {
2330 if (std::get<Dependence::DepType>(Res) == Dependence::Unknown &&
2331 CheckCompletelyBeforeOrAfter())
2332 return Dependence::NoDep;
2333 return std::get<Dependence::DepType>(Res);
2334 }
2335
2336 auto &[Dist, MaxStride, CommonStride, TypeByteSize, AIsWrite, BIsWrite] =
2337 std::get<DepDistanceStrideAndSizeInfo>(Res);
2338 bool HasSameSize = TypeByteSize > 0;
2339
2340 ScalarEvolution &SE = *PSE.getSE();
2341 auto &DL = InnermostLoop->getHeader()->getDataLayout();
2342
2343 // If the distance between the acecsses is larger than their maximum absolute
2344 // stride multiplied by the symbolic maximum backedge taken count (which is an
2345 // upper bound of the number of iterations), the accesses are independet, i.e.
2346 // they are far enough appart that accesses won't access the same location
2347 // across all loop ierations.
2348 if (HasSameSize &&
2350 DL, SE, *(PSE.getSymbolicMaxBackedgeTakenCount()), *Dist, MaxStride))
2351 return Dependence::NoDep;
2352
2353 const APInt *APDist = nullptr;
2354 uint64_t ConstDist = 0;
2355 if (match(Dist, m_scev_APInt(APDist))) {
2356 std::optional<uint64_t> Val = APDist->abs().tryZExtValue();
2357 if (!Val) {
2358 LLVM_DEBUG(dbgs() << "LAA: Constant distance does not fit in 64 bits.\n");
2359 return Dependence::Unknown;
2360 }
2361 ConstDist = *Val;
2362 }
2363
2364 // Attempt to prove strided accesses independent.
2365 if (APDist) {
2366 // If the distance between accesses and their strides are known constants,
2367 // check whether the accesses interlace each other.
2368 if (ConstDist > 0 && CommonStride && CommonStride > 1 && HasSameSize &&
2369 areStridedAccessesIndependent(ConstDist, *CommonStride, TypeByteSize)) {
2370 LLVM_DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
2371 return Dependence::NoDep;
2372 }
2373 } else {
2374 if (!LoopGuards)
2375 LoopGuards.emplace(
2376 ScalarEvolution::LoopGuards::collect(InnermostLoop, SE));
2377 Dist = SE.applyLoopGuards(Dist, *LoopGuards);
2378 }
2379
2380 // Negative distances are not plausible dependencies.
2381 if (SE.isKnownNonPositive(Dist)) {
2382 if (SE.isKnownNonNegative(Dist)) {
2383 if (HasSameSize) {
2384 // Write to the same location with the same size.
2385 return Dependence::Forward;
2386 }
2387 LLVM_DEBUG(dbgs() << "LAA: possibly zero dependence difference but "
2388 "different type sizes\n");
2389 return Dependence::Unknown;
2390 }
2391
2392 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
2393 // Check if the first access writes to a location that is read in a later
2394 // iteration, where the distance between them is not a multiple of a vector
2395 // factor and relatively small.
2396 //
2397 // NOTE: There is no need to update MaxSafeVectorWidthInBits after call to
2398 // couldPreventStoreLoadForward, even if it changed MinDepDistBytes, since a
2399 // forward dependency will allow vectorization using any width.
2400
2401 if (IsTrueDataDependence && EnableForwardingConflictDetection) {
2402 if (!ConstDist) {
2403 return CheckCompletelyBeforeOrAfter() ? Dependence::NoDep
2405 }
2406 if (!HasSameSize ||
2407 couldPreventStoreLoadForward(ConstDist, TypeByteSize)) {
2408 LLVM_DEBUG(
2409 dbgs() << "LAA: Forward but may prevent st->ld forwarding\n");
2411 }
2412 }
2413
2414 LLVM_DEBUG(dbgs() << "LAA: Dependence is negative\n");
2415 return Dependence::Forward;
2416 }
2417
2418 std::optional<int64_t> MinDistanceOpt =
2420 if (!MinDistanceOpt) {
2421 LLVM_DEBUG(dbgs() << "LAA: Minimum distance does not fit in 64 bits.\n");
2422 return Dependence::Unknown;
2423 }
2424 int64_t MinDistance = *MinDistanceOpt;
2425 // Below we only handle strictly positive distances.
2426 if (MinDistance <= 0) {
2427 return CheckCompletelyBeforeOrAfter() ? Dependence::NoDep
2429 }
2430
2431 if (!HasSameSize) {
2432 if (CheckCompletelyBeforeOrAfter())
2433 return Dependence::NoDep;
2434 LLVM_DEBUG(dbgs() << "LAA: ReadWrite-Write positive dependency with "
2435 "different type sizes\n");
2436 return Dependence::Unknown;
2437 }
2438 // Bail out early if passed-in parameters make vectorization not feasible.
2439 unsigned MinForcedFactor =
2440 std::max(1U, VectorizerParams::VectorizationFactor.getKnownMinValue());
2441 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
2443 // The minimum number of iterations for a vectorized/unrolled version.
2444 unsigned MinNumIter = std::max(MinForcedFactor * ForcedUnroll, 2U);
2445
2446 // It's not vectorizable if the distance is smaller than the minimum distance
2447 // needed for a vectroized/unrolled version. Vectorizing one iteration in
2448 // front needs MaxStride. Vectorizing the last iteration needs TypeByteSize.
2449 // (No need to plus the last gap distance).
2450 //
2451 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
2452 // foo(int *A) {
2453 // int *B = (int *)((char *)A + 14);
2454 // for (i = 0 ; i < 1024 ; i += 2)
2455 // B[i] = A[i] + 1;
2456 // }
2457 //
2458 // Two accesses in memory (stride is 4 * 2):
2459 // | A[0] | | A[2] | | A[4] | | A[6] | |
2460 // | B[0] | | B[2] | | B[4] |
2461 //
2462 // MinDistance needs for vectorizing iterations except the last iteration:
2463 // 4 * 2 * (MinNumIter - 1). MinDistance needs for the last iteration: 4.
2464 // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
2465 //
2466 // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
2467 // 12, which is less than distance.
2468 //
2469 // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
2470 // the minimum distance needed is 28, which is greater than distance. It is
2471 // not safe to do vectorization.
2472 //
2473 // We use MaxStride (maximum of src and sink strides) to get a conservative
2474 // lower bound on the MinDistanceNeeded in case of different strides.
2475
2476 // We know that Dist is positive, but it may not be constant. Use the signed
2477 // minimum for computations below, as this ensures we compute the closest
2478 // possible dependence distance.
2479 uint64_t MinDistanceNeeded = MaxStride * (MinNumIter - 1) + TypeByteSize;
2480 if (MinDistanceNeeded > static_cast<uint64_t>(MinDistance)) {
2481 if (!ConstDist) {
2482 // For non-constant distances, we checked the lower bound of the
2483 // dependence distance and the distance may be larger at runtime (and safe
2484 // for vectorization). Classify it as Unknown, so we re-try with runtime
2485 // checks, unless we can prove both accesses cannot overlap.
2486 return CheckCompletelyBeforeOrAfter() ? Dependence::NoDep
2488 }
2489 LLVM_DEBUG(dbgs() << "LAA: Failure because of positive minimum distance "
2490 << MinDistance << '\n');
2491 return Dependence::Backward;
2492 }
2493
2494 // Unsafe if the minimum distance needed is greater than smallest dependence
2495 // distance distance.
2496 if (MinDistanceNeeded > MinDepDistBytes) {
2497 LLVM_DEBUG(dbgs() << "LAA: Failure because it needs at least "
2498 << MinDistanceNeeded << " size in bytes\n");
2499 return Dependence::Backward;
2500 }
2501
2502 MinDepDistBytes =
2503 std::min(static_cast<uint64_t>(MinDistance), MinDepDistBytes);
2504
2505 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
2506 if (IsTrueDataDependence && EnableForwardingConflictDetection && ConstDist &&
2507 couldPreventStoreLoadForward(MinDistance, TypeByteSize, *CommonStride))
2509
2510 uint64_t MaxVF = MinDepDistBytes / MaxStride;
2511 LLVM_DEBUG(dbgs() << "LAA: Positive min distance " << MinDistance
2512 << " with max VF = " << MaxVF << '\n');
2513
2514 uint64_t MaxVFInBits = MaxVF * TypeByteSize * 8;
2515 if (!ConstDist && MaxVFInBits < MaxTargetVectorWidthInBits) {
2516 // For non-constant distances, we checked the lower bound of the dependence
2517 // distance and the distance may be larger at runtime (and safe for
2518 // vectorization). Classify it as Unknown, so we re-try with runtime checks,
2519 // unless we can prove both accesses cannot overlap.
2520 return CheckCompletelyBeforeOrAfter() ? Dependence::NoDep
2522 }
2523
2524 if (CheckCompletelyBeforeOrAfter())
2525 return Dependence::NoDep;
2526
2527 MaxSafeVectorWidthInBits = std::min(MaxSafeVectorWidthInBits, MaxVFInBits);
2529}
2530
2532 ArrayRef<MemAccessInfo> CheckDeps) {
2533
2534 MinDepDistBytes = -1;
2536 for (MemAccessInfo CurAccess : CheckDeps) {
2537 if (Visited.contains(CurAccess))
2538 continue;
2539
2540 // Check accesses within this set.
2542 DepCands.findLeader(CurAccess);
2544 DepCands.member_end();
2545
2546 // Check every access pair.
2547 while (AI != AE) {
2548 Visited.insert(*AI);
2549 bool AIIsWrite = AI->getInt();
2550 // Reads from the same pointer don't create extra hazards, but multiple
2551 // stores do (WAW), so start from AI for writes and next(AI) for reads.
2553 (AIIsWrite ? AI : std::next(AI));
2554 while (OI != AE) {
2555 // Check every accessing instruction pair in program order.
2556 auto &Acc = Accesses[*AI];
2557 for (std::vector<unsigned>::iterator I1 = Acc.begin(), I1E = Acc.end();
2558 I1 != I1E; ++I1)
2559 // When checking for WAW (OI == AI) caused by multiple writes to the
2560 // same pointer, start I2 at the next access past I1 to avoid
2561 // self-comparison.
2562 for (std::vector<unsigned>::iterator
2563 I2 = (OI == AI ? std::next(I1) : Accesses[*OI].begin()),
2564 I2E = (OI == AI ? I1E : Accesses[*OI].end());
2565 I2 != I2E; ++I2) {
2566 auto A = std::make_pair(&*AI, *I1);
2567 auto B = std::make_pair(&*OI, *I2);
2568
2569 assert(*I1 != *I2);
2570 if (*I1 > *I2)
2571 std::swap(A, B);
2572
2574 isDependent(*A.first, A.second, *B.first, B.second);
2576
2577 // Gather dependences unless we accumulated MaxDependences
2578 // dependences. In that case return as soon as we find the first
2579 // unsafe dependence. This puts a limit on this quadratic
2580 // algorithm.
2581 if (RecordDependences) {
2582 if (Type != Dependence::NoDep)
2583 Dependences.emplace_back(A.second, B.second, Type);
2584
2585 if (Dependences.size() >= MaxDependences) {
2586 RecordDependences = false;
2587 Dependences.clear();
2589 << "Too many dependences, stopped recording\n");
2590 }
2591 }
2592 if (!RecordDependences && !isSafeForVectorization())
2593 return false;
2594 }
2595 ++OI;
2596 }
2597 ++AI;
2598 }
2599 }
2600
2601 LLVM_DEBUG(dbgs() << "Total Dependences: " << Dependences.size() << "\n");
2602 return isSafeForVectorization();
2603}
2604
2607 MemAccessInfo Access(Ptr, IsWrite);
2608 auto I = Accesses.find(Access);
2610 if (I != Accesses.end()) {
2611 transform(I->second, std::back_inserter(Insts),
2612 [&](unsigned Idx) { return this->InstMap[Idx]; });
2613 }
2614
2615 return Insts;
2616}
2617
2619 "NoDep",
2620 "Unknown",
2621 "IndirectUnsafe",
2622 "InvariantUnsafe",
2623 "Forward",
2624 "ForwardButPreventsForwarding",
2625 "Backward",
2626 "BackwardVectorizable",
2627 "BackwardVectorizableButPreventsForwarding"};
2628
2630 raw_ostream &OS, unsigned Depth,
2631 const SmallVectorImpl<Instruction *> &Instrs) const {
2632 OS.indent(Depth) << DepName[Type] << ":\n";
2633 OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
2634 OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
2635}
2636
2637bool LoopAccessInfo::canAnalyzeLoop() {
2638 // We need to have a loop header.
2639 LLVM_DEBUG(dbgs() << "\nLAA: Checking a loop in '"
2640 << TheLoop->getHeader()->getParent()->getName() << "' from "
2641 << TheLoop->getLocStr() << "\n");
2642
2643 // We can only analyze innermost loops.
2644 if (!TheLoop->isInnermost()) {
2645 LLVM_DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
2646 recordAnalysis("NotInnerMostLoop") << "loop is not the innermost loop";
2647 return false;
2648 }
2649
2650 // We must have a single backedge.
2651 if (TheLoop->getNumBackEdges() != 1) {
2652 LLVM_DEBUG(
2653 dbgs() << "LAA: loop control flow is not understood by analyzer\n");
2654 recordAnalysis("CFGNotUnderstood")
2655 << "loop control flow is not understood by analyzer";
2656 return false;
2657 }
2658
2659 // ScalarEvolution needs to be able to find the symbolic max backedge taken
2660 // count, which is an upper bound on the number of loop iterations. The loop
2661 // may execute fewer iterations, if it exits via an uncountable exit.
2662 const SCEV *ExitCount = PSE->getSymbolicMaxBackedgeTakenCount();
2663 if (isa<SCEVCouldNotCompute>(ExitCount)) {
2664 recordAnalysis("CantComputeNumberOfIterations")
2665 << "could not determine number of loop iterations";
2666 LLVM_DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
2667 return false;
2668 }
2669
2670 LLVM_DEBUG(dbgs() << "LAA: Found an analyzable loop: "
2671 << TheLoop->getHeader()->getName() << "\n");
2672 return true;
2673}
2674
2675bool LoopAccessInfo::analyzeLoop(AAResults *AA, const LoopInfo *LI,
2676 const TargetLibraryInfo *TLI,
2677 DominatorTree *DT) {
2678 // Holds the Load and Store instructions.
2681 SmallPtrSet<MDNode *, 8> LoopAliasScopes;
2682
2683 // Holds all the different accesses in the loop.
2684 unsigned NumReads = 0;
2685 unsigned NumReadWrites = 0;
2686
2687 bool HasComplexMemInst = false;
2688
2689 // A runtime check is only legal to insert if there are no convergent calls.
2690 HasConvergentOp = false;
2691
2692 PtrRtChecking->Pointers.clear();
2693 PtrRtChecking->Need = false;
2694
2695 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
2696
2697 const bool EnableMemAccessVersioningOfLoop =
2699 !TheLoop->getHeader()->getParent()->hasOptSize();
2700
2701 // Traverse blocks in fixed RPOT order, regardless of their storage in the
2702 // loop info, as it may be arbitrary.
2703 LoopBlocksRPO RPOT(TheLoop);
2704 RPOT.perform(LI);
2705
2706 // Don't return early as soon as we found a memory access that cannot be
2707 // vectorize - HasConvergentOp must still be computed as it is part of LAI's
2708 // public API (used by LoopDistribute).
2709 for (BasicBlock *BB : RPOT) {
2710 // Scan the BB and collect legal loads and stores. Also detect any
2711 // convergent instructions.
2712 for (Instruction &I : *BB) {
2713 if (auto *Call = dyn_cast<CallBase>(&I)) {
2714 if (Call->isConvergent())
2715 HasConvergentOp = true;
2716 }
2717
2718 // Unsafe to vectorize and we already found a convergent operation, can
2719 // early return now.
2720 if (HasComplexMemInst && HasConvergentOp)
2721 return false;
2722
2723 // Already unsafe to vectorize; keep scanning for convergent ops.
2724 if (HasComplexMemInst)
2725 continue;
2726
2727 // Record alias scopes defined inside the loop.
2728 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
2729 for (Metadata *Op : Decl->getScopeList()->operands())
2730 LoopAliasScopes.insert(cast<MDNode>(Op));
2731
2732 // Many math library functions read the rounding mode. We will only
2733 // vectorize a loop if it contains known function calls that don't set
2734 // the flag. Therefore, it is safe to ignore this read from memory.
2735 auto *Call = dyn_cast<CallInst>(&I);
2737 continue;
2738
2739 // If this is a load, save it. If this instruction can read from memory
2740 // but is not a load, we only allow it if it's a call to a function with a
2741 // vector mapping and no pointer arguments.
2742 if (I.mayReadFromMemory()) {
2743 auto hasPointerArgs = [](CallBase *CB) {
2744 return any_of(CB->args(), [](Value const *Arg) {
2745 return Arg->getType()->isPointerTy();
2746 });
2747 };
2748
2749 // If the function has an explicit vectorized counterpart, and does not
2750 // take output/input pointers, we can safely assume that it can be
2751 // vectorized.
2752 if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
2753 !hasPointerArgs(Call) && !VFDatabase::getMappings(*Call).empty())
2754 continue;
2755
2756 auto *Ld = dyn_cast<LoadInst>(&I);
2757 if (!Ld) {
2758 recordAnalysis("CantVectorizeInstruction", &I)
2759 << "instruction cannot be vectorized";
2760 HasComplexMemInst = true;
2761 continue;
2762 }
2763 if (!Ld->isSimple() && !IsAnnotatedParallel) {
2764 recordAnalysis("NonSimpleLoad", Ld)
2765 << "read with atomic ordering or volatile read";
2766 LLVM_DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
2767 HasComplexMemInst = true;
2768 continue;
2769 }
2770 NumLoads++;
2771 Loads.push_back(Ld);
2772 DepChecker->addAccess(Ld);
2773 if (EnableMemAccessVersioningOfLoop)
2774 collectStridedAccess(Ld);
2775 continue;
2776 }
2777
2778 // Save 'store' instructions. Abort if other instructions write to memory.
2779 if (I.mayWriteToMemory()) {
2780 auto *St = dyn_cast<StoreInst>(&I);
2781 if (!St) {
2782 recordAnalysis("CantVectorizeInstruction", &I)
2783 << "instruction cannot be vectorized";
2784 HasComplexMemInst = true;
2785 continue;
2786 }
2787 if (!St->isSimple() && !IsAnnotatedParallel) {
2788 recordAnalysis("NonSimpleStore", St)
2789 << "write with atomic ordering or volatile write";
2790 LLVM_DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
2791 HasComplexMemInst = true;
2792 continue;
2793 }
2794 NumStores++;
2795 Stores.push_back(St);
2796 DepChecker->addAccess(St);
2797 if (EnableMemAccessVersioningOfLoop)
2798 collectStridedAccess(St);
2799 }
2800 } // Next instr.
2801 } // Next block.
2802
2803 if (HasComplexMemInst)
2804 return false;
2805
2806 // Now we have two lists that hold the loads and the stores.
2807 // Next, we find the pointers that they use.
2808
2809 // Check if we see any stores. If there are no stores, then we don't
2810 // care if the pointers are *restrict*.
2811 if (!Stores.size()) {
2812 LLVM_DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
2813 return true;
2814 }
2815
2817 AccessAnalysis Accesses(TheLoop, AA, LI, *DT, DepCands, *PSE,
2818 LoopAliasScopes);
2819
2820 // Holds the analyzed pointers. We don't want to call getUnderlyingObjects
2821 // multiple times on the same object. If the ptr is accessed twice, once
2822 // for read and once for write, it will only appear once (on the write
2823 // list). This is okay, since we are going to check for conflicts between
2824 // writes and between reads and writes, but not between reads and reads.
2825 SmallSet<std::pair<Value *, Type *>, 16> Seen;
2826
2827 // Record uniform store addresses to identify if we have multiple stores
2828 // to the same address.
2829 SmallPtrSet<Value *, 16> UniformStores;
2830
2831 for (StoreInst *ST : Stores) {
2832 Value *Ptr = ST->getPointerOperand();
2833
2834 if (isInvariant(Ptr)) {
2835 // Record store instructions to loop invariant addresses
2836 StoresToInvariantAddresses.push_back(ST);
2837 HasStoreStoreDependenceInvolvingLoopInvariantAddress |=
2838 !UniformStores.insert(Ptr).second;
2839 }
2840
2841 // If we did *not* see this pointer before, insert it to the read-write
2842 // list. At this phase it is only a 'write' list.
2843 Type *AccessTy = getLoadStoreType(ST);
2844 if (Seen.insert({Ptr, AccessTy}).second) {
2845 ++NumReadWrites;
2846
2847 MemoryLocation Loc = MemoryLocation::get(ST);
2848 // The TBAA metadata could have a control dependency on the predication
2849 // condition, so we cannot rely on it when determining whether or not we
2850 // need runtime pointer checks.
2851 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
2852 Loc.AATags.TBAA = nullptr;
2853
2854 // Expand forked pointers (i.e., a phi of multiple strided pointers) into
2855 // all alternatives.
2856 visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop,
2857 [&Accesses, AccessTy, Loc](Value *Ptr) {
2858 MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr);
2859 Accesses.addStore(NewLoc, AccessTy);
2860 });
2861 }
2862 }
2863
2864 if (IsAnnotatedParallel) {
2865 LLVM_DEBUG(
2866 dbgs() << "LAA: A loop annotated parallel, ignore memory dependency "
2867 << "checks.\n");
2868 return true;
2869 }
2870
2871 for (LoadInst *LD : Loads) {
2872 Value *Ptr = LD->getPointerOperand();
2873 // If we did *not* see this pointer before, insert it to the read list. If
2874 // we *did* see it before, then it is already in the read-write list. This
2875 // allows us to vectorize expressions such as A[i] += x; Because the address
2876 // of A[i] is a read-write pointer. This only works if the index of A[i] is
2877 // strictly monotonic, which we approximate (conservatively) via
2878 // getPtrStride. If the address is unknown (e.g. A[B[i]]) then we may read,
2879 // modify, and write overlapping words. Note that "zero stride" is unsafe
2880 // and is being handled below.
2881 bool IsReadOnlyPtr = false;
2882 Type *AccessTy = getLoadStoreType(LD);
2883 if (Seen.insert({Ptr, AccessTy}).second ||
2884 !getPtrStride(*PSE, AccessTy, Ptr, TheLoop, *DT, SymbolicStrides, false,
2885 true)) {
2886 ++NumReads;
2887 IsReadOnlyPtr = true;
2888 }
2889
2890 // See if there is an unsafe dependency between a load to a uniform address and
2891 // store to the same uniform address.
2892 if (UniformStores.contains(Ptr)) {
2893 LLVM_DEBUG(dbgs() << "LAA: Found an unsafe dependency between a uniform "
2894 "load and uniform store to the same address!\n");
2895 HasLoadStoreDependenceInvolvingLoopInvariantAddress = true;
2896 }
2897
2898 MemoryLocation Loc = MemoryLocation::get(LD);
2899 // The TBAA metadata could have a control dependency on the predication
2900 // condition, so we cannot rely on it when determining whether or not we
2901 // need runtime pointer checks.
2902 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
2903 Loc.AATags.TBAA = nullptr;
2904
2905 // Expand forked pointers (i.e., a phi of multiple strided pointers) into
2906 // all alternatives.
2907 visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop,
2908 [&Accesses, AccessTy, Loc, IsReadOnlyPtr](Value *Ptr) {
2909 MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr);
2910 Accesses.addLoad(NewLoc, AccessTy, IsReadOnlyPtr);
2911 });
2912 }
2913
2914 // If we write (or read-write) to a single destination and there are no other
2915 // reads in this loop then is it safe to vectorize: the vectorized stores
2916 // preserve ordering via replication or order-preserving @llvm.masked.scatter.
2917 if (NumReadWrites == 1 && NumReads == 0) {
2918 LLVM_DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
2919 return true;
2920 }
2921
2922 // Build dependence sets and check whether we need a runtime pointer bounds
2923 // check.
2924 Accesses.buildDependenceSets();
2925
2926 // Find pointers with computable bounds. We are going to use this information
2927 // to place a runtime bound check.
2928 Value *UncomputablePtr = nullptr;
2929 HasCompletePtrRtChecking =
2930 Accesses.canCheckPtrAtRT(*PtrRtChecking, TheLoop, SymbolicStrides,
2931 UncomputablePtr, AllowPartial, getDepChecker());
2932 if (!HasCompletePtrRtChecking) {
2933 const auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr);
2934 recordAnalysis("CantIdentifyArrayBounds", I)
2935 << "cannot identify array bounds";
2936 LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
2937 << "the array bounds.\n");
2938 return false;
2939 }
2940
2941 LLVM_DEBUG(
2942 dbgs() << "LAA: May be able to perform a memory runtime check if needed.\n");
2943
2944 bool DepsAreSafe = true;
2945 if (Accesses.isDependencyCheckNeeded()) {
2946 LLVM_DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
2947 DepsAreSafe =
2948 DepChecker->areDepsSafe(DepCands, Accesses.getDependenciesToCheck());
2949
2950 if (!DepsAreSafe && DepChecker->shouldRetryWithRuntimeChecks()) {
2951 LLVM_DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
2952
2953 PtrRtChecking->reset();
2954 PtrRtChecking->Need = true;
2955
2956 UncomputablePtr = nullptr;
2957 HasCompletePtrRtChecking = Accesses.canCheckPtrAtRT(
2958 *PtrRtChecking, TheLoop, SymbolicStrides, UncomputablePtr,
2959 AllowPartial, getDepChecker());
2960
2961 // Check that we found the bounds for the pointer.
2962 if (!HasCompletePtrRtChecking) {
2963 auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr);
2964 recordAnalysis("CantCheckMemDepsAtRunTime", I)
2965 << "cannot check memory dependencies at runtime";
2966 LLVM_DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
2967 return false;
2968 }
2969
2970 // Clear the dependency checks. They are no longer needed.
2971 Accesses.resetDepChecks(*DepChecker);
2972
2973 DepsAreSafe = true;
2974 }
2975 }
2976
2977 // Update the invariant address dependence flags based on dependences found
2978 // by the dep checker. Even if dependences were not recorded (too many to
2979 // track), any InvariantUnsafe dep would still have set the status to Unsafe
2980 if (const auto *Deps = DepChecker->getDependences()) {
2981 for (const auto &Dep : *Deps) {
2983 continue;
2984 Instruction *Src = Dep.getSource(*DepChecker);
2985 Instruction *Dst = Dep.getDestination(*DepChecker);
2986 if (isa<LoadInst>(Src) != isa<LoadInst>(Dst)) {
2987 HasLoadStoreDependenceInvolvingLoopInvariantAddress = true;
2988 } else {
2989 assert(isa<StoreInst>(Src) && isa<StoreInst>(Dst) &&
2990 "Expected both to be stores");
2991 HasStoreStoreDependenceInvolvingLoopInvariantAddress = true;
2992 }
2993 }
2994 }
2995
2996 if (HasConvergentOp) {
2997 recordAnalysis("CantInsertRuntimeCheckWithConvergent")
2998 << "cannot add control dependency to convergent operation";
2999 LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because a runtime check "
3000 "would be needed with a convergent operation\n");
3001 return false;
3002 }
3003
3004 if (DepsAreSafe) {
3005 LLVM_DEBUG(
3006 dbgs() << "LAA: No unsafe dependent memory operations in loop. We"
3007 << (PtrRtChecking->Need ? "" : " don't")
3008 << " need runtime memory checks.\n");
3009 return true;
3010 }
3011
3012 emitUnsafeDependenceRemark();
3013 return false;
3014}
3015
3016void LoopAccessInfo::emitUnsafeDependenceRemark() {
3017 const auto *Deps = getDepChecker().getDependences();
3018 if (!Deps)
3019 return;
3020 const auto *Found =
3021 llvm::find_if(*Deps, [](const MemoryDepChecker::Dependence &D) {
3024 });
3025 if (Found == Deps->end())
3026 return;
3027 MemoryDepChecker::Dependence Dep = *Found;
3028
3029 LLVM_DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
3030
3031 // Emit remark for first unsafe dependence
3032 bool HasForcedDistribution =
3033 getBooleanLoopAttribute(TheLoop, "llvm.loop.distribute.enable");
3034
3035 const std::string Info =
3036 HasForcedDistribution
3037 ? "unsafe dependent memory operations in loop."
3038 : "unsafe dependent memory operations in loop. Use "
3039 "#pragma clang loop distribute(enable) to allow loop distribution "
3040 "to attempt to isolate the offending operations into a separate "
3041 "loop";
3042 OptimizationRemarkAnalysis &R =
3043 recordAnalysis("UnsafeDep", Dep.getDestination(getDepChecker())) << Info;
3044
3045 switch (Dep.Type) {
3049 llvm_unreachable("Unexpected dependence");
3051 R << "\nBackward loop carried data dependence.";
3052 break;
3054 R << "\nForward loop carried data dependence that prevents "
3055 "store-to-load forwarding.";
3056 break;
3058 R << "\nBackward loop carried data dependence that prevents "
3059 "store-to-load forwarding.";
3060 break;
3062 R << "\nUnsafe indirect dependence.";
3063 break;
3065 R << "\nUnsafe dependence on loop-invariant address.";
3066 break;
3068 R << "\nUnknown data dependence.";
3069 break;
3070 }
3071
3072 if (Instruction *I = Dep.getSource(getDepChecker())) {
3073 DebugLoc SourceLoc = I->getDebugLoc();
3075 SourceLoc = DD->getDebugLoc();
3076 if (SourceLoc)
3077 R << " Memory location is the same as accessed at "
3078 << ore::NV("Location", SourceLoc);
3079 }
3080}
3081
3083 const Loop *TheLoop,
3084 const DominatorTree *DT) {
3085 assert(TheLoop->contains(BB) && "Unknown block used");
3086
3087 // Blocks that do not dominate the latch need predication.
3088 const BasicBlock *Latch = TheLoop->getLoopLatch();
3089 assert(Latch && "Loop expected to have a single latch.");
3090 return !DT->dominates(BB, Latch);
3091}
3092
3094LoopAccessInfo::recordAnalysis(StringRef RemarkName, const Instruction *I) {
3095 assert(!Report && "Multiple reports generated");
3096
3097 const BasicBlock *CodeRegion = TheLoop->getHeader();
3098 DebugLoc DL = TheLoop->getStartLoc();
3099
3100 if (I) {
3101 CodeRegion = I->getParent();
3102 // If there is no debug location attached to the instruction, revert back to
3103 // using the loop's.
3104 if (I->getDebugLoc())
3105 DL = I->getDebugLoc();
3106 }
3107
3108 Report = std::make_unique<OptimizationRemarkAnalysis>(DEBUG_TYPE, RemarkName,
3109 DL, CodeRegion);
3110 return *Report;
3111}
3112
3114 auto *SE = PSE->getSE();
3115 if (TheLoop->isLoopInvariant(V))
3116 return true;
3117 if (!SE->isSCEVable(V->getType()))
3118 return false;
3119 const SCEV *S = SE->getSCEV(V);
3120 return SE->isLoopInvariant(S, TheLoop);
3121}
3122
3123/// If \p Ptr is a GEP, which has a loop-variant operand, return that operand.
3124/// Otherwise, return \p Ptr.
3126 Loop *Lp) {
3127 auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3128 if (!GEP)
3129 return Ptr;
3130
3131 Value *V = Ptr;
3132 for (const Use &U : GEP->operands()) {
3133 if (!SE->isLoopInvariant(SE->getSCEV(U), Lp)) {
3134 if (V == Ptr)
3135 V = U;
3136 else
3137 // There must be exactly one loop-variant operand.
3138 return Ptr;
3139 }
3140 }
3141 return V;
3142}
3143
3144/// Get the stride of a pointer access in a loop. Looks for symbolic
3145/// strides "a[i*stride]". Returns the symbolic stride, or null otherwise.
3146static const SCEV *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
3147 auto *PtrTy = dyn_cast<PointerType>(Ptr->getType());
3148 if (!PtrTy)
3149 return nullptr;
3150
3151 // Try to remove a gep instruction to make the pointer (actually index at this
3152 // point) easier analyzable. If OrigPtr is equal to Ptr we are analyzing the
3153 // pointer, otherwise, we are analyzing the index.
3154 Value *OrigPtr = Ptr;
3155
3156 Ptr = getLoopVariantGEPOperand(Ptr, SE, Lp);
3157 const SCEV *V = SE->getSCEV(Ptr);
3158
3159 if (Ptr != OrigPtr)
3160 // Strip off casts.
3161 while (auto *C = dyn_cast<SCEVIntegralCastExpr>(V))
3162 V = C->getOperand();
3163
3165 return nullptr;
3166
3167 // Note that the restriction after this loop invariant check are only
3168 // profitability restrictions.
3169 if (!SE->isLoopInvariant(V, Lp))
3170 return nullptr;
3171
3172 // Look for the loop invariant symbolic value.
3173 if (isa<SCEVUnknown>(V))
3174 return V;
3175
3176 // Look through multiplies that scale a stride by a constant.
3178 if (auto *C = dyn_cast<SCEVIntegralCastExpr>(V))
3179 if (isa<SCEVUnknown>(C->getOperand()))
3180 return V;
3181
3182 return nullptr;
3183}
3184
3185void LoopAccessInfo::collectStridedAccess(Value *MemAccess) {
3186 Value *Ptr = getLoadStorePointerOperand(MemAccess);
3187 if (!Ptr)
3188 return;
3189
3190 // Note: getStrideFromPointer is a *profitability* heuristic. We
3191 // could broaden the scope of values returned here - to anything
3192 // which happens to be loop invariant and contributes to the
3193 // computation of an interesting IV - but we chose not to as we
3194 // don't have a cost model here, and broadening the scope exposes
3195 // far too many unprofitable cases.
3196 const SCEV *StrideExpr = getStrideFromPointer(Ptr, PSE->getSE(), TheLoop);
3197 if (!StrideExpr)
3198 return;
3199
3200 if (match(StrideExpr, m_scev_UndefOrPoison()))
3201 return;
3202
3203 LLVM_DEBUG(dbgs() << "LAA: Found a strided access that is a candidate for "
3204 "versioning:");
3205 LLVM_DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *StrideExpr << "\n");
3206
3207 if (!SpeculateUnitStride) {
3208 LLVM_DEBUG(dbgs() << " Chose not to due to -laa-speculate-unit-stride\n");
3209 return;
3210 }
3211
3212 // Avoid adding the "Stride == 1" predicate when we know that
3213 // Stride >= Trip-Count. Such a predicate will effectively optimize a single
3214 // or zero iteration loop, as Trip-Count <= Stride == 1.
3215 //
3216 // TODO: We are currently not making a very informed decision on when it is
3217 // beneficial to apply stride versioning. It might make more sense that the
3218 // users of this analysis (such as the vectorizer) will trigger it, based on
3219 // their specific cost considerations; For example, in cases where stride
3220 // versioning does not help resolving memory accesses/dependences, the
3221 // vectorizer should evaluate the cost of the runtime test, and the benefit
3222 // of various possible stride specializations, considering the alternatives
3223 // of using gather/scatters (if available).
3224
3225 const SCEV *MaxBTC = PSE->getSymbolicMaxBackedgeTakenCount();
3226
3227 // Match the types so we can compare the stride and the MaxBTC.
3228 // The Stride can be positive/negative, so we sign extend Stride;
3229 // The backedgeTakenCount is non-negative, so we zero extend MaxBTC.
3230 const DataLayout &DL = TheLoop->getHeader()->getDataLayout();
3231 uint64_t StrideTypeSizeBits = DL.getTypeSizeInBits(StrideExpr->getType());
3232 uint64_t BETypeSizeBits = DL.getTypeSizeInBits(MaxBTC->getType());
3233 const SCEV *CastedStride = StrideExpr;
3234 const SCEV *CastedBECount = MaxBTC;
3235 ScalarEvolution *SE = PSE->getSE();
3236 if (BETypeSizeBits >= StrideTypeSizeBits)
3237 CastedStride = SE->getNoopOrSignExtend(StrideExpr, MaxBTC->getType());
3238 else
3239 CastedBECount = SE->getZeroExtendExpr(MaxBTC, StrideExpr->getType());
3240 const SCEV *StrideMinusBETaken = SE->getMinusSCEV(CastedStride, CastedBECount);
3241 // Since TripCount == BackEdgeTakenCount + 1, checking:
3242 // "Stride >= TripCount" is equivalent to checking:
3243 // Stride - MaxBTC> 0
3244 if (SE->isKnownPositive(StrideMinusBETaken)) {
3245 LLVM_DEBUG(
3246 dbgs() << "LAA: Stride>=TripCount; No point in versioning as the "
3247 "Stride==1 predicate will imply that the loop executes "
3248 "at most once.\n");
3249 return;
3250 }
3251 LLVM_DEBUG(dbgs() << "LAA: Found a strided access that we can version.\n");
3252
3253 // Strip back off the integer cast, and check that our result is a
3254 // SCEVUnknown as we expect.
3255 const SCEV *StrideBase = StrideExpr;
3256 if (const auto *C = dyn_cast<SCEVIntegralCastExpr>(StrideBase))
3257 StrideBase = C->getOperand();
3258 assert(SE->isLoopInvariant(StrideBase, TheLoop) &&
3259 "users of the map rely on the stride being loop invariant");
3260 SymbolicStrides[Ptr] = cast<SCEVUnknown>(StrideBase);
3261}
3262
3264 const TargetTransformInfo *TTI,
3265 const TargetLibraryInfo *TLI, AAResults *AA,
3266 DominatorTree *DT, LoopInfo *LI,
3267 AssumptionCache *AC, bool AllowPartial)
3268 : PSE(std::make_unique<PredicatedScalarEvolution>(*SE, *L)),
3269 PtrRtChecking(nullptr), TheLoop(L), AllowPartial(AllowPartial) {
3270 unsigned MaxTargetVectorWidthInBits = std::numeric_limits<unsigned>::max();
3271 if (TTI && !TTI->enableScalableVectorization())
3272 // Scale the vector width by 2 as rough estimate to also consider
3273 // interleaving.
3274 MaxTargetVectorWidthInBits =
3275 TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector) * 2;
3276
3277 DepChecker = std::make_unique<MemoryDepChecker>(
3278 *PSE, AC, DT, L, SymbolicStrides, MaxTargetVectorWidthInBits, LoopGuards);
3279 PtrRtChecking =
3280 std::make_unique<RuntimePointerChecking>(*DepChecker, SE, LoopGuards);
3281 if (canAnalyzeLoop())
3282 CanVecMem = analyzeLoop(AA, LI, TLI, DT);
3283}
3284
3285void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
3286 if (CanVecMem) {
3287 OS.indent(Depth) << "Memory dependences are safe";
3288 const MemoryDepChecker &DC = getDepChecker();
3289 if (!DC.isSafeForAnyVectorWidth())
3290 OS << " with a maximum safe vector width of "
3291 << DC.getMaxSafeVectorWidthInBits() << " bits";
3293 uint64_t SLDist = DC.getStoreLoadForwardSafeDistanceInBits();
3294 OS << ", with a maximum safe store-load forward width of " << SLDist
3295 << " bits";
3296 }
3297 if (PtrRtChecking->Need)
3298 OS << " with run-time checks";
3299 OS << "\n";
3300 }
3301
3302 if (HasConvergentOp)
3303 OS.indent(Depth) << "Has convergent operation in loop\n";
3304
3305 if (Report)
3306 OS.indent(Depth) << "Report: " << Report->getMsg() << "\n";
3307
3308 if (auto *Dependences = DepChecker->getDependences()) {
3309 OS.indent(Depth) << "Dependences:\n";
3310 for (const auto &Dep : *Dependences) {
3311 Dep.print(OS, Depth + 2, DepChecker->getMemoryInstructions());
3312 OS << "\n";
3313 }
3314 } else
3315 OS.indent(Depth) << "Too many dependences, not recorded\n";
3316
3317 // List the pair of accesses need run-time checks to prove independence.
3318 PtrRtChecking->print(OS, Depth);
3319 if (PtrRtChecking->Need && !HasCompletePtrRtChecking)
3320 OS.indent(Depth) << "Generated run-time checks are incomplete\n";
3321 OS << "\n";
3322
3323 OS.indent(Depth)
3324 << "Non vectorizable stores to invariant address were "
3325 << (HasStoreStoreDependenceInvolvingLoopInvariantAddress ||
3326 HasLoadStoreDependenceInvolvingLoopInvariantAddress
3327 ? ""
3328 : "not ")
3329 << "found in loop.\n";
3330
3331 OS.indent(Depth) << "SCEV assumptions:\n";
3332 PSE->getPredicate().print(OS, Depth);
3333
3334 OS << "\n";
3335
3336 OS.indent(Depth) << "Expressions re-written:\n";
3337 PSE->print(OS, Depth);
3338}
3339
3341 bool AllowPartial) {
3342 const auto &[It, Inserted] = LoopAccessInfoMap.try_emplace(&L);
3343
3344 // We need to create the LoopAccessInfo if either we don't already have one,
3345 // or if it was created with a different value of AllowPartial.
3346 if (Inserted || It->second->hasAllowPartial() != AllowPartial)
3347 It->second = std::make_unique<LoopAccessInfo>(&L, &SE, TTI, TLI, &AA, &DT,
3348 &LI, AC, AllowPartial);
3349
3350 return *It->second;
3351}
3353 // Collect LoopAccessInfo entries that may keep references to IR outside the
3354 // analyzed loop or SCEVs that may have been modified or invalidated. At the
3355 // moment, that is loops requiring memory or SCEV runtime checks, as those cache
3356 // SCEVs, e.g. for pointer expressions.
3357 LoopAccessInfoMap.remove_if([](const auto &Entry) {
3358 const auto &LAI = Entry.second;
3359 return !(LAI->getRuntimePointerChecking()->getChecks().empty() &&
3360 LAI->getPSE().getPredicate().isAlwaysTrue());
3361 });
3362}
3363
3365 Function &F, const PreservedAnalyses &PA,
3366 FunctionAnalysisManager::Invalidator &Inv) {
3367 // Check whether our analysis is preserved.
3368 auto PAC = PA.getChecker<LoopAccessAnalysis>();
3369 if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>())
3370 // If not, give up now.
3371 return true;
3372
3373 // Check whether the analyses we depend on became invalid for any reason.
3374 // Skip checking TargetLibraryAnalysis as it is immutable and can't become
3375 // invalid.
3376 return Inv.invalidate<AAManager>(F, PA) ||
3377 Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) ||
3378 Inv.invalidate<LoopAnalysis>(F, PA) ||
3379 Inv.invalidate<DominatorTreeAnalysis>(F, PA);
3380}
3381
3384 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
3385 auto &AA = FAM.getResult<AAManager>(F);
3386 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
3387 auto &LI = FAM.getResult<LoopAnalysis>(F);
3388 auto &TTI = FAM.getResult<TargetIRAnalysis>(F);
3389 auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
3390 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
3391 return LoopAccessInfoManager(SE, AA, DT, LI, &TTI, &TLI, &AC);
3392}
3393
3394AnalysisKey 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
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")
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.
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 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< 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...
static std::pair< const SCEV *, const SCEV * > getNonAffineMonotonicBounds(const Loop *Lp, const SCEV *PtrExpr, ScalarEvolution *SE)
Try to bound a loop-variant pointer that is not an affine AddRec.
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 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 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
This file provides utility analysis objects describing memory locations.
#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:1573
APInt abs() const
Get the absolute value.
Definition APInt.h:1816
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1085
std::optional< int64_t > trySExtValue() const
Get sign extended value if possible.
Definition APInt.h:1595
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 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_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ 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)
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A debug info location.
Definition DebugLoc.h:126
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:250
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
iterator end()
Definition DenseMap.h:141
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:698
bool empty() const
Definition Function.h:843
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:1424
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 bool hasNoOverflow(Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags)
Returns true if we've statically proved that V doesn't wrap.
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 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.
LLVM_ABI void insert(Loop *Lp, Value *Ptr, const SCEV *PtrExpr, Type *AccessTy, bool WritePtr, unsigned DepSetId, unsigned ASId, PredicatedScalarEvolution &PSE, bool NeedsFreeze)
Insert a pointer and calculate the start and end SCEVs.
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
NoWrapFlags getNoWrapFlags(NoWrapFlags Mask=NoWrapMask) const
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
IncrementWrapFlags
Similar to SCEV::NoWrapFlags, but with slightly different semantics for FlagNUSW.
static SCEVWrapPredicate::IncrementWrapFlags clearFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OffFlags)
Convenient IncrementWrapFlags manipulation methods.
static SCEVWrapPredicate::IncrementWrapFlags getImpliedFlags(const SCEVAddRecExpr *AR, ScalarEvolution &SE)
Returns the set of SCEVWrapPredicate no wrap flags implied by a SCEVAddRecExpr.
This class represents an analyzed expression in the program.
static constexpr auto NoWrapMask
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 * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
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.
LLVM_ABI const SCEV * getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
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 SCEVPredicate * getEqualPredicate(const SCEV *LHS, const SCEV *RHS)
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 * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
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 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...
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 const SCEV * getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, 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 const SCEV * getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
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 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 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:288
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
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:255
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
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
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)
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:315
@ 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:830
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
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 isValidAssumeForContext(const Instruction *I, const Instruction *CxtI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
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:2554
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:2208
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
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:2026
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
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
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
TargetTransformInfo TTI
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
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:1772
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
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...
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.
MDNode * Scope
The tag for alias scope specification (used with noalias).
Definition Metadata.h:786
MDNode * TBAA
The tag for type-based alias analysis.
Definition Metadata.h:780
MDNode * NoAlias
The tag specifying the noalias scope.
Definition Metadata.h:789
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.
static LLVM_ABI const unsigned MaxVectorWidth
Maximum SIMD width.
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:1439