10b57cec5SDimitry Andric //===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==//
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 // The implementation for the loop memory dependence that was originally
100b57cec5SDimitry Andric // developed for the loop vectorizer.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "llvm/Analysis/LoopAccessAnalysis.h"
150b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
160b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
170b57cec5SDimitry Andric #include "llvm/ADT/EquivalenceClasses.h"
180b57cec5SDimitry Andric #include "llvm/ADT/PointerIntPair.h"
190b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
200b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
210b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
220b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
230b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
240b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
250b57cec5SDimitry Andric #include "llvm/Analysis/AliasSetTracker.h"
260b57cec5SDimitry Andric #include "llvm/Analysis/LoopAnalysisManager.h"
270b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
28bdd1243dSDimitry Andric #include "llvm/Analysis/LoopIterator.h"
290b57cec5SDimitry Andric #include "llvm/Analysis/MemoryLocation.h"
300b57cec5SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
310b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
320b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h"
330b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
340b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
350b57cec5SDimitry Andric #include "llvm/Analysis/VectorUtils.h"
360b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
370b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
380b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
390b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
400b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
410b57cec5SDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
420b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
430b57cec5SDimitry Andric #include "llvm/IR/Function.h"
44fe013be4SDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h"
450b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
460b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
470b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
480b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
490b57cec5SDimitry Andric #include "llvm/IR/PassManager.h"
5081ad6265SDimitry Andric #include "llvm/IR/PatternMatch.h"
510b57cec5SDimitry Andric #include "llvm/IR/Type.h"
520b57cec5SDimitry Andric #include "llvm/IR/Value.h"
530b57cec5SDimitry Andric #include "llvm/IR/ValueHandle.h"
540b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
550b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
560b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
570b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
580b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
590b57cec5SDimitry Andric #include <algorithm>
600b57cec5SDimitry Andric #include <cassert>
610b57cec5SDimitry Andric #include <cstdint>
620b57cec5SDimitry Andric #include <iterator>
630b57cec5SDimitry Andric #include <utility>
64c9157d92SDimitry Andric #include <variant>
650b57cec5SDimitry Andric #include <vector>
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric using namespace llvm;
6881ad6265SDimitry Andric using namespace llvm::PatternMatch;
690b57cec5SDimitry Andric 
700b57cec5SDimitry Andric #define DEBUG_TYPE "loop-accesses"
710b57cec5SDimitry Andric 
720b57cec5SDimitry Andric static cl::opt<unsigned, true>
730b57cec5SDimitry Andric VectorizationFactor("force-vector-width", cl::Hidden,
740b57cec5SDimitry Andric                     cl::desc("Sets the SIMD width. Zero is autoselect."),
750b57cec5SDimitry Andric                     cl::location(VectorizerParams::VectorizationFactor));
760b57cec5SDimitry Andric unsigned VectorizerParams::VectorizationFactor;
770b57cec5SDimitry Andric 
780b57cec5SDimitry Andric static cl::opt<unsigned, true>
790b57cec5SDimitry Andric VectorizationInterleave("force-vector-interleave", cl::Hidden,
800b57cec5SDimitry Andric                         cl::desc("Sets the vectorization interleave count. "
810b57cec5SDimitry Andric                                  "Zero is autoselect."),
820b57cec5SDimitry Andric                         cl::location(
830b57cec5SDimitry Andric                             VectorizerParams::VectorizationInterleave));
840b57cec5SDimitry Andric unsigned VectorizerParams::VectorizationInterleave;
850b57cec5SDimitry Andric 
860b57cec5SDimitry Andric static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
870b57cec5SDimitry Andric     "runtime-memory-check-threshold", cl::Hidden,
880b57cec5SDimitry Andric     cl::desc("When performing memory disambiguation checks at runtime do not "
890b57cec5SDimitry Andric              "generate more than this number of comparisons (default = 8)."),
900b57cec5SDimitry Andric     cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
910b57cec5SDimitry Andric unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
920b57cec5SDimitry Andric 
930b57cec5SDimitry Andric /// The maximum iterations used to merge memory checks
940b57cec5SDimitry Andric static cl::opt<unsigned> MemoryCheckMergeThreshold(
950b57cec5SDimitry Andric     "memory-check-merge-threshold", cl::Hidden,
960b57cec5SDimitry Andric     cl::desc("Maximum number of comparisons done when trying to merge "
970b57cec5SDimitry Andric              "runtime memory checks. (default = 100)"),
980b57cec5SDimitry Andric     cl::init(100));
990b57cec5SDimitry Andric 
1000b57cec5SDimitry Andric /// Maximum SIMD width.
1010b57cec5SDimitry Andric const unsigned VectorizerParams::MaxVectorWidth = 64;
1020b57cec5SDimitry Andric 
1030b57cec5SDimitry Andric /// We collect dependences up to this threshold.
1040b57cec5SDimitry Andric static cl::opt<unsigned>
1050b57cec5SDimitry Andric     MaxDependences("max-dependences", cl::Hidden,
1060b57cec5SDimitry Andric                    cl::desc("Maximum number of dependences collected by "
1070b57cec5SDimitry Andric                             "loop-access analysis (default = 100)"),
1080b57cec5SDimitry Andric                    cl::init(100));
1090b57cec5SDimitry Andric 
1100b57cec5SDimitry Andric /// This enables versioning on the strides of symbolically striding memory
1110b57cec5SDimitry Andric /// accesses in code like the following.
1120b57cec5SDimitry Andric ///   for (i = 0; i < N; ++i)
1130b57cec5SDimitry Andric ///     A[i * Stride1] += B[i * Stride2] ...
1140b57cec5SDimitry Andric ///
1150b57cec5SDimitry Andric /// Will be roughly translated to
1160b57cec5SDimitry Andric ///    if (Stride1 == 1 && Stride2 == 1) {
1170b57cec5SDimitry Andric ///      for (i = 0; i < N; i+=4)
1180b57cec5SDimitry Andric ///       A[i:i+3] += ...
1190b57cec5SDimitry Andric ///    } else
1200b57cec5SDimitry Andric ///      ...
1210b57cec5SDimitry Andric static cl::opt<bool> EnableMemAccessVersioning(
1220b57cec5SDimitry Andric     "enable-mem-access-versioning", cl::init(true), cl::Hidden,
1230b57cec5SDimitry Andric     cl::desc("Enable symbolic stride memory access versioning"));
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric /// Enable store-to-load forwarding conflict detection. This option can
1260b57cec5SDimitry Andric /// be disabled for correctness testing.
1270b57cec5SDimitry Andric static cl::opt<bool> EnableForwardingConflictDetection(
1280b57cec5SDimitry Andric     "store-to-load-forwarding-conflict-detection", cl::Hidden,
1290b57cec5SDimitry Andric     cl::desc("Enable conflict detection in loop-access analysis"),
1300b57cec5SDimitry Andric     cl::init(true));
1310b57cec5SDimitry Andric 
132fcaf7f86SDimitry Andric static cl::opt<unsigned> MaxForkedSCEVDepth(
133fcaf7f86SDimitry Andric     "max-forked-scev-depth", cl::Hidden,
134fcaf7f86SDimitry Andric     cl::desc("Maximum recursion depth when finding forked SCEVs (default = 5)"),
135fcaf7f86SDimitry Andric     cl::init(5));
136fcaf7f86SDimitry Andric 
137fe013be4SDimitry Andric static cl::opt<bool> SpeculateUnitStride(
138fe013be4SDimitry Andric     "laa-speculate-unit-stride", cl::Hidden,
139fe013be4SDimitry Andric     cl::desc("Speculate that non-constant strides are unit in LAA"),
140fe013be4SDimitry Andric     cl::init(true));
141fe013be4SDimitry Andric 
142c9157d92SDimitry Andric static cl::opt<bool, true> HoistRuntimeChecks(
143c9157d92SDimitry Andric     "hoist-runtime-checks", cl::Hidden,
144c9157d92SDimitry Andric     cl::desc(
145c9157d92SDimitry Andric         "Hoist inner loop runtime memory checks to outer loop if possible"),
146e710425bSDimitry Andric     cl::location(VectorizerParams::HoistRuntimeChecks), cl::init(true));
147c9157d92SDimitry Andric bool VectorizerParams::HoistRuntimeChecks;
148c9157d92SDimitry Andric 
1490b57cec5SDimitry Andric bool VectorizerParams::isInterleaveForced() {
1500b57cec5SDimitry Andric   return ::VectorizationInterleave.getNumOccurrences() > 0;
1510b57cec5SDimitry Andric }
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric const SCEV *llvm::replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE,
154fe013be4SDimitry Andric                                             const DenseMap<Value *, const SCEV *> &PtrToStride,
155349cc55cSDimitry Andric                                             Value *Ptr) {
1560b57cec5SDimitry Andric   const SCEV *OrigSCEV = PSE.getSCEV(Ptr);
1570b57cec5SDimitry Andric 
1580b57cec5SDimitry Andric   // If there is an entry in the map return the SCEV of the pointer with the
1590b57cec5SDimitry Andric   // symbolic stride replaced by one.
160fe013be4SDimitry Andric   DenseMap<Value *, const SCEV *>::const_iterator SI = PtrToStride.find(Ptr);
161e8d8bef9SDimitry Andric   if (SI == PtrToStride.end())
162e8d8bef9SDimitry Andric     // For a non-symbolic stride, just return the original expression.
163e8d8bef9SDimitry Andric     return OrigSCEV;
1640b57cec5SDimitry Andric 
165fe013be4SDimitry Andric   const SCEV *StrideSCEV = SI->second;
166fe013be4SDimitry Andric   // Note: This assert is both overly strong and overly weak.  The actual
167fe013be4SDimitry Andric   // invariant here is that StrideSCEV should be loop invariant.  The only
168fe013be4SDimitry Andric   // such invariant strides we happen to speculate right now are unknowns
169fe013be4SDimitry Andric   // and thus this is a reasonable proxy of the actual invariant.
170fe013be4SDimitry Andric   assert(isa<SCEVUnknown>(StrideSCEV) && "shouldn't be in map");
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric   ScalarEvolution *SE = PSE.getSE();
173fe013be4SDimitry Andric   const auto *CT = SE->getOne(StrideSCEV->getType());
174fe013be4SDimitry Andric   PSE.addPredicate(*SE->getEqualPredicate(StrideSCEV, CT));
1750b57cec5SDimitry Andric   auto *Expr = PSE.getSCEV(Ptr);
1760b57cec5SDimitry Andric 
1770b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV
1780b57cec5SDimitry Andric 	     << " by: " << *Expr << "\n");
1790b57cec5SDimitry Andric   return Expr;
1800b57cec5SDimitry Andric }
1810b57cec5SDimitry Andric 
1825ffd83dbSDimitry Andric RuntimeCheckingPtrGroup::RuntimeCheckingPtrGroup(
1835ffd83dbSDimitry Andric     unsigned Index, RuntimePointerChecking &RtCheck)
184fe6060f1SDimitry Andric     : High(RtCheck.Pointers[Index].End), Low(RtCheck.Pointers[Index].Start),
185fe6060f1SDimitry Andric       AddressSpace(RtCheck.Pointers[Index]
186fe6060f1SDimitry Andric                        .PointerValue->getType()
18781ad6265SDimitry Andric                        ->getPointerAddressSpace()),
18881ad6265SDimitry Andric       NeedsFreeze(RtCheck.Pointers[Index].NeedsFreeze) {
1895ffd83dbSDimitry Andric   Members.push_back(Index);
1905ffd83dbSDimitry Andric }
1915ffd83dbSDimitry Andric 
1920b57cec5SDimitry Andric /// Calculate Start and End points of memory access.
1930b57cec5SDimitry Andric /// Let's assume A is the first access and B is a memory access on N-th loop
1940b57cec5SDimitry Andric /// iteration. Then B is calculated as:
1950b57cec5SDimitry Andric ///   B = A + Step*N .
1960b57cec5SDimitry Andric /// Step value may be positive or negative.
1970b57cec5SDimitry Andric /// N is a calculated back-edge taken count:
1980b57cec5SDimitry Andric ///     N = (TripCount > 0) ? RoundDown(TripCount -1 , VF) : 0
1990b57cec5SDimitry Andric /// Start and End points are calculated in the following way:
2000b57cec5SDimitry Andric /// Start = UMIN(A, B) ; End = UMAX(A, B) + SizeOfElt,
2010b57cec5SDimitry Andric /// where SizeOfElt is the size of single memory access in bytes.
2020b57cec5SDimitry Andric ///
2030b57cec5SDimitry Andric /// There is no conflict when the intervals are disjoint:
2040b57cec5SDimitry Andric /// NoConflict = (P2.Start >= P1.End) || (P1.Start >= P2.End)
20581ad6265SDimitry Andric void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, const SCEV *PtrExpr,
20681ad6265SDimitry Andric                                     Type *AccessTy, bool WritePtr,
2070b57cec5SDimitry Andric                                     unsigned DepSetId, unsigned ASId,
20881ad6265SDimitry Andric                                     PredicatedScalarEvolution &PSE,
20981ad6265SDimitry Andric                                     bool NeedsFreeze) {
2100b57cec5SDimitry Andric   ScalarEvolution *SE = PSE.getSE();
2110b57cec5SDimitry Andric 
2120b57cec5SDimitry Andric   const SCEV *ScStart;
2130b57cec5SDimitry Andric   const SCEV *ScEnd;
2140b57cec5SDimitry Andric 
21581ad6265SDimitry Andric   if (SE->isLoopInvariant(PtrExpr, Lp)) {
21681ad6265SDimitry Andric     ScStart = ScEnd = PtrExpr;
217fe6060f1SDimitry Andric   } else {
21881ad6265SDimitry Andric     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrExpr);
2190b57cec5SDimitry Andric     assert(AR && "Invalid addrec expression");
2200b57cec5SDimitry Andric     const SCEV *Ex = PSE.getBackedgeTakenCount();
2210b57cec5SDimitry Andric 
2220b57cec5SDimitry Andric     ScStart = AR->getStart();
2230b57cec5SDimitry Andric     ScEnd = AR->evaluateAtIteration(Ex, *SE);
2240b57cec5SDimitry Andric     const SCEV *Step = AR->getStepRecurrence(*SE);
2250b57cec5SDimitry Andric 
2260b57cec5SDimitry Andric     // For expressions with negative step, the upper bound is ScStart and the
2270b57cec5SDimitry Andric     // lower bound is ScEnd.
2280b57cec5SDimitry Andric     if (const auto *CStep = dyn_cast<SCEVConstant>(Step)) {
2290b57cec5SDimitry Andric       if (CStep->getValue()->isNegative())
2300b57cec5SDimitry Andric         std::swap(ScStart, ScEnd);
2310b57cec5SDimitry Andric     } else {
2320b57cec5SDimitry Andric       // Fallback case: the step is not constant, but we can still
2330b57cec5SDimitry Andric       // get the upper and lower bounds of the interval by using min/max
2340b57cec5SDimitry Andric       // expressions.
2350b57cec5SDimitry Andric       ScStart = SE->getUMinExpr(ScStart, ScEnd);
2360b57cec5SDimitry Andric       ScEnd = SE->getUMaxExpr(AR->getStart(), ScEnd);
2370b57cec5SDimitry Andric     }
238fe6060f1SDimitry Andric   }
239fe013be4SDimitry Andric   assert(SE->isLoopInvariant(ScStart, Lp) && "ScStart needs to be invariant");
240fe013be4SDimitry Andric   assert(SE->isLoopInvariant(ScEnd, Lp)&& "ScEnd needs to be invariant");
241fe013be4SDimitry Andric 
2420b57cec5SDimitry Andric   // Add the size of the pointed element to ScEnd.
243e8d8bef9SDimitry Andric   auto &DL = Lp->getHeader()->getModule()->getDataLayout();
244e8d8bef9SDimitry Andric   Type *IdxTy = DL.getIndexType(Ptr->getType());
24581ad6265SDimitry Andric   const SCEV *EltSizeSCEV = SE->getStoreSizeOfExpr(IdxTy, AccessTy);
2460b57cec5SDimitry Andric   ScEnd = SE->getAddExpr(ScEnd, EltSizeSCEV);
2470b57cec5SDimitry Andric 
24881ad6265SDimitry Andric   Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, PtrExpr,
24981ad6265SDimitry Andric                         NeedsFreeze);
2500b57cec5SDimitry Andric }
2510b57cec5SDimitry Andric 
25281ad6265SDimitry Andric void RuntimePointerChecking::tryToCreateDiffCheck(
25381ad6265SDimitry Andric     const RuntimeCheckingPtrGroup &CGI, const RuntimeCheckingPtrGroup &CGJ) {
25481ad6265SDimitry Andric   if (!CanUseDiffCheck)
25581ad6265SDimitry Andric     return;
25681ad6265SDimitry Andric 
25781ad6265SDimitry Andric   // If either group contains multiple different pointers, bail out.
25881ad6265SDimitry Andric   // TODO: Support multiple pointers by using the minimum or maximum pointer,
25981ad6265SDimitry Andric   // depending on src & sink.
26081ad6265SDimitry Andric   if (CGI.Members.size() != 1 || CGJ.Members.size() != 1) {
26181ad6265SDimitry Andric     CanUseDiffCheck = false;
26281ad6265SDimitry Andric     return;
26381ad6265SDimitry Andric   }
26481ad6265SDimitry Andric 
26581ad6265SDimitry Andric   PointerInfo *Src = &Pointers[CGI.Members[0]];
26681ad6265SDimitry Andric   PointerInfo *Sink = &Pointers[CGJ.Members[0]];
26781ad6265SDimitry Andric 
26881ad6265SDimitry Andric   // If either pointer is read and written, multiple checks may be needed. Bail
26981ad6265SDimitry Andric   // out.
27081ad6265SDimitry Andric   if (!DC.getOrderForAccess(Src->PointerValue, !Src->IsWritePtr).empty() ||
27181ad6265SDimitry Andric       !DC.getOrderForAccess(Sink->PointerValue, !Sink->IsWritePtr).empty()) {
27281ad6265SDimitry Andric     CanUseDiffCheck = false;
27381ad6265SDimitry Andric     return;
27481ad6265SDimitry Andric   }
27581ad6265SDimitry Andric 
27681ad6265SDimitry Andric   ArrayRef<unsigned> AccSrc =
27781ad6265SDimitry Andric       DC.getOrderForAccess(Src->PointerValue, Src->IsWritePtr);
27881ad6265SDimitry Andric   ArrayRef<unsigned> AccSink =
27981ad6265SDimitry Andric       DC.getOrderForAccess(Sink->PointerValue, Sink->IsWritePtr);
28081ad6265SDimitry Andric   // If either pointer is accessed multiple times, there may not be a clear
28181ad6265SDimitry Andric   // src/sink relation. Bail out for now.
28281ad6265SDimitry Andric   if (AccSrc.size() != 1 || AccSink.size() != 1) {
28381ad6265SDimitry Andric     CanUseDiffCheck = false;
28481ad6265SDimitry Andric     return;
28581ad6265SDimitry Andric   }
28681ad6265SDimitry Andric   // If the sink is accessed before src, swap src/sink.
28781ad6265SDimitry Andric   if (AccSink[0] < AccSrc[0])
28881ad6265SDimitry Andric     std::swap(Src, Sink);
28981ad6265SDimitry Andric 
29081ad6265SDimitry Andric   auto *SrcAR = dyn_cast<SCEVAddRecExpr>(Src->Expr);
29181ad6265SDimitry Andric   auto *SinkAR = dyn_cast<SCEVAddRecExpr>(Sink->Expr);
292a4a491e2SDimitry Andric   if (!SrcAR || !SinkAR || SrcAR->getLoop() != DC.getInnermostLoop() ||
293a4a491e2SDimitry Andric       SinkAR->getLoop() != DC.getInnermostLoop()) {
29481ad6265SDimitry Andric     CanUseDiffCheck = false;
29581ad6265SDimitry Andric     return;
29681ad6265SDimitry Andric   }
29781ad6265SDimitry Andric 
29881ad6265SDimitry Andric   SmallVector<Instruction *, 4> SrcInsts =
29981ad6265SDimitry Andric       DC.getInstructionsForAccess(Src->PointerValue, Src->IsWritePtr);
30081ad6265SDimitry Andric   SmallVector<Instruction *, 4> SinkInsts =
30181ad6265SDimitry Andric       DC.getInstructionsForAccess(Sink->PointerValue, Sink->IsWritePtr);
30281ad6265SDimitry Andric   Type *SrcTy = getLoadStoreType(SrcInsts[0]);
30381ad6265SDimitry Andric   Type *DstTy = getLoadStoreType(SinkInsts[0]);
304fcaf7f86SDimitry Andric   if (isa<ScalableVectorType>(SrcTy) || isa<ScalableVectorType>(DstTy)) {
305fcaf7f86SDimitry Andric     CanUseDiffCheck = false;
30681ad6265SDimitry Andric     return;
307fcaf7f86SDimitry Andric   }
308bdd1243dSDimitry Andric   const DataLayout &DL =
309bdd1243dSDimitry Andric       SinkAR->getLoop()->getHeader()->getModule()->getDataLayout();
31081ad6265SDimitry Andric   unsigned AllocSize =
31181ad6265SDimitry Andric       std::max(DL.getTypeAllocSize(SrcTy), DL.getTypeAllocSize(DstTy));
31281ad6265SDimitry Andric 
31381ad6265SDimitry Andric   // Only matching constant steps matching the AllocSize are supported at the
31481ad6265SDimitry Andric   // moment. This simplifies the difference computation. Can be extended in the
31581ad6265SDimitry Andric   // future.
31681ad6265SDimitry Andric   auto *Step = dyn_cast<SCEVConstant>(SinkAR->getStepRecurrence(*SE));
31781ad6265SDimitry Andric   if (!Step || Step != SrcAR->getStepRecurrence(*SE) ||
31881ad6265SDimitry Andric       Step->getAPInt().abs() != AllocSize) {
31981ad6265SDimitry Andric     CanUseDiffCheck = false;
32081ad6265SDimitry Andric     return;
32181ad6265SDimitry Andric   }
32281ad6265SDimitry Andric 
323bdd1243dSDimitry Andric   IntegerType *IntTy =
324bdd1243dSDimitry Andric       IntegerType::get(Src->PointerValue->getContext(),
325bdd1243dSDimitry Andric                        DL.getPointerSizeInBits(CGI.AddressSpace));
326bdd1243dSDimitry Andric 
32781ad6265SDimitry Andric   // When counting down, the dependence distance needs to be swapped.
32881ad6265SDimitry Andric   if (Step->getValue()->isNegative())
32981ad6265SDimitry Andric     std::swap(SinkAR, SrcAR);
33081ad6265SDimitry Andric 
33181ad6265SDimitry Andric   const SCEV *SinkStartInt = SE->getPtrToIntExpr(SinkAR->getStart(), IntTy);
33281ad6265SDimitry Andric   const SCEV *SrcStartInt = SE->getPtrToIntExpr(SrcAR->getStart(), IntTy);
33381ad6265SDimitry Andric   if (isa<SCEVCouldNotCompute>(SinkStartInt) ||
33481ad6265SDimitry Andric       isa<SCEVCouldNotCompute>(SrcStartInt)) {
33581ad6265SDimitry Andric     CanUseDiffCheck = false;
33681ad6265SDimitry Andric     return;
33781ad6265SDimitry Andric   }
338c9157d92SDimitry Andric 
339c9157d92SDimitry Andric   const Loop *InnerLoop = SrcAR->getLoop();
340c9157d92SDimitry Andric   // If the start values for both Src and Sink also vary according to an outer
341c9157d92SDimitry Andric   // loop, then it's probably better to avoid creating diff checks because
342c9157d92SDimitry Andric   // they may not be hoisted. We should instead let llvm::addRuntimeChecks
343c9157d92SDimitry Andric   // do the expanded full range overlap checks, which can be hoisted.
344c9157d92SDimitry Andric   if (HoistRuntimeChecks && InnerLoop->getParentLoop() &&
345c9157d92SDimitry Andric       isa<SCEVAddRecExpr>(SinkStartInt) && isa<SCEVAddRecExpr>(SrcStartInt)) {
346c9157d92SDimitry Andric     auto *SrcStartAR = cast<SCEVAddRecExpr>(SrcStartInt);
347c9157d92SDimitry Andric     auto *SinkStartAR = cast<SCEVAddRecExpr>(SinkStartInt);
348c9157d92SDimitry Andric     const Loop *StartARLoop = SrcStartAR->getLoop();
349c9157d92SDimitry Andric     if (StartARLoop == SinkStartAR->getLoop() &&
350c9157d92SDimitry Andric         StartARLoop == InnerLoop->getParentLoop() &&
351c9157d92SDimitry Andric         // If the diff check would already be loop invariant (due to the
352c9157d92SDimitry Andric         // recurrences being the same), then we prefer to keep the diff checks
353c9157d92SDimitry Andric         // because they are cheaper.
354c9157d92SDimitry Andric         SrcStartAR->getStepRecurrence(*SE) !=
355c9157d92SDimitry Andric             SinkStartAR->getStepRecurrence(*SE)) {
356c9157d92SDimitry Andric       LLVM_DEBUG(dbgs() << "LAA: Not creating diff runtime check, since these "
357c9157d92SDimitry Andric                            "cannot be hoisted out of the outer loop\n");
358c9157d92SDimitry Andric       CanUseDiffCheck = false;
359c9157d92SDimitry Andric       return;
360c9157d92SDimitry Andric     }
361c9157d92SDimitry Andric   }
362c9157d92SDimitry Andric 
363c9157d92SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Creating diff runtime check for:\n"
364c9157d92SDimitry Andric                     << "SrcStart: " << *SrcStartInt << '\n'
365c9157d92SDimitry Andric                     << "SinkStartInt: " << *SinkStartInt << '\n');
36681ad6265SDimitry Andric   DiffChecks.emplace_back(SrcStartInt, SinkStartInt, AllocSize,
36781ad6265SDimitry Andric                           Src->NeedsFreeze || Sink->NeedsFreeze);
36881ad6265SDimitry Andric }
36981ad6265SDimitry Andric 
37081ad6265SDimitry Andric SmallVector<RuntimePointerCheck, 4> RuntimePointerChecking::generateChecks() {
3715ffd83dbSDimitry Andric   SmallVector<RuntimePointerCheck, 4> Checks;
3720b57cec5SDimitry Andric 
3730b57cec5SDimitry Andric   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
3740b57cec5SDimitry Andric     for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) {
3755ffd83dbSDimitry Andric       const RuntimeCheckingPtrGroup &CGI = CheckingGroups[I];
3765ffd83dbSDimitry Andric       const RuntimeCheckingPtrGroup &CGJ = CheckingGroups[J];
3770b57cec5SDimitry Andric 
37881ad6265SDimitry Andric       if (needsChecking(CGI, CGJ)) {
37981ad6265SDimitry Andric         tryToCreateDiffCheck(CGI, CGJ);
3800b57cec5SDimitry Andric         Checks.push_back(std::make_pair(&CGI, &CGJ));
3810b57cec5SDimitry Andric       }
3820b57cec5SDimitry Andric     }
38381ad6265SDimitry Andric   }
3840b57cec5SDimitry Andric   return Checks;
3850b57cec5SDimitry Andric }
3860b57cec5SDimitry Andric 
3870b57cec5SDimitry Andric void RuntimePointerChecking::generateChecks(
3880b57cec5SDimitry Andric     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
3890b57cec5SDimitry Andric   assert(Checks.empty() && "Checks is not empty");
3900b57cec5SDimitry Andric   groupChecks(DepCands, UseDependencies);
3910b57cec5SDimitry Andric   Checks = generateChecks();
3920b57cec5SDimitry Andric }
3930b57cec5SDimitry Andric 
3945ffd83dbSDimitry Andric bool RuntimePointerChecking::needsChecking(
3955ffd83dbSDimitry Andric     const RuntimeCheckingPtrGroup &M, const RuntimeCheckingPtrGroup &N) const {
3960b57cec5SDimitry Andric   for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I)
3970b57cec5SDimitry Andric     for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J)
3980b57cec5SDimitry Andric       if (needsChecking(M.Members[I], N.Members[J]))
3990b57cec5SDimitry Andric         return true;
4000b57cec5SDimitry Andric   return false;
4010b57cec5SDimitry Andric }
4020b57cec5SDimitry Andric 
4030b57cec5SDimitry Andric /// Compare \p I and \p J and return the minimum.
4040b57cec5SDimitry Andric /// Return nullptr in case we couldn't find an answer.
4050b57cec5SDimitry Andric static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
4060b57cec5SDimitry Andric                                    ScalarEvolution *SE) {
4070b57cec5SDimitry Andric   const SCEV *Diff = SE->getMinusSCEV(J, I);
4080b57cec5SDimitry Andric   const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
4090b57cec5SDimitry Andric 
4100b57cec5SDimitry Andric   if (!C)
4110b57cec5SDimitry Andric     return nullptr;
4120b57cec5SDimitry Andric   if (C->getValue()->isNegative())
4130b57cec5SDimitry Andric     return J;
4140b57cec5SDimitry Andric   return I;
4150b57cec5SDimitry Andric }
4160b57cec5SDimitry Andric 
417fe6060f1SDimitry Andric bool RuntimeCheckingPtrGroup::addPointer(unsigned Index,
418fe6060f1SDimitry Andric                                          RuntimePointerChecking &RtCheck) {
419fe6060f1SDimitry Andric   return addPointer(
420fe6060f1SDimitry Andric       Index, RtCheck.Pointers[Index].Start, RtCheck.Pointers[Index].End,
421fe6060f1SDimitry Andric       RtCheck.Pointers[Index].PointerValue->getType()->getPointerAddressSpace(),
42281ad6265SDimitry Andric       RtCheck.Pointers[Index].NeedsFreeze, *RtCheck.SE);
423fe6060f1SDimitry Andric }
424fe6060f1SDimitry Andric 
425fe6060f1SDimitry Andric bool RuntimeCheckingPtrGroup::addPointer(unsigned Index, const SCEV *Start,
426fe6060f1SDimitry Andric                                          const SCEV *End, unsigned AS,
42781ad6265SDimitry Andric                                          bool NeedsFreeze,
428fe6060f1SDimitry Andric                                          ScalarEvolution &SE) {
429fe6060f1SDimitry Andric   assert(AddressSpace == AS &&
430fe6060f1SDimitry Andric          "all pointers in a checking group must be in the same address space");
4310b57cec5SDimitry Andric 
4320b57cec5SDimitry Andric   // Compare the starts and ends with the known minimum and maximum
4330b57cec5SDimitry Andric   // of this set. We need to know how we compare against the min/max
4340b57cec5SDimitry Andric   // of the set in order to be able to emit memchecks.
435fe6060f1SDimitry Andric   const SCEV *Min0 = getMinFromExprs(Start, Low, &SE);
4360b57cec5SDimitry Andric   if (!Min0)
4370b57cec5SDimitry Andric     return false;
4380b57cec5SDimitry Andric 
439fe6060f1SDimitry Andric   const SCEV *Min1 = getMinFromExprs(End, High, &SE);
4400b57cec5SDimitry Andric   if (!Min1)
4410b57cec5SDimitry Andric     return false;
4420b57cec5SDimitry Andric 
4430b57cec5SDimitry Andric   // Update the low bound  expression if we've found a new min value.
4440b57cec5SDimitry Andric   if (Min0 == Start)
4450b57cec5SDimitry Andric     Low = Start;
4460b57cec5SDimitry Andric 
4470b57cec5SDimitry Andric   // Update the high bound expression if we've found a new max value.
4480b57cec5SDimitry Andric   if (Min1 != End)
4490b57cec5SDimitry Andric     High = End;
4500b57cec5SDimitry Andric 
4510b57cec5SDimitry Andric   Members.push_back(Index);
45281ad6265SDimitry Andric   this->NeedsFreeze |= NeedsFreeze;
4530b57cec5SDimitry Andric   return true;
4540b57cec5SDimitry Andric }
4550b57cec5SDimitry Andric 
4560b57cec5SDimitry Andric void RuntimePointerChecking::groupChecks(
4570b57cec5SDimitry Andric     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
4580b57cec5SDimitry Andric   // We build the groups from dependency candidates equivalence classes
4590b57cec5SDimitry Andric   // because:
4600b57cec5SDimitry Andric   //    - We know that pointers in the same equivalence class share
4610b57cec5SDimitry Andric   //      the same underlying object and therefore there is a chance
4620b57cec5SDimitry Andric   //      that we can compare pointers
4630b57cec5SDimitry Andric   //    - We wouldn't be able to merge two pointers for which we need
4640b57cec5SDimitry Andric   //      to emit a memcheck. The classes in DepCands are already
4650b57cec5SDimitry Andric   //      conveniently built such that no two pointers in the same
4660b57cec5SDimitry Andric   //      class need checking against each other.
4670b57cec5SDimitry Andric 
4680b57cec5SDimitry Andric   // We use the following (greedy) algorithm to construct the groups
4690b57cec5SDimitry Andric   // For every pointer in the equivalence class:
4700b57cec5SDimitry Andric   //   For each existing group:
4710b57cec5SDimitry Andric   //   - if the difference between this pointer and the min/max bounds
4720b57cec5SDimitry Andric   //     of the group is a constant, then make the pointer part of the
4730b57cec5SDimitry Andric   //     group and update the min/max bounds of that group as required.
4740b57cec5SDimitry Andric 
4750b57cec5SDimitry Andric   CheckingGroups.clear();
4760b57cec5SDimitry Andric 
4770b57cec5SDimitry Andric   // If we need to check two pointers to the same underlying object
4780b57cec5SDimitry Andric   // with a non-constant difference, we shouldn't perform any pointer
4790b57cec5SDimitry Andric   // grouping with those pointers. This is because we can easily get
4800b57cec5SDimitry Andric   // into cases where the resulting check would return false, even when
4810b57cec5SDimitry Andric   // the accesses are safe.
4820b57cec5SDimitry Andric   //
4830b57cec5SDimitry Andric   // The following example shows this:
4840b57cec5SDimitry Andric   // for (i = 0; i < 1000; ++i)
4850b57cec5SDimitry Andric   //   a[5000 + i * m] = a[i] + a[i + 9000]
4860b57cec5SDimitry Andric   //
4870b57cec5SDimitry Andric   // Here grouping gives a check of (5000, 5000 + 1000 * m) against
4880b57cec5SDimitry Andric   // (0, 10000) which is always false. However, if m is 1, there is no
4890b57cec5SDimitry Andric   // dependence. Not grouping the checks for a[i] and a[i + 9000] allows
4900b57cec5SDimitry Andric   // us to perform an accurate check in this case.
4910b57cec5SDimitry Andric   //
4920b57cec5SDimitry Andric   // The above case requires that we have an UnknownDependence between
4930b57cec5SDimitry Andric   // accesses to the same underlying object. This cannot happen unless
4940b57cec5SDimitry Andric   // FoundNonConstantDistanceDependence is set, and therefore UseDependencies
4950b57cec5SDimitry Andric   // is also false. In this case we will use the fallback path and create
4960b57cec5SDimitry Andric   // separate checking groups for all pointers.
4970b57cec5SDimitry Andric 
4980b57cec5SDimitry Andric   // If we don't have the dependency partitions, construct a new
4990b57cec5SDimitry Andric   // checking pointer group for each pointer. This is also required
5000b57cec5SDimitry Andric   // for correctness, because in this case we can have checking between
5010b57cec5SDimitry Andric   // pointers to the same underlying object.
5020b57cec5SDimitry Andric   if (!UseDependencies) {
5030b57cec5SDimitry Andric     for (unsigned I = 0; I < Pointers.size(); ++I)
5045ffd83dbSDimitry Andric       CheckingGroups.push_back(RuntimeCheckingPtrGroup(I, *this));
5050b57cec5SDimitry Andric     return;
5060b57cec5SDimitry Andric   }
5070b57cec5SDimitry Andric 
5080b57cec5SDimitry Andric   unsigned TotalComparisons = 0;
5090b57cec5SDimitry Andric 
51081ad6265SDimitry Andric   DenseMap<Value *, SmallVector<unsigned>> PositionMap;
51181ad6265SDimitry Andric   for (unsigned Index = 0; Index < Pointers.size(); ++Index) {
51281ad6265SDimitry Andric     auto Iter = PositionMap.insert({Pointers[Index].PointerValue, {}});
51381ad6265SDimitry Andric     Iter.first->second.push_back(Index);
51481ad6265SDimitry Andric   }
5150b57cec5SDimitry Andric 
5160b57cec5SDimitry Andric   // We need to keep track of what pointers we've already seen so we
5170b57cec5SDimitry Andric   // don't process them twice.
5180b57cec5SDimitry Andric   SmallSet<unsigned, 2> Seen;
5190b57cec5SDimitry Andric 
5200b57cec5SDimitry Andric   // Go through all equivalence classes, get the "pointer check groups"
5210b57cec5SDimitry Andric   // and add them to the overall solution. We use the order in which accesses
5220b57cec5SDimitry Andric   // appear in 'Pointers' to enforce determinism.
5230b57cec5SDimitry Andric   for (unsigned I = 0; I < Pointers.size(); ++I) {
5240b57cec5SDimitry Andric     // We've seen this pointer before, and therefore already processed
5250b57cec5SDimitry Andric     // its equivalence class.
5260b57cec5SDimitry Andric     if (Seen.count(I))
5270b57cec5SDimitry Andric       continue;
5280b57cec5SDimitry Andric 
5290b57cec5SDimitry Andric     MemoryDepChecker::MemAccessInfo Access(Pointers[I].PointerValue,
5300b57cec5SDimitry Andric                                            Pointers[I].IsWritePtr);
5310b57cec5SDimitry Andric 
5325ffd83dbSDimitry Andric     SmallVector<RuntimeCheckingPtrGroup, 2> Groups;
5330b57cec5SDimitry Andric     auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access));
5340b57cec5SDimitry Andric 
5350b57cec5SDimitry Andric     // Because DepCands is constructed by visiting accesses in the order in
5360b57cec5SDimitry Andric     // which they appear in alias sets (which is deterministic) and the
5370b57cec5SDimitry Andric     // iteration order within an equivalence class member is only dependent on
5380b57cec5SDimitry Andric     // the order in which unions and insertions are performed on the
5390b57cec5SDimitry Andric     // equivalence class, the iteration order is deterministic.
5400b57cec5SDimitry Andric     for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end();
5410b57cec5SDimitry Andric          MI != ME; ++MI) {
5421106035dSDimitry Andric       auto PointerI = PositionMap.find(MI->getPointer());
5431106035dSDimitry Andric       assert(PointerI != PositionMap.end() &&
5441106035dSDimitry Andric              "pointer in equivalence class not found in PositionMap");
54581ad6265SDimitry Andric       for (unsigned Pointer : PointerI->second) {
5460b57cec5SDimitry Andric         bool Merged = false;
5470b57cec5SDimitry Andric         // Mark this pointer as seen.
5480b57cec5SDimitry Andric         Seen.insert(Pointer);
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric         // Go through all the existing sets and see if we can find one
5510b57cec5SDimitry Andric         // which can include this pointer.
5525ffd83dbSDimitry Andric         for (RuntimeCheckingPtrGroup &Group : Groups) {
5530b57cec5SDimitry Andric           // Don't perform more than a certain amount of comparisons.
5540b57cec5SDimitry Andric           // This should limit the cost of grouping the pointers to something
5550b57cec5SDimitry Andric           // reasonable.  If we do end up hitting this threshold, the algorithm
5560b57cec5SDimitry Andric           // will create separate groups for all remaining pointers.
5570b57cec5SDimitry Andric           if (TotalComparisons > MemoryCheckMergeThreshold)
5580b57cec5SDimitry Andric             break;
5590b57cec5SDimitry Andric 
5600b57cec5SDimitry Andric           TotalComparisons++;
5610b57cec5SDimitry Andric 
562fe6060f1SDimitry Andric           if (Group.addPointer(Pointer, *this)) {
5630b57cec5SDimitry Andric             Merged = true;
5640b57cec5SDimitry Andric             break;
5650b57cec5SDimitry Andric           }
5660b57cec5SDimitry Andric         }
5670b57cec5SDimitry Andric 
5680b57cec5SDimitry Andric         if (!Merged)
5690b57cec5SDimitry Andric           // We couldn't add this pointer to any existing set or the threshold
5700b57cec5SDimitry Andric           // for the number of comparisons has been reached. Create a new group
5710b57cec5SDimitry Andric           // to hold the current pointer.
5725ffd83dbSDimitry Andric           Groups.push_back(RuntimeCheckingPtrGroup(Pointer, *this));
5730b57cec5SDimitry Andric       }
57481ad6265SDimitry Andric     }
5750b57cec5SDimitry Andric 
5760b57cec5SDimitry Andric     // We've computed the grouped checks for this partition.
5770b57cec5SDimitry Andric     // Save the results and continue with the next one.
5780b57cec5SDimitry Andric     llvm::copy(Groups, std::back_inserter(CheckingGroups));
5790b57cec5SDimitry Andric   }
5800b57cec5SDimitry Andric }
5810b57cec5SDimitry Andric 
5820b57cec5SDimitry Andric bool RuntimePointerChecking::arePointersInSamePartition(
5830b57cec5SDimitry Andric     const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
5840b57cec5SDimitry Andric     unsigned PtrIdx2) {
5850b57cec5SDimitry Andric   return (PtrToPartition[PtrIdx1] != -1 &&
5860b57cec5SDimitry Andric           PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
5870b57cec5SDimitry Andric }
5880b57cec5SDimitry Andric 
5890b57cec5SDimitry Andric bool RuntimePointerChecking::needsChecking(unsigned I, unsigned J) const {
5900b57cec5SDimitry Andric   const PointerInfo &PointerI = Pointers[I];
5910b57cec5SDimitry Andric   const PointerInfo &PointerJ = Pointers[J];
5920b57cec5SDimitry Andric 
5930b57cec5SDimitry Andric   // No need to check if two readonly pointers intersect.
5940b57cec5SDimitry Andric   if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
5950b57cec5SDimitry Andric     return false;
5960b57cec5SDimitry Andric 
5970b57cec5SDimitry Andric   // Only need to check pointers between two different dependency sets.
5980b57cec5SDimitry Andric   if (PointerI.DependencySetId == PointerJ.DependencySetId)
5990b57cec5SDimitry Andric     return false;
6000b57cec5SDimitry Andric 
6010b57cec5SDimitry Andric   // Only need to check pointers in the same alias set.
6020b57cec5SDimitry Andric   if (PointerI.AliasSetId != PointerJ.AliasSetId)
6030b57cec5SDimitry Andric     return false;
6040b57cec5SDimitry Andric 
6050b57cec5SDimitry Andric   return true;
6060b57cec5SDimitry Andric }
6070b57cec5SDimitry Andric 
6080b57cec5SDimitry Andric void RuntimePointerChecking::printChecks(
6095ffd83dbSDimitry Andric     raw_ostream &OS, const SmallVectorImpl<RuntimePointerCheck> &Checks,
6100b57cec5SDimitry Andric     unsigned Depth) const {
6110b57cec5SDimitry Andric   unsigned N = 0;
6120b57cec5SDimitry Andric   for (const auto &Check : Checks) {
6130b57cec5SDimitry Andric     const auto &First = Check.first->Members, &Second = Check.second->Members;
6140b57cec5SDimitry Andric 
6150b57cec5SDimitry Andric     OS.indent(Depth) << "Check " << N++ << ":\n";
6160b57cec5SDimitry Andric 
6170b57cec5SDimitry Andric     OS.indent(Depth + 2) << "Comparing group (" << Check.first << "):\n";
6180b57cec5SDimitry Andric     for (unsigned K = 0; K < First.size(); ++K)
6190b57cec5SDimitry Andric       OS.indent(Depth + 2) << *Pointers[First[K]].PointerValue << "\n";
6200b57cec5SDimitry Andric 
6210b57cec5SDimitry Andric     OS.indent(Depth + 2) << "Against group (" << Check.second << "):\n";
6220b57cec5SDimitry Andric     for (unsigned K = 0; K < Second.size(); ++K)
6230b57cec5SDimitry Andric       OS.indent(Depth + 2) << *Pointers[Second[K]].PointerValue << "\n";
6240b57cec5SDimitry Andric   }
6250b57cec5SDimitry Andric }
6260b57cec5SDimitry Andric 
6270b57cec5SDimitry Andric void RuntimePointerChecking::print(raw_ostream &OS, unsigned Depth) const {
6280b57cec5SDimitry Andric 
6290b57cec5SDimitry Andric   OS.indent(Depth) << "Run-time memory checks:\n";
6300b57cec5SDimitry Andric   printChecks(OS, Checks, Depth);
6310b57cec5SDimitry Andric 
6320b57cec5SDimitry Andric   OS.indent(Depth) << "Grouped accesses:\n";
6330b57cec5SDimitry Andric   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
6340b57cec5SDimitry Andric     const auto &CG = CheckingGroups[I];
6350b57cec5SDimitry Andric 
6360b57cec5SDimitry Andric     OS.indent(Depth + 2) << "Group " << &CG << ":\n";
6370b57cec5SDimitry Andric     OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High
6380b57cec5SDimitry Andric                          << ")\n";
6390b57cec5SDimitry Andric     for (unsigned J = 0; J < CG.Members.size(); ++J) {
6400b57cec5SDimitry Andric       OS.indent(Depth + 6) << "Member: " << *Pointers[CG.Members[J]].Expr
6410b57cec5SDimitry Andric                            << "\n";
6420b57cec5SDimitry Andric     }
6430b57cec5SDimitry Andric   }
6440b57cec5SDimitry Andric }
6450b57cec5SDimitry Andric 
6460b57cec5SDimitry Andric namespace {
6470b57cec5SDimitry Andric 
6480b57cec5SDimitry Andric /// Analyses memory accesses in a loop.
6490b57cec5SDimitry Andric ///
6500b57cec5SDimitry Andric /// Checks whether run time pointer checks are needed and builds sets for data
6510b57cec5SDimitry Andric /// dependence checking.
6520b57cec5SDimitry Andric class AccessAnalysis {
6530b57cec5SDimitry Andric public:
6540b57cec5SDimitry Andric   /// Read or write access location.
6550b57cec5SDimitry Andric   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
6560b57cec5SDimitry Andric   typedef SmallVector<MemAccessInfo, 8> MemAccessInfoList;
6570b57cec5SDimitry Andric 
658e8d8bef9SDimitry Andric   AccessAnalysis(Loop *TheLoop, AAResults *AA, LoopInfo *LI,
659e8d8bef9SDimitry Andric                  MemoryDepChecker::DepCandidates &DA,
6600b57cec5SDimitry Andric                  PredicatedScalarEvolution &PSE)
661bdd1243dSDimitry Andric       : TheLoop(TheLoop), BAA(*AA), AST(BAA), LI(LI), DepCands(DA), PSE(PSE) {
662bdd1243dSDimitry Andric     // We're analyzing dependences across loop iterations.
663bdd1243dSDimitry Andric     BAA.enableCrossIterationMode();
664bdd1243dSDimitry Andric   }
6650b57cec5SDimitry Andric 
6660b57cec5SDimitry Andric   /// Register a load  and whether it is only read from.
66781ad6265SDimitry Andric   void addLoad(MemoryLocation &Loc, Type *AccessTy, bool IsReadOnly) {
6680b57cec5SDimitry Andric     Value *Ptr = const_cast<Value*>(Loc.Ptr);
669c9157d92SDimitry Andric     AST.add(Loc.getWithNewSize(LocationSize::beforeOrAfterPointer()));
67081ad6265SDimitry Andric     Accesses[MemAccessInfo(Ptr, false)].insert(AccessTy);
6710b57cec5SDimitry Andric     if (IsReadOnly)
6720b57cec5SDimitry Andric       ReadOnlyPtr.insert(Ptr);
6730b57cec5SDimitry Andric   }
6740b57cec5SDimitry Andric 
6750b57cec5SDimitry Andric   /// Register a store.
67681ad6265SDimitry Andric   void addStore(MemoryLocation &Loc, Type *AccessTy) {
6770b57cec5SDimitry Andric     Value *Ptr = const_cast<Value*>(Loc.Ptr);
678c9157d92SDimitry Andric     AST.add(Loc.getWithNewSize(LocationSize::beforeOrAfterPointer()));
67981ad6265SDimitry Andric     Accesses[MemAccessInfo(Ptr, true)].insert(AccessTy);
6800b57cec5SDimitry Andric   }
6810b57cec5SDimitry Andric 
6820b57cec5SDimitry Andric   /// Check if we can emit a run-time no-alias check for \p Access.
6830b57cec5SDimitry Andric   ///
6840b57cec5SDimitry Andric   /// Returns true if we can emit a run-time no alias check for \p Access.
6850b57cec5SDimitry Andric   /// If we can check this access, this also adds it to a dependence set and
6860b57cec5SDimitry Andric   /// adds a run-time to check for it to \p RtCheck. If \p Assume is true,
6870b57cec5SDimitry Andric   /// we will attempt to use additional run-time checks in order to get
6880b57cec5SDimitry Andric   /// the bounds of the pointer.
6890b57cec5SDimitry Andric   bool createCheckForAccess(RuntimePointerChecking &RtCheck,
69081ad6265SDimitry Andric                             MemAccessInfo Access, Type *AccessTy,
691fe013be4SDimitry Andric                             const DenseMap<Value *, const SCEV *> &Strides,
6920b57cec5SDimitry Andric                             DenseMap<Value *, unsigned> &DepSetId,
6930b57cec5SDimitry Andric                             Loop *TheLoop, unsigned &RunningDepId,
69481ad6265SDimitry Andric                             unsigned ASId, bool ShouldCheckStride, bool Assume);
6950b57cec5SDimitry Andric 
6960b57cec5SDimitry Andric   /// Check whether we can check the pointers at runtime for
6970b57cec5SDimitry Andric   /// non-intersection.
6980b57cec5SDimitry Andric   ///
6990b57cec5SDimitry Andric   /// Returns true if we need no check or if we do and we can generate them
7000b57cec5SDimitry Andric   /// (i.e. the pointers have computable bounds).
7010b57cec5SDimitry Andric   bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE,
702fe013be4SDimitry Andric                        Loop *TheLoop, const DenseMap<Value *, const SCEV *> &Strides,
70381ad6265SDimitry Andric                        Value *&UncomputablePtr, bool ShouldCheckWrap = false);
7040b57cec5SDimitry Andric 
7050b57cec5SDimitry Andric   /// Goes over all memory accesses, checks whether a RT check is needed
7060b57cec5SDimitry Andric   /// and builds sets of dependent accesses.
7070b57cec5SDimitry Andric   void buildDependenceSets() {
7080b57cec5SDimitry Andric     processMemAccesses();
7090b57cec5SDimitry Andric   }
7100b57cec5SDimitry Andric 
7110b57cec5SDimitry Andric   /// Initial processing of memory accesses determined that we need to
7120b57cec5SDimitry Andric   /// perform dependency checking.
7130b57cec5SDimitry Andric   ///
7140b57cec5SDimitry Andric   /// Note that this can later be cleared if we retry memcheck analysis without
7150b57cec5SDimitry Andric   /// dependency checking (i.e. FoundNonConstantDistanceDependence).
7160b57cec5SDimitry Andric   bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
7170b57cec5SDimitry Andric 
7180b57cec5SDimitry Andric   /// We decided that no dependence analysis would be used.  Reset the state.
7190b57cec5SDimitry Andric   void resetDepChecks(MemoryDepChecker &DepChecker) {
7200b57cec5SDimitry Andric     CheckDeps.clear();
7210b57cec5SDimitry Andric     DepChecker.clearDependences();
7220b57cec5SDimitry Andric   }
7230b57cec5SDimitry Andric 
7240b57cec5SDimitry Andric   MemAccessInfoList &getDependenciesToCheck() { return CheckDeps; }
7250b57cec5SDimitry Andric 
726c9157d92SDimitry Andric   const DenseMap<Value *, SmallVector<const Value *, 16>> &
727c9157d92SDimitry Andric   getUnderlyingObjects() {
728c9157d92SDimitry Andric     return UnderlyingObjects;
729c9157d92SDimitry Andric   }
730c9157d92SDimitry Andric 
7310b57cec5SDimitry Andric private:
73281ad6265SDimitry Andric   typedef MapVector<MemAccessInfo, SmallSetVector<Type *, 1>> PtrAccessMap;
7330b57cec5SDimitry Andric 
7340b57cec5SDimitry Andric   /// Go over all memory access and check whether runtime pointer checks
7350b57cec5SDimitry Andric   /// are needed and build sets of dependency check candidates.
7360b57cec5SDimitry Andric   void processMemAccesses();
7370b57cec5SDimitry Andric 
73881ad6265SDimitry Andric   /// Map of all accesses. Values are the types used to access memory pointed to
73981ad6265SDimitry Andric   /// by the pointer.
74081ad6265SDimitry Andric   PtrAccessMap Accesses;
7410b57cec5SDimitry Andric 
7420b57cec5SDimitry Andric   /// The loop being checked.
7430b57cec5SDimitry Andric   const Loop *TheLoop;
7440b57cec5SDimitry Andric 
7450b57cec5SDimitry Andric   /// List of accesses that need a further dependence check.
7460b57cec5SDimitry Andric   MemAccessInfoList CheckDeps;
7470b57cec5SDimitry Andric 
7480b57cec5SDimitry Andric   /// Set of pointers that are read only.
7490b57cec5SDimitry Andric   SmallPtrSet<Value*, 16> ReadOnlyPtr;
7500b57cec5SDimitry Andric 
751bdd1243dSDimitry Andric   /// Batched alias analysis results.
752bdd1243dSDimitry Andric   BatchAAResults BAA;
753bdd1243dSDimitry Andric 
7540b57cec5SDimitry Andric   /// An alias set tracker to partition the access set by underlying object and
7550b57cec5SDimitry Andric   //intrinsic property (such as TBAA metadata).
7560b57cec5SDimitry Andric   AliasSetTracker AST;
7570b57cec5SDimitry Andric 
7580b57cec5SDimitry Andric   LoopInfo *LI;
7590b57cec5SDimitry Andric 
7600b57cec5SDimitry Andric   /// Sets of potentially dependent accesses - members of one set share an
7610b57cec5SDimitry Andric   /// underlying pointer. The set "CheckDeps" identfies which sets really need a
7620b57cec5SDimitry Andric   /// dependence check.
7630b57cec5SDimitry Andric   MemoryDepChecker::DepCandidates &DepCands;
7640b57cec5SDimitry Andric 
7650b57cec5SDimitry Andric   /// Initial processing of memory accesses determined that we may need
7660b57cec5SDimitry Andric   /// to add memchecks.  Perform the analysis to determine the necessary checks.
7670b57cec5SDimitry Andric   ///
7680b57cec5SDimitry Andric   /// Note that, this is different from isDependencyCheckNeeded.  When we retry
7690b57cec5SDimitry Andric   /// memcheck analysis without dependency checking
7700b57cec5SDimitry Andric   /// (i.e. FoundNonConstantDistanceDependence), isDependencyCheckNeeded is
7710b57cec5SDimitry Andric   /// cleared while this remains set if we have potentially dependent accesses.
77204eeddc0SDimitry Andric   bool IsRTCheckAnalysisNeeded = false;
7730b57cec5SDimitry Andric 
7740b57cec5SDimitry Andric   /// The SCEV predicate containing all the SCEV-related assumptions.
7750b57cec5SDimitry Andric   PredicatedScalarEvolution &PSE;
776c9157d92SDimitry Andric 
777c9157d92SDimitry Andric   DenseMap<Value *, SmallVector<const Value *, 16>> UnderlyingObjects;
7780b57cec5SDimitry Andric };
7790b57cec5SDimitry Andric 
7800b57cec5SDimitry Andric } // end anonymous namespace
7810b57cec5SDimitry Andric 
7820b57cec5SDimitry Andric /// Check whether a pointer can participate in a runtime bounds check.
7830b57cec5SDimitry Andric /// If \p Assume, try harder to prove that we can compute the bounds of \p Ptr
7840b57cec5SDimitry Andric /// by adding run-time checks (overflow checks) if necessary.
78581ad6265SDimitry Andric static bool hasComputableBounds(PredicatedScalarEvolution &PSE, Value *Ptr,
78681ad6265SDimitry Andric                                 const SCEV *PtrScev, Loop *L, bool Assume) {
7870b57cec5SDimitry Andric   // The bounds for loop-invariant pointer is trivial.
7880b57cec5SDimitry Andric   if (PSE.getSE()->isLoopInvariant(PtrScev, L))
7890b57cec5SDimitry Andric     return true;
7900b57cec5SDimitry Andric 
7910b57cec5SDimitry Andric   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
7920b57cec5SDimitry Andric 
7930b57cec5SDimitry Andric   if (!AR && Assume)
7940b57cec5SDimitry Andric     AR = PSE.getAsAddRec(Ptr);
7950b57cec5SDimitry Andric 
7960b57cec5SDimitry Andric   if (!AR)
7970b57cec5SDimitry Andric     return false;
7980b57cec5SDimitry Andric 
7990b57cec5SDimitry Andric   return AR->isAffine();
8000b57cec5SDimitry Andric }
8010b57cec5SDimitry Andric 
8020b57cec5SDimitry Andric /// Check whether a pointer address cannot wrap.
8030b57cec5SDimitry Andric static bool isNoWrap(PredicatedScalarEvolution &PSE,
804fe013be4SDimitry Andric                      const DenseMap<Value *, const SCEV *> &Strides, Value *Ptr, Type *AccessTy,
80581ad6265SDimitry Andric                      Loop *L) {
8060b57cec5SDimitry Andric   const SCEV *PtrScev = PSE.getSCEV(Ptr);
8070b57cec5SDimitry Andric   if (PSE.getSE()->isLoopInvariant(PtrScev, L))
8080b57cec5SDimitry Andric     return true;
8090b57cec5SDimitry Andric 
810bdd1243dSDimitry Andric   int64_t Stride = getPtrStride(PSE, AccessTy, Ptr, L, Strides).value_or(0);
8110b57cec5SDimitry Andric   if (Stride == 1 || PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW))
8120b57cec5SDimitry Andric     return true;
8130b57cec5SDimitry Andric 
8140b57cec5SDimitry Andric   return false;
8150b57cec5SDimitry Andric }
8160b57cec5SDimitry Andric 
8174824e7fdSDimitry Andric static void visitPointers(Value *StartPtr, const Loop &InnermostLoop,
8184824e7fdSDimitry Andric                           function_ref<void(Value *)> AddPointer) {
8194824e7fdSDimitry Andric   SmallPtrSet<Value *, 8> Visited;
8204824e7fdSDimitry Andric   SmallVector<Value *> WorkList;
8214824e7fdSDimitry Andric   WorkList.push_back(StartPtr);
8224824e7fdSDimitry Andric 
8234824e7fdSDimitry Andric   while (!WorkList.empty()) {
8244824e7fdSDimitry Andric     Value *Ptr = WorkList.pop_back_val();
8254824e7fdSDimitry Andric     if (!Visited.insert(Ptr).second)
8264824e7fdSDimitry Andric       continue;
8274824e7fdSDimitry Andric     auto *PN = dyn_cast<PHINode>(Ptr);
8284824e7fdSDimitry Andric     // SCEV does not look through non-header PHIs inside the loop. Such phis
8294824e7fdSDimitry Andric     // can be analyzed by adding separate accesses for each incoming pointer
8304824e7fdSDimitry Andric     // value.
8314824e7fdSDimitry Andric     if (PN && InnermostLoop.contains(PN->getParent()) &&
8324824e7fdSDimitry Andric         PN->getParent() != InnermostLoop.getHeader()) {
8334824e7fdSDimitry Andric       for (const Use &Inc : PN->incoming_values())
8344824e7fdSDimitry Andric         WorkList.push_back(Inc);
8354824e7fdSDimitry Andric     } else
8364824e7fdSDimitry Andric       AddPointer(Ptr);
8374824e7fdSDimitry Andric   }
8384824e7fdSDimitry Andric }
8394824e7fdSDimitry Andric 
840fcaf7f86SDimitry Andric // Walk back through the IR for a pointer, looking for a select like the
841fcaf7f86SDimitry Andric // following:
842fcaf7f86SDimitry Andric //
843fcaf7f86SDimitry Andric //  %offset = select i1 %cmp, i64 %a, i64 %b
844fcaf7f86SDimitry Andric //  %addr = getelementptr double, double* %base, i64 %offset
845fcaf7f86SDimitry Andric //  %ld = load double, double* %addr, align 8
846fcaf7f86SDimitry Andric //
847fcaf7f86SDimitry Andric // We won't be able to form a single SCEVAddRecExpr from this since the
848fcaf7f86SDimitry Andric // address for each loop iteration depends on %cmp. We could potentially
849fcaf7f86SDimitry Andric // produce multiple valid SCEVAddRecExprs, though, and check all of them for
850fcaf7f86SDimitry Andric // memory safety/aliasing if needed.
851fcaf7f86SDimitry Andric //
852fcaf7f86SDimitry Andric // If we encounter some IR we don't yet handle, or something obviously fine
853fcaf7f86SDimitry Andric // like a constant, then we just add the SCEV for that term to the list passed
854fcaf7f86SDimitry Andric // in by the caller. If we have a node that may potentially yield a valid
855fcaf7f86SDimitry Andric // SCEVAddRecExpr then we decompose it into parts and build the SCEV terms
856fcaf7f86SDimitry Andric // ourselves before adding to the list.
857bdd1243dSDimitry Andric static void findForkedSCEVs(
858bdd1243dSDimitry Andric     ScalarEvolution *SE, const Loop *L, Value *Ptr,
859bdd1243dSDimitry Andric     SmallVectorImpl<PointerIntPair<const SCEV *, 1, bool>> &ScevList,
860fcaf7f86SDimitry Andric     unsigned Depth) {
861fcaf7f86SDimitry Andric   // If our Value is a SCEVAddRecExpr, loop invariant, not an instruction, or
862fcaf7f86SDimitry Andric   // we've exceeded our limit on recursion, just return whatever we have
863fcaf7f86SDimitry Andric   // regardless of whether it can be used for a forked pointer or not, along
864fcaf7f86SDimitry Andric   // with an indication of whether it might be a poison or undef value.
865fcaf7f86SDimitry Andric   const SCEV *Scev = SE->getSCEV(Ptr);
866fcaf7f86SDimitry Andric   if (isa<SCEVAddRecExpr>(Scev) || L->isLoopInvariant(Ptr) ||
867fcaf7f86SDimitry Andric       !isa<Instruction>(Ptr) || Depth == 0) {
868bdd1243dSDimitry Andric     ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
869fcaf7f86SDimitry Andric     return;
870fcaf7f86SDimitry Andric   }
871fcaf7f86SDimitry Andric 
872fcaf7f86SDimitry Andric   Depth--;
873fcaf7f86SDimitry Andric 
874bdd1243dSDimitry Andric   auto UndefPoisonCheck = [](PointerIntPair<const SCEV *, 1, bool> S) {
875bdd1243dSDimitry Andric     return get<1>(S);
876bdd1243dSDimitry Andric   };
877bdd1243dSDimitry Andric 
878bdd1243dSDimitry Andric   auto GetBinOpExpr = [&SE](unsigned Opcode, const SCEV *L, const SCEV *R) {
879bdd1243dSDimitry Andric     switch (Opcode) {
880bdd1243dSDimitry Andric     case Instruction::Add:
881bdd1243dSDimitry Andric       return SE->getAddExpr(L, R);
882bdd1243dSDimitry Andric     case Instruction::Sub:
883bdd1243dSDimitry Andric       return SE->getMinusSCEV(L, R);
884bdd1243dSDimitry Andric     default:
885bdd1243dSDimitry Andric       llvm_unreachable("Unexpected binary operator when walking ForkedPtrs");
886bdd1243dSDimitry Andric     }
887fcaf7f86SDimitry Andric   };
888fcaf7f86SDimitry Andric 
889fcaf7f86SDimitry Andric   Instruction *I = cast<Instruction>(Ptr);
890fcaf7f86SDimitry Andric   unsigned Opcode = I->getOpcode();
891fcaf7f86SDimitry Andric   switch (Opcode) {
892fcaf7f86SDimitry Andric   case Instruction::GetElementPtr: {
893fcaf7f86SDimitry Andric     GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
894fcaf7f86SDimitry Andric     Type *SourceTy = GEP->getSourceElementType();
895fcaf7f86SDimitry Andric     // We only handle base + single offset GEPs here for now.
896fcaf7f86SDimitry Andric     // Not dealing with preexisting gathers yet, so no vectors.
897fcaf7f86SDimitry Andric     if (I->getNumOperands() != 2 || SourceTy->isVectorTy()) {
898bdd1243dSDimitry Andric       ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(GEP));
899fcaf7f86SDimitry Andric       break;
900fcaf7f86SDimitry Andric     }
901bdd1243dSDimitry Andric     SmallVector<PointerIntPair<const SCEV *, 1, bool>, 2> BaseScevs;
902bdd1243dSDimitry Andric     SmallVector<PointerIntPair<const SCEV *, 1, bool>, 2> OffsetScevs;
903fcaf7f86SDimitry Andric     findForkedSCEVs(SE, L, I->getOperand(0), BaseScevs, Depth);
904fcaf7f86SDimitry Andric     findForkedSCEVs(SE, L, I->getOperand(1), OffsetScevs, Depth);
905fcaf7f86SDimitry Andric 
906fcaf7f86SDimitry Andric     // See if we need to freeze our fork...
907fcaf7f86SDimitry Andric     bool NeedsFreeze = any_of(BaseScevs, UndefPoisonCheck) ||
908fcaf7f86SDimitry Andric                        any_of(OffsetScevs, UndefPoisonCheck);
909fcaf7f86SDimitry Andric 
910fcaf7f86SDimitry Andric     // Check that we only have a single fork, on either the base or the offset.
911fcaf7f86SDimitry Andric     // Copy the SCEV across for the one without a fork in order to generate
912fcaf7f86SDimitry Andric     // the full SCEV for both sides of the GEP.
913fcaf7f86SDimitry Andric     if (OffsetScevs.size() == 2 && BaseScevs.size() == 1)
914fcaf7f86SDimitry Andric       BaseScevs.push_back(BaseScevs[0]);
915fcaf7f86SDimitry Andric     else if (BaseScevs.size() == 2 && OffsetScevs.size() == 1)
916fcaf7f86SDimitry Andric       OffsetScevs.push_back(OffsetScevs[0]);
917fcaf7f86SDimitry Andric     else {
918bdd1243dSDimitry Andric       ScevList.emplace_back(Scev, NeedsFreeze);
919fcaf7f86SDimitry Andric       break;
920fcaf7f86SDimitry Andric     }
921fcaf7f86SDimitry Andric 
922fcaf7f86SDimitry Andric     // Find the pointer type we need to extend to.
923fcaf7f86SDimitry Andric     Type *IntPtrTy = SE->getEffectiveSCEVType(
924fcaf7f86SDimitry Andric         SE->getSCEV(GEP->getPointerOperand())->getType());
925fcaf7f86SDimitry Andric 
926fcaf7f86SDimitry Andric     // Find the size of the type being pointed to. We only have a single
927fcaf7f86SDimitry Andric     // index term (guarded above) so we don't need to index into arrays or
928fcaf7f86SDimitry Andric     // structures, just get the size of the scalar value.
929fcaf7f86SDimitry Andric     const SCEV *Size = SE->getSizeOfExpr(IntPtrTy, SourceTy);
930fcaf7f86SDimitry Andric 
931fcaf7f86SDimitry Andric     // Scale up the offsets by the size of the type, then add to the bases.
932fcaf7f86SDimitry Andric     const SCEV *Scaled1 = SE->getMulExpr(
933bdd1243dSDimitry Andric         Size, SE->getTruncateOrSignExtend(get<0>(OffsetScevs[0]), IntPtrTy));
934fcaf7f86SDimitry Andric     const SCEV *Scaled2 = SE->getMulExpr(
935bdd1243dSDimitry Andric         Size, SE->getTruncateOrSignExtend(get<0>(OffsetScevs[1]), IntPtrTy));
936bdd1243dSDimitry Andric     ScevList.emplace_back(SE->getAddExpr(get<0>(BaseScevs[0]), Scaled1),
937bdd1243dSDimitry Andric                           NeedsFreeze);
938bdd1243dSDimitry Andric     ScevList.emplace_back(SE->getAddExpr(get<0>(BaseScevs[1]), Scaled2),
939bdd1243dSDimitry Andric                           NeedsFreeze);
940fcaf7f86SDimitry Andric     break;
941fcaf7f86SDimitry Andric   }
942fcaf7f86SDimitry Andric   case Instruction::Select: {
943bdd1243dSDimitry Andric     SmallVector<PointerIntPair<const SCEV *, 1, bool>, 2> ChildScevs;
944fcaf7f86SDimitry Andric     // A select means we've found a forked pointer, but we currently only
945fcaf7f86SDimitry Andric     // support a single select per pointer so if there's another behind this
946fcaf7f86SDimitry Andric     // then we just bail out and return the generic SCEV.
947fcaf7f86SDimitry Andric     findForkedSCEVs(SE, L, I->getOperand(1), ChildScevs, Depth);
948fcaf7f86SDimitry Andric     findForkedSCEVs(SE, L, I->getOperand(2), ChildScevs, Depth);
949fcaf7f86SDimitry Andric     if (ChildScevs.size() == 2) {
950fcaf7f86SDimitry Andric       ScevList.push_back(ChildScevs[0]);
951fcaf7f86SDimitry Andric       ScevList.push_back(ChildScevs[1]);
952fcaf7f86SDimitry Andric     } else
953bdd1243dSDimitry Andric       ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
954bdd1243dSDimitry Andric     break;
955bdd1243dSDimitry Andric   }
956c9157d92SDimitry Andric   case Instruction::PHI: {
957c9157d92SDimitry Andric     SmallVector<PointerIntPair<const SCEV *, 1, bool>, 2> ChildScevs;
958c9157d92SDimitry Andric     // A phi means we've found a forked pointer, but we currently only
959c9157d92SDimitry Andric     // support a single phi per pointer so if there's another behind this
960c9157d92SDimitry Andric     // then we just bail out and return the generic SCEV.
961c9157d92SDimitry Andric     if (I->getNumOperands() == 2) {
962c9157d92SDimitry Andric       findForkedSCEVs(SE, L, I->getOperand(0), ChildScevs, Depth);
963c9157d92SDimitry Andric       findForkedSCEVs(SE, L, I->getOperand(1), ChildScevs, Depth);
964c9157d92SDimitry Andric     }
965c9157d92SDimitry Andric     if (ChildScevs.size() == 2) {
966c9157d92SDimitry Andric       ScevList.push_back(ChildScevs[0]);
967c9157d92SDimitry Andric       ScevList.push_back(ChildScevs[1]);
968c9157d92SDimitry Andric     } else
969c9157d92SDimitry Andric       ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
970c9157d92SDimitry Andric     break;
971c9157d92SDimitry Andric   }
972bdd1243dSDimitry Andric   case Instruction::Add:
973bdd1243dSDimitry Andric   case Instruction::Sub: {
974bdd1243dSDimitry Andric     SmallVector<PointerIntPair<const SCEV *, 1, bool>> LScevs;
975bdd1243dSDimitry Andric     SmallVector<PointerIntPair<const SCEV *, 1, bool>> RScevs;
976bdd1243dSDimitry Andric     findForkedSCEVs(SE, L, I->getOperand(0), LScevs, Depth);
977bdd1243dSDimitry Andric     findForkedSCEVs(SE, L, I->getOperand(1), RScevs, Depth);
978bdd1243dSDimitry Andric 
979bdd1243dSDimitry Andric     // See if we need to freeze our fork...
980bdd1243dSDimitry Andric     bool NeedsFreeze =
981bdd1243dSDimitry Andric         any_of(LScevs, UndefPoisonCheck) || any_of(RScevs, UndefPoisonCheck);
982bdd1243dSDimitry Andric 
983bdd1243dSDimitry Andric     // Check that we only have a single fork, on either the left or right side.
984bdd1243dSDimitry Andric     // Copy the SCEV across for the one without a fork in order to generate
985bdd1243dSDimitry Andric     // the full SCEV for both sides of the BinOp.
986bdd1243dSDimitry Andric     if (LScevs.size() == 2 && RScevs.size() == 1)
987bdd1243dSDimitry Andric       RScevs.push_back(RScevs[0]);
988bdd1243dSDimitry Andric     else if (RScevs.size() == 2 && LScevs.size() == 1)
989bdd1243dSDimitry Andric       LScevs.push_back(LScevs[0]);
990bdd1243dSDimitry Andric     else {
991bdd1243dSDimitry Andric       ScevList.emplace_back(Scev, NeedsFreeze);
992bdd1243dSDimitry Andric       break;
993bdd1243dSDimitry Andric     }
994bdd1243dSDimitry Andric 
995bdd1243dSDimitry Andric     ScevList.emplace_back(
996bdd1243dSDimitry Andric         GetBinOpExpr(Opcode, get<0>(LScevs[0]), get<0>(RScevs[0])),
997bdd1243dSDimitry Andric         NeedsFreeze);
998bdd1243dSDimitry Andric     ScevList.emplace_back(
999bdd1243dSDimitry Andric         GetBinOpExpr(Opcode, get<0>(LScevs[1]), get<0>(RScevs[1])),
1000bdd1243dSDimitry Andric         NeedsFreeze);
1001fcaf7f86SDimitry Andric     break;
1002fcaf7f86SDimitry Andric   }
1003fcaf7f86SDimitry Andric   default:
1004fcaf7f86SDimitry Andric     // Just return the current SCEV if we haven't handled the instruction yet.
1005fcaf7f86SDimitry Andric     LLVM_DEBUG(dbgs() << "ForkedPtr unhandled instruction: " << *I << "\n");
1006bdd1243dSDimitry Andric     ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
1007fcaf7f86SDimitry Andric     break;
1008fcaf7f86SDimitry Andric   }
1009fcaf7f86SDimitry Andric }
1010fcaf7f86SDimitry Andric 
1011bdd1243dSDimitry Andric static SmallVector<PointerIntPair<const SCEV *, 1, bool>>
1012fcaf7f86SDimitry Andric findForkedPointer(PredicatedScalarEvolution &PSE,
1013fe013be4SDimitry Andric                   const DenseMap<Value *, const SCEV *> &StridesMap, Value *Ptr,
1014fcaf7f86SDimitry Andric                   const Loop *L) {
1015fcaf7f86SDimitry Andric   ScalarEvolution *SE = PSE.getSE();
1016fcaf7f86SDimitry Andric   assert(SE->isSCEVable(Ptr->getType()) && "Value is not SCEVable!");
1017bdd1243dSDimitry Andric   SmallVector<PointerIntPair<const SCEV *, 1, bool>> Scevs;
1018fcaf7f86SDimitry Andric   findForkedSCEVs(SE, L, Ptr, Scevs, MaxForkedSCEVDepth);
1019fcaf7f86SDimitry Andric 
1020bdd1243dSDimitry Andric   // For now, we will only accept a forked pointer with two possible SCEVs
1021bdd1243dSDimitry Andric   // that are either SCEVAddRecExprs or loop invariant.
1022bdd1243dSDimitry Andric   if (Scevs.size() == 2 &&
1023bdd1243dSDimitry Andric       (isa<SCEVAddRecExpr>(get<0>(Scevs[0])) ||
1024bdd1243dSDimitry Andric        SE->isLoopInvariant(get<0>(Scevs[0]), L)) &&
1025bdd1243dSDimitry Andric       (isa<SCEVAddRecExpr>(get<0>(Scevs[1])) ||
1026bdd1243dSDimitry Andric        SE->isLoopInvariant(get<0>(Scevs[1]), L))) {
1027bdd1243dSDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Found forked pointer: " << *Ptr << "\n");
1028bdd1243dSDimitry Andric     LLVM_DEBUG(dbgs() << "\t(1) " << *get<0>(Scevs[0]) << "\n");
1029bdd1243dSDimitry Andric     LLVM_DEBUG(dbgs() << "\t(2) " << *get<0>(Scevs[1]) << "\n");
1030fcaf7f86SDimitry Andric     return Scevs;
1031bdd1243dSDimitry Andric   }
1032fcaf7f86SDimitry Andric 
1033bdd1243dSDimitry Andric   return {{replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr), false}};
1034fcaf7f86SDimitry Andric }
1035fcaf7f86SDimitry Andric 
10360b57cec5SDimitry Andric bool AccessAnalysis::createCheckForAccess(RuntimePointerChecking &RtCheck,
103781ad6265SDimitry Andric                                           MemAccessInfo Access, Type *AccessTy,
1038fe013be4SDimitry Andric                                           const DenseMap<Value *, const SCEV *> &StridesMap,
10390b57cec5SDimitry Andric                                           DenseMap<Value *, unsigned> &DepSetId,
10400b57cec5SDimitry Andric                                           Loop *TheLoop, unsigned &RunningDepId,
10410b57cec5SDimitry Andric                                           unsigned ASId, bool ShouldCheckWrap,
10420b57cec5SDimitry Andric                                           bool Assume) {
10430b57cec5SDimitry Andric   Value *Ptr = Access.getPointer();
10440b57cec5SDimitry Andric 
1045bdd1243dSDimitry Andric   SmallVector<PointerIntPair<const SCEV *, 1, bool>> TranslatedPtrs =
1046fcaf7f86SDimitry Andric       findForkedPointer(PSE, StridesMap, Ptr, TheLoop);
104781ad6265SDimitry Andric 
104881ad6265SDimitry Andric   for (auto &P : TranslatedPtrs) {
1049bdd1243dSDimitry Andric     const SCEV *PtrExpr = get<0>(P);
105081ad6265SDimitry Andric     if (!hasComputableBounds(PSE, Ptr, PtrExpr, TheLoop, Assume))
10510b57cec5SDimitry Andric       return false;
10520b57cec5SDimitry Andric 
10530b57cec5SDimitry Andric     // When we run after a failing dependency check we have to make sure
10540b57cec5SDimitry Andric     // we don't have wrapping pointers.
105581ad6265SDimitry Andric     if (ShouldCheckWrap) {
105681ad6265SDimitry Andric       // Skip wrap checking when translating pointers.
105781ad6265SDimitry Andric       if (TranslatedPtrs.size() > 1)
105881ad6265SDimitry Andric         return false;
105981ad6265SDimitry Andric 
106081ad6265SDimitry Andric       if (!isNoWrap(PSE, StridesMap, Ptr, AccessTy, TheLoop)) {
10610b57cec5SDimitry Andric         auto *Expr = PSE.getSCEV(Ptr);
10620b57cec5SDimitry Andric         if (!Assume || !isa<SCEVAddRecExpr>(Expr))
10630b57cec5SDimitry Andric           return false;
10640b57cec5SDimitry Andric         PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
10650b57cec5SDimitry Andric       }
106681ad6265SDimitry Andric     }
106781ad6265SDimitry Andric     // If there's only one option for Ptr, look it up after bounds and wrap
106881ad6265SDimitry Andric     // checking, because assumptions might have been added to PSE.
106981ad6265SDimitry Andric     if (TranslatedPtrs.size() == 1)
1070bdd1243dSDimitry Andric       TranslatedPtrs[0] = {replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr),
1071bdd1243dSDimitry Andric                            false};
107281ad6265SDimitry Andric   }
107381ad6265SDimitry Andric 
1074bdd1243dSDimitry Andric   for (auto [PtrExpr, NeedsFreeze] : TranslatedPtrs) {
10750b57cec5SDimitry Andric     // The id of the dependence set.
10760b57cec5SDimitry Andric     unsigned DepId;
10770b57cec5SDimitry Andric 
10780b57cec5SDimitry Andric     if (isDependencyCheckNeeded()) {
10790b57cec5SDimitry Andric       Value *Leader = DepCands.getLeaderValue(Access).getPointer();
10800b57cec5SDimitry Andric       unsigned &LeaderId = DepSetId[Leader];
10810b57cec5SDimitry Andric       if (!LeaderId)
10820b57cec5SDimitry Andric         LeaderId = RunningDepId++;
10830b57cec5SDimitry Andric       DepId = LeaderId;
10840b57cec5SDimitry Andric     } else
10850b57cec5SDimitry Andric       // Each access has its own dependence set.
10860b57cec5SDimitry Andric       DepId = RunningDepId++;
10870b57cec5SDimitry Andric 
10880b57cec5SDimitry Andric     bool IsWrite = Access.getInt();
108981ad6265SDimitry Andric     RtCheck.insert(TheLoop, Ptr, PtrExpr, AccessTy, IsWrite, DepId, ASId, PSE,
1090bdd1243dSDimitry Andric                    NeedsFreeze);
10910b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
109281ad6265SDimitry Andric   }
10930b57cec5SDimitry Andric 
10940b57cec5SDimitry Andric   return true;
10950b57cec5SDimitry Andric }
10960b57cec5SDimitry Andric 
10970b57cec5SDimitry Andric bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
10980b57cec5SDimitry Andric                                      ScalarEvolution *SE, Loop *TheLoop,
1099fe013be4SDimitry Andric                                      const DenseMap<Value *, const SCEV *> &StridesMap,
110081ad6265SDimitry Andric                                      Value *&UncomputablePtr, bool ShouldCheckWrap) {
11010b57cec5SDimitry Andric   // Find pointers with computable bounds. We are going to use this information
11020b57cec5SDimitry Andric   // to place a runtime bound check.
11030b57cec5SDimitry Andric   bool CanDoRT = true;
11040b57cec5SDimitry Andric 
11055ffd83dbSDimitry Andric   bool MayNeedRTCheck = false;
11060b57cec5SDimitry Andric   if (!IsRTCheckAnalysisNeeded) return true;
11070b57cec5SDimitry Andric 
11080b57cec5SDimitry Andric   bool IsDepCheckNeeded = isDependencyCheckNeeded();
11090b57cec5SDimitry Andric 
11100b57cec5SDimitry Andric   // We assign a consecutive id to access from different alias sets.
11110b57cec5SDimitry Andric   // Accesses between different groups doesn't need to be checked.
11125ffd83dbSDimitry Andric   unsigned ASId = 0;
11130b57cec5SDimitry Andric   for (auto &AS : AST) {
11140b57cec5SDimitry Andric     int NumReadPtrChecks = 0;
11150b57cec5SDimitry Andric     int NumWritePtrChecks = 0;
11160b57cec5SDimitry Andric     bool CanDoAliasSetRT = true;
11175ffd83dbSDimitry Andric     ++ASId;
11180b57cec5SDimitry Andric 
11190b57cec5SDimitry Andric     // We assign consecutive id to access from different dependence sets.
11200b57cec5SDimitry Andric     // Accesses within the same set don't need a runtime check.
11210b57cec5SDimitry Andric     unsigned RunningDepId = 1;
11220b57cec5SDimitry Andric     DenseMap<Value *, unsigned> DepSetId;
11230b57cec5SDimitry Andric 
1124fcaf7f86SDimitry Andric     SmallVector<std::pair<MemAccessInfo, Type *>, 4> Retries;
11250b57cec5SDimitry Andric 
11261106035dSDimitry Andric     // First, count how many write and read accesses are in the alias set. Also
11271106035dSDimitry Andric     // collect MemAccessInfos for later.
11281106035dSDimitry Andric     SmallVector<MemAccessInfo, 4> AccessInfos;
1129e8d8bef9SDimitry Andric     for (const auto &A : AS) {
11300b57cec5SDimitry Andric       Value *Ptr = A.getValue();
11310b57cec5SDimitry Andric       bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
11320b57cec5SDimitry Andric       if (IsWrite)
11330b57cec5SDimitry Andric         ++NumWritePtrChecks;
11340b57cec5SDimitry Andric       else
11350b57cec5SDimitry Andric         ++NumReadPtrChecks;
11361106035dSDimitry Andric       AccessInfos.emplace_back(Ptr, IsWrite);
11370b57cec5SDimitry Andric     }
11380b57cec5SDimitry Andric 
11391106035dSDimitry Andric     // We do not need runtime checks for this alias set, if there are no writes
11401106035dSDimitry Andric     // or a single write and no reads.
11411106035dSDimitry Andric     if (NumWritePtrChecks == 0 ||
11421106035dSDimitry Andric         (NumWritePtrChecks == 1 && NumReadPtrChecks == 0)) {
11435ffd83dbSDimitry Andric       assert((AS.size() <= 1 ||
11445ffd83dbSDimitry Andric               all_of(AS,
11455ffd83dbSDimitry Andric                      [this](auto AC) {
11465ffd83dbSDimitry Andric                        MemAccessInfo AccessWrite(AC.getValue(), true);
11471106035dSDimitry Andric                        return DepCands.findValue(AccessWrite) == DepCands.end();
11485ffd83dbSDimitry Andric                      })) &&
11495ffd83dbSDimitry Andric              "Can only skip updating CanDoRT below, if all entries in AS "
11505ffd83dbSDimitry Andric              "are reads or there is at most 1 entry");
11515ffd83dbSDimitry Andric       continue;
11525ffd83dbSDimitry Andric     }
11531106035dSDimitry Andric 
11541106035dSDimitry Andric     for (auto &Access : AccessInfos) {
1155fcaf7f86SDimitry Andric       for (const auto &AccessTy : Accesses[Access]) {
115681ad6265SDimitry Andric         if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap,
115781ad6265SDimitry Andric                                   DepSetId, TheLoop, RunningDepId, ASId,
115881ad6265SDimitry Andric                                   ShouldCheckWrap, false)) {
11591106035dSDimitry Andric           LLVM_DEBUG(dbgs() << "LAA: Can't find bounds for ptr:"
11601106035dSDimitry Andric                             << *Access.getPointer() << '\n');
1161fcaf7f86SDimitry Andric           Retries.push_back({Access, AccessTy});
11621106035dSDimitry Andric           CanDoAliasSetRT = false;
11635ffd83dbSDimitry Andric         }
11641106035dSDimitry Andric       }
116581ad6265SDimitry Andric     }
11661106035dSDimitry Andric 
11671106035dSDimitry Andric     // Note that this function computes CanDoRT and MayNeedRTCheck
11681106035dSDimitry Andric     // independently. For example CanDoRT=false, MayNeedRTCheck=false means that
11691106035dSDimitry Andric     // we have a pointer for which we couldn't find the bounds but we don't
11701106035dSDimitry Andric     // actually need to emit any checks so it does not matter.
11711106035dSDimitry Andric     //
11721106035dSDimitry Andric     // We need runtime checks for this alias set, if there are at least 2
11731106035dSDimitry Andric     // dependence sets (in which case RunningDepId > 2) or if we need to re-try
11741106035dSDimitry Andric     // any bound checks (because in that case the number of dependence sets is
11751106035dSDimitry Andric     // incomplete).
11761106035dSDimitry Andric     bool NeedsAliasSetRTCheck = RunningDepId > 2 || !Retries.empty();
11770b57cec5SDimitry Andric 
11780b57cec5SDimitry Andric     // We need to perform run-time alias checks, but some pointers had bounds
11790b57cec5SDimitry Andric     // that couldn't be checked.
11800b57cec5SDimitry Andric     if (NeedsAliasSetRTCheck && !CanDoAliasSetRT) {
11810b57cec5SDimitry Andric       // Reset the CanDoSetRt flag and retry all accesses that have failed.
11820b57cec5SDimitry Andric       // We know that we need these checks, so we can now be more aggressive
11830b57cec5SDimitry Andric       // and add further checks if required (overflow checks).
11840b57cec5SDimitry Andric       CanDoAliasSetRT = true;
1185fcaf7f86SDimitry Andric       for (auto Retry : Retries) {
1186fcaf7f86SDimitry Andric         MemAccessInfo Access = Retry.first;
1187fcaf7f86SDimitry Andric         Type *AccessTy = Retry.second;
118881ad6265SDimitry Andric         if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap,
118981ad6265SDimitry Andric                                   DepSetId, TheLoop, RunningDepId, ASId,
11900b57cec5SDimitry Andric                                   ShouldCheckWrap, /*Assume=*/true)) {
11910b57cec5SDimitry Andric           CanDoAliasSetRT = false;
119281ad6265SDimitry Andric           UncomputablePtr = Access.getPointer();
11930b57cec5SDimitry Andric           break;
11940b57cec5SDimitry Andric         }
11950b57cec5SDimitry Andric       }
119681ad6265SDimitry Andric     }
11970b57cec5SDimitry Andric 
11980b57cec5SDimitry Andric     CanDoRT &= CanDoAliasSetRT;
11995ffd83dbSDimitry Andric     MayNeedRTCheck |= NeedsAliasSetRTCheck;
12000b57cec5SDimitry Andric     ++ASId;
12010b57cec5SDimitry Andric   }
12020b57cec5SDimitry Andric 
12030b57cec5SDimitry Andric   // If the pointers that we would use for the bounds comparison have different
12040b57cec5SDimitry Andric   // address spaces, assume the values aren't directly comparable, so we can't
12050b57cec5SDimitry Andric   // use them for the runtime check. We also have to assume they could
12060b57cec5SDimitry Andric   // overlap. In the future there should be metadata for whether address spaces
12070b57cec5SDimitry Andric   // are disjoint.
12080b57cec5SDimitry Andric   unsigned NumPointers = RtCheck.Pointers.size();
12090b57cec5SDimitry Andric   for (unsigned i = 0; i < NumPointers; ++i) {
12100b57cec5SDimitry Andric     for (unsigned j = i + 1; j < NumPointers; ++j) {
12110b57cec5SDimitry Andric       // Only need to check pointers between two different dependency sets.
12120b57cec5SDimitry Andric       if (RtCheck.Pointers[i].DependencySetId ==
12130b57cec5SDimitry Andric           RtCheck.Pointers[j].DependencySetId)
12140b57cec5SDimitry Andric        continue;
12150b57cec5SDimitry Andric       // Only need to check pointers in the same alias set.
12160b57cec5SDimitry Andric       if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
12170b57cec5SDimitry Andric         continue;
12180b57cec5SDimitry Andric 
12190b57cec5SDimitry Andric       Value *PtrI = RtCheck.Pointers[i].PointerValue;
12200b57cec5SDimitry Andric       Value *PtrJ = RtCheck.Pointers[j].PointerValue;
12210b57cec5SDimitry Andric 
12220b57cec5SDimitry Andric       unsigned ASi = PtrI->getType()->getPointerAddressSpace();
12230b57cec5SDimitry Andric       unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
12240b57cec5SDimitry Andric       if (ASi != ASj) {
12250b57cec5SDimitry Andric         LLVM_DEBUG(
12260b57cec5SDimitry Andric             dbgs() << "LAA: Runtime check would require comparison between"
12270b57cec5SDimitry Andric                       " different address spaces\n");
12280b57cec5SDimitry Andric         return false;
12290b57cec5SDimitry Andric       }
12300b57cec5SDimitry Andric     }
12310b57cec5SDimitry Andric   }
12320b57cec5SDimitry Andric 
12335ffd83dbSDimitry Andric   if (MayNeedRTCheck && CanDoRT)
12340b57cec5SDimitry Andric     RtCheck.generateChecks(DepCands, IsDepCheckNeeded);
12350b57cec5SDimitry Andric 
12360b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks()
12370b57cec5SDimitry Andric                     << " pointer comparisons.\n");
12380b57cec5SDimitry Andric 
12395ffd83dbSDimitry Andric   // If we can do run-time checks, but there are no checks, no runtime checks
12405ffd83dbSDimitry Andric   // are needed. This can happen when all pointers point to the same underlying
12415ffd83dbSDimitry Andric   // object for example.
12425ffd83dbSDimitry Andric   RtCheck.Need = CanDoRT ? RtCheck.getNumberOfChecks() != 0 : MayNeedRTCheck;
12430b57cec5SDimitry Andric 
12445ffd83dbSDimitry Andric   bool CanDoRTIfNeeded = !RtCheck.Need || CanDoRT;
12450b57cec5SDimitry Andric   if (!CanDoRTIfNeeded)
12460b57cec5SDimitry Andric     RtCheck.reset();
12470b57cec5SDimitry Andric   return CanDoRTIfNeeded;
12480b57cec5SDimitry Andric }
12490b57cec5SDimitry Andric 
12500b57cec5SDimitry Andric void AccessAnalysis::processMemAccesses() {
12510b57cec5SDimitry Andric   // We process the set twice: first we process read-write pointers, last we
12520b57cec5SDimitry Andric   // process read-only pointers. This allows us to skip dependence tests for
12530b57cec5SDimitry Andric   // read-only pointers.
12540b57cec5SDimitry Andric 
12550b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
12560b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  AST: "; AST.dump());
12570b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA:   Accesses(" << Accesses.size() << "):\n");
12580b57cec5SDimitry Andric   LLVM_DEBUG({
12590b57cec5SDimitry Andric     for (auto A : Accesses)
126081ad6265SDimitry Andric       dbgs() << "\t" << *A.first.getPointer() << " ("
126181ad6265SDimitry Andric              << (A.first.getInt()
126281ad6265SDimitry Andric                      ? "write"
126381ad6265SDimitry Andric                      : (ReadOnlyPtr.count(A.first.getPointer()) ? "read-only"
126481ad6265SDimitry Andric                                                                 : "read"))
126581ad6265SDimitry Andric              << ")\n";
12660b57cec5SDimitry Andric   });
12670b57cec5SDimitry Andric 
12680b57cec5SDimitry Andric   // The AliasSetTracker has nicely partitioned our pointers by metadata
12690b57cec5SDimitry Andric   // compatibility and potential for underlying-object overlap. As a result, we
12700b57cec5SDimitry Andric   // only need to check for potential pointer dependencies within each alias
12710b57cec5SDimitry Andric   // set.
1272e8d8bef9SDimitry Andric   for (const auto &AS : AST) {
12730b57cec5SDimitry Andric     // Note that both the alias-set tracker and the alias sets themselves used
12740b57cec5SDimitry Andric     // linked lists internally and so the iteration order here is deterministic
12750b57cec5SDimitry Andric     // (matching the original instruction order within each set).
12760b57cec5SDimitry Andric 
12770b57cec5SDimitry Andric     bool SetHasWrite = false;
12780b57cec5SDimitry Andric 
12790b57cec5SDimitry Andric     // Map of pointers to last access encountered.
12800b57cec5SDimitry Andric     typedef DenseMap<const Value*, MemAccessInfo> UnderlyingObjToAccessMap;
12810b57cec5SDimitry Andric     UnderlyingObjToAccessMap ObjToLastAccess;
12820b57cec5SDimitry Andric 
12830b57cec5SDimitry Andric     // Set of access to check after all writes have been processed.
128481ad6265SDimitry Andric     PtrAccessMap DeferredAccesses;
12850b57cec5SDimitry Andric 
12860b57cec5SDimitry Andric     // Iterate over each alias set twice, once to process read/write pointers,
12870b57cec5SDimitry Andric     // and then to process read-only pointers.
12880b57cec5SDimitry Andric     for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
12890b57cec5SDimitry Andric       bool UseDeferred = SetIteration > 0;
129081ad6265SDimitry Andric       PtrAccessMap &S = UseDeferred ? DeferredAccesses : Accesses;
12910b57cec5SDimitry Andric 
1292e8d8bef9SDimitry Andric       for (const auto &AV : AS) {
12930b57cec5SDimitry Andric         Value *Ptr = AV.getValue();
12940b57cec5SDimitry Andric 
12950b57cec5SDimitry Andric         // For a single memory access in AliasSetTracker, Accesses may contain
12960b57cec5SDimitry Andric         // both read and write, and they both need to be handled for CheckDeps.
1297e8d8bef9SDimitry Andric         for (const auto &AC : S) {
129881ad6265SDimitry Andric           if (AC.first.getPointer() != Ptr)
12990b57cec5SDimitry Andric             continue;
13000b57cec5SDimitry Andric 
130181ad6265SDimitry Andric           bool IsWrite = AC.first.getInt();
13020b57cec5SDimitry Andric 
13030b57cec5SDimitry Andric           // If we're using the deferred access set, then it contains only
13040b57cec5SDimitry Andric           // reads.
13050b57cec5SDimitry Andric           bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
13060b57cec5SDimitry Andric           if (UseDeferred && !IsReadOnlyPtr)
13070b57cec5SDimitry Andric             continue;
13080b57cec5SDimitry Andric           // Otherwise, the pointer must be in the PtrAccessSet, either as a
13090b57cec5SDimitry Andric           // read or a write.
13100b57cec5SDimitry Andric           assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
13110b57cec5SDimitry Andric                   S.count(MemAccessInfo(Ptr, false))) &&
13120b57cec5SDimitry Andric                  "Alias-set pointer not in the access set?");
13130b57cec5SDimitry Andric 
13140b57cec5SDimitry Andric           MemAccessInfo Access(Ptr, IsWrite);
13150b57cec5SDimitry Andric           DepCands.insert(Access);
13160b57cec5SDimitry Andric 
13170b57cec5SDimitry Andric           // Memorize read-only pointers for later processing and skip them in
13180b57cec5SDimitry Andric           // the first round (they need to be checked after we have seen all
13190b57cec5SDimitry Andric           // write pointers). Note: we also mark pointer that are not
13200b57cec5SDimitry Andric           // consecutive as "read-only" pointers (so that we check
13210b57cec5SDimitry Andric           // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
13220b57cec5SDimitry Andric           if (!UseDeferred && IsReadOnlyPtr) {
132381ad6265SDimitry Andric             // We only use the pointer keys, the types vector values don't
132481ad6265SDimitry Andric             // matter.
132581ad6265SDimitry Andric             DeferredAccesses.insert({Access, {}});
13260b57cec5SDimitry Andric             continue;
13270b57cec5SDimitry Andric           }
13280b57cec5SDimitry Andric 
13290b57cec5SDimitry Andric           // If this is a write - check other reads and writes for conflicts. If
13300b57cec5SDimitry Andric           // this is a read only check other writes for conflicts (but only if
13310b57cec5SDimitry Andric           // there is no other write to the ptr - this is an optimization to
13320b57cec5SDimitry Andric           // catch "a[i] = a[i] + " without having to do a dependence check).
13330b57cec5SDimitry Andric           if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
13340b57cec5SDimitry Andric             CheckDeps.push_back(Access);
13350b57cec5SDimitry Andric             IsRTCheckAnalysisNeeded = true;
13360b57cec5SDimitry Andric           }
13370b57cec5SDimitry Andric 
13380b57cec5SDimitry Andric           if (IsWrite)
13390b57cec5SDimitry Andric             SetHasWrite = true;
13400b57cec5SDimitry Andric 
13410b57cec5SDimitry Andric           // Create sets of pointers connected by a shared alias set and
13420b57cec5SDimitry Andric           // underlying object.
13430b57cec5SDimitry Andric           typedef SmallVector<const Value *, 16> ValueVector;
13440b57cec5SDimitry Andric           ValueVector TempObjects;
13450b57cec5SDimitry Andric 
1346c9157d92SDimitry Andric           UnderlyingObjects[Ptr] = {};
1347c9157d92SDimitry Andric           SmallVector<const Value *, 16> &UOs = UnderlyingObjects[Ptr];
1348c9157d92SDimitry Andric           ::getUnderlyingObjects(Ptr, UOs, LI);
13490b57cec5SDimitry Andric           LLVM_DEBUG(dbgs()
13500b57cec5SDimitry Andric                      << "Underlying objects for pointer " << *Ptr << "\n");
1351c9157d92SDimitry Andric           for (const Value *UnderlyingObj : UOs) {
13520b57cec5SDimitry Andric             // nullptr never alias, don't join sets for pointer that have "null"
13530b57cec5SDimitry Andric             // in their UnderlyingObjects list.
13540b57cec5SDimitry Andric             if (isa<ConstantPointerNull>(UnderlyingObj) &&
13550b57cec5SDimitry Andric                 !NullPointerIsDefined(
13560b57cec5SDimitry Andric                     TheLoop->getHeader()->getParent(),
13570b57cec5SDimitry Andric                     UnderlyingObj->getType()->getPointerAddressSpace()))
13580b57cec5SDimitry Andric               continue;
13590b57cec5SDimitry Andric 
13600b57cec5SDimitry Andric             UnderlyingObjToAccessMap::iterator Prev =
13610b57cec5SDimitry Andric                 ObjToLastAccess.find(UnderlyingObj);
13620b57cec5SDimitry Andric             if (Prev != ObjToLastAccess.end())
13630b57cec5SDimitry Andric               DepCands.unionSets(Access, Prev->second);
13640b57cec5SDimitry Andric 
13650b57cec5SDimitry Andric             ObjToLastAccess[UnderlyingObj] = Access;
13660b57cec5SDimitry Andric             LLVM_DEBUG(dbgs() << "  " << *UnderlyingObj << "\n");
13670b57cec5SDimitry Andric           }
13680b57cec5SDimitry Andric         }
13690b57cec5SDimitry Andric       }
13700b57cec5SDimitry Andric     }
13710b57cec5SDimitry Andric   }
13720b57cec5SDimitry Andric }
13730b57cec5SDimitry Andric 
13740b57cec5SDimitry Andric /// Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
13750b57cec5SDimitry Andric /// i.e. monotonically increasing/decreasing.
13760b57cec5SDimitry Andric static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
13770b57cec5SDimitry Andric                            PredicatedScalarEvolution &PSE, const Loop *L) {
1378fe013be4SDimitry Andric 
13790b57cec5SDimitry Andric   // FIXME: This should probably only return true for NUW.
13800b57cec5SDimitry Andric   if (AR->getNoWrapFlags(SCEV::NoWrapMask))
13810b57cec5SDimitry Andric     return true;
13820b57cec5SDimitry Andric 
1383fe013be4SDimitry Andric   if (PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW))
1384fe013be4SDimitry Andric     return true;
1385fe013be4SDimitry Andric 
13860b57cec5SDimitry Andric   // Scalar evolution does not propagate the non-wrapping flags to values that
13870b57cec5SDimitry Andric   // are derived from a non-wrapping induction variable because non-wrapping
13880b57cec5SDimitry Andric   // could be flow-sensitive.
13890b57cec5SDimitry Andric   //
13900b57cec5SDimitry Andric   // Look through the potentially overflowing instruction to try to prove
13910b57cec5SDimitry Andric   // non-wrapping for the *specific* value of Ptr.
13920b57cec5SDimitry Andric 
13930b57cec5SDimitry Andric   // The arithmetic implied by an inbounds GEP can't overflow.
13940b57cec5SDimitry Andric   auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
13950b57cec5SDimitry Andric   if (!GEP || !GEP->isInBounds())
13960b57cec5SDimitry Andric     return false;
13970b57cec5SDimitry Andric 
13980b57cec5SDimitry Andric   // Make sure there is only one non-const index and analyze that.
13990b57cec5SDimitry Andric   Value *NonConstIndex = nullptr;
1400e8d8bef9SDimitry Andric   for (Value *Index : GEP->indices())
14010b57cec5SDimitry Andric     if (!isa<ConstantInt>(Index)) {
14020b57cec5SDimitry Andric       if (NonConstIndex)
14030b57cec5SDimitry Andric         return false;
14040b57cec5SDimitry Andric       NonConstIndex = Index;
14050b57cec5SDimitry Andric     }
14060b57cec5SDimitry Andric   if (!NonConstIndex)
14070b57cec5SDimitry Andric     // The recurrence is on the pointer, ignore for now.
14080b57cec5SDimitry Andric     return false;
14090b57cec5SDimitry Andric 
14100b57cec5SDimitry Andric   // The index in GEP is signed.  It is non-wrapping if it's derived from a NSW
14110b57cec5SDimitry Andric   // AddRec using a NSW operation.
14120b57cec5SDimitry Andric   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
14130b57cec5SDimitry Andric     if (OBO->hasNoSignedWrap() &&
14140b57cec5SDimitry Andric         // Assume constant for other the operand so that the AddRec can be
14150b57cec5SDimitry Andric         // easily found.
14160b57cec5SDimitry Andric         isa<ConstantInt>(OBO->getOperand(1))) {
14170b57cec5SDimitry Andric       auto *OpScev = PSE.getSCEV(OBO->getOperand(0));
14180b57cec5SDimitry Andric 
14190b57cec5SDimitry Andric       if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
14200b57cec5SDimitry Andric         return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
14210b57cec5SDimitry Andric     }
14220b57cec5SDimitry Andric 
14230b57cec5SDimitry Andric   return false;
14240b57cec5SDimitry Andric }
14250b57cec5SDimitry Andric 
14260b57cec5SDimitry Andric /// Check whether the access through \p Ptr has a constant stride.
1427bdd1243dSDimitry Andric std::optional<int64_t> llvm::getPtrStride(PredicatedScalarEvolution &PSE,
1428bdd1243dSDimitry Andric                                           Type *AccessTy, Value *Ptr,
1429bdd1243dSDimitry Andric                                           const Loop *Lp,
1430fe013be4SDimitry Andric                                           const DenseMap<Value *, const SCEV *> &StridesMap,
1431bdd1243dSDimitry Andric                                           bool Assume, bool ShouldCheckWrap) {
14320b57cec5SDimitry Andric   Type *Ty = Ptr->getType();
14330b57cec5SDimitry Andric   assert(Ty->isPointerTy() && "Unexpected non-ptr");
14340b57cec5SDimitry Andric 
14354824e7fdSDimitry Andric   if (isa<ScalableVectorType>(AccessTy)) {
14364824e7fdSDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Scalable object: " << *AccessTy
14374824e7fdSDimitry Andric                       << "\n");
1438bdd1243dSDimitry Andric     return std::nullopt;
14390b57cec5SDimitry Andric   }
14400b57cec5SDimitry Andric 
14410b57cec5SDimitry Andric   const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr);
14420b57cec5SDimitry Andric 
14430b57cec5SDimitry Andric   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
14440b57cec5SDimitry Andric   if (Assume && !AR)
14450b57cec5SDimitry Andric     AR = PSE.getAsAddRec(Ptr);
14460b57cec5SDimitry Andric 
14470b57cec5SDimitry Andric   if (!AR) {
14480b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer " << *Ptr
14490b57cec5SDimitry Andric                       << " SCEV: " << *PtrScev << "\n");
1450bdd1243dSDimitry Andric     return std::nullopt;
14510b57cec5SDimitry Andric   }
14520b57cec5SDimitry Andric 
14530b57cec5SDimitry Andric   // The access function must stride over the innermost loop.
14540b57cec5SDimitry Andric   if (Lp != AR->getLoop()) {
14550b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop "
14560b57cec5SDimitry Andric                       << *Ptr << " SCEV: " << *AR << "\n");
1457bdd1243dSDimitry Andric     return std::nullopt;
14580b57cec5SDimitry Andric   }
14590b57cec5SDimitry Andric 
14600b57cec5SDimitry Andric   // Check the step is constant.
14610b57cec5SDimitry Andric   const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
14620b57cec5SDimitry Andric 
14630b57cec5SDimitry Andric   // Calculate the pointer stride and check if it is constant.
14640b57cec5SDimitry Andric   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
14650b57cec5SDimitry Andric   if (!C) {
14660b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr
14670b57cec5SDimitry Andric                       << " SCEV: " << *AR << "\n");
1468bdd1243dSDimitry Andric     return std::nullopt;
14690b57cec5SDimitry Andric   }
14700b57cec5SDimitry Andric 
14710b57cec5SDimitry Andric   auto &DL = Lp->getHeader()->getModule()->getDataLayout();
14724824e7fdSDimitry Andric   TypeSize AllocSize = DL.getTypeAllocSize(AccessTy);
1473bdd1243dSDimitry Andric   int64_t Size = AllocSize.getFixedValue();
14740b57cec5SDimitry Andric   const APInt &APStepVal = C->getAPInt();
14750b57cec5SDimitry Andric 
14760b57cec5SDimitry Andric   // Huge step value - give up.
14770b57cec5SDimitry Andric   if (APStepVal.getBitWidth() > 64)
1478bdd1243dSDimitry Andric     return std::nullopt;
14790b57cec5SDimitry Andric 
14800b57cec5SDimitry Andric   int64_t StepVal = APStepVal.getSExtValue();
14810b57cec5SDimitry Andric 
14820b57cec5SDimitry Andric   // Strided access.
14830b57cec5SDimitry Andric   int64_t Stride = StepVal / Size;
14840b57cec5SDimitry Andric   int64_t Rem = StepVal % Size;
14850b57cec5SDimitry Andric   if (Rem)
1486bdd1243dSDimitry Andric     return std::nullopt;
14870b57cec5SDimitry Andric 
1488fe013be4SDimitry Andric   if (!ShouldCheckWrap)
1489fe013be4SDimitry Andric     return Stride;
1490fe013be4SDimitry Andric 
1491fe013be4SDimitry Andric   // The address calculation must not wrap. Otherwise, a dependence could be
1492fe013be4SDimitry Andric   // inverted.
1493fe013be4SDimitry Andric   if (isNoWrapAddRec(Ptr, AR, PSE, Lp))
1494fe013be4SDimitry Andric     return Stride;
1495fe013be4SDimitry Andric 
1496fe013be4SDimitry Andric   // An inbounds getelementptr that is a AddRec with a unit stride
1497fe013be4SDimitry Andric   // cannot wrap per definition.  If it did, the result would be poison
1498fe013be4SDimitry Andric   // and any memory access dependent on it would be immediate UB
1499fe013be4SDimitry Andric   // when executed.
1500fe013be4SDimitry Andric   if (auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
1501fe013be4SDimitry Andric       GEP && GEP->isInBounds() && (Stride == 1 || Stride == -1))
1502fe013be4SDimitry Andric     return Stride;
1503fe013be4SDimitry Andric 
1504fe013be4SDimitry Andric   // If the null pointer is undefined, then a access sequence which would
1505fe013be4SDimitry Andric   // otherwise access it can be assumed not to unsigned wrap.  Note that this
1506fe013be4SDimitry Andric   // assumes the object in memory is aligned to the natural alignment.
1507fe013be4SDimitry Andric   unsigned AddrSpace = Ty->getPointerAddressSpace();
1508fe013be4SDimitry Andric   if (!NullPointerIsDefined(Lp->getHeader()->getParent(), AddrSpace) &&
1509fe013be4SDimitry Andric       (Stride == 1 || Stride == -1))
1510fe013be4SDimitry Andric     return Stride;
1511fe013be4SDimitry Andric 
15120b57cec5SDimitry Andric   if (Assume) {
1513fe013be4SDimitry Andric     PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
1514fe013be4SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Pointer may wrap:\n"
15150b57cec5SDimitry Andric                       << "LAA:   Pointer: " << *Ptr << "\n"
15160b57cec5SDimitry Andric                       << "LAA:   SCEV: " << *AR << "\n"
15170b57cec5SDimitry Andric                       << "LAA:   Added an overflow assumption\n");
15180b57cec5SDimitry Andric     return Stride;
15190b57cec5SDimitry Andric   }
1520fe013be4SDimitry Andric   LLVM_DEBUG(
1521fe013be4SDimitry Andric       dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
1522fe013be4SDimitry Andric              << *Ptr << " SCEV: " << *AR << "\n");
1523fe013be4SDimitry Andric   return std::nullopt;
1524fe013be4SDimitry Andric }
15250b57cec5SDimitry Andric 
1526bdd1243dSDimitry Andric std::optional<int> llvm::getPointersDiff(Type *ElemTyA, Value *PtrA,
1527bdd1243dSDimitry Andric                                          Type *ElemTyB, Value *PtrB,
1528bdd1243dSDimitry Andric                                          const DataLayout &DL,
1529fe6060f1SDimitry Andric                                          ScalarEvolution &SE, bool StrictCheck,
1530fe6060f1SDimitry Andric                                          bool CheckType) {
1531fe6060f1SDimitry Andric   assert(PtrA && PtrB && "Expected non-nullptr pointers.");
1532fe6060f1SDimitry Andric 
1533fe6060f1SDimitry Andric   // Make sure that A and B are different pointers.
1534fe6060f1SDimitry Andric   if (PtrA == PtrB)
1535fe6060f1SDimitry Andric     return 0;
1536fe6060f1SDimitry Andric 
1537fe6060f1SDimitry Andric   // Make sure that the element types are the same if required.
1538fe6060f1SDimitry Andric   if (CheckType && ElemTyA != ElemTyB)
1539bdd1243dSDimitry Andric     return std::nullopt;
1540fe6060f1SDimitry Andric 
1541fe6060f1SDimitry Andric   unsigned ASA = PtrA->getType()->getPointerAddressSpace();
1542fe6060f1SDimitry Andric   unsigned ASB = PtrB->getType()->getPointerAddressSpace();
1543fe6060f1SDimitry Andric 
1544fe6060f1SDimitry Andric   // Check that the address spaces match.
1545fe6060f1SDimitry Andric   if (ASA != ASB)
1546bdd1243dSDimitry Andric     return std::nullopt;
1547fe6060f1SDimitry Andric   unsigned IdxWidth = DL.getIndexSizeInBits(ASA);
1548fe6060f1SDimitry Andric 
1549fe6060f1SDimitry Andric   APInt OffsetA(IdxWidth, 0), OffsetB(IdxWidth, 0);
1550fe6060f1SDimitry Andric   Value *PtrA1 = PtrA->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetA);
1551fe6060f1SDimitry Andric   Value *PtrB1 = PtrB->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetB);
1552fe6060f1SDimitry Andric 
1553fe6060f1SDimitry Andric   int Val;
1554fe6060f1SDimitry Andric   if (PtrA1 == PtrB1) {
1555fe6060f1SDimitry Andric     // Retrieve the address space again as pointer stripping now tracks through
1556fe6060f1SDimitry Andric     // `addrspacecast`.
1557fe6060f1SDimitry Andric     ASA = cast<PointerType>(PtrA1->getType())->getAddressSpace();
1558fe6060f1SDimitry Andric     ASB = cast<PointerType>(PtrB1->getType())->getAddressSpace();
1559fe6060f1SDimitry Andric     // Check that the address spaces match and that the pointers are valid.
1560fe6060f1SDimitry Andric     if (ASA != ASB)
1561bdd1243dSDimitry Andric       return std::nullopt;
1562fe6060f1SDimitry Andric 
1563fe6060f1SDimitry Andric     IdxWidth = DL.getIndexSizeInBits(ASA);
1564fe6060f1SDimitry Andric     OffsetA = OffsetA.sextOrTrunc(IdxWidth);
1565fe6060f1SDimitry Andric     OffsetB = OffsetB.sextOrTrunc(IdxWidth);
1566fe6060f1SDimitry Andric 
1567fe6060f1SDimitry Andric     OffsetB -= OffsetA;
1568fe6060f1SDimitry Andric     Val = OffsetB.getSExtValue();
1569fe6060f1SDimitry Andric   } else {
1570fe6060f1SDimitry Andric     // Otherwise compute the distance with SCEV between the base pointers.
1571fe6060f1SDimitry Andric     const SCEV *PtrSCEVA = SE.getSCEV(PtrA);
1572fe6060f1SDimitry Andric     const SCEV *PtrSCEVB = SE.getSCEV(PtrB);
1573fe6060f1SDimitry Andric     const auto *Diff =
1574fe6060f1SDimitry Andric         dyn_cast<SCEVConstant>(SE.getMinusSCEV(PtrSCEVB, PtrSCEVA));
1575fe6060f1SDimitry Andric     if (!Diff)
1576bdd1243dSDimitry Andric       return std::nullopt;
1577fe6060f1SDimitry Andric     Val = Diff->getAPInt().getSExtValue();
1578fe6060f1SDimitry Andric   }
1579fe6060f1SDimitry Andric   int Size = DL.getTypeStoreSize(ElemTyA);
1580fe6060f1SDimitry Andric   int Dist = Val / Size;
1581fe6060f1SDimitry Andric 
1582fe6060f1SDimitry Andric   // Ensure that the calculated distance matches the type-based one after all
1583fe6060f1SDimitry Andric   // the bitcasts removal in the provided pointers.
1584fe6060f1SDimitry Andric   if (!StrictCheck || Dist * Size == Val)
1585fe6060f1SDimitry Andric     return Dist;
1586bdd1243dSDimitry Andric   return std::nullopt;
1587fe6060f1SDimitry Andric }
1588fe6060f1SDimitry Andric 
1589fe6060f1SDimitry Andric bool llvm::sortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy,
1590fe6060f1SDimitry Andric                            const DataLayout &DL, ScalarEvolution &SE,
15910b57cec5SDimitry Andric                            SmallVectorImpl<unsigned> &SortedIndices) {
15920b57cec5SDimitry Andric   assert(llvm::all_of(
15930b57cec5SDimitry Andric              VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&
15940b57cec5SDimitry Andric          "Expected list of pointer operands.");
15950b57cec5SDimitry Andric   // Walk over the pointers, and map each of them to an offset relative to
15960b57cec5SDimitry Andric   // first pointer in the array.
15970b57cec5SDimitry Andric   Value *Ptr0 = VL[0];
15980b57cec5SDimitry Andric 
1599fe6060f1SDimitry Andric   using DistOrdPair = std::pair<int64_t, int>;
1600972a253aSDimitry Andric   auto Compare = llvm::less_first();
1601fe6060f1SDimitry Andric   std::set<DistOrdPair, decltype(Compare)> Offsets(Compare);
1602fe6060f1SDimitry Andric   Offsets.emplace(0, 0);
1603fe6060f1SDimitry Andric   int Cnt = 1;
1604fe6060f1SDimitry Andric   bool IsConsecutive = true;
1605fe6060f1SDimitry Andric   for (auto *Ptr : VL.drop_front()) {
1606bdd1243dSDimitry Andric     std::optional<int> Diff = getPointersDiff(ElemTy, Ptr0, ElemTy, Ptr, DL, SE,
1607fe6060f1SDimitry Andric                                               /*StrictCheck=*/true);
16080b57cec5SDimitry Andric     if (!Diff)
16090b57cec5SDimitry Andric       return false;
16100b57cec5SDimitry Andric 
16110b57cec5SDimitry Andric     // Check if the pointer with the same offset is found.
1612fe6060f1SDimitry Andric     int64_t Offset = *Diff;
1613fe6060f1SDimitry Andric     auto Res = Offsets.emplace(Offset, Cnt);
1614fe6060f1SDimitry Andric     if (!Res.second)
16150b57cec5SDimitry Andric       return false;
1616fe6060f1SDimitry Andric     // Consecutive order if the inserted element is the last one.
1617fe6060f1SDimitry Andric     IsConsecutive = IsConsecutive && std::next(Res.first) == Offsets.end();
1618fe6060f1SDimitry Andric     ++Cnt;
16190b57cec5SDimitry Andric   }
16200b57cec5SDimitry Andric   SortedIndices.clear();
1621fe6060f1SDimitry Andric   if (!IsConsecutive) {
1622fe6060f1SDimitry Andric     // Fill SortedIndices array only if it is non-consecutive.
16230b57cec5SDimitry Andric     SortedIndices.resize(VL.size());
1624fe6060f1SDimitry Andric     Cnt = 0;
1625fe6060f1SDimitry Andric     for (const std::pair<int64_t, int> &Pair : Offsets) {
1626fe6060f1SDimitry Andric       SortedIndices[Cnt] = Pair.second;
1627fe6060f1SDimitry Andric       ++Cnt;
16280b57cec5SDimitry Andric     }
1629fe6060f1SDimitry Andric   }
1630fe6060f1SDimitry Andric   return true;
16310b57cec5SDimitry Andric }
16320b57cec5SDimitry Andric 
16330b57cec5SDimitry Andric /// Returns true if the memory operations \p A and \p B are consecutive.
16340b57cec5SDimitry Andric bool llvm::isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL,
16350b57cec5SDimitry Andric                                ScalarEvolution &SE, bool CheckType) {
16360b57cec5SDimitry Andric   Value *PtrA = getLoadStorePointerOperand(A);
16370b57cec5SDimitry Andric   Value *PtrB = getLoadStorePointerOperand(B);
1638fe6060f1SDimitry Andric   if (!PtrA || !PtrB)
16390b57cec5SDimitry Andric     return false;
1640fe6060f1SDimitry Andric   Type *ElemTyA = getLoadStoreType(A);
1641fe6060f1SDimitry Andric   Type *ElemTyB = getLoadStoreType(B);
1642bdd1243dSDimitry Andric   std::optional<int> Diff =
1643bdd1243dSDimitry Andric       getPointersDiff(ElemTyA, PtrA, ElemTyB, PtrB, DL, SE,
1644fe6060f1SDimitry Andric                       /*StrictCheck=*/true, CheckType);
1645fe6060f1SDimitry Andric   return Diff && *Diff == 1;
16460b57cec5SDimitry Andric }
16470b57cec5SDimitry Andric 
1648349cc55cSDimitry Andric void MemoryDepChecker::addAccess(StoreInst *SI) {
1649349cc55cSDimitry Andric   visitPointers(SI->getPointerOperand(), *InnermostLoop,
1650349cc55cSDimitry Andric                 [this, SI](Value *Ptr) {
1651349cc55cSDimitry Andric                   Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
1652349cc55cSDimitry Andric                   InstMap.push_back(SI);
1653349cc55cSDimitry Andric                   ++AccessIdx;
1654349cc55cSDimitry Andric                 });
1655349cc55cSDimitry Andric }
1656349cc55cSDimitry Andric 
1657349cc55cSDimitry Andric void MemoryDepChecker::addAccess(LoadInst *LI) {
1658349cc55cSDimitry Andric   visitPointers(LI->getPointerOperand(), *InnermostLoop,
1659349cc55cSDimitry Andric                 [this, LI](Value *Ptr) {
1660349cc55cSDimitry Andric                   Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
1661349cc55cSDimitry Andric                   InstMap.push_back(LI);
1662349cc55cSDimitry Andric                   ++AccessIdx;
1663349cc55cSDimitry Andric                 });
1664349cc55cSDimitry Andric }
1665349cc55cSDimitry Andric 
16660b57cec5SDimitry Andric MemoryDepChecker::VectorizationSafetyStatus
16670b57cec5SDimitry Andric MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
16680b57cec5SDimitry Andric   switch (Type) {
16690b57cec5SDimitry Andric   case NoDep:
16700b57cec5SDimitry Andric   case Forward:
16710b57cec5SDimitry Andric   case BackwardVectorizable:
16720b57cec5SDimitry Andric     return VectorizationSafetyStatus::Safe;
16730b57cec5SDimitry Andric 
16740b57cec5SDimitry Andric   case Unknown:
16750b57cec5SDimitry Andric     return VectorizationSafetyStatus::PossiblySafeWithRtChecks;
16760b57cec5SDimitry Andric   case ForwardButPreventsForwarding:
16770b57cec5SDimitry Andric   case Backward:
16780b57cec5SDimitry Andric   case BackwardVectorizableButPreventsForwarding:
1679c9157d92SDimitry Andric   case IndirectUnsafe:
16800b57cec5SDimitry Andric     return VectorizationSafetyStatus::Unsafe;
16810b57cec5SDimitry Andric   }
16820b57cec5SDimitry Andric   llvm_unreachable("unexpected DepType!");
16830b57cec5SDimitry Andric }
16840b57cec5SDimitry Andric 
16850b57cec5SDimitry Andric bool MemoryDepChecker::Dependence::isBackward() const {
16860b57cec5SDimitry Andric   switch (Type) {
16870b57cec5SDimitry Andric   case NoDep:
16880b57cec5SDimitry Andric   case Forward:
16890b57cec5SDimitry Andric   case ForwardButPreventsForwarding:
16900b57cec5SDimitry Andric   case Unknown:
1691c9157d92SDimitry Andric   case IndirectUnsafe:
16920b57cec5SDimitry Andric     return false;
16930b57cec5SDimitry Andric 
16940b57cec5SDimitry Andric   case BackwardVectorizable:
16950b57cec5SDimitry Andric   case Backward:
16960b57cec5SDimitry Andric   case BackwardVectorizableButPreventsForwarding:
16970b57cec5SDimitry Andric     return true;
16980b57cec5SDimitry Andric   }
16990b57cec5SDimitry Andric   llvm_unreachable("unexpected DepType!");
17000b57cec5SDimitry Andric }
17010b57cec5SDimitry Andric 
17020b57cec5SDimitry Andric bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
17030b57cec5SDimitry Andric   return isBackward() || Type == Unknown;
17040b57cec5SDimitry Andric }
17050b57cec5SDimitry Andric 
17060b57cec5SDimitry Andric bool MemoryDepChecker::Dependence::isForward() const {
17070b57cec5SDimitry Andric   switch (Type) {
17080b57cec5SDimitry Andric   case Forward:
17090b57cec5SDimitry Andric   case ForwardButPreventsForwarding:
17100b57cec5SDimitry Andric     return true;
17110b57cec5SDimitry Andric 
17120b57cec5SDimitry Andric   case NoDep:
17130b57cec5SDimitry Andric   case Unknown:
17140b57cec5SDimitry Andric   case BackwardVectorizable:
17150b57cec5SDimitry Andric   case Backward:
17160b57cec5SDimitry Andric   case BackwardVectorizableButPreventsForwarding:
1717c9157d92SDimitry Andric   case IndirectUnsafe:
17180b57cec5SDimitry Andric     return false;
17190b57cec5SDimitry Andric   }
17200b57cec5SDimitry Andric   llvm_unreachable("unexpected DepType!");
17210b57cec5SDimitry Andric }
17220b57cec5SDimitry Andric 
17230b57cec5SDimitry Andric bool MemoryDepChecker::couldPreventStoreLoadForward(uint64_t Distance,
17240b57cec5SDimitry Andric                                                     uint64_t TypeByteSize) {
17250b57cec5SDimitry Andric   // If loads occur at a distance that is not a multiple of a feasible vector
17260b57cec5SDimitry Andric   // factor store-load forwarding does not take place.
17270b57cec5SDimitry Andric   // Positive dependences might cause troubles because vectorizing them might
17280b57cec5SDimitry Andric   // prevent store-load forwarding making vectorized code run a lot slower.
17290b57cec5SDimitry Andric   //   a[i] = a[i-3] ^ a[i-8];
17300b57cec5SDimitry Andric   //   The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
17310b57cec5SDimitry Andric   //   hence on your typical architecture store-load forwarding does not take
17320b57cec5SDimitry Andric   //   place. Vectorizing in such cases does not make sense.
17330b57cec5SDimitry Andric   // Store-load forwarding distance.
17340b57cec5SDimitry Andric 
17350b57cec5SDimitry Andric   // After this many iterations store-to-load forwarding conflicts should not
17360b57cec5SDimitry Andric   // cause any slowdowns.
17370b57cec5SDimitry Andric   const uint64_t NumItersForStoreLoadThroughMemory = 8 * TypeByteSize;
17380b57cec5SDimitry Andric   // Maximum vector factor.
17390b57cec5SDimitry Andric   uint64_t MaxVFWithoutSLForwardIssues = std::min(
1740c9157d92SDimitry Andric       VectorizerParams::MaxVectorWidth * TypeByteSize, MinDepDistBytes);
17410b57cec5SDimitry Andric 
17420b57cec5SDimitry Andric   // Compute the smallest VF at which the store and load would be misaligned.
17430b57cec5SDimitry Andric   for (uint64_t VF = 2 * TypeByteSize; VF <= MaxVFWithoutSLForwardIssues;
17440b57cec5SDimitry Andric        VF *= 2) {
17450b57cec5SDimitry Andric     // If the number of vector iteration between the store and the load are
17460b57cec5SDimitry Andric     // small we could incur conflicts.
17470b57cec5SDimitry Andric     if (Distance % VF && Distance / VF < NumItersForStoreLoadThroughMemory) {
1748e8d8bef9SDimitry Andric       MaxVFWithoutSLForwardIssues = (VF >> 1);
17490b57cec5SDimitry Andric       break;
17500b57cec5SDimitry Andric     }
17510b57cec5SDimitry Andric   }
17520b57cec5SDimitry Andric 
17530b57cec5SDimitry Andric   if (MaxVFWithoutSLForwardIssues < 2 * TypeByteSize) {
17540b57cec5SDimitry Andric     LLVM_DEBUG(
17550b57cec5SDimitry Andric         dbgs() << "LAA: Distance " << Distance
17560b57cec5SDimitry Andric                << " that could cause a store-load forwarding conflict\n");
17570b57cec5SDimitry Andric     return true;
17580b57cec5SDimitry Andric   }
17590b57cec5SDimitry Andric 
1760c9157d92SDimitry Andric   if (MaxVFWithoutSLForwardIssues < MinDepDistBytes &&
17610b57cec5SDimitry Andric       MaxVFWithoutSLForwardIssues !=
17620b57cec5SDimitry Andric           VectorizerParams::MaxVectorWidth * TypeByteSize)
1763c9157d92SDimitry Andric     MinDepDistBytes = MaxVFWithoutSLForwardIssues;
17640b57cec5SDimitry Andric   return false;
17650b57cec5SDimitry Andric }
17660b57cec5SDimitry Andric 
17670b57cec5SDimitry Andric void MemoryDepChecker::mergeInStatus(VectorizationSafetyStatus S) {
17680b57cec5SDimitry Andric   if (Status < S)
17690b57cec5SDimitry Andric     Status = S;
17700b57cec5SDimitry Andric }
17710b57cec5SDimitry Andric 
1772bdd1243dSDimitry Andric /// Given a dependence-distance \p Dist between two
17730b57cec5SDimitry Andric /// memory accesses, that have the same stride whose absolute value is given
17740b57cec5SDimitry Andric /// in \p Stride, and that have the same type size \p TypeByteSize,
17750b57cec5SDimitry Andric /// in a loop whose takenCount is \p BackedgeTakenCount, check if it is
17760b57cec5SDimitry Andric /// possible to prove statically that the dependence distance is larger
17770b57cec5SDimitry Andric /// than the range that the accesses will travel through the execution of
17780b57cec5SDimitry Andric /// the loop. If so, return true; false otherwise. This is useful for
17790b57cec5SDimitry Andric /// example in loops such as the following (PR31098):
17800b57cec5SDimitry Andric ///     for (i = 0; i < D; ++i) {
17810b57cec5SDimitry Andric ///                = out[i];
17820b57cec5SDimitry Andric ///       out[i+D] =
17830b57cec5SDimitry Andric ///     }
17840b57cec5SDimitry Andric static bool isSafeDependenceDistance(const DataLayout &DL, ScalarEvolution &SE,
17850b57cec5SDimitry Andric                                      const SCEV &BackedgeTakenCount,
17860b57cec5SDimitry Andric                                      const SCEV &Dist, uint64_t Stride,
17870b57cec5SDimitry Andric                                      uint64_t TypeByteSize) {
17880b57cec5SDimitry Andric 
17890b57cec5SDimitry Andric   // If we can prove that
17900b57cec5SDimitry Andric   //      (**) |Dist| > BackedgeTakenCount * Step
17910b57cec5SDimitry Andric   // where Step is the absolute stride of the memory accesses in bytes,
17920b57cec5SDimitry Andric   // then there is no dependence.
17930b57cec5SDimitry Andric   //
17940b57cec5SDimitry Andric   // Rationale:
17950b57cec5SDimitry Andric   // We basically want to check if the absolute distance (|Dist/Step|)
17960b57cec5SDimitry Andric   // is >= the loop iteration count (or > BackedgeTakenCount).
17970b57cec5SDimitry Andric   // This is equivalent to the Strong SIV Test (Practical Dependence Testing,
17980b57cec5SDimitry Andric   // Section 4.2.1); Note, that for vectorization it is sufficient to prove
17990b57cec5SDimitry Andric   // that the dependence distance is >= VF; This is checked elsewhere.
1800bdd1243dSDimitry Andric   // But in some cases we can prune dependence distances early, and
18010b57cec5SDimitry Andric   // even before selecting the VF, and without a runtime test, by comparing
18020b57cec5SDimitry Andric   // the distance against the loop iteration count. Since the vectorized code
18030b57cec5SDimitry Andric   // will be executed only if LoopCount >= VF, proving distance >= LoopCount
18040b57cec5SDimitry Andric   // also guarantees that distance >= VF.
18050b57cec5SDimitry Andric   //
18060b57cec5SDimitry Andric   const uint64_t ByteStride = Stride * TypeByteSize;
18070b57cec5SDimitry Andric   const SCEV *Step = SE.getConstant(BackedgeTakenCount.getType(), ByteStride);
18080b57cec5SDimitry Andric   const SCEV *Product = SE.getMulExpr(&BackedgeTakenCount, Step);
18090b57cec5SDimitry Andric 
18100b57cec5SDimitry Andric   const SCEV *CastedDist = &Dist;
18110b57cec5SDimitry Andric   const SCEV *CastedProduct = Product;
181281ad6265SDimitry Andric   uint64_t DistTypeSizeBits = DL.getTypeSizeInBits(Dist.getType());
181381ad6265SDimitry Andric   uint64_t ProductTypeSizeBits = DL.getTypeSizeInBits(Product->getType());
18140b57cec5SDimitry Andric 
18150b57cec5SDimitry Andric   // The dependence distance can be positive/negative, so we sign extend Dist;
18160b57cec5SDimitry Andric   // The multiplication of the absolute stride in bytes and the
18170b57cec5SDimitry Andric   // backedgeTakenCount is non-negative, so we zero extend Product.
181881ad6265SDimitry Andric   if (DistTypeSizeBits > ProductTypeSizeBits)
18190b57cec5SDimitry Andric     CastedProduct = SE.getZeroExtendExpr(Product, Dist.getType());
18200b57cec5SDimitry Andric   else
18210b57cec5SDimitry Andric     CastedDist = SE.getNoopOrSignExtend(&Dist, Product->getType());
18220b57cec5SDimitry Andric 
18230b57cec5SDimitry Andric   // Is  Dist - (BackedgeTakenCount * Step) > 0 ?
18240b57cec5SDimitry Andric   // (If so, then we have proven (**) because |Dist| >= Dist)
18250b57cec5SDimitry Andric   const SCEV *Minus = SE.getMinusSCEV(CastedDist, CastedProduct);
18260b57cec5SDimitry Andric   if (SE.isKnownPositive(Minus))
18270b57cec5SDimitry Andric     return true;
18280b57cec5SDimitry Andric 
18290b57cec5SDimitry Andric   // Second try: Is  -Dist - (BackedgeTakenCount * Step) > 0 ?
18300b57cec5SDimitry Andric   // (If so, then we have proven (**) because |Dist| >= -1*Dist)
18310b57cec5SDimitry Andric   const SCEV *NegDist = SE.getNegativeSCEV(CastedDist);
18320b57cec5SDimitry Andric   Minus = SE.getMinusSCEV(NegDist, CastedProduct);
18330b57cec5SDimitry Andric   if (SE.isKnownPositive(Minus))
18340b57cec5SDimitry Andric     return true;
18350b57cec5SDimitry Andric 
18360b57cec5SDimitry Andric   return false;
18370b57cec5SDimitry Andric }
18380b57cec5SDimitry Andric 
18390b57cec5SDimitry Andric /// Check the dependence for two accesses with the same stride \p Stride.
18400b57cec5SDimitry Andric /// \p Distance is the positive distance and \p TypeByteSize is type size in
18410b57cec5SDimitry Andric /// bytes.
18420b57cec5SDimitry Andric ///
18430b57cec5SDimitry Andric /// \returns true if they are independent.
18440b57cec5SDimitry Andric static bool areStridedAccessesIndependent(uint64_t Distance, uint64_t Stride,
18450b57cec5SDimitry Andric                                           uint64_t TypeByteSize) {
18460b57cec5SDimitry Andric   assert(Stride > 1 && "The stride must be greater than 1");
18470b57cec5SDimitry Andric   assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
18480b57cec5SDimitry Andric   assert(Distance > 0 && "The distance must be non-zero");
18490b57cec5SDimitry Andric 
18500b57cec5SDimitry Andric   // Skip if the distance is not multiple of type byte size.
18510b57cec5SDimitry Andric   if (Distance % TypeByteSize)
18520b57cec5SDimitry Andric     return false;
18530b57cec5SDimitry Andric 
18540b57cec5SDimitry Andric   uint64_t ScaledDist = Distance / TypeByteSize;
18550b57cec5SDimitry Andric 
18560b57cec5SDimitry Andric   // No dependence if the scaled distance is not multiple of the stride.
18570b57cec5SDimitry Andric   // E.g.
18580b57cec5SDimitry Andric   //      for (i = 0; i < 1024 ; i += 4)
18590b57cec5SDimitry Andric   //        A[i+2] = A[i] + 1;
18600b57cec5SDimitry Andric   //
18610b57cec5SDimitry Andric   // Two accesses in memory (scaled distance is 2, stride is 4):
18620b57cec5SDimitry Andric   //     | A[0] |      |      |      | A[4] |      |      |      |
18630b57cec5SDimitry Andric   //     |      |      | A[2] |      |      |      | A[6] |      |
18640b57cec5SDimitry Andric   //
18650b57cec5SDimitry Andric   // E.g.
18660b57cec5SDimitry Andric   //      for (i = 0; i < 1024 ; i += 3)
18670b57cec5SDimitry Andric   //        A[i+4] = A[i] + 1;
18680b57cec5SDimitry Andric   //
18690b57cec5SDimitry Andric   // Two accesses in memory (scaled distance is 4, stride is 3):
18700b57cec5SDimitry Andric   //     | A[0] |      |      | A[3] |      |      | A[6] |      |      |
18710b57cec5SDimitry Andric   //     |      |      |      |      | A[4] |      |      | A[7] |      |
18720b57cec5SDimitry Andric   return ScaledDist % Stride;
18730b57cec5SDimitry Andric }
18740b57cec5SDimitry Andric 
1875c9157d92SDimitry Andric /// Returns true if any of the underlying objects has a loop varying address,
1876c9157d92SDimitry Andric /// i.e. may change in \p L.
1877c9157d92SDimitry Andric static bool
1878c9157d92SDimitry Andric isLoopVariantIndirectAddress(ArrayRef<const Value *> UnderlyingObjects,
1879c9157d92SDimitry Andric                              ScalarEvolution &SE, const Loop *L) {
1880c9157d92SDimitry Andric   return any_of(UnderlyingObjects, [&SE, L](const Value *UO) {
1881c9157d92SDimitry Andric     return !SE.isLoopInvariant(SE.getSCEV(const_cast<Value *>(UO)), L);
1882c9157d92SDimitry Andric   });
1883c9157d92SDimitry Andric }
18840b57cec5SDimitry Andric 
1885c9157d92SDimitry Andric // Get the dependence distance, stride, type size in whether i is a write for
1886c9157d92SDimitry Andric // the dependence between A and B. Returns a DepType, if we can prove there's
1887c9157d92SDimitry Andric // no dependence or the analysis fails. Outlined to lambda to limit he scope
1888c9157d92SDimitry Andric // of various temporary variables, like A/BPtr, StrideA/BPtr and others.
1889c9157d92SDimitry Andric // Returns either the dependence result, if it could already be determined, or a
1890c9157d92SDimitry Andric // tuple with (Distance, Stride, TypeSize, AIsWrite, BIsWrite).
1891c9157d92SDimitry Andric static std::variant<MemoryDepChecker::Dependence::DepType,
1892c9157d92SDimitry Andric                     std::tuple<const SCEV *, uint64_t, uint64_t, bool, bool>>
1893c9157d92SDimitry Andric getDependenceDistanceStrideAndSize(
1894c9157d92SDimitry Andric     const AccessAnalysis::MemAccessInfo &A, Instruction *AInst,
1895c9157d92SDimitry Andric     const AccessAnalysis::MemAccessInfo &B, Instruction *BInst,
1896c9157d92SDimitry Andric     const DenseMap<Value *, const SCEV *> &Strides,
1897c9157d92SDimitry Andric     const DenseMap<Value *, SmallVector<const Value *, 16>> &UnderlyingObjects,
1898c9157d92SDimitry Andric     PredicatedScalarEvolution &PSE, const Loop *InnermostLoop) {
1899c9157d92SDimitry Andric   auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
1900c9157d92SDimitry Andric   auto &SE = *PSE.getSE();
1901bdd1243dSDimitry Andric   auto [APtr, AIsWrite] = A;
1902bdd1243dSDimitry Andric   auto [BPtr, BIsWrite] = B;
19030b57cec5SDimitry Andric 
19040b57cec5SDimitry Andric   // Two reads are independent.
19050b57cec5SDimitry Andric   if (!AIsWrite && !BIsWrite)
1906c9157d92SDimitry Andric     return MemoryDepChecker::Dependence::NoDep;
1907c9157d92SDimitry Andric 
1908c9157d92SDimitry Andric   Type *ATy = getLoadStoreType(AInst);
1909c9157d92SDimitry Andric   Type *BTy = getLoadStoreType(BInst);
19100b57cec5SDimitry Andric 
19110b57cec5SDimitry Andric   // We cannot check pointers in different address spaces.
19120b57cec5SDimitry Andric   if (APtr->getType()->getPointerAddressSpace() !=
19130b57cec5SDimitry Andric       BPtr->getType()->getPointerAddressSpace())
1914c9157d92SDimitry Andric     return MemoryDepChecker::Dependence::Unknown;
19150b57cec5SDimitry Andric 
1916349cc55cSDimitry Andric   int64_t StrideAPtr =
1917bdd1243dSDimitry Andric       getPtrStride(PSE, ATy, APtr, InnermostLoop, Strides, true).value_or(0);
1918349cc55cSDimitry Andric   int64_t StrideBPtr =
1919bdd1243dSDimitry Andric       getPtrStride(PSE, BTy, BPtr, InnermostLoop, Strides, true).value_or(0);
19200b57cec5SDimitry Andric 
19210b57cec5SDimitry Andric   const SCEV *Src = PSE.getSCEV(APtr);
19220b57cec5SDimitry Andric   const SCEV *Sink = PSE.getSCEV(BPtr);
19230b57cec5SDimitry Andric 
19240b57cec5SDimitry Andric   // If the induction step is negative we have to invert source and sink of the
1925c9157d92SDimitry Andric   // dependence when measuring the distance between them. We should not swap
1926c9157d92SDimitry Andric   // AIsWrite with BIsWrite, as their uses expect them in program order.
19270b57cec5SDimitry Andric   if (StrideAPtr < 0) {
19280b57cec5SDimitry Andric     std::swap(Src, Sink);
1929c9157d92SDimitry Andric     std::swap(AInst, BInst);
19300b57cec5SDimitry Andric   }
19310b57cec5SDimitry Andric 
1932bdd1243dSDimitry Andric   const SCEV *Dist = SE.getMinusSCEV(Sink, Src);
19330b57cec5SDimitry Andric 
19340b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
19350b57cec5SDimitry Andric                     << "(Induction step: " << StrideAPtr << ")\n");
1936c9157d92SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Distance for " << *AInst << " to " << *BInst
1937c9157d92SDimitry Andric                     << ": " << *Dist << "\n");
1938c9157d92SDimitry Andric 
1939c9157d92SDimitry Andric   // Needs accesses where the addresses of the accessed underlying objects do
1940c9157d92SDimitry Andric   // not change within the loop.
1941c9157d92SDimitry Andric   if (isLoopVariantIndirectAddress(UnderlyingObjects.find(APtr)->second, SE,
1942c9157d92SDimitry Andric                                    InnermostLoop) ||
1943c9157d92SDimitry Andric       isLoopVariantIndirectAddress(UnderlyingObjects.find(BPtr)->second, SE,
1944c9157d92SDimitry Andric                                    InnermostLoop))
1945c9157d92SDimitry Andric     return MemoryDepChecker::Dependence::IndirectUnsafe;
19460b57cec5SDimitry Andric 
19470b57cec5SDimitry Andric   // Need accesses with constant stride. We don't want to vectorize
1948c9157d92SDimitry Andric   // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap
1949c9157d92SDimitry Andric   // in the address space.
19500b57cec5SDimitry Andric   if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr) {
19510b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Pointer access with non-constant stride\n");
1952c9157d92SDimitry Andric     return MemoryDepChecker::Dependence::Unknown;
19530b57cec5SDimitry Andric   }
19540b57cec5SDimitry Andric 
19550b57cec5SDimitry Andric   uint64_t TypeByteSize = DL.getTypeAllocSize(ATy);
19560eae32dcSDimitry Andric   bool HasSameSize =
19570eae32dcSDimitry Andric       DL.getTypeStoreSizeInBits(ATy) == DL.getTypeStoreSizeInBits(BTy);
1958c9157d92SDimitry Andric   if (!HasSameSize)
1959c9157d92SDimitry Andric     TypeByteSize = 0;
19600b57cec5SDimitry Andric   uint64_t Stride = std::abs(StrideAPtr);
1961c9157d92SDimitry Andric   return std::make_tuple(Dist, Stride, TypeByteSize, AIsWrite, BIsWrite);
1962c9157d92SDimitry Andric }
1963bdd1243dSDimitry Andric 
1964c9157d92SDimitry Andric MemoryDepChecker::Dependence::DepType MemoryDepChecker::isDependent(
1965c9157d92SDimitry Andric     const MemAccessInfo &A, unsigned AIdx, const MemAccessInfo &B,
1966c9157d92SDimitry Andric     unsigned BIdx, const DenseMap<Value *, const SCEV *> &Strides,
1967c9157d92SDimitry Andric     const DenseMap<Value *, SmallVector<const Value *, 16>>
1968c9157d92SDimitry Andric         &UnderlyingObjects) {
1969c9157d92SDimitry Andric   assert(AIdx < BIdx && "Must pass arguments in program order");
1970c9157d92SDimitry Andric 
1971c9157d92SDimitry Andric   // Get the dependence distance, stride, type size and what access writes for
1972c9157d92SDimitry Andric   // the dependence between A and B.
1973c9157d92SDimitry Andric   auto Res = getDependenceDistanceStrideAndSize(
1974c9157d92SDimitry Andric       A, InstMap[AIdx], B, InstMap[BIdx], Strides, UnderlyingObjects, PSE,
1975c9157d92SDimitry Andric       InnermostLoop);
1976c9157d92SDimitry Andric   if (std::holds_alternative<Dependence::DepType>(Res))
1977c9157d92SDimitry Andric     return std::get<Dependence::DepType>(Res);
1978c9157d92SDimitry Andric 
1979c9157d92SDimitry Andric   const auto &[Dist, Stride, TypeByteSize, AIsWrite, BIsWrite] =
1980c9157d92SDimitry Andric       std::get<std::tuple<const SCEV *, uint64_t, uint64_t, bool, bool>>(Res);
1981c9157d92SDimitry Andric   bool HasSameSize = TypeByteSize > 0;
1982c9157d92SDimitry Andric 
1983c9157d92SDimitry Andric   ScalarEvolution &SE = *PSE.getSE();
1984c9157d92SDimitry Andric   auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
19850eae32dcSDimitry Andric   if (!isa<SCEVCouldNotCompute>(Dist) && HasSameSize &&
1986bdd1243dSDimitry Andric       isSafeDependenceDistance(DL, SE, *(PSE.getBackedgeTakenCount()), *Dist,
1987bdd1243dSDimitry Andric                                Stride, TypeByteSize))
19880b57cec5SDimitry Andric     return Dependence::NoDep;
19890b57cec5SDimitry Andric 
1990bdd1243dSDimitry Andric   const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
1991bdd1243dSDimitry Andric   if (!C) {
19920b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
19930b57cec5SDimitry Andric     FoundNonConstantDistanceDependence = true;
19940b57cec5SDimitry Andric     return Dependence::Unknown;
19950b57cec5SDimitry Andric   }
19960b57cec5SDimitry Andric 
19970b57cec5SDimitry Andric   const APInt &Val = C->getAPInt();
19980b57cec5SDimitry Andric   int64_t Distance = Val.getSExtValue();
19990b57cec5SDimitry Andric 
20000b57cec5SDimitry Andric   // Attempt to prove strided accesses independent.
20010eae32dcSDimitry Andric   if (std::abs(Distance) > 0 && Stride > 1 && HasSameSize &&
20020b57cec5SDimitry Andric       areStridedAccessesIndependent(std::abs(Distance), Stride, TypeByteSize)) {
20030b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
20040b57cec5SDimitry Andric     return Dependence::NoDep;
20050b57cec5SDimitry Andric   }
20060b57cec5SDimitry Andric 
20070b57cec5SDimitry Andric   // Negative distances are not plausible dependencies.
20080b57cec5SDimitry Andric   if (Val.isNegative()) {
20090b57cec5SDimitry Andric     bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
2010c9157d92SDimitry Andric     // There is no need to update MaxSafeVectorWidthInBits after call to
2011c9157d92SDimitry Andric     // couldPreventStoreLoadForward, even if it changed MinDepDistBytes,
2012c9157d92SDimitry Andric     // since a forward dependency will allow vectorization using any width.
20130b57cec5SDimitry Andric     if (IsTrueDataDependence && EnableForwardingConflictDetection &&
2014c9157d92SDimitry Andric         (!HasSameSize || couldPreventStoreLoadForward(Val.abs().getZExtValue(),
2015c9157d92SDimitry Andric                                                       TypeByteSize))) {
20160b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "LAA: Forward but may prevent st->ld forwarding\n");
20170b57cec5SDimitry Andric       return Dependence::ForwardButPreventsForwarding;
20180b57cec5SDimitry Andric     }
20190b57cec5SDimitry Andric 
20200b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Dependence is negative\n");
20210b57cec5SDimitry Andric     return Dependence::Forward;
20220b57cec5SDimitry Andric   }
20230b57cec5SDimitry Andric 
20240b57cec5SDimitry Andric   // Write to the same location with the same size.
20250b57cec5SDimitry Andric   if (Val == 0) {
20260eae32dcSDimitry Andric     if (HasSameSize)
20270b57cec5SDimitry Andric       return Dependence::Forward;
20280b57cec5SDimitry Andric     LLVM_DEBUG(
20290eae32dcSDimitry Andric         dbgs() << "LAA: Zero dependence difference but different type sizes\n");
20300b57cec5SDimitry Andric     return Dependence::Unknown;
20310b57cec5SDimitry Andric   }
20320b57cec5SDimitry Andric 
20330b57cec5SDimitry Andric   assert(Val.isStrictlyPositive() && "Expect a positive value");
20340b57cec5SDimitry Andric 
20350eae32dcSDimitry Andric   if (!HasSameSize) {
20360eae32dcSDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: ReadWrite-Write positive dependency with "
20370eae32dcSDimitry Andric                          "different type sizes\n");
20380b57cec5SDimitry Andric     return Dependence::Unknown;
20390b57cec5SDimitry Andric   }
20400b57cec5SDimitry Andric 
20410b57cec5SDimitry Andric   // Bail out early if passed-in parameters make vectorization not feasible.
20420b57cec5SDimitry Andric   unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
20430b57cec5SDimitry Andric                            VectorizerParams::VectorizationFactor : 1);
20440b57cec5SDimitry Andric   unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
20450b57cec5SDimitry Andric                            VectorizerParams::VectorizationInterleave : 1);
20460b57cec5SDimitry Andric   // The minimum number of iterations for a vectorized/unrolled version.
20470b57cec5SDimitry Andric   unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
20480b57cec5SDimitry Andric 
20490b57cec5SDimitry Andric   // It's not vectorizable if the distance is smaller than the minimum distance
20500b57cec5SDimitry Andric   // needed for a vectroized/unrolled version. Vectorizing one iteration in
20510b57cec5SDimitry Andric   // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
20520b57cec5SDimitry Andric   // TypeByteSize (No need to plus the last gap distance).
20530b57cec5SDimitry Andric   //
20540b57cec5SDimitry Andric   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
20550b57cec5SDimitry Andric   //      foo(int *A) {
20560b57cec5SDimitry Andric   //        int *B = (int *)((char *)A + 14);
20570b57cec5SDimitry Andric   //        for (i = 0 ; i < 1024 ; i += 2)
20580b57cec5SDimitry Andric   //          B[i] = A[i] + 1;
20590b57cec5SDimitry Andric   //      }
20600b57cec5SDimitry Andric   //
20610b57cec5SDimitry Andric   // Two accesses in memory (stride is 2):
20620b57cec5SDimitry Andric   //     | A[0] |      | A[2] |      | A[4] |      | A[6] |      |
20630b57cec5SDimitry Andric   //                              | B[0] |      | B[2] |      | B[4] |
20640b57cec5SDimitry Andric   //
20650b57cec5SDimitry Andric   // Distance needs for vectorizing iterations except the last iteration:
20660b57cec5SDimitry Andric   // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
20670b57cec5SDimitry Andric   // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
20680b57cec5SDimitry Andric   //
20690b57cec5SDimitry Andric   // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
20700b57cec5SDimitry Andric   // 12, which is less than distance.
20710b57cec5SDimitry Andric   //
20720b57cec5SDimitry Andric   // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
20730b57cec5SDimitry Andric   // the minimum distance needed is 28, which is greater than distance. It is
20740b57cec5SDimitry Andric   // not safe to do vectorization.
20750b57cec5SDimitry Andric   uint64_t MinDistanceNeeded =
20760b57cec5SDimitry Andric       TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
20770b57cec5SDimitry Andric   if (MinDistanceNeeded > static_cast<uint64_t>(Distance)) {
20780b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Failure because of positive distance "
20790b57cec5SDimitry Andric                       << Distance << '\n');
20800b57cec5SDimitry Andric     return Dependence::Backward;
20810b57cec5SDimitry Andric   }
20820b57cec5SDimitry Andric 
2083c9157d92SDimitry Andric   // Unsafe if the minimum distance needed is greater than smallest dependence
2084c9157d92SDimitry Andric   // distance distance.
2085c9157d92SDimitry Andric   if (MinDistanceNeeded > MinDepDistBytes) {
20860b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Failure because it needs at least "
2087bdd1243dSDimitry Andric                       << MinDistanceNeeded << " size in bytes\n");
20880b57cec5SDimitry Andric     return Dependence::Backward;
20890b57cec5SDimitry Andric   }
20900b57cec5SDimitry Andric 
20910b57cec5SDimitry Andric   // Positive distance bigger than max vectorization factor.
20920b57cec5SDimitry Andric   // FIXME: Should use max factor instead of max distance in bytes, which could
20930b57cec5SDimitry Andric   // not handle different types.
20940b57cec5SDimitry Andric   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
20950b57cec5SDimitry Andric   //      void foo (int *A, char *B) {
20960b57cec5SDimitry Andric   //        for (unsigned i = 0; i < 1024; i++) {
20970b57cec5SDimitry Andric   //          A[i+2] = A[i] + 1;
20980b57cec5SDimitry Andric   //          B[i+2] = B[i] + 1;
20990b57cec5SDimitry Andric   //        }
21000b57cec5SDimitry Andric   //      }
21010b57cec5SDimitry Andric   //
21020b57cec5SDimitry Andric   // This case is currently unsafe according to the max safe distance. If we
21030b57cec5SDimitry Andric   // analyze the two accesses on array B, the max safe dependence distance
21040b57cec5SDimitry Andric   // is 2. Then we analyze the accesses on array A, the minimum distance needed
21050b57cec5SDimitry Andric   // is 8, which is less than 2 and forbidden vectorization, But actually
21060b57cec5SDimitry Andric   // both A and B could be vectorized by 2 iterations.
2107c9157d92SDimitry Andric   MinDepDistBytes =
2108c9157d92SDimitry Andric       std::min(static_cast<uint64_t>(Distance), MinDepDistBytes);
21090b57cec5SDimitry Andric 
21100b57cec5SDimitry Andric   bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
2111c9157d92SDimitry Andric   uint64_t MinDepDistBytesOld = MinDepDistBytes;
21120b57cec5SDimitry Andric   if (IsTrueDataDependence && EnableForwardingConflictDetection &&
2113c9157d92SDimitry Andric       couldPreventStoreLoadForward(Distance, TypeByteSize)) {
2114c9157d92SDimitry Andric     // Sanity check that we didn't update MinDepDistBytes when calling
2115c9157d92SDimitry Andric     // couldPreventStoreLoadForward
2116c9157d92SDimitry Andric     assert(MinDepDistBytes == MinDepDistBytesOld &&
2117c9157d92SDimitry Andric            "An update to MinDepDistBytes requires an update to "
2118c9157d92SDimitry Andric            "MaxSafeVectorWidthInBits");
2119c9157d92SDimitry Andric     (void)MinDepDistBytesOld;
21200b57cec5SDimitry Andric     return Dependence::BackwardVectorizableButPreventsForwarding;
2121c9157d92SDimitry Andric   }
21220b57cec5SDimitry Andric 
2123c9157d92SDimitry Andric   // An update to MinDepDistBytes requires an update to MaxSafeVectorWidthInBits
2124c9157d92SDimitry Andric   // since there is a backwards dependency.
2125c9157d92SDimitry Andric   uint64_t MaxVF = MinDepDistBytes / (TypeByteSize * Stride);
21260b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
21270b57cec5SDimitry Andric                     << " with max VF = " << MaxVF << '\n');
21280b57cec5SDimitry Andric   uint64_t MaxVFInBits = MaxVF * TypeByteSize * 8;
2129e8d8bef9SDimitry Andric   MaxSafeVectorWidthInBits = std::min(MaxSafeVectorWidthInBits, MaxVFInBits);
21300b57cec5SDimitry Andric   return Dependence::BackwardVectorizable;
21310b57cec5SDimitry Andric }
21320b57cec5SDimitry Andric 
2133c9157d92SDimitry Andric bool MemoryDepChecker::areDepsSafe(
2134c9157d92SDimitry Andric     DepCandidates &AccessSets, MemAccessInfoList &CheckDeps,
2135c9157d92SDimitry Andric     const DenseMap<Value *, const SCEV *> &Strides,
2136c9157d92SDimitry Andric     const DenseMap<Value *, SmallVector<const Value *, 16>>
2137c9157d92SDimitry Andric         &UnderlyingObjects) {
21380b57cec5SDimitry Andric 
2139c9157d92SDimitry Andric   MinDepDistBytes = -1;
21400b57cec5SDimitry Andric   SmallPtrSet<MemAccessInfo, 8> Visited;
21410b57cec5SDimitry Andric   for (MemAccessInfo CurAccess : CheckDeps) {
21420b57cec5SDimitry Andric     if (Visited.count(CurAccess))
21430b57cec5SDimitry Andric       continue;
21440b57cec5SDimitry Andric 
21450b57cec5SDimitry Andric     // Get the relevant memory access set.
21460b57cec5SDimitry Andric     EquivalenceClasses<MemAccessInfo>::iterator I =
21470b57cec5SDimitry Andric       AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
21480b57cec5SDimitry Andric 
21490b57cec5SDimitry Andric     // Check accesses within this set.
21500b57cec5SDimitry Andric     EquivalenceClasses<MemAccessInfo>::member_iterator AI =
21510b57cec5SDimitry Andric         AccessSets.member_begin(I);
21520b57cec5SDimitry Andric     EquivalenceClasses<MemAccessInfo>::member_iterator AE =
21530b57cec5SDimitry Andric         AccessSets.member_end();
21540b57cec5SDimitry Andric 
21550b57cec5SDimitry Andric     // Check every access pair.
21560b57cec5SDimitry Andric     while (AI != AE) {
21570b57cec5SDimitry Andric       Visited.insert(*AI);
21588bcb0991SDimitry Andric       bool AIIsWrite = AI->getInt();
21598bcb0991SDimitry Andric       // Check loads only against next equivalent class, but stores also against
21608bcb0991SDimitry Andric       // other stores in the same equivalence class - to the same address.
21618bcb0991SDimitry Andric       EquivalenceClasses<MemAccessInfo>::member_iterator OI =
21628bcb0991SDimitry Andric           (AIIsWrite ? AI : std::next(AI));
21630b57cec5SDimitry Andric       while (OI != AE) {
21640b57cec5SDimitry Andric         // Check every accessing instruction pair in program order.
21650b57cec5SDimitry Andric         for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
21660b57cec5SDimitry Andric              I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
21678bcb0991SDimitry Andric           // Scan all accesses of another equivalence class, but only the next
21688bcb0991SDimitry Andric           // accesses of the same equivalent class.
21698bcb0991SDimitry Andric           for (std::vector<unsigned>::iterator
21708bcb0991SDimitry Andric                    I2 = (OI == AI ? std::next(I1) : Accesses[*OI].begin()),
21718bcb0991SDimitry Andric                    I2E = (OI == AI ? I1E : Accesses[*OI].end());
21728bcb0991SDimitry Andric                I2 != I2E; ++I2) {
21730b57cec5SDimitry Andric             auto A = std::make_pair(&*AI, *I1);
21740b57cec5SDimitry Andric             auto B = std::make_pair(&*OI, *I2);
21750b57cec5SDimitry Andric 
21760b57cec5SDimitry Andric             assert(*I1 != *I2);
21770b57cec5SDimitry Andric             if (*I1 > *I2)
21780b57cec5SDimitry Andric               std::swap(A, B);
21790b57cec5SDimitry Andric 
21800b57cec5SDimitry Andric             Dependence::DepType Type =
2181c9157d92SDimitry Andric                 isDependent(*A.first, A.second, *B.first, B.second, Strides,
2182c9157d92SDimitry Andric                             UnderlyingObjects);
21830b57cec5SDimitry Andric             mergeInStatus(Dependence::isSafeForVectorization(Type));
21840b57cec5SDimitry Andric 
21850b57cec5SDimitry Andric             // Gather dependences unless we accumulated MaxDependences
21860b57cec5SDimitry Andric             // dependences.  In that case return as soon as we find the first
21870b57cec5SDimitry Andric             // unsafe dependence.  This puts a limit on this quadratic
21880b57cec5SDimitry Andric             // algorithm.
21890b57cec5SDimitry Andric             if (RecordDependences) {
21900b57cec5SDimitry Andric               if (Type != Dependence::NoDep)
21910b57cec5SDimitry Andric                 Dependences.push_back(Dependence(A.second, B.second, Type));
21920b57cec5SDimitry Andric 
21930b57cec5SDimitry Andric               if (Dependences.size() >= MaxDependences) {
21940b57cec5SDimitry Andric                 RecordDependences = false;
21950b57cec5SDimitry Andric                 Dependences.clear();
21960b57cec5SDimitry Andric                 LLVM_DEBUG(dbgs()
21970b57cec5SDimitry Andric                            << "Too many dependences, stopped recording\n");
21980b57cec5SDimitry Andric               }
21990b57cec5SDimitry Andric             }
22000b57cec5SDimitry Andric             if (!RecordDependences && !isSafeForVectorization())
22010b57cec5SDimitry Andric               return false;
22020b57cec5SDimitry Andric           }
22030b57cec5SDimitry Andric         ++OI;
22040b57cec5SDimitry Andric       }
22050b57cec5SDimitry Andric       AI++;
22060b57cec5SDimitry Andric     }
22070b57cec5SDimitry Andric   }
22080b57cec5SDimitry Andric 
22090b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Total Dependences: " << Dependences.size() << "\n");
22100b57cec5SDimitry Andric   return isSafeForVectorization();
22110b57cec5SDimitry Andric }
22120b57cec5SDimitry Andric 
22130b57cec5SDimitry Andric SmallVector<Instruction *, 4>
22140b57cec5SDimitry Andric MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
22150b57cec5SDimitry Andric   MemAccessInfo Access(Ptr, isWrite);
22160b57cec5SDimitry Andric   auto &IndexVector = Accesses.find(Access)->second;
22170b57cec5SDimitry Andric 
22180b57cec5SDimitry Andric   SmallVector<Instruction *, 4> Insts;
22190b57cec5SDimitry Andric   transform(IndexVector,
22200b57cec5SDimitry Andric                  std::back_inserter(Insts),
22210b57cec5SDimitry Andric                  [&](unsigned Idx) { return this->InstMap[Idx]; });
22220b57cec5SDimitry Andric   return Insts;
22230b57cec5SDimitry Andric }
22240b57cec5SDimitry Andric 
22250b57cec5SDimitry Andric const char *MemoryDepChecker::Dependence::DepName[] = {
2226c9157d92SDimitry Andric     "NoDep",
2227c9157d92SDimitry Andric     "Unknown",
2228c9157d92SDimitry Andric     "IndidrectUnsafe",
2229c9157d92SDimitry Andric     "Forward",
2230c9157d92SDimitry Andric     "ForwardButPreventsForwarding",
2231c9157d92SDimitry Andric     "Backward",
2232c9157d92SDimitry Andric     "BackwardVectorizable",
2233c9157d92SDimitry Andric     "BackwardVectorizableButPreventsForwarding"};
22340b57cec5SDimitry Andric 
22350b57cec5SDimitry Andric void MemoryDepChecker::Dependence::print(
22360b57cec5SDimitry Andric     raw_ostream &OS, unsigned Depth,
22370b57cec5SDimitry Andric     const SmallVectorImpl<Instruction *> &Instrs) const {
22380b57cec5SDimitry Andric   OS.indent(Depth) << DepName[Type] << ":\n";
22390b57cec5SDimitry Andric   OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
22400b57cec5SDimitry Andric   OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
22410b57cec5SDimitry Andric }
22420b57cec5SDimitry Andric 
22430b57cec5SDimitry Andric bool LoopAccessInfo::canAnalyzeLoop() {
22440b57cec5SDimitry Andric   // We need to have a loop header.
22450b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Found a loop in "
22460b57cec5SDimitry Andric                     << TheLoop->getHeader()->getParent()->getName() << ": "
22470b57cec5SDimitry Andric                     << TheLoop->getHeader()->getName() << '\n');
22480b57cec5SDimitry Andric 
22490b57cec5SDimitry Andric   // We can only analyze innermost loops.
2250e8d8bef9SDimitry Andric   if (!TheLoop->isInnermost()) {
22510b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
22520b57cec5SDimitry Andric     recordAnalysis("NotInnerMostLoop") << "loop is not the innermost loop";
22530b57cec5SDimitry Andric     return false;
22540b57cec5SDimitry Andric   }
22550b57cec5SDimitry Andric 
22560b57cec5SDimitry Andric   // We must have a single backedge.
22570b57cec5SDimitry Andric   if (TheLoop->getNumBackEdges() != 1) {
22580b57cec5SDimitry Andric     LLVM_DEBUG(
22590b57cec5SDimitry Andric         dbgs() << "LAA: loop control flow is not understood by analyzer\n");
22600b57cec5SDimitry Andric     recordAnalysis("CFGNotUnderstood")
22610b57cec5SDimitry Andric         << "loop control flow is not understood by analyzer";
22620b57cec5SDimitry Andric     return false;
22630b57cec5SDimitry Andric   }
22640b57cec5SDimitry Andric 
22650b57cec5SDimitry Andric   // ScalarEvolution needs to be able to find the exit count.
22660b57cec5SDimitry Andric   const SCEV *ExitCount = PSE->getBackedgeTakenCount();
2267e8d8bef9SDimitry Andric   if (isa<SCEVCouldNotCompute>(ExitCount)) {
22680b57cec5SDimitry Andric     recordAnalysis("CantComputeNumberOfIterations")
22690b57cec5SDimitry Andric         << "could not determine number of loop iterations";
22700b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
22710b57cec5SDimitry Andric     return false;
22720b57cec5SDimitry Andric   }
22730b57cec5SDimitry Andric 
22740b57cec5SDimitry Andric   return true;
22750b57cec5SDimitry Andric }
22760b57cec5SDimitry Andric 
22775ffd83dbSDimitry Andric void LoopAccessInfo::analyzeLoop(AAResults *AA, LoopInfo *LI,
22780b57cec5SDimitry Andric                                  const TargetLibraryInfo *TLI,
22790b57cec5SDimitry Andric                                  DominatorTree *DT) {
22800b57cec5SDimitry Andric   // Holds the Load and Store instructions.
22810b57cec5SDimitry Andric   SmallVector<LoadInst *, 16> Loads;
22820b57cec5SDimitry Andric   SmallVector<StoreInst *, 16> Stores;
22830b57cec5SDimitry Andric 
22840b57cec5SDimitry Andric   // Holds all the different accesses in the loop.
22850b57cec5SDimitry Andric   unsigned NumReads = 0;
22860b57cec5SDimitry Andric   unsigned NumReadWrites = 0;
22870b57cec5SDimitry Andric 
22880b57cec5SDimitry Andric   bool HasComplexMemInst = false;
22890b57cec5SDimitry Andric 
22900b57cec5SDimitry Andric   // A runtime check is only legal to insert if there are no convergent calls.
22910b57cec5SDimitry Andric   HasConvergentOp = false;
22920b57cec5SDimitry Andric 
22930b57cec5SDimitry Andric   PtrRtChecking->Pointers.clear();
22940b57cec5SDimitry Andric   PtrRtChecking->Need = false;
22950b57cec5SDimitry Andric 
22960b57cec5SDimitry Andric   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
22970b57cec5SDimitry Andric 
22985ffd83dbSDimitry Andric   const bool EnableMemAccessVersioningOfLoop =
22995ffd83dbSDimitry Andric       EnableMemAccessVersioning &&
23005ffd83dbSDimitry Andric       !TheLoop->getHeader()->getParent()->hasOptSize();
23015ffd83dbSDimitry Andric 
2302bdd1243dSDimitry Andric   // Traverse blocks in fixed RPOT order, regardless of their storage in the
2303bdd1243dSDimitry Andric   // loop info, as it may be arbitrary.
2304bdd1243dSDimitry Andric   LoopBlocksRPO RPOT(TheLoop);
2305bdd1243dSDimitry Andric   RPOT.perform(LI);
2306bdd1243dSDimitry Andric   for (BasicBlock *BB : RPOT) {
23070b57cec5SDimitry Andric     // Scan the BB and collect legal loads and stores. Also detect any
23080b57cec5SDimitry Andric     // convergent instructions.
23090b57cec5SDimitry Andric     for (Instruction &I : *BB) {
23100b57cec5SDimitry Andric       if (auto *Call = dyn_cast<CallBase>(&I)) {
23110b57cec5SDimitry Andric         if (Call->isConvergent())
23120b57cec5SDimitry Andric           HasConvergentOp = true;
23130b57cec5SDimitry Andric       }
23140b57cec5SDimitry Andric 
23150b57cec5SDimitry Andric       // With both a non-vectorizable memory instruction and a convergent
23160b57cec5SDimitry Andric       // operation, found in this loop, no reason to continue the search.
23170b57cec5SDimitry Andric       if (HasComplexMemInst && HasConvergentOp) {
23180b57cec5SDimitry Andric         CanVecMem = false;
23190b57cec5SDimitry Andric         return;
23200b57cec5SDimitry Andric       }
23210b57cec5SDimitry Andric 
23220b57cec5SDimitry Andric       // Avoid hitting recordAnalysis multiple times.
23230b57cec5SDimitry Andric       if (HasComplexMemInst)
23240b57cec5SDimitry Andric         continue;
23250b57cec5SDimitry Andric 
23260b57cec5SDimitry Andric       // Many math library functions read the rounding mode. We will only
23270b57cec5SDimitry Andric       // vectorize a loop if it contains known function calls that don't set
23280b57cec5SDimitry Andric       // the flag. Therefore, it is safe to ignore this read from memory.
23290b57cec5SDimitry Andric       auto *Call = dyn_cast<CallInst>(&I);
23300b57cec5SDimitry Andric       if (Call && getVectorIntrinsicIDForCall(Call, TLI))
23310b57cec5SDimitry Andric         continue;
23320b57cec5SDimitry Andric 
2333c9157d92SDimitry Andric       // If this is a load, save it. If this instruction can read from memory
2334c9157d92SDimitry Andric       // but is not a load, then we quit. Notice that we don't handle function
2335c9157d92SDimitry Andric       // calls that read or write.
2336c9157d92SDimitry Andric       if (I.mayReadFromMemory()) {
23370b57cec5SDimitry Andric         // If the function has an explicit vectorized counterpart, we can safely
23380b57cec5SDimitry Andric         // assume that it can be vectorized.
23390b57cec5SDimitry Andric         if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
23405ffd83dbSDimitry Andric             !VFDatabase::getMappings(*Call).empty())
23410b57cec5SDimitry Andric           continue;
23420b57cec5SDimitry Andric 
23430b57cec5SDimitry Andric         auto *Ld = dyn_cast<LoadInst>(&I);
23440b57cec5SDimitry Andric         if (!Ld) {
23450b57cec5SDimitry Andric           recordAnalysis("CantVectorizeInstruction", Ld)
23460b57cec5SDimitry Andric             << "instruction cannot be vectorized";
23470b57cec5SDimitry Andric           HasComplexMemInst = true;
23480b57cec5SDimitry Andric           continue;
23490b57cec5SDimitry Andric         }
23500b57cec5SDimitry Andric         if (!Ld->isSimple() && !IsAnnotatedParallel) {
23510b57cec5SDimitry Andric           recordAnalysis("NonSimpleLoad", Ld)
23520b57cec5SDimitry Andric               << "read with atomic ordering or volatile read";
23530b57cec5SDimitry Andric           LLVM_DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
23540b57cec5SDimitry Andric           HasComplexMemInst = true;
23550b57cec5SDimitry Andric           continue;
23560b57cec5SDimitry Andric         }
23570b57cec5SDimitry Andric         NumLoads++;
23580b57cec5SDimitry Andric         Loads.push_back(Ld);
23590b57cec5SDimitry Andric         DepChecker->addAccess(Ld);
23605ffd83dbSDimitry Andric         if (EnableMemAccessVersioningOfLoop)
23610b57cec5SDimitry Andric           collectStridedAccess(Ld);
23620b57cec5SDimitry Andric         continue;
23630b57cec5SDimitry Andric       }
23640b57cec5SDimitry Andric 
23650b57cec5SDimitry Andric       // Save 'store' instructions. Abort if other instructions write to memory.
23660b57cec5SDimitry Andric       if (I.mayWriteToMemory()) {
23670b57cec5SDimitry Andric         auto *St = dyn_cast<StoreInst>(&I);
23680b57cec5SDimitry Andric         if (!St) {
23690b57cec5SDimitry Andric           recordAnalysis("CantVectorizeInstruction", St)
23700b57cec5SDimitry Andric               << "instruction cannot be vectorized";
23710b57cec5SDimitry Andric           HasComplexMemInst = true;
23720b57cec5SDimitry Andric           continue;
23730b57cec5SDimitry Andric         }
23740b57cec5SDimitry Andric         if (!St->isSimple() && !IsAnnotatedParallel) {
23750b57cec5SDimitry Andric           recordAnalysis("NonSimpleStore", St)
23760b57cec5SDimitry Andric               << "write with atomic ordering or volatile write";
23770b57cec5SDimitry Andric           LLVM_DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
23780b57cec5SDimitry Andric           HasComplexMemInst = true;
23790b57cec5SDimitry Andric           continue;
23800b57cec5SDimitry Andric         }
23810b57cec5SDimitry Andric         NumStores++;
23820b57cec5SDimitry Andric         Stores.push_back(St);
23830b57cec5SDimitry Andric         DepChecker->addAccess(St);
23845ffd83dbSDimitry Andric         if (EnableMemAccessVersioningOfLoop)
23850b57cec5SDimitry Andric           collectStridedAccess(St);
23860b57cec5SDimitry Andric       }
23870b57cec5SDimitry Andric     } // Next instr.
23880b57cec5SDimitry Andric   } // Next block.
23890b57cec5SDimitry Andric 
23900b57cec5SDimitry Andric   if (HasComplexMemInst) {
23910b57cec5SDimitry Andric     CanVecMem = false;
23920b57cec5SDimitry Andric     return;
23930b57cec5SDimitry Andric   }
23940b57cec5SDimitry Andric 
23950b57cec5SDimitry Andric   // Now we have two lists that hold the loads and the stores.
23960b57cec5SDimitry Andric   // Next, we find the pointers that they use.
23970b57cec5SDimitry Andric 
23980b57cec5SDimitry Andric   // Check if we see any stores. If there are no stores, then we don't
23990b57cec5SDimitry Andric   // care if the pointers are *restrict*.
24000b57cec5SDimitry Andric   if (!Stores.size()) {
24010b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
24020b57cec5SDimitry Andric     CanVecMem = true;
24030b57cec5SDimitry Andric     return;
24040b57cec5SDimitry Andric   }
24050b57cec5SDimitry Andric 
24060b57cec5SDimitry Andric   MemoryDepChecker::DepCandidates DependentAccesses;
2407e8d8bef9SDimitry Andric   AccessAnalysis Accesses(TheLoop, AA, LI, DependentAccesses, *PSE);
24080b57cec5SDimitry Andric 
2409e8d8bef9SDimitry Andric   // Holds the analyzed pointers. We don't want to call getUnderlyingObjects
24100b57cec5SDimitry Andric   // multiple times on the same object. If the ptr is accessed twice, once
24110b57cec5SDimitry Andric   // for read and once for write, it will only appear once (on the write
24120b57cec5SDimitry Andric   // list). This is okay, since we are going to check for conflicts between
24130b57cec5SDimitry Andric   // writes and between reads and writes, but not between reads and reads.
241481ad6265SDimitry Andric   SmallSet<std::pair<Value *, Type *>, 16> Seen;
24150b57cec5SDimitry Andric 
24160b57cec5SDimitry Andric   // Record uniform store addresses to identify if we have multiple stores
24170b57cec5SDimitry Andric   // to the same address.
241881ad6265SDimitry Andric   SmallPtrSet<Value *, 16> UniformStores;
24190b57cec5SDimitry Andric 
24200b57cec5SDimitry Andric   for (StoreInst *ST : Stores) {
24210b57cec5SDimitry Andric     Value *Ptr = ST->getPointerOperand();
24220b57cec5SDimitry Andric 
2423fe013be4SDimitry Andric     if (isInvariant(Ptr)) {
242481ad6265SDimitry Andric       // Record store instructions to loop invariant addresses
242581ad6265SDimitry Andric       StoresToInvariantAddresses.push_back(ST);
24260b57cec5SDimitry Andric       HasDependenceInvolvingLoopInvariantAddress |=
24270b57cec5SDimitry Andric           !UniformStores.insert(Ptr).second;
242881ad6265SDimitry Andric     }
24290b57cec5SDimitry Andric 
24300b57cec5SDimitry Andric     // If we did *not* see this pointer before, insert it to  the read-write
24310b57cec5SDimitry Andric     // list. At this phase it is only a 'write' list.
243281ad6265SDimitry Andric     Type *AccessTy = getLoadStoreType(ST);
243381ad6265SDimitry Andric     if (Seen.insert({Ptr, AccessTy}).second) {
24340b57cec5SDimitry Andric       ++NumReadWrites;
24350b57cec5SDimitry Andric 
24360b57cec5SDimitry Andric       MemoryLocation Loc = MemoryLocation::get(ST);
24370b57cec5SDimitry Andric       // The TBAA metadata could have a control dependency on the predication
24380b57cec5SDimitry Andric       // condition, so we cannot rely on it when determining whether or not we
24390b57cec5SDimitry Andric       // need runtime pointer checks.
24400b57cec5SDimitry Andric       if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
24410b57cec5SDimitry Andric         Loc.AATags.TBAA = nullptr;
24420b57cec5SDimitry Andric 
2443349cc55cSDimitry Andric       visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop,
244481ad6265SDimitry Andric                     [&Accesses, AccessTy, Loc](Value *Ptr) {
2445349cc55cSDimitry Andric                       MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr);
244681ad6265SDimitry Andric                       Accesses.addStore(NewLoc, AccessTy);
2447349cc55cSDimitry Andric                     });
24480b57cec5SDimitry Andric     }
24490b57cec5SDimitry Andric   }
24500b57cec5SDimitry Andric 
24510b57cec5SDimitry Andric   if (IsAnnotatedParallel) {
24520b57cec5SDimitry Andric     LLVM_DEBUG(
24530b57cec5SDimitry Andric         dbgs() << "LAA: A loop annotated parallel, ignore memory dependency "
24540b57cec5SDimitry Andric                << "checks.\n");
24550b57cec5SDimitry Andric     CanVecMem = true;
24560b57cec5SDimitry Andric     return;
24570b57cec5SDimitry Andric   }
24580b57cec5SDimitry Andric 
24590b57cec5SDimitry Andric   for (LoadInst *LD : Loads) {
24600b57cec5SDimitry Andric     Value *Ptr = LD->getPointerOperand();
24610b57cec5SDimitry Andric     // If we did *not* see this pointer before, insert it to the
24620b57cec5SDimitry Andric     // read list. If we *did* see it before, then it is already in
24630b57cec5SDimitry Andric     // the read-write list. This allows us to vectorize expressions
24640b57cec5SDimitry Andric     // such as A[i] += x;  Because the address of A[i] is a read-write
24650b57cec5SDimitry Andric     // pointer. This only works if the index of A[i] is consecutive.
24660b57cec5SDimitry Andric     // If the address of i is unknown (for example A[B[i]]) then we may
24670b57cec5SDimitry Andric     // read a few words, modify, and write a few words, and some of the
24680b57cec5SDimitry Andric     // words may be written to the same address.
24690b57cec5SDimitry Andric     bool IsReadOnlyPtr = false;
247081ad6265SDimitry Andric     Type *AccessTy = getLoadStoreType(LD);
247181ad6265SDimitry Andric     if (Seen.insert({Ptr, AccessTy}).second ||
2472bdd1243dSDimitry Andric         !getPtrStride(*PSE, LD->getType(), Ptr, TheLoop, SymbolicStrides).value_or(0)) {
24730b57cec5SDimitry Andric       ++NumReads;
24740b57cec5SDimitry Andric       IsReadOnlyPtr = true;
24750b57cec5SDimitry Andric     }
24760b57cec5SDimitry Andric 
24770b57cec5SDimitry Andric     // See if there is an unsafe dependency between a load to a uniform address and
24780b57cec5SDimitry Andric     // store to the same uniform address.
24790b57cec5SDimitry Andric     if (UniformStores.count(Ptr)) {
24800b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "LAA: Found an unsafe dependency between a uniform "
24810b57cec5SDimitry Andric                            "load and uniform store to the same address!\n");
24820b57cec5SDimitry Andric       HasDependenceInvolvingLoopInvariantAddress = true;
24830b57cec5SDimitry Andric     }
24840b57cec5SDimitry Andric 
24850b57cec5SDimitry Andric     MemoryLocation Loc = MemoryLocation::get(LD);
24860b57cec5SDimitry Andric     // The TBAA metadata could have a control dependency on the predication
24870b57cec5SDimitry Andric     // condition, so we cannot rely on it when determining whether or not we
24880b57cec5SDimitry Andric     // need runtime pointer checks.
24890b57cec5SDimitry Andric     if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
24900b57cec5SDimitry Andric       Loc.AATags.TBAA = nullptr;
24910b57cec5SDimitry Andric 
2492349cc55cSDimitry Andric     visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop,
249381ad6265SDimitry Andric                   [&Accesses, AccessTy, Loc, IsReadOnlyPtr](Value *Ptr) {
2494349cc55cSDimitry Andric                     MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr);
249581ad6265SDimitry Andric                     Accesses.addLoad(NewLoc, AccessTy, IsReadOnlyPtr);
2496349cc55cSDimitry Andric                   });
24970b57cec5SDimitry Andric   }
24980b57cec5SDimitry Andric 
24990b57cec5SDimitry Andric   // If we write (or read-write) to a single destination and there are no
25000b57cec5SDimitry Andric   // other reads in this loop then is it safe to vectorize.
25010b57cec5SDimitry Andric   if (NumReadWrites == 1 && NumReads == 0) {
25020b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
25030b57cec5SDimitry Andric     CanVecMem = true;
25040b57cec5SDimitry Andric     return;
25050b57cec5SDimitry Andric   }
25060b57cec5SDimitry Andric 
25070b57cec5SDimitry Andric   // Build dependence sets and check whether we need a runtime pointer bounds
25080b57cec5SDimitry Andric   // check.
25090b57cec5SDimitry Andric   Accesses.buildDependenceSets();
25100b57cec5SDimitry Andric 
25110b57cec5SDimitry Andric   // Find pointers with computable bounds. We are going to use this information
25120b57cec5SDimitry Andric   // to place a runtime bound check.
251381ad6265SDimitry Andric   Value *UncomputablePtr = nullptr;
251481ad6265SDimitry Andric   bool CanDoRTIfNeeded =
251581ad6265SDimitry Andric       Accesses.canCheckPtrAtRT(*PtrRtChecking, PSE->getSE(), TheLoop,
251681ad6265SDimitry Andric                                SymbolicStrides, UncomputablePtr, false);
25170b57cec5SDimitry Andric   if (!CanDoRTIfNeeded) {
251881ad6265SDimitry Andric     auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr);
251981ad6265SDimitry Andric     recordAnalysis("CantIdentifyArrayBounds", I)
252081ad6265SDimitry Andric         << "cannot identify array bounds";
25210b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
25220b57cec5SDimitry Andric                       << "the array bounds.\n");
25230b57cec5SDimitry Andric     CanVecMem = false;
25240b57cec5SDimitry Andric     return;
25250b57cec5SDimitry Andric   }
25260b57cec5SDimitry Andric 
25270b57cec5SDimitry Andric   LLVM_DEBUG(
25280b57cec5SDimitry Andric     dbgs() << "LAA: May be able to perform a memory runtime check if needed.\n");
25290b57cec5SDimitry Andric 
25300b57cec5SDimitry Andric   CanVecMem = true;
25310b57cec5SDimitry Andric   if (Accesses.isDependencyCheckNeeded()) {
25320b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
25330b57cec5SDimitry Andric     CanVecMem = DepChecker->areDepsSafe(
2534c9157d92SDimitry Andric         DependentAccesses, Accesses.getDependenciesToCheck(), SymbolicStrides,
2535c9157d92SDimitry Andric         Accesses.getUnderlyingObjects());
25360b57cec5SDimitry Andric 
25370b57cec5SDimitry Andric     if (!CanVecMem && DepChecker->shouldRetryWithRuntimeCheck()) {
25380b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
25390b57cec5SDimitry Andric 
25400b57cec5SDimitry Andric       // Clear the dependency checks. We assume they are not needed.
25410b57cec5SDimitry Andric       Accesses.resetDepChecks(*DepChecker);
25420b57cec5SDimitry Andric 
25430b57cec5SDimitry Andric       PtrRtChecking->reset();
25440b57cec5SDimitry Andric       PtrRtChecking->Need = true;
25450b57cec5SDimitry Andric 
25460b57cec5SDimitry Andric       auto *SE = PSE->getSE();
254781ad6265SDimitry Andric       UncomputablePtr = nullptr;
254881ad6265SDimitry Andric       CanDoRTIfNeeded = Accesses.canCheckPtrAtRT(
254981ad6265SDimitry Andric           *PtrRtChecking, SE, TheLoop, SymbolicStrides, UncomputablePtr, true);
25500b57cec5SDimitry Andric 
25510b57cec5SDimitry Andric       // Check that we found the bounds for the pointer.
25520b57cec5SDimitry Andric       if (!CanDoRTIfNeeded) {
255381ad6265SDimitry Andric         auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr);
255481ad6265SDimitry Andric         recordAnalysis("CantCheckMemDepsAtRunTime", I)
25550b57cec5SDimitry Andric             << "cannot check memory dependencies at runtime";
25560b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
25570b57cec5SDimitry Andric         CanVecMem = false;
25580b57cec5SDimitry Andric         return;
25590b57cec5SDimitry Andric       }
25600b57cec5SDimitry Andric 
25610b57cec5SDimitry Andric       CanVecMem = true;
25620b57cec5SDimitry Andric     }
25630b57cec5SDimitry Andric   }
25640b57cec5SDimitry Andric 
25650b57cec5SDimitry Andric   if (HasConvergentOp) {
25660b57cec5SDimitry Andric     recordAnalysis("CantInsertRuntimeCheckWithConvergent")
25670b57cec5SDimitry Andric       << "cannot add control dependency to convergent operation";
25680b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because a runtime check "
25690b57cec5SDimitry Andric                          "would be needed with a convergent operation\n");
25700b57cec5SDimitry Andric     CanVecMem = false;
25710b57cec5SDimitry Andric     return;
25720b57cec5SDimitry Andric   }
25730b57cec5SDimitry Andric 
25740b57cec5SDimitry Andric   if (CanVecMem)
25750b57cec5SDimitry Andric     LLVM_DEBUG(
25760b57cec5SDimitry Andric         dbgs() << "LAA: No unsafe dependent memory operations in loop.  We"
25770b57cec5SDimitry Andric                << (PtrRtChecking->Need ? "" : " don't")
25780b57cec5SDimitry Andric                << " need runtime memory checks.\n");
257981ad6265SDimitry Andric   else
258081ad6265SDimitry Andric     emitUnsafeDependenceRemark();
258181ad6265SDimitry Andric }
258281ad6265SDimitry Andric 
258381ad6265SDimitry Andric void LoopAccessInfo::emitUnsafeDependenceRemark() {
258481ad6265SDimitry Andric   auto Deps = getDepChecker().getDependences();
258581ad6265SDimitry Andric   if (!Deps)
258681ad6265SDimitry Andric     return;
2587bdd1243dSDimitry Andric   auto Found = llvm::find_if(*Deps, [](const MemoryDepChecker::Dependence &D) {
258881ad6265SDimitry Andric     return MemoryDepChecker::Dependence::isSafeForVectorization(D.Type) !=
258981ad6265SDimitry Andric            MemoryDepChecker::VectorizationSafetyStatus::Safe;
259081ad6265SDimitry Andric   });
259181ad6265SDimitry Andric   if (Found == Deps->end())
259281ad6265SDimitry Andric     return;
259381ad6265SDimitry Andric   MemoryDepChecker::Dependence Dep = *Found;
259481ad6265SDimitry Andric 
259581ad6265SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
259681ad6265SDimitry Andric 
259781ad6265SDimitry Andric   // Emit remark for first unsafe dependence
2598c9157d92SDimitry Andric   bool HasForcedDistribution = false;
2599c9157d92SDimitry Andric   std::optional<const MDOperand *> Value =
2600c9157d92SDimitry Andric       findStringMetadataForLoop(TheLoop, "llvm.loop.distribute.enable");
2601c9157d92SDimitry Andric   if (Value) {
2602c9157d92SDimitry Andric     const MDOperand *Op = *Value;
2603c9157d92SDimitry Andric     assert(Op && mdconst::hasa<ConstantInt>(*Op) && "invalid metadata");
2604c9157d92SDimitry Andric     HasForcedDistribution = mdconst::extract<ConstantInt>(*Op)->getZExtValue();
2605c9157d92SDimitry Andric   }
2606c9157d92SDimitry Andric 
2607c9157d92SDimitry Andric   const std::string Info =
2608c9157d92SDimitry Andric       HasForcedDistribution
2609c9157d92SDimitry Andric           ? "unsafe dependent memory operations in loop."
2610c9157d92SDimitry Andric           : "unsafe dependent memory operations in loop. Use "
2611c9157d92SDimitry Andric             "#pragma clang loop distribute(enable) to allow loop distribution "
26120b57cec5SDimitry Andric             "to attempt to isolate the offending operations into a separate "
26130b57cec5SDimitry Andric             "loop";
2614c9157d92SDimitry Andric   OptimizationRemarkAnalysis &R =
2615c9157d92SDimitry Andric       recordAnalysis("UnsafeDep", Dep.getDestination(*this)) << Info;
261681ad6265SDimitry Andric 
261781ad6265SDimitry Andric   switch (Dep.Type) {
261881ad6265SDimitry Andric   case MemoryDepChecker::Dependence::NoDep:
261981ad6265SDimitry Andric   case MemoryDepChecker::Dependence::Forward:
262081ad6265SDimitry Andric   case MemoryDepChecker::Dependence::BackwardVectorizable:
262181ad6265SDimitry Andric     llvm_unreachable("Unexpected dependence");
262281ad6265SDimitry Andric   case MemoryDepChecker::Dependence::Backward:
262381ad6265SDimitry Andric     R << "\nBackward loop carried data dependence.";
262481ad6265SDimitry Andric     break;
262581ad6265SDimitry Andric   case MemoryDepChecker::Dependence::ForwardButPreventsForwarding:
262681ad6265SDimitry Andric     R << "\nForward loop carried data dependence that prevents "
262781ad6265SDimitry Andric          "store-to-load forwarding.";
262881ad6265SDimitry Andric     break;
262981ad6265SDimitry Andric   case MemoryDepChecker::Dependence::BackwardVectorizableButPreventsForwarding:
263081ad6265SDimitry Andric     R << "\nBackward loop carried data dependence that prevents "
263181ad6265SDimitry Andric          "store-to-load forwarding.";
263281ad6265SDimitry Andric     break;
2633c9157d92SDimitry Andric   case MemoryDepChecker::Dependence::IndirectUnsafe:
2634c9157d92SDimitry Andric     R << "\nUnsafe indirect dependence.";
2635c9157d92SDimitry Andric     break;
263681ad6265SDimitry Andric   case MemoryDepChecker::Dependence::Unknown:
263781ad6265SDimitry Andric     R << "\nUnknown data dependence.";
263881ad6265SDimitry Andric     break;
263981ad6265SDimitry Andric   }
264081ad6265SDimitry Andric 
264181ad6265SDimitry Andric   if (Instruction *I = Dep.getSource(*this)) {
264281ad6265SDimitry Andric     DebugLoc SourceLoc = I->getDebugLoc();
264381ad6265SDimitry Andric     if (auto *DD = dyn_cast_or_null<Instruction>(getPointerOperand(I)))
264481ad6265SDimitry Andric       SourceLoc = DD->getDebugLoc();
264581ad6265SDimitry Andric     if (SourceLoc)
264681ad6265SDimitry Andric       R << " Memory location is the same as accessed at "
264781ad6265SDimitry Andric         << ore::NV("Location", SourceLoc);
26480b57cec5SDimitry Andric   }
26490b57cec5SDimitry Andric }
26500b57cec5SDimitry Andric 
26510b57cec5SDimitry Andric bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
26520b57cec5SDimitry Andric                                            DominatorTree *DT)  {
26530b57cec5SDimitry Andric   assert(TheLoop->contains(BB) && "Unknown block used");
26540b57cec5SDimitry Andric 
26550b57cec5SDimitry Andric   // Blocks that do not dominate the latch need predication.
26560b57cec5SDimitry Andric   BasicBlock* Latch = TheLoop->getLoopLatch();
26570b57cec5SDimitry Andric   return !DT->dominates(BB, Latch);
26580b57cec5SDimitry Andric }
26590b57cec5SDimitry Andric 
26600b57cec5SDimitry Andric OptimizationRemarkAnalysis &LoopAccessInfo::recordAnalysis(StringRef RemarkName,
26610b57cec5SDimitry Andric                                                            Instruction *I) {
26620b57cec5SDimitry Andric   assert(!Report && "Multiple reports generated");
26630b57cec5SDimitry Andric 
26640b57cec5SDimitry Andric   Value *CodeRegion = TheLoop->getHeader();
26650b57cec5SDimitry Andric   DebugLoc DL = TheLoop->getStartLoc();
26660b57cec5SDimitry Andric 
26670b57cec5SDimitry Andric   if (I) {
26680b57cec5SDimitry Andric     CodeRegion = I->getParent();
26690b57cec5SDimitry Andric     // If there is no debug location attached to the instruction, revert back to
26700b57cec5SDimitry Andric     // using the loop's.
26710b57cec5SDimitry Andric     if (I->getDebugLoc())
26720b57cec5SDimitry Andric       DL = I->getDebugLoc();
26730b57cec5SDimitry Andric   }
26740b57cec5SDimitry Andric 
26758bcb0991SDimitry Andric   Report = std::make_unique<OptimizationRemarkAnalysis>(DEBUG_TYPE, RemarkName, DL,
26760b57cec5SDimitry Andric                                                    CodeRegion);
26770b57cec5SDimitry Andric   return *Report;
26780b57cec5SDimitry Andric }
26790b57cec5SDimitry Andric 
2680fe013be4SDimitry Andric bool LoopAccessInfo::isInvariant(Value *V) const {
26810b57cec5SDimitry Andric   auto *SE = PSE->getSE();
26820b57cec5SDimitry Andric   // TODO: Is this really what we want? Even without FP SCEV, we may want some
2683fe013be4SDimitry Andric   // trivially loop-invariant FP values to be considered invariant.
26840b57cec5SDimitry Andric   if (!SE->isSCEVable(V->getType()))
26850b57cec5SDimitry Andric     return false;
2686fe013be4SDimitry Andric   const SCEV *S = SE->getSCEV(V);
2687fe013be4SDimitry Andric   return SE->isLoopInvariant(S, TheLoop);
2688fe013be4SDimitry Andric }
2689fe013be4SDimitry Andric 
2690fe013be4SDimitry Andric /// Find the operand of the GEP that should be checked for consecutive
2691fe013be4SDimitry Andric /// stores. This ignores trailing indices that have no effect on the final
2692fe013be4SDimitry Andric /// pointer.
2693fe013be4SDimitry Andric static unsigned getGEPInductionOperand(const GetElementPtrInst *Gep) {
2694fe013be4SDimitry Andric   const DataLayout &DL = Gep->getModule()->getDataLayout();
2695fe013be4SDimitry Andric   unsigned LastOperand = Gep->getNumOperands() - 1;
2696fe013be4SDimitry Andric   TypeSize GEPAllocSize = DL.getTypeAllocSize(Gep->getResultElementType());
2697fe013be4SDimitry Andric 
2698fe013be4SDimitry Andric   // Walk backwards and try to peel off zeros.
2699fe013be4SDimitry Andric   while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
2700fe013be4SDimitry Andric     // Find the type we're currently indexing into.
2701fe013be4SDimitry Andric     gep_type_iterator GEPTI = gep_type_begin(Gep);
2702fe013be4SDimitry Andric     std::advance(GEPTI, LastOperand - 2);
2703fe013be4SDimitry Andric 
2704fe013be4SDimitry Andric     // If it's a type with the same allocation size as the result of the GEP we
2705fe013be4SDimitry Andric     // can peel off the zero index.
2706*cdc20ff6SDimitry Andric     TypeSize ElemSize = GEPTI.isStruct()
2707*cdc20ff6SDimitry Andric                             ? DL.getTypeAllocSize(GEPTI.getIndexedType())
2708*cdc20ff6SDimitry Andric                             : GEPTI.getSequentialElementStride(DL);
2709*cdc20ff6SDimitry Andric     if (ElemSize != GEPAllocSize)
2710fe013be4SDimitry Andric       break;
2711fe013be4SDimitry Andric     --LastOperand;
2712fe013be4SDimitry Andric   }
2713fe013be4SDimitry Andric 
2714fe013be4SDimitry Andric   return LastOperand;
2715fe013be4SDimitry Andric }
2716fe013be4SDimitry Andric 
2717fe013be4SDimitry Andric /// If the argument is a GEP, then returns the operand identified by
2718fe013be4SDimitry Andric /// getGEPInductionOperand. However, if there is some other non-loop-invariant
2719fe013be4SDimitry Andric /// operand, it returns that instead.
2720fe013be4SDimitry Andric static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
2721fe013be4SDimitry Andric   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
2722fe013be4SDimitry Andric   if (!GEP)
2723fe013be4SDimitry Andric     return Ptr;
2724fe013be4SDimitry Andric 
2725fe013be4SDimitry Andric   unsigned InductionOperand = getGEPInductionOperand(GEP);
2726fe013be4SDimitry Andric 
2727fe013be4SDimitry Andric   // Check that all of the gep indices are uniform except for our induction
2728fe013be4SDimitry Andric   // operand.
2729fe013be4SDimitry Andric   for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
2730fe013be4SDimitry Andric     if (i != InductionOperand &&
2731fe013be4SDimitry Andric         !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
2732fe013be4SDimitry Andric       return Ptr;
2733fe013be4SDimitry Andric   return GEP->getOperand(InductionOperand);
2734fe013be4SDimitry Andric }
2735fe013be4SDimitry Andric 
2736fe013be4SDimitry Andric /// If a value has only one user that is a CastInst, return it.
2737fe013be4SDimitry Andric static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
2738fe013be4SDimitry Andric   Value *UniqueCast = nullptr;
2739fe013be4SDimitry Andric   for (User *U : Ptr->users()) {
2740fe013be4SDimitry Andric     CastInst *CI = dyn_cast<CastInst>(U);
2741fe013be4SDimitry Andric     if (CI && CI->getType() == Ty) {
2742fe013be4SDimitry Andric       if (!UniqueCast)
2743fe013be4SDimitry Andric         UniqueCast = CI;
2744fe013be4SDimitry Andric       else
2745fe013be4SDimitry Andric         return nullptr;
2746fe013be4SDimitry Andric     }
2747fe013be4SDimitry Andric   }
2748fe013be4SDimitry Andric   return UniqueCast;
2749fe013be4SDimitry Andric }
2750fe013be4SDimitry Andric 
2751fe013be4SDimitry Andric /// Get the stride of a pointer access in a loop. Looks for symbolic
2752fe013be4SDimitry Andric /// strides "a[i*stride]". Returns the symbolic stride, or null otherwise.
2753fe013be4SDimitry Andric static const SCEV *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
2754fe013be4SDimitry Andric   auto *PtrTy = dyn_cast<PointerType>(Ptr->getType());
2755fe013be4SDimitry Andric   if (!PtrTy || PtrTy->isAggregateType())
2756fe013be4SDimitry Andric     return nullptr;
2757fe013be4SDimitry Andric 
2758fe013be4SDimitry Andric   // Try to remove a gep instruction to make the pointer (actually index at this
2759fe013be4SDimitry Andric   // point) easier analyzable. If OrigPtr is equal to Ptr we are analyzing the
2760fe013be4SDimitry Andric   // pointer, otherwise, we are analyzing the index.
2761fe013be4SDimitry Andric   Value *OrigPtr = Ptr;
2762fe013be4SDimitry Andric 
2763fe013be4SDimitry Andric   // The size of the pointer access.
2764fe013be4SDimitry Andric   int64_t PtrAccessSize = 1;
2765fe013be4SDimitry Andric 
2766fe013be4SDimitry Andric   Ptr = stripGetElementPtr(Ptr, SE, Lp);
2767fe013be4SDimitry Andric   const SCEV *V = SE->getSCEV(Ptr);
2768fe013be4SDimitry Andric 
2769fe013be4SDimitry Andric   if (Ptr != OrigPtr)
2770fe013be4SDimitry Andric     // Strip off casts.
2771fe013be4SDimitry Andric     while (const SCEVIntegralCastExpr *C = dyn_cast<SCEVIntegralCastExpr>(V))
2772fe013be4SDimitry Andric       V = C->getOperand();
2773fe013be4SDimitry Andric 
2774fe013be4SDimitry Andric   const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
2775fe013be4SDimitry Andric   if (!S)
2776fe013be4SDimitry Andric     return nullptr;
2777fe013be4SDimitry Andric 
2778fe013be4SDimitry Andric   // If the pointer is invariant then there is no stride and it makes no
2779fe013be4SDimitry Andric   // sense to add it here.
2780fe013be4SDimitry Andric   if (Lp != S->getLoop())
2781fe013be4SDimitry Andric     return nullptr;
2782fe013be4SDimitry Andric 
2783fe013be4SDimitry Andric   V = S->getStepRecurrence(*SE);
2784fe013be4SDimitry Andric   if (!V)
2785fe013be4SDimitry Andric     return nullptr;
2786fe013be4SDimitry Andric 
2787fe013be4SDimitry Andric   // Strip off the size of access multiplication if we are still analyzing the
2788fe013be4SDimitry Andric   // pointer.
2789fe013be4SDimitry Andric   if (OrigPtr == Ptr) {
2790fe013be4SDimitry Andric     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
2791fe013be4SDimitry Andric       if (M->getOperand(0)->getSCEVType() != scConstant)
2792fe013be4SDimitry Andric         return nullptr;
2793fe013be4SDimitry Andric 
2794fe013be4SDimitry Andric       const APInt &APStepVal = cast<SCEVConstant>(M->getOperand(0))->getAPInt();
2795fe013be4SDimitry Andric 
2796fe013be4SDimitry Andric       // Huge step value - give up.
2797fe013be4SDimitry Andric       if (APStepVal.getBitWidth() > 64)
2798fe013be4SDimitry Andric         return nullptr;
2799fe013be4SDimitry Andric 
2800fe013be4SDimitry Andric       int64_t StepVal = APStepVal.getSExtValue();
2801fe013be4SDimitry Andric       if (PtrAccessSize != StepVal)
2802fe013be4SDimitry Andric         return nullptr;
2803fe013be4SDimitry Andric       V = M->getOperand(1);
2804fe013be4SDimitry Andric     }
2805fe013be4SDimitry Andric   }
2806fe013be4SDimitry Andric 
2807fe013be4SDimitry Andric   // Note that the restriction after this loop invariant check are only
2808fe013be4SDimitry Andric   // profitability restrictions.
2809fe013be4SDimitry Andric   if (!SE->isLoopInvariant(V, Lp))
2810fe013be4SDimitry Andric     return nullptr;
2811fe013be4SDimitry Andric 
2812fe013be4SDimitry Andric   // Look for the loop invariant symbolic value.
2813fe013be4SDimitry Andric   const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
2814fe013be4SDimitry Andric   if (!U) {
2815fe013be4SDimitry Andric     const auto *C = dyn_cast<SCEVIntegralCastExpr>(V);
2816fe013be4SDimitry Andric     if (!C)
2817fe013be4SDimitry Andric       return nullptr;
2818fe013be4SDimitry Andric     U = dyn_cast<SCEVUnknown>(C->getOperand());
2819fe013be4SDimitry Andric     if (!U)
2820fe013be4SDimitry Andric       return nullptr;
2821fe013be4SDimitry Andric 
2822fe013be4SDimitry Andric     // Match legacy behavior - this is not needed for correctness
2823fe013be4SDimitry Andric     if (!getUniqueCastUse(U->getValue(), Lp, V->getType()))
2824fe013be4SDimitry Andric       return nullptr;
2825fe013be4SDimitry Andric   }
2826fe013be4SDimitry Andric 
2827fe013be4SDimitry Andric   return V;
28280b57cec5SDimitry Andric }
28290b57cec5SDimitry Andric 
28300b57cec5SDimitry Andric void LoopAccessInfo::collectStridedAccess(Value *MemAccess) {
2831e8d8bef9SDimitry Andric   Value *Ptr = getLoadStorePointerOperand(MemAccess);
2832e8d8bef9SDimitry Andric   if (!Ptr)
28330b57cec5SDimitry Andric     return;
28340b57cec5SDimitry Andric 
2835fe013be4SDimitry Andric   // Note: getStrideFromPointer is a *profitability* heuristic.  We
2836fe013be4SDimitry Andric   // could broaden the scope of values returned here - to anything
2837fe013be4SDimitry Andric   // which happens to be loop invariant and contributes to the
2838fe013be4SDimitry Andric   // computation of an interesting IV - but we chose not to as we
2839fe013be4SDimitry Andric   // don't have a cost model here, and broadening the scope exposes
2840fe013be4SDimitry Andric   // far too many unprofitable cases.
2841fe013be4SDimitry Andric   const SCEV *StrideExpr = getStrideFromPointer(Ptr, PSE->getSE(), TheLoop);
2842fe013be4SDimitry Andric   if (!StrideExpr)
28430b57cec5SDimitry Andric     return;
28440b57cec5SDimitry Andric 
28450b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Found a strided access that is a candidate for "
28460b57cec5SDimitry Andric                        "versioning:");
2847fe013be4SDimitry Andric   LLVM_DEBUG(dbgs() << "  Ptr: " << *Ptr << " Stride: " << *StrideExpr << "\n");
2848fe013be4SDimitry Andric 
2849fe013be4SDimitry Andric   if (!SpeculateUnitStride) {
2850fe013be4SDimitry Andric     LLVM_DEBUG(dbgs() << "  Chose not to due to -laa-speculate-unit-stride\n");
2851fe013be4SDimitry Andric     return;
2852fe013be4SDimitry Andric   }
28530b57cec5SDimitry Andric 
28540b57cec5SDimitry Andric   // Avoid adding the "Stride == 1" predicate when we know that
28550b57cec5SDimitry Andric   // Stride >= Trip-Count. Such a predicate will effectively optimize a single
28560b57cec5SDimitry Andric   // or zero iteration loop, as Trip-Count <= Stride == 1.
28570b57cec5SDimitry Andric   //
28580b57cec5SDimitry Andric   // TODO: We are currently not making a very informed decision on when it is
28590b57cec5SDimitry Andric   // beneficial to apply stride versioning. It might make more sense that the
28600b57cec5SDimitry Andric   // users of this analysis (such as the vectorizer) will trigger it, based on
28610b57cec5SDimitry Andric   // their specific cost considerations; For example, in cases where stride
28620b57cec5SDimitry Andric   // versioning does  not help resolving memory accesses/dependences, the
28630b57cec5SDimitry Andric   // vectorizer should evaluate the cost of the runtime test, and the benefit
28640b57cec5SDimitry Andric   // of various possible stride specializations, considering the alternatives
28650b57cec5SDimitry Andric   // of using gather/scatters (if available).
28660b57cec5SDimitry Andric 
28670b57cec5SDimitry Andric   const SCEV *BETakenCount = PSE->getBackedgeTakenCount();
28680b57cec5SDimitry Andric 
28690b57cec5SDimitry Andric   // Match the types so we can compare the stride and the BETakenCount.
28700b57cec5SDimitry Andric   // The Stride can be positive/negative, so we sign extend Stride;
28710b57cec5SDimitry Andric   // The backedgeTakenCount is non-negative, so we zero extend BETakenCount.
28720b57cec5SDimitry Andric   const DataLayout &DL = TheLoop->getHeader()->getModule()->getDataLayout();
287381ad6265SDimitry Andric   uint64_t StrideTypeSizeBits = DL.getTypeSizeInBits(StrideExpr->getType());
287481ad6265SDimitry Andric   uint64_t BETypeSizeBits = DL.getTypeSizeInBits(BETakenCount->getType());
28750b57cec5SDimitry Andric   const SCEV *CastedStride = StrideExpr;
28760b57cec5SDimitry Andric   const SCEV *CastedBECount = BETakenCount;
28770b57cec5SDimitry Andric   ScalarEvolution *SE = PSE->getSE();
287881ad6265SDimitry Andric   if (BETypeSizeBits >= StrideTypeSizeBits)
28790b57cec5SDimitry Andric     CastedStride = SE->getNoopOrSignExtend(StrideExpr, BETakenCount->getType());
28800b57cec5SDimitry Andric   else
28810b57cec5SDimitry Andric     CastedBECount = SE->getZeroExtendExpr(BETakenCount, StrideExpr->getType());
28820b57cec5SDimitry Andric   const SCEV *StrideMinusBETaken = SE->getMinusSCEV(CastedStride, CastedBECount);
28830b57cec5SDimitry Andric   // Since TripCount == BackEdgeTakenCount + 1, checking:
28840b57cec5SDimitry Andric   // "Stride >= TripCount" is equivalent to checking:
28850b57cec5SDimitry Andric   // Stride - BETakenCount > 0
28860b57cec5SDimitry Andric   if (SE->isKnownPositive(StrideMinusBETaken)) {
28870b57cec5SDimitry Andric     LLVM_DEBUG(
28880b57cec5SDimitry Andric         dbgs() << "LAA: Stride>=TripCount; No point in versioning as the "
28890b57cec5SDimitry Andric                   "Stride==1 predicate will imply that the loop executes "
28900b57cec5SDimitry Andric                   "at most once.\n");
28910b57cec5SDimitry Andric     return;
28920b57cec5SDimitry Andric   }
289381ad6265SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Found a strided access that we can version.\n");
28940b57cec5SDimitry Andric 
2895fe013be4SDimitry Andric   // Strip back off the integer cast, and check that our result is a
2896fe013be4SDimitry Andric   // SCEVUnknown as we expect.
2897fe013be4SDimitry Andric   const SCEV *StrideBase = StrideExpr;
2898fe013be4SDimitry Andric   if (const auto *C = dyn_cast<SCEVIntegralCastExpr>(StrideBase))
2899fe013be4SDimitry Andric     StrideBase = C->getOperand();
2900fe013be4SDimitry Andric   SymbolicStrides[Ptr] = cast<SCEVUnknown>(StrideBase);
29010b57cec5SDimitry Andric }
29020b57cec5SDimitry Andric 
29030b57cec5SDimitry Andric LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
29045ffd83dbSDimitry Andric                                const TargetLibraryInfo *TLI, AAResults *AA,
29050b57cec5SDimitry Andric                                DominatorTree *DT, LoopInfo *LI)
29068bcb0991SDimitry Andric     : PSE(std::make_unique<PredicatedScalarEvolution>(*SE, *L)),
290781ad6265SDimitry Andric       PtrRtChecking(nullptr),
290804eeddc0SDimitry Andric       DepChecker(std::make_unique<MemoryDepChecker>(*PSE, L)), TheLoop(L) {
290981ad6265SDimitry Andric   PtrRtChecking = std::make_unique<RuntimePointerChecking>(*DepChecker, SE);
291081ad6265SDimitry Andric   if (canAnalyzeLoop()) {
29110b57cec5SDimitry Andric     analyzeLoop(AA, LI, TLI, DT);
29120b57cec5SDimitry Andric   }
291381ad6265SDimitry Andric }
29140b57cec5SDimitry Andric 
29150b57cec5SDimitry Andric void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
29160b57cec5SDimitry Andric   if (CanVecMem) {
29170b57cec5SDimitry Andric     OS.indent(Depth) << "Memory dependences are safe";
2918c9157d92SDimitry Andric     const MemoryDepChecker &DC = getDepChecker();
2919c9157d92SDimitry Andric     if (!DC.isSafeForAnyVectorWidth())
2920c9157d92SDimitry Andric       OS << " with a maximum safe vector width of "
2921c9157d92SDimitry Andric          << DC.getMaxSafeVectorWidthInBits() << " bits";
29220b57cec5SDimitry Andric     if (PtrRtChecking->Need)
29230b57cec5SDimitry Andric       OS << " with run-time checks";
29240b57cec5SDimitry Andric     OS << "\n";
29250b57cec5SDimitry Andric   }
29260b57cec5SDimitry Andric 
29270b57cec5SDimitry Andric   if (HasConvergentOp)
29280b57cec5SDimitry Andric     OS.indent(Depth) << "Has convergent operation in loop\n";
29290b57cec5SDimitry Andric 
29300b57cec5SDimitry Andric   if (Report)
29310b57cec5SDimitry Andric     OS.indent(Depth) << "Report: " << Report->getMsg() << "\n";
29320b57cec5SDimitry Andric 
29330b57cec5SDimitry Andric   if (auto *Dependences = DepChecker->getDependences()) {
29340b57cec5SDimitry Andric     OS.indent(Depth) << "Dependences:\n";
2935fcaf7f86SDimitry Andric     for (const auto &Dep : *Dependences) {
29360b57cec5SDimitry Andric       Dep.print(OS, Depth + 2, DepChecker->getMemoryInstructions());
29370b57cec5SDimitry Andric       OS << "\n";
29380b57cec5SDimitry Andric     }
29390b57cec5SDimitry Andric   } else
29400b57cec5SDimitry Andric     OS.indent(Depth) << "Too many dependences, not recorded\n";
29410b57cec5SDimitry Andric 
29420b57cec5SDimitry Andric   // List the pair of accesses need run-time checks to prove independence.
29430b57cec5SDimitry Andric   PtrRtChecking->print(OS, Depth);
29440b57cec5SDimitry Andric   OS << "\n";
29450b57cec5SDimitry Andric 
29460b57cec5SDimitry Andric   OS.indent(Depth) << "Non vectorizable stores to invariant address were "
29470b57cec5SDimitry Andric                    << (HasDependenceInvolvingLoopInvariantAddress ? "" : "not ")
29480b57cec5SDimitry Andric                    << "found in loop.\n";
29490b57cec5SDimitry Andric 
29500b57cec5SDimitry Andric   OS.indent(Depth) << "SCEV assumptions:\n";
295181ad6265SDimitry Andric   PSE->getPredicate().print(OS, Depth);
29520b57cec5SDimitry Andric 
29530b57cec5SDimitry Andric   OS << "\n";
29540b57cec5SDimitry Andric 
29550b57cec5SDimitry Andric   OS.indent(Depth) << "Expressions re-written:\n";
29560b57cec5SDimitry Andric   PSE->print(OS, Depth);
29570b57cec5SDimitry Andric }
29580b57cec5SDimitry Andric 
2959bdd1243dSDimitry Andric const LoopAccessInfo &LoopAccessInfoManager::getInfo(Loop &L) {
2960bdd1243dSDimitry Andric   auto I = LoopAccessInfoMap.insert({&L, nullptr});
2961bdd1243dSDimitry Andric 
2962bdd1243dSDimitry Andric   if (I.second)
2963bdd1243dSDimitry Andric     I.first->second =
2964bdd1243dSDimitry Andric         std::make_unique<LoopAccessInfo>(&L, &SE, TLI, &AA, &DT, &LI);
2965bdd1243dSDimitry Andric 
2966bdd1243dSDimitry Andric   return *I.first->second;
2967bdd1243dSDimitry Andric }
2968bdd1243dSDimitry Andric 
2969fe013be4SDimitry Andric bool LoopAccessInfoManager::invalidate(
2970fe013be4SDimitry Andric     Function &F, const PreservedAnalyses &PA,
2971fe013be4SDimitry Andric     FunctionAnalysisManager::Invalidator &Inv) {
2972fe013be4SDimitry Andric   // Check whether our analysis is preserved.
2973fe013be4SDimitry Andric   auto PAC = PA.getChecker<LoopAccessAnalysis>();
2974fe013be4SDimitry Andric   if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>())
2975fe013be4SDimitry Andric     // If not, give up now.
2976fe013be4SDimitry Andric     return true;
2977480093f4SDimitry Andric 
2978fe013be4SDimitry Andric   // Check whether the analyses we depend on became invalid for any reason.
2979fe013be4SDimitry Andric   // Skip checking TargetLibraryAnalysis as it is immutable and can't become
2980fe013be4SDimitry Andric   // invalid.
2981fe013be4SDimitry Andric   return Inv.invalidate<AAManager>(F, PA) ||
2982fe013be4SDimitry Andric          Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) ||
2983fe013be4SDimitry Andric          Inv.invalidate<LoopAnalysis>(F, PA) ||
2984fe013be4SDimitry Andric          Inv.invalidate<DominatorTreeAnalysis>(F, PA);
29850b57cec5SDimitry Andric }
29860b57cec5SDimitry Andric 
2987bdd1243dSDimitry Andric LoopAccessInfoManager LoopAccessAnalysis::run(Function &F,
2988fe013be4SDimitry Andric                                               FunctionAnalysisManager &FAM) {
2989fe013be4SDimitry Andric   auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
2990fe013be4SDimitry Andric   auto &AA = FAM.getResult<AAManager>(F);
2991fe013be4SDimitry Andric   auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
2992fe013be4SDimitry Andric   auto &LI = FAM.getResult<LoopAnalysis>(F);
2993fe013be4SDimitry Andric   auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
2994fe013be4SDimitry Andric   return LoopAccessInfoManager(SE, AA, DT, LI, &TLI);
2995bdd1243dSDimitry Andric }
2996bdd1243dSDimitry Andric 
29970b57cec5SDimitry Andric AnalysisKey LoopAccessAnalysis::Key;
2998