blob: f689a17cb283de9753095b12a8a81a3a9129b923 [file] [log] [blame]
Dan Gohman826bdf82010-05-28 16:19:17 +00001//===- Loads.cpp - Local load analysis ------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Dan Gohman826bdf82010-05-28 16:19:17 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file defines simple local analyses for load instructions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/Analysis/Loads.h"
14#include "llvm/Analysis/AliasAnalysis.h"
Philip Reamescffa6302019-09-10 21:33:53 +000015#include "llvm/Analysis/LoopInfo.h"
16#include "llvm/Analysis/ScalarEvolution.h"
17#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Nuno Lopes69dcc7d2012-12-31 17:42:11 +000018#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/DataLayout.h"
20#include "llvm/IR/GlobalAlias.h"
21#include "llvm/IR/GlobalVariable.h"
22#include "llvm/IR/IntrinsicInst.h"
23#include "llvm/IR/LLVMContext.h"
Mehdi Amini9a9738f2015-03-03 22:01:13 +000024#include "llvm/IR/Module.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Operator.h"
Artur Pilipenko31bcca42016-02-24 12:49:04 +000026#include "llvm/IR/Statepoint.h"
27
Dan Gohman826bdf82010-05-28 16:19:17 +000028using namespace llvm;
29
Benjamin Kramerc321e532016-06-08 19:09:22 +000030static bool isAligned(const Value *Base, const APInt &Offset, unsigned Align,
Artur Pilipenko31bcca42016-02-24 12:49:04 +000031 const DataLayout &DL) {
32 APInt BaseAlign(Offset.getBitWidth(), Base->getPointerAlignment(DL));
33
34 if (!BaseAlign) {
35 Type *Ty = Base->getType()->getPointerElementType();
36 if (!Ty->isSized())
37 return false;
38 BaseAlign = DL.getABITypeAlignment(Ty);
39 }
40
41 APInt Alignment(Offset.getBitWidth(), Align);
42
43 assert(Alignment.isPowerOf2() && "must be a power of 2!");
44 return BaseAlign.uge(Alignment) && !(Offset & (Alignment-1));
45}
46
Artur Pilipenko31bcca42016-02-24 12:49:04 +000047/// Test if V is always a pointer to allocated and suitably aligned memory for
48/// a simple load or store.
49static bool isDereferenceableAndAlignedPointer(
Benjamin Kramerc321e532016-06-08 19:09:22 +000050 const Value *V, unsigned Align, const APInt &Size, const DataLayout &DL,
Artur Pilipenko31bcca42016-02-24 12:49:04 +000051 const Instruction *CtxI, const DominatorTree *DT,
Sean Silva45835e72016-07-02 23:47:27 +000052 SmallPtrSetImpl<const Value *> &Visited) {
David Majnemera90e51e2016-08-31 03:22:32 +000053 // Already visited? Bail out, we've likely hit unreachable code.
54 if (!Visited.insert(V).second)
55 return false;
56
Artur Pilipenko31bcca42016-02-24 12:49:04 +000057 // Note that it is not safe to speculate into a malloc'd region because
58 // malloc may return null.
59
Sanjoy Das10df4972016-06-01 16:47:45 +000060 // bitcast instructions are no-ops as far as dereferenceability is concerned.
61 if (const BitCastOperator *BC = dyn_cast<BitCastOperator>(V))
62 return isDereferenceableAndAlignedPointer(BC->getOperand(0), Align, Size,
Sean Silva45835e72016-07-02 23:47:27 +000063 DL, CtxI, DT, Visited);
Artur Pilipenko31bcca42016-02-24 12:49:04 +000064
Sanjoy Das48cad712016-06-02 00:52:53 +000065 bool CheckForNonNull = false;
66 APInt KnownDerefBytes(Size.getBitWidth(),
67 V->getPointerDereferenceableBytes(DL, CheckForNonNull));
Philip Reames2f858c22019-08-26 23:57:27 +000068 if (KnownDerefBytes.getBoolValue() && KnownDerefBytes.uge(Size))
69 if (!CheckForNonNull || isKnownNonZero(V, DL, 0, nullptr, CtxI, DT)) {
Philip Reames20650ed2019-08-27 04:52:35 +000070 // As we recursed through GEPs to get here, we've incrementally checked
71 // that each step advanced by a multiple of the alignment. If our base is
72 // properly aligned, then the original offset accessed must also be.
Philip Reames2f858c22019-08-26 23:57:27 +000073 Type *Ty = V->getType();
74 assert(Ty->isSized() && "must be sized");
75 APInt Offset(DL.getTypeStoreSizeInBits(Ty), 0);
76 return isAligned(V, Offset, Align, DL);
77 }
Artur Pilipenko31bcca42016-02-24 12:49:04 +000078
79 // For GEPs, determine if the indexing lands within the allocated object.
80 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Artur Pilipenko31bcca42016-02-24 12:49:04 +000081 const Value *Base = GEP->getPointerOperand();
82
Elena Demikhovsky945b7e52018-02-14 06:58:08 +000083 APInt Offset(DL.getIndexTypeSizeInBits(GEP->getType()), 0);
Sanjoy Das10df4972016-06-01 16:47:45 +000084 if (!GEP->accumulateConstantOffset(DL, Offset) || Offset.isNegative() ||
85 !Offset.urem(APInt(Offset.getBitWidth(), Align)).isMinValue())
Artur Pilipenko31bcca42016-02-24 12:49:04 +000086 return false;
87
Sanjoy Das10df4972016-06-01 16:47:45 +000088 // If the base pointer is dereferenceable for Offset+Size bytes, then the
89 // GEP (== Base + Offset) is dereferenceable for Size bytes. If the base
90 // pointer is aligned to Align bytes, and the Offset is divisible by Align
91 // then the GEP (== Base + Offset == k_0 * Align + k_1 * Align) is also
92 // aligned to Align bytes.
93
Tom Stellard130689952016-10-28 15:32:28 +000094 // Offset and Size may have different bit widths if we have visited an
95 // addrspacecast, so we can't do arithmetic directly on the APInt values.
96 return isDereferenceableAndAlignedPointer(
97 Base, Align, Offset + Size.sextOrTrunc(Offset.getBitWidth()),
98 DL, CtxI, DT, Visited);
Artur Pilipenko31bcca42016-02-24 12:49:04 +000099 }
100
101 // For gc.relocate, look through relocations
102 if (const GCRelocateInst *RelocateInst = dyn_cast<GCRelocateInst>(V))
103 return isDereferenceableAndAlignedPointer(
Sean Silva45835e72016-07-02 23:47:27 +0000104 RelocateInst->getDerivedPtr(), Align, Size, DL, CtxI, DT, Visited);
Artur Pilipenko31bcca42016-02-24 12:49:04 +0000105
106 if (const AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(V))
Sanjoy Das10df4972016-06-01 16:47:45 +0000107 return isDereferenceableAndAlignedPointer(ASC->getOperand(0), Align, Size,
Sean Silva45835e72016-07-02 23:47:27 +0000108 DL, CtxI, DT, Visited);
Artur Pilipenko31bcca42016-02-24 12:49:04 +0000109
Chandler Carruth363ac682019-01-07 05:42:51 +0000110 if (const auto *Call = dyn_cast<CallBase>(V))
Florian Hahnfd72bf22019-08-15 12:13:02 +0000111 if (auto *RP = getArgumentAliasingToReturnedPointer(Call, true))
Piotr Padlewskid6f73462018-05-23 09:16:44 +0000112 return isDereferenceableAndAlignedPointer(RP, Align, Size, DL, CtxI, DT,
Hal Finkelbf3957a2016-07-11 03:08:49 +0000113 Visited);
Piotr Padlewskid6f73462018-05-23 09:16:44 +0000114
Artur Pilipenko31bcca42016-02-24 12:49:04 +0000115 // If we don't know, assume the worst.
116 return false;
117}
118
119bool llvm::isDereferenceableAndAlignedPointer(const Value *V, unsigned Align,
Vitaly Buka9c2a0362017-06-24 01:35:13 +0000120 const APInt &Size,
121 const DataLayout &DL,
122 const Instruction *CtxI,
123 const DominatorTree *DT) {
Philip Reames93a26ec2019-08-27 23:36:31 +0000124 assert(Align != 0 && "expected explicitly set alignment");
125 // Note: At the moment, Size can be zero. This ends up being interpreted as
126 // a query of whether [Base, V] is dereferenceable and V is aligned (since
127 // that's what the implementation happened to do). It's unclear if this is
128 // the desired semantic, but at least SelectionDAG does exercise this case.
129
Vitaly Buka9c2a0362017-06-24 01:35:13 +0000130 SmallPtrSet<const Value *, 32> Visited;
131 return ::isDereferenceableAndAlignedPointer(V, Align, Size, DL, CtxI, DT,
132 Visited);
133}
134
Tim Northover60afa492019-07-09 11:35:35 +0000135bool llvm::isDereferenceableAndAlignedPointer(const Value *V, Type *Ty,
136 unsigned Align,
Artur Pilipenko31bcca42016-02-24 12:49:04 +0000137 const DataLayout &DL,
138 const Instruction *CtxI,
Sean Silva45835e72016-07-02 23:47:27 +0000139 const DominatorTree *DT) {
Artur Pilipenko31bcca42016-02-24 12:49:04 +0000140 // When dereferenceability information is provided by a dereferenceable
141 // attribute, we know exactly how many bytes are dereferenceable. If we can
142 // determine the exact offset to the attributed variable, we can use that
143 // information here.
Artur Pilipenko31bcca42016-02-24 12:49:04 +0000144
145 // Require ABI alignment for loads without alignment specification
146 if (Align == 0)
147 Align = DL.getABITypeAlignment(Ty);
148
Sanjoy Das10df4972016-06-01 16:47:45 +0000149 if (!Ty->isSized())
150 return false;
Philip Reames93a26ec2019-08-27 23:36:31 +0000151
152 APInt AccessSize(DL.getIndexTypeSizeInBits(V->getType()),
153 DL.getTypeStoreSize(Ty));
154 return isDereferenceableAndAlignedPointer(V, Align, AccessSize,
155 DL, CtxI, DT);
Artur Pilipenko31bcca42016-02-24 12:49:04 +0000156}
157
Tim Northover60afa492019-07-09 11:35:35 +0000158bool llvm::isDereferenceablePointer(const Value *V, Type *Ty,
159 const DataLayout &DL,
Artur Pilipenko31bcca42016-02-24 12:49:04 +0000160 const Instruction *CtxI,
Sean Silva45835e72016-07-02 23:47:27 +0000161 const DominatorTree *DT) {
Tim Northover60afa492019-07-09 11:35:35 +0000162 return isDereferenceableAndAlignedPointer(V, Ty, 1, DL, CtxI, DT);
Artur Pilipenko31bcca42016-02-24 12:49:04 +0000163}
164
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000165/// Test if A and B will obviously have the same value.
Chandler Carruthb56052f2014-10-18 23:31:55 +0000166///
167/// This includes recognizing that %t0 and %t1 will have the same
Dan Gohman826bdf82010-05-28 16:19:17 +0000168/// value in code like this:
Chandler Carruthb56052f2014-10-18 23:31:55 +0000169/// \code
Dan Gohman826bdf82010-05-28 16:19:17 +0000170/// %t0 = getelementptr \@a, 0, 3
171/// store i32 0, i32* %t0
172/// %t1 = getelementptr \@a, 0, 3
173/// %t2 = load i32* %t1
Chandler Carruthb56052f2014-10-18 23:31:55 +0000174/// \endcode
Dan Gohman826bdf82010-05-28 16:19:17 +0000175///
176static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
177 // Test if the values are trivially equivalent.
Chandler Carruthbe49df32014-10-18 23:41:25 +0000178 if (A == B)
179 return true;
Hans Wennborg060b9942011-06-03 17:15:37 +0000180
Dan Gohman826bdf82010-05-28 16:19:17 +0000181 // Test if the values come from identical arithmetic instructions.
182 // Use isIdenticalToWhenDefined instead of isIdenticalTo because
183 // this function is only used when one address use dominates the
184 // other, which means that they'll always either have the same
185 // value or one of them will have an undefined value.
Chandler Carruthbe49df32014-10-18 23:41:25 +0000186 if (isa<BinaryOperator>(A) || isa<CastInst>(A) || isa<PHINode>(A) ||
187 isa<GetElementPtrInst>(A))
Dan Gohman826bdf82010-05-28 16:19:17 +0000188 if (const Instruction *BI = dyn_cast<Instruction>(B))
189 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
190 return true;
Hans Wennborg060b9942011-06-03 17:15:37 +0000191
Dan Gohman826bdf82010-05-28 16:19:17 +0000192 // Otherwise they may not be equivalent.
193 return false;
194}
195
Philip Reamescffa6302019-09-10 21:33:53 +0000196bool llvm::isDereferenceableAndAlignedInLoop(LoadInst *LI, Loop *L,
197 ScalarEvolution &SE,
198 DominatorTree &DT) {
199 auto &DL = LI->getModule()->getDataLayout();
200 Value *Ptr = LI->getPointerOperand();
Philip Reamesb90f94f2019-09-12 16:49:10 +0000201
202 APInt EltSize(DL.getIndexTypeSizeInBits(Ptr->getType()),
203 DL.getTypeStoreSize(LI->getType()));
204 unsigned Align = LI->getAlignment();
205 if (Align == 0)
206 Align = DL.getABITypeAlignment(LI->getType());
207
208 Instruction *HeaderFirstNonPHI = L->getHeader()->getFirstNonPHI();
209
210 // If given a uniform (i.e. non-varying) address, see if we can prove the
211 // access is safe within the loop w/o needing predication.
212 if (L->isLoopInvariant(Ptr))
213 return isDereferenceableAndAlignedPointer(Ptr, Align, EltSize, DL,
214 HeaderFirstNonPHI, &DT);
215
216 // Otherwise, check to see if we have a repeating access pattern where we can
217 // prove that all accesses are well aligned and dereferenceable.
Philip Reamescffa6302019-09-10 21:33:53 +0000218 auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Ptr));
219 if (!AddRec || AddRec->getLoop() != L || !AddRec->isAffine())
220 return false;
221 auto* Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(SE));
222 if (!Step)
223 return false;
Philip Reamescffa6302019-09-10 21:33:53 +0000224 // TODO: generalize to access patterns which have gaps
Philip Reamesb90f94f2019-09-12 16:49:10 +0000225 if (Step->getAPInt() != EltSize)
Philip Reamescffa6302019-09-10 21:33:53 +0000226 return false;
227
228 // TODO: If the symbolic trip count has a small bound (max count), we might
229 // be able to prove safety.
230 auto TC = SE.getSmallConstantTripCount(L);
231 if (!TC)
232 return false;
233
234 const APInt AccessSize = TC * EltSize;
235
236 auto *StartS = dyn_cast<SCEVUnknown>(AddRec->getStart());
237 if (!StartS)
238 return false;
239 assert(SE.isLoopInvariant(StartS, L) && "implied by addrec definition");
240 Value *Base = StartS->getValue();
241
Philip Reamescffa6302019-09-10 21:33:53 +0000242 // For the moment, restrict ourselves to the case where the access size is a
243 // multiple of the requested alignment and the base is aligned.
244 // TODO: generalize if a case found which warrants
245 if (EltSize.urem(Align) != 0)
246 return false;
247 return isDereferenceableAndAlignedPointer(Base, Align, AccessSize,
248 DL, HeaderFirstNonPHI, &DT);
249}
250
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000251/// Check if executing a load of this pointer value cannot trap.
Chandler Carruth1f27f032014-10-18 23:46:17 +0000252///
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +0000253/// If DT and ScanFrom are specified this method performs context-sensitive
254/// analysis and returns true if it is safe to load immediately before ScanFrom.
Artur Pilipenko66d6d3e2016-02-11 13:42:59 +0000255///
Chandler Carruth1f27f032014-10-18 23:46:17 +0000256/// If it is not obviously safe to load from the specified pointer, we do
257/// a quick local scan of the basic block containing \c ScanFrom, to determine
258/// if the address is already accessed.
259///
260/// This uses the pointee type to determine how many bytes need to be safe to
261/// load from the pointer.
Tim Northover60afa492019-07-09 11:35:35 +0000262bool llvm::isSafeToLoadUnconditionally(Value *V, unsigned Align, APInt &Size,
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +0000263 const DataLayout &DL,
Artur Pilipenko66d6d3e2016-02-11 13:42:59 +0000264 Instruction *ScanFrom,
Sean Silva45835e72016-07-02 23:47:27 +0000265 const DominatorTree *DT) {
Artur Pilipenko0e21d542015-06-25 12:18:43 +0000266 // Zero alignment means that the load has the ABI alignment for the target
267 if (Align == 0)
268 Align = DL.getABITypeAlignment(V->getType()->getPointerElementType());
269 assert(isPowerOf2_32(Align));
270
Artur Pilipenko66d6d3e2016-02-11 13:42:59 +0000271 // If DT is not specified we can't make context-sensitive query
272 const Instruction* CtxI = DT ? ScanFrom : nullptr;
Tim Northover60afa492019-07-09 11:35:35 +0000273 if (isDereferenceableAndAlignedPointer(V, Align, Size, DL, CtxI, DT))
Artur Pilipenkof84dc062016-01-17 12:35:29 +0000274 return true;
275
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +0000276 if (!ScanFrom)
277 return false;
278
Philip Reames26945222019-08-27 19:34:43 +0000279 if (Size.getBitWidth() > 64)
280 return false;
281 const uint64_t LoadSize = Size.getZExtValue();
282
Dan Gohman826bdf82010-05-28 16:19:17 +0000283 // Otherwise, be a little bit aggressive by scanning the local block where we
284 // want to check to see if the pointer is already being loaded or stored
285 // from/to. If so, the previous load or store would have already trapped,
286 // so there is no harm doing an extra load (also, CSE will later eliminate
287 // the load entirely).
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000288 BasicBlock::iterator BBI = ScanFrom->getIterator(),
289 E = ScanFrom->getParent()->begin();
Dan Gohman826bdf82010-05-28 16:19:17 +0000290
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000291 // We can at least always strip pointer casts even though we can't use the
292 // base here.
293 V = V->stripPointerCasts();
294
Dan Gohman826bdf82010-05-28 16:19:17 +0000295 while (BBI != E) {
296 --BBI;
297
298 // If we see a free or a call which may write to memory (i.e. which might do
299 // a free) the pointer could be marked invalid.
300 if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
301 !isa<DbgInfoIntrinsic>(BBI))
302 return false;
303
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000304 Value *AccessedPtr;
Artur Pilipenko0e21d542015-06-25 12:18:43 +0000305 unsigned AccessedAlign;
306 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Eli Friedman525ef012019-01-24 21:31:13 +0000307 // Ignore volatile loads. The execution of a volatile load cannot
308 // be used to prove an address is backed by regular memory; it can,
309 // for example, point to an MMIO register.
310 if (LI->isVolatile())
311 continue;
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000312 AccessedPtr = LI->getPointerOperand();
Artur Pilipenko0e21d542015-06-25 12:18:43 +0000313 AccessedAlign = LI->getAlignment();
314 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Eli Friedman525ef012019-01-24 21:31:13 +0000315 // Ignore volatile stores (see comment for loads).
316 if (SI->isVolatile())
317 continue;
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000318 AccessedPtr = SI->getPointerOperand();
Artur Pilipenko0e21d542015-06-25 12:18:43 +0000319 AccessedAlign = SI->getAlignment();
320 } else
321 continue;
322
323 Type *AccessedTy = AccessedPtr->getType()->getPointerElementType();
324 if (AccessedAlign == 0)
325 AccessedAlign = DL.getABITypeAlignment(AccessedTy);
326 if (AccessedAlign < Align)
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000327 continue;
328
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000329 // Handle trivial cases.
Philip Reames26945222019-08-27 19:34:43 +0000330 if (AccessedPtr == V &&
331 LoadSize <= DL.getTypeStoreSize(AccessedTy))
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000332 return true;
333
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000334 if (AreEquivalentAddressValues(AccessedPtr->stripPointerCasts(), V) &&
Artur Pilipenko0e21d542015-06-25 12:18:43 +0000335 LoadSize <= DL.getTypeStoreSize(AccessedTy))
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000336 return true;
Dan Gohman826bdf82010-05-28 16:19:17 +0000337 }
338 return false;
339}
340
Tim Northover60afa492019-07-09 11:35:35 +0000341bool llvm::isSafeToLoadUnconditionally(Value *V, Type *Ty, unsigned Align,
342 const DataLayout &DL,
343 Instruction *ScanFrom,
344 const DominatorTree *DT) {
345 APInt Size(DL.getIndexTypeSizeInBits(V->getType()), DL.getTypeStoreSize(Ty));
346 return isSafeToLoadUnconditionally(V, Align, Size, DL, ScanFrom, DT);
347}
348
349 /// DefMaxInstsToScan - the default number of maximum instructions
Larisse Voufo532bf712015-09-18 19:14:35 +0000350/// to scan in the block, used by FindAvailableLoadedValue().
351/// FindAvailableLoadedValue() was introduced in r60148, to improve jump
352/// threading in part by eliminating partially redundant loads.
353/// At that point, the value of MaxInstsToScan was already set to '6'
354/// without documented explanation.
355cl::opt<unsigned>
356llvm::DefMaxInstsToScan("available-load-scan-limit", cl::init(6), cl::Hidden,
357 cl::desc("Use this to specify the default maximum number of instructions "
358 "to scan backward from a given instruction, when searching for "
359 "available loaded value"));
360
Eli Friedman02419a92016-08-08 04:10:22 +0000361Value *llvm::FindAvailableLoadedValue(LoadInst *Load,
362 BasicBlock *ScanBB,
Dan Gohman826bdf82010-05-28 16:19:17 +0000363 BasicBlock::iterator &ScanFrom,
364 unsigned MaxInstsToScan,
Xin Tongaef0fcb2017-03-19 15:27:52 +0000365 AliasAnalysis *AA, bool *IsLoad,
Jun Bum Lim180bc5a2017-02-02 15:12:34 +0000366 unsigned *NumScanedInst) {
Xin Tongaef0fcb2017-03-19 15:27:52 +0000367 // Don't CSE load that is volatile or anything stronger than unordered.
Anna Thomas9ad45ad2016-07-08 22:15:08 +0000368 if (!Load->isUnordered())
369 return nullptr;
370
Xin Tongaef0fcb2017-03-19 15:27:52 +0000371 return FindAvailablePtrLoadStore(
372 Load->getPointerOperand(), Load->getType(), Load->isAtomic(), ScanBB,
373 ScanFrom, MaxInstsToScan, AA, IsLoad, NumScanedInst);
374}
375
376Value *llvm::FindAvailablePtrLoadStore(Value *Ptr, Type *AccessTy,
377 bool AtLeastAtomic, BasicBlock *ScanBB,
378 BasicBlock::iterator &ScanFrom,
379 unsigned MaxInstsToScan,
380 AliasAnalysis *AA, bool *IsLoadCSE,
381 unsigned *NumScanedInst) {
382 if (MaxInstsToScan == 0)
383 MaxInstsToScan = ~0U;
384
Mehdi Amini46a43552015-03-04 18:43:29 +0000385 const DataLayout &DL = ScanBB->getModule()->getDataLayout();
Anna Thomas9ad45ad2016-07-08 22:15:08 +0000386
Chandler Carruth1a3c2c42014-11-25 08:20:27 +0000387 // Try to get the store size for the type.
George Burgess IV8c5413f32018-12-23 03:10:56 +0000388 auto AccessSize = LocationSize::precise(DL.getTypeStoreSize(AccessTy));
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000389
390 Value *StrippedPtr = Ptr->stripPointerCasts();
Chandler Carruthd67244d2014-10-18 23:19:03 +0000391
Dan Gohman826bdf82010-05-28 16:19:17 +0000392 while (ScanFrom != ScanBB->begin()) {
393 // We must ignore debug info directives when counting (otherwise they
394 // would affect codegen).
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000395 Instruction *Inst = &*--ScanFrom;
Dan Gohman826bdf82010-05-28 16:19:17 +0000396 if (isa<DbgInfoIntrinsic>(Inst))
397 continue;
398
399 // Restore ScanFrom to expected value in case next test succeeds
400 ScanFrom++;
Chandler Carruthd67244d2014-10-18 23:19:03 +0000401
Jun Bum Lim180bc5a2017-02-02 15:12:34 +0000402 if (NumScanedInst)
403 ++(*NumScanedInst);
404
Dan Gohman826bdf82010-05-28 16:19:17 +0000405 // Don't scan huge blocks.
Chandler Carruthd67244d2014-10-18 23:19:03 +0000406 if (MaxInstsToScan-- == 0)
407 return nullptr;
408
Dan Gohman826bdf82010-05-28 16:19:17 +0000409 --ScanFrom;
410 // If this is a load of Ptr, the loaded value is available.
Eli Friedman4419cd22011-08-15 21:56:39 +0000411 // (This is true even if the load is volatile or atomic, although
412 // those cases are unlikely.)
Reid Klecknerfbd5eef2016-06-24 18:42:58 +0000413 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
414 if (AreEquivalentAddressValues(
415 LI->getPointerOperand()->stripPointerCasts(), StrippedPtr) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000416 CastInst::isBitOrNoopPointerCastable(LI->getType(), AccessTy, DL)) {
Philip Reames92c43692016-04-21 16:51:08 +0000417
418 // We can value forward from an atomic to a non-atomic, but not the
419 // other way around.
Xin Tongaef0fcb2017-03-19 15:27:52 +0000420 if (LI->isAtomic() < AtLeastAtomic)
Philip Reames92c43692016-04-21 16:51:08 +0000421 return nullptr;
422
Eli Friedmanbd254a62016-06-16 02:33:42 +0000423 if (IsLoadCSE)
424 *IsLoadCSE = true;
Dan Gohman826bdf82010-05-28 16:19:17 +0000425 return LI;
Chris Lattner87fa77b2012-03-13 18:07:41 +0000426 }
Chandler Carruthd67244d2014-10-18 23:19:03 +0000427
Dan Gohman826bdf82010-05-28 16:19:17 +0000428 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000429 Value *StorePtr = SI->getPointerOperand()->stripPointerCasts();
Dan Gohman826bdf82010-05-28 16:19:17 +0000430 // If this is a store through Ptr, the value is available!
Eli Friedman4419cd22011-08-15 21:56:39 +0000431 // (This is true even if the store is volatile or atomic, although
432 // those cases are unlikely.)
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000433 if (AreEquivalentAddressValues(StorePtr, StrippedPtr) &&
Chandler Carruth1a3c2c42014-11-25 08:20:27 +0000434 CastInst::isBitOrNoopPointerCastable(SI->getValueOperand()->getType(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000435 AccessTy, DL)) {
Philip Reames92c43692016-04-21 16:51:08 +0000436
437 // We can value forward from an atomic to a non-atomic, but not the
438 // other way around.
Xin Tongaef0fcb2017-03-19 15:27:52 +0000439 if (SI->isAtomic() < AtLeastAtomic)
Philip Reames92c43692016-04-21 16:51:08 +0000440 return nullptr;
441
Eli Friedman02419a92016-08-08 04:10:22 +0000442 if (IsLoadCSE)
443 *IsLoadCSE = false;
Dan Gohman826bdf82010-05-28 16:19:17 +0000444 return SI->getOperand(0);
Chris Lattner87fa77b2012-03-13 18:07:41 +0000445 }
Chandler Carruthd67244d2014-10-18 23:19:03 +0000446
Chandler Carrutha32038b2014-10-20 10:03:01 +0000447 // If both StrippedPtr and StorePtr reach all the way to an alloca or
448 // global and they are different, ignore the store. This is a trivial form
449 // of alias analysis that is important for reg2mem'd code.
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000450 if ((isa<AllocaInst>(StrippedPtr) || isa<GlobalVariable>(StrippedPtr)) &&
Chandler Carrutha32038b2014-10-20 10:03:01 +0000451 (isa<AllocaInst>(StorePtr) || isa<GlobalVariable>(StorePtr)) &&
452 StrippedPtr != StorePtr)
Dan Gohman826bdf82010-05-28 16:19:17 +0000453 continue;
Chandler Carruthd67244d2014-10-18 23:19:03 +0000454
Dan Gohman826bdf82010-05-28 16:19:17 +0000455 // If we have alias analysis and it says the store won't modify the loaded
456 // value, ignore the store.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000457 if (AA && !isModSet(AA->getModRefInfo(SI, StrippedPtr, AccessSize)))
Dan Gohman826bdf82010-05-28 16:19:17 +0000458 continue;
Chandler Carruthd67244d2014-10-18 23:19:03 +0000459
Dan Gohman826bdf82010-05-28 16:19:17 +0000460 // Otherwise the store that may or may not alias the pointer, bail out.
461 ++ScanFrom;
Craig Topper9f008862014-04-15 04:59:12 +0000462 return nullptr;
Dan Gohman826bdf82010-05-28 16:19:17 +0000463 }
Chandler Carruthd67244d2014-10-18 23:19:03 +0000464
Dan Gohman826bdf82010-05-28 16:19:17 +0000465 // If this is some other instruction that may clobber Ptr, bail out.
466 if (Inst->mayWriteToMemory()) {
467 // If alias analysis claims that it really won't modify the load,
468 // ignore it.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000469 if (AA && !isModSet(AA->getModRefInfo(Inst, StrippedPtr, AccessSize)))
Dan Gohman826bdf82010-05-28 16:19:17 +0000470 continue;
Chandler Carruthd67244d2014-10-18 23:19:03 +0000471
Dan Gohman826bdf82010-05-28 16:19:17 +0000472 // May modify the pointer, bail out.
473 ++ScanFrom;
Craig Topper9f008862014-04-15 04:59:12 +0000474 return nullptr;
Dan Gohman826bdf82010-05-28 16:19:17 +0000475 }
476 }
Chandler Carruthd67244d2014-10-18 23:19:03 +0000477
Dan Gohman826bdf82010-05-28 16:19:17 +0000478 // Got to the start of the block, we didn't find it, but are done for this
479 // block.
Craig Topper9f008862014-04-15 04:59:12 +0000480 return nullptr;
Dan Gohman826bdf82010-05-28 16:19:17 +0000481}