Rename 'TD' to 'DL' in this function as the argument is now a DataLayout
[oota-llvm.git] / lib / Analysis / Loads.cpp
1 //===- Loads.cpp - Local load analysis ------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines simple local analyses for load instructions.
11 //
12 //===----------------------------------------------------------------------===//
13
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"
23 using namespace llvm;
24
25 /// \brief Test if A and B will obviously have the same value.
26 ///
27 /// This includes recognizing that %t0 and %t1 will have the same
28 /// value in code like this:
29 /// \code
30 ///   %t0 = getelementptr \@a, 0, 3
31 ///   store i32 0, i32* %t0
32 ///   %t1 = getelementptr \@a, 0, 3
33 ///   %t2 = load i32* %t1
34 /// \endcode
35 ///
36 static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
37   // Test if the values are trivially equivalent.
38   if (A == B)
39     return true;
40
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))
50         return true;
51
52   // Otherwise they may not be equivalent.
53   return false;
54 }
55
56 /// \brief Check if executing a load of this pointer value cannot trap.
57 ///
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.
61 ///
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;
67   Value *Base = V;
68   Base = GetPointerBaseWithConstantOffset(V, ByteOffset, DL);
69
70   if (ByteOffset < 0) // out of bounds
71     return false;
72
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 safe to load from but their size cannot be
81     // guaranteed if they are overridden.
82     if (!GV->mayBeOverridden()) {
83       BaseType = GV->getType()->getElementType();
84       BaseAlign = GV->getAlignment();
85     }
86   }
87
88   if (BaseType && BaseType->isSized()) {
89     if (DL && BaseAlign == 0)
90       BaseAlign = DL->getPrefTypeAlignment(BaseType);
91
92     if (Align <= BaseAlign) {
93       if (!DL)
94         return true; // Loading directly from an alloca or global is OK.
95
96       // Check if the load is within the bounds of the underlying object.
97       PointerType *AddrTy = cast<PointerType>(V->getType());
98       uint64_t LoadSize = DL->getTypeStoreSize(AddrTy->getElementType());
99       if (ByteOffset + LoadSize <= DL->getTypeAllocSize(BaseType) &&
100           (Align == 0 || (ByteOffset % Align) == 0))
101         return true;
102     }
103   }
104
105   // Otherwise, be a little bit aggressive by scanning the local block where we
106   // want to check to see if the pointer is already being loaded or stored
107   // from/to.  If so, the previous load or store would have already trapped,
108   // so there is no harm doing an extra load (also, CSE will later eliminate
109   // the load entirely).
110   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
111
112   while (BBI != E) {
113     --BBI;
114
115     // If we see a free or a call which may write to memory (i.e. which might do
116     // a free) the pointer could be marked invalid.
117     if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
118         !isa<DbgInfoIntrinsic>(BBI))
119       return false;
120
121     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
122       if (AreEquivalentAddressValues(LI->getOperand(0), V))
123         return true;
124     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
125       if (AreEquivalentAddressValues(SI->getOperand(1), V))
126         return true;
127     }
128   }
129   return false;
130 }
131
132 /// \brief Scan the ScanBB block backwards to see if we have the value at the
133 /// memory address *Ptr locally available within a small number of instructions.
134 ///
135 /// The scan starts from \c ScanFrom. \c MaxInstsToScan specifies the maximum
136 /// instructions to scan in the block. If it is set to \c 0, it will scan the whole
137 /// block.
138 ///
139 /// If the value is available, this function returns it. If not, it returns the
140 /// iterator for the last validated instruction that the value would be live
141 /// through. If we scanned the entire block and didn't find something that
142 /// invalidates \c *Ptr or provides it, \c ScanFrom is left at the last
143 /// instruction processed and this returns null.
144 ///
145 /// You can also optionally specify an alias analysis implementation, which
146 /// makes this more precise.
147 ///
148 /// If \c AATags is non-null and a load or store is found, the AA tags from the
149 /// load or store are recorded there. If there are no AA tags or if no access is
150 /// found, it is left unmodified.
151 Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
152                                       BasicBlock::iterator &ScanFrom,
153                                       unsigned MaxInstsToScan,
154                                       AliasAnalysis *AA, AAMDNodes *AATags) {
155   if (MaxInstsToScan == 0)
156     MaxInstsToScan = ~0U;
157
158   // If we're using alias analysis to disambiguate get the size of *Ptr.
159   uint64_t AccessSize = 0;
160   if (AA) {
161     Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
162     AccessSize = AA->getTypeStoreSize(AccessTy);
163   }
164
165   while (ScanFrom != ScanBB->begin()) {
166     // We must ignore debug info directives when counting (otherwise they
167     // would affect codegen).
168     Instruction *Inst = --ScanFrom;
169     if (isa<DbgInfoIntrinsic>(Inst))
170       continue;
171
172     // Restore ScanFrom to expected value in case next test succeeds
173     ScanFrom++;
174
175     // Don't scan huge blocks.
176     if (MaxInstsToScan-- == 0)
177       return nullptr;
178
179     --ScanFrom;
180     // If this is a load of Ptr, the loaded value is available.
181     // (This is true even if the load is volatile or atomic, although
182     // those cases are unlikely.)
183     if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
184       if (AreEquivalentAddressValues(LI->getOperand(0), Ptr)) {
185         if (AATags)
186           LI->getAAMetadata(*AATags);
187         return LI;
188       }
189
190     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
191       // If this is a store through Ptr, the value is available!
192       // (This is true even if the store is volatile or atomic, although
193       // those cases are unlikely.)
194       if (AreEquivalentAddressValues(SI->getOperand(1), Ptr)) {
195         if (AATags)
196           SI->getAAMetadata(*AATags);
197         return SI->getOperand(0);
198       }
199
200       // If Ptr is an alloca and this is a store to a different alloca, ignore
201       // the store.  This is a trivial form of alias analysis that is important
202       // for reg2mem'd code.
203       if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
204           (isa<AllocaInst>(SI->getOperand(1)) ||
205            isa<GlobalVariable>(SI->getOperand(1))))
206         continue;
207
208       // If we have alias analysis and it says the store won't modify the loaded
209       // value, ignore the store.
210       if (AA &&
211           (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
212         continue;
213
214       // Otherwise the store that may or may not alias the pointer, bail out.
215       ++ScanFrom;
216       return nullptr;
217     }
218
219     // If this is some other instruction that may clobber Ptr, bail out.
220     if (Inst->mayWriteToMemory()) {
221       // If alias analysis claims that it really won't modify the load,
222       // ignore it.
223       if (AA &&
224           (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
225         continue;
226
227       // May modify the pointer, bail out.
228       ++ScanFrom;
229       return nullptr;
230     }
231   }
232
233   // Got to the start of the block, we didn't find it, but are done for this
234   // block.
235   return nullptr;
236 }