10b57cec5SDimitry Andric //===- Loads.cpp - Local load analysis ------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file defines simple local analyses for load instructions.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "llvm/Analysis/Loads.h"
140b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
15fe6060f1SDimitry Andric #include "llvm/Analysis/AssumeBundleQueries.h"
168bcb0991SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
17e8d8bef9SDimitry Andric #include "llvm/Analysis/MemoryBuiltins.h"
18fe6060f1SDimitry Andric #include "llvm/Analysis/MemoryLocation.h"
198bcb0991SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
208bcb0991SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h"
210b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
220b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
230b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
240b57cec5SDimitry Andric #include "llvm/IR/Module.h"
250b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
260b57cec5SDimitry Andric 
270b57cec5SDimitry Andric using namespace llvm;
280b57cec5SDimitry Andric 
isAligned(const Value * Base,const APInt & Offset,Align Alignment,const DataLayout & DL)298bcb0991SDimitry Andric static bool isAligned(const Value *Base, const APInt &Offset, Align Alignment,
308bcb0991SDimitry Andric                       const DataLayout &DL) {
315ffd83dbSDimitry Andric   Align BA = Base->getPointerAlignment(DL);
3206c3fb27SDimitry Andric   return BA >= Alignment && Offset.isAligned(BA);
330b57cec5SDimitry Andric }
340b57cec5SDimitry Andric 
350b57cec5SDimitry Andric /// Test if V is always a pointer to allocated and suitably aligned memory for
360b57cec5SDimitry Andric /// a simple load or store.
isDereferenceableAndAlignedPointer(const Value * V,Align Alignment,const APInt & Size,const DataLayout & DL,const Instruction * CtxI,AssumptionCache * AC,const DominatorTree * DT,const TargetLibraryInfo * TLI,SmallPtrSetImpl<const Value * > & Visited,unsigned MaxDepth)370b57cec5SDimitry Andric static bool isDereferenceableAndAlignedPointer(
388bcb0991SDimitry Andric     const Value *V, Align Alignment, const APInt &Size, const DataLayout &DL,
39bdd1243dSDimitry Andric     const Instruction *CtxI, AssumptionCache *AC, const DominatorTree *DT,
40fe6060f1SDimitry Andric     const TargetLibraryInfo *TLI, SmallPtrSetImpl<const Value *> &Visited,
41fe6060f1SDimitry Andric     unsigned MaxDepth) {
425ffd83dbSDimitry Andric   assert(V->getType()->isPointerTy() && "Base must be pointer");
435ffd83dbSDimitry Andric 
445ffd83dbSDimitry Andric   // Recursion limit.
455ffd83dbSDimitry Andric   if (MaxDepth-- == 0)
465ffd83dbSDimitry Andric     return false;
475ffd83dbSDimitry Andric 
480b57cec5SDimitry Andric   // Already visited?  Bail out, we've likely hit unreachable code.
490b57cec5SDimitry Andric   if (!Visited.insert(V).second)
500b57cec5SDimitry Andric     return false;
510b57cec5SDimitry Andric 
520b57cec5SDimitry Andric   // Note that it is not safe to speculate into a malloc'd region because
530b57cec5SDimitry Andric   // malloc may return null.
540b57cec5SDimitry Andric 
550b57cec5SDimitry Andric   // For GEPs, determine if the indexing lands within the allocated object.
560b57cec5SDimitry Andric   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
570b57cec5SDimitry Andric     const Value *Base = GEP->getPointerOperand();
580b57cec5SDimitry Andric 
590b57cec5SDimitry Andric     APInt Offset(DL.getIndexTypeSizeInBits(GEP->getType()), 0);
600b57cec5SDimitry Andric     if (!GEP->accumulateConstantOffset(DL, Offset) || Offset.isNegative() ||
618bcb0991SDimitry Andric         !Offset.urem(APInt(Offset.getBitWidth(), Alignment.value()))
628bcb0991SDimitry Andric              .isMinValue())
630b57cec5SDimitry Andric       return false;
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric     // If the base pointer is dereferenceable for Offset+Size bytes, then the
660b57cec5SDimitry Andric     // GEP (== Base + Offset) is dereferenceable for Size bytes.  If the base
670b57cec5SDimitry Andric     // pointer is aligned to Align bytes, and the Offset is divisible by Align
680b57cec5SDimitry Andric     // then the GEP (== Base + Offset == k_0 * Align + k_1 * Align) is also
690b57cec5SDimitry Andric     // aligned to Align bytes.
700b57cec5SDimitry Andric 
710b57cec5SDimitry Andric     // Offset and Size may have different bit widths if we have visited an
720b57cec5SDimitry Andric     // addrspacecast, so we can't do arithmetic directly on the APInt values.
730b57cec5SDimitry Andric     return isDereferenceableAndAlignedPointer(
748bcb0991SDimitry Andric         Base, Alignment, Offset + Size.sextOrTrunc(Offset.getBitWidth()), DL,
75bdd1243dSDimitry Andric         CtxI, AC, DT, TLI, Visited, MaxDepth);
760b57cec5SDimitry Andric   }
770b57cec5SDimitry Andric 
78bdd1243dSDimitry Andric   // bitcast instructions are no-ops as far as dereferenceability is concerned.
79bdd1243dSDimitry Andric   if (const BitCastOperator *BC = dyn_cast<BitCastOperator>(V)) {
80bdd1243dSDimitry Andric     if (BC->getSrcTy()->isPointerTy())
81bdd1243dSDimitry Andric       return isDereferenceableAndAlignedPointer(
82bdd1243dSDimitry Andric         BC->getOperand(0), Alignment, Size, DL, CtxI, AC, DT, TLI,
83fe6060f1SDimitry Andric           Visited, MaxDepth);
84bdd1243dSDimitry Andric   }
85bdd1243dSDimitry Andric 
86bdd1243dSDimitry Andric   // Recurse into both hands of select.
87bdd1243dSDimitry Andric   if (const SelectInst *Sel = dyn_cast<SelectInst>(V)) {
88bdd1243dSDimitry Andric     return isDereferenceableAndAlignedPointer(Sel->getTrueValue(), Alignment,
89bdd1243dSDimitry Andric                                               Size, DL, CtxI, AC, DT, TLI,
90bdd1243dSDimitry Andric                                               Visited, MaxDepth) &&
91bdd1243dSDimitry Andric            isDereferenceableAndAlignedPointer(Sel->getFalseValue(), Alignment,
92bdd1243dSDimitry Andric                                               Size, DL, CtxI, AC, DT, TLI,
93bdd1243dSDimitry Andric                                               Visited, MaxDepth);
94bdd1243dSDimitry Andric   }
95bdd1243dSDimitry Andric 
96bdd1243dSDimitry Andric   bool CheckForNonNull, CheckForFreed;
97bdd1243dSDimitry Andric   APInt KnownDerefBytes(Size.getBitWidth(),
98bdd1243dSDimitry Andric                         V->getPointerDereferenceableBytes(DL, CheckForNonNull,
99bdd1243dSDimitry Andric                                                           CheckForFreed));
100bdd1243dSDimitry Andric   if (KnownDerefBytes.getBoolValue() && KnownDerefBytes.uge(Size) &&
101bdd1243dSDimitry Andric       !CheckForFreed)
102bdd1243dSDimitry Andric     if (!CheckForNonNull || isKnownNonZero(V, DL, 0, AC, CtxI, DT)) {
103bdd1243dSDimitry Andric       // As we recursed through GEPs to get here, we've incrementally checked
104bdd1243dSDimitry Andric       // that each step advanced by a multiple of the alignment. If our base is
105bdd1243dSDimitry Andric       // properly aligned, then the original offset accessed must also be.
106bdd1243dSDimitry Andric       APInt Offset(DL.getTypeStoreSizeInBits(V->getType()), 0);
107bdd1243dSDimitry Andric       return isAligned(V, Offset, Alignment, DL);
108bdd1243dSDimitry Andric     }
109bdd1243dSDimitry Andric 
110bdd1243dSDimitry Andric   /// TODO refactor this function to be able to search independently for
111bdd1243dSDimitry Andric   /// Dereferencability and Alignment requirements.
112bdd1243dSDimitry Andric 
1130b57cec5SDimitry Andric 
114e8d8bef9SDimitry Andric   if (const auto *Call = dyn_cast<CallBase>(V)) {
1158bcb0991SDimitry Andric     if (auto *RP = getArgumentAliasingToReturnedPointer(Call, true))
1168bcb0991SDimitry Andric       return isDereferenceableAndAlignedPointer(RP, Alignment, Size, DL, CtxI,
117bdd1243dSDimitry Andric                                                 AC, DT, TLI, Visited, MaxDepth);
1180b57cec5SDimitry Andric 
119e8d8bef9SDimitry Andric     // If we have a call we can't recurse through, check to see if this is an
120e8d8bef9SDimitry Andric     // allocation function for which we can establish an minimum object size.
121e8d8bef9SDimitry Andric     // Such a minimum object size is analogous to a deref_or_null attribute in
122e8d8bef9SDimitry Andric     // that we still need to prove the result non-null at point of use.
123e8d8bef9SDimitry Andric     // NOTE: We can only use the object size as a base fact as we a) need to
124e8d8bef9SDimitry Andric     // prove alignment too, and b) don't want the compile time impact of a
125e8d8bef9SDimitry Andric     // separate recursive walk.
126e8d8bef9SDimitry Andric     ObjectSizeOpts Opts;
127e8d8bef9SDimitry Andric     // TODO: It may be okay to round to align, but that would imply that
128e8d8bef9SDimitry Andric     // accessing slightly out of bounds was legal, and we're currently
129e8d8bef9SDimitry Andric     // inconsistent about that.  For the moment, be conservative.
130e8d8bef9SDimitry Andric     Opts.RoundToAlign = false;
131e8d8bef9SDimitry Andric     Opts.NullIsUnknownSize = true;
132e8d8bef9SDimitry Andric     uint64_t ObjSize;
133fe6060f1SDimitry Andric     if (getObjectSize(V, ObjSize, DL, TLI, Opts)) {
134e8d8bef9SDimitry Andric       APInt KnownDerefBytes(Size.getBitWidth(), ObjSize);
135e8d8bef9SDimitry Andric       if (KnownDerefBytes.getBoolValue() && KnownDerefBytes.uge(Size) &&
136bdd1243dSDimitry Andric           isKnownNonZero(V, DL, 0, AC, CtxI, DT) && !V->canBeFreed()) {
137e8d8bef9SDimitry Andric         // As we recursed through GEPs to get here, we've incrementally
138e8d8bef9SDimitry Andric         // checked that each step advanced by a multiple of the alignment. If
139e8d8bef9SDimitry Andric         // our base is properly aligned, then the original offset accessed
140e8d8bef9SDimitry Andric         // must also be.
141bdd1243dSDimitry Andric         APInt Offset(DL.getTypeStoreSizeInBits(V->getType()), 0);
142e8d8bef9SDimitry Andric         return isAligned(V, Offset, Alignment, DL);
143e8d8bef9SDimitry Andric       }
144e8d8bef9SDimitry Andric     }
145e8d8bef9SDimitry Andric   }
146e8d8bef9SDimitry Andric 
147bdd1243dSDimitry Andric   // For gc.relocate, look through relocations
148bdd1243dSDimitry Andric   if (const GCRelocateInst *RelocateInst = dyn_cast<GCRelocateInst>(V))
149bdd1243dSDimitry Andric     return isDereferenceableAndAlignedPointer(RelocateInst->getDerivedPtr(),
150bdd1243dSDimitry Andric                                               Alignment, Size, DL, CtxI, AC, DT,
151bdd1243dSDimitry Andric                                               TLI, Visited, MaxDepth);
152bdd1243dSDimitry Andric 
153bdd1243dSDimitry Andric   if (const AddrSpaceCastOperator *ASC = dyn_cast<AddrSpaceCastOperator>(V))
154bdd1243dSDimitry Andric     return isDereferenceableAndAlignedPointer(ASC->getOperand(0), Alignment,
155bdd1243dSDimitry Andric                                               Size, DL, CtxI, AC, DT, TLI,
156bdd1243dSDimitry Andric                                               Visited, MaxDepth);
157bdd1243dSDimitry Andric 
158bdd1243dSDimitry Andric   if (CtxI) {
159bdd1243dSDimitry Andric     /// Look through assumes to see if both dereferencability and alignment can
160bdd1243dSDimitry Andric     /// be provent by an assume
161bdd1243dSDimitry Andric     RetainedKnowledge AlignRK;
162bdd1243dSDimitry Andric     RetainedKnowledge DerefRK;
163bdd1243dSDimitry Andric     if (getKnowledgeForValue(
164bdd1243dSDimitry Andric             V, {Attribute::Dereferenceable, Attribute::Alignment}, AC,
165bdd1243dSDimitry Andric             [&](RetainedKnowledge RK, Instruction *Assume, auto) {
166bdd1243dSDimitry Andric               if (!isValidAssumeForContext(Assume, CtxI))
167bdd1243dSDimitry Andric                 return false;
168bdd1243dSDimitry Andric               if (RK.AttrKind == Attribute::Alignment)
169bdd1243dSDimitry Andric                 AlignRK = std::max(AlignRK, RK);
170bdd1243dSDimitry Andric               if (RK.AttrKind == Attribute::Dereferenceable)
171bdd1243dSDimitry Andric                 DerefRK = std::max(DerefRK, RK);
172bdd1243dSDimitry Andric               if (AlignRK && DerefRK && AlignRK.ArgValue >= Alignment.value() &&
173bdd1243dSDimitry Andric                   DerefRK.ArgValue >= Size.getZExtValue())
174bdd1243dSDimitry Andric                 return true; // We have found what we needed so we stop looking
175bdd1243dSDimitry Andric               return false;  // Other assumes may have better information. so
176bdd1243dSDimitry Andric                              // keep looking
177bdd1243dSDimitry Andric             }))
178bdd1243dSDimitry Andric       return true;
179bdd1243dSDimitry Andric   }
180bdd1243dSDimitry Andric 
1810b57cec5SDimitry Andric   // If we don't know, assume the worst.
1820b57cec5SDimitry Andric   return false;
1830b57cec5SDimitry Andric }
1840b57cec5SDimitry Andric 
isDereferenceableAndAlignedPointer(const Value * V,Align Alignment,const APInt & Size,const DataLayout & DL,const Instruction * CtxI,AssumptionCache * AC,const DominatorTree * DT,const TargetLibraryInfo * TLI)185bdd1243dSDimitry Andric bool llvm::isDereferenceableAndAlignedPointer(
186bdd1243dSDimitry Andric     const Value *V, Align Alignment, const APInt &Size, const DataLayout &DL,
187bdd1243dSDimitry Andric     const Instruction *CtxI, AssumptionCache *AC, const DominatorTree *DT,
188fe6060f1SDimitry Andric     const TargetLibraryInfo *TLI) {
1898bcb0991SDimitry Andric   // Note: At the moment, Size can be zero.  This ends up being interpreted as
1908bcb0991SDimitry Andric   // a query of whether [Base, V] is dereferenceable and V is aligned (since
1918bcb0991SDimitry Andric   // that's what the implementation happened to do).  It's unclear if this is
1928bcb0991SDimitry Andric   // the desired semantic, but at least SelectionDAG does exercise this case.
1938bcb0991SDimitry Andric 
1940b57cec5SDimitry Andric   SmallPtrSet<const Value *, 32> Visited;
195bdd1243dSDimitry Andric   return ::isDereferenceableAndAlignedPointer(V, Alignment, Size, DL, CtxI, AC,
196bdd1243dSDimitry Andric                                               DT, TLI, Visited, 16);
1970b57cec5SDimitry Andric }
1980b57cec5SDimitry Andric 
isDereferenceableAndAlignedPointer(const Value * V,Type * Ty,Align Alignment,const DataLayout & DL,const Instruction * CtxI,AssumptionCache * AC,const DominatorTree * DT,const TargetLibraryInfo * TLI)199bdd1243dSDimitry Andric bool llvm::isDereferenceableAndAlignedPointer(
200bdd1243dSDimitry Andric     const Value *V, Type *Ty, Align Alignment, const DataLayout &DL,
201bdd1243dSDimitry Andric     const Instruction *CtxI, AssumptionCache *AC, const DominatorTree *DT,
202fe6060f1SDimitry Andric     const TargetLibraryInfo *TLI) {
2035ffd83dbSDimitry Andric   // For unsized types or scalable vectors we don't know exactly how many bytes
2045ffd83dbSDimitry Andric   // are dereferenced, so bail out.
20506c3fb27SDimitry Andric   if (!Ty->isSized() || Ty->isScalableTy())
2068bcb0991SDimitry Andric     return false;
2078bcb0991SDimitry Andric 
2080b57cec5SDimitry Andric   // When dereferenceability information is provided by a dereferenceable
2090b57cec5SDimitry Andric   // attribute, we know exactly how many bytes are dereferenceable. If we can
2100b57cec5SDimitry Andric   // determine the exact offset to the attributed variable, we can use that
2110b57cec5SDimitry Andric   // information here.
2120b57cec5SDimitry Andric 
213480093f4SDimitry Andric   APInt AccessSize(DL.getPointerTypeSizeInBits(V->getType()),
2148bcb0991SDimitry Andric                    DL.getTypeStoreSize(Ty));
2158bcb0991SDimitry Andric   return isDereferenceableAndAlignedPointer(V, Alignment, AccessSize, DL, CtxI,
216bdd1243dSDimitry Andric                                             AC, DT, TLI);
2170b57cec5SDimitry Andric }
2180b57cec5SDimitry Andric 
isDereferenceablePointer(const Value * V,Type * Ty,const DataLayout & DL,const Instruction * CtxI,AssumptionCache * AC,const DominatorTree * DT,const TargetLibraryInfo * TLI)2190b57cec5SDimitry Andric bool llvm::isDereferenceablePointer(const Value *V, Type *Ty,
2200b57cec5SDimitry Andric                                     const DataLayout &DL,
2210b57cec5SDimitry Andric                                     const Instruction *CtxI,
222bdd1243dSDimitry Andric                                     AssumptionCache *AC,
223fe6060f1SDimitry Andric                                     const DominatorTree *DT,
224fe6060f1SDimitry Andric                                     const TargetLibraryInfo *TLI) {
225bdd1243dSDimitry Andric   return isDereferenceableAndAlignedPointer(V, Ty, Align(1), DL, CtxI, AC, DT,
226bdd1243dSDimitry Andric                                             TLI);
2270b57cec5SDimitry Andric }
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric /// Test if A and B will obviously have the same value.
2300b57cec5SDimitry Andric ///
2310b57cec5SDimitry Andric /// This includes recognizing that %t0 and %t1 will have the same
2320b57cec5SDimitry Andric /// value in code like this:
2330b57cec5SDimitry Andric /// \code
2340b57cec5SDimitry Andric ///   %t0 = getelementptr \@a, 0, 3
2350b57cec5SDimitry Andric ///   store i32 0, i32* %t0
2360b57cec5SDimitry Andric ///   %t1 = getelementptr \@a, 0, 3
2370b57cec5SDimitry Andric ///   %t2 = load i32* %t1
2380b57cec5SDimitry Andric /// \endcode
2390b57cec5SDimitry Andric ///
AreEquivalentAddressValues(const Value * A,const Value * B)2400b57cec5SDimitry Andric static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
2410b57cec5SDimitry Andric   // Test if the values are trivially equivalent.
2420b57cec5SDimitry Andric   if (A == B)
2430b57cec5SDimitry Andric     return true;
2440b57cec5SDimitry Andric 
2450b57cec5SDimitry Andric   // Test if the values come from identical arithmetic instructions.
2460b57cec5SDimitry Andric   // Use isIdenticalToWhenDefined instead of isIdenticalTo because
2470b57cec5SDimitry Andric   // this function is only used when one address use dominates the
2480b57cec5SDimitry Andric   // other, which means that they'll always either have the same
2490b57cec5SDimitry Andric   // value or one of them will have an undefined value.
2500b57cec5SDimitry Andric   if (isa<BinaryOperator>(A) || isa<CastInst>(A) || isa<PHINode>(A) ||
2510b57cec5SDimitry Andric       isa<GetElementPtrInst>(A))
2520b57cec5SDimitry Andric     if (const Instruction *BI = dyn_cast<Instruction>(B))
2530b57cec5SDimitry Andric       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
2540b57cec5SDimitry Andric         return true;
2550b57cec5SDimitry Andric 
2560b57cec5SDimitry Andric   // Otherwise they may not be equivalent.
2570b57cec5SDimitry Andric   return false;
2580b57cec5SDimitry Andric }
2590b57cec5SDimitry Andric 
isDereferenceableAndAlignedInLoop(LoadInst * LI,Loop * L,ScalarEvolution & SE,DominatorTree & DT,AssumptionCache * AC)2608bcb0991SDimitry Andric bool llvm::isDereferenceableAndAlignedInLoop(LoadInst *LI, Loop *L,
2618bcb0991SDimitry Andric                                              ScalarEvolution &SE,
262bdd1243dSDimitry Andric                                              DominatorTree &DT,
263bdd1243dSDimitry Andric                                              AssumptionCache *AC) {
2648bcb0991SDimitry Andric   auto &DL = LI->getModule()->getDataLayout();
2658bcb0991SDimitry Andric   Value *Ptr = LI->getPointerOperand();
2668bcb0991SDimitry Andric 
2678bcb0991SDimitry Andric   APInt EltSize(DL.getIndexTypeSizeInBits(Ptr->getType()),
268bdd1243dSDimitry Andric                 DL.getTypeStoreSize(LI->getType()).getFixedValue());
2695ffd83dbSDimitry Andric   const Align Alignment = LI->getAlign();
2708bcb0991SDimitry Andric 
2718bcb0991SDimitry Andric   Instruction *HeaderFirstNonPHI = L->getHeader()->getFirstNonPHI();
2728bcb0991SDimitry Andric 
2738bcb0991SDimitry Andric   // If given a uniform (i.e. non-varying) address, see if we can prove the
2748bcb0991SDimitry Andric   // access is safe within the loop w/o needing predication.
2758bcb0991SDimitry Andric   if (L->isLoopInvariant(Ptr))
2768bcb0991SDimitry Andric     return isDereferenceableAndAlignedPointer(Ptr, Alignment, EltSize, DL,
277bdd1243dSDimitry Andric                                               HeaderFirstNonPHI, AC, &DT);
2788bcb0991SDimitry Andric 
2798bcb0991SDimitry Andric   // Otherwise, check to see if we have a repeating access pattern where we can
2808bcb0991SDimitry Andric   // prove that all accesses are well aligned and dereferenceable.
2818bcb0991SDimitry Andric   auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Ptr));
2828bcb0991SDimitry Andric   if (!AddRec || AddRec->getLoop() != L || !AddRec->isAffine())
2838bcb0991SDimitry Andric     return false;
2848bcb0991SDimitry Andric   auto* Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(SE));
2858bcb0991SDimitry Andric   if (!Step)
2868bcb0991SDimitry Andric     return false;
2878bcb0991SDimitry Andric 
288e8d8bef9SDimitry Andric   auto TC = SE.getSmallConstantMaxTripCount(L);
2898bcb0991SDimitry Andric   if (!TC)
2908bcb0991SDimitry Andric     return false;
2918bcb0991SDimitry Andric 
29206c3fb27SDimitry Andric   // TODO: Handle overlapping accesses.
29306c3fb27SDimitry Andric   // We should be computing AccessSize as (TC - 1) * Step + EltSize.
29406c3fb27SDimitry Andric   if (EltSize.sgt(Step->getAPInt()))
2958bcb0991SDimitry Andric     return false;
29606c3fb27SDimitry Andric 
29706c3fb27SDimitry Andric   // Compute the total access size for access patterns with unit stride and
29806c3fb27SDimitry Andric   // patterns with gaps. For patterns with unit stride, Step and EltSize are the
29906c3fb27SDimitry Andric   // same.
30006c3fb27SDimitry Andric   // For patterns with gaps (i.e. non unit stride), we are
30106c3fb27SDimitry Andric   // accessing EltSize bytes at every Step.
30206c3fb27SDimitry Andric   APInt AccessSize = TC * Step->getAPInt();
30306c3fb27SDimitry Andric 
30406c3fb27SDimitry Andric   assert(SE.isLoopInvariant(AddRec->getStart(), L) &&
30506c3fb27SDimitry Andric          "implied by addrec definition");
30606c3fb27SDimitry Andric   Value *Base = nullptr;
30706c3fb27SDimitry Andric   if (auto *StartS = dyn_cast<SCEVUnknown>(AddRec->getStart())) {
30806c3fb27SDimitry Andric     Base = StartS->getValue();
30906c3fb27SDimitry Andric   } else if (auto *StartS = dyn_cast<SCEVAddExpr>(AddRec->getStart())) {
31006c3fb27SDimitry Andric     // Handle (NewBase + offset) as start value.
31106c3fb27SDimitry Andric     const auto *Offset = dyn_cast<SCEVConstant>(StartS->getOperand(0));
31206c3fb27SDimitry Andric     const auto *NewBase = dyn_cast<SCEVUnknown>(StartS->getOperand(1));
31306c3fb27SDimitry Andric     if (StartS->getNumOperands() == 2 && Offset && NewBase) {
31406c3fb27SDimitry Andric       // For the moment, restrict ourselves to the case where the offset is a
31506c3fb27SDimitry Andric       // multiple of the requested alignment and the base is aligned.
31606c3fb27SDimitry Andric       // TODO: generalize if a case found which warrants
31706c3fb27SDimitry Andric       if (Offset->getAPInt().urem(Alignment.value()) != 0)
31806c3fb27SDimitry Andric         return false;
31906c3fb27SDimitry Andric       Base = NewBase->getValue();
32006c3fb27SDimitry Andric       bool Overflow = false;
32106c3fb27SDimitry Andric       AccessSize = AccessSize.uadd_ov(Offset->getAPInt(), Overflow);
32206c3fb27SDimitry Andric       if (Overflow)
32306c3fb27SDimitry Andric         return false;
32406c3fb27SDimitry Andric     }
32506c3fb27SDimitry Andric   }
32606c3fb27SDimitry Andric 
32706c3fb27SDimitry Andric   if (!Base)
32806c3fb27SDimitry Andric     return false;
3298bcb0991SDimitry Andric 
3308bcb0991SDimitry Andric   // For the moment, restrict ourselves to the case where the access size is a
3318bcb0991SDimitry Andric   // multiple of the requested alignment and the base is aligned.
3328bcb0991SDimitry Andric   // TODO: generalize if a case found which warrants
3338bcb0991SDimitry Andric   if (EltSize.urem(Alignment.value()) != 0)
3348bcb0991SDimitry Andric     return false;
3358bcb0991SDimitry Andric   return isDereferenceableAndAlignedPointer(Base, Alignment, AccessSize, DL,
336bdd1243dSDimitry Andric                                             HeaderFirstNonPHI, AC, &DT);
3378bcb0991SDimitry Andric }
3388bcb0991SDimitry Andric 
3390b57cec5SDimitry Andric /// Check if executing a load of this pointer value cannot trap.
3400b57cec5SDimitry Andric ///
3410b57cec5SDimitry Andric /// If DT and ScanFrom are specified this method performs context-sensitive
3420b57cec5SDimitry Andric /// analysis and returns true if it is safe to load immediately before ScanFrom.
3430b57cec5SDimitry Andric ///
3440b57cec5SDimitry Andric /// If it is not obviously safe to load from the specified pointer, we do
3450b57cec5SDimitry Andric /// a quick local scan of the basic block containing \c ScanFrom, to determine
3460b57cec5SDimitry Andric /// if the address is already accessed.
3470b57cec5SDimitry Andric ///
3480b57cec5SDimitry Andric /// This uses the pointee type to determine how many bytes need to be safe to
3490b57cec5SDimitry Andric /// load from the pointer.
isSafeToLoadUnconditionally(Value * V,Align Alignment,APInt & Size,const DataLayout & DL,Instruction * ScanFrom,AssumptionCache * AC,const DominatorTree * DT,const TargetLibraryInfo * TLI)3505ffd83dbSDimitry Andric bool llvm::isSafeToLoadUnconditionally(Value *V, Align Alignment, APInt &Size,
3510b57cec5SDimitry Andric                                        const DataLayout &DL,
3520b57cec5SDimitry Andric                                        Instruction *ScanFrom,
353bdd1243dSDimitry Andric                                        AssumptionCache *AC,
354fe6060f1SDimitry Andric                                        const DominatorTree *DT,
355fe6060f1SDimitry Andric                                        const TargetLibraryInfo *TLI) {
3560b57cec5SDimitry Andric   // If DT is not specified we can't make context-sensitive query
3570b57cec5SDimitry Andric   const Instruction* CtxI = DT ? ScanFrom : nullptr;
358bdd1243dSDimitry Andric   if (isDereferenceableAndAlignedPointer(V, Alignment, Size, DL, CtxI, AC, DT,
359bdd1243dSDimitry Andric                                          TLI))
3600b57cec5SDimitry Andric     return true;
3610b57cec5SDimitry Andric 
3620b57cec5SDimitry Andric   if (!ScanFrom)
3630b57cec5SDimitry Andric     return false;
3640b57cec5SDimitry Andric 
3658bcb0991SDimitry Andric   if (Size.getBitWidth() > 64)
3668bcb0991SDimitry Andric     return false;
3674c2d3b02SDimitry Andric   const TypeSize LoadSize = TypeSize::getFixed(Size.getZExtValue());
3688bcb0991SDimitry Andric 
3690b57cec5SDimitry Andric   // Otherwise, be a little bit aggressive by scanning the local block where we
3700b57cec5SDimitry Andric   // want to check to see if the pointer is already being loaded or stored
3710b57cec5SDimitry Andric   // from/to.  If so, the previous load or store would have already trapped,
3720b57cec5SDimitry Andric   // so there is no harm doing an extra load (also, CSE will later eliminate
3730b57cec5SDimitry Andric   // the load entirely).
3740b57cec5SDimitry Andric   BasicBlock::iterator BBI = ScanFrom->getIterator(),
3750b57cec5SDimitry Andric                        E = ScanFrom->getParent()->begin();
3760b57cec5SDimitry Andric 
3770b57cec5SDimitry Andric   // We can at least always strip pointer casts even though we can't use the
3780b57cec5SDimitry Andric   // base here.
3790b57cec5SDimitry Andric   V = V->stripPointerCasts();
3800b57cec5SDimitry Andric 
3810b57cec5SDimitry Andric   while (BBI != E) {
3820b57cec5SDimitry Andric     --BBI;
3830b57cec5SDimitry Andric 
3840b57cec5SDimitry Andric     // If we see a free or a call which may write to memory (i.e. which might do
3850b57cec5SDimitry Andric     // a free) the pointer could be marked invalid.
3860b57cec5SDimitry Andric     if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
387bdd1243dSDimitry Andric         !isa<LifetimeIntrinsic>(BBI) && !isa<DbgInfoIntrinsic>(BBI))
3880b57cec5SDimitry Andric       return false;
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric     Value *AccessedPtr;
3915ffd83dbSDimitry Andric     Type *AccessedTy;
3925ffd83dbSDimitry Andric     Align AccessedAlign;
3930b57cec5SDimitry Andric     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3940b57cec5SDimitry Andric       // Ignore volatile loads. The execution of a volatile load cannot
3950b57cec5SDimitry Andric       // be used to prove an address is backed by regular memory; it can,
3960b57cec5SDimitry Andric       // for example, point to an MMIO register.
3970b57cec5SDimitry Andric       if (LI->isVolatile())
3980b57cec5SDimitry Andric         continue;
3990b57cec5SDimitry Andric       AccessedPtr = LI->getPointerOperand();
4005ffd83dbSDimitry Andric       AccessedTy = LI->getType();
4015ffd83dbSDimitry Andric       AccessedAlign = LI->getAlign();
4020b57cec5SDimitry Andric     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
4030b57cec5SDimitry Andric       // Ignore volatile stores (see comment for loads).
4040b57cec5SDimitry Andric       if (SI->isVolatile())
4050b57cec5SDimitry Andric         continue;
4060b57cec5SDimitry Andric       AccessedPtr = SI->getPointerOperand();
4075ffd83dbSDimitry Andric       AccessedTy = SI->getValueOperand()->getType();
4085ffd83dbSDimitry Andric       AccessedAlign = SI->getAlign();
4090b57cec5SDimitry Andric     } else
4100b57cec5SDimitry Andric       continue;
4110b57cec5SDimitry Andric 
4128bcb0991SDimitry Andric     if (AccessedAlign < Alignment)
4130b57cec5SDimitry Andric       continue;
4140b57cec5SDimitry Andric 
4150b57cec5SDimitry Andric     // Handle trivial cases.
4168bcb0991SDimitry Andric     if (AccessedPtr == V &&
4174c2d3b02SDimitry Andric         TypeSize::isKnownLE(LoadSize, DL.getTypeStoreSize(AccessedTy)))
4180b57cec5SDimitry Andric       return true;
4190b57cec5SDimitry Andric 
4200b57cec5SDimitry Andric     if (AreEquivalentAddressValues(AccessedPtr->stripPointerCasts(), V) &&
4214c2d3b02SDimitry Andric         TypeSize::isKnownLE(LoadSize, DL.getTypeStoreSize(AccessedTy)))
4220b57cec5SDimitry Andric       return true;
4230b57cec5SDimitry Andric   }
4240b57cec5SDimitry Andric   return false;
4250b57cec5SDimitry Andric }
4260b57cec5SDimitry Andric 
isSafeToLoadUnconditionally(Value * V,Type * Ty,Align Alignment,const DataLayout & DL,Instruction * ScanFrom,AssumptionCache * AC,const DominatorTree * DT,const TargetLibraryInfo * TLI)4275ffd83dbSDimitry Andric bool llvm::isSafeToLoadUnconditionally(Value *V, Type *Ty, Align Alignment,
4280b57cec5SDimitry Andric                                        const DataLayout &DL,
4290b57cec5SDimitry Andric                                        Instruction *ScanFrom,
430bdd1243dSDimitry Andric                                        AssumptionCache *AC,
431fe6060f1SDimitry Andric                                        const DominatorTree *DT,
432fe6060f1SDimitry Andric                                        const TargetLibraryInfo *TLI) {
433753f127fSDimitry Andric   TypeSize TySize = DL.getTypeStoreSize(Ty);
434753f127fSDimitry Andric   if (TySize.isScalable())
435753f127fSDimitry Andric     return false;
436753f127fSDimitry Andric   APInt Size(DL.getIndexTypeSizeInBits(V->getType()), TySize.getFixedValue());
437bdd1243dSDimitry Andric   return isSafeToLoadUnconditionally(V, Alignment, Size, DL, ScanFrom, AC, DT,
438bdd1243dSDimitry Andric                                      TLI);
4390b57cec5SDimitry Andric }
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric /// DefMaxInstsToScan - the default number of maximum instructions
4420b57cec5SDimitry Andric /// to scan in the block, used by FindAvailableLoadedValue().
4430b57cec5SDimitry Andric /// FindAvailableLoadedValue() was introduced in r60148, to improve jump
4440b57cec5SDimitry Andric /// threading in part by eliminating partially redundant loads.
4450b57cec5SDimitry Andric /// At that point, the value of MaxInstsToScan was already set to '6'
4460b57cec5SDimitry Andric /// without documented explanation.
4470b57cec5SDimitry Andric cl::opt<unsigned>
4480b57cec5SDimitry Andric llvm::DefMaxInstsToScan("available-load-scan-limit", cl::init(6), cl::Hidden,
4490b57cec5SDimitry Andric   cl::desc("Use this to specify the default maximum number of instructions "
4500b57cec5SDimitry Andric            "to scan backward from a given instruction, when searching for "
4510b57cec5SDimitry Andric            "available loaded value"));
4520b57cec5SDimitry Andric 
FindAvailableLoadedValue(LoadInst * Load,BasicBlock * ScanBB,BasicBlock::iterator & ScanFrom,unsigned MaxInstsToScan,BatchAAResults * AA,bool * IsLoad,unsigned * NumScanedInst)453b3edf446SDimitry Andric Value *llvm::FindAvailableLoadedValue(LoadInst *Load, BasicBlock *ScanBB,
4540b57cec5SDimitry Andric                                       BasicBlock::iterator &ScanFrom,
4550b57cec5SDimitry Andric                                       unsigned MaxInstsToScan,
456b3edf446SDimitry Andric                                       BatchAAResults *AA, bool *IsLoad,
4570b57cec5SDimitry Andric                                       unsigned *NumScanedInst) {
4580b57cec5SDimitry Andric   // Don't CSE load that is volatile or anything stronger than unordered.
4590b57cec5SDimitry Andric   if (!Load->isUnordered())
4600b57cec5SDimitry Andric     return nullptr;
4610b57cec5SDimitry Andric 
462fe6060f1SDimitry Andric   MemoryLocation Loc = MemoryLocation::get(Load);
463fe6060f1SDimitry Andric   return findAvailablePtrLoadStore(Loc, Load->getType(), Load->isAtomic(),
464fe6060f1SDimitry Andric                                    ScanBB, ScanFrom, MaxInstsToScan, AA, IsLoad,
465fe6060f1SDimitry Andric                                    NumScanedInst);
4660b57cec5SDimitry Andric }
4670b57cec5SDimitry Andric 
4685ffd83dbSDimitry Andric // Check if the load and the store have the same base, constant offsets and
4695ffd83dbSDimitry Andric // non-overlapping access ranges.
areNonOverlapSameBaseLoadAndStore(const Value * LoadPtr,Type * LoadTy,const Value * StorePtr,Type * StoreTy,const DataLayout & DL)470fe6060f1SDimitry Andric static bool areNonOverlapSameBaseLoadAndStore(const Value *LoadPtr,
471fe6060f1SDimitry Andric                                               Type *LoadTy,
472fe6060f1SDimitry Andric                                               const Value *StorePtr,
473fe6060f1SDimitry Andric                                               Type *StoreTy,
4745ffd83dbSDimitry Andric                                               const DataLayout &DL) {
475349cc55cSDimitry Andric   APInt LoadOffset(DL.getIndexTypeSizeInBits(LoadPtr->getType()), 0);
476349cc55cSDimitry Andric   APInt StoreOffset(DL.getIndexTypeSizeInBits(StorePtr->getType()), 0);
477fe6060f1SDimitry Andric   const Value *LoadBase = LoadPtr->stripAndAccumulateConstantOffsets(
4785ffd83dbSDimitry Andric       DL, LoadOffset, /* AllowNonInbounds */ false);
479fe6060f1SDimitry Andric   const Value *StoreBase = StorePtr->stripAndAccumulateConstantOffsets(
4805ffd83dbSDimitry Andric       DL, StoreOffset, /* AllowNonInbounds */ false);
4815ffd83dbSDimitry Andric   if (LoadBase != StoreBase)
4825ffd83dbSDimitry Andric     return false;
4835ffd83dbSDimitry Andric   auto LoadAccessSize = LocationSize::precise(DL.getTypeStoreSize(LoadTy));
4845ffd83dbSDimitry Andric   auto StoreAccessSize = LocationSize::precise(DL.getTypeStoreSize(StoreTy));
4855ffd83dbSDimitry Andric   ConstantRange LoadRange(LoadOffset,
4865ffd83dbSDimitry Andric                           LoadOffset + LoadAccessSize.toRaw());
4875ffd83dbSDimitry Andric   ConstantRange StoreRange(StoreOffset,
4885ffd83dbSDimitry Andric                            StoreOffset + StoreAccessSize.toRaw());
4895ffd83dbSDimitry Andric   return LoadRange.intersectWith(StoreRange).isEmptySet();
4905ffd83dbSDimitry Andric }
4915ffd83dbSDimitry Andric 
getAvailableLoadStore(Instruction * Inst,const Value * Ptr,Type * AccessTy,bool AtLeastAtomic,const DataLayout & DL,bool * IsLoadCSE)492fe6060f1SDimitry Andric static Value *getAvailableLoadStore(Instruction *Inst, const Value *Ptr,
493fe6060f1SDimitry Andric                                     Type *AccessTy, bool AtLeastAtomic,
494fe6060f1SDimitry Andric                                     const DataLayout &DL, bool *IsLoadCSE) {
495fe6060f1SDimitry Andric   // If this is a load of Ptr, the loaded value is available.
496fe6060f1SDimitry Andric   // (This is true even if the load is volatile or atomic, although
497fe6060f1SDimitry Andric   // those cases are unlikely.)
498fe6060f1SDimitry Andric   if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
499fe6060f1SDimitry Andric     // We can value forward from an atomic to a non-atomic, but not the
500fe6060f1SDimitry Andric     // other way around.
501fe6060f1SDimitry Andric     if (LI->isAtomic() < AtLeastAtomic)
502fe6060f1SDimitry Andric       return nullptr;
503fe6060f1SDimitry Andric 
504fe6060f1SDimitry Andric     Value *LoadPtr = LI->getPointerOperand()->stripPointerCasts();
505fe6060f1SDimitry Andric     if (!AreEquivalentAddressValues(LoadPtr, Ptr))
506fe6060f1SDimitry Andric       return nullptr;
507fe6060f1SDimitry Andric 
508fe6060f1SDimitry Andric     if (CastInst::isBitOrNoopPointerCastable(LI->getType(), AccessTy, DL)) {
509fe6060f1SDimitry Andric       if (IsLoadCSE)
510fe6060f1SDimitry Andric         *IsLoadCSE = true;
511fe6060f1SDimitry Andric       return LI;
512fe6060f1SDimitry Andric     }
513fe6060f1SDimitry Andric   }
514fe6060f1SDimitry Andric 
515fe6060f1SDimitry Andric   // If this is a store through Ptr, the value is available!
516fe6060f1SDimitry Andric   // (This is true even if the store is volatile or atomic, although
517fe6060f1SDimitry Andric   // those cases are unlikely.)
518fe6060f1SDimitry Andric   if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
519fe6060f1SDimitry Andric     // We can value forward from an atomic to a non-atomic, but not the
520fe6060f1SDimitry Andric     // other way around.
521fe6060f1SDimitry Andric     if (SI->isAtomic() < AtLeastAtomic)
522fe6060f1SDimitry Andric       return nullptr;
523fe6060f1SDimitry Andric 
524fe6060f1SDimitry Andric     Value *StorePtr = SI->getPointerOperand()->stripPointerCasts();
525fe6060f1SDimitry Andric     if (!AreEquivalentAddressValues(StorePtr, Ptr))
526fe6060f1SDimitry Andric       return nullptr;
527fe6060f1SDimitry Andric 
528fe6060f1SDimitry Andric     if (IsLoadCSE)
529fe6060f1SDimitry Andric       *IsLoadCSE = false;
530fe6060f1SDimitry Andric 
531fe6060f1SDimitry Andric     Value *Val = SI->getValueOperand();
532fe6060f1SDimitry Andric     if (CastInst::isBitOrNoopPointerCastable(Val->getType(), AccessTy, DL))
533fe6060f1SDimitry Andric       return Val;
534fe6060f1SDimitry Andric 
53581ad6265SDimitry Andric     TypeSize StoreSize = DL.getTypeSizeInBits(Val->getType());
53681ad6265SDimitry Andric     TypeSize LoadSize = DL.getTypeSizeInBits(AccessTy);
537349cc55cSDimitry Andric     if (TypeSize::isKnownLE(LoadSize, StoreSize))
538fe6060f1SDimitry Andric       if (auto *C = dyn_cast<Constant>(Val))
539349cc55cSDimitry Andric         return ConstantFoldLoadFromConst(C, AccessTy, DL);
540fe6060f1SDimitry Andric   }
541fe6060f1SDimitry Andric 
542bdd1243dSDimitry Andric   if (auto *MSI = dyn_cast<MemSetInst>(Inst)) {
543bdd1243dSDimitry Andric     // Don't forward from (non-atomic) memset to atomic load.
544bdd1243dSDimitry Andric     if (AtLeastAtomic)
545bdd1243dSDimitry Andric       return nullptr;
546bdd1243dSDimitry Andric 
547bdd1243dSDimitry Andric     // Only handle constant memsets.
548bdd1243dSDimitry Andric     auto *Val = dyn_cast<ConstantInt>(MSI->getValue());
549bdd1243dSDimitry Andric     auto *Len = dyn_cast<ConstantInt>(MSI->getLength());
550bdd1243dSDimitry Andric     if (!Val || !Len)
551bdd1243dSDimitry Andric       return nullptr;
552bdd1243dSDimitry Andric 
553bdd1243dSDimitry Andric     // TODO: Handle offsets.
554bdd1243dSDimitry Andric     Value *Dst = MSI->getDest();
555bdd1243dSDimitry Andric     if (!AreEquivalentAddressValues(Dst, Ptr))
556bdd1243dSDimitry Andric       return nullptr;
557bdd1243dSDimitry Andric 
558bdd1243dSDimitry Andric     if (IsLoadCSE)
559bdd1243dSDimitry Andric       *IsLoadCSE = false;
560bdd1243dSDimitry Andric 
561bdd1243dSDimitry Andric     TypeSize LoadTypeSize = DL.getTypeSizeInBits(AccessTy);
562bdd1243dSDimitry Andric     if (LoadTypeSize.isScalable())
563bdd1243dSDimitry Andric       return nullptr;
564bdd1243dSDimitry Andric 
565bdd1243dSDimitry Andric     // Make sure the read bytes are contained in the memset.
566bdd1243dSDimitry Andric     uint64_t LoadSize = LoadTypeSize.getFixedValue();
567bdd1243dSDimitry Andric     if ((Len->getValue() * 8).ult(LoadSize))
568bdd1243dSDimitry Andric       return nullptr;
569bdd1243dSDimitry Andric 
570bdd1243dSDimitry Andric     APInt Splat = LoadSize >= 8 ? APInt::getSplat(LoadSize, Val->getValue())
571bdd1243dSDimitry Andric                                 : Val->getValue().trunc(LoadSize);
572bdd1243dSDimitry Andric     ConstantInt *SplatC = ConstantInt::get(MSI->getContext(), Splat);
573bdd1243dSDimitry Andric     if (CastInst::isBitOrNoopPointerCastable(SplatC->getType(), AccessTy, DL))
574bdd1243dSDimitry Andric       return SplatC;
575bdd1243dSDimitry Andric 
576bdd1243dSDimitry Andric     return nullptr;
577bdd1243dSDimitry Andric   }
578bdd1243dSDimitry Andric 
579fe6060f1SDimitry Andric   return nullptr;
580fe6060f1SDimitry Andric }
581fe6060f1SDimitry Andric 
findAvailablePtrLoadStore(const MemoryLocation & Loc,Type * AccessTy,bool AtLeastAtomic,BasicBlock * ScanBB,BasicBlock::iterator & ScanFrom,unsigned MaxInstsToScan,BatchAAResults * AA,bool * IsLoadCSE,unsigned * NumScanedInst)582fe6060f1SDimitry Andric Value *llvm::findAvailablePtrLoadStore(
583fe6060f1SDimitry Andric     const MemoryLocation &Loc, Type *AccessTy, bool AtLeastAtomic,
584fe6060f1SDimitry Andric     BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan,
585b3edf446SDimitry Andric     BatchAAResults *AA, bool *IsLoadCSE, unsigned *NumScanedInst) {
5860b57cec5SDimitry Andric   if (MaxInstsToScan == 0)
5870b57cec5SDimitry Andric     MaxInstsToScan = ~0U;
5880b57cec5SDimitry Andric 
5890b57cec5SDimitry Andric   const DataLayout &DL = ScanBB->getModule()->getDataLayout();
590fe6060f1SDimitry Andric   const Value *StrippedPtr = Loc.Ptr->stripPointerCasts();
5910b57cec5SDimitry Andric 
5920b57cec5SDimitry Andric   while (ScanFrom != ScanBB->begin()) {
5930b57cec5SDimitry Andric     // We must ignore debug info directives when counting (otherwise they
5940b57cec5SDimitry Andric     // would affect codegen).
5950b57cec5SDimitry Andric     Instruction *Inst = &*--ScanFrom;
596fe6060f1SDimitry Andric     if (Inst->isDebugOrPseudoInst())
5970b57cec5SDimitry Andric       continue;
5980b57cec5SDimitry Andric 
5990b57cec5SDimitry Andric     // Restore ScanFrom to expected value in case next test succeeds
6000b57cec5SDimitry Andric     ScanFrom++;
6010b57cec5SDimitry Andric 
6020b57cec5SDimitry Andric     if (NumScanedInst)
6030b57cec5SDimitry Andric       ++(*NumScanedInst);
6040b57cec5SDimitry Andric 
6050b57cec5SDimitry Andric     // Don't scan huge blocks.
6060b57cec5SDimitry Andric     if (MaxInstsToScan-- == 0)
6070b57cec5SDimitry Andric       return nullptr;
6080b57cec5SDimitry Andric 
6090b57cec5SDimitry Andric     --ScanFrom;
6100b57cec5SDimitry Andric 
611fe6060f1SDimitry Andric     if (Value *Available = getAvailableLoadStore(Inst, StrippedPtr, AccessTy,
612fe6060f1SDimitry Andric                                                  AtLeastAtomic, DL, IsLoadCSE))
613fe6060f1SDimitry Andric       return Available;
6140b57cec5SDimitry Andric 
615480093f4SDimitry Andric     // Try to get the store size for the type.
6160b57cec5SDimitry Andric     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
6170b57cec5SDimitry Andric       Value *StorePtr = SI->getPointerOperand()->stripPointerCasts();
6180b57cec5SDimitry Andric 
6190b57cec5SDimitry Andric       // If both StrippedPtr and StorePtr reach all the way to an alloca or
6200b57cec5SDimitry Andric       // global and they are different, ignore the store. This is a trivial form
6210b57cec5SDimitry Andric       // of alias analysis that is important for reg2mem'd code.
6220b57cec5SDimitry Andric       if ((isa<AllocaInst>(StrippedPtr) || isa<GlobalVariable>(StrippedPtr)) &&
6230b57cec5SDimitry Andric           (isa<AllocaInst>(StorePtr) || isa<GlobalVariable>(StorePtr)) &&
6240b57cec5SDimitry Andric           StrippedPtr != StorePtr)
6250b57cec5SDimitry Andric         continue;
6260b57cec5SDimitry Andric 
6275ffd83dbSDimitry Andric       if (!AA) {
6285ffd83dbSDimitry Andric         // When AA isn't available, but if the load and the store have the same
6295ffd83dbSDimitry Andric         // base, constant offsets and non-overlapping access ranges, ignore the
6305ffd83dbSDimitry Andric         // store. This is a simple form of alias analysis that is used by the
6315ffd83dbSDimitry Andric         // inliner. FIXME: use BasicAA if possible.
632fe6060f1SDimitry Andric         if (areNonOverlapSameBaseLoadAndStore(
633fe6060f1SDimitry Andric                 Loc.Ptr, AccessTy, SI->getPointerOperand(),
6345ffd83dbSDimitry Andric                 SI->getValueOperand()->getType(), DL))
6350b57cec5SDimitry Andric           continue;
6365ffd83dbSDimitry Andric       } else {
6375ffd83dbSDimitry Andric         // If we have alias analysis and it says the store won't modify the
6385ffd83dbSDimitry Andric         // loaded value, ignore the store.
639fe6060f1SDimitry Andric         if (!isModSet(AA->getModRefInfo(SI, Loc)))
6405ffd83dbSDimitry Andric           continue;
6415ffd83dbSDimitry Andric       }
6420b57cec5SDimitry Andric 
6430b57cec5SDimitry Andric       // Otherwise the store that may or may not alias the pointer, bail out.
6440b57cec5SDimitry Andric       ++ScanFrom;
6450b57cec5SDimitry Andric       return nullptr;
6460b57cec5SDimitry Andric     }
6470b57cec5SDimitry Andric 
6480b57cec5SDimitry Andric     // If this is some other instruction that may clobber Ptr, bail out.
6490b57cec5SDimitry Andric     if (Inst->mayWriteToMemory()) {
6500b57cec5SDimitry Andric       // If alias analysis claims that it really won't modify the load,
6510b57cec5SDimitry Andric       // ignore it.
652fe6060f1SDimitry Andric       if (AA && !isModSet(AA->getModRefInfo(Inst, Loc)))
6530b57cec5SDimitry Andric         continue;
6540b57cec5SDimitry Andric 
6550b57cec5SDimitry Andric       // May modify the pointer, bail out.
6560b57cec5SDimitry Andric       ++ScanFrom;
6570b57cec5SDimitry Andric       return nullptr;
6580b57cec5SDimitry Andric     }
6590b57cec5SDimitry Andric   }
6600b57cec5SDimitry Andric 
6610b57cec5SDimitry Andric   // Got to the start of the block, we didn't find it, but are done for this
6620b57cec5SDimitry Andric   // block.
6630b57cec5SDimitry Andric   return nullptr;
6640b57cec5SDimitry Andric }
665e8d8bef9SDimitry Andric 
FindAvailableLoadedValue(LoadInst * Load,BatchAAResults & AA,bool * IsLoadCSE,unsigned MaxInstsToScan)666b3edf446SDimitry Andric Value *llvm::FindAvailableLoadedValue(LoadInst *Load, BatchAAResults &AA,
667fe6060f1SDimitry Andric                                       bool *IsLoadCSE,
668fe6060f1SDimitry Andric                                       unsigned MaxInstsToScan) {
669fe6060f1SDimitry Andric   const DataLayout &DL = Load->getModule()->getDataLayout();
670fe6060f1SDimitry Andric   Value *StrippedPtr = Load->getPointerOperand()->stripPointerCasts();
671fe6060f1SDimitry Andric   BasicBlock *ScanBB = Load->getParent();
672fe6060f1SDimitry Andric   Type *AccessTy = Load->getType();
673fe6060f1SDimitry Andric   bool AtLeastAtomic = Load->isAtomic();
674fe6060f1SDimitry Andric 
675fe6060f1SDimitry Andric   if (!Load->isUnordered())
676fe6060f1SDimitry Andric     return nullptr;
677fe6060f1SDimitry Andric 
678fe6060f1SDimitry Andric   // Try to find an available value first, and delay expensive alias analysis
679fe6060f1SDimitry Andric   // queries until later.
68006c3fb27SDimitry Andric   Value *Available = nullptr;
681fe6060f1SDimitry Andric   SmallVector<Instruction *> MustNotAliasInsts;
682fe6060f1SDimitry Andric   for (Instruction &Inst : make_range(++Load->getReverseIterator(),
683fe6060f1SDimitry Andric                                       ScanBB->rend())) {
684fe6060f1SDimitry Andric     if (Inst.isDebugOrPseudoInst())
685fe6060f1SDimitry Andric       continue;
686fe6060f1SDimitry Andric 
687fe6060f1SDimitry Andric     if (MaxInstsToScan-- == 0)
688fe6060f1SDimitry Andric       return nullptr;
689fe6060f1SDimitry Andric 
690fe6060f1SDimitry Andric     Available = getAvailableLoadStore(&Inst, StrippedPtr, AccessTy,
691fe6060f1SDimitry Andric                                       AtLeastAtomic, DL, IsLoadCSE);
692fe6060f1SDimitry Andric     if (Available)
693fe6060f1SDimitry Andric       break;
694fe6060f1SDimitry Andric 
695fe6060f1SDimitry Andric     if (Inst.mayWriteToMemory())
696fe6060f1SDimitry Andric       MustNotAliasInsts.push_back(&Inst);
697fe6060f1SDimitry Andric   }
698fe6060f1SDimitry Andric 
699fe6060f1SDimitry Andric   // If we found an available value, ensure that the instructions in between
700fe6060f1SDimitry Andric   // did not modify the memory location.
701fe6060f1SDimitry Andric   if (Available) {
702fe6060f1SDimitry Andric     MemoryLocation Loc = MemoryLocation::get(Load);
703fe6060f1SDimitry Andric     for (Instruction *Inst : MustNotAliasInsts)
704fe6060f1SDimitry Andric       if (isModSet(AA.getModRefInfo(Inst, Loc)))
705fe6060f1SDimitry Andric         return nullptr;
706fe6060f1SDimitry Andric   }
707fe6060f1SDimitry Andric 
708fe6060f1SDimitry Andric   return Available;
709fe6060f1SDimitry Andric }
710fe6060f1SDimitry Andric 
canReplacePointersIfEqual(Value * A,Value * B,const DataLayout & DL,Instruction * CtxI)711e8d8bef9SDimitry Andric bool llvm::canReplacePointersIfEqual(Value *A, Value *B, const DataLayout &DL,
712e8d8bef9SDimitry Andric                                      Instruction *CtxI) {
713e8d8bef9SDimitry Andric   Type *Ty = A->getType();
714e8d8bef9SDimitry Andric   assert(Ty == B->getType() && Ty->isPointerTy() &&
715e8d8bef9SDimitry Andric          "values must have matching pointer types");
716e8d8bef9SDimitry Andric 
717e8d8bef9SDimitry Andric   // NOTE: The checks in the function are incomplete and currently miss illegal
718e8d8bef9SDimitry Andric   // cases! The current implementation is a starting point and the
719e8d8bef9SDimitry Andric   // implementation should be made stricter over time.
720e8d8bef9SDimitry Andric   if (auto *C = dyn_cast<Constant>(B)) {
721e8d8bef9SDimitry Andric     // Do not allow replacing a pointer with a constant pointer, unless it is
722e8d8bef9SDimitry Andric     // either null or at least one byte is dereferenceable.
723e8d8bef9SDimitry Andric     APInt OneByte(DL.getPointerTypeSizeInBits(Ty), 1);
724e8d8bef9SDimitry Andric     return C->isNullValue() ||
725e8d8bef9SDimitry Andric            isDereferenceableAndAlignedPointer(B, Align(1), OneByte, DL, CtxI);
726e8d8bef9SDimitry Andric   }
727e8d8bef9SDimitry Andric 
728e8d8bef9SDimitry Andric   return true;
729e8d8bef9SDimitry Andric }
730