LLVM  3.7.0
Loads.cpp
Go to the documentation of this file.
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"
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/Module.h"
23 #include "llvm/IR/Operator.h"
24 using namespace llvm;
25 
26 /// \brief Test if A and B will obviously have the same value.
27 ///
28 /// This includes recognizing that %t0 and %t1 will have the same
29 /// value in code like this:
30 /// \code
31 /// %t0 = getelementptr \@a, 0, 3
32 /// store i32 0, i32* %t0
33 /// %t1 = getelementptr \@a, 0, 3
34 /// %t2 = load i32* %t1
35 /// \endcode
36 ///
37 static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
38  // Test if the values are trivially equivalent.
39  if (A == B)
40  return true;
41 
42  // Test if the values come from identical arithmetic instructions.
43  // Use isIdenticalToWhenDefined instead of isIdenticalTo because
44  // this function is only used when one address use dominates the
45  // other, which means that they'll always either have the same
46  // value or one of them will have an undefined value.
47  if (isa<BinaryOperator>(A) || isa<CastInst>(A) || isa<PHINode>(A) ||
48  isa<GetElementPtrInst>(A))
49  if (const Instruction *BI = dyn_cast<Instruction>(B))
50  if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
51  return true;
52 
53  // Otherwise they may not be equivalent.
54  return false;
55 }
56 
57 /// \brief Check if executing a load of this pointer value cannot trap.
58 ///
59 /// If it is not obviously safe to load from the specified pointer, we do
60 /// a quick local scan of the basic block containing \c ScanFrom, to determine
61 /// if the address is already accessed.
62 ///
63 /// This uses the pointee type to determine how many bytes need to be safe to
64 /// load from the pointer.
66  unsigned Align) {
67  const DataLayout &DL = ScanFrom->getModule()->getDataLayout();
68 
69  // Zero alignment means that the load has the ABI alignment for the target
70  if (Align == 0)
72  assert(isPowerOf2_32(Align));
73 
74  int64_t ByteOffset = 0;
75  Value *Base = V;
76  Base = GetPointerBaseWithConstantOffset(V, ByteOffset, DL);
77 
78  if (ByteOffset < 0) // out of bounds
79  return false;
80 
81  Type *BaseType = nullptr;
82  unsigned BaseAlign = 0;
83  if (const AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
84  // An alloca is safe to load from as load as it is suitably aligned.
85  BaseType = AI->getAllocatedType();
86  BaseAlign = AI->getAlignment();
87  } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
88  // Global variables are not necessarily safe to load from if they are
89  // overridden. Their size may change or they may be weak and require a test
90  // to determine if they were in fact provided.
91  if (!GV->mayBeOverridden()) {
92  BaseType = GV->getType()->getElementType();
93  BaseAlign = GV->getAlignment();
94  }
95  }
96 
97  PointerType *AddrTy = cast<PointerType>(V->getType());
98  uint64_t LoadSize = DL.getTypeStoreSize(AddrTy->getElementType());
99 
100  // If we found a base allocated type from either an alloca or global variable,
101  // try to see if we are definitively within the allocated region. We need to
102  // know the size of the base type and the loaded type to do anything in this
103  // case.
104  if (BaseType && BaseType->isSized()) {
105  if (BaseAlign == 0)
106  BaseAlign = DL.getPrefTypeAlignment(BaseType);
107 
108  if (Align <= BaseAlign) {
109  // Check if the load is within the bounds of the underlying object.
110  if (ByteOffset + LoadSize <= DL.getTypeAllocSize(BaseType) &&
111  ((ByteOffset % Align) == 0))
112  return true;
113  }
114  }
115 
116  // Otherwise, be a little bit aggressive by scanning the local block where we
117  // want to check to see if the pointer is already being loaded or stored
118  // from/to. If so, the previous load or store would have already trapped,
119  // so there is no harm doing an extra load (also, CSE will later eliminate
120  // the load entirely).
121  BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
122 
123  // We can at least always strip pointer casts even though we can't use the
124  // base here.
125  V = V->stripPointerCasts();
126 
127  while (BBI != E) {
128  --BBI;
129 
130  // If we see a free or a call which may write to memory (i.e. which might do
131  // a free) the pointer could be marked invalid.
132  if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
133  !isa<DbgInfoIntrinsic>(BBI))
134  return false;
135 
136  Value *AccessedPtr;
137  unsigned AccessedAlign;
138  if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
139  AccessedPtr = LI->getPointerOperand();
140  AccessedAlign = LI->getAlignment();
141  } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
142  AccessedPtr = SI->getPointerOperand();
143  AccessedAlign = SI->getAlignment();
144  } else
145  continue;
146 
147  Type *AccessedTy = AccessedPtr->getType()->getPointerElementType();
148  if (AccessedAlign == 0)
149  AccessedAlign = DL.getABITypeAlignment(AccessedTy);
150  if (AccessedAlign < Align)
151  continue;
152 
153  // Handle trivial cases.
154  if (AccessedPtr == V)
155  return true;
156 
157  if (AreEquivalentAddressValues(AccessedPtr->stripPointerCasts(), V) &&
158  LoadSize <= DL.getTypeStoreSize(AccessedTy))
159  return true;
160  }
161  return false;
162 }
163 
164 /// \brief Scan the ScanBB block backwards to see if we have the value at the
165 /// memory address *Ptr locally available within a small number of instructions.
166 ///
167 /// The scan starts from \c ScanFrom. \c MaxInstsToScan specifies the maximum
168 /// instructions to scan in the block. If it is set to \c 0, it will scan the whole
169 /// block.
170 ///
171 /// If the value is available, this function returns it. If not, it returns the
172 /// iterator for the last validated instruction that the value would be live
173 /// through. If we scanned the entire block and didn't find something that
174 /// invalidates \c *Ptr or provides it, \c ScanFrom is left at the last
175 /// instruction processed and this returns null.
176 ///
177 /// You can also optionally specify an alias analysis implementation, which
178 /// makes this more precise.
179 ///
180 /// If \c AATags is non-null and a load or store is found, the AA tags from the
181 /// load or store are recorded there. If there are no AA tags or if no access is
182 /// found, it is left unmodified.
184  BasicBlock::iterator &ScanFrom,
185  unsigned MaxInstsToScan,
186  AliasAnalysis *AA, AAMDNodes *AATags) {
187  if (MaxInstsToScan == 0)
188  MaxInstsToScan = ~0U;
189 
190  Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
191 
192  const DataLayout &DL = ScanBB->getModule()->getDataLayout();
193 
194  // Try to get the store size for the type.
195  uint64_t AccessSize = DL.getTypeStoreSize(AccessTy);
196 
197  Value *StrippedPtr = Ptr->stripPointerCasts();
198 
199  while (ScanFrom != ScanBB->begin()) {
200  // We must ignore debug info directives when counting (otherwise they
201  // would affect codegen).
202  Instruction *Inst = --ScanFrom;
203  if (isa<DbgInfoIntrinsic>(Inst))
204  continue;
205 
206  // Restore ScanFrom to expected value in case next test succeeds
207  ScanFrom++;
208 
209  // Don't scan huge blocks.
210  if (MaxInstsToScan-- == 0)
211  return nullptr;
212 
213  --ScanFrom;
214  // If this is a load of Ptr, the loaded value is available.
215  // (This is true even if the load is volatile or atomic, although
216  // those cases are unlikely.)
217  if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
219  LI->getPointerOperand()->stripPointerCasts(), StrippedPtr) &&
220  CastInst::isBitOrNoopPointerCastable(LI->getType(), AccessTy, DL)) {
221  if (AATags)
222  LI->getAAMetadata(*AATags);
223  return LI;
224  }
225 
226  if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
227  Value *StorePtr = SI->getPointerOperand()->stripPointerCasts();
228  // If this is a store through Ptr, the value is available!
229  // (This is true even if the store is volatile or atomic, although
230  // those cases are unlikely.)
231  if (AreEquivalentAddressValues(StorePtr, StrippedPtr) &&
232  CastInst::isBitOrNoopPointerCastable(SI->getValueOperand()->getType(),
233  AccessTy, DL)) {
234  if (AATags)
235  SI->getAAMetadata(*AATags);
236  return SI->getOperand(0);
237  }
238 
239  // If both StrippedPtr and StorePtr reach all the way to an alloca or
240  // global and they are different, ignore the store. This is a trivial form
241  // of alias analysis that is important for reg2mem'd code.
242  if ((isa<AllocaInst>(StrippedPtr) || isa<GlobalVariable>(StrippedPtr)) &&
243  (isa<AllocaInst>(StorePtr) || isa<GlobalVariable>(StorePtr)) &&
244  StrippedPtr != StorePtr)
245  continue;
246 
247  // If we have alias analysis and it says the store won't modify the loaded
248  // value, ignore the store.
249  if (AA &&
250  (AA->getModRefInfo(SI, StrippedPtr, AccessSize) &
251  AliasAnalysis::Mod) == 0)
252  continue;
253 
254  // Otherwise the store that may or may not alias the pointer, bail out.
255  ++ScanFrom;
256  return nullptr;
257  }
258 
259  // If this is some other instruction that may clobber Ptr, bail out.
260  if (Inst->mayWriteToMemory()) {
261  // If alias analysis claims that it really won't modify the load,
262  // ignore it.
263  if (AA &&
264  (AA->getModRefInfo(Inst, StrippedPtr, AccessSize) &
265  AliasAnalysis::Mod) == 0)
266  continue;
267 
268  // May modify the pointer, bail out.
269  ++ScanFrom;
270  return nullptr;
271  }
272  }
273 
274  // Got to the start of the block, we didn't find it, but are done for this
275  // block.
276  return nullptr;
277 }
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:104
unsigned getPrefTypeAlignment(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
Definition: DataLayout.cpp:684
LoadInst - an instruction for reading from memory.
Definition: Instructions.h:177
Type * getPointerElementType() const
Definition: Type.h:366
static bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op...
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:231
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr it the function does no...
Definition: BasicBlock.cpp:116
bool isSized(SmallPtrSetImpl< const Type * > *Visited=nullptr) const
isSized - Return true if it makes sense to take the size of this type.
Definition: Type.h:268
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL)
GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if it can be expressed as a b...
StoreInst - an instruction for storing to memory.
Definition: Instructions.h:316
Type * getElementType() const
Definition: DerivedTypes.h:323
PointerType - Class to represent pointers.
Definition: DerivedTypes.h:449
LLVM Basic Block Representation.
Definition: BasicBlock.h:65
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
bool mayWriteToMemory() const
mayWriteToMemory - Return true if this instruction may modify memory.
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
Definition: DataLayout.cpp:674
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:388
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:57
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:222
ModRefResult getModRefInfo(const Instruction *I)
getModRefInfo - Return information about whether or not an instruction may read or write memory (with...
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition: Metadata.h:548
Value * stripPointerCasts()
Strip off pointer casts, all-zero GEPs, and aliases.
Definition: Value.cpp:458
static cl::opt< AlignMode > Align(cl::desc("Load/store alignment support"), cl::Hidden, cl::init(NoStrictAlign), cl::values(clEnumValN(StrictAlign,"aarch64-strict-align","Disallow all unaligned memory accesses"), clEnumValN(NoStrictAlign,"aarch64-no-strict-align","Allow unaligned memory accesses"), clEnumValEnd))
static bool AreEquivalentAddressValues(const Value *A, const Value *B)
Test if A and B will obviously have the same value.
Definition: Loads.cpp:37
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.cpp:372
uint64_t getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
Definition: DataLayout.h:371
Value * FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan=6, AliasAnalysis *AA=nullptr, AAMDNodes *AATags=nullptr)
FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the instruction before ScanFr...
Definition: Loads.cpp:183
LLVM Value Representation.
Definition: Value.h:69
bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom, unsigned Align)
isSafeToLoadUnconditionally - Return true if we know that executing a load from this value cannot tra...
Definition: Loads.cpp:65
bool isPowerOf2_32(uint32_t Value)
isPowerOf2_32 - This function returns true if the argument is a power of two > 0. ...
Definition: MathExtras.h:354
const BasicBlock * getParent() const
Definition: Instruction.h:72
AllocaInst - an instruction to allocate memory on the stack.
Definition: Instructions.h:76