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 /// AreEquivalentAddressValues - Test if A and B will obviously have the same
26 /// value. This includes recognizing that %t0 and %t1 will have the same
27 /// value in code like this:
28 /// %t0 = getelementptr \@a, 0, 3
29 /// store i32 0, i32* %t0
30 /// %t1 = getelementptr \@a, 0, 3
31 /// %t2 = load i32* %t1
33 static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
34 // Test if the values are trivially equivalent.
35 if (A == B) return true;
37 // Test if the values come from identical arithmetic instructions.
38 // Use isIdenticalToWhenDefined instead of isIdenticalTo because
39 // this function is only used when one address use dominates the
40 // other, which means that they'll always either have the same
41 // value or one of them will have an undefined value.
42 if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||
43 isa<PHINode>(A) || isa<GetElementPtrInst>(A))
44 if (const Instruction *BI = dyn_cast<Instruction>(B))
45 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
48 // Otherwise they may not be equivalent.
52 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
53 /// from this value cannot trap. If it is not obviously safe to load from the
54 /// specified pointer, we do a quick local scan of the basic block containing
55 /// ScanFrom, to determine if the address is already accessed.
56 bool llvm::isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom,
57 unsigned Align, const DataLayout *TD) {
58 int64_t ByteOffset = 0;
61 Base = GetPointerBaseWithConstantOffset(V, ByteOffset, *TD);
63 if (ByteOffset < 0) // out of bounds
67 unsigned BaseAlign = 0;
68 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
69 // An alloca is safe to load from as load as it is suitably aligned.
70 BaseType = AI->getAllocatedType();
71 BaseAlign = AI->getAlignment();
72 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
73 // Global variables are safe to load from but their size cannot be
74 // guaranteed if they are overridden.
75 if (!GV->mayBeOverridden()) {
76 BaseType = GV->getType()->getElementType();
77 BaseAlign = GV->getAlignment();
81 if (BaseType && BaseType->isSized()) {
82 if (TD && BaseAlign == 0)
83 BaseAlign = TD->getPrefTypeAlignment(BaseType);
85 if (Align <= BaseAlign) {
87 return true; // Loading directly from an alloca or global is OK.
89 // Check if the load is within the bounds of the underlying object.
90 PointerType *AddrTy = cast<PointerType>(V->getType());
91 uint64_t LoadSize = TD->getTypeStoreSize(AddrTy->getElementType());
92 if (ByteOffset + LoadSize <= TD->getTypeAllocSize(BaseType) &&
93 (Align == 0 || (ByteOffset % Align) == 0))
98 // Otherwise, be a little bit aggressive by scanning the local block where we
99 // want to check to see if the pointer is already being loaded or stored
100 // from/to. If so, the previous load or store would have already trapped,
101 // so there is no harm doing an extra load (also, CSE will later eliminate
102 // the load entirely).
103 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
108 // If we see a free or a call which may write to memory (i.e. which might do
109 // a free) the pointer could be marked invalid.
110 if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
111 !isa<DbgInfoIntrinsic>(BBI))
114 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
115 if (AreEquivalentAddressValues(LI->getOperand(0), V)) return true;
116 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
117 if (AreEquivalentAddressValues(SI->getOperand(1), V)) return true;
123 /// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the
124 /// instruction before ScanFrom) checking to see if we have the value at the
125 /// memory address *Ptr locally available within a small number of instructions.
126 /// If the value is available, return it.
128 /// If not, return the iterator for the last validated instruction that the
129 /// value would be live through. If we scanned the entire block and didn't find
130 /// something that invalidates *Ptr or provides it, ScanFrom would be left at
131 /// begin() and this returns null. ScanFrom could also be left
133 /// MaxInstsToScan specifies the maximum instructions to scan in the block. If
134 /// it is set to 0, it will scan the whole block. You can also optionally
135 /// specify an alias analysis implementation, which makes this more precise.
137 /// If TBAATag is non-null and a load or store is found, the TBAA tag from the
138 /// load or store is recorded there. If there is no TBAA tag or if no access
139 /// is found, it is left unmodified.
140 Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
141 BasicBlock::iterator &ScanFrom,
142 unsigned MaxInstsToScan,
145 if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;
147 // If we're using alias analysis to disambiguate get the size of *Ptr.
148 uint64_t AccessSize = 0;
150 Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
151 AccessSize = AA->getTypeStoreSize(AccessTy);
154 while (ScanFrom != ScanBB->begin()) {
155 // We must ignore debug info directives when counting (otherwise they
156 // would affect codegen).
157 Instruction *Inst = --ScanFrom;
158 if (isa<DbgInfoIntrinsic>(Inst))
161 // Restore ScanFrom to expected value in case next test succeeds
164 // Don't scan huge blocks.
165 if (MaxInstsToScan-- == 0) return 0;
168 // If this is a load of Ptr, the loaded value is available.
169 // (This is true even if the load is volatile or atomic, although
170 // those cases are unlikely.)
171 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
172 if (AreEquivalentAddressValues(LI->getOperand(0), Ptr)) {
173 if (TBAATag) *TBAATag = LI->getMetadata(LLVMContext::MD_tbaa);
177 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
178 // If this is a store through Ptr, the value is available!
179 // (This is true even if the store is volatile or atomic, although
180 // those cases are unlikely.)
181 if (AreEquivalentAddressValues(SI->getOperand(1), Ptr)) {
182 if (TBAATag) *TBAATag = SI->getMetadata(LLVMContext::MD_tbaa);
183 return SI->getOperand(0);
186 // If Ptr is an alloca and this is a store to a different alloca, ignore
187 // the store. This is a trivial form of alias analysis that is important
188 // for reg2mem'd code.
189 if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
190 (isa<AllocaInst>(SI->getOperand(1)) ||
191 isa<GlobalVariable>(SI->getOperand(1))))
194 // If we have alias analysis and it says the store won't modify the loaded
195 // value, ignore the store.
197 (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
200 // Otherwise the store that may or may not alias the pointer, bail out.
205 // If this is some other instruction that may clobber Ptr, bail out.
206 if (Inst->mayWriteToMemory()) {
207 // If alias analysis claims that it really won't modify the load,
210 (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
213 // May modify the pointer, bail out.
219 // Got to the start of the block, we didn't find it, but are done for this