VNCoercion.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. #include "llvm/Transforms/Utils/VNCoercion.h"
  2. #include "llvm/Analysis/ConstantFolding.h"
  3. #include "llvm/Analysis/ValueTracking.h"
  4. #include "llvm/IR/IRBuilder.h"
  5. #include "llvm/Support/Debug.h"
  6. #define DEBUG_TYPE "vncoerce"
  7. namespace llvm {
  8. namespace VNCoercion {
  9. static bool isFirstClassAggregateOrScalableType(Type *Ty) {
  10. return Ty->isStructTy() || Ty->isArrayTy() || isa<ScalableVectorType>(Ty);
  11. }
  12. /// Return true if coerceAvailableValueToLoadType will succeed.
  13. bool canCoerceMustAliasedValueToLoad(Value *StoredVal, Type *LoadTy,
  14. const DataLayout &DL) {
  15. Type *StoredTy = StoredVal->getType();
  16. if (StoredTy == LoadTy)
  17. return true;
  18. // If the loaded/stored value is a first class array/struct, or scalable type,
  19. // don't try to transform them. We need to be able to bitcast to integer.
  20. if (isFirstClassAggregateOrScalableType(LoadTy) ||
  21. isFirstClassAggregateOrScalableType(StoredTy))
  22. return false;
  23. uint64_t StoreSize = DL.getTypeSizeInBits(StoredTy).getFixedSize();
  24. // The store size must be byte-aligned to support future type casts.
  25. if (llvm::alignTo(StoreSize, 8) != StoreSize)
  26. return false;
  27. // The store has to be at least as big as the load.
  28. if (StoreSize < DL.getTypeSizeInBits(LoadTy).getFixedSize())
  29. return false;
  30. bool StoredNI = DL.isNonIntegralPointerType(StoredTy->getScalarType());
  31. bool LoadNI = DL.isNonIntegralPointerType(LoadTy->getScalarType());
  32. // Don't coerce non-integral pointers to integers or vice versa.
  33. if (StoredNI != LoadNI) {
  34. // As a special case, allow coercion of memset used to initialize
  35. // an array w/null. Despite non-integral pointers not generally having a
  36. // specific bit pattern, we do assume null is zero.
  37. if (auto *CI = dyn_cast<Constant>(StoredVal))
  38. return CI->isNullValue();
  39. return false;
  40. } else if (StoredNI && LoadNI &&
  41. StoredTy->getPointerAddressSpace() !=
  42. LoadTy->getPointerAddressSpace()) {
  43. return false;
  44. }
  45. // The implementation below uses inttoptr for vectors of unequal size; we
  46. // can't allow this for non integral pointers. We could teach it to extract
  47. // exact subvectors if desired.
  48. if (StoredNI && StoreSize != DL.getTypeSizeInBits(LoadTy).getFixedSize())
  49. return false;
  50. return true;
  51. }
  52. template <class T, class HelperClass>
  53. static T *coerceAvailableValueToLoadTypeHelper(T *StoredVal, Type *LoadedTy,
  54. HelperClass &Helper,
  55. const DataLayout &DL) {
  56. assert(canCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, DL) &&
  57. "precondition violation - materialization can't fail");
  58. if (auto *C = dyn_cast<Constant>(StoredVal))
  59. StoredVal = ConstantFoldConstant(C, DL);
  60. // If this is already the right type, just return it.
  61. Type *StoredValTy = StoredVal->getType();
  62. uint64_t StoredValSize = DL.getTypeSizeInBits(StoredValTy).getFixedSize();
  63. uint64_t LoadedValSize = DL.getTypeSizeInBits(LoadedTy).getFixedSize();
  64. // If the store and reload are the same size, we can always reuse it.
  65. if (StoredValSize == LoadedValSize) {
  66. // Pointer to Pointer -> use bitcast.
  67. if (StoredValTy->isPtrOrPtrVectorTy() && LoadedTy->isPtrOrPtrVectorTy()) {
  68. StoredVal = Helper.CreateBitCast(StoredVal, LoadedTy);
  69. } else {
  70. // Convert source pointers to integers, which can be bitcast.
  71. if (StoredValTy->isPtrOrPtrVectorTy()) {
  72. StoredValTy = DL.getIntPtrType(StoredValTy);
  73. StoredVal = Helper.CreatePtrToInt(StoredVal, StoredValTy);
  74. }
  75. Type *TypeToCastTo = LoadedTy;
  76. if (TypeToCastTo->isPtrOrPtrVectorTy())
  77. TypeToCastTo = DL.getIntPtrType(TypeToCastTo);
  78. if (StoredValTy != TypeToCastTo)
  79. StoredVal = Helper.CreateBitCast(StoredVal, TypeToCastTo);
  80. // Cast to pointer if the load needs a pointer type.
  81. if (LoadedTy->isPtrOrPtrVectorTy())
  82. StoredVal = Helper.CreateIntToPtr(StoredVal, LoadedTy);
  83. }
  84. if (auto *C = dyn_cast<ConstantExpr>(StoredVal))
  85. StoredVal = ConstantFoldConstant(C, DL);
  86. return StoredVal;
  87. }
  88. // If the loaded value is smaller than the available value, then we can
  89. // extract out a piece from it. If the available value is too small, then we
  90. // can't do anything.
  91. assert(StoredValSize >= LoadedValSize &&
  92. "canCoerceMustAliasedValueToLoad fail");
  93. // Convert source pointers to integers, which can be manipulated.
  94. if (StoredValTy->isPtrOrPtrVectorTy()) {
  95. StoredValTy = DL.getIntPtrType(StoredValTy);
  96. StoredVal = Helper.CreatePtrToInt(StoredVal, StoredValTy);
  97. }
  98. // Convert vectors and fp to integer, which can be manipulated.
  99. if (!StoredValTy->isIntegerTy()) {
  100. StoredValTy = IntegerType::get(StoredValTy->getContext(), StoredValSize);
  101. StoredVal = Helper.CreateBitCast(StoredVal, StoredValTy);
  102. }
  103. // If this is a big-endian system, we need to shift the value down to the low
  104. // bits so that a truncate will work.
  105. if (DL.isBigEndian()) {
  106. uint64_t ShiftAmt = DL.getTypeStoreSizeInBits(StoredValTy).getFixedSize() -
  107. DL.getTypeStoreSizeInBits(LoadedTy).getFixedSize();
  108. StoredVal = Helper.CreateLShr(
  109. StoredVal, ConstantInt::get(StoredVal->getType(), ShiftAmt));
  110. }
  111. // Truncate the integer to the right size now.
  112. Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadedValSize);
  113. StoredVal = Helper.CreateTruncOrBitCast(StoredVal, NewIntTy);
  114. if (LoadedTy != NewIntTy) {
  115. // If the result is a pointer, inttoptr.
  116. if (LoadedTy->isPtrOrPtrVectorTy())
  117. StoredVal = Helper.CreateIntToPtr(StoredVal, LoadedTy);
  118. else
  119. // Otherwise, bitcast.
  120. StoredVal = Helper.CreateBitCast(StoredVal, LoadedTy);
  121. }
  122. if (auto *C = dyn_cast<Constant>(StoredVal))
  123. StoredVal = ConstantFoldConstant(C, DL);
  124. return StoredVal;
  125. }
  126. /// If we saw a store of a value to memory, and
  127. /// then a load from a must-aliased pointer of a different type, try to coerce
  128. /// the stored value. LoadedTy is the type of the load we want to replace.
  129. /// IRB is IRBuilder used to insert new instructions.
  130. ///
  131. /// If we can't do it, return null.
  132. Value *coerceAvailableValueToLoadType(Value *StoredVal, Type *LoadedTy,
  133. IRBuilderBase &IRB,
  134. const DataLayout &DL) {
  135. return coerceAvailableValueToLoadTypeHelper(StoredVal, LoadedTy, IRB, DL);
  136. }
  137. /// This function is called when we have a memdep query of a load that ends up
  138. /// being a clobbering memory write (store, memset, memcpy, memmove). This
  139. /// means that the write *may* provide bits used by the load but we can't be
  140. /// sure because the pointers don't must-alias.
  141. ///
  142. /// Check this case to see if there is anything more we can do before we give
  143. /// up. This returns -1 if we have to give up, or a byte number in the stored
  144. /// value of the piece that feeds the load.
  145. static int analyzeLoadFromClobberingWrite(Type *LoadTy, Value *LoadPtr,
  146. Value *WritePtr,
  147. uint64_t WriteSizeInBits,
  148. const DataLayout &DL) {
  149. // If the loaded/stored value is a first class array/struct, or scalable type,
  150. // don't try to transform them. We need to be able to bitcast to integer.
  151. if (isFirstClassAggregateOrScalableType(LoadTy))
  152. return -1;
  153. int64_t StoreOffset = 0, LoadOffset = 0;
  154. Value *StoreBase =
  155. GetPointerBaseWithConstantOffset(WritePtr, StoreOffset, DL);
  156. Value *LoadBase = GetPointerBaseWithConstantOffset(LoadPtr, LoadOffset, DL);
  157. if (StoreBase != LoadBase)
  158. return -1;
  159. // If the load and store are to the exact same address, they should have been
  160. // a must alias. AA must have gotten confused.
  161. // FIXME: Study to see if/when this happens. One case is forwarding a memset
  162. // to a load from the base of the memset.
  163. // If the load and store don't overlap at all, the store doesn't provide
  164. // anything to the load. In this case, they really don't alias at all, AA
  165. // must have gotten confused.
  166. uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy).getFixedSize();
  167. if ((WriteSizeInBits & 7) | (LoadSize & 7))
  168. return -1;
  169. uint64_t StoreSize = WriteSizeInBits / 8; // Convert to bytes.
  170. LoadSize /= 8;
  171. bool isAAFailure = false;
  172. if (StoreOffset < LoadOffset)
  173. isAAFailure = StoreOffset + int64_t(StoreSize) <= LoadOffset;
  174. else
  175. isAAFailure = LoadOffset + int64_t(LoadSize) <= StoreOffset;
  176. if (isAAFailure)
  177. return -1;
  178. // If the Load isn't completely contained within the stored bits, we don't
  179. // have all the bits to feed it. We could do something crazy in the future
  180. // (issue a smaller load then merge the bits in) but this seems unlikely to be
  181. // valuable.
  182. if (StoreOffset > LoadOffset ||
  183. StoreOffset + StoreSize < LoadOffset + LoadSize)
  184. return -1;
  185. // Okay, we can do this transformation. Return the number of bytes into the
  186. // store that the load is.
  187. return LoadOffset - StoreOffset;
  188. }
  189. /// This function is called when we have a
  190. /// memdep query of a load that ends up being a clobbering store.
  191. int analyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr,
  192. StoreInst *DepSI, const DataLayout &DL) {
  193. auto *StoredVal = DepSI->getValueOperand();
  194. // Cannot handle reading from store of first-class aggregate or scalable type.
  195. if (isFirstClassAggregateOrScalableType(StoredVal->getType()))
  196. return -1;
  197. if (!canCoerceMustAliasedValueToLoad(StoredVal, LoadTy, DL))
  198. return -1;
  199. Value *StorePtr = DepSI->getPointerOperand();
  200. uint64_t StoreSize =
  201. DL.getTypeSizeInBits(DepSI->getValueOperand()->getType()).getFixedSize();
  202. return analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, StorePtr, StoreSize,
  203. DL);
  204. }
  205. /// Looks at a memory location for a load (specified by MemLocBase, Offs, and
  206. /// Size) and compares it against a load.
  207. ///
  208. /// If the specified load could be safely widened to a larger integer load
  209. /// that is 1) still efficient, 2) safe for the target, and 3) would provide
  210. /// the specified memory location value, then this function returns the size
  211. /// in bytes of the load width to use. If not, this returns zero.
  212. static unsigned getLoadLoadClobberFullWidthSize(const Value *MemLocBase,
  213. int64_t MemLocOffs,
  214. unsigned MemLocSize,
  215. const LoadInst *LI) {
  216. // We can only extend simple integer loads.
  217. if (!isa<IntegerType>(LI->getType()) || !LI->isSimple())
  218. return 0;
  219. // Load widening is hostile to ThreadSanitizer: it may cause false positives
  220. // or make the reports more cryptic (access sizes are wrong).
  221. if (LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
  222. return 0;
  223. const DataLayout &DL = LI->getModule()->getDataLayout();
  224. // Get the base of this load.
  225. int64_t LIOffs = 0;
  226. const Value *LIBase =
  227. GetPointerBaseWithConstantOffset(LI->getPointerOperand(), LIOffs, DL);
  228. // If the two pointers are not based on the same pointer, we can't tell that
  229. // they are related.
  230. if (LIBase != MemLocBase)
  231. return 0;
  232. // Okay, the two values are based on the same pointer, but returned as
  233. // no-alias. This happens when we have things like two byte loads at "P+1"
  234. // and "P+3". Check to see if increasing the size of the "LI" load up to its
  235. // alignment (or the largest native integer type) will allow us to load all
  236. // the bits required by MemLoc.
  237. // If MemLoc is before LI, then no widening of LI will help us out.
  238. if (MemLocOffs < LIOffs)
  239. return 0;
  240. // Get the alignment of the load in bytes. We assume that it is safe to load
  241. // any legal integer up to this size without a problem. For example, if we're
  242. // looking at an i8 load on x86-32 that is known 1024 byte aligned, we can
  243. // widen it up to an i32 load. If it is known 2-byte aligned, we can widen it
  244. // to i16.
  245. unsigned LoadAlign = LI->getAlignment();
  246. int64_t MemLocEnd = MemLocOffs + MemLocSize;
  247. // If no amount of rounding up will let MemLoc fit into LI, then bail out.
  248. if (LIOffs + LoadAlign < MemLocEnd)
  249. return 0;
  250. // This is the size of the load to try. Start with the next larger power of
  251. // two.
  252. unsigned NewLoadByteSize = LI->getType()->getPrimitiveSizeInBits() / 8U;
  253. NewLoadByteSize = NextPowerOf2(NewLoadByteSize);
  254. while (true) {
  255. // If this load size is bigger than our known alignment or would not fit
  256. // into a native integer register, then we fail.
  257. if (NewLoadByteSize > LoadAlign ||
  258. !DL.fitsInLegalInteger(NewLoadByteSize * 8))
  259. return 0;
  260. if (LIOffs + NewLoadByteSize > MemLocEnd &&
  261. (LI->getParent()->getParent()->hasFnAttribute(
  262. Attribute::SanitizeAddress) ||
  263. LI->getParent()->getParent()->hasFnAttribute(
  264. Attribute::SanitizeHWAddress)))
  265. // We will be reading past the location accessed by the original program.
  266. // While this is safe in a regular build, Address Safety analysis tools
  267. // may start reporting false warnings. So, don't do widening.
  268. return 0;
  269. // If a load of this width would include all of MemLoc, then we succeed.
  270. if (LIOffs + NewLoadByteSize >= MemLocEnd)
  271. return NewLoadByteSize;
  272. NewLoadByteSize <<= 1;
  273. }
  274. }
  275. /// This function is called when we have a
  276. /// memdep query of a load that ends up being clobbered by another load. See if
  277. /// the other load can feed into the second load.
  278. int analyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr, LoadInst *DepLI,
  279. const DataLayout &DL) {
  280. // Cannot handle reading from store of first-class aggregate yet.
  281. if (DepLI->getType()->isStructTy() || DepLI->getType()->isArrayTy())
  282. return -1;
  283. if (!canCoerceMustAliasedValueToLoad(DepLI, LoadTy, DL))
  284. return -1;
  285. Value *DepPtr = DepLI->getPointerOperand();
  286. uint64_t DepSize = DL.getTypeSizeInBits(DepLI->getType()).getFixedSize();
  287. int R = analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, DepSize, DL);
  288. if (R != -1)
  289. return R;
  290. // If we have a load/load clobber an DepLI can be widened to cover this load,
  291. // then we should widen it!
  292. int64_t LoadOffs = 0;
  293. const Value *LoadBase =
  294. GetPointerBaseWithConstantOffset(LoadPtr, LoadOffs, DL);
  295. unsigned LoadSize = DL.getTypeStoreSize(LoadTy).getFixedSize();
  296. unsigned Size =
  297. getLoadLoadClobberFullWidthSize(LoadBase, LoadOffs, LoadSize, DepLI);
  298. if (Size == 0)
  299. return -1;
  300. // Check non-obvious conditions enforced by MDA which we rely on for being
  301. // able to materialize this potentially available value
  302. assert(DepLI->isSimple() && "Cannot widen volatile/atomic load!");
  303. assert(DepLI->getType()->isIntegerTy() && "Can't widen non-integer load");
  304. return analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, Size * 8, DL);
  305. }
  306. int analyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr,
  307. MemIntrinsic *MI, const DataLayout &DL) {
  308. // If the mem operation is a non-constant size, we can't handle it.
  309. ConstantInt *SizeCst = dyn_cast<ConstantInt>(MI->getLength());
  310. if (!SizeCst)
  311. return -1;
  312. uint64_t MemSizeInBits = SizeCst->getZExtValue() * 8;
  313. // If this is memset, we just need to see if the offset is valid in the size
  314. // of the memset..
  315. if (MI->getIntrinsicID() == Intrinsic::memset) {
  316. if (DL.isNonIntegralPointerType(LoadTy->getScalarType())) {
  317. auto *CI = dyn_cast<ConstantInt>(cast<MemSetInst>(MI)->getValue());
  318. if (!CI || !CI->isZero())
  319. return -1;
  320. }
  321. return analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
  322. MemSizeInBits, DL);
  323. }
  324. // If we have a memcpy/memmove, the only case we can handle is if this is a
  325. // copy from constant memory. In that case, we can read directly from the
  326. // constant memory.
  327. MemTransferInst *MTI = cast<MemTransferInst>(MI);
  328. Constant *Src = dyn_cast<Constant>(MTI->getSource());
  329. if (!Src)
  330. return -1;
  331. GlobalVariable *GV = dyn_cast<GlobalVariable>(getUnderlyingObject(Src));
  332. if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
  333. return -1;
  334. // See if the access is within the bounds of the transfer.
  335. int Offset = analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
  336. MemSizeInBits, DL);
  337. if (Offset == -1)
  338. return Offset;
  339. unsigned AS = Src->getType()->getPointerAddressSpace();
  340. // Otherwise, see if we can constant fold a load from the constant with the
  341. // offset applied as appropriate.
  342. if (Offset) {
  343. Src = ConstantExpr::getBitCast(Src,
  344. Type::getInt8PtrTy(Src->getContext(), AS));
  345. Constant *OffsetCst =
  346. ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
  347. Src = ConstantExpr::getGetElementPtr(Type::getInt8Ty(Src->getContext()),
  348. Src, OffsetCst);
  349. }
  350. Src = ConstantExpr::getBitCast(Src, PointerType::get(LoadTy, AS));
  351. if (ConstantFoldLoadFromConstPtr(Src, LoadTy, DL))
  352. return Offset;
  353. return -1;
  354. }
  355. template <class T, class HelperClass>
  356. static T *getStoreValueForLoadHelper(T *SrcVal, unsigned Offset, Type *LoadTy,
  357. HelperClass &Helper,
  358. const DataLayout &DL) {
  359. LLVMContext &Ctx = SrcVal->getType()->getContext();
  360. // If two pointers are in the same address space, they have the same size,
  361. // so we don't need to do any truncation, etc. This avoids introducing
  362. // ptrtoint instructions for pointers that may be non-integral.
  363. if (SrcVal->getType()->isPointerTy() && LoadTy->isPointerTy() &&
  364. cast<PointerType>(SrcVal->getType())->getAddressSpace() ==
  365. cast<PointerType>(LoadTy)->getAddressSpace()) {
  366. return SrcVal;
  367. }
  368. uint64_t StoreSize =
  369. (DL.getTypeSizeInBits(SrcVal->getType()).getFixedSize() + 7) / 8;
  370. uint64_t LoadSize = (DL.getTypeSizeInBits(LoadTy).getFixedSize() + 7) / 8;
  371. // Compute which bits of the stored value are being used by the load. Convert
  372. // to an integer type to start with.
  373. if (SrcVal->getType()->isPtrOrPtrVectorTy())
  374. SrcVal = Helper.CreatePtrToInt(SrcVal, DL.getIntPtrType(SrcVal->getType()));
  375. if (!SrcVal->getType()->isIntegerTy())
  376. SrcVal = Helper.CreateBitCast(SrcVal, IntegerType::get(Ctx, StoreSize * 8));
  377. // Shift the bits to the least significant depending on endianness.
  378. unsigned ShiftAmt;
  379. if (DL.isLittleEndian())
  380. ShiftAmt = Offset * 8;
  381. else
  382. ShiftAmt = (StoreSize - LoadSize - Offset) * 8;
  383. if (ShiftAmt)
  384. SrcVal = Helper.CreateLShr(SrcVal,
  385. ConstantInt::get(SrcVal->getType(), ShiftAmt));
  386. if (LoadSize != StoreSize)
  387. SrcVal = Helper.CreateTruncOrBitCast(SrcVal,
  388. IntegerType::get(Ctx, LoadSize * 8));
  389. return SrcVal;
  390. }
  391. /// This function is called when we have a memdep query of a load that ends up
  392. /// being a clobbering store. This means that the store provides bits used by
  393. /// the load but the pointers don't must-alias. Check this case to see if
  394. /// there is anything more we can do before we give up.
  395. Value *getStoreValueForLoad(Value *SrcVal, unsigned Offset, Type *LoadTy,
  396. Instruction *InsertPt, const DataLayout &DL) {
  397. IRBuilder<> Builder(InsertPt);
  398. SrcVal = getStoreValueForLoadHelper(SrcVal, Offset, LoadTy, Builder, DL);
  399. return coerceAvailableValueToLoadTypeHelper(SrcVal, LoadTy, Builder, DL);
  400. }
  401. Constant *getConstantStoreValueForLoad(Constant *SrcVal, unsigned Offset,
  402. Type *LoadTy, const DataLayout &DL) {
  403. ConstantFolder F;
  404. SrcVal = getStoreValueForLoadHelper(SrcVal, Offset, LoadTy, F, DL);
  405. return coerceAvailableValueToLoadTypeHelper(SrcVal, LoadTy, F, DL);
  406. }
  407. /// This function is called when we have a memdep query of a load that ends up
  408. /// being a clobbering load. This means that the load *may* provide bits used
  409. /// by the load but we can't be sure because the pointers don't must-alias.
  410. /// Check this case to see if there is anything more we can do before we give
  411. /// up.
  412. Value *getLoadValueForLoad(LoadInst *SrcVal, unsigned Offset, Type *LoadTy,
  413. Instruction *InsertPt, const DataLayout &DL) {
  414. // If Offset+LoadTy exceeds the size of SrcVal, then we must be wanting to
  415. // widen SrcVal out to a larger load.
  416. unsigned SrcValStoreSize =
  417. DL.getTypeStoreSize(SrcVal->getType()).getFixedSize();
  418. unsigned LoadSize = DL.getTypeStoreSize(LoadTy).getFixedSize();
  419. if (Offset + LoadSize > SrcValStoreSize) {
  420. assert(SrcVal->isSimple() && "Cannot widen volatile/atomic load!");
  421. assert(SrcVal->getType()->isIntegerTy() && "Can't widen non-integer load");
  422. // If we have a load/load clobber an DepLI can be widened to cover this
  423. // load, then we should widen it to the next power of 2 size big enough!
  424. unsigned NewLoadSize = Offset + LoadSize;
  425. if (!isPowerOf2_32(NewLoadSize))
  426. NewLoadSize = NextPowerOf2(NewLoadSize);
  427. Value *PtrVal = SrcVal->getPointerOperand();
  428. // Insert the new load after the old load. This ensures that subsequent
  429. // memdep queries will find the new load. We can't easily remove the old
  430. // load completely because it is already in the value numbering table.
  431. IRBuilder<> Builder(SrcVal->getParent(), ++BasicBlock::iterator(SrcVal));
  432. Type *DestTy = IntegerType::get(LoadTy->getContext(), NewLoadSize * 8);
  433. Type *DestPTy =
  434. PointerType::get(DestTy, PtrVal->getType()->getPointerAddressSpace());
  435. Builder.SetCurrentDebugLocation(SrcVal->getDebugLoc());
  436. PtrVal = Builder.CreateBitCast(PtrVal, DestPTy);
  437. LoadInst *NewLoad = Builder.CreateLoad(DestTy, PtrVal);
  438. NewLoad->takeName(SrcVal);
  439. NewLoad->setAlignment(SrcVal->getAlign());
  440. LLVM_DEBUG(dbgs() << "GVN WIDENED LOAD: " << *SrcVal << "\n");
  441. LLVM_DEBUG(dbgs() << "TO: " << *NewLoad << "\n");
  442. // Replace uses of the original load with the wider load. On a big endian
  443. // system, we need to shift down to get the relevant bits.
  444. Value *RV = NewLoad;
  445. if (DL.isBigEndian())
  446. RV = Builder.CreateLShr(RV, (NewLoadSize - SrcValStoreSize) * 8);
  447. RV = Builder.CreateTrunc(RV, SrcVal->getType());
  448. SrcVal->replaceAllUsesWith(RV);
  449. SrcVal = NewLoad;
  450. }
  451. return getStoreValueForLoad(SrcVal, Offset, LoadTy, InsertPt, DL);
  452. }
  453. Constant *getConstantLoadValueForLoad(Constant *SrcVal, unsigned Offset,
  454. Type *LoadTy, const DataLayout &DL) {
  455. unsigned SrcValStoreSize =
  456. DL.getTypeStoreSize(SrcVal->getType()).getFixedSize();
  457. unsigned LoadSize = DL.getTypeStoreSize(LoadTy).getFixedSize();
  458. if (Offset + LoadSize > SrcValStoreSize)
  459. return nullptr;
  460. return getConstantStoreValueForLoad(SrcVal, Offset, LoadTy, DL);
  461. }
  462. template <class T, class HelperClass>
  463. T *getMemInstValueForLoadHelper(MemIntrinsic *SrcInst, unsigned Offset,
  464. Type *LoadTy, HelperClass &Helper,
  465. const DataLayout &DL) {
  466. LLVMContext &Ctx = LoadTy->getContext();
  467. uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy).getFixedSize() / 8;
  468. // We know that this method is only called when the mem transfer fully
  469. // provides the bits for the load.
  470. if (MemSetInst *MSI = dyn_cast<MemSetInst>(SrcInst)) {
  471. // memset(P, 'x', 1234) -> splat('x'), even if x is a variable, and
  472. // independently of what the offset is.
  473. T *Val = cast<T>(MSI->getValue());
  474. if (LoadSize != 1)
  475. Val =
  476. Helper.CreateZExtOrBitCast(Val, IntegerType::get(Ctx, LoadSize * 8));
  477. T *OneElt = Val;
  478. // Splat the value out to the right number of bits.
  479. for (unsigned NumBytesSet = 1; NumBytesSet != LoadSize;) {
  480. // If we can double the number of bytes set, do it.
  481. if (NumBytesSet * 2 <= LoadSize) {
  482. T *ShVal = Helper.CreateShl(
  483. Val, ConstantInt::get(Val->getType(), NumBytesSet * 8));
  484. Val = Helper.CreateOr(Val, ShVal);
  485. NumBytesSet <<= 1;
  486. continue;
  487. }
  488. // Otherwise insert one byte at a time.
  489. T *ShVal = Helper.CreateShl(Val, ConstantInt::get(Val->getType(), 1 * 8));
  490. Val = Helper.CreateOr(OneElt, ShVal);
  491. ++NumBytesSet;
  492. }
  493. return coerceAvailableValueToLoadTypeHelper(Val, LoadTy, Helper, DL);
  494. }
  495. // Otherwise, this is a memcpy/memmove from a constant global.
  496. MemTransferInst *MTI = cast<MemTransferInst>(SrcInst);
  497. Constant *Src = cast<Constant>(MTI->getSource());
  498. unsigned AS = Src->getType()->getPointerAddressSpace();
  499. // Otherwise, see if we can constant fold a load from the constant with the
  500. // offset applied as appropriate.
  501. if (Offset) {
  502. Src = ConstantExpr::getBitCast(Src,
  503. Type::getInt8PtrTy(Src->getContext(), AS));
  504. Constant *OffsetCst =
  505. ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
  506. Src = ConstantExpr::getGetElementPtr(Type::getInt8Ty(Src->getContext()),
  507. Src, OffsetCst);
  508. }
  509. Src = ConstantExpr::getBitCast(Src, PointerType::get(LoadTy, AS));
  510. return ConstantFoldLoadFromConstPtr(Src, LoadTy, DL);
  511. }
  512. /// This function is called when we have a
  513. /// memdep query of a load that ends up being a clobbering mem intrinsic.
  514. Value *getMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
  515. Type *LoadTy, Instruction *InsertPt,
  516. const DataLayout &DL) {
  517. IRBuilder<> Builder(InsertPt);
  518. return getMemInstValueForLoadHelper<Value, IRBuilder<>>(SrcInst, Offset,
  519. LoadTy, Builder, DL);
  520. }
  521. Constant *getConstantMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
  522. Type *LoadTy, const DataLayout &DL) {
  523. // The only case analyzeLoadFromClobberingMemInst cannot be converted to a
  524. // constant is when it's a memset of a non-constant.
  525. if (auto *MSI = dyn_cast<MemSetInst>(SrcInst))
  526. if (!isa<Constant>(MSI->getValue()))
  527. return nullptr;
  528. ConstantFolder F;
  529. return getMemInstValueForLoadHelper<Constant, ConstantFolder>(SrcInst, Offset,
  530. LoadTy, F, DL);
  531. }
  532. } // namespace VNCoercion
  533. } // namespace llvm