Loads.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. //===- Loads.cpp - Local load analysis ------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines simple local analyses for load instructions.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Analysis/Loads.h"
  13. #include "llvm/Analysis/AliasAnalysis.h"
  14. #include "llvm/Analysis/AssumeBundleQueries.h"
  15. #include "llvm/Analysis/LoopInfo.h"
  16. #include "llvm/Analysis/MemoryBuiltins.h"
  17. #include "llvm/Analysis/MemoryLocation.h"
  18. #include "llvm/Analysis/ScalarEvolution.h"
  19. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  20. #include "llvm/Analysis/ValueTracking.h"
  21. #include "llvm/IR/DataLayout.h"
  22. #include "llvm/IR/IntrinsicInst.h"
  23. #include "llvm/IR/Module.h"
  24. #include "llvm/IR/Operator.h"
  25. using namespace llvm;
  26. static bool isAligned(const Value *Base, const APInt &Offset, Align Alignment,
  27. const DataLayout &DL) {
  28. Align BA = Base->getPointerAlignment(DL);
  29. const APInt APAlign(Offset.getBitWidth(), Alignment.value());
  30. assert(APAlign.isPowerOf2() && "must be a power of 2!");
  31. return BA >= Alignment && !(Offset & (APAlign - 1));
  32. }
  33. /// Test if V is always a pointer to allocated and suitably aligned memory for
  34. /// a simple load or store.
  35. static bool isDereferenceableAndAlignedPointer(
  36. const Value *V, Align Alignment, const APInt &Size, const DataLayout &DL,
  37. const Instruction *CtxI, AssumptionCache *AC, const DominatorTree *DT,
  38. const TargetLibraryInfo *TLI, SmallPtrSetImpl<const Value *> &Visited,
  39. unsigned MaxDepth) {
  40. assert(V->getType()->isPointerTy() && "Base must be pointer");
  41. // Recursion limit.
  42. if (MaxDepth-- == 0)
  43. return false;
  44. // Already visited? Bail out, we've likely hit unreachable code.
  45. if (!Visited.insert(V).second)
  46. return false;
  47. // Note that it is not safe to speculate into a malloc'd region because
  48. // malloc may return null.
  49. // For GEPs, determine if the indexing lands within the allocated object.
  50. if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
  51. const Value *Base = GEP->getPointerOperand();
  52. APInt Offset(DL.getIndexTypeSizeInBits(GEP->getType()), 0);
  53. if (!GEP->accumulateConstantOffset(DL, Offset) || Offset.isNegative() ||
  54. !Offset.urem(APInt(Offset.getBitWidth(), Alignment.value()))
  55. .isMinValue())
  56. return false;
  57. // If the base pointer is dereferenceable for Offset+Size bytes, then the
  58. // GEP (== Base + Offset) is dereferenceable for Size bytes. If the base
  59. // pointer is aligned to Align bytes, and the Offset is divisible by Align
  60. // then the GEP (== Base + Offset == k_0 * Align + k_1 * Align) is also
  61. // aligned to Align bytes.
  62. // Offset and Size may have different bit widths if we have visited an
  63. // addrspacecast, so we can't do arithmetic directly on the APInt values.
  64. return isDereferenceableAndAlignedPointer(
  65. Base, Alignment, Offset + Size.sextOrTrunc(Offset.getBitWidth()), DL,
  66. CtxI, AC, DT, TLI, Visited, MaxDepth);
  67. }
  68. // bitcast instructions are no-ops as far as dereferenceability is concerned.
  69. if (const BitCastOperator *BC = dyn_cast<BitCastOperator>(V)) {
  70. if (BC->getSrcTy()->isPointerTy())
  71. return isDereferenceableAndAlignedPointer(
  72. BC->getOperand(0), Alignment, Size, DL, CtxI, AC, DT, TLI,
  73. Visited, MaxDepth);
  74. }
  75. // Recurse into both hands of select.
  76. if (const SelectInst *Sel = dyn_cast<SelectInst>(V)) {
  77. return isDereferenceableAndAlignedPointer(Sel->getTrueValue(), Alignment,
  78. Size, DL, CtxI, AC, DT, TLI,
  79. Visited, MaxDepth) &&
  80. isDereferenceableAndAlignedPointer(Sel->getFalseValue(), Alignment,
  81. Size, DL, CtxI, AC, DT, TLI,
  82. Visited, MaxDepth);
  83. }
  84. bool CheckForNonNull, CheckForFreed;
  85. APInt KnownDerefBytes(Size.getBitWidth(),
  86. V->getPointerDereferenceableBytes(DL, CheckForNonNull,
  87. CheckForFreed));
  88. if (KnownDerefBytes.getBoolValue() && KnownDerefBytes.uge(Size) &&
  89. !CheckForFreed)
  90. if (!CheckForNonNull || isKnownNonZero(V, DL, 0, AC, CtxI, DT)) {
  91. // As we recursed through GEPs to get here, we've incrementally checked
  92. // that each step advanced by a multiple of the alignment. If our base is
  93. // properly aligned, then the original offset accessed must also be.
  94. APInt Offset(DL.getTypeStoreSizeInBits(V->getType()), 0);
  95. return isAligned(V, Offset, Alignment, DL);
  96. }
  97. /// TODO refactor this function to be able to search independently for
  98. /// Dereferencability and Alignment requirements.
  99. if (const auto *Call = dyn_cast<CallBase>(V)) {
  100. if (auto *RP = getArgumentAliasingToReturnedPointer(Call, true))
  101. return isDereferenceableAndAlignedPointer(RP, Alignment, Size, DL, CtxI,
  102. AC, DT, TLI, Visited, MaxDepth);
  103. // If we have a call we can't recurse through, check to see if this is an
  104. // allocation function for which we can establish an minimum object size.
  105. // Such a minimum object size is analogous to a deref_or_null attribute in
  106. // that we still need to prove the result non-null at point of use.
  107. // NOTE: We can only use the object size as a base fact as we a) need to
  108. // prove alignment too, and b) don't want the compile time impact of a
  109. // separate recursive walk.
  110. ObjectSizeOpts Opts;
  111. // TODO: It may be okay to round to align, but that would imply that
  112. // accessing slightly out of bounds was legal, and we're currently
  113. // inconsistent about that. For the moment, be conservative.
  114. Opts.RoundToAlign = false;
  115. Opts.NullIsUnknownSize = true;
  116. uint64_t ObjSize;
  117. if (getObjectSize(V, ObjSize, DL, TLI, Opts)) {
  118. APInt KnownDerefBytes(Size.getBitWidth(), ObjSize);
  119. if (KnownDerefBytes.getBoolValue() && KnownDerefBytes.uge(Size) &&
  120. isKnownNonZero(V, DL, 0, AC, CtxI, DT) && !V->canBeFreed()) {
  121. // As we recursed through GEPs to get here, we've incrementally
  122. // checked that each step advanced by a multiple of the alignment. If
  123. // our base is properly aligned, then the original offset accessed
  124. // must also be.
  125. APInt Offset(DL.getTypeStoreSizeInBits(V->getType()), 0);
  126. return isAligned(V, Offset, Alignment, DL);
  127. }
  128. }
  129. }
  130. // For gc.relocate, look through relocations
  131. if (const GCRelocateInst *RelocateInst = dyn_cast<GCRelocateInst>(V))
  132. return isDereferenceableAndAlignedPointer(RelocateInst->getDerivedPtr(),
  133. Alignment, Size, DL, CtxI, AC, DT,
  134. TLI, Visited, MaxDepth);
  135. if (const AddrSpaceCastOperator *ASC = dyn_cast<AddrSpaceCastOperator>(V))
  136. return isDereferenceableAndAlignedPointer(ASC->getOperand(0), Alignment,
  137. Size, DL, CtxI, AC, DT, TLI,
  138. Visited, MaxDepth);
  139. if (CtxI) {
  140. /// Look through assumes to see if both dereferencability and alignment can
  141. /// be provent by an assume
  142. RetainedKnowledge AlignRK;
  143. RetainedKnowledge DerefRK;
  144. if (getKnowledgeForValue(
  145. V, {Attribute::Dereferenceable, Attribute::Alignment}, AC,
  146. [&](RetainedKnowledge RK, Instruction *Assume, auto) {
  147. if (!isValidAssumeForContext(Assume, CtxI))
  148. return false;
  149. if (RK.AttrKind == Attribute::Alignment)
  150. AlignRK = std::max(AlignRK, RK);
  151. if (RK.AttrKind == Attribute::Dereferenceable)
  152. DerefRK = std::max(DerefRK, RK);
  153. if (AlignRK && DerefRK && AlignRK.ArgValue >= Alignment.value() &&
  154. DerefRK.ArgValue >= Size.getZExtValue())
  155. return true; // We have found what we needed so we stop looking
  156. return false; // Other assumes may have better information. so
  157. // keep looking
  158. }))
  159. return true;
  160. }
  161. // If we don't know, assume the worst.
  162. return false;
  163. }
  164. bool llvm::isDereferenceableAndAlignedPointer(
  165. const Value *V, Align Alignment, const APInt &Size, const DataLayout &DL,
  166. const Instruction *CtxI, AssumptionCache *AC, const DominatorTree *DT,
  167. const TargetLibraryInfo *TLI) {
  168. // Note: At the moment, Size can be zero. This ends up being interpreted as
  169. // a query of whether [Base, V] is dereferenceable and V is aligned (since
  170. // that's what the implementation happened to do). It's unclear if this is
  171. // the desired semantic, but at least SelectionDAG does exercise this case.
  172. SmallPtrSet<const Value *, 32> Visited;
  173. return ::isDereferenceableAndAlignedPointer(V, Alignment, Size, DL, CtxI, AC,
  174. DT, TLI, Visited, 16);
  175. }
  176. bool llvm::isDereferenceableAndAlignedPointer(
  177. const Value *V, Type *Ty, Align Alignment, const DataLayout &DL,
  178. const Instruction *CtxI, AssumptionCache *AC, const DominatorTree *DT,
  179. const TargetLibraryInfo *TLI) {
  180. // For unsized types or scalable vectors we don't know exactly how many bytes
  181. // are dereferenced, so bail out.
  182. if (!Ty->isSized() || isa<ScalableVectorType>(Ty))
  183. return false;
  184. // When dereferenceability information is provided by a dereferenceable
  185. // attribute, we know exactly how many bytes are dereferenceable. If we can
  186. // determine the exact offset to the attributed variable, we can use that
  187. // information here.
  188. APInt AccessSize(DL.getPointerTypeSizeInBits(V->getType()),
  189. DL.getTypeStoreSize(Ty));
  190. return isDereferenceableAndAlignedPointer(V, Alignment, AccessSize, DL, CtxI,
  191. AC, DT, TLI);
  192. }
  193. bool llvm::isDereferenceablePointer(const Value *V, Type *Ty,
  194. const DataLayout &DL,
  195. const Instruction *CtxI,
  196. AssumptionCache *AC,
  197. const DominatorTree *DT,
  198. const TargetLibraryInfo *TLI) {
  199. return isDereferenceableAndAlignedPointer(V, Ty, Align(1), DL, CtxI, AC, DT,
  200. TLI);
  201. }
  202. /// Test if A and B will obviously have the same value.
  203. ///
  204. /// This includes recognizing that %t0 and %t1 will have the same
  205. /// value in code like this:
  206. /// \code
  207. /// %t0 = getelementptr \@a, 0, 3
  208. /// store i32 0, i32* %t0
  209. /// %t1 = getelementptr \@a, 0, 3
  210. /// %t2 = load i32* %t1
  211. /// \endcode
  212. ///
  213. static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
  214. // Test if the values are trivially equivalent.
  215. if (A == B)
  216. return true;
  217. // Test if the values come from identical arithmetic instructions.
  218. // Use isIdenticalToWhenDefined instead of isIdenticalTo because
  219. // this function is only used when one address use dominates the
  220. // other, which means that they'll always either have the same
  221. // value or one of them will have an undefined value.
  222. if (isa<BinaryOperator>(A) || isa<CastInst>(A) || isa<PHINode>(A) ||
  223. isa<GetElementPtrInst>(A))
  224. if (const Instruction *BI = dyn_cast<Instruction>(B))
  225. if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
  226. return true;
  227. // Otherwise they may not be equivalent.
  228. return false;
  229. }
  230. bool llvm::isDereferenceableAndAlignedInLoop(LoadInst *LI, Loop *L,
  231. ScalarEvolution &SE,
  232. DominatorTree &DT,
  233. AssumptionCache *AC) {
  234. auto &DL = LI->getModule()->getDataLayout();
  235. Value *Ptr = LI->getPointerOperand();
  236. APInt EltSize(DL.getIndexTypeSizeInBits(Ptr->getType()),
  237. DL.getTypeStoreSize(LI->getType()).getFixedValue());
  238. const Align Alignment = LI->getAlign();
  239. Instruction *HeaderFirstNonPHI = L->getHeader()->getFirstNonPHI();
  240. // If given a uniform (i.e. non-varying) address, see if we can prove the
  241. // access is safe within the loop w/o needing predication.
  242. if (L->isLoopInvariant(Ptr))
  243. return isDereferenceableAndAlignedPointer(Ptr, Alignment, EltSize, DL,
  244. HeaderFirstNonPHI, AC, &DT);
  245. // Otherwise, check to see if we have a repeating access pattern where we can
  246. // prove that all accesses are well aligned and dereferenceable.
  247. auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Ptr));
  248. if (!AddRec || AddRec->getLoop() != L || !AddRec->isAffine())
  249. return false;
  250. auto* Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(SE));
  251. if (!Step)
  252. return false;
  253. // TODO: generalize to access patterns which have gaps
  254. if (Step->getAPInt() != EltSize)
  255. return false;
  256. auto TC = SE.getSmallConstantMaxTripCount(L);
  257. if (!TC)
  258. return false;
  259. const APInt AccessSize = TC * EltSize;
  260. auto *StartS = dyn_cast<SCEVUnknown>(AddRec->getStart());
  261. if (!StartS)
  262. return false;
  263. assert(SE.isLoopInvariant(StartS, L) && "implied by addrec definition");
  264. Value *Base = StartS->getValue();
  265. // For the moment, restrict ourselves to the case where the access size is a
  266. // multiple of the requested alignment and the base is aligned.
  267. // TODO: generalize if a case found which warrants
  268. if (EltSize.urem(Alignment.value()) != 0)
  269. return false;
  270. return isDereferenceableAndAlignedPointer(Base, Alignment, AccessSize, DL,
  271. HeaderFirstNonPHI, AC, &DT);
  272. }
  273. /// Check if executing a load of this pointer value cannot trap.
  274. ///
  275. /// If DT and ScanFrom are specified this method performs context-sensitive
  276. /// analysis and returns true if it is safe to load immediately before ScanFrom.
  277. ///
  278. /// If it is not obviously safe to load from the specified pointer, we do
  279. /// a quick local scan of the basic block containing \c ScanFrom, to determine
  280. /// if the address is already accessed.
  281. ///
  282. /// This uses the pointee type to determine how many bytes need to be safe to
  283. /// load from the pointer.
  284. bool llvm::isSafeToLoadUnconditionally(Value *V, Align Alignment, APInt &Size,
  285. const DataLayout &DL,
  286. Instruction *ScanFrom,
  287. AssumptionCache *AC,
  288. const DominatorTree *DT,
  289. const TargetLibraryInfo *TLI) {
  290. // If DT is not specified we can't make context-sensitive query
  291. const Instruction* CtxI = DT ? ScanFrom : nullptr;
  292. if (isDereferenceableAndAlignedPointer(V, Alignment, Size, DL, CtxI, AC, DT,
  293. TLI))
  294. return true;
  295. if (!ScanFrom)
  296. return false;
  297. if (Size.getBitWidth() > 64)
  298. return false;
  299. const uint64_t LoadSize = Size.getZExtValue();
  300. // Otherwise, be a little bit aggressive by scanning the local block where we
  301. // want to check to see if the pointer is already being loaded or stored
  302. // from/to. If so, the previous load or store would have already trapped,
  303. // so there is no harm doing an extra load (also, CSE will later eliminate
  304. // the load entirely).
  305. BasicBlock::iterator BBI = ScanFrom->getIterator(),
  306. E = ScanFrom->getParent()->begin();
  307. // We can at least always strip pointer casts even though we can't use the
  308. // base here.
  309. V = V->stripPointerCasts();
  310. while (BBI != E) {
  311. --BBI;
  312. // If we see a free or a call which may write to memory (i.e. which might do
  313. // a free) the pointer could be marked invalid.
  314. if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
  315. !isa<LifetimeIntrinsic>(BBI) && !isa<DbgInfoIntrinsic>(BBI))
  316. return false;
  317. Value *AccessedPtr;
  318. Type *AccessedTy;
  319. Align AccessedAlign;
  320. if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
  321. // Ignore volatile loads. The execution of a volatile load cannot
  322. // be used to prove an address is backed by regular memory; it can,
  323. // for example, point to an MMIO register.
  324. if (LI->isVolatile())
  325. continue;
  326. AccessedPtr = LI->getPointerOperand();
  327. AccessedTy = LI->getType();
  328. AccessedAlign = LI->getAlign();
  329. } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
  330. // Ignore volatile stores (see comment for loads).
  331. if (SI->isVolatile())
  332. continue;
  333. AccessedPtr = SI->getPointerOperand();
  334. AccessedTy = SI->getValueOperand()->getType();
  335. AccessedAlign = SI->getAlign();
  336. } else
  337. continue;
  338. if (AccessedAlign < Alignment)
  339. continue;
  340. // Handle trivial cases.
  341. if (AccessedPtr == V &&
  342. LoadSize <= DL.getTypeStoreSize(AccessedTy))
  343. return true;
  344. if (AreEquivalentAddressValues(AccessedPtr->stripPointerCasts(), V) &&
  345. LoadSize <= DL.getTypeStoreSize(AccessedTy))
  346. return true;
  347. }
  348. return false;
  349. }
  350. bool llvm::isSafeToLoadUnconditionally(Value *V, Type *Ty, Align Alignment,
  351. const DataLayout &DL,
  352. Instruction *ScanFrom,
  353. AssumptionCache *AC,
  354. const DominatorTree *DT,
  355. const TargetLibraryInfo *TLI) {
  356. TypeSize TySize = DL.getTypeStoreSize(Ty);
  357. if (TySize.isScalable())
  358. return false;
  359. APInt Size(DL.getIndexTypeSizeInBits(V->getType()), TySize.getFixedValue());
  360. return isSafeToLoadUnconditionally(V, Alignment, Size, DL, ScanFrom, AC, DT,
  361. TLI);
  362. }
  363. /// DefMaxInstsToScan - the default number of maximum instructions
  364. /// to scan in the block, used by FindAvailableLoadedValue().
  365. /// FindAvailableLoadedValue() was introduced in r60148, to improve jump
  366. /// threading in part by eliminating partially redundant loads.
  367. /// At that point, the value of MaxInstsToScan was already set to '6'
  368. /// without documented explanation.
  369. cl::opt<unsigned>
  370. llvm::DefMaxInstsToScan("available-load-scan-limit", cl::init(6), cl::Hidden,
  371. cl::desc("Use this to specify the default maximum number of instructions "
  372. "to scan backward from a given instruction, when searching for "
  373. "available loaded value"));
  374. Value *llvm::FindAvailableLoadedValue(LoadInst *Load,
  375. BasicBlock *ScanBB,
  376. BasicBlock::iterator &ScanFrom,
  377. unsigned MaxInstsToScan,
  378. AAResults *AA, bool *IsLoad,
  379. unsigned *NumScanedInst) {
  380. // Don't CSE load that is volatile or anything stronger than unordered.
  381. if (!Load->isUnordered())
  382. return nullptr;
  383. MemoryLocation Loc = MemoryLocation::get(Load);
  384. return findAvailablePtrLoadStore(Loc, Load->getType(), Load->isAtomic(),
  385. ScanBB, ScanFrom, MaxInstsToScan, AA, IsLoad,
  386. NumScanedInst);
  387. }
  388. // Check if the load and the store have the same base, constant offsets and
  389. // non-overlapping access ranges.
  390. static bool areNonOverlapSameBaseLoadAndStore(const Value *LoadPtr,
  391. Type *LoadTy,
  392. const Value *StorePtr,
  393. Type *StoreTy,
  394. const DataLayout &DL) {
  395. APInt LoadOffset(DL.getIndexTypeSizeInBits(LoadPtr->getType()), 0);
  396. APInt StoreOffset(DL.getIndexTypeSizeInBits(StorePtr->getType()), 0);
  397. const Value *LoadBase = LoadPtr->stripAndAccumulateConstantOffsets(
  398. DL, LoadOffset, /* AllowNonInbounds */ false);
  399. const Value *StoreBase = StorePtr->stripAndAccumulateConstantOffsets(
  400. DL, StoreOffset, /* AllowNonInbounds */ false);
  401. if (LoadBase != StoreBase)
  402. return false;
  403. auto LoadAccessSize = LocationSize::precise(DL.getTypeStoreSize(LoadTy));
  404. auto StoreAccessSize = LocationSize::precise(DL.getTypeStoreSize(StoreTy));
  405. ConstantRange LoadRange(LoadOffset,
  406. LoadOffset + LoadAccessSize.toRaw());
  407. ConstantRange StoreRange(StoreOffset,
  408. StoreOffset + StoreAccessSize.toRaw());
  409. return LoadRange.intersectWith(StoreRange).isEmptySet();
  410. }
  411. static Value *getAvailableLoadStore(Instruction *Inst, const Value *Ptr,
  412. Type *AccessTy, bool AtLeastAtomic,
  413. const DataLayout &DL, bool *IsLoadCSE) {
  414. // If this is a load of Ptr, the loaded value is available.
  415. // (This is true even if the load is volatile or atomic, although
  416. // those cases are unlikely.)
  417. if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
  418. // We can value forward from an atomic to a non-atomic, but not the
  419. // other way around.
  420. if (LI->isAtomic() < AtLeastAtomic)
  421. return nullptr;
  422. Value *LoadPtr = LI->getPointerOperand()->stripPointerCasts();
  423. if (!AreEquivalentAddressValues(LoadPtr, Ptr))
  424. return nullptr;
  425. if (CastInst::isBitOrNoopPointerCastable(LI->getType(), AccessTy, DL)) {
  426. if (IsLoadCSE)
  427. *IsLoadCSE = true;
  428. return LI;
  429. }
  430. }
  431. // If this is a store through Ptr, the value is available!
  432. // (This is true even if the store is volatile or atomic, although
  433. // those cases are unlikely.)
  434. if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
  435. // We can value forward from an atomic to a non-atomic, but not the
  436. // other way around.
  437. if (SI->isAtomic() < AtLeastAtomic)
  438. return nullptr;
  439. Value *StorePtr = SI->getPointerOperand()->stripPointerCasts();
  440. if (!AreEquivalentAddressValues(StorePtr, Ptr))
  441. return nullptr;
  442. if (IsLoadCSE)
  443. *IsLoadCSE = false;
  444. Value *Val = SI->getValueOperand();
  445. if (CastInst::isBitOrNoopPointerCastable(Val->getType(), AccessTy, DL))
  446. return Val;
  447. TypeSize StoreSize = DL.getTypeSizeInBits(Val->getType());
  448. TypeSize LoadSize = DL.getTypeSizeInBits(AccessTy);
  449. if (TypeSize::isKnownLE(LoadSize, StoreSize))
  450. if (auto *C = dyn_cast<Constant>(Val))
  451. return ConstantFoldLoadFromConst(C, AccessTy, DL);
  452. }
  453. if (auto *MSI = dyn_cast<MemSetInst>(Inst)) {
  454. // Don't forward from (non-atomic) memset to atomic load.
  455. if (AtLeastAtomic)
  456. return nullptr;
  457. // Only handle constant memsets.
  458. auto *Val = dyn_cast<ConstantInt>(MSI->getValue());
  459. auto *Len = dyn_cast<ConstantInt>(MSI->getLength());
  460. if (!Val || !Len)
  461. return nullptr;
  462. // TODO: Handle offsets.
  463. Value *Dst = MSI->getDest();
  464. if (!AreEquivalentAddressValues(Dst, Ptr))
  465. return nullptr;
  466. if (IsLoadCSE)
  467. *IsLoadCSE = false;
  468. TypeSize LoadTypeSize = DL.getTypeSizeInBits(AccessTy);
  469. if (LoadTypeSize.isScalable())
  470. return nullptr;
  471. // Make sure the read bytes are contained in the memset.
  472. uint64_t LoadSize = LoadTypeSize.getFixedValue();
  473. if ((Len->getValue() * 8).ult(LoadSize))
  474. return nullptr;
  475. APInt Splat = LoadSize >= 8 ? APInt::getSplat(LoadSize, Val->getValue())
  476. : Val->getValue().trunc(LoadSize);
  477. ConstantInt *SplatC = ConstantInt::get(MSI->getContext(), Splat);
  478. if (CastInst::isBitOrNoopPointerCastable(SplatC->getType(), AccessTy, DL))
  479. return SplatC;
  480. return nullptr;
  481. }
  482. return nullptr;
  483. }
  484. Value *llvm::findAvailablePtrLoadStore(
  485. const MemoryLocation &Loc, Type *AccessTy, bool AtLeastAtomic,
  486. BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan,
  487. AAResults *AA, bool *IsLoadCSE, unsigned *NumScanedInst) {
  488. if (MaxInstsToScan == 0)
  489. MaxInstsToScan = ~0U;
  490. const DataLayout &DL = ScanBB->getModule()->getDataLayout();
  491. const Value *StrippedPtr = Loc.Ptr->stripPointerCasts();
  492. while (ScanFrom != ScanBB->begin()) {
  493. // We must ignore debug info directives when counting (otherwise they
  494. // would affect codegen).
  495. Instruction *Inst = &*--ScanFrom;
  496. if (Inst->isDebugOrPseudoInst())
  497. continue;
  498. // Restore ScanFrom to expected value in case next test succeeds
  499. ScanFrom++;
  500. if (NumScanedInst)
  501. ++(*NumScanedInst);
  502. // Don't scan huge blocks.
  503. if (MaxInstsToScan-- == 0)
  504. return nullptr;
  505. --ScanFrom;
  506. if (Value *Available = getAvailableLoadStore(Inst, StrippedPtr, AccessTy,
  507. AtLeastAtomic, DL, IsLoadCSE))
  508. return Available;
  509. // Try to get the store size for the type.
  510. if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
  511. Value *StorePtr = SI->getPointerOperand()->stripPointerCasts();
  512. // If both StrippedPtr and StorePtr reach all the way to an alloca or
  513. // global and they are different, ignore the store. This is a trivial form
  514. // of alias analysis that is important for reg2mem'd code.
  515. if ((isa<AllocaInst>(StrippedPtr) || isa<GlobalVariable>(StrippedPtr)) &&
  516. (isa<AllocaInst>(StorePtr) || isa<GlobalVariable>(StorePtr)) &&
  517. StrippedPtr != StorePtr)
  518. continue;
  519. if (!AA) {
  520. // When AA isn't available, but if the load and the store have the same
  521. // base, constant offsets and non-overlapping access ranges, ignore the
  522. // store. This is a simple form of alias analysis that is used by the
  523. // inliner. FIXME: use BasicAA if possible.
  524. if (areNonOverlapSameBaseLoadAndStore(
  525. Loc.Ptr, AccessTy, SI->getPointerOperand(),
  526. SI->getValueOperand()->getType(), DL))
  527. continue;
  528. } else {
  529. // If we have alias analysis and it says the store won't modify the
  530. // loaded value, ignore the store.
  531. if (!isModSet(AA->getModRefInfo(SI, Loc)))
  532. continue;
  533. }
  534. // Otherwise the store that may or may not alias the pointer, bail out.
  535. ++ScanFrom;
  536. return nullptr;
  537. }
  538. // If this is some other instruction that may clobber Ptr, bail out.
  539. if (Inst->mayWriteToMemory()) {
  540. // If alias analysis claims that it really won't modify the load,
  541. // ignore it.
  542. if (AA && !isModSet(AA->getModRefInfo(Inst, Loc)))
  543. continue;
  544. // May modify the pointer, bail out.
  545. ++ScanFrom;
  546. return nullptr;
  547. }
  548. }
  549. // Got to the start of the block, we didn't find it, but are done for this
  550. // block.
  551. return nullptr;
  552. }
  553. Value *llvm::FindAvailableLoadedValue(LoadInst *Load, AAResults &AA,
  554. bool *IsLoadCSE,
  555. unsigned MaxInstsToScan) {
  556. const DataLayout &DL = Load->getModule()->getDataLayout();
  557. Value *StrippedPtr = Load->getPointerOperand()->stripPointerCasts();
  558. BasicBlock *ScanBB = Load->getParent();
  559. Type *AccessTy = Load->getType();
  560. bool AtLeastAtomic = Load->isAtomic();
  561. if (!Load->isUnordered())
  562. return nullptr;
  563. // Try to find an available value first, and delay expensive alias analysis
  564. // queries until later.
  565. Value *Available = nullptr;;
  566. SmallVector<Instruction *> MustNotAliasInsts;
  567. for (Instruction &Inst : make_range(++Load->getReverseIterator(),
  568. ScanBB->rend())) {
  569. if (Inst.isDebugOrPseudoInst())
  570. continue;
  571. if (MaxInstsToScan-- == 0)
  572. return nullptr;
  573. Available = getAvailableLoadStore(&Inst, StrippedPtr, AccessTy,
  574. AtLeastAtomic, DL, IsLoadCSE);
  575. if (Available)
  576. break;
  577. if (Inst.mayWriteToMemory())
  578. MustNotAliasInsts.push_back(&Inst);
  579. }
  580. // If we found an available value, ensure that the instructions in between
  581. // did not modify the memory location.
  582. if (Available) {
  583. MemoryLocation Loc = MemoryLocation::get(Load);
  584. for (Instruction *Inst : MustNotAliasInsts)
  585. if (isModSet(AA.getModRefInfo(Inst, Loc)))
  586. return nullptr;
  587. }
  588. return Available;
  589. }
  590. bool llvm::canReplacePointersIfEqual(Value *A, Value *B, const DataLayout &DL,
  591. Instruction *CtxI) {
  592. Type *Ty = A->getType();
  593. assert(Ty == B->getType() && Ty->isPointerTy() &&
  594. "values must have matching pointer types");
  595. // NOTE: The checks in the function are incomplete and currently miss illegal
  596. // cases! The current implementation is a starting point and the
  597. // implementation should be made stricter over time.
  598. if (auto *C = dyn_cast<Constant>(B)) {
  599. // Do not allow replacing a pointer with a constant pointer, unless it is
  600. // either null or at least one byte is dereferenceable.
  601. APInt OneByte(DL.getPointerTypeSizeInBits(Ty), 1);
  602. return C->isNullValue() ||
  603. isDereferenceableAndAlignedPointer(B, Align(1), OneByte, DL, CtxI);
  604. }
  605. return true;
  606. }