LLVM 23.0.0git
Loads.cpp
Go to the documentation of this file.
1//===- Loads.cpp - Local load analysis ------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines simple local analyses for load instructions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/Analysis/Loads.h"
23#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/Operator.h"
27
28using namespace llvm;
29
30static bool isAligned(const Value *Base, Align Alignment,
31 const DataLayout &DL) {
32 return Base->getPointerAlignment(DL) >= Alignment;
33}
34
36 const Value *Ptr, Align Alignment,
37 function_ref<bool(const RetainedKnowledge &RK)> CheckSize,
38 const DataLayout &DL, const Instruction *CtxI, AssumptionCache *AC,
39 const DominatorTree *DT) {
40 if (!CtxI)
41 return false;
42 /// Look through assumes to see if both dereferencability and alignment can
43 /// be proven by an assume if needed.
44 RetainedKnowledge AlignRK;
45 RetainedKnowledge DerefRK;
46 bool PtrCanBeFreed = Ptr->canBeFreed();
47 bool IsAligned = Ptr->getPointerAlignment(DL) >= Alignment;
49 Ptr, {Attribute::Dereferenceable, Attribute::Alignment}, *AC,
50 [&](RetainedKnowledge RK, Instruction *Assume, auto) {
51 if (!isValidAssumeForContext(Assume, CtxI, DT))
52 return false;
53 if (RK.AttrKind == Attribute::Alignment)
54 AlignRK = std::max(AlignRK, RK);
55
56 // Dereferenceable information from assumptions is only valid if the
57 // value cannot be freed between the assumption and use.
58 if ((!PtrCanBeFreed || willNotFreeBetween(Assume, CtxI)) &&
59 RK.AttrKind == Attribute::Dereferenceable)
60 DerefRK = std::max(DerefRK, RK);
61 IsAligned |= AlignRK && AlignRK.ArgValue >= Alignment.value();
62 if (IsAligned && DerefRK && CheckSize(DerefRK))
63 return true; // We have found what we needed so we stop looking
64 return false; // Other assumes may have better information. so
65 // keep looking
66 });
67}
68
69/// Test if V is always a pointer to allocated and suitably aligned memory for
70/// a simple load or store.
72 const Value *V, Align Alignment, const APInt &Size, const DataLayout &DL,
73 const Instruction *CtxI, AssumptionCache *AC, const DominatorTree *DT,
75 unsigned MaxDepth) {
76 assert(V->getType()->isPointerTy() && "Base must be pointer");
77
78 // Recursion limit.
79 if (MaxDepth-- == 0)
80 return false;
81
82 // Already visited? Bail out, we've likely hit unreachable code.
83 if (!Visited.insert(V).second)
84 return false;
85
86 // Note that it is not safe to speculate into a malloc'd region because
87 // malloc may return null.
88
89 // For GEPs, determine if the indexing lands within the allocated object.
90 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
91 const Value *Base = GEP->getPointerOperand();
92
93 APInt Offset(DL.getIndexTypeSizeInBits(GEP->getType()), 0);
94 if (!GEP->accumulateConstantOffset(DL, Offset) || Offset.isNegative() ||
95 !Offset.urem(APInt(Offset.getBitWidth(), Alignment.value()))
96 .isMinValue())
97 return false;
98
99 // If the base pointer is dereferenceable for Offset+Size bytes, then the
100 // GEP (== Base + Offset) is dereferenceable for Size bytes. If the base
101 // pointer is aligned to Align bytes, and the Offset is divisible by Align
102 // then the GEP (== Base + Offset == k_0 * Align + k_1 * Align) is also
103 // aligned to Align bytes.
104
105 // Offset and Size may have different bit widths if we have visited an
106 // addrspacecast, so we can't do arithmetic directly on the APInt values.
108 Base, Alignment, Offset + Size.sextOrTrunc(Offset.getBitWidth()), DL,
109 CtxI, AC, DT, TLI, Visited, MaxDepth);
110 }
111
112 // bitcast instructions are no-ops as far as dereferenceability is concerned.
113 if (const BitCastOperator *BC = dyn_cast<BitCastOperator>(V)) {
114 if (BC->getSrcTy()->isPointerTy())
116 BC->getOperand(0), Alignment, Size, DL, CtxI, AC, DT, TLI,
117 Visited, MaxDepth);
118 }
119
120 // Recurse into both hands of select.
121 if (const SelectInst *Sel = dyn_cast<SelectInst>(V)) {
122 return isDereferenceableAndAlignedPointer(Sel->getTrueValue(), Alignment,
123 Size, DL, CtxI, AC, DT, TLI,
124 Visited, MaxDepth) &&
125 isDereferenceableAndAlignedPointer(Sel->getFalseValue(), Alignment,
126 Size, DL, CtxI, AC, DT, TLI,
127 Visited, MaxDepth);
128 }
129
130 auto IsKnownDeref = [&]() {
131 bool CheckForNonNull, CheckForFreed;
132 if (!Size.ule(V->getPointerDereferenceableBytes(DL, CheckForNonNull,
133 CheckForFreed)))
134 return false;
135 if (CheckForNonNull &&
136 !isKnownNonZero(V, SimplifyQuery(DL, DT, AC, CtxI)))
137 return false;
138
139 auto *I = dyn_cast<Instruction>(V);
140 if (CheckForFreed) {
141 const Instruction *DefI;
142 if (I) {
143 // We don't want to consider frees by the instruction producing the
144 // pointer, so skip it if we can.
145 if (auto *II = dyn_cast<InvokeInst>(V)) {
146 DefI = &II->getNormalDest()->front();
147 } else if (!I->isTerminator()) {
148 DefI = I->getNextNode();
149 } else {
150 DefI = I;
151 }
152 } else {
153 // For arguments, check frees from the start of the entry block.
154 DefI = &cast<Argument>(V)->getParent()->getEntryBlock().front();
155 }
156
157 if (!willNotFreeBetween(DefI, CtxI))
158 return false;
159 }
160
161 // When using something like !dereferenceable on a load, the
162 // dereferenceability may only be valid on a specific control-flow path.
163 // If the instruction doesn't dominate the context instruction, we're
164 // asking about dereferenceability under the assumption that the
165 // instruction has been speculated to the point of the context instruction,
166 // in which case we don't know if the dereferenceability info still holds.
167 // We don't bother handling allocas here, as they aren't speculatable
168 // anyway.
169 if (I && !isa<AllocaInst>(I))
170 return CtxI && isValidAssumeForContext(I, CtxI, DT);
171 return true;
172 };
173 if (IsKnownDeref()) {
174 // As we recursed through GEPs to get here, we've incrementally checked
175 // that each step advanced by a multiple of the alignment. If our base is
176 // properly aligned, then the original offset accessed must also be.
177 return isAligned(V, Alignment, DL);
178 }
179
180 /// TODO refactor this function to be able to search independently for
181 /// Dereferencability and Alignment requirements.
182
183
184 if (const auto *Call = dyn_cast<CallBase>(V)) {
186 Call, /*MustPreserveOffset=*/true))
187 return isDereferenceableAndAlignedPointer(RP, Alignment, Size, DL, CtxI,
188 AC, DT, TLI, Visited, MaxDepth);
189
190 // If we have a call we can't recurse through, check to see if this is an
191 // allocation function for which we can establish an minimum object size.
192 // Such a minimum object size is analogous to a deref_or_null attribute in
193 // that we still need to prove the result non-null at point of use.
194 // NOTE: We can only use the object size as a base fact as we a) need to
195 // prove alignment too, and b) don't want the compile time impact of a
196 // separate recursive walk.
197 ObjectSizeOpts Opts;
198 // TODO: It may be okay to round to align, but that would imply that
199 // accessing slightly out of bounds was legal, and we're currently
200 // inconsistent about that. For the moment, be conservative.
201 Opts.RoundToAlign = false;
202 Opts.NullIsUnknownSize = true;
203 uint64_t ObjSize;
204 if (getObjectSize(V, ObjSize, DL, TLI, Opts)) {
205 APInt KnownDerefBytes(Size.getBitWidth(), ObjSize);
206 if (KnownDerefBytes.getBoolValue() && KnownDerefBytes.uge(Size) &&
207 isKnownNonZero(V, SimplifyQuery(DL, DT, AC, CtxI)) &&
208 !V->canBeFreed()) {
209 // As we recursed through GEPs to get here, we've incrementally
210 // checked that each step advanced by a multiple of the alignment. If
211 // our base is properly aligned, then the original offset accessed
212 // must also be.
213 return isAligned(V, Alignment, DL);
214 }
215 }
216 }
217
218 // For gc.relocate, look through relocations
219 if (const GCRelocateInst *RelocateInst = dyn_cast<GCRelocateInst>(V))
220 return isDereferenceableAndAlignedPointer(RelocateInst->getDerivedPtr(),
221 Alignment, Size, DL, CtxI, AC, DT,
222 TLI, Visited, MaxDepth);
223
225 return isDereferenceableAndAlignedPointer(ASC->getOperand(0), Alignment,
226 Size, DL, CtxI, AC, DT, TLI,
227 Visited, MaxDepth);
228
230 V, Alignment,
231 [Size](const RetainedKnowledge &RK) {
232 return RK.ArgValue >= Size.getZExtValue();
233 },
234 DL, CtxI, AC, DT);
235}
236
238 const Value *V, Align Alignment, const APInt &Size, const DataLayout &DL,
239 const Instruction *CtxI, AssumptionCache *AC, const DominatorTree *DT,
240 const TargetLibraryInfo *TLI) {
241 // Note: At the moment, Size can be zero. This ends up being interpreted as
242 // a query of whether [Base, V] is dereferenceable and V is aligned (since
243 // that's what the implementation happened to do). It's unclear if this is
244 // the desired semantic, but at least SelectionDAG does exercise this case.
245
247 return ::isDereferenceableAndAlignedPointer(V, Alignment, Size, DL, CtxI, AC,
248 DT, TLI, Visited, 16);
249}
250
252 const Value *V, Type *Ty, Align Alignment, const DataLayout &DL,
253 const Instruction *CtxI, AssumptionCache *AC, const DominatorTree *DT,
254 const TargetLibraryInfo *TLI) {
255 // For unsized types or scalable vectors we don't know exactly how many bytes
256 // are dereferenced, so bail out.
257 if (!Ty->isSized() || Ty->isScalableTy())
258 return false;
259
260 // When dereferenceability information is provided by a dereferenceable
261 // attribute, we know exactly how many bytes are dereferenceable. If we can
262 // determine the exact offset to the attributed variable, we can use that
263 // information here.
264
265 APInt AccessSize(DL.getPointerTypeSizeInBits(V->getType()),
266 DL.getTypeStoreSize(Ty));
267 return isDereferenceableAndAlignedPointer(V, Alignment, AccessSize, DL, CtxI,
268 AC, DT, TLI);
269}
270
272 const DataLayout &DL,
273 const Instruction *CtxI,
274 AssumptionCache *AC,
275 const DominatorTree *DT,
276 const TargetLibraryInfo *TLI) {
277 return isDereferenceableAndAlignedPointer(V, Ty, Align(1), DL, CtxI, AC, DT,
278 TLI);
279}
280
281/// Test if A and B will obviously have the same value.
282///
283/// This includes recognizing that %t0 and %t1 will have the same
284/// value in code like this:
285/// \code
286/// %t0 = getelementptr \@a, 0, 3
287/// store i32 0, i32* %t0
288/// %t1 = getelementptr \@a, 0, 3
289/// %t2 = load i32* %t1
290/// \endcode
291///
292static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
293 // Test if the values are trivially equivalent.
294 if (A == B)
295 return true;
296
297 // Test if the values come from identical arithmetic instructions.
298 // Use isIdenticalToWhenDefined instead of isIdenticalTo because
299 // this function is only used when one address use dominates the
300 // other, which means that they'll always either have the same
301 // value or one of them will have an undefined value.
303 if (const Instruction *BI = dyn_cast<Instruction>(B))
304 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
305 return true;
306
307 // Otherwise they may not be equivalent.
308 return false;
309}
310
312 LoadInst *LI, Loop *L, ScalarEvolution &SE, DominatorTree &DT,
314 auto &DL = LI->getDataLayout();
315 Value *Ptr = LI->getPointerOperand();
316 const SCEV *PtrSCEV = SE.getSCEV(Ptr);
317 APInt EltSize(DL.getIndexTypeSizeInBits(Ptr->getType()),
318 DL.getTypeStoreSize(LI->getType()).getFixedValue());
319
320 // If given a uniform (i.e. non-varying) address, see if we can prove the
321 // access is safe within the loop w/o needing predication.
322 if (L->isLoopInvariant(Ptr))
324 Ptr, LI->getAlign(), EltSize, DL, &*L->getHeader()->getFirstNonPHIIt(),
325 AC, &DT);
326
327 const SCEV *EltSizeSCEV = SE.getConstant(EltSize);
328 return isDereferenceableAndAlignedInLoop(PtrSCEV, LI->getAlign(), EltSizeSCEV,
329 L, SE, DT, AC, Predicates);
330}
331
333 const SCEV *PtrSCEV, Align Alignment, const SCEV *EltSizeSCEV, Loop *L,
336 auto *AddRec = dyn_cast<SCEVAddRecExpr>(PtrSCEV);
337
338 // Check to see if we have a repeating access pattern and it's possible
339 // to prove all accesses are well aligned.
340 if (!AddRec || AddRec->getLoop() != L || !AddRec->isAffine())
341 return false;
342
343 auto *Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(SE));
344 if (!Step)
345 return false;
346
347 const APInt &EltSize = cast<SCEVConstant>(EltSizeSCEV)->getAPInt();
348 // For the moment, restrict ourselves to the case where the access size is a
349 // multiple of the requested alignment and the base is aligned.
350 // TODO: generalize if a case found which warrants
351 if (EltSize.urem(Alignment.value()) != 0)
352 return false;
353
354 // TODO: Handle overlapping accesses.
355 if (EltSize.ugt(Step->getAPInt().abs()))
356 return false;
357
358 const SCEV *MaxBECount =
359 Predicates ? SE.getPredicatedSymbolicMaxBackedgeTakenCount(L, *Predicates)
361 const SCEV *BECount = Predicates
362 ? SE.getPredicatedBackedgeTakenCount(L, *Predicates)
363 : SE.getBackedgeTakenCount(L);
364 if (isa<SCEVCouldNotCompute>(MaxBECount))
365 return false;
366 std::optional<ScalarEvolution::LoopGuards> LoopGuards;
367
368 auto &DL = L->getHeader()->getDataLayout();
369 const auto &[AccessStart, AccessEnd] =
370 getStartAndEndForAccess(L, PtrSCEV, EltSizeSCEV, BECount, MaxBECount, &SE,
371 nullptr, &DT, AC, LoopGuards);
372 if (isa<SCEVCouldNotCompute>(AccessStart) ||
373 isa<SCEVCouldNotCompute>(AccessEnd))
374 return false;
375
376 // Try to get the access size.
377 const SCEV *PtrDiff = SE.getMinusSCEV(AccessEnd, AccessStart);
378 if (isa<SCEVCouldNotCompute>(PtrDiff))
379 return false;
380
381 if (!LoopGuards)
382 LoopGuards.emplace(
383 ScalarEvolution::LoopGuards::collect(AddRec->getLoop(), SE));
384
385 APInt MaxPtrDiff =
386 SE.getUnsignedRangeMax(SE.applyLoopGuards(PtrDiff, *LoopGuards));
387
388 Value *Base = nullptr;
389 APInt AccessSize;
390 const SCEV *AccessSizeSCEV = nullptr;
391 if (const SCEVUnknown *NewBase = dyn_cast<SCEVUnknown>(AccessStart)) {
392 Base = NewBase->getValue();
393 AccessSize = std::move(MaxPtrDiff);
394 AccessSizeSCEV = PtrDiff;
395 } else if (auto *MinAdd = dyn_cast<SCEVAddExpr>(AccessStart)) {
396 if (MinAdd->getNumOperands() != 2)
397 return false;
398
399 const auto *Offset = dyn_cast<SCEVConstant>(MinAdd->getOperand(0));
400 const auto *NewBase = dyn_cast<SCEVUnknown>(MinAdd->getOperand(1));
401 if (!Offset || !NewBase)
402 return false;
403
404 // The following code below assumes the offset is unsigned, but GEP
405 // offsets are treated as signed so we can end up with a signed value
406 // here too. For example, suppose the initial PHI value is (i8 255),
407 // the offset will be treated as (i8 -1) and sign-extended to (i64 -1).
408 if (Offset->getAPInt().isNegative())
409 return false;
410
411 // For the moment, restrict ourselves to the case where the offset is a
412 // multiple of the requested alignment and the base is aligned.
413 // TODO: generalize if a case found which warrants
414 if (Offset->getAPInt().urem(Alignment.value()) != 0)
415 return false;
416
417 bool Overflow = false;
418 AccessSize = MaxPtrDiff.uadd_ov(Offset->getAPInt(), Overflow);
419 if (Overflow)
420 return false;
421 AccessSizeSCEV = SE.getAddExpr(PtrDiff, Offset);
422 Base = NewBase->getValue();
423 } else
424 return false;
425
426 Instruction *CtxI = &*L->getHeader()->getFirstNonPHIIt();
427 if (BasicBlock *LoopPred = L->getLoopPredecessor()) {
428 if (isa<UncondBrInst, CondBrInst>(LoopPred->getTerminator()))
429 CtxI = LoopPred->getTerminator();
430 }
432 Base, Alignment,
433 [&SE, AccessSizeSCEV, &LoopGuards](const RetainedKnowledge &RK) {
434 return SE.isKnownPredicate(
436 SE.applyLoopGuards(AccessSizeSCEV, *LoopGuards),
437 SE.applyLoopGuards(SE.getSCEV(RK.IRArgValue), *LoopGuards));
438 },
439 DL, CtxI, AC, &DT) ||
440 isDereferenceableAndAlignedPointer(Base, Alignment, AccessSize, DL,
441 CtxI, AC, &DT);
442}
443
445 const Function &F = *CtxI.getFunction();
446 // Speculative load may create a race that did not exist in the source.
447 return F.hasFnAttribute(Attribute::SanitizeThread) ||
448 // Speculative load may load data from dirty regions.
449 F.hasFnAttribute(Attribute::SanitizeAddress) ||
450 F.hasFnAttribute(Attribute::SanitizeHWAddress);
451}
452
456
457/// Check if executing a load of this pointer value cannot trap.
458///
459/// If DT and ScanFrom are specified this method performs context-sensitive
460/// analysis and returns true if it is safe to load immediately before ScanFrom.
461///
462/// If it is not obviously safe to load from the specified pointer, we do
463/// a quick local scan of the basic block containing \c ScanFrom, to determine
464/// if the address is already accessed.
465///
466/// This uses the pointee type to determine how many bytes need to be safe to
467/// load from the pointer.
469 const DataLayout &DL,
470 Instruction *ScanFrom,
471 AssumptionCache *AC,
472 const DominatorTree *DT,
473 const TargetLibraryInfo *TLI) {
474 // If DT is not specified we can't make context-sensitive query
475 const Instruction* CtxI = DT ? ScanFrom : nullptr;
476 if (isDereferenceableAndAlignedPointer(V, Alignment, Size, DL, CtxI, AC, DT,
477 TLI)) {
478 // With sanitizers `Dereferenceable` is not always enough for unconditional
479 // load.
480 if (!ScanFrom || !suppressSpeculativeLoadForSanitizers(*ScanFrom))
481 return true;
482 }
483
484 if (!ScanFrom)
485 return false;
486
487 if (Size.getBitWidth() > 64)
488 return false;
489 const TypeSize LoadSize = TypeSize::getFixed(Size.getZExtValue());
490
491 // Otherwise, be a little bit aggressive by scanning the local block where we
492 // want to check to see if the pointer is already being loaded or stored
493 // from/to. If so, the previous load or store would have already trapped,
494 // so there is no harm doing an extra load (also, CSE will later eliminate
495 // the load entirely).
496 BasicBlock::iterator BBI = ScanFrom->getIterator(),
497 E = ScanFrom->getParent()->begin();
498
499 // We can at least always strip pointer casts even though we can't use the
500 // base here.
501 V = V->stripPointerCasts();
502
503 while (BBI != E) {
504 --BBI;
505
506 // If we see a free or a call which may write to memory (i.e. which might do
507 // a free) the pointer could be marked invalid.
508 if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
510 return false;
511
512 Value *AccessedPtr;
513 Type *AccessedTy;
514 Align AccessedAlign;
515 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
516 // Ignore volatile loads. The execution of a volatile load cannot
517 // be used to prove an address is backed by regular memory; it can,
518 // for example, point to an MMIO register.
519 if (LI->isVolatile())
520 continue;
521 AccessedPtr = LI->getPointerOperand();
522 AccessedTy = LI->getType();
523 AccessedAlign = LI->getAlign();
524 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
525 // Ignore volatile stores (see comment for loads).
526 if (SI->isVolatile())
527 continue;
528 AccessedPtr = SI->getPointerOperand();
529 AccessedTy = SI->getValueOperand()->getType();
530 AccessedAlign = SI->getAlign();
531 } else
532 continue;
533
534 if (AccessedAlign < Alignment)
535 continue;
536
537 // Handle trivial cases.
538 if (AccessedPtr == V &&
539 TypeSize::isKnownLE(LoadSize, DL.getTypeStoreSize(AccessedTy)))
540 return true;
541
542 if (AreEquivalentAddressValues(AccessedPtr->stripPointerCasts(), V) &&
543 TypeSize::isKnownLE(LoadSize, DL.getTypeStoreSize(AccessedTy)))
544 return true;
545 }
546 return false;
547}
548
550 const DataLayout &DL,
551 Instruction *ScanFrom,
552 AssumptionCache *AC,
553 const DominatorTree *DT,
554 const TargetLibraryInfo *TLI) {
555 TypeSize TySize = DL.getTypeStoreSize(Ty);
556 if (TySize.isScalable())
557 return false;
558 APInt Size(DL.getIndexTypeSizeInBits(V->getType()), TySize.getFixedValue());
559 return isSafeToLoadUnconditionally(V, Alignment, Size, DL, ScanFrom, AC, DT,
560 TLI);
561}
562
563/// DefMaxInstsToScan - the default number of maximum instructions
564/// to scan in the block, used by FindAvailableLoadedValue().
565/// FindAvailableLoadedValue() was introduced in r60148, to improve jump
566/// threading in part by eliminating partially redundant loads.
567/// At that point, the value of MaxInstsToScan was already set to '6'
568/// without documented explanation.
570llvm::DefMaxInstsToScan("available-load-scan-limit", cl::init(6), cl::Hidden,
571 cl::desc("Use this to specify the default maximum number of instructions "
572 "to scan backward from a given instruction, when searching for "
573 "available loaded value"));
574
576 BasicBlock::iterator &ScanFrom,
577 unsigned MaxInstsToScan,
578 BatchAAResults *AA, bool *IsLoad,
579 unsigned *NumScanedInst) {
580 // Don't CSE load that is volatile or anything stronger than unordered.
581 if (!Load->isUnordered())
582 return nullptr;
583
585 return findAvailablePtrLoadStore(Loc, Load->getType(), Load->isAtomic(),
586 ScanBB, ScanFrom, MaxInstsToScan, AA, IsLoad,
587 NumScanedInst);
588}
589
590// Check if the load and the store have the same base, constant offsets and
591// non-overlapping access ranges.
592static bool areNonOverlapSameBaseLoadAndStore(const Value *LoadPtr,
593 Type *LoadTy,
594 const Value *StorePtr,
595 Type *StoreTy,
596 const DataLayout &DL) {
597 APInt LoadOffset(DL.getIndexTypeSizeInBits(LoadPtr->getType()), 0);
598 APInt StoreOffset(DL.getIndexTypeSizeInBits(StorePtr->getType()), 0);
599 if (LoadOffset.getBitWidth() != StoreOffset.getBitWidth())
600 return false;
601 const Value *LoadBase = LoadPtr->stripAndAccumulateConstantOffsets(
602 DL, LoadOffset, /* AllowNonInbounds */ false);
603 const Value *StoreBase = StorePtr->stripAndAccumulateConstantOffsets(
604 DL, StoreOffset, /* AllowNonInbounds */ false);
605 if (LoadBase != StoreBase)
606 return false;
607 auto LoadAccessSize = LocationSize::precise(DL.getTypeStoreSize(LoadTy));
608 auto StoreAccessSize = LocationSize::precise(DL.getTypeStoreSize(StoreTy));
609 ConstantRange LoadRange(LoadOffset,
610 LoadOffset + LoadAccessSize.toRaw());
611 ConstantRange StoreRange(StoreOffset,
612 StoreOffset + StoreAccessSize.toRaw());
613 return LoadRange.intersectWith(StoreRange).isEmptySet();
614}
615
617 Type *AccessTy, bool AtLeastAtomic,
618 const DataLayout &DL, bool *IsLoadCSE) {
619 // If this is a load of Ptr, the loaded value is available.
620 // (This is true even if the load is volatile or atomic, although
621 // those cases are unlikely.)
622 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
623 // We can value forward from an atomic to a non-atomic, but not the
624 // other way around.
625 if (LI->isAtomic() < AtLeastAtomic)
626 return nullptr;
627
628 Value *LoadPtr = LI->getPointerOperand()->stripPointerCasts();
629 if (!AreEquivalentAddressValues(LoadPtr, Ptr))
630 return nullptr;
631
632 if (CastInst::isBitOrNoopPointerCastable(LI->getType(), AccessTy, DL)) {
633 if (IsLoadCSE)
634 *IsLoadCSE = true;
635 return LI;
636 }
637 }
638
639 // If this is a store through Ptr, the value is available!
640 // (This is true even if the store is volatile or atomic, although
641 // those cases are unlikely.)
642 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
643 // We can value forward from an atomic to a non-atomic, but not the
644 // other way around.
645 if (SI->isAtomic() < AtLeastAtomic)
646 return nullptr;
647
648 Value *StorePtr = SI->getPointerOperand()->stripPointerCasts();
649 if (!AreEquivalentAddressValues(StorePtr, Ptr))
650 return nullptr;
651
652 if (IsLoadCSE)
653 *IsLoadCSE = false;
654
655 Value *Val = SI->getValueOperand();
656 if (CastInst::isBitOrNoopPointerCastable(Val->getType(), AccessTy, DL))
657 return Val;
658
659 TypeSize StoreSize = DL.getTypeSizeInBits(Val->getType());
660 TypeSize LoadSize = DL.getTypeSizeInBits(AccessTy);
661 if (TypeSize::isKnownLE(LoadSize, StoreSize))
662 if (auto *C = dyn_cast<Constant>(Val))
663 return ConstantFoldLoadFromConst(C, AccessTy, DL);
664 }
665
666 if (auto *MSI = dyn_cast<MemSetInst>(Inst)) {
667 // Don't forward from (non-atomic) memset to atomic load.
668 if (AtLeastAtomic)
669 return nullptr;
670
671 // Only handle constant memsets.
672 auto *Val = dyn_cast<ConstantInt>(MSI->getValue());
673 auto *Len = dyn_cast<ConstantInt>(MSI->getLength());
674 if (!Val || !Len)
675 return nullptr;
676
677 // Handle offsets.
678 int64_t StoreOffset = 0, LoadOffset = 0;
679 const Value *StoreBase =
680 GetPointerBaseWithConstantOffset(MSI->getDest(), StoreOffset, DL);
681 const Value *LoadBase =
682 GetPointerBaseWithConstantOffset(Ptr, LoadOffset, DL);
683 if (StoreBase != LoadBase || LoadOffset < StoreOffset)
684 return nullptr;
685
686 if (IsLoadCSE)
687 *IsLoadCSE = false;
688
689 TypeSize LoadTypeSize = DL.getTypeSizeInBits(AccessTy);
690 if (LoadTypeSize.isScalable())
691 return nullptr;
692
693 // Make sure the read bytes are contained in the memset.
694 uint64_t LoadSize = LoadTypeSize.getFixedValue();
695 if ((Len->getValue() * 8).ult(LoadSize + (LoadOffset - StoreOffset) * 8))
696 return nullptr;
697
698 APInt Splat = LoadSize >= 8 ? APInt::getSplat(LoadSize, Val->getValue())
699 : Val->getValue().trunc(LoadSize);
700 ConstantInt *SplatC = ConstantInt::get(MSI->getContext(), Splat);
701 if (CastInst::isBitOrNoopPointerCastable(SplatC->getType(), AccessTy, DL))
702 return SplatC;
703
704 return nullptr;
705 }
706
707 return nullptr;
708}
709
711 const MemoryLocation &Loc, Type *AccessTy, bool AtLeastAtomic,
712 BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan,
713 BatchAAResults *AA, bool *IsLoadCSE, unsigned *NumScanedInst) {
714 if (MaxInstsToScan == 0)
715 MaxInstsToScan = ~0U;
716
717 const DataLayout &DL = ScanBB->getDataLayout();
718 const Value *StrippedPtr = Loc.Ptr->stripPointerCasts();
719
720 while (ScanFrom != ScanBB->begin()) {
721 // We must ignore debug info directives when counting (otherwise they
722 // would affect codegen).
723 Instruction *Inst = &*--ScanFrom;
724 if (Inst->isDebugOrPseudoInst())
725 continue;
726
727 // Restore ScanFrom to expected value in case next test succeeds
728 ScanFrom++;
729
730 if (NumScanedInst)
731 ++(*NumScanedInst);
732
733 // Don't scan huge blocks.
734 if (MaxInstsToScan-- == 0)
735 return nullptr;
736
737 --ScanFrom;
738
739 if (Value *Available = getAvailableLoadStore(Inst, StrippedPtr, AccessTy,
740 AtLeastAtomic, DL, IsLoadCSE))
741 return Available;
742
743 // Try to get the store size for the type.
744 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
745 Value *StorePtr = SI->getPointerOperand()->stripPointerCasts();
746
747 // If both StrippedPtr and StorePtr reach all the way to an alloca or
748 // global and they are different, ignore the store. This is a trivial form
749 // of alias analysis that is important for reg2mem'd code.
750 if ((isa<AllocaInst>(StrippedPtr) || isa<GlobalVariable>(StrippedPtr)) &&
751 (isa<AllocaInst>(StorePtr) || isa<GlobalVariable>(StorePtr)) &&
752 StrippedPtr != StorePtr)
753 continue;
754
755 if (!AA) {
756 // When AA isn't available, but if the load and the store have the same
757 // base, constant offsets and non-overlapping access ranges, ignore the
758 // store. This is a simple form of alias analysis that is used by the
759 // inliner. FIXME: use BasicAA if possible.
761 Loc.Ptr, AccessTy, SI->getPointerOperand(),
762 SI->getValueOperand()->getType(), DL))
763 continue;
764 } else {
765 // If we have alias analysis and it says the store won't modify the
766 // loaded value, ignore the store.
767 if (!isModSet(AA->getModRefInfo(SI, Loc)))
768 continue;
769 }
770
771 // Otherwise the store that may or may not alias the pointer, bail out.
772 ++ScanFrom;
773 return nullptr;
774 }
775
776 // If this is some other instruction that may clobber Ptr, bail out.
777 if (Inst->mayWriteToMemory()) {
778 // If alias analysis claims that it really won't modify the load,
779 // ignore it.
780 if (AA && !isModSet(AA->getModRefInfo(Inst, Loc)))
781 continue;
782
783 // May modify the pointer, bail out.
784 ++ScanFrom;
785 return nullptr;
786 }
787 }
788
789 // Got to the start of the block, we didn't find it, but are done for this
790 // block.
791 return nullptr;
792}
793
795 bool *IsLoadCSE,
796 unsigned MaxInstsToScan) {
797 const DataLayout &DL = Load->getDataLayout();
798 Value *StrippedPtr = Load->getPointerOperand()->stripPointerCasts();
799 BasicBlock *ScanBB = Load->getParent();
800 Type *AccessTy = Load->getType();
801 bool AtLeastAtomic = Load->isAtomic();
802
803 if (!Load->isUnordered())
804 return nullptr;
805
806 // Try to find an available value first, and delay expensive alias analysis
807 // queries until later.
808 Value *Available = nullptr;
809 SmallVector<Instruction *> MustNotAliasInsts;
810 for (Instruction &Inst : make_range(++Load->getReverseIterator(),
811 ScanBB->rend())) {
812 if (Inst.isDebugOrPseudoInst())
813 continue;
814
815 if (MaxInstsToScan-- == 0)
816 return nullptr;
817
818 Available = getAvailableLoadStore(&Inst, StrippedPtr, AccessTy,
819 AtLeastAtomic, DL, IsLoadCSE);
820 if (Available)
821 break;
822
823 if (Inst.mayWriteToMemory())
824 MustNotAliasInsts.push_back(&Inst);
825 }
826
827 // If we found an available value, ensure that the instructions in between
828 // did not modify the memory location.
829 if (Available) {
831 for (Instruction *Inst : MustNotAliasInsts)
832 if (isModSet(AA.getModRefInfo(Inst, Loc)))
833 return nullptr;
834 }
835
836 return Available;
837}
838
839// Returns true if a use is either in an ICmp/PtrToInt or a Phi/Select that only
840// feeds into them.
841static bool isPointerUseReplacable(const Use &U, bool HasNonAddressBits) {
842 unsigned Limit = 40;
843 SmallVector<const User *> Worklist({U.getUser()});
845
846 while (!Worklist.empty() && --Limit) {
847 auto *User = Worklist.pop_back_val();
848 if (!Visited.insert(User).second)
849 continue;
851 continue;
852 // FIXME: The PtrToIntInst case here is not strictly correct, as it
853 // changes which provenance is exposed.
854 if (!HasNonAddressBits && isa<PtrToIntInst>(User))
855 continue;
857 Worklist.append(User->user_begin(), User->user_end());
858 else
859 return false;
860 }
861
862 return Limit != 0;
863}
864
865static bool isPointerAlwaysReplaceable(const Value *From, const Value *To,
866 const DataLayout &DL) {
867 // This is not strictly correct, but we do it for now to retain important
868 // optimizations.
870 return true;
871 // Conversely, replacing null in the default address space with destination
872 // pointer is always valid.
873 if (isa<ConstantPointerNull>(From) &&
874 From->getType()->getPointerAddressSpace() == 0)
875 return true;
876 if (isa<Constant>(To) && To->getType()->isPointerTy() &&
878 return true;
879 return getUnderlyingObjectAggressive(From) ==
881}
882
884 const DataLayout &DL) {
885 Type *Ty = To->getType();
886 assert(U->getType() == Ty && "values must have matching types");
887 // Not a pointer, just return true.
888 if (!Ty->isPtrOrPtrVectorTy())
889 return true;
890
891 // Do not perform replacements in lifetime intrinsic arguments.
892 if (isa<LifetimeIntrinsic>(U.getUser()))
893 return false;
894
895 if (isPointerAlwaysReplaceable(&*U, To, DL))
896 return true;
897
898 bool HasNonAddressBits =
899 DL.getAddressSizeInBits(Ty) != DL.getPointerTypeSizeInBits(Ty);
900 return isPointerUseReplacable(U, HasNonAddressBits);
901}
902
903bool llvm::canReplacePointersIfEqual(const Value *From, const Value *To,
904 const DataLayout &DL) {
905 assert(From->getType() == To->getType() && "values must have matching types");
906 // Not a pointer, just return true.
907 if (!From->getType()->isPtrOrPtrVectorTy())
908 return true;
909
910 return isPointerAlwaysReplaceable(From, To, DL);
911}
912
915 SmallVectorImpl<LoadInst *> &NonDereferenceableAndAlignedLoads,
917 for (BasicBlock *BB : L->blocks()) {
918 for (Instruction &I : *BB) {
919 if (auto *LI = dyn_cast<LoadInst>(&I)) {
920 if (!isDereferenceableAndAlignedInLoop(LI, L, *SE, *DT, AC, Predicates))
921 NonDereferenceableAndAlignedLoads.push_back(LI);
922 } else if (I.mayReadFromMemory() || I.mayWriteToMemory() ||
923 I.mayThrow()) {
924 return false;
925 }
926 }
927 }
928 return true;
929}
930
932 Value *Ptr) {
933 assert(Ptr->getType()->isPointerTy() && "Must be called with pointer arg");
934
935 unsigned BitWidth = DL.getIndexTypeSizeInBits(Ptr->getType());
936 LinearExpression Expr(Ptr, BitWidth);
937
938 while (true) {
939 auto *GEP = dyn_cast<GEPOperator>(Expr.BasePtr);
940 if (!GEP || GEP->getSourceElementType()->isScalableTy())
941 return Expr;
942
943 Value *VarIndex = nullptr;
944 for (Value *Index : GEP->indices()) {
945 if (isa<ConstantInt>(Index))
946 continue;
947 // Only allow a single variable index. We do not bother to handle the
948 // case of the same variable index appearing multiple times.
949 if (Expr.Index || VarIndex)
950 return Expr;
951 VarIndex = Index;
952 }
953
954 // Don't return non-canonical indexes.
955 if (VarIndex && !VarIndex->getType()->isIntegerTy(BitWidth))
956 return Expr;
957
958 // We have verified that we can fully handle this GEP, so we can update Expr
959 // members past this point.
960 Expr.BasePtr = GEP->getPointerOperand();
961 Expr.Flags = Expr.Flags.intersectForOffsetAdd(GEP->getNoWrapFlags());
963 GTI != GTE; ++GTI) {
964 Value *Index = GTI.getOperand();
965 if (auto *ConstOffset = dyn_cast<ConstantInt>(Index)) {
966 if (ConstOffset->isZero())
967 continue;
968 if (StructType *STy = GTI.getStructTypeOrNull()) {
969 unsigned ElementIdx = ConstOffset->getZExtValue();
970 const StructLayout *SL = DL.getStructLayout(STy);
971 Expr.Offset += SL->getElementOffset(ElementIdx);
972 continue;
973 }
974 // Truncate if type size exceeds index space.
975 APInt IndexedSize(BitWidth, GTI.getSequentialElementStride(DL),
976 /*isSigned=*/false,
977 /*implcitTrunc=*/true);
978 Expr.Offset += ConstOffset->getValue() * IndexedSize;
979 continue;
980 }
981
982 // FIXME: Also look through a mul/shl in the index.
983 assert(Expr.Index == nullptr && "Shouldn't have index yet");
984 Expr.Index = Index;
985 // Truncate if type size exceeds index space.
986 Expr.Scale = APInt(BitWidth, GTI.getSequentialElementStride(DL),
987 /*isSigned=*/false, /*implicitTrunc=*/true);
988 }
989 }
990
991 return Expr;
992}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
@ Available
We know the block is fully available. This is a fixpoint.
Definition GVN.cpp:949
Hexagon Common GEP
static bool AreEquivalentAddressValues(const Value *A, const Value *B)
Test if A and B will obviously have the same value.
Definition Loads.cpp:292
static bool isPointerAlwaysReplaceable(const Value *From, const Value *To, const DataLayout &DL)
Definition Loads.cpp:865
static bool isPointerUseReplacable(const Use &U, bool HasNonAddressBits)
Definition Loads.cpp:841
static bool areNonOverlapSameBaseLoadAndStore(const Value *LoadPtr, Type *LoadTy, const Value *StorePtr, Type *StoreTy, const DataLayout &DL)
Definition Loads.cpp:592
static bool isDereferenceableAndAlignedPointerViaAssumption(const Value *Ptr, Align Alignment, function_ref< bool(const RetainedKnowledge &RK)> CheckSize, const DataLayout &DL, const Instruction *CtxI, AssumptionCache *AC, const DominatorTree *DT)
Definition Loads.cpp:35
static Value * getAvailableLoadStore(Instruction *Inst, const Value *Ptr, Type *AccessTy, bool AtLeastAtomic, const DataLayout &DL, bool *IsLoadCSE)
Definition Loads.cpp:616
static bool suppressSpeculativeLoadForSanitizers(const Instruction &CtxI)
Definition Loads.cpp:444
#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.
uint64_t IntrinsicInst * II
Class for arbitrary precision integers.
Definition APInt.h:78
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1189
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1709
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1511
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1987
static LLVM_ABI APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition APInt.cpp:652
bool getBoolValue() const
Convert APInt to a boolean value.
Definition APInt.h:472
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1228
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:461
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
reverse_iterator rend()
Definition BasicBlock.h:479
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
static LLVM_ABI bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op.
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
This is the shared class of boolean and integer constants.
Definition Constants.h:87
This class represents a range of values.
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:155
Represents calls to the gc.relocate intrinsic.
GEPNoWrapFlags intersectForOffsetAdd(GEPNoWrapFlags Other) const
Given (gep (gep p, x), y), determine the nowrap flags for (gep p, x+y).
LLVM_ABI bool isDebugOrPseudoInst() const LLVM_READONLY
Return true if the instruction is a DbgInfoIntrinsic or PseudoProbeInst.
LLVM_ABI bool mayWriteToMemory() const LLVM_READONLY
Return true if this instruction may modify memory.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
An instruction for reading from memory.
Value * getPointerOperand()
bool isUnordered() const
Align getAlign() const
Return the alignment of the access that is being performed.
static LocationSize precise(uint64_t Value)
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
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.
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
This class represents an analyzed expression in the program.
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.
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getPredicatedBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getBackedgeTakenCount, except it will add a set of SCEV predicates to Predicates that are ...
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.
APInt getUnsignedRangeMax(const SCEV *S)
Determine the max of the unsigned range for a particular SCEV.
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 * getPredicatedSymbolicMaxBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getSymbolicMaxBackedgeTakenCount, except it will add a set of SCEV predicates to Predicate...
const SCEV * getSymbolicMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEV that is greater than or equal to (i.e.
This class represents the LLVM 'select' instruction.
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.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
iterator insert(iterator I, T &&Elt)
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.
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:743
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
Class to represent struct types.
Provides information about what library functions are available for the current target.
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:343
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
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.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:285
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
user_iterator user_begin()
Definition Value.h:402
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:972
LLVM_ABI bool canBeFreed() const
Return true if the memory object referred to by V can by freed in the scope for which the SSA value d...
Definition Value.cpp:827
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 const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:712
user_iterator user_end()
Definition Value.h:410
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:230
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
CallInst * Call
Abstract Attribute helper functions.
Definition Attributor.h:165
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
initializer< Ty > init(const Ty &Val)
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...
LLVM_ABI bool willNotFreeBetween(const Instruction *Assume, const Instruction *CtxI)
Returns true, if no instruction between Assume and CtxI may free (including through synchronization).
@ Offset
Definition DWP.cpp:558
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,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool isAligned(Align Lhs, uint64_t SizeInBytes)
Checks that SizeInBytes is a multiple of the alignment.
Definition Alignment.h:134
LLVM_ABI bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, Align Alignment, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested.
Definition Loads.cpp:251
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL, bool AllowNonInbounds=true)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset.
LLVM_ABI Value * findAvailablePtrLoadStore(const MemoryLocation &Loc, Type *AccessTy, bool AtLeastAtomic, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan, BatchAAResults *AA, bool *IsLoadCSE, unsigned *NumScanedInst)
Scan backwards to see if we have the value of the given pointer available locally within a small numb...
Definition Loads.cpp:710
LLVM_ABI bool mustSuppressSpeculation(const LoadInst &LI)
Return true if speculation of the given load must be suppressed to avoid ordering or interfering with...
Definition Loads.cpp:453
gep_type_iterator gep_type_end(const User *GEP)
LLVM_ABI Value * FindAvailableLoadedValue(LoadInst *Load, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan=DefMaxInstsToScan, BatchAAResults *AA=nullptr, bool *IsLoadCSE=nullptr, unsigned *NumScanedInst=nullptr)
Scan backwards to see if we have the value of the given load available locally within a small number ...
Definition Loads.cpp:575
LLVM_ABI const Value * getArgumentAliasingToReturnedPointer(const CallBase *Call, bool MustPreserveOffset)
This function returns call pointer argument that is considered the same by aliasing rules.
LLVM_ABI bool getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL, const TargetLibraryInfo *TLI, ObjectSizeOpts Opts={})
Compute the size of the object pointed by Ptr.
LLVM_ABI bool canReplacePointersInUseIfEqual(const Use &U, const Value *To, const DataLayout &DL)
Definition Loads.cpp:883
LLVM_ABI bool canReplacePointersIfEqual(const Value *From, const Value *To, const DataLayout &DL)
Returns true if a pointer value From can be replaced with another pointer value \To if they are deeme...
Definition Loads.cpp:903
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
LLVM_ABI LinearExpression decomposeLinearExpression(const DataLayout &DL, Value *Ptr)
Decompose a pointer into a linear expression.
Definition Loads.cpp:931
LLVM_ABI bool isSafeToLoadUnconditionally(Value *V, Align Alignment, const APInt &Size, const DataLayout &DL, Instruction *ScanFrom, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Return true if we know that executing a load from this value cannot trap.
Definition Loads.cpp:468
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI Constant * ConstantFoldLoadFromConst(Constant *C, Type *Ty, const APInt &Offset, const DataLayout &DL)
Extract value of C at the given Offset reinterpreted as Ty.
LLVM_ABI cl::opt< unsigned > DefMaxInstsToScan
The default number of maximum instructions to scan in the block, used by FindAvailableLoadedValue().
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
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
LLVM_ABI const Value * getUnderlyingObjectAggressive(const Value *V)
Like getUnderlyingObject(), but will try harder to find a single underlying object.
constexpr unsigned BitWidth
LLVM_ABI bool isDereferenceablePointer(const Value *V, Type *Ty, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Return true if this is always a dereferenceable pointer.
Definition Loads.cpp:271
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isReadOnlyLoop(Loop *L, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, SmallVectorImpl< LoadInst * > &NonDereferenceableAndAlignedLoads, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Returns true if the loop contains read-only memory accesses and doesn't throw.
Definition Loads.cpp:913
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI bool isDereferenceableAndAlignedInLoop(LoadInst *LI, Loop *L, ScalarEvolution &SE, DominatorTree &DT, AssumptionCache *AC=nullptr, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Return true if we can prove that the given load (which is assumed to be within the specified loop) wo...
Definition Loads.cpp:311
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
Linear expression BasePtr + Index * Scale + Offset.
Definition Loads.h:211
GEPNoWrapFlags Flags
Definition Loads.h:216
Various options to control the behavior of getObjectSize.
bool NullIsUnknownSize
If this is true, null pointers in address space 0 will be treated as though they can't be evaluated.
bool RoundToAlign
Whether to round the result up to the alignment of allocas, byval arguments, and global variables.
Represent one information held inside an operand bundle of an llvm.assume.
Attribute::AttrKind AttrKind