1 //===- Loads.cpp - Local load analysis ------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines simple local analyses for load instructions.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Analysis/Loads.h"
15 #include "llvm/Analysis/AliasAnalysis.h"
16 #include "llvm/Analysis/ValueTracking.h"
17 #include "llvm/IR/DataLayout.h"
18 #include "llvm/IR/GlobalAlias.h"
19 #include "llvm/IR/GlobalVariable.h"
20 #include "llvm/IR/IntrinsicInst.h"
21 #include "llvm/IR/LLVMContext.h"
22 #include "llvm/IR/Operator.h"
25 /// \brief Test if A and B will obviously have the same value.
27 /// This includes recognizing that %t0 and %t1 will have the same
28 /// value in code like this:
30 /// %t0 = getelementptr \@a, 0, 3
31 /// store i32 0, i32* %t0
32 /// %t1 = getelementptr \@a, 0, 3
33 /// %t2 = load i32* %t1
36 static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
37 // Test if the values are trivially equivalent.
41 // Test if the values come from identical arithmetic instructions.
42 // Use isIdenticalToWhenDefined instead of isIdenticalTo because
43 // this function is only used when one address use dominates the
44 // other, which means that they'll always either have the same
45 // value or one of them will have an undefined value.
46 if (isa<BinaryOperator>(A) || isa<CastInst>(A) || isa<PHINode>(A) ||
47 isa<GetElementPtrInst>(A))
48 if (const Instruction *BI = dyn_cast<Instruction>(B))
49 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
52 // Otherwise they may not be equivalent.
56 /// \brief Check if executing a load of this pointer value cannot trap.
58 /// If it is not obviously safe to load from the specified pointer, we do
59 /// a quick local scan of the basic block containing \c ScanFrom, to determine
60 /// if the address is already accessed.
62 /// This uses the pointee type to determine how many bytes need to be safe to
63 /// load from the pointer.
64 bool llvm::isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom,
65 unsigned Align, const DataLayout *DL) {
66 int64_t ByteOffset = 0;
68 Base = GetPointerBaseWithConstantOffset(V, ByteOffset, DL);
70 if (ByteOffset < 0) // out of bounds
73 Type *BaseType = nullptr;
74 unsigned BaseAlign = 0;
75 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
76 // An alloca is safe to load from as load as it is suitably aligned.
77 BaseType = AI->getAllocatedType();
78 BaseAlign = AI->getAlignment();
79 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
80 // Global variables are not necessarily safe to load from if they are
81 // overridden. Their size may change or they may be weak and require a test
82 // to determine if they were in fact provided.
83 if (!GV->mayBeOverridden()) {
84 BaseType = GV->getType()->getElementType();
85 BaseAlign = GV->getAlignment();
89 PointerType *AddrTy = cast<PointerType>(V->getType());
90 uint64_t LoadSize = DL ? DL->getTypeStoreSize(AddrTy->getElementType()) : 0;
92 // If we found a base allocated type from either an alloca or global variable,
93 // try to see if we are definitively within the allocated region. We need to
94 // know the size of the base type and the loaded type to do anything in this
95 // case, so only try this when we have the DataLayout available.
96 if (BaseType && BaseType->isSized() && DL) {
98 BaseAlign = DL->getPrefTypeAlignment(BaseType);
100 if (Align <= BaseAlign) {
101 // Check if the load is within the bounds of the underlying object.
102 if (ByteOffset + LoadSize <= DL->getTypeAllocSize(BaseType) &&
103 (Align == 0 || (ByteOffset % Align) == 0))
108 // Otherwise, be a little bit aggressive by scanning the local block where we
109 // want to check to see if the pointer is already being loaded or stored
110 // from/to. If so, the previous load or store would have already trapped,
111 // so there is no harm doing an extra load (also, CSE will later eliminate
112 // the load entirely).
113 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
115 // We can at least always strip pointer casts even though we can't use the
117 V = V->stripPointerCasts();
122 // If we see a free or a call which may write to memory (i.e. which might do
123 // a free) the pointer could be marked invalid.
124 if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
125 !isa<DbgInfoIntrinsic>(BBI))
129 if (LoadInst *LI = dyn_cast<LoadInst>(BBI))
130 AccessedPtr = LI->getPointerOperand();
131 else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
132 AccessedPtr = SI->getPointerOperand();
136 // Handle trivial cases even w/o DataLayout or other work.
137 if (AccessedPtr == V)
143 auto *AccessedTy = cast<PointerType>(AccessedPtr->getType());
144 if (AreEquivalentAddressValues(AccessedPtr->stripPointerCasts(), V) &&
145 LoadSize <= DL->getTypeStoreSize(AccessedTy->getElementType()))
151 /// \brief Scan the ScanBB block backwards to see if we have the value at the
152 /// memory address *Ptr locally available within a small number of instructions.
154 /// The scan starts from \c ScanFrom. \c MaxInstsToScan specifies the maximum
155 /// instructions to scan in the block. If it is set to \c 0, it will scan the whole
158 /// If the value is available, this function returns it. If not, it returns the
159 /// iterator for the last validated instruction that the value would be live
160 /// through. If we scanned the entire block and didn't find something that
161 /// invalidates \c *Ptr or provides it, \c ScanFrom is left at the last
162 /// instruction processed and this returns null.
164 /// You can also optionally specify an alias analysis implementation, which
165 /// makes this more precise.
167 /// If \c AATags is non-null and a load or store is found, the AA tags from the
168 /// load or store are recorded there. If there are no AA tags or if no access is
169 /// found, it is left unmodified.
170 Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
171 BasicBlock::iterator &ScanFrom,
172 unsigned MaxInstsToScan,
173 AliasAnalysis *AA, AAMDNodes *AATags) {
174 if (MaxInstsToScan == 0)
175 MaxInstsToScan = ~0U;
177 Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
179 // Try to get the DataLayout for this module. This may be null, in which case
180 // the optimizations will be limited.
181 const DataLayout *DL = ScanBB->getDataLayout();
183 // Try to get the store size for the type.
184 uint64_t AccessSize = DL ? DL->getTypeStoreSize(AccessTy)
185 : AA ? AA->getTypeStoreSize(AccessTy) : 0;
187 Value *StrippedPtr = Ptr->stripPointerCasts();
189 while (ScanFrom != ScanBB->begin()) {
190 // We must ignore debug info directives when counting (otherwise they
191 // would affect codegen).
192 Instruction *Inst = --ScanFrom;
193 if (isa<DbgInfoIntrinsic>(Inst))
196 // Restore ScanFrom to expected value in case next test succeeds
199 // Don't scan huge blocks.
200 if (MaxInstsToScan-- == 0)
204 // If this is a load of Ptr, the loaded value is available.
205 // (This is true even if the load is volatile or atomic, although
206 // those cases are unlikely.)
207 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
208 if (AreEquivalentAddressValues(
209 LI->getPointerOperand()->stripPointerCasts(), StrippedPtr) &&
210 CastInst::isBitOrNoopPointerCastable(LI->getType(), AccessTy, DL)) {
212 LI->getAAMetadata(*AATags);
216 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
217 Value *StorePtr = SI->getPointerOperand()->stripPointerCasts();
218 // If this is a store through Ptr, the value is available!
219 // (This is true even if the store is volatile or atomic, although
220 // those cases are unlikely.)
221 if (AreEquivalentAddressValues(StorePtr, StrippedPtr) &&
222 CastInst::isBitOrNoopPointerCastable(SI->getValueOperand()->getType(),
225 SI->getAAMetadata(*AATags);
226 return SI->getOperand(0);
229 // If both StrippedPtr and StorePtr reach all the way to an alloca or
230 // global and they are different, ignore the store. This is a trivial form
231 // of alias analysis that is important for reg2mem'd code.
232 if ((isa<AllocaInst>(StrippedPtr) || isa<GlobalVariable>(StrippedPtr)) &&
233 (isa<AllocaInst>(StorePtr) || isa<GlobalVariable>(StorePtr)) &&
234 StrippedPtr != StorePtr)
237 // If we have alias analysis and it says the store won't modify the loaded
238 // value, ignore the store.
240 (AA->getModRefInfo(SI, StrippedPtr, AccessSize) &
241 AliasAnalysis::Mod) == 0)
244 // Otherwise the store that may or may not alias the pointer, bail out.
249 // If this is some other instruction that may clobber Ptr, bail out.
250 if (Inst->mayWriteToMemory()) {
251 // If alias analysis claims that it really won't modify the load,
254 (AA->getModRefInfo(Inst, StrippedPtr, AccessSize) &
255 AliasAnalysis::Mod) == 0)
258 // May modify the pointer, bail out.
264 // Got to the start of the block, we didn't find it, but are done for this