1 //===- Loads.cpp - Local load analysis ------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines simple local analyses for load instructions.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/Analysis/Loads.h"
14 #include "llvm/Analysis/AliasAnalysis.h"
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/IR/DataLayout.h"
17 #include "llvm/IR/GlobalAlias.h"
18 #include "llvm/IR/GlobalVariable.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/Operator.h"
23 #include "llvm/IR/Statepoint.h"
27 static bool isAligned(const Value
*Base
, const APInt
&Offset
, unsigned Align
,
28 const DataLayout
&DL
) {
29 APInt
BaseAlign(Offset
.getBitWidth(), Base
->getPointerAlignment(DL
));
32 Type
*Ty
= Base
->getType()->getPointerElementType();
35 BaseAlign
= DL
.getABITypeAlignment(Ty
);
38 APInt
Alignment(Offset
.getBitWidth(), Align
);
40 assert(Alignment
.isPowerOf2() && "must be a power of 2!");
41 return BaseAlign
.uge(Alignment
) && !(Offset
& (Alignment
-1));
44 /// Test if V is always a pointer to allocated and suitably aligned memory for
45 /// a simple load or store.
46 static bool isDereferenceableAndAlignedPointer(
47 const Value
*V
, unsigned Align
, const APInt
&Size
, const DataLayout
&DL
,
48 const Instruction
*CtxI
, const DominatorTree
*DT
,
49 SmallPtrSetImpl
<const Value
*> &Visited
) {
50 // Already visited? Bail out, we've likely hit unreachable code.
51 if (!Visited
.insert(V
).second
)
54 // Note that it is not safe to speculate into a malloc'd region because
55 // malloc may return null.
57 // bitcast instructions are no-ops as far as dereferenceability is concerned.
58 if (const BitCastOperator
*BC
= dyn_cast
<BitCastOperator
>(V
))
59 return isDereferenceableAndAlignedPointer(BC
->getOperand(0), Align
, Size
,
60 DL
, CtxI
, DT
, Visited
);
62 bool CheckForNonNull
= false;
63 APInt
KnownDerefBytes(Size
.getBitWidth(),
64 V
->getPointerDereferenceableBytes(DL
, CheckForNonNull
));
65 if (KnownDerefBytes
.getBoolValue() && KnownDerefBytes
.uge(Size
))
66 if (!CheckForNonNull
|| isKnownNonZero(V
, DL
, 0, nullptr, CtxI
, DT
)) {
67 // As we recursed through GEPs to get here, we've incrementally checked
68 // that each step advanced by a multiple of the alignment. If our base is
69 // properly aligned, then the original offset accessed must also be.
70 Type
*Ty
= V
->getType();
71 assert(Ty
->isSized() && "must be sized");
72 APInt
Offset(DL
.getTypeStoreSizeInBits(Ty
), 0);
73 return isAligned(V
, Offset
, Align
, DL
);
76 // For GEPs, determine if the indexing lands within the allocated object.
77 if (const GEPOperator
*GEP
= dyn_cast
<GEPOperator
>(V
)) {
78 const Value
*Base
= GEP
->getPointerOperand();
80 APInt
Offset(DL
.getIndexTypeSizeInBits(GEP
->getType()), 0);
81 if (!GEP
->accumulateConstantOffset(DL
, Offset
) || Offset
.isNegative() ||
82 !Offset
.urem(APInt(Offset
.getBitWidth(), Align
)).isMinValue())
85 // If the base pointer is dereferenceable for Offset+Size bytes, then the
86 // GEP (== Base + Offset) is dereferenceable for Size bytes. If the base
87 // pointer is aligned to Align bytes, and the Offset is divisible by Align
88 // then the GEP (== Base + Offset == k_0 * Align + k_1 * Align) is also
89 // aligned to Align bytes.
91 // Offset and Size may have different bit widths if we have visited an
92 // addrspacecast, so we can't do arithmetic directly on the APInt values.
93 return isDereferenceableAndAlignedPointer(
94 Base
, Align
, Offset
+ Size
.sextOrTrunc(Offset
.getBitWidth()),
95 DL
, CtxI
, DT
, Visited
);
98 // For gc.relocate, look through relocations
99 if (const GCRelocateInst
*RelocateInst
= dyn_cast
<GCRelocateInst
>(V
))
100 return isDereferenceableAndAlignedPointer(
101 RelocateInst
->getDerivedPtr(), Align
, Size
, DL
, CtxI
, DT
, Visited
);
103 if (const AddrSpaceCastInst
*ASC
= dyn_cast
<AddrSpaceCastInst
>(V
))
104 return isDereferenceableAndAlignedPointer(ASC
->getOperand(0), Align
, Size
,
105 DL
, CtxI
, DT
, Visited
);
107 if (const auto *Call
= dyn_cast
<CallBase
>(V
))
108 if (auto *RP
= getArgumentAliasingToReturnedPointer(Call
, true))
109 return isDereferenceableAndAlignedPointer(RP
, Align
, Size
, DL
, CtxI
, DT
,
112 // If we don't know, assume the worst.
116 bool llvm::isDereferenceableAndAlignedPointer(const Value
*V
, unsigned Align
,
118 const DataLayout
&DL
,
119 const Instruction
*CtxI
,
120 const DominatorTree
*DT
) {
121 SmallPtrSet
<const Value
*, 32> Visited
;
122 return ::isDereferenceableAndAlignedPointer(V
, Align
, Size
, DL
, CtxI
, DT
,
126 bool llvm::isDereferenceableAndAlignedPointer(const Value
*V
, Type
*Ty
,
128 const DataLayout
&DL
,
129 const Instruction
*CtxI
,
130 const DominatorTree
*DT
) {
131 // When dereferenceability information is provided by a dereferenceable
132 // attribute, we know exactly how many bytes are dereferenceable. If we can
133 // determine the exact offset to the attributed variable, we can use that
136 // Require ABI alignment for loads without alignment specification
138 Align
= DL
.getABITypeAlignment(Ty
);
143 SmallPtrSet
<const Value
*, 32> Visited
;
144 return ::isDereferenceableAndAlignedPointer(
146 APInt(DL
.getIndexTypeSizeInBits(V
->getType()), DL
.getTypeStoreSize(Ty
)),
147 DL
, CtxI
, DT
, Visited
);
150 bool llvm::isDereferenceablePointer(const Value
*V
, Type
*Ty
,
151 const DataLayout
&DL
,
152 const Instruction
*CtxI
,
153 const DominatorTree
*DT
) {
154 return isDereferenceableAndAlignedPointer(V
, Ty
, 1, DL
, CtxI
, DT
);
157 /// Test if A and B will obviously have the same value.
159 /// This includes recognizing that %t0 and %t1 will have the same
160 /// value in code like this:
162 /// %t0 = getelementptr \@a, 0, 3
163 /// store i32 0, i32* %t0
164 /// %t1 = getelementptr \@a, 0, 3
165 /// %t2 = load i32* %t1
168 static bool AreEquivalentAddressValues(const Value
*A
, const Value
*B
) {
169 // Test if the values are trivially equivalent.
173 // Test if the values come from identical arithmetic instructions.
174 // Use isIdenticalToWhenDefined instead of isIdenticalTo because
175 // this function is only used when one address use dominates the
176 // other, which means that they'll always either have the same
177 // value or one of them will have an undefined value.
178 if (isa
<BinaryOperator
>(A
) || isa
<CastInst
>(A
) || isa
<PHINode
>(A
) ||
179 isa
<GetElementPtrInst
>(A
))
180 if (const Instruction
*BI
= dyn_cast
<Instruction
>(B
))
181 if (cast
<Instruction
>(A
)->isIdenticalToWhenDefined(BI
))
184 // Otherwise they may not be equivalent.
188 /// Check if executing a load of this pointer value cannot trap.
190 /// If DT and ScanFrom are specified this method performs context-sensitive
191 /// analysis and returns true if it is safe to load immediately before ScanFrom.
193 /// If it is not obviously safe to load from the specified pointer, we do
194 /// a quick local scan of the basic block containing \c ScanFrom, to determine
195 /// if the address is already accessed.
197 /// This uses the pointee type to determine how many bytes need to be safe to
198 /// load from the pointer.
199 bool llvm::isSafeToLoadUnconditionally(Value
*V
, unsigned Align
, APInt
&Size
,
200 const DataLayout
&DL
,
201 Instruction
*ScanFrom
,
202 const DominatorTree
*DT
) {
203 // Zero alignment means that the load has the ABI alignment for the target
205 Align
= DL
.getABITypeAlignment(V
->getType()->getPointerElementType());
206 assert(isPowerOf2_32(Align
));
208 // If DT is not specified we can't make context-sensitive query
209 const Instruction
* CtxI
= DT
? ScanFrom
: nullptr;
210 if (isDereferenceableAndAlignedPointer(V
, Align
, Size
, DL
, CtxI
, DT
))
213 int64_t ByteOffset
= 0;
215 Base
= GetPointerBaseWithConstantOffset(V
, ByteOffset
, DL
);
217 if (ByteOffset
< 0) // out of bounds
220 Type
*BaseType
= nullptr;
221 unsigned BaseAlign
= 0;
222 if (const AllocaInst
*AI
= dyn_cast
<AllocaInst
>(Base
)) {
223 // An alloca is safe to load from as load as it is suitably aligned.
224 BaseType
= AI
->getAllocatedType();
225 BaseAlign
= AI
->getAlignment();
226 } else if (const GlobalVariable
*GV
= dyn_cast
<GlobalVariable
>(Base
)) {
227 // Global variables are not necessarily safe to load from if they are
228 // interposed arbitrarily. Their size may change or they may be weak and
229 // require a test to determine if they were in fact provided.
230 if (!GV
->isInterposable()) {
231 BaseType
= GV
->getType()->getElementType();
232 BaseAlign
= GV
->getAlignment();
236 PointerType
*AddrTy
= cast
<PointerType
>(V
->getType());
237 uint64_t LoadSize
= DL
.getTypeStoreSize(AddrTy
->getElementType());
239 // If we found a base allocated type from either an alloca or global variable,
240 // try to see if we are definitively within the allocated region. We need to
241 // know the size of the base type and the loaded type to do anything in this
243 if (BaseType
&& BaseType
->isSized()) {
245 BaseAlign
= DL
.getPrefTypeAlignment(BaseType
);
247 if (Align
<= BaseAlign
) {
248 // Check if the load is within the bounds of the underlying object.
249 if (ByteOffset
+ LoadSize
<= DL
.getTypeAllocSize(BaseType
) &&
250 ((ByteOffset
% Align
) == 0))
258 // Otherwise, be a little bit aggressive by scanning the local block where we
259 // want to check to see if the pointer is already being loaded or stored
260 // from/to. If so, the previous load or store would have already trapped,
261 // so there is no harm doing an extra load (also, CSE will later eliminate
262 // the load entirely).
263 BasicBlock::iterator BBI
= ScanFrom
->getIterator(),
264 E
= ScanFrom
->getParent()->begin();
266 // We can at least always strip pointer casts even though we can't use the
268 V
= V
->stripPointerCasts();
273 // If we see a free or a call which may write to memory (i.e. which might do
274 // a free) the pointer could be marked invalid.
275 if (isa
<CallInst
>(BBI
) && BBI
->mayWriteToMemory() &&
276 !isa
<DbgInfoIntrinsic
>(BBI
))
280 unsigned AccessedAlign
;
281 if (LoadInst
*LI
= dyn_cast
<LoadInst
>(BBI
)) {
282 // Ignore volatile loads. The execution of a volatile load cannot
283 // be used to prove an address is backed by regular memory; it can,
284 // for example, point to an MMIO register.
285 if (LI
->isVolatile())
287 AccessedPtr
= LI
->getPointerOperand();
288 AccessedAlign
= LI
->getAlignment();
289 } else if (StoreInst
*SI
= dyn_cast
<StoreInst
>(BBI
)) {
290 // Ignore volatile stores (see comment for loads).
291 if (SI
->isVolatile())
293 AccessedPtr
= SI
->getPointerOperand();
294 AccessedAlign
= SI
->getAlignment();
298 Type
*AccessedTy
= AccessedPtr
->getType()->getPointerElementType();
299 if (AccessedAlign
== 0)
300 AccessedAlign
= DL
.getABITypeAlignment(AccessedTy
);
301 if (AccessedAlign
< Align
)
304 // Handle trivial cases.
305 if (AccessedPtr
== V
)
308 if (AreEquivalentAddressValues(AccessedPtr
->stripPointerCasts(), V
) &&
309 LoadSize
<= DL
.getTypeStoreSize(AccessedTy
))
315 bool llvm::isSafeToLoadUnconditionally(Value
*V
, Type
*Ty
, unsigned Align
,
316 const DataLayout
&DL
,
317 Instruction
*ScanFrom
,
318 const DominatorTree
*DT
) {
319 APInt
Size(DL
.getIndexTypeSizeInBits(V
->getType()), DL
.getTypeStoreSize(Ty
));
320 return isSafeToLoadUnconditionally(V
, Align
, Size
, DL
, ScanFrom
, DT
);
323 /// DefMaxInstsToScan - the default number of maximum instructions
324 /// to scan in the block, used by FindAvailableLoadedValue().
325 /// FindAvailableLoadedValue() was introduced in r60148, to improve jump
326 /// threading in part by eliminating partially redundant loads.
327 /// At that point, the value of MaxInstsToScan was already set to '6'
328 /// without documented explanation.
330 llvm::DefMaxInstsToScan("available-load-scan-limit", cl::init(6), cl::Hidden
,
331 cl::desc("Use this to specify the default maximum number of instructions "
332 "to scan backward from a given instruction, when searching for "
333 "available loaded value"));
335 Value
*llvm::FindAvailableLoadedValue(LoadInst
*Load
,
337 BasicBlock::iterator
&ScanFrom
,
338 unsigned MaxInstsToScan
,
339 AliasAnalysis
*AA
, bool *IsLoad
,
340 unsigned *NumScanedInst
) {
341 // Don't CSE load that is volatile or anything stronger than unordered.
342 if (!Load
->isUnordered())
345 return FindAvailablePtrLoadStore(
346 Load
->getPointerOperand(), Load
->getType(), Load
->isAtomic(), ScanBB
,
347 ScanFrom
, MaxInstsToScan
, AA
, IsLoad
, NumScanedInst
);
350 Value
*llvm::FindAvailablePtrLoadStore(Value
*Ptr
, Type
*AccessTy
,
351 bool AtLeastAtomic
, BasicBlock
*ScanBB
,
352 BasicBlock::iterator
&ScanFrom
,
353 unsigned MaxInstsToScan
,
354 AliasAnalysis
*AA
, bool *IsLoadCSE
,
355 unsigned *NumScanedInst
) {
356 if (MaxInstsToScan
== 0)
357 MaxInstsToScan
= ~0U;
359 const DataLayout
&DL
= ScanBB
->getModule()->getDataLayout();
361 // Try to get the store size for the type.
362 auto AccessSize
= LocationSize::precise(DL
.getTypeStoreSize(AccessTy
));
364 Value
*StrippedPtr
= Ptr
->stripPointerCasts();
366 while (ScanFrom
!= ScanBB
->begin()) {
367 // We must ignore debug info directives when counting (otherwise they
368 // would affect codegen).
369 Instruction
*Inst
= &*--ScanFrom
;
370 if (isa
<DbgInfoIntrinsic
>(Inst
))
373 // Restore ScanFrom to expected value in case next test succeeds
379 // Don't scan huge blocks.
380 if (MaxInstsToScan
-- == 0)
384 // If this is a load of Ptr, the loaded value is available.
385 // (This is true even if the load is volatile or atomic, although
386 // those cases are unlikely.)
387 if (LoadInst
*LI
= dyn_cast
<LoadInst
>(Inst
))
388 if (AreEquivalentAddressValues(
389 LI
->getPointerOperand()->stripPointerCasts(), StrippedPtr
) &&
390 CastInst::isBitOrNoopPointerCastable(LI
->getType(), AccessTy
, DL
)) {
392 // We can value forward from an atomic to a non-atomic, but not the
394 if (LI
->isAtomic() < AtLeastAtomic
)
402 if (StoreInst
*SI
= dyn_cast
<StoreInst
>(Inst
)) {
403 Value
*StorePtr
= SI
->getPointerOperand()->stripPointerCasts();
404 // If this is a store through Ptr, the value is available!
405 // (This is true even if the store is volatile or atomic, although
406 // those cases are unlikely.)
407 if (AreEquivalentAddressValues(StorePtr
, StrippedPtr
) &&
408 CastInst::isBitOrNoopPointerCastable(SI
->getValueOperand()->getType(),
411 // We can value forward from an atomic to a non-atomic, but not the
413 if (SI
->isAtomic() < AtLeastAtomic
)
418 return SI
->getOperand(0);
421 // If both StrippedPtr and StorePtr reach all the way to an alloca or
422 // global and they are different, ignore the store. This is a trivial form
423 // of alias analysis that is important for reg2mem'd code.
424 if ((isa
<AllocaInst
>(StrippedPtr
) || isa
<GlobalVariable
>(StrippedPtr
)) &&
425 (isa
<AllocaInst
>(StorePtr
) || isa
<GlobalVariable
>(StorePtr
)) &&
426 StrippedPtr
!= StorePtr
)
429 // If we have alias analysis and it says the store won't modify the loaded
430 // value, ignore the store.
431 if (AA
&& !isModSet(AA
->getModRefInfo(SI
, StrippedPtr
, AccessSize
)))
434 // Otherwise the store that may or may not alias the pointer, bail out.
439 // If this is some other instruction that may clobber Ptr, bail out.
440 if (Inst
->mayWriteToMemory()) {
441 // If alias analysis claims that it really won't modify the load,
443 if (AA
&& !isModSet(AA
->getModRefInfo(Inst
, StrippedPtr
, AccessSize
)))
446 // May modify the pointer, bail out.
452 // Got to the start of the block, we didn't find it, but are done for this