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