Clean up doxygen syntax and reword comments to flow better, have a brief
[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) return true;
39
40   // Test if the values come from identical arithmetic instructions.
41   // Use isIdenticalToWhenDefined instead of isIdenticalTo because
42   // this function is only used when one address use dominates the
43   // other, which means that they'll always either have the same
44   // value or one of them will have an undefined value.
45   if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||
46       isa<PHINode>(A) || isa<GetElementPtrInst>(A))
47     if (const Instruction *BI = dyn_cast<Instruction>(B))
48       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
49         return true;
50
51   // Otherwise they may not be equivalent.
52   return false;
53 }
54
55 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
56 /// from this value cannot trap.  If it is not obviously safe to load from the
57 /// specified pointer, we do a quick local scan of the basic block containing
58 /// ScanFrom, to determine if the address is already accessed.
59 bool llvm::isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom,
60                                        unsigned Align, const DataLayout *TD) {
61   int64_t ByteOffset = 0;
62   Value *Base = V;
63   Base = GetPointerBaseWithConstantOffset(V, ByteOffset, TD);
64
65   if (ByteOffset < 0) // out of bounds
66     return false;
67
68   Type *BaseType = nullptr;
69   unsigned BaseAlign = 0;
70   if (const AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
71     // An alloca is safe to load from as load as it is suitably aligned.
72     BaseType = AI->getAllocatedType();
73     BaseAlign = AI->getAlignment();
74   } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
75     // Global variables are safe to load from but their size cannot be
76     // guaranteed if they are overridden.
77     if (!GV->mayBeOverridden()) {
78       BaseType = GV->getType()->getElementType();
79       BaseAlign = GV->getAlignment();
80     }
81   }
82
83   if (BaseType && BaseType->isSized()) {
84     if (TD && BaseAlign == 0)
85       BaseAlign = TD->getPrefTypeAlignment(BaseType);
86
87     if (Align <= BaseAlign) {
88       if (!TD)
89         return true; // Loading directly from an alloca or global is OK.
90
91       // Check if the load is within the bounds of the underlying object.
92       PointerType *AddrTy = cast<PointerType>(V->getType());
93       uint64_t LoadSize = TD->getTypeStoreSize(AddrTy->getElementType());
94       if (ByteOffset + LoadSize <= TD->getTypeAllocSize(BaseType) &&
95           (Align == 0 || (ByteOffset % Align) == 0))
96         return true;
97     }
98   }
99
100   // Otherwise, be a little bit aggressive by scanning the local block where we
101   // want to check to see if the pointer is already being loaded or stored
102   // from/to.  If so, the previous load or store would have already trapped,
103   // so there is no harm doing an extra load (also, CSE will later eliminate
104   // the load entirely).
105   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
106
107   while (BBI != E) {
108     --BBI;
109
110     // If we see a free or a call which may write to memory (i.e. which might do
111     // a free) the pointer could be marked invalid.
112     if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
113         !isa<DbgInfoIntrinsic>(BBI))
114       return false;
115
116     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
117       if (AreEquivalentAddressValues(LI->getOperand(0), V)) return true;
118     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
119       if (AreEquivalentAddressValues(SI->getOperand(1), V)) return true;
120     }
121   }
122   return false;
123 }
124
125 /// \brief Scan the ScanBB block backwards to see if we have the value at the
126 /// memory address *Ptr locally available within a small number of instructions.
127 ///
128 /// The scan starts from \c ScanFrom. \c MaxInstsToScan specifies the maximum
129 /// instructions to scan in the block. If it is set to \c 0, it will scan the whole
130 /// block.
131 ///
132 /// If the value is available, this function returns it. If not, it returns the
133 /// iterator for the last validated instruction that the value would be live
134 /// through. If we scanned the entire block and didn't find something that
135 /// invalidates \c *Ptr or provides it, \c ScanFrom is left at the last
136 /// instruction processed and this returns null.
137 ///
138 /// You can also optionally specify an alias analysis implementation, which
139 /// makes this more precise.
140 ///
141 /// If \c AATags is non-null and a load or store is found, the AA tags from the
142 /// load or store are recorded there. If there are no AA tags or if no access is
143 /// found, it is left unmodified.
144 Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
145                                       BasicBlock::iterator &ScanFrom,
146                                       unsigned MaxInstsToScan,
147                                       AliasAnalysis *AA, AAMDNodes *AATags) {
148   if (MaxInstsToScan == 0)
149     MaxInstsToScan = ~0U;
150
151   // If we're using alias analysis to disambiguate get the size of *Ptr.
152   uint64_t AccessSize = 0;
153   if (AA) {
154     Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
155     AccessSize = AA->getTypeStoreSize(AccessTy);
156   }
157
158   while (ScanFrom != ScanBB->begin()) {
159     // We must ignore debug info directives when counting (otherwise they
160     // would affect codegen).
161     Instruction *Inst = --ScanFrom;
162     if (isa<DbgInfoIntrinsic>(Inst))
163       continue;
164
165     // Restore ScanFrom to expected value in case next test succeeds
166     ScanFrom++;
167
168     // Don't scan huge blocks.
169     if (MaxInstsToScan-- == 0)
170       return nullptr;
171
172     --ScanFrom;
173     // If this is a load of Ptr, the loaded value is available.
174     // (This is true even if the load is volatile or atomic, although
175     // those cases are unlikely.)
176     if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
177       if (AreEquivalentAddressValues(LI->getOperand(0), Ptr)) {
178         if (AATags)
179           LI->getAAMetadata(*AATags);
180         return LI;
181       }
182
183     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
184       // If this is a store through Ptr, the value is available!
185       // (This is true even if the store is volatile or atomic, although
186       // those cases are unlikely.)
187       if (AreEquivalentAddressValues(SI->getOperand(1), Ptr)) {
188         if (AATags)
189           SI->getAAMetadata(*AATags);
190         return SI->getOperand(0);
191       }
192
193       // If Ptr is an alloca and this is a store to a different alloca, ignore
194       // the store.  This is a trivial form of alias analysis that is important
195       // for reg2mem'd code.
196       if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
197           (isa<AllocaInst>(SI->getOperand(1)) ||
198            isa<GlobalVariable>(SI->getOperand(1))))
199         continue;
200
201       // If we have alias analysis and it says the store won't modify the loaded
202       // value, ignore the store.
203       if (AA &&
204           (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
205         continue;
206
207       // Otherwise the store that may or may not alias the pointer, bail out.
208       ++ScanFrom;
209       return nullptr;
210     }
211
212     // If this is some other instruction that may clobber Ptr, bail out.
213     if (Inst->mayWriteToMemory()) {
214       // If alias analysis claims that it really won't modify the load,
215       // ignore it.
216       if (AA &&
217           (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
218         continue;
219
220       // May modify the pointer, bail out.
221       ++ScanFrom;
222       return nullptr;
223     }
224   }
225
226   // Got to the start of the block, we didn't find it, but are done for this
227   // block.
228   return nullptr;
229 }