VNCoercion.cpp 25 KB

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