Loads.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. #include "llvm/Analysis/Loads.h"
  14. #include "llvm/Analysis/AliasAnalysis.h"
  15. #include "llvm/Analysis/ValueTracking.h"
  16. #include "llvm/IR/DataLayout.h"
  17. #include "llvm/IR/GlobalAlias.h"
  18. #include "llvm/IR/GlobalVariable.h"
  19. #include "llvm/IR/IntrinsicInst.h"
  20. #include "llvm/IR/LLVMContext.h"
  21. #include "llvm/IR/Module.h"
  22. #include "llvm/IR/Operator.h"
  23. using namespace llvm;
  24. /// \brief Test if A and B will obviously have the same value.
  25. ///
  26. /// This includes recognizing that %t0 and %t1 will have the same
  27. /// value in code like this:
  28. /// \code
  29. /// %t0 = getelementptr \@a, 0, 3
  30. /// store i32 0, i32* %t0
  31. /// %t1 = getelementptr \@a, 0, 3
  32. /// %t2 = load i32* %t1
  33. /// \endcode
  34. ///
  35. static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
  36. // Test if the values are trivially equivalent.
  37. if (A == B)
  38. return true;
  39. // Test if the values come from identical arithmetic instructions.
  40. // Use isIdenticalToWhenDefined instead of isIdenticalTo because
  41. // this function is only used when one address use dominates the
  42. // other, which means that they'll always either have the same
  43. // value or one of them will have an undefined value.
  44. if (isa<BinaryOperator>(A) || isa<CastInst>(A) || isa<PHINode>(A) ||
  45. isa<GetElementPtrInst>(A))
  46. if (const Instruction *BI = dyn_cast<Instruction>(B))
  47. if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
  48. return true;
  49. // Otherwise they may not be equivalent.
  50. return false;
  51. }
  52. /// \brief Check if executing a load of this pointer value cannot trap.
  53. ///
  54. /// If it is not obviously safe to load from the specified pointer, we do
  55. /// a quick local scan of the basic block containing \c ScanFrom, to determine
  56. /// if the address is already accessed.
  57. ///
  58. /// This uses the pointee type to determine how many bytes need to be safe to
  59. /// load from the pointer.
  60. bool llvm::isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom,
  61. unsigned Align) {
  62. const DataLayout &DL = ScanFrom->getModule()->getDataLayout();
  63. // Zero alignment means that the load has the ABI alignment for the target
  64. if (Align == 0)
  65. Align = DL.getABITypeAlignment(V->getType()->getPointerElementType());
  66. assert(isPowerOf2_32(Align));
  67. int64_t ByteOffset = 0;
  68. Value *Base = V;
  69. Base = GetPointerBaseWithConstantOffset(V, ByteOffset, DL);
  70. if (ByteOffset < 0) // out of bounds
  71. return false;
  72. Type *BaseType = nullptr;
  73. unsigned BaseAlign = 0;
  74. if (const AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
  75. // An alloca is safe to load from as load as it is suitably aligned.
  76. BaseType = AI->getAllocatedType();
  77. BaseAlign = AI->getAlignment();
  78. } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
  79. // Global variables are not necessarily safe to load from if they are
  80. // overridden. Their size may change or they may be weak and require a test
  81. // to determine if they were in fact provided.
  82. if (!GV->mayBeOverridden()) {
  83. BaseType = GV->getType()->getElementType();
  84. BaseAlign = GV->getAlignment();
  85. }
  86. }
  87. PointerType *AddrTy = cast<PointerType>(V->getType());
  88. uint64_t LoadSize = DL.getTypeStoreSize(AddrTy->getElementType());
  89. // If we found a base allocated type from either an alloca or global variable,
  90. // try to see if we are definitively within the allocated region. We need to
  91. // know the size of the base type and the loaded type to do anything in this
  92. // case.
  93. if (BaseType && BaseType->isSized()) {
  94. if (BaseAlign == 0)
  95. BaseAlign = DL.getPrefTypeAlignment(BaseType);
  96. if (Align <= BaseAlign) {
  97. // Check if the load is within the bounds of the underlying object.
  98. if (ByteOffset + LoadSize <= DL.getTypeAllocSize(BaseType) &&
  99. ((ByteOffset % Align) == 0))
  100. return true;
  101. }
  102. }
  103. // Otherwise, be a little bit aggressive by scanning the local block where we
  104. // want to check to see if the pointer is already being loaded or stored
  105. // from/to. If so, the previous load or store would have already trapped,
  106. // so there is no harm doing an extra load (also, CSE will later eliminate
  107. // the load entirely).
  108. BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
  109. // We can at least always strip pointer casts even though we can't use the
  110. // base here.
  111. V = V->stripPointerCasts();
  112. while (BBI != E) {
  113. --BBI;
  114. // If we see a free or a call which may write to memory (i.e. which might do
  115. // a free) the pointer could be marked invalid.
  116. if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
  117. !isa<DbgInfoIntrinsic>(BBI))
  118. return false;
  119. Value *AccessedPtr;
  120. unsigned AccessedAlign;
  121. if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
  122. AccessedPtr = LI->getPointerOperand();
  123. AccessedAlign = LI->getAlignment();
  124. } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
  125. AccessedPtr = SI->getPointerOperand();
  126. AccessedAlign = SI->getAlignment();
  127. } else
  128. continue;
  129. Type *AccessedTy = AccessedPtr->getType()->getPointerElementType();
  130. if (AccessedAlign == 0)
  131. AccessedAlign = DL.getABITypeAlignment(AccessedTy);
  132. if (AccessedAlign < Align)
  133. continue;
  134. // Handle trivial cases.
  135. if (AccessedPtr == V)
  136. return true;
  137. if (AreEquivalentAddressValues(AccessedPtr->stripPointerCasts(), V) &&
  138. LoadSize <= DL.getTypeStoreSize(AccessedTy))
  139. return true;
  140. }
  141. return false;
  142. }
  143. /// \brief Scan the ScanBB block backwards to see if we have the value at the
  144. /// memory address *Ptr locally available within a small number of instructions.
  145. ///
  146. /// The scan starts from \c ScanFrom. \c MaxInstsToScan specifies the maximum
  147. /// instructions to scan in the block. If it is set to \c 0, it will scan the whole
  148. /// block.
  149. ///
  150. /// If the value is available, this function returns it. If not, it returns the
  151. /// iterator for the last validated instruction that the value would be live
  152. /// through. If we scanned the entire block and didn't find something that
  153. /// invalidates \c *Ptr or provides it, \c ScanFrom is left at the last
  154. /// instruction processed and this returns null.
  155. ///
  156. /// You can also optionally specify an alias analysis implementation, which
  157. /// makes this more precise.
  158. ///
  159. /// If \c AATags is non-null and a load or store is found, the AA tags from the
  160. /// load or store are recorded there. If there are no AA tags or if no access is
  161. /// found, it is left unmodified.
  162. Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
  163. BasicBlock::iterator &ScanFrom,
  164. unsigned MaxInstsToScan,
  165. AliasAnalysis *AA, AAMDNodes *AATags) {
  166. if (MaxInstsToScan == 0)
  167. MaxInstsToScan = ~0U;
  168. Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
  169. const DataLayout &DL = ScanBB->getModule()->getDataLayout();
  170. // Try to get the store size for the type.
  171. uint64_t AccessSize = DL.getTypeStoreSize(AccessTy);
  172. Value *StrippedPtr = Ptr->stripPointerCasts();
  173. while (ScanFrom != ScanBB->begin()) {
  174. // We must ignore debug info directives when counting (otherwise they
  175. // would affect codegen).
  176. Instruction *Inst = --ScanFrom;
  177. if (isa<DbgInfoIntrinsic>(Inst))
  178. continue;
  179. // Restore ScanFrom to expected value in case next test succeeds
  180. ScanFrom++;
  181. // Don't scan huge blocks.
  182. if (MaxInstsToScan-- == 0)
  183. return nullptr;
  184. --ScanFrom;
  185. // If this is a load of Ptr, the loaded value is available.
  186. // (This is true even if the load is volatile or atomic, although
  187. // those cases are unlikely.)
  188. if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
  189. if (AreEquivalentAddressValues(
  190. LI->getPointerOperand()->stripPointerCasts(), StrippedPtr) &&
  191. CastInst::isBitOrNoopPointerCastable(LI->getType(), AccessTy, DL)) {
  192. if (AATags)
  193. LI->getAAMetadata(*AATags);
  194. return LI;
  195. }
  196. if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
  197. Value *StorePtr = SI->getPointerOperand()->stripPointerCasts();
  198. // If this is a store through Ptr, the value is available!
  199. // (This is true even if the store is volatile or atomic, although
  200. // those cases are unlikely.)
  201. if (AreEquivalentAddressValues(StorePtr, StrippedPtr) &&
  202. CastInst::isBitOrNoopPointerCastable(SI->getValueOperand()->getType(),
  203. AccessTy, DL)) {
  204. if (AATags)
  205. SI->getAAMetadata(*AATags);
  206. return SI->getOperand(0);
  207. }
  208. // If both StrippedPtr and StorePtr reach all the way to an alloca or
  209. // global and they are different, ignore the store. This is a trivial form
  210. // of alias analysis that is important for reg2mem'd code.
  211. if ((isa<AllocaInst>(StrippedPtr) || isa<GlobalVariable>(StrippedPtr)) &&
  212. (isa<AllocaInst>(StorePtr) || isa<GlobalVariable>(StorePtr)) &&
  213. StrippedPtr != StorePtr)
  214. continue;
  215. // If we have alias analysis and it says the store won't modify the loaded
  216. // value, ignore the store.
  217. if (AA &&
  218. (AA->getModRefInfo(SI, StrippedPtr, AccessSize) &
  219. AliasAnalysis::Mod) == 0)
  220. continue;
  221. // Otherwise the store that may or may not alias the pointer, bail out.
  222. ++ScanFrom;
  223. return nullptr;
  224. }
  225. // If this is some other instruction that may clobber Ptr, bail out.
  226. if (Inst->mayWriteToMemory()) {
  227. // If alias analysis claims that it really won't modify the load,
  228. // ignore it.
  229. if (AA &&
  230. (AA->getModRefInfo(Inst, StrippedPtr, AccessSize) &
  231. AliasAnalysis::Mod) == 0)
  232. continue;
  233. // May modify the pointer, bail out.
  234. ++ScanFrom;
  235. return nullptr;
  236. }
  237. }
  238. // Got to the start of the block, we didn't find it, but are done for this
  239. // block.
  240. return nullptr;
  241. }