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