LLVM 24.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"
25#include "llvm/IR/IRBuilder.h"
27#include "llvm/IR/Operator.h"
29
30using namespace llvm;
31using namespace llvm::PatternMatch;
32
33static bool isAligned(const Value *Base, Align Alignment,
34 const DataLayout &DL) {
35 return Base->getPointerAlignment(DL) >= Alignment;
36}
37
39 const Value *Ptr, Align Alignment, const SimplifyQuery &SQ, bool IgnoreFree,
40 function_ref<bool(const RetainedKnowledge &RK)> CheckSize) {
41 if (!SQ.CtxI)
42 return false;
43 // Look through assumes to see if both dereferenceability and alignment can
44 // be proven by an assume if needed.
45 bool PtrCanBeFreed = Ptr->canBeFreed() && !IgnoreFree;
46 bool IsAligned = Ptr->getPointerAlignment(SQ.DL) >= Alignment;
47 bool IsDerefable = false;
49 Ptr, {Attribute::Dereferenceable, Attribute::Alignment}, *SQ.AC,
50 [&](RetainedKnowledge RK, Instruction *Assume, auto) {
51 if (!isValidAssumeForContext(Assume, SQ.CtxI, SQ.DT))
52 return false;
53 if (RK.AttrKind == Attribute::Alignment) {
54 IsAligned |= RK.ArgValue >= Alignment.value();
55 } else {
56 assert(RK.AttrKind == Attribute::Dereferenceable);
57 // Dereferenceable information from assumptions is only valid if the
58 // value cannot be freed between the assumption and use.
59 if (!IsDerefable &&
60 (!PtrCanBeFreed || willNotFreeBetween(Assume, SQ.CtxI, SQ.DT)) &&
61 CheckSize(RK))
62 IsDerefable = true;
63 }
64 // Stop looking if we have proven both necessary facts.
65 return IsAligned && IsDerefable;
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 SimplifyQuery &SQ,
73 bool IgnoreFree, SmallPtrSetImpl<const Value *> &Visited,
74 unsigned MaxDepth) {
75 assert(V->getType()->isPointerTy() && "Base must be pointer");
76
77 // Recursion limit.
78 if (MaxDepth-- == 0)
79 return false;
80
81 // Already visited? Bail out, we've likely hit unreachable code.
82 if (!Visited.insert(V).second)
83 return false;
84
85 // Note that it is not safe to speculate into a malloc'd region because
86 // malloc may return null.
87
88 // For GEPs, determine if the indexing lands within the allocated object.
89 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
90 const Value *Base = GEP->getPointerOperand();
91
92 APInt Offset(SQ.DL.getIndexTypeSizeInBits(GEP->getType()), 0);
93 if (!GEP->accumulateConstantOffset(SQ.DL, Offset) || Offset.isNegative() ||
94 !Offset.urem(APInt(Offset.getBitWidth(), Alignment.value()))
95 .isMinValue())
96 return false;
97
98 // If the base pointer is dereferenceable for Offset+Size bytes, then the
99 // GEP (== Base + Offset) is dereferenceable for Size bytes. If the base
100 // pointer is aligned to Align bytes, and the Offset is divisible by Align
101 // then the GEP (== Base + Offset == k_0 * Align + k_1 * Align) is also
102 // aligned to Align bytes.
103
104 // Offset and Size may have different bit widths if we have visited an
105 // addrspacecast, so we can't do arithmetic directly on the APInt values.
107 Base, Alignment, Offset + Size.sextOrTrunc(Offset.getBitWidth()), SQ,
108 IgnoreFree, Visited, MaxDepth);
109 }
110
111 // bitcast instructions are no-ops as far as dereferenceability is concerned.
113 if (BC->getSrcTy()->isPointerTy())
114 return isDereferenceableAndAlignedPointer(BC->getOperand(0), Alignment,
115 Size, SQ, IgnoreFree, Visited,
116 MaxDepth);
117 }
118
119 // Recurse into both hands of select.
120 if (const SelectInst *Sel = dyn_cast<SelectInst>(V)) {
121 return isDereferenceableAndAlignedPointer(Sel->getTrueValue(), Alignment,
122 Size, SQ, IgnoreFree, Visited,
123 MaxDepth) &&
124 isDereferenceableAndAlignedPointer(Sel->getFalseValue(), Alignment,
125 Size, SQ, IgnoreFree, Visited,
126 MaxDepth);
127 }
128
129 auto IsKnownDeref = [&]() {
130 bool CheckForNonNull, CheckForFreed;
131 if (!Size.ule(V->getPointerDereferenceableBytes(SQ.DL, CheckForNonNull,
132 &CheckForFreed)))
133 return false;
134 if (CheckForNonNull && !isKnownNonZero(V, SQ))
135 return false;
136
137 auto *I = dyn_cast<Instruction>(V);
138 if (CheckForFreed && !IgnoreFree) {
139 const Instruction *DefI;
140 if (I) {
141 // We don't want to consider frees by the instruction producing the
142 // pointer, so skip it if we can.
143 if (auto *II = dyn_cast<InvokeInst>(V)) {
144 DefI = &II->getNormalDest()->front();
145 } else if (!I->isTerminator()) {
146 DefI = I->getNextNode();
147 } else {
148 DefI = I;
149 }
150 } else {
151 // For arguments, check frees from the start of the entry block.
152 DefI = &cast<Argument>(V)->getParent()->getEntryBlock().front();
153 }
154
155 if (!SQ.CtxI || !willNotFreeBetween(DefI, SQ.CtxI, SQ.DT))
156 return false;
157 }
158
159 // When using something like !dereferenceable on a load, the
160 // dereferenceability may only be valid on a specific control-flow path.
161 // If the instruction doesn't dominate the context instruction, we're
162 // asking about dereferenceability under the assumption that the
163 // instruction has been speculated to the point of the context instruction,
164 // in which case we don't know if the dereferenceability info still holds.
165 // We don't bother handling allocas here, as they aren't speculatable
166 // anyway.
167 if (I && !isa<AllocaInst>(I))
168 return SQ.CtxI && isValidAssumeForContext(I, SQ.CtxI, SQ.DT);
169 return true;
170 };
171 if (IsKnownDeref()) {
172 // As we recursed through GEPs to get here, we've incrementally checked
173 // that each step advanced by a multiple of the alignment. If our base is
174 // properly aligned, then the original offset accessed must also be.
175 return isAligned(V, Alignment, SQ.DL);
176 }
177
178 /// TODO refactor this function to be able to search independently for
179 /// Dereferencability and Alignment requirements.
180
181
182 if (const auto *Call = dyn_cast<CallBase>(V)) {
184 Call, /*MustPreserveOffset=*/true))
185 return isDereferenceableAndAlignedPointer(RP, Alignment, Size, SQ,
186 IgnoreFree, Visited, MaxDepth);
187
188 // If we have a call we can't recurse through, check to see if this is an
189 // allocation function for which we can establish an minimum object size.
190 // Such a minimum object size is analogous to a deref_or_null attribute in
191 // that we still need to prove the result non-null at point of use.
192 // NOTE: We can only use the object size as a base fact as we a) need to
193 // prove alignment too, and b) don't want the compile time impact of a
194 // separate recursive walk.
195 ObjectSizeOpts Opts;
196 // TODO: It may be okay to round to align, but that would imply that
197 // accessing slightly out of bounds was legal, and we're currently
198 // inconsistent about that. For the moment, be conservative.
199 Opts.RoundToAlign = false;
200 Opts.NullIsUnknownSize = true;
201 uint64_t ObjSize;
202 if (getObjectSize(V, ObjSize, SQ.DL, SQ.TLI, Opts)) {
203 APInt KnownDerefBytes(Size.getBitWidth(), ObjSize);
204 if (KnownDerefBytes.getBoolValue() && KnownDerefBytes.uge(Size) &&
205 isKnownNonZero(V, SQ) && !V->canBeFreed()) {
206 // As we recursed through GEPs to get here, we've incrementally
207 // checked that each step advanced by a multiple of the alignment. If
208 // our base is properly aligned, then the original offset accessed
209 // must also be.
210 return isAligned(V, Alignment, SQ.DL);
211 }
212 }
213 }
214
215 // For gc.relocate, look through relocations
216 if (const GCRelocateInst *RelocateInst = dyn_cast<GCRelocateInst>(V))
217 return isDereferenceableAndAlignedPointer(RelocateInst->getDerivedPtr(),
218 Alignment, Size, SQ, IgnoreFree,
219 Visited, MaxDepth);
220
223 ASC->getOperand(0), Alignment, Size, SQ, IgnoreFree, Visited, MaxDepth);
224
225 return SQ.AC &&
227 V, Alignment, SQ, IgnoreFree, [Size](const RetainedKnowledge &RK) {
228 return RK.ArgValue >= Size.getZExtValue();
229 });
230}
231
233 const APInt &Size,
234 const SimplifyQuery &SQ,
235 bool IgnoreFree) {
236 // Note: At the moment, Size can be zero. This ends up being interpreted as
237 // a query of whether [Base, V] is dereferenceable and V is aligned (since
238 // that's what the implementation happened to do). It's unclear if this is
239 // the desired semantic, but at least SelectionDAG does exercise this case.
240
242 return ::isDereferenceableAndAlignedPointer(V, Alignment, Size, SQ,
243 IgnoreFree, Visited,
244 /*MaxDepth=*/16);
245}
246
248 Align Alignment,
249 const SimplifyQuery &SQ,
250 bool IgnoreFree) {
251 // For unsized types or scalable vectors we don't know exactly how many bytes
252 // are dereferenced, so bail out.
253 if (!Ty->isSized() || Ty->isScalableTy())
254 return false;
255
256 // When dereferenceability information is provided by a dereferenceable
257 // attribute, we know exactly how many bytes are dereferenceable. If we can
258 // determine the exact offset to the attributed variable, we can use that
259 // information here.
260
261 APInt AccessSize(SQ.DL.getPointerTypeSizeInBits(V->getType()),
262 SQ.DL.getTypeStoreSize(Ty));
263 return isDereferenceableAndAlignedPointer(V, Alignment, AccessSize, SQ,
264 IgnoreFree);
265}
266
268 const SimplifyQuery &SQ, bool IgnoreFree) {
269 return isDereferenceableAndAlignedPointer(V, Ty, Align(1), SQ, IgnoreFree);
270}
271
273 const SimplifyQuery &Q, bool IgnoreFree) {
274 return isDereferenceableAndAlignedPointer(V, Align(1), Size, Q, IgnoreFree);
275}
276
277/// Test if A and B will obviously have the same value.
278///
279/// This includes recognizing that %t0 and %t1 will have the same
280/// value in code like this:
281/// \code
282/// %t0 = getelementptr \@a, 0, 3
283/// store i32 0, i32* %t0
284/// %t1 = getelementptr \@a, 0, 3
285/// %t2 = load i32* %t1
286/// \endcode
287///
288static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
289 // Test if the values are trivially equivalent.
290 if (A == B)
291 return true;
292
293 // Test if the values come from identical arithmetic instructions.
294 // Use isIdenticalToWhenDefined instead of isIdenticalTo because
295 // this function is only used when one address use dominates the
296 // other, which means that they'll always either have the same
297 // value or one of them will have an undefined value.
299 if (const Instruction *BI = dyn_cast<Instruction>(B))
300 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
301 return true;
302
303 // Otherwise they may not be equivalent.
304 return false;
305}
306
308 LoadInst *LI, Loop *L, ScalarEvolution &SE, DominatorTree &DT,
310 auto &DL = LI->getDataLayout();
311 Value *Ptr = LI->getPointerOperand();
312 const SCEV *PtrSCEV = SE.getSCEV(Ptr);
313 APInt EltSize(DL.getIndexTypeSizeInBits(Ptr->getType()),
314 DL.getTypeStoreSize(LI->getType()).getFixedValue());
315
316 // If given a uniform (i.e. non-varying) address, see if we can prove the
317 // access is safe within the loop w/o needing predication.
318 if (L->isLoopInvariant(Ptr))
320 Ptr, LI->getAlign(), EltSize,
321 SimplifyQuery(DL, &DT, AC, &*L->getHeader()->getFirstNonPHIIt()));
322
323 const SCEV *EltSizeSCEV = SE.getConstant(EltSize);
324 return isDereferenceableAndAlignedInLoop(PtrSCEV, LI->getAlign(), EltSizeSCEV,
325 L, SE, DT, AC, Predicates);
326}
327
329 const SCEV *PtrSCEV, Align Alignment, const SCEV *EltSizeSCEV, Loop *L,
332 auto *AddRec = dyn_cast<SCEVAddRecExpr>(PtrSCEV);
333
334 // Check to see if we have a repeating access pattern and it's possible
335 // to prove all accesses are well aligned.
336 if (!AddRec || AddRec->getLoop() != L || !AddRec->isAffine())
337 return false;
338
339 auto *Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(SE));
340 if (!Step)
341 return false;
342
343 const APInt &EltSize = cast<SCEVConstant>(EltSizeSCEV)->getAPInt();
344 // For the moment, restrict ourselves to the case where the access size and
345 // step are multiples of the requested alignment and the base is aligned.
346 // TODO: generalize if a case found which warrants
347 if (EltSize.urem(Alignment.value()) != 0 ||
348 Step->getAPInt().urem(Alignment.value()) != 0)
349 return false;
350
351 // TODO: Handle overlapping accesses.
352 if (EltSize.ugt(Step->getAPInt().abs()))
353 return false;
354
355 const SCEV *MaxBECount =
356 Predicates ? SE.getPredicatedSymbolicMaxBackedgeTakenCount(L, *Predicates)
358 const SCEV *BECount = Predicates
359 ? SE.getPredicatedBackedgeTakenCount(L, *Predicates)
360 : SE.getBackedgeTakenCount(L);
361 if (isa<SCEVCouldNotCompute>(MaxBECount))
362 return false;
363 auto LoopGuards = ScalarEvolution::LoopGuards::collectOnDemand(L, SE);
364
365 auto &DL = L->getHeader()->getDataLayout();
366 const auto &[AccessStart, AccessEnd] =
367 getStartAndEndForAccess(L, PtrSCEV, EltSizeSCEV, BECount, MaxBECount, &SE,
368 nullptr, &DT, AC, LoopGuards);
369 if (isa<SCEVCouldNotCompute>(AccessStart) ||
370 isa<SCEVCouldNotCompute>(AccessEnd))
371 return false;
372
373 // Try to get the access size.
374 const SCEV *PtrDiff = SE.getMinusSCEV(AccessEnd, AccessStart);
375 if (isa<SCEVCouldNotCompute>(PtrDiff))
376 return false;
377
378 APInt MaxPtrDiff =
379 SE.getUnsignedRangeMax(SE.applyLoopGuards(PtrDiff, LoopGuards));
380
381 Value *Base = nullptr;
382 APInt AccessSize;
383 const SCEV *AccessSizeSCEV = nullptr;
384 if (const SCEVUnknown *NewBase = dyn_cast<SCEVUnknown>(AccessStart)) {
385 Base = NewBase->getValue();
386 AccessSize = std::move(MaxPtrDiff);
387 AccessSizeSCEV = PtrDiff;
388 } else if (auto *MinAdd = dyn_cast<SCEVAddExpr>(AccessStart)) {
389 if (MinAdd->getNumOperands() != 2)
390 return false;
391
392 const auto *Offset = dyn_cast<SCEVConstant>(MinAdd->getOperand(0));
393 const auto *NewBase = dyn_cast<SCEVUnknown>(MinAdd->getOperand(1));
394 if (!Offset || !NewBase)
395 return false;
396
397 // The following code below assumes the offset is unsigned, but GEP
398 // offsets are treated as signed so we can end up with a signed value
399 // here too. For example, suppose the initial PHI value is (i8 255),
400 // the offset will be treated as (i8 -1) and sign-extended to (i64 -1).
401 if (Offset->getAPInt().isNegative())
402 return false;
403
404 // For the moment, restrict ourselves to the case where the offset is a
405 // multiple of the requested alignment and the base is aligned.
406 // TODO: generalize if a case found which warrants
407 if (Offset->getAPInt().urem(Alignment.value()) != 0)
408 return false;
409
410 bool Overflow = false;
411 AccessSize = MaxPtrDiff.uadd_ov(Offset->getAPInt(), Overflow);
412 if (Overflow)
413 return false;
414 AccessSizeSCEV = SE.getAddExpr(PtrDiff, Offset);
415 Base = NewBase->getValue();
416 } else
417 return false;
418
419 Instruction *CtxI = &*L->getHeader()->getFirstNonPHIIt();
420 if (BasicBlock *LoopPred = L->getLoopPredecessor()) {
421 if (isa<UncondBrInst, CondBrInst>(LoopPred->getTerminator()))
422 CtxI = LoopPred->getTerminator();
423 }
424 SimplifyQuery SQ(DL, &DT, AC, CtxI);
426 Base, Alignment, SQ, /*IgnoreFree=*/false,
427 [&SE, AccessSizeSCEV, &LoopGuards](const RetainedKnowledge &RK) {
428 const SCEV *DerefBytesSCEV = SE.getSCEV(RK.IRArgValue);
429 Type *WiderTy = SE.getWiderType(AccessSizeSCEV->getType(),
430 DerefBytesSCEV->getType());
431 const SCEV *AccessSizeExt =
432 SE.getNoopOrZeroExtend(AccessSizeSCEV, WiderTy);
433 const SCEV *DerefBytesExt =
434 SE.getNoopOrZeroExtend(DerefBytesSCEV, WiderTy);
435 return SE.isKnownPredicate(
437 SE.applyLoopGuards(AccessSizeExt, LoopGuards),
438 SE.applyLoopGuards(DerefBytesExt, LoopGuards));
439 }) ||
440 isDereferenceableAndAlignedPointer(Base, Alignment, AccessSize, SQ);
441}
442
444 const Function &F = *CtxI.getFunction();
445 // Speculative load may create a race that did not exist in the source.
446 return F.hasFnAttribute(Attribute::SanitizeThread) ||
447 F.hasFnAttribute(Attribute::SanitizeConcurrency) ||
448 // Speculative load may load data from dirty regions.
449 F.hasFnAttribute(Attribute::SanitizeAddress) ||
450 F.hasFnAttribute(Attribute::SanitizeHWAddress);
451}
452
456
458 const APInt &Size,
459 const SimplifyQuery &SQ,
460 bool IgnoreFree) {
461 if (isDereferenceableAndAlignedPointer(V, Alignment, Size, SQ, IgnoreFree)) {
462 // With sanitizers `Dereferenceable` is not always enough for unconditional
463 // load.
465 return true;
466 }
467
468 if (!SQ.CtxI)
469 return false;
470
471 if (Size.getBitWidth() > 64)
472 return false;
473 const TypeSize LoadSize = TypeSize::getFixed(Size.getZExtValue());
474
475 // Otherwise, be a little bit aggressive by scanning the local block where we
476 // want to check to see if the pointer is already being loaded or stored
477 // from/to. If so, the previous load or store would have already trapped,
478 // so there is no harm doing an extra load (also, CSE will later eliminate
479 // the load entirely).
480 auto BBI = SQ.CtxI->getIterator(), E = SQ.CtxI->getParent()->begin();
481
482 // We can at least always strip pointer casts even though we can't use the
483 // base here.
484 V = V->stripPointerCasts();
485
486 while (BBI != E) {
487 --BBI;
488
489 // If we see a free or a call which may write to memory (i.e. which might do
490 // a free) the pointer could be marked invalid.
491 if (!IgnoreFree && isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
493 return false;
494
495 const Value *AccessedPtr;
496 Type *AccessedTy;
497 Align AccessedAlign;
498 if (const auto *LI = dyn_cast<LoadInst>(BBI)) {
499 // Ignore volatile loads. The execution of a volatile load cannot
500 // be used to prove an address is backed by regular memory; it can,
501 // for example, point to an MMIO register.
502 if (LI->isVolatile())
503 continue;
504 AccessedPtr = LI->getPointerOperand();
505 AccessedTy = LI->getType();
506 AccessedAlign = LI->getAlign();
507 } else if (const auto *SI = dyn_cast<StoreInst>(BBI)) {
508 // Ignore volatile stores (see comment for loads).
509 if (SI->isVolatile())
510 continue;
511 AccessedPtr = SI->getPointerOperand();
512 AccessedTy = SI->getValueOperand()->getType();
513 AccessedAlign = SI->getAlign();
514 } else
515 continue;
516
517 if (AccessedAlign < Alignment)
518 continue;
519
520 // Handle trivial cases.
521 if (AccessedPtr == V &&
522 TypeSize::isKnownLE(LoadSize, SQ.DL.getTypeStoreSize(AccessedTy)))
523 return true;
524
525 if (AreEquivalentAddressValues(AccessedPtr->stripPointerCasts(), V) &&
526 TypeSize::isKnownLE(LoadSize, SQ.DL.getTypeStoreSize(AccessedTy)))
527 return true;
528 }
529 return false;
530}
531
533 const SimplifyQuery &SQ,
534 bool IgnoreFree) {
535 TypeSize TySize = SQ.DL.getTypeStoreSize(Ty);
536 if (TySize.isScalable())
537 return false;
538 APInt Size(SQ.DL.getIndexTypeSizeInBits(V->getType()),
539 TySize.getFixedValue());
540 return isSafeToLoadUnconditionally(V, Alignment, Size, SQ, IgnoreFree);
541}
542
543/// DefMaxInstsToScan - the default number of maximum instructions
544/// to scan in the block, used by FindAvailableLoadedValue().
545/// FindAvailableLoadedValue() was introduced in r60148, to improve jump
546/// threading in part by eliminating partially redundant loads.
547/// At that point, the value of MaxInstsToScan was already set to '6'
548/// without documented explanation.
550llvm::DefMaxInstsToScan("available-load-scan-limit", cl::init(6), cl::Hidden,
551 cl::desc("Use this to specify the default maximum number of instructions "
552 "to scan backward from a given instruction, when searching for "
553 "available loaded value"));
554
556 BasicBlock::iterator &ScanFrom,
557 unsigned MaxInstsToScan,
558 BatchAAResults *AA, bool *IsLoad,
559 unsigned *NumScanedInst) {
560 // Don't CSE load that is volatile or anything stronger than unordered.
561 if (!Load->isUnordered())
562 return nullptr;
563
565 return findAvailablePtrLoadStore(Loc, Load->getType(), Load->getProperties(),
566 ScanBB, ScanFrom, MaxInstsToScan, AA, IsLoad,
567 NumScanedInst);
568}
569
570// Check if the load and the store have the same base, constant offsets and
571// non-overlapping access ranges.
572static bool areNonOverlapSameBaseLoadAndStore(const Value *LoadPtr,
573 Type *LoadTy,
574 const Value *StorePtr,
575 Type *StoreTy,
576 const DataLayout &DL) {
577 APInt LoadOffset(DL.getIndexTypeSizeInBits(LoadPtr->getType()), 0);
578 APInt StoreOffset(DL.getIndexTypeSizeInBits(StorePtr->getType()), 0);
579 if (LoadOffset.getBitWidth() != StoreOffset.getBitWidth())
580 return false;
581 const Value *LoadBase = LoadPtr->stripAndAccumulateConstantOffsets(
582 DL, LoadOffset, /* AllowNonInbounds */ false);
583 const Value *StoreBase = StorePtr->stripAndAccumulateConstantOffsets(
584 DL, StoreOffset, /* AllowNonInbounds */ false);
585 if (LoadBase != StoreBase)
586 return false;
587 auto LoadAccessSize = LocationSize::precise(DL.getTypeStoreSize(LoadTy));
588 auto StoreAccessSize = LocationSize::precise(DL.getTypeStoreSize(StoreTy));
589 ConstantRange LoadRange(LoadOffset,
590 LoadOffset + LoadAccessSize.toRaw());
591 ConstantRange StoreRange(StoreOffset,
592 StoreOffset + StoreAccessSize.toRaw());
593 return LoadRange.intersectWith(StoreRange).isEmptySet();
594}
595
596// For elementwise atomics, each vector element is a separate atomic access.
597// Reusing an operation with a different access size would change atomicity.
599 Type *AccessTy, const LoadStoreInstProperties &AccessProps,
600 Type *OtherAccessTy, const LoadStoreInstProperties &OtherProps,
601 const DataLayout &DL) {
602 if (AccessProps.Ordering == AtomicOrdering::NotAtomic)
603 return true;
604
605 Type *AtomicAccessTy =
606 AccessProps.IsElementwise ? AccessTy->getScalarType() : AccessTy;
607 Type *OtherAtomicAccessTy =
608 OtherProps.IsElementwise ? OtherAccessTy->getScalarType() : OtherAccessTy;
609 return DL.getTypeStoreSize(AtomicAccessTy) ==
610 DL.getTypeStoreSize(OtherAtomicAccessTy);
611}
612
614 Type *AccessTy,
615 const LoadStoreInstProperties &AccessProps,
616 const DataLayout &DL, bool *IsLoadCSE) {
617 const bool AtLeastAtomic = AccessProps.Ordering != AtomicOrdering::NotAtomic;
618
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 (hasCompatibleAtomicAccessSize(AccessTy, AccessProps, LI->getType(),
633 LI->getProperties(), DL) &&
634 CastInst::isBitOrNoopPointerCastable(LI->getType(), AccessTy, DL)) {
635 if (IsLoadCSE)
636 *IsLoadCSE = true;
637 return LI;
638 }
639 }
640
641 // If this is a store through Ptr, the value is available!
642 // (This is true even if the store is volatile or atomic, although
643 // those cases are unlikely.)
644 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
645 // We can value forward from an atomic to a non-atomic, but not the
646 // other way around.
647 if (SI->isAtomic() < AtLeastAtomic)
648 return nullptr;
649
650 Value *StorePtr = SI->getPointerOperand()->stripPointerCasts();
651 if (!AreEquivalentAddressValues(StorePtr, Ptr))
652 return nullptr;
653
654 if (IsLoadCSE)
655 *IsLoadCSE = false;
656
657 Value *Val = SI->getValueOperand();
658 if (!hasCompatibleAtomicAccessSize(AccessTy, AccessProps, Val->getType(),
659 SI->getProperties(), DL))
660 return nullptr;
661
662 if (CastInst::isBitOrNoopPointerCastable(Val->getType(), AccessTy, DL))
663 return Val;
664
665 TypeSize StoreSize = DL.getTypeSizeInBits(Val->getType());
666 TypeSize LoadSize = DL.getTypeSizeInBits(AccessTy);
667 if (TypeSize::isKnownLE(LoadSize, StoreSize))
668 if (auto *C = dyn_cast<Constant>(Val))
669 return ConstantFoldLoadFromConst(C, AccessTy, DL);
670 }
671
672 if (auto *MSI = dyn_cast<MemSetInst>(Inst)) {
673 // Don't forward from (non-atomic) memset to atomic load.
674 if (AtLeastAtomic)
675 return nullptr;
676
677 // Only handle constant memsets.
678 auto *Val = dyn_cast<ConstantInt>(MSI->getValue());
679 auto *Len = dyn_cast<ConstantInt>(MSI->getLength());
680 if (!Val || !Len)
681 return nullptr;
682
683 // Handle offsets.
684 int64_t StoreOffset = 0, LoadOffset = 0;
685 const Value *StoreBase =
686 GetPointerBaseWithConstantOffset(MSI->getDest(), StoreOffset, DL);
687 const Value *LoadBase =
688 GetPointerBaseWithConstantOffset(Ptr, LoadOffset, DL);
689 if (StoreBase != LoadBase || LoadOffset < StoreOffset)
690 return nullptr;
691
692 if (IsLoadCSE)
693 *IsLoadCSE = false;
694
695 TypeSize LoadTypeSize = DL.getTypeSizeInBits(AccessTy);
696 if (LoadTypeSize.isScalable())
697 return nullptr;
698
699 // Make sure the read bytes are contained in the memset.
700 uint64_t LoadSize = LoadTypeSize.getFixedValue();
701 if ((Len->getValue() * 8).ult(LoadSize + (LoadOffset - StoreOffset) * 8))
702 return nullptr;
703
704 APInt Splat = LoadSize >= 8 ? APInt::getSplat(LoadSize, Val->getValue())
705 : Val->getValue().trunc(LoadSize);
706 ConstantInt *SplatC = ConstantInt::get(MSI->getContext(), Splat);
707 if (CastInst::isBitOrNoopPointerCastable(SplatC->getType(), AccessTy, DL))
708 return SplatC;
709
710 return nullptr;
711 }
712
713 return nullptr;
714}
715
717 const MemoryLocation &Loc, Type *AccessTy,
718 const LoadStoreInstProperties &AccessProps, BasicBlock *ScanBB,
719 BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan, BatchAAResults *AA,
720 bool *IsLoadCSE, unsigned *NumScanedInst) {
721 if (MaxInstsToScan == 0)
722 MaxInstsToScan = ~0U;
723
724 const DataLayout &DL = ScanBB->getDataLayout();
725 const Value *StrippedPtr = Loc.Ptr->stripPointerCasts();
726
727 while (ScanFrom != ScanBB->begin()) {
728 // We must ignore pseudo probes when counting (otherwise they
729 // would affect codegen).
730 Instruction *Inst = &*--ScanFrom;
731 if (isa<PseudoProbeInst>(Inst))
732 continue;
733
734 // Restore ScanFrom to expected value in case next test succeeds
735 ScanFrom++;
736
737 if (NumScanedInst)
738 ++(*NumScanedInst);
739
740 // Don't scan huge blocks.
741 if (MaxInstsToScan-- == 0)
742 return nullptr;
743
744 --ScanFrom;
745
746 if (Value *Available = getAvailableLoadStore(Inst, StrippedPtr, AccessTy,
747 AccessProps, DL, IsLoadCSE))
748 return Available;
749
750 // Try to get the store size for the type.
751 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
752 Value *StorePtr = SI->getPointerOperand()->stripPointerCasts();
753
754 // If both StrippedPtr and StorePtr reach all the way to an alloca or
755 // global and they are different, ignore the store. This is a trivial form
756 // of alias analysis that is important for reg2mem'd code.
757 if ((isa<AllocaInst>(StrippedPtr) || isa<GlobalVariable>(StrippedPtr)) &&
758 (isa<AllocaInst>(StorePtr) || isa<GlobalVariable>(StorePtr)) &&
759 StrippedPtr != StorePtr)
760 continue;
761
762 if (!AA) {
763 // When AA isn't available, but if the load and the store have the same
764 // base, constant offsets and non-overlapping access ranges, ignore the
765 // store. This is a simple form of alias analysis that is used by the
766 // inliner. FIXME: use BasicAA if possible.
768 Loc.Ptr, AccessTy, SI->getPointerOperand(),
769 SI->getValueOperand()->getType(), DL))
770 continue;
771 } else {
772 // If we have alias analysis and it says the store won't modify the
773 // loaded value, ignore the store.
774 if (!isModSet(AA->getModRefInfo(SI, Loc)))
775 continue;
776 }
777
778 // Otherwise the store that may or may not alias the pointer, bail out.
779 ++ScanFrom;
780 return nullptr;
781 }
782
783 // If this is some other instruction that may clobber Ptr, bail out.
784 if (Inst->mayWriteToMemory()) {
785 // If alias analysis claims that it really won't modify the load,
786 // ignore it.
787 if (AA && !isModSet(AA->getModRefInfo(Inst, Loc)))
788 continue;
789
790 // May modify the pointer, bail out.
791 ++ScanFrom;
792 return nullptr;
793 }
794 }
795
796 // Got to the start of the block, we didn't find it, but are done for this
797 // block.
798 return nullptr;
799}
800
802 bool *IsLoadCSE,
803 unsigned MaxInstsToScan) {
804 const DataLayout &DL = Load->getDataLayout();
805 Value *StrippedPtr = Load->getPointerOperand()->stripPointerCasts();
806 BasicBlock *ScanBB = Load->getParent();
807 Type *AccessTy = Load->getType();
808 LoadStoreInstProperties AccessProps = Load->getProperties();
809
810 if (!Load->isUnordered())
811 return nullptr;
812
813 // Try to find an available value first, and delay expensive alias analysis
814 // queries until later.
815 Value *Available = nullptr;
816 SmallVector<Instruction *> MustNotAliasInsts;
817 for (Instruction &Inst : make_range(++Load->getReverseIterator(),
818 ScanBB->rend())) {
819 if (isa<PseudoProbeInst>(Inst))
820 continue;
821
822 if (MaxInstsToScan-- == 0)
823 return nullptr;
824
825 Available = getAvailableLoadStore(&Inst, StrippedPtr, AccessTy, AccessProps,
826 DL, IsLoadCSE);
827 if (Available)
828 break;
829
830 if (Inst.mayWriteToMemory())
831 MustNotAliasInsts.push_back(&Inst);
832 }
833
834 // If we found an available value, ensure that the instructions in between
835 // did not modify the memory location.
836 if (Available) {
838 for (Instruction *Inst : MustNotAliasInsts)
839 if (isModSet(AA.getModRefInfo(Inst, Loc)))
840 return nullptr;
841 }
842
843 return Available;
844}
845
847 const MemoryLocation &MemLoc,
848 Align MemLocAlign,
850 unsigned ScanLimit) {
851 // Ensure no partial overlap is possible, and that the stored value is the
852 // current content of MemLoc.
853 if (!MemLoc.Size.hasValue() || MemLoc.Size.isScalable())
854 return false;
855 if (MemoryLocation::get(SI).Size != MemLoc.Size)
856 return false;
857 if (std::min(MemLocAlign, SI->getAlign()).value() <
858 MemLoc.Size.getValue().getFixedValue())
859 return false;
860
861 auto *LI = dyn_cast<LoadInst>(SI->getValueOperand());
862 if (!LI || LI->getParent() != SI->getParent())
863 return false;
864 if (AA.alias(MemoryLocation::get(LI), MemLoc) != AliasResult::MustAlias)
865 return false;
866
867 // No memory operation in between may modify MemLoc.
868 unsigned NumVisited = 0;
869 for (const Instruction *I = LI; I != SI; I = I->getNextNode())
870 if (++NumVisited > ScanLimit || isModSet(AA.getModRefInfo(I, MemLoc)))
871 return false;
872
873 return true;
874}
875
876// Returns true if a use is either in an ICmp/PtrToInt or a Phi/Select that only
877// feeds into them.
878static bool isPointerUseReplaceable(const Use &U, bool HasNonAddressBits) {
879 unsigned Limit = 40;
880 SmallVector<const User *> Worklist({U.getUser()});
882
883 while (!Worklist.empty() && --Limit) {
884 auto *User = Worklist.pop_back_val();
885 if (!Visited.insert(User).second)
886 continue;
888 continue;
889 // FIXME: The PtrToIntInst case here is not strictly correct, as it
890 // changes which provenance is exposed.
891 if (!HasNonAddressBits && isa<PtrToIntInst>(User))
892 continue;
894 Worklist.append(User->user_begin(), User->user_end());
895 else
896 return false;
897 }
898
899 return Limit != 0;
900}
901
902static bool isPointerAlwaysReplaceable(const Value *From, const Value *To,
903 const DataLayout &DL) {
904 // This is not strictly correct, but we do it for now to retain important
905 // optimizations.
907 return true;
908 // Conversely, replacing null in the default address space with destination
909 // pointer is always valid.
910 if (isa<ConstantPointerNull>(From) &&
911 From->getType()->getPointerAddressSpace() == 0)
912 return true;
913 // Allow replacement with dereferenceable constants. This is not strictly
914 // correct, but required for vtable assumptions.
915 auto IsBasedOnConstantGlobal = [](const Value *V) {
917 return GV && GV->isConstant();
918 };
919 if (isa<Constant>(To) && To->getType()->isPointerTy() &&
921 IsBasedOnConstantGlobal(To))
922 return true;
923 return getUnderlyingObjectAggressive(From, /*MustPreserveProvenance=*/true) ==
924 getUnderlyingObjectAggressive(To, /*MustPreserveProvenance=*/true);
925}
926
928 const DataLayout &DL) {
929 Type *Ty = To->getType();
930 assert(U->getType() == Ty && "values must have matching types");
931 // Not a pointer, just return true.
932 if (!Ty->isPtrOrPtrVectorTy())
933 return true;
934
935 // Do not perform replacements in lifetime intrinsic arguments.
936 if (isa<LifetimeIntrinsic>(U.getUser()))
937 return false;
938
939 if (isPointerAlwaysReplaceable(&*U, To, DL))
940 return true;
941
942 bool HasNonAddressBits =
943 DL.getAddressSizeInBits(Ty) != DL.getPointerTypeSizeInBits(Ty);
944 return isPointerUseReplaceable(U, HasNonAddressBits);
945}
946
947bool llvm::canReplacePointersIfEqual(const Value *From, const Value *To,
948 const DataLayout &DL) {
949 assert(From->getType() == To->getType() && "values must have matching types");
950 // Not a pointer, just return true.
951 if (!From->getType()->isPtrOrPtrVectorTy())
952 return true;
953
954 return isPointerAlwaysReplaceable(From, To, DL);
955}
956
959 SmallVectorImpl<LoadInst *> &NonDereferenceableAndAlignedLoads,
961 for (BasicBlock *BB : L->blocks()) {
962 for (Instruction &I : *BB) {
963 // Pseudo-probes are placeholders with side effects but
964 // no real memory access, and do not affect dereferenceability.
966 continue;
967 if (auto *LI = dyn_cast<LoadInst>(&I)) {
968 if (!isDereferenceableAndAlignedInLoop(LI, L, *SE, *DT, AC, Predicates))
969 NonDereferenceableAndAlignedLoads.push_back(LI);
970 } else if (I.mayReadFromMemory() || I.mayWriteToMemory() ||
971 I.mayThrow()) {
972 return false;
973 }
974 }
975 }
976 return true;
977}
978
980 Value *const Ptr) {
981 assert(Ptr->getType()->isPointerTy() && "Must be called with pointer arg");
982
983 unsigned BitWidth = DL.getIndexTypeSizeInBits(Ptr->getType());
984 LinearExpression Expr(Ptr, BitWidth);
985
986 while (true) {
987 auto *GEP = dyn_cast<GEPOperator>(Expr.BasePtr);
988 if (!GEP || GEP->getSourceElementType()->isScalableTy())
989 return Expr;
990
991 Value *VarIndex = nullptr;
992 for (Value *Index : GEP->indices()) {
993 if (isa<ConstantInt>(Index))
994 continue;
995 // Only allow a single variable index. We do not bother to handle the
996 // case of the same variable index appearing multiple times.
997 if (Expr.Index || VarIndex)
998 return Expr;
999 VarIndex = Index;
1000 }
1001
1002 // Don't return non-canonical indexes.
1003 if (VarIndex && !VarIndex->getType()->isIntegerTy(BitWidth))
1004 return Expr;
1005
1006 // We have verified that we can fully handle this GEP, so we can update Expr
1007 // members past this point.
1008 Expr.BasePtr = GEP->getPointerOperand();
1009 Expr.Flags = GEP == Ptr
1010 ? GEP->getNoWrapFlags()
1011 : Expr.Flags.intersectForOffsetAdd(GEP->getNoWrapFlags());
1012
1013 // Try to look through mul and shl
1014 APInt IndexScale(BitWidth, 1);
1015 if (auto *BO = dyn_cast_or_null<BinaryOperator>(VarIndex)) {
1016 Value *UnscaledIndex = nullptr;
1017 const APInt *Constant;
1018 bool FoundIndexScale = true;
1019 if (match(BO, m_Mul(m_Value(UnscaledIndex), m_APInt(Constant)))) {
1020 IndexScale *= *Constant;
1021 } else if (match(BO, m_Shl(m_Value(UnscaledIndex), m_APInt(Constant))) &&
1022 Constant->ult(BitWidth)) {
1023 IndexScale <<= *Constant;
1024 } else {
1025 FoundIndexScale = false;
1026 }
1027
1028 if (FoundIndexScale) {
1029 // If we do not have nuw or nsw on the mul/shl we need to update the
1030 // flags
1031 if (!BO->hasNoSignedWrap())
1033 if (!BO->hasNoUnsignedWrap())
1034 Expr.Flags = Expr.Flags.withoutNoUnsignedWrap();
1035
1036 VarIndex = UnscaledIndex;
1037 }
1038 }
1039
1041 GTI != GTE; ++GTI) {
1042 Value *Index = GTI.getOperand();
1043 if (auto *ConstOffset = dyn_cast<ConstantInt>(Index)) {
1044 if (ConstOffset->isZero())
1045 continue;
1046 if (StructType *STy = GTI.getStructTypeOrNull()) {
1047 unsigned ElementIdx = ConstOffset->getZExtValue();
1048 const StructLayout *SL = DL.getStructLayout(STy);
1049 Expr.Offset += SL->getElementOffset(ElementIdx);
1050 continue;
1051 }
1052 // Truncate if type size exceeds index space.
1053 APInt IndexedSize(BitWidth, GTI.getSequentialElementStride(DL),
1054 /*isSigned=*/false,
1055 /*implicitTrunc=*/true);
1056 Expr.Offset +=
1057 ConstOffset->getValue().sextOrTrunc(BitWidth) * IndexedSize;
1058 continue;
1059 }
1060
1061 assert(Expr.Index == nullptr && "Shouldn't have index yet");
1062 Expr.Index = VarIndex;
1063 // Truncate if type size exceeds index space.
1064 Expr.Scale = APInt(BitWidth, GTI.getSequentialElementStride(DL),
1065 /*isSigned=*/false, /*implicitTrunc=*/true) *
1066 IndexScale;
1067 }
1068 }
1069
1070 return Expr;
1071}
1072
1073std::optional<ConstGlobalLoad> ConstGlobalLoad::fromLoadInst(LoadInst *LI) {
1074 if (LI->isVolatile())
1075 return std::nullopt;
1076
1077 // `decomposeLinearExpression` can be expensive, check the underlying object
1078 // before `decomposeLinearExpression` to bail out quickly in the common cases.
1079 Value *Ptr = LI->getPointerOperand();
1081 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
1082 return std::nullopt;
1083
1084 const DataLayout &DL = LI->getDataLayout();
1085
1086 Type *EltTy = LI->getType();
1087 TypeSize EltSize = DL.getTypeStoreSize(EltTy);
1088 if (EltSize.isScalable())
1089 return std::nullopt;
1090
1092 if (!Expr.Index || Expr.BasePtr != GV || Expr.Offset.getBitWidth() > 64)
1093 return std::nullopt;
1094
1095 Constant *Init = GV->getInitializer();
1096 TypeSize GlobalSize = DL.getTypeAllocSize(Init->getType());
1097
1098 const APInt &Stride = Expr.Scale;
1099 const APInt &ConstOffset = Expr.Offset;
1100
1101 // Allow an additional context offset, but only within the stride.
1102 if (!ConstOffset.ult(Stride))
1103 return std::nullopt;
1104
1105 // Don't handle overlapping loads for now.
1106 if (!Stride.uge(EltSize.getFixedValue()))
1107 return std::nullopt;
1108
1109 // - With nuw: `Idx * Stride` does not wrap and all strides are valid.
1110 // - With nusw: `Idx * Stride` does not wrap as signed, and the following
1111 // enumeration over ArrayElementCount is valid so long as the stride is
1112 // positive.
1113 // - Without nusw or nuw: `Idx * Stride` is computed modulo 2^N (see
1114 // getIndex), and the masking we may do in buildCanonicalIndex is only
1115 // exact when the stride is a power of two.
1116 bool StrideIsValid =
1117 Expr.Flags.hasNoUnsignedWrap() ||
1118 (Expr.Flags.hasNoUnsignedSignedWrap() ? !Stride.isNegative()
1119 : Stride.isPowerOf2());
1120 if (!StrideIsValid)
1121 return std::nullopt;
1122
1123 uint64_t ArrayElementCount =
1124 divideCeil((GlobalSize.getFixedValue() - ConstOffset.getZExtValue()),
1125 Stride.getZExtValue());
1126
1127 return ConstGlobalLoad(DL, Expr, ArrayElementCount, GV, EltTy);
1128}
1129
1131 assert(Idx < ElementCount);
1132 APInt Offset = Expr.Offset + (Expr.Scale * Idx);
1133 GlobalVariable *GV = cast<GlobalVariable>(Expr.BasePtr);
1134 return ConstantFoldLoadFromConst(GV->getInitializer(), EltTy, Offset,
1135 GV->getDataLayout());
1136}
1137
1139 // If neither nusw (implied by inbounds) nor nuw is present, `Idx * Stride`
1140 // can wrap, so multiple index values can address the same offset in the
1141 // global. E.g. with a stride of 2, both 0x00..00 and 0x80..00 address offset
1142 // 0.
1143 //
1144 // To be able to compare the index against known element indices with a
1145 // single test like `icmp eq CanonicalIdx, 0`, we map all such index values
1146 // to one canonical value: the smallest one, obtained by clearing the highest
1147 // `countr_zero(Stride)` bits of `Idx`. Since `fromLoadInst` only accepts
1148 // power-of-two strides in this case, `CanonicalIdx * Stride` doesn't wrap.
1149 Value *Idx = Expr.Index;
1150 unsigned Shift = Expr.Scale.countr_zero();
1151 if (Expr.Flags.hasNoUnsignedWrap() || Expr.Flags.hasNoUnsignedSignedWrap() ||
1152 Shift == 0)
1153 return Idx;
1154 unsigned BitWidth = Expr.Scale.getBitWidth();
1156 return Builder.CreateAnd(Idx, ConstantInt::get(Idx->getType(), Mask));
1157}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
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< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
@ Available
We know the block is fully available. This is a fixpoint.
Definition GVN.cpp:1241
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:288
static bool isPointerUseReplaceable(const Use &U, bool HasNonAddressBits)
Definition Loads.cpp:878
static bool isPointerAlwaysReplaceable(const Value *From, const Value *To, const DataLayout &DL)
Definition Loads.cpp:902
static bool isDereferenceableAndAlignedPointerViaAssumption(const Value *Ptr, Align Alignment, const SimplifyQuery &SQ, bool IgnoreFree, function_ref< bool(const RetainedKnowledge &RK)> CheckSize)
Definition Loads.cpp:38
static bool areNonOverlapSameBaseLoadAndStore(const Value *LoadPtr, Type *LoadTy, const Value *StorePtr, Type *StoreTy, const DataLayout &DL)
Definition Loads.cpp:572
static bool hasCompatibleAtomicAccessSize(Type *AccessTy, const LoadStoreInstProperties &AccessProps, Type *OtherAccessTy, const LoadStoreInstProperties &OtherProps, const DataLayout &DL)
Definition Loads.cpp:598
static Value * getAvailableLoadStore(Instruction *Inst, const Value *Ptr, Type *AccessTy, const LoadStoreInstProperties &AccessProps, const DataLayout &DL, bool *IsLoadCSE)
Definition Loads.cpp:613
static bool suppressSpeculativeLoadForSanitizers(const Instruction &CtxI)
Definition Loads.cpp:443
#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
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1973
static LLVM_ABI APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition APInt.cpp:648
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1086
bool getBoolValue() const
Convert APInt to a boolean value.
Definition APInt.h:467
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
@ MustAlias
The two locations precisely alias each other.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:439
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
reverse_iterator rend()
Definition BasicBlock.h:457
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
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
LLVM_ABI Value * buildCanonicalIndex(IRBuilderBase &Builder) const
Build the canonicalized index that will index the global without wrapping.
Definition Loads.cpp:1138
static LLVM_ABI std::optional< ConstGlobalLoad > fromLoadInst(LoadInst *LI)
Analyze a load instruction to a linear expression that loads from a constant global.
Definition Loads.cpp:1073
LLVM_ABI Constant * getElementAt(uint64_t Idx) const
Get the element of the global that the load instruction reads for the given canonical index.
Definition Loads.cpp:1130
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.
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
LLVM_ABI unsigned getPointerTypeSizeInBits(Type *) const
The pointer representation size in bits for this type.
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
Definition DataLayout.h:581
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
Represents calls to the gc.relocate intrinsic.
GEPNoWrapFlags withoutNoUnsignedSignedWrap() const
GEPNoWrapFlags intersectForOffsetAdd(GEPNoWrapFlags Other) const
Given (gep (gep p, x), y), determine the nowrap flags for (gep p, x+y).
GEPNoWrapFlags withoutNoUnsignedWrap() const
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:205
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
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 isVolatile() const
Return true if this is a load from a volatile memory location.
bool isUnordered() const
Align getAlign() const
Return the alignment of the access that is being performed.
bool hasValue() const
static LocationSize precise(uint64_t Value)
bool isScalable() const
TypeSize getValue() const
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.
LocationSize Size
The maximum size of the location, in address-units, or UnknownSize if the size is not known.
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.
Type * getType() const
Return the LLVM type of this SCEV expression.
static LoopGuards collectOnDemand(const Loop *L, ScalarEvolution &SE)
Return loop guards for loop L, which are collected on first use.
The main scalar evolution driver.
LLVM_ABI Type * getWiderType(Type *Ty1, Type *Ty2) const
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 * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
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 SCEVUse getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
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.
APInt getUnsignedRangeMax(const SCEV *S)
Determine the max of the unsigned range for a particular SCEV.
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, unsigned Depth=0)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
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:745
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:776
Class to represent struct types.
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
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:277
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:292
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
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:257
user_iterator user_begin()
Definition Value.h:404
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:985
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:707
user_iterator user_end()
Definition Value.h:412
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:231
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
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:166
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
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...
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:139
@ Load
The value being inserted comes from a load (InsertElement only).
LLVM_ABI const Value * getArgumentAliasingToReturnedPointer(const CallBase *Call, bool MustPreserveOffset, bool MustPreserveProvenance=false)
This function returns call pointer argument that is considered the same by aliasing rules.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI bool isStorePreservingMemoryLocation(const StoreInst *SI, const MemoryLocation &MemLoc, Align MemLocAlign, BatchAAResults &AA, unsigned ScanLimit)
Check whether SI, which may alias MemLoc, can be safely skipped.
Definition Loads.cpp:846
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 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:555
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CtxI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
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:927
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:947
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:979
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 const Value * getUnderlyingObjectAggressive(const Value *V, bool MustPreserveProvenance=false)
Like getUnderlyingObject(), but will try harder to find a single underlying object.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
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.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
LLVM_ABI bool isSafeToLoadUnconditionally(Value *V, Align Alignment, const APInt &Size, const SimplifyQuery &SQ, bool IgnoreFree=false)
Return true if we know that executing a load from this value cannot trap.
Definition Loads.cpp:457
LLVM_ABI bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, Align Alignment, const SimplifyQuery &Q, bool IgnoreFree=false)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested.
Definition Loads.cpp:247
LLVM_ABI bool willNotFreeBetween(const Instruction *Assume, const Instruction *CtxI, const DominatorTree *DT=nullptr)
Returns true, if no instruction between Assume and CtxI may free (including through synchronization).
constexpr unsigned BitWidth
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:957
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI bool isDereferenceablePointer(const Value *V, Type *Ty, const SimplifyQuery &Q, bool IgnoreFree=false)
Equivalent to isDereferenceableAndAlignedPointer with an alignment of 1.
Definition Loads.cpp:267
LLVM_ABI Value * findAvailablePtrLoadStore(const MemoryLocation &Loc, Type *AccessTy, const LoadStoreInstProperties &AccessProps, 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:716
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:307
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, ScalarEvolution::LoopGuards &LoopGuards)
Calculate Start and End points of memory access using exact backedge taken count BTC if computable or...
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Linear expression BasePtr + Index * Scale + Offset.
Definition Loads.h:227
GEPNoWrapFlags Flags
Definition Loads.h:232
A structure representing the properties of a load or store instruction.
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
const DataLayout & DL
const DominatorTree * DT
AssumptionCache * AC
const Instruction * CtxI
const TargetLibraryInfo * TLI