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/DepthFirstIterator.h" 180b57cec5SDimitry Andric #include "llvm/ADT/EquivalenceClasses.h" 190b57cec5SDimitry Andric #include "llvm/ADT/PointerIntPair.h" 200b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h" 210b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h" 220b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h" 230b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h" 240b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h" 250b57cec5SDimitry Andric #include "llvm/ADT/iterator_range.h" 260b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h" 270b57cec5SDimitry Andric #include "llvm/Analysis/AliasSetTracker.h" 280b57cec5SDimitry Andric #include "llvm/Analysis/LoopAnalysisManager.h" 290b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h" 30bdd1243dSDimitry Andric #include "llvm/Analysis/LoopIterator.h" 310b57cec5SDimitry Andric #include "llvm/Analysis/MemoryLocation.h" 320b57cec5SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h" 330b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h" 340b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h" 350b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h" 360b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h" 370b57cec5SDimitry Andric #include "llvm/Analysis/VectorUtils.h" 380b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h" 390b57cec5SDimitry Andric #include "llvm/IR/Constants.h" 400b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h" 410b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h" 420b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h" 430b57cec5SDimitry Andric #include "llvm/IR/DiagnosticInfo.h" 440b57cec5SDimitry Andric #include "llvm/IR/Dominators.h" 450b57cec5SDimitry Andric #include "llvm/IR/Function.h" 46*fe013be4SDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h" 470b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h" 480b57cec5SDimitry Andric #include "llvm/IR/Instruction.h" 490b57cec5SDimitry Andric #include "llvm/IR/Instructions.h" 500b57cec5SDimitry Andric #include "llvm/IR/Operator.h" 510b57cec5SDimitry Andric #include "llvm/IR/PassManager.h" 5281ad6265SDimitry Andric #include "llvm/IR/PatternMatch.h" 530b57cec5SDimitry Andric #include "llvm/IR/Type.h" 540b57cec5SDimitry Andric #include "llvm/IR/Value.h" 550b57cec5SDimitry Andric #include "llvm/IR/ValueHandle.h" 56480093f4SDimitry Andric #include "llvm/InitializePasses.h" 570b57cec5SDimitry Andric #include "llvm/Pass.h" 580b57cec5SDimitry Andric #include "llvm/Support/Casting.h" 590b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h" 600b57cec5SDimitry Andric #include "llvm/Support/Debug.h" 610b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h" 620b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 630b57cec5SDimitry Andric #include <algorithm> 640b57cec5SDimitry Andric #include <cassert> 650b57cec5SDimitry Andric #include <cstdint> 660b57cec5SDimitry Andric #include <iterator> 670b57cec5SDimitry Andric #include <utility> 680b57cec5SDimitry Andric #include <vector> 690b57cec5SDimitry Andric 700b57cec5SDimitry Andric using namespace llvm; 7181ad6265SDimitry Andric using namespace llvm::PatternMatch; 720b57cec5SDimitry Andric 730b57cec5SDimitry Andric #define DEBUG_TYPE "loop-accesses" 740b57cec5SDimitry Andric 750b57cec5SDimitry Andric static cl::opt<unsigned, true> 760b57cec5SDimitry Andric VectorizationFactor("force-vector-width", cl::Hidden, 770b57cec5SDimitry Andric cl::desc("Sets the SIMD width. Zero is autoselect."), 780b57cec5SDimitry Andric cl::location(VectorizerParams::VectorizationFactor)); 790b57cec5SDimitry Andric unsigned VectorizerParams::VectorizationFactor; 800b57cec5SDimitry Andric 810b57cec5SDimitry Andric static cl::opt<unsigned, true> 820b57cec5SDimitry Andric VectorizationInterleave("force-vector-interleave", cl::Hidden, 830b57cec5SDimitry Andric cl::desc("Sets the vectorization interleave count. " 840b57cec5SDimitry Andric "Zero is autoselect."), 850b57cec5SDimitry Andric cl::location( 860b57cec5SDimitry Andric VectorizerParams::VectorizationInterleave)); 870b57cec5SDimitry Andric unsigned VectorizerParams::VectorizationInterleave; 880b57cec5SDimitry Andric 890b57cec5SDimitry Andric static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold( 900b57cec5SDimitry Andric "runtime-memory-check-threshold", cl::Hidden, 910b57cec5SDimitry Andric cl::desc("When performing memory disambiguation checks at runtime do not " 920b57cec5SDimitry Andric "generate more than this number of comparisons (default = 8)."), 930b57cec5SDimitry Andric cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8)); 940b57cec5SDimitry Andric unsigned VectorizerParams::RuntimeMemoryCheckThreshold; 950b57cec5SDimitry Andric 960b57cec5SDimitry Andric /// The maximum iterations used to merge memory checks 970b57cec5SDimitry Andric static cl::opt<unsigned> MemoryCheckMergeThreshold( 980b57cec5SDimitry Andric "memory-check-merge-threshold", cl::Hidden, 990b57cec5SDimitry Andric cl::desc("Maximum number of comparisons done when trying to merge " 1000b57cec5SDimitry Andric "runtime memory checks. (default = 100)"), 1010b57cec5SDimitry Andric cl::init(100)); 1020b57cec5SDimitry Andric 1030b57cec5SDimitry Andric /// Maximum SIMD width. 1040b57cec5SDimitry Andric const unsigned VectorizerParams::MaxVectorWidth = 64; 1050b57cec5SDimitry Andric 1060b57cec5SDimitry Andric /// We collect dependences up to this threshold. 1070b57cec5SDimitry Andric static cl::opt<unsigned> 1080b57cec5SDimitry Andric MaxDependences("max-dependences", cl::Hidden, 1090b57cec5SDimitry Andric cl::desc("Maximum number of dependences collected by " 1100b57cec5SDimitry Andric "loop-access analysis (default = 100)"), 1110b57cec5SDimitry Andric cl::init(100)); 1120b57cec5SDimitry Andric 1130b57cec5SDimitry Andric /// This enables versioning on the strides of symbolically striding memory 1140b57cec5SDimitry Andric /// accesses in code like the following. 1150b57cec5SDimitry Andric /// for (i = 0; i < N; ++i) 1160b57cec5SDimitry Andric /// A[i * Stride1] += B[i * Stride2] ... 1170b57cec5SDimitry Andric /// 1180b57cec5SDimitry Andric /// Will be roughly translated to 1190b57cec5SDimitry Andric /// if (Stride1 == 1 && Stride2 == 1) { 1200b57cec5SDimitry Andric /// for (i = 0; i < N; i+=4) 1210b57cec5SDimitry Andric /// A[i:i+3] += ... 1220b57cec5SDimitry Andric /// } else 1230b57cec5SDimitry Andric /// ... 1240b57cec5SDimitry Andric static cl::opt<bool> EnableMemAccessVersioning( 1250b57cec5SDimitry Andric "enable-mem-access-versioning", cl::init(true), cl::Hidden, 1260b57cec5SDimitry Andric cl::desc("Enable symbolic stride memory access versioning")); 1270b57cec5SDimitry Andric 1280b57cec5SDimitry Andric /// Enable store-to-load forwarding conflict detection. This option can 1290b57cec5SDimitry Andric /// be disabled for correctness testing. 1300b57cec5SDimitry Andric static cl::opt<bool> EnableForwardingConflictDetection( 1310b57cec5SDimitry Andric "store-to-load-forwarding-conflict-detection", cl::Hidden, 1320b57cec5SDimitry Andric cl::desc("Enable conflict detection in loop-access analysis"), 1330b57cec5SDimitry Andric cl::init(true)); 1340b57cec5SDimitry Andric 135fcaf7f86SDimitry Andric static cl::opt<unsigned> MaxForkedSCEVDepth( 136fcaf7f86SDimitry Andric "max-forked-scev-depth", cl::Hidden, 137fcaf7f86SDimitry Andric cl::desc("Maximum recursion depth when finding forked SCEVs (default = 5)"), 138fcaf7f86SDimitry Andric cl::init(5)); 139fcaf7f86SDimitry Andric 140*fe013be4SDimitry Andric static cl::opt<bool> SpeculateUnitStride( 141*fe013be4SDimitry Andric "laa-speculate-unit-stride", cl::Hidden, 142*fe013be4SDimitry Andric cl::desc("Speculate that non-constant strides are unit in LAA"), 143*fe013be4SDimitry Andric cl::init(true)); 144*fe013be4SDimitry Andric 1450b57cec5SDimitry Andric bool VectorizerParams::isInterleaveForced() { 1460b57cec5SDimitry Andric return ::VectorizationInterleave.getNumOccurrences() > 0; 1470b57cec5SDimitry Andric } 1480b57cec5SDimitry Andric 1490b57cec5SDimitry Andric const SCEV *llvm::replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE, 150*fe013be4SDimitry Andric const DenseMap<Value *, const SCEV *> &PtrToStride, 151349cc55cSDimitry Andric Value *Ptr) { 1520b57cec5SDimitry Andric const SCEV *OrigSCEV = PSE.getSCEV(Ptr); 1530b57cec5SDimitry Andric 1540b57cec5SDimitry Andric // If there is an entry in the map return the SCEV of the pointer with the 1550b57cec5SDimitry Andric // symbolic stride replaced by one. 156*fe013be4SDimitry Andric DenseMap<Value *, const SCEV *>::const_iterator SI = PtrToStride.find(Ptr); 157e8d8bef9SDimitry Andric if (SI == PtrToStride.end()) 158e8d8bef9SDimitry Andric // For a non-symbolic stride, just return the original expression. 159e8d8bef9SDimitry Andric return OrigSCEV; 1600b57cec5SDimitry Andric 161*fe013be4SDimitry Andric const SCEV *StrideSCEV = SI->second; 162*fe013be4SDimitry Andric // Note: This assert is both overly strong and overly weak. The actual 163*fe013be4SDimitry Andric // invariant here is that StrideSCEV should be loop invariant. The only 164*fe013be4SDimitry Andric // such invariant strides we happen to speculate right now are unknowns 165*fe013be4SDimitry Andric // and thus this is a reasonable proxy of the actual invariant. 166*fe013be4SDimitry Andric assert(isa<SCEVUnknown>(StrideSCEV) && "shouldn't be in map"); 1670b57cec5SDimitry Andric 1680b57cec5SDimitry Andric ScalarEvolution *SE = PSE.getSE(); 169*fe013be4SDimitry Andric const auto *CT = SE->getOne(StrideSCEV->getType()); 170*fe013be4SDimitry Andric PSE.addPredicate(*SE->getEqualPredicate(StrideSCEV, CT)); 1710b57cec5SDimitry Andric auto *Expr = PSE.getSCEV(Ptr); 1720b57cec5SDimitry Andric 1730b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV 1740b57cec5SDimitry Andric << " by: " << *Expr << "\n"); 1750b57cec5SDimitry Andric return Expr; 1760b57cec5SDimitry Andric } 1770b57cec5SDimitry Andric 1785ffd83dbSDimitry Andric RuntimeCheckingPtrGroup::RuntimeCheckingPtrGroup( 1795ffd83dbSDimitry Andric unsigned Index, RuntimePointerChecking &RtCheck) 180fe6060f1SDimitry Andric : High(RtCheck.Pointers[Index].End), Low(RtCheck.Pointers[Index].Start), 181fe6060f1SDimitry Andric AddressSpace(RtCheck.Pointers[Index] 182fe6060f1SDimitry Andric .PointerValue->getType() 18381ad6265SDimitry Andric ->getPointerAddressSpace()), 18481ad6265SDimitry Andric NeedsFreeze(RtCheck.Pointers[Index].NeedsFreeze) { 1855ffd83dbSDimitry Andric Members.push_back(Index); 1865ffd83dbSDimitry Andric } 1875ffd83dbSDimitry Andric 1880b57cec5SDimitry Andric /// Calculate Start and End points of memory access. 1890b57cec5SDimitry Andric /// Let's assume A is the first access and B is a memory access on N-th loop 1900b57cec5SDimitry Andric /// iteration. Then B is calculated as: 1910b57cec5SDimitry Andric /// B = A + Step*N . 1920b57cec5SDimitry Andric /// Step value may be positive or negative. 1930b57cec5SDimitry Andric /// N is a calculated back-edge taken count: 1940b57cec5SDimitry Andric /// N = (TripCount > 0) ? RoundDown(TripCount -1 , VF) : 0 1950b57cec5SDimitry Andric /// Start and End points are calculated in the following way: 1960b57cec5SDimitry Andric /// Start = UMIN(A, B) ; End = UMAX(A, B) + SizeOfElt, 1970b57cec5SDimitry Andric /// where SizeOfElt is the size of single memory access in bytes. 1980b57cec5SDimitry Andric /// 1990b57cec5SDimitry Andric /// There is no conflict when the intervals are disjoint: 2000b57cec5SDimitry Andric /// NoConflict = (P2.Start >= P1.End) || (P1.Start >= P2.End) 20181ad6265SDimitry Andric void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, const SCEV *PtrExpr, 20281ad6265SDimitry Andric Type *AccessTy, bool WritePtr, 2030b57cec5SDimitry Andric unsigned DepSetId, unsigned ASId, 20481ad6265SDimitry Andric PredicatedScalarEvolution &PSE, 20581ad6265SDimitry Andric bool NeedsFreeze) { 2060b57cec5SDimitry Andric ScalarEvolution *SE = PSE.getSE(); 2070b57cec5SDimitry Andric 2080b57cec5SDimitry Andric const SCEV *ScStart; 2090b57cec5SDimitry Andric const SCEV *ScEnd; 2100b57cec5SDimitry Andric 21181ad6265SDimitry Andric if (SE->isLoopInvariant(PtrExpr, Lp)) { 21281ad6265SDimitry Andric ScStart = ScEnd = PtrExpr; 213fe6060f1SDimitry Andric } else { 21481ad6265SDimitry Andric const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrExpr); 2150b57cec5SDimitry Andric assert(AR && "Invalid addrec expression"); 2160b57cec5SDimitry Andric const SCEV *Ex = PSE.getBackedgeTakenCount(); 2170b57cec5SDimitry Andric 2180b57cec5SDimitry Andric ScStart = AR->getStart(); 2190b57cec5SDimitry Andric ScEnd = AR->evaluateAtIteration(Ex, *SE); 2200b57cec5SDimitry Andric const SCEV *Step = AR->getStepRecurrence(*SE); 2210b57cec5SDimitry Andric 2220b57cec5SDimitry Andric // For expressions with negative step, the upper bound is ScStart and the 2230b57cec5SDimitry Andric // lower bound is ScEnd. 2240b57cec5SDimitry Andric if (const auto *CStep = dyn_cast<SCEVConstant>(Step)) { 2250b57cec5SDimitry Andric if (CStep->getValue()->isNegative()) 2260b57cec5SDimitry Andric std::swap(ScStart, ScEnd); 2270b57cec5SDimitry Andric } else { 2280b57cec5SDimitry Andric // Fallback case: the step is not constant, but we can still 2290b57cec5SDimitry Andric // get the upper and lower bounds of the interval by using min/max 2300b57cec5SDimitry Andric // expressions. 2310b57cec5SDimitry Andric ScStart = SE->getUMinExpr(ScStart, ScEnd); 2320b57cec5SDimitry Andric ScEnd = SE->getUMaxExpr(AR->getStart(), ScEnd); 2330b57cec5SDimitry Andric } 234fe6060f1SDimitry Andric } 235*fe013be4SDimitry Andric assert(SE->isLoopInvariant(ScStart, Lp) && "ScStart needs to be invariant"); 236*fe013be4SDimitry Andric assert(SE->isLoopInvariant(ScEnd, Lp)&& "ScEnd needs to be invariant"); 237*fe013be4SDimitry Andric 2380b57cec5SDimitry Andric // Add the size of the pointed element to ScEnd. 239e8d8bef9SDimitry Andric auto &DL = Lp->getHeader()->getModule()->getDataLayout(); 240e8d8bef9SDimitry Andric Type *IdxTy = DL.getIndexType(Ptr->getType()); 24181ad6265SDimitry Andric const SCEV *EltSizeSCEV = SE->getStoreSizeOfExpr(IdxTy, AccessTy); 2420b57cec5SDimitry Andric ScEnd = SE->getAddExpr(ScEnd, EltSizeSCEV); 2430b57cec5SDimitry Andric 24481ad6265SDimitry Andric Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, PtrExpr, 24581ad6265SDimitry Andric NeedsFreeze); 2460b57cec5SDimitry Andric } 2470b57cec5SDimitry Andric 24881ad6265SDimitry Andric void RuntimePointerChecking::tryToCreateDiffCheck( 24981ad6265SDimitry Andric const RuntimeCheckingPtrGroup &CGI, const RuntimeCheckingPtrGroup &CGJ) { 25081ad6265SDimitry Andric if (!CanUseDiffCheck) 25181ad6265SDimitry Andric return; 25281ad6265SDimitry Andric 25381ad6265SDimitry Andric // If either group contains multiple different pointers, bail out. 25481ad6265SDimitry Andric // TODO: Support multiple pointers by using the minimum or maximum pointer, 25581ad6265SDimitry Andric // depending on src & sink. 25681ad6265SDimitry Andric if (CGI.Members.size() != 1 || CGJ.Members.size() != 1) { 25781ad6265SDimitry Andric CanUseDiffCheck = false; 25881ad6265SDimitry Andric return; 25981ad6265SDimitry Andric } 26081ad6265SDimitry Andric 26181ad6265SDimitry Andric PointerInfo *Src = &Pointers[CGI.Members[0]]; 26281ad6265SDimitry Andric PointerInfo *Sink = &Pointers[CGJ.Members[0]]; 26381ad6265SDimitry Andric 26481ad6265SDimitry Andric // If either pointer is read and written, multiple checks may be needed. Bail 26581ad6265SDimitry Andric // out. 26681ad6265SDimitry Andric if (!DC.getOrderForAccess(Src->PointerValue, !Src->IsWritePtr).empty() || 26781ad6265SDimitry Andric !DC.getOrderForAccess(Sink->PointerValue, !Sink->IsWritePtr).empty()) { 26881ad6265SDimitry Andric CanUseDiffCheck = false; 26981ad6265SDimitry Andric return; 27081ad6265SDimitry Andric } 27181ad6265SDimitry Andric 27281ad6265SDimitry Andric ArrayRef<unsigned> AccSrc = 27381ad6265SDimitry Andric DC.getOrderForAccess(Src->PointerValue, Src->IsWritePtr); 27481ad6265SDimitry Andric ArrayRef<unsigned> AccSink = 27581ad6265SDimitry Andric DC.getOrderForAccess(Sink->PointerValue, Sink->IsWritePtr); 27681ad6265SDimitry Andric // If either pointer is accessed multiple times, there may not be a clear 27781ad6265SDimitry Andric // src/sink relation. Bail out for now. 27881ad6265SDimitry Andric if (AccSrc.size() != 1 || AccSink.size() != 1) { 27981ad6265SDimitry Andric CanUseDiffCheck = false; 28081ad6265SDimitry Andric return; 28181ad6265SDimitry Andric } 28281ad6265SDimitry Andric // If the sink is accessed before src, swap src/sink. 28381ad6265SDimitry Andric if (AccSink[0] < AccSrc[0]) 28481ad6265SDimitry Andric std::swap(Src, Sink); 28581ad6265SDimitry Andric 28681ad6265SDimitry Andric auto *SrcAR = dyn_cast<SCEVAddRecExpr>(Src->Expr); 28781ad6265SDimitry Andric auto *SinkAR = dyn_cast<SCEVAddRecExpr>(Sink->Expr); 288a4a491e2SDimitry Andric if (!SrcAR || !SinkAR || SrcAR->getLoop() != DC.getInnermostLoop() || 289a4a491e2SDimitry Andric SinkAR->getLoop() != DC.getInnermostLoop()) { 29081ad6265SDimitry Andric CanUseDiffCheck = false; 29181ad6265SDimitry Andric return; 29281ad6265SDimitry Andric } 29381ad6265SDimitry Andric 29481ad6265SDimitry Andric SmallVector<Instruction *, 4> SrcInsts = 29581ad6265SDimitry Andric DC.getInstructionsForAccess(Src->PointerValue, Src->IsWritePtr); 29681ad6265SDimitry Andric SmallVector<Instruction *, 4> SinkInsts = 29781ad6265SDimitry Andric DC.getInstructionsForAccess(Sink->PointerValue, Sink->IsWritePtr); 29881ad6265SDimitry Andric Type *SrcTy = getLoadStoreType(SrcInsts[0]); 29981ad6265SDimitry Andric Type *DstTy = getLoadStoreType(SinkInsts[0]); 300fcaf7f86SDimitry Andric if (isa<ScalableVectorType>(SrcTy) || isa<ScalableVectorType>(DstTy)) { 301fcaf7f86SDimitry Andric CanUseDiffCheck = false; 30281ad6265SDimitry Andric return; 303fcaf7f86SDimitry Andric } 304bdd1243dSDimitry Andric const DataLayout &DL = 305bdd1243dSDimitry Andric SinkAR->getLoop()->getHeader()->getModule()->getDataLayout(); 30681ad6265SDimitry Andric unsigned AllocSize = 30781ad6265SDimitry Andric std::max(DL.getTypeAllocSize(SrcTy), DL.getTypeAllocSize(DstTy)); 30881ad6265SDimitry Andric 30981ad6265SDimitry Andric // Only matching constant steps matching the AllocSize are supported at the 31081ad6265SDimitry Andric // moment. This simplifies the difference computation. Can be extended in the 31181ad6265SDimitry Andric // future. 31281ad6265SDimitry Andric auto *Step = dyn_cast<SCEVConstant>(SinkAR->getStepRecurrence(*SE)); 31381ad6265SDimitry Andric if (!Step || Step != SrcAR->getStepRecurrence(*SE) || 31481ad6265SDimitry Andric Step->getAPInt().abs() != AllocSize) { 31581ad6265SDimitry Andric CanUseDiffCheck = false; 31681ad6265SDimitry Andric return; 31781ad6265SDimitry Andric } 31881ad6265SDimitry Andric 319bdd1243dSDimitry Andric IntegerType *IntTy = 320bdd1243dSDimitry Andric IntegerType::get(Src->PointerValue->getContext(), 321bdd1243dSDimitry Andric DL.getPointerSizeInBits(CGI.AddressSpace)); 322bdd1243dSDimitry Andric 32381ad6265SDimitry Andric // When counting down, the dependence distance needs to be swapped. 32481ad6265SDimitry Andric if (Step->getValue()->isNegative()) 32581ad6265SDimitry Andric std::swap(SinkAR, SrcAR); 32681ad6265SDimitry Andric 32781ad6265SDimitry Andric const SCEV *SinkStartInt = SE->getPtrToIntExpr(SinkAR->getStart(), IntTy); 32881ad6265SDimitry Andric const SCEV *SrcStartInt = SE->getPtrToIntExpr(SrcAR->getStart(), IntTy); 32981ad6265SDimitry Andric if (isa<SCEVCouldNotCompute>(SinkStartInt) || 33081ad6265SDimitry Andric isa<SCEVCouldNotCompute>(SrcStartInt)) { 33181ad6265SDimitry Andric CanUseDiffCheck = false; 33281ad6265SDimitry Andric return; 33381ad6265SDimitry Andric } 33481ad6265SDimitry Andric DiffChecks.emplace_back(SrcStartInt, SinkStartInt, AllocSize, 33581ad6265SDimitry Andric Src->NeedsFreeze || Sink->NeedsFreeze); 33681ad6265SDimitry Andric } 33781ad6265SDimitry Andric 33881ad6265SDimitry Andric SmallVector<RuntimePointerCheck, 4> RuntimePointerChecking::generateChecks() { 3395ffd83dbSDimitry Andric SmallVector<RuntimePointerCheck, 4> Checks; 3400b57cec5SDimitry Andric 3410b57cec5SDimitry Andric for (unsigned I = 0; I < CheckingGroups.size(); ++I) { 3420b57cec5SDimitry Andric for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) { 3435ffd83dbSDimitry Andric const RuntimeCheckingPtrGroup &CGI = CheckingGroups[I]; 3445ffd83dbSDimitry Andric const RuntimeCheckingPtrGroup &CGJ = CheckingGroups[J]; 3450b57cec5SDimitry Andric 34681ad6265SDimitry Andric if (needsChecking(CGI, CGJ)) { 34781ad6265SDimitry Andric tryToCreateDiffCheck(CGI, CGJ); 3480b57cec5SDimitry Andric Checks.push_back(std::make_pair(&CGI, &CGJ)); 3490b57cec5SDimitry Andric } 3500b57cec5SDimitry Andric } 35181ad6265SDimitry Andric } 3520b57cec5SDimitry Andric return Checks; 3530b57cec5SDimitry Andric } 3540b57cec5SDimitry Andric 3550b57cec5SDimitry Andric void RuntimePointerChecking::generateChecks( 3560b57cec5SDimitry Andric MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) { 3570b57cec5SDimitry Andric assert(Checks.empty() && "Checks is not empty"); 3580b57cec5SDimitry Andric groupChecks(DepCands, UseDependencies); 3590b57cec5SDimitry Andric Checks = generateChecks(); 3600b57cec5SDimitry Andric } 3610b57cec5SDimitry Andric 3625ffd83dbSDimitry Andric bool RuntimePointerChecking::needsChecking( 3635ffd83dbSDimitry Andric const RuntimeCheckingPtrGroup &M, const RuntimeCheckingPtrGroup &N) const { 3640b57cec5SDimitry Andric for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I) 3650b57cec5SDimitry Andric for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J) 3660b57cec5SDimitry Andric if (needsChecking(M.Members[I], N.Members[J])) 3670b57cec5SDimitry Andric return true; 3680b57cec5SDimitry Andric return false; 3690b57cec5SDimitry Andric } 3700b57cec5SDimitry Andric 3710b57cec5SDimitry Andric /// Compare \p I and \p J and return the minimum. 3720b57cec5SDimitry Andric /// Return nullptr in case we couldn't find an answer. 3730b57cec5SDimitry Andric static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J, 3740b57cec5SDimitry Andric ScalarEvolution *SE) { 3750b57cec5SDimitry Andric const SCEV *Diff = SE->getMinusSCEV(J, I); 3760b57cec5SDimitry Andric const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff); 3770b57cec5SDimitry Andric 3780b57cec5SDimitry Andric if (!C) 3790b57cec5SDimitry Andric return nullptr; 3800b57cec5SDimitry Andric if (C->getValue()->isNegative()) 3810b57cec5SDimitry Andric return J; 3820b57cec5SDimitry Andric return I; 3830b57cec5SDimitry Andric } 3840b57cec5SDimitry Andric 385fe6060f1SDimitry Andric bool RuntimeCheckingPtrGroup::addPointer(unsigned Index, 386fe6060f1SDimitry Andric RuntimePointerChecking &RtCheck) { 387fe6060f1SDimitry Andric return addPointer( 388fe6060f1SDimitry Andric Index, RtCheck.Pointers[Index].Start, RtCheck.Pointers[Index].End, 389fe6060f1SDimitry Andric RtCheck.Pointers[Index].PointerValue->getType()->getPointerAddressSpace(), 39081ad6265SDimitry Andric RtCheck.Pointers[Index].NeedsFreeze, *RtCheck.SE); 391fe6060f1SDimitry Andric } 392fe6060f1SDimitry Andric 393fe6060f1SDimitry Andric bool RuntimeCheckingPtrGroup::addPointer(unsigned Index, const SCEV *Start, 394fe6060f1SDimitry Andric const SCEV *End, unsigned AS, 39581ad6265SDimitry Andric bool NeedsFreeze, 396fe6060f1SDimitry Andric ScalarEvolution &SE) { 397fe6060f1SDimitry Andric assert(AddressSpace == AS && 398fe6060f1SDimitry Andric "all pointers in a checking group must be in the same address space"); 3990b57cec5SDimitry Andric 4000b57cec5SDimitry Andric // Compare the starts and ends with the known minimum and maximum 4010b57cec5SDimitry Andric // of this set. We need to know how we compare against the min/max 4020b57cec5SDimitry Andric // of the set in order to be able to emit memchecks. 403fe6060f1SDimitry Andric const SCEV *Min0 = getMinFromExprs(Start, Low, &SE); 4040b57cec5SDimitry Andric if (!Min0) 4050b57cec5SDimitry Andric return false; 4060b57cec5SDimitry Andric 407fe6060f1SDimitry Andric const SCEV *Min1 = getMinFromExprs(End, High, &SE); 4080b57cec5SDimitry Andric if (!Min1) 4090b57cec5SDimitry Andric return false; 4100b57cec5SDimitry Andric 4110b57cec5SDimitry Andric // Update the low bound expression if we've found a new min value. 4120b57cec5SDimitry Andric if (Min0 == Start) 4130b57cec5SDimitry Andric Low = Start; 4140b57cec5SDimitry Andric 4150b57cec5SDimitry Andric // Update the high bound expression if we've found a new max value. 4160b57cec5SDimitry Andric if (Min1 != End) 4170b57cec5SDimitry Andric High = End; 4180b57cec5SDimitry Andric 4190b57cec5SDimitry Andric Members.push_back(Index); 42081ad6265SDimitry Andric this->NeedsFreeze |= NeedsFreeze; 4210b57cec5SDimitry Andric return true; 4220b57cec5SDimitry Andric } 4230b57cec5SDimitry Andric 4240b57cec5SDimitry Andric void RuntimePointerChecking::groupChecks( 4250b57cec5SDimitry Andric MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) { 4260b57cec5SDimitry Andric // We build the groups from dependency candidates equivalence classes 4270b57cec5SDimitry Andric // because: 4280b57cec5SDimitry Andric // - We know that pointers in the same equivalence class share 4290b57cec5SDimitry Andric // the same underlying object and therefore there is a chance 4300b57cec5SDimitry Andric // that we can compare pointers 4310b57cec5SDimitry Andric // - We wouldn't be able to merge two pointers for which we need 4320b57cec5SDimitry Andric // to emit a memcheck. The classes in DepCands are already 4330b57cec5SDimitry Andric // conveniently built such that no two pointers in the same 4340b57cec5SDimitry Andric // class need checking against each other. 4350b57cec5SDimitry Andric 4360b57cec5SDimitry Andric // We use the following (greedy) algorithm to construct the groups 4370b57cec5SDimitry Andric // For every pointer in the equivalence class: 4380b57cec5SDimitry Andric // For each existing group: 4390b57cec5SDimitry Andric // - if the difference between this pointer and the min/max bounds 4400b57cec5SDimitry Andric // of the group is a constant, then make the pointer part of the 4410b57cec5SDimitry Andric // group and update the min/max bounds of that group as required. 4420b57cec5SDimitry Andric 4430b57cec5SDimitry Andric CheckingGroups.clear(); 4440b57cec5SDimitry Andric 4450b57cec5SDimitry Andric // If we need to check two pointers to the same underlying object 4460b57cec5SDimitry Andric // with a non-constant difference, we shouldn't perform any pointer 4470b57cec5SDimitry Andric // grouping with those pointers. This is because we can easily get 4480b57cec5SDimitry Andric // into cases where the resulting check would return false, even when 4490b57cec5SDimitry Andric // the accesses are safe. 4500b57cec5SDimitry Andric // 4510b57cec5SDimitry Andric // The following example shows this: 4520b57cec5SDimitry Andric // for (i = 0; i < 1000; ++i) 4530b57cec5SDimitry Andric // a[5000 + i * m] = a[i] + a[i + 9000] 4540b57cec5SDimitry Andric // 4550b57cec5SDimitry Andric // Here grouping gives a check of (5000, 5000 + 1000 * m) against 4560b57cec5SDimitry Andric // (0, 10000) which is always false. However, if m is 1, there is no 4570b57cec5SDimitry Andric // dependence. Not grouping the checks for a[i] and a[i + 9000] allows 4580b57cec5SDimitry Andric // us to perform an accurate check in this case. 4590b57cec5SDimitry Andric // 4600b57cec5SDimitry Andric // The above case requires that we have an UnknownDependence between 4610b57cec5SDimitry Andric // accesses to the same underlying object. This cannot happen unless 4620b57cec5SDimitry Andric // FoundNonConstantDistanceDependence is set, and therefore UseDependencies 4630b57cec5SDimitry Andric // is also false. In this case we will use the fallback path and create 4640b57cec5SDimitry Andric // separate checking groups for all pointers. 4650b57cec5SDimitry Andric 4660b57cec5SDimitry Andric // If we don't have the dependency partitions, construct a new 4670b57cec5SDimitry Andric // checking pointer group for each pointer. This is also required 4680b57cec5SDimitry Andric // for correctness, because in this case we can have checking between 4690b57cec5SDimitry Andric // pointers to the same underlying object. 4700b57cec5SDimitry Andric if (!UseDependencies) { 4710b57cec5SDimitry Andric for (unsigned I = 0; I < Pointers.size(); ++I) 4725ffd83dbSDimitry Andric CheckingGroups.push_back(RuntimeCheckingPtrGroup(I, *this)); 4730b57cec5SDimitry Andric return; 4740b57cec5SDimitry Andric } 4750b57cec5SDimitry Andric 4760b57cec5SDimitry Andric unsigned TotalComparisons = 0; 4770b57cec5SDimitry Andric 47881ad6265SDimitry Andric DenseMap<Value *, SmallVector<unsigned>> PositionMap; 47981ad6265SDimitry Andric for (unsigned Index = 0; Index < Pointers.size(); ++Index) { 48081ad6265SDimitry Andric auto Iter = PositionMap.insert({Pointers[Index].PointerValue, {}}); 48181ad6265SDimitry Andric Iter.first->second.push_back(Index); 48281ad6265SDimitry Andric } 4830b57cec5SDimitry Andric 4840b57cec5SDimitry Andric // We need to keep track of what pointers we've already seen so we 4850b57cec5SDimitry Andric // don't process them twice. 4860b57cec5SDimitry Andric SmallSet<unsigned, 2> Seen; 4870b57cec5SDimitry Andric 4880b57cec5SDimitry Andric // Go through all equivalence classes, get the "pointer check groups" 4890b57cec5SDimitry Andric // and add them to the overall solution. We use the order in which accesses 4900b57cec5SDimitry Andric // appear in 'Pointers' to enforce determinism. 4910b57cec5SDimitry Andric for (unsigned I = 0; I < Pointers.size(); ++I) { 4920b57cec5SDimitry Andric // We've seen this pointer before, and therefore already processed 4930b57cec5SDimitry Andric // its equivalence class. 4940b57cec5SDimitry Andric if (Seen.count(I)) 4950b57cec5SDimitry Andric continue; 4960b57cec5SDimitry Andric 4970b57cec5SDimitry Andric MemoryDepChecker::MemAccessInfo Access(Pointers[I].PointerValue, 4980b57cec5SDimitry Andric Pointers[I].IsWritePtr); 4990b57cec5SDimitry Andric 5005ffd83dbSDimitry Andric SmallVector<RuntimeCheckingPtrGroup, 2> Groups; 5010b57cec5SDimitry Andric auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access)); 5020b57cec5SDimitry Andric 5030b57cec5SDimitry Andric // Because DepCands is constructed by visiting accesses in the order in 5040b57cec5SDimitry Andric // which they appear in alias sets (which is deterministic) and the 5050b57cec5SDimitry Andric // iteration order within an equivalence class member is only dependent on 5060b57cec5SDimitry Andric // the order in which unions and insertions are performed on the 5070b57cec5SDimitry Andric // equivalence class, the iteration order is deterministic. 5080b57cec5SDimitry Andric for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end(); 5090b57cec5SDimitry Andric MI != ME; ++MI) { 5101106035dSDimitry Andric auto PointerI = PositionMap.find(MI->getPointer()); 5111106035dSDimitry Andric assert(PointerI != PositionMap.end() && 5121106035dSDimitry Andric "pointer in equivalence class not found in PositionMap"); 51381ad6265SDimitry Andric for (unsigned Pointer : PointerI->second) { 5140b57cec5SDimitry Andric bool Merged = false; 5150b57cec5SDimitry Andric // Mark this pointer as seen. 5160b57cec5SDimitry Andric Seen.insert(Pointer); 5170b57cec5SDimitry Andric 5180b57cec5SDimitry Andric // Go through all the existing sets and see if we can find one 5190b57cec5SDimitry Andric // which can include this pointer. 5205ffd83dbSDimitry Andric for (RuntimeCheckingPtrGroup &Group : Groups) { 5210b57cec5SDimitry Andric // Don't perform more than a certain amount of comparisons. 5220b57cec5SDimitry Andric // This should limit the cost of grouping the pointers to something 5230b57cec5SDimitry Andric // reasonable. If we do end up hitting this threshold, the algorithm 5240b57cec5SDimitry Andric // will create separate groups for all remaining pointers. 5250b57cec5SDimitry Andric if (TotalComparisons > MemoryCheckMergeThreshold) 5260b57cec5SDimitry Andric break; 5270b57cec5SDimitry Andric 5280b57cec5SDimitry Andric TotalComparisons++; 5290b57cec5SDimitry Andric 530fe6060f1SDimitry Andric if (Group.addPointer(Pointer, *this)) { 5310b57cec5SDimitry Andric Merged = true; 5320b57cec5SDimitry Andric break; 5330b57cec5SDimitry Andric } 5340b57cec5SDimitry Andric } 5350b57cec5SDimitry Andric 5360b57cec5SDimitry Andric if (!Merged) 5370b57cec5SDimitry Andric // We couldn't add this pointer to any existing set or the threshold 5380b57cec5SDimitry Andric // for the number of comparisons has been reached. Create a new group 5390b57cec5SDimitry Andric // to hold the current pointer. 5405ffd83dbSDimitry Andric Groups.push_back(RuntimeCheckingPtrGroup(Pointer, *this)); 5410b57cec5SDimitry Andric } 54281ad6265SDimitry Andric } 5430b57cec5SDimitry Andric 5440b57cec5SDimitry Andric // We've computed the grouped checks for this partition. 5450b57cec5SDimitry Andric // Save the results and continue with the next one. 5460b57cec5SDimitry Andric llvm::copy(Groups, std::back_inserter(CheckingGroups)); 5470b57cec5SDimitry Andric } 5480b57cec5SDimitry Andric } 5490b57cec5SDimitry Andric 5500b57cec5SDimitry Andric bool RuntimePointerChecking::arePointersInSamePartition( 5510b57cec5SDimitry Andric const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1, 5520b57cec5SDimitry Andric unsigned PtrIdx2) { 5530b57cec5SDimitry Andric return (PtrToPartition[PtrIdx1] != -1 && 5540b57cec5SDimitry Andric PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]); 5550b57cec5SDimitry Andric } 5560b57cec5SDimitry Andric 5570b57cec5SDimitry Andric bool RuntimePointerChecking::needsChecking(unsigned I, unsigned J) const { 5580b57cec5SDimitry Andric const PointerInfo &PointerI = Pointers[I]; 5590b57cec5SDimitry Andric const PointerInfo &PointerJ = Pointers[J]; 5600b57cec5SDimitry Andric 5610b57cec5SDimitry Andric // No need to check if two readonly pointers intersect. 5620b57cec5SDimitry Andric if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr) 5630b57cec5SDimitry Andric return false; 5640b57cec5SDimitry Andric 5650b57cec5SDimitry Andric // Only need to check pointers between two different dependency sets. 5660b57cec5SDimitry Andric if (PointerI.DependencySetId == PointerJ.DependencySetId) 5670b57cec5SDimitry Andric return false; 5680b57cec5SDimitry Andric 5690b57cec5SDimitry Andric // Only need to check pointers in the same alias set. 5700b57cec5SDimitry Andric if (PointerI.AliasSetId != PointerJ.AliasSetId) 5710b57cec5SDimitry Andric return false; 5720b57cec5SDimitry Andric 5730b57cec5SDimitry Andric return true; 5740b57cec5SDimitry Andric } 5750b57cec5SDimitry Andric 5760b57cec5SDimitry Andric void RuntimePointerChecking::printChecks( 5775ffd83dbSDimitry Andric raw_ostream &OS, const SmallVectorImpl<RuntimePointerCheck> &Checks, 5780b57cec5SDimitry Andric unsigned Depth) const { 5790b57cec5SDimitry Andric unsigned N = 0; 5800b57cec5SDimitry Andric for (const auto &Check : Checks) { 5810b57cec5SDimitry Andric const auto &First = Check.first->Members, &Second = Check.second->Members; 5820b57cec5SDimitry Andric 5830b57cec5SDimitry Andric OS.indent(Depth) << "Check " << N++ << ":\n"; 5840b57cec5SDimitry Andric 5850b57cec5SDimitry Andric OS.indent(Depth + 2) << "Comparing group (" << Check.first << "):\n"; 5860b57cec5SDimitry Andric for (unsigned K = 0; K < First.size(); ++K) 5870b57cec5SDimitry Andric OS.indent(Depth + 2) << *Pointers[First[K]].PointerValue << "\n"; 5880b57cec5SDimitry Andric 5890b57cec5SDimitry Andric OS.indent(Depth + 2) << "Against group (" << Check.second << "):\n"; 5900b57cec5SDimitry Andric for (unsigned K = 0; K < Second.size(); ++K) 5910b57cec5SDimitry Andric OS.indent(Depth + 2) << *Pointers[Second[K]].PointerValue << "\n"; 5920b57cec5SDimitry Andric } 5930b57cec5SDimitry Andric } 5940b57cec5SDimitry Andric 5950b57cec5SDimitry Andric void RuntimePointerChecking::print(raw_ostream &OS, unsigned Depth) const { 5960b57cec5SDimitry Andric 5970b57cec5SDimitry Andric OS.indent(Depth) << "Run-time memory checks:\n"; 5980b57cec5SDimitry Andric printChecks(OS, Checks, Depth); 5990b57cec5SDimitry Andric 6000b57cec5SDimitry Andric OS.indent(Depth) << "Grouped accesses:\n"; 6010b57cec5SDimitry Andric for (unsigned I = 0; I < CheckingGroups.size(); ++I) { 6020b57cec5SDimitry Andric const auto &CG = CheckingGroups[I]; 6030b57cec5SDimitry Andric 6040b57cec5SDimitry Andric OS.indent(Depth + 2) << "Group " << &CG << ":\n"; 6050b57cec5SDimitry Andric OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High 6060b57cec5SDimitry Andric << ")\n"; 6070b57cec5SDimitry Andric for (unsigned J = 0; J < CG.Members.size(); ++J) { 6080b57cec5SDimitry Andric OS.indent(Depth + 6) << "Member: " << *Pointers[CG.Members[J]].Expr 6090b57cec5SDimitry Andric << "\n"; 6100b57cec5SDimitry Andric } 6110b57cec5SDimitry Andric } 6120b57cec5SDimitry Andric } 6130b57cec5SDimitry Andric 6140b57cec5SDimitry Andric namespace { 6150b57cec5SDimitry Andric 6160b57cec5SDimitry Andric /// Analyses memory accesses in a loop. 6170b57cec5SDimitry Andric /// 6180b57cec5SDimitry Andric /// Checks whether run time pointer checks are needed and builds sets for data 6190b57cec5SDimitry Andric /// dependence checking. 6200b57cec5SDimitry Andric class AccessAnalysis { 6210b57cec5SDimitry Andric public: 6220b57cec5SDimitry Andric /// Read or write access location. 6230b57cec5SDimitry Andric typedef PointerIntPair<Value *, 1, bool> MemAccessInfo; 6240b57cec5SDimitry Andric typedef SmallVector<MemAccessInfo, 8> MemAccessInfoList; 6250b57cec5SDimitry Andric 626e8d8bef9SDimitry Andric AccessAnalysis(Loop *TheLoop, AAResults *AA, LoopInfo *LI, 627e8d8bef9SDimitry Andric MemoryDepChecker::DepCandidates &DA, 6280b57cec5SDimitry Andric PredicatedScalarEvolution &PSE) 629bdd1243dSDimitry Andric : TheLoop(TheLoop), BAA(*AA), AST(BAA), LI(LI), DepCands(DA), PSE(PSE) { 630bdd1243dSDimitry Andric // We're analyzing dependences across loop iterations. 631bdd1243dSDimitry Andric BAA.enableCrossIterationMode(); 632bdd1243dSDimitry Andric } 6330b57cec5SDimitry Andric 6340b57cec5SDimitry Andric /// Register a load and whether it is only read from. 63581ad6265SDimitry Andric void addLoad(MemoryLocation &Loc, Type *AccessTy, bool IsReadOnly) { 6360b57cec5SDimitry Andric Value *Ptr = const_cast<Value*>(Loc.Ptr); 637e8d8bef9SDimitry Andric AST.add(Ptr, LocationSize::beforeOrAfterPointer(), Loc.AATags); 63881ad6265SDimitry Andric Accesses[MemAccessInfo(Ptr, false)].insert(AccessTy); 6390b57cec5SDimitry Andric if (IsReadOnly) 6400b57cec5SDimitry Andric ReadOnlyPtr.insert(Ptr); 6410b57cec5SDimitry Andric } 6420b57cec5SDimitry Andric 6430b57cec5SDimitry Andric /// Register a store. 64481ad6265SDimitry Andric void addStore(MemoryLocation &Loc, Type *AccessTy) { 6450b57cec5SDimitry Andric Value *Ptr = const_cast<Value*>(Loc.Ptr); 646e8d8bef9SDimitry Andric AST.add(Ptr, LocationSize::beforeOrAfterPointer(), Loc.AATags); 64781ad6265SDimitry Andric Accesses[MemAccessInfo(Ptr, true)].insert(AccessTy); 6480b57cec5SDimitry Andric } 6490b57cec5SDimitry Andric 6500b57cec5SDimitry Andric /// Check if we can emit a run-time no-alias check for \p Access. 6510b57cec5SDimitry Andric /// 6520b57cec5SDimitry Andric /// Returns true if we can emit a run-time no alias check for \p Access. 6530b57cec5SDimitry Andric /// If we can check this access, this also adds it to a dependence set and 6540b57cec5SDimitry Andric /// adds a run-time to check for it to \p RtCheck. If \p Assume is true, 6550b57cec5SDimitry Andric /// we will attempt to use additional run-time checks in order to get 6560b57cec5SDimitry Andric /// the bounds of the pointer. 6570b57cec5SDimitry Andric bool createCheckForAccess(RuntimePointerChecking &RtCheck, 65881ad6265SDimitry Andric MemAccessInfo Access, Type *AccessTy, 659*fe013be4SDimitry Andric const DenseMap<Value *, const SCEV *> &Strides, 6600b57cec5SDimitry Andric DenseMap<Value *, unsigned> &DepSetId, 6610b57cec5SDimitry Andric Loop *TheLoop, unsigned &RunningDepId, 66281ad6265SDimitry Andric unsigned ASId, bool ShouldCheckStride, bool Assume); 6630b57cec5SDimitry Andric 6640b57cec5SDimitry Andric /// Check whether we can check the pointers at runtime for 6650b57cec5SDimitry Andric /// non-intersection. 6660b57cec5SDimitry Andric /// 6670b57cec5SDimitry Andric /// Returns true if we need no check or if we do and we can generate them 6680b57cec5SDimitry Andric /// (i.e. the pointers have computable bounds). 6690b57cec5SDimitry Andric bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE, 670*fe013be4SDimitry Andric Loop *TheLoop, const DenseMap<Value *, const SCEV *> &Strides, 67181ad6265SDimitry Andric Value *&UncomputablePtr, bool ShouldCheckWrap = false); 6720b57cec5SDimitry Andric 6730b57cec5SDimitry Andric /// Goes over all memory accesses, checks whether a RT check is needed 6740b57cec5SDimitry Andric /// and builds sets of dependent accesses. 6750b57cec5SDimitry Andric void buildDependenceSets() { 6760b57cec5SDimitry Andric processMemAccesses(); 6770b57cec5SDimitry Andric } 6780b57cec5SDimitry Andric 6790b57cec5SDimitry Andric /// Initial processing of memory accesses determined that we need to 6800b57cec5SDimitry Andric /// perform dependency checking. 6810b57cec5SDimitry Andric /// 6820b57cec5SDimitry Andric /// Note that this can later be cleared if we retry memcheck analysis without 6830b57cec5SDimitry Andric /// dependency checking (i.e. FoundNonConstantDistanceDependence). 6840b57cec5SDimitry Andric bool isDependencyCheckNeeded() { return !CheckDeps.empty(); } 6850b57cec5SDimitry Andric 6860b57cec5SDimitry Andric /// We decided that no dependence analysis would be used. Reset the state. 6870b57cec5SDimitry Andric void resetDepChecks(MemoryDepChecker &DepChecker) { 6880b57cec5SDimitry Andric CheckDeps.clear(); 6890b57cec5SDimitry Andric DepChecker.clearDependences(); 6900b57cec5SDimitry Andric } 6910b57cec5SDimitry Andric 6920b57cec5SDimitry Andric MemAccessInfoList &getDependenciesToCheck() { return CheckDeps; } 6930b57cec5SDimitry Andric 6940b57cec5SDimitry Andric private: 69581ad6265SDimitry Andric typedef MapVector<MemAccessInfo, SmallSetVector<Type *, 1>> PtrAccessMap; 6960b57cec5SDimitry Andric 6970b57cec5SDimitry Andric /// Go over all memory access and check whether runtime pointer checks 6980b57cec5SDimitry Andric /// are needed and build sets of dependency check candidates. 6990b57cec5SDimitry Andric void processMemAccesses(); 7000b57cec5SDimitry Andric 70181ad6265SDimitry Andric /// Map of all accesses. Values are the types used to access memory pointed to 70281ad6265SDimitry Andric /// by the pointer. 70381ad6265SDimitry Andric PtrAccessMap Accesses; 7040b57cec5SDimitry Andric 7050b57cec5SDimitry Andric /// The loop being checked. 7060b57cec5SDimitry Andric const Loop *TheLoop; 7070b57cec5SDimitry Andric 7080b57cec5SDimitry Andric /// List of accesses that need a further dependence check. 7090b57cec5SDimitry Andric MemAccessInfoList CheckDeps; 7100b57cec5SDimitry Andric 7110b57cec5SDimitry Andric /// Set of pointers that are read only. 7120b57cec5SDimitry Andric SmallPtrSet<Value*, 16> ReadOnlyPtr; 7130b57cec5SDimitry Andric 714bdd1243dSDimitry Andric /// Batched alias analysis results. 715bdd1243dSDimitry Andric BatchAAResults BAA; 716bdd1243dSDimitry Andric 7170b57cec5SDimitry Andric /// An alias set tracker to partition the access set by underlying object and 7180b57cec5SDimitry Andric //intrinsic property (such as TBAA metadata). 7190b57cec5SDimitry Andric AliasSetTracker AST; 7200b57cec5SDimitry Andric 7210b57cec5SDimitry Andric LoopInfo *LI; 7220b57cec5SDimitry Andric 7230b57cec5SDimitry Andric /// Sets of potentially dependent accesses - members of one set share an 7240b57cec5SDimitry Andric /// underlying pointer. The set "CheckDeps" identfies which sets really need a 7250b57cec5SDimitry Andric /// dependence check. 7260b57cec5SDimitry Andric MemoryDepChecker::DepCandidates &DepCands; 7270b57cec5SDimitry Andric 7280b57cec5SDimitry Andric /// Initial processing of memory accesses determined that we may need 7290b57cec5SDimitry Andric /// to add memchecks. Perform the analysis to determine the necessary checks. 7300b57cec5SDimitry Andric /// 7310b57cec5SDimitry Andric /// Note that, this is different from isDependencyCheckNeeded. When we retry 7320b57cec5SDimitry Andric /// memcheck analysis without dependency checking 7330b57cec5SDimitry Andric /// (i.e. FoundNonConstantDistanceDependence), isDependencyCheckNeeded is 7340b57cec5SDimitry Andric /// cleared while this remains set if we have potentially dependent accesses. 73504eeddc0SDimitry Andric bool IsRTCheckAnalysisNeeded = false; 7360b57cec5SDimitry Andric 7370b57cec5SDimitry Andric /// The SCEV predicate containing all the SCEV-related assumptions. 7380b57cec5SDimitry Andric PredicatedScalarEvolution &PSE; 7390b57cec5SDimitry Andric }; 7400b57cec5SDimitry Andric 7410b57cec5SDimitry Andric } // end anonymous namespace 7420b57cec5SDimitry Andric 7430b57cec5SDimitry Andric /// Check whether a pointer can participate in a runtime bounds check. 7440b57cec5SDimitry Andric /// If \p Assume, try harder to prove that we can compute the bounds of \p Ptr 7450b57cec5SDimitry Andric /// by adding run-time checks (overflow checks) if necessary. 74681ad6265SDimitry Andric static bool hasComputableBounds(PredicatedScalarEvolution &PSE, Value *Ptr, 74781ad6265SDimitry Andric const SCEV *PtrScev, Loop *L, bool Assume) { 7480b57cec5SDimitry Andric // The bounds for loop-invariant pointer is trivial. 7490b57cec5SDimitry Andric if (PSE.getSE()->isLoopInvariant(PtrScev, L)) 7500b57cec5SDimitry Andric return true; 7510b57cec5SDimitry Andric 7520b57cec5SDimitry Andric const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev); 7530b57cec5SDimitry Andric 7540b57cec5SDimitry Andric if (!AR && Assume) 7550b57cec5SDimitry Andric AR = PSE.getAsAddRec(Ptr); 7560b57cec5SDimitry Andric 7570b57cec5SDimitry Andric if (!AR) 7580b57cec5SDimitry Andric return false; 7590b57cec5SDimitry Andric 7600b57cec5SDimitry Andric return AR->isAffine(); 7610b57cec5SDimitry Andric } 7620b57cec5SDimitry Andric 7630b57cec5SDimitry Andric /// Check whether a pointer address cannot wrap. 7640b57cec5SDimitry Andric static bool isNoWrap(PredicatedScalarEvolution &PSE, 765*fe013be4SDimitry Andric const DenseMap<Value *, const SCEV *> &Strides, Value *Ptr, Type *AccessTy, 76681ad6265SDimitry Andric Loop *L) { 7670b57cec5SDimitry Andric const SCEV *PtrScev = PSE.getSCEV(Ptr); 7680b57cec5SDimitry Andric if (PSE.getSE()->isLoopInvariant(PtrScev, L)) 7690b57cec5SDimitry Andric return true; 7700b57cec5SDimitry Andric 771bdd1243dSDimitry Andric int64_t Stride = getPtrStride(PSE, AccessTy, Ptr, L, Strides).value_or(0); 7720b57cec5SDimitry Andric if (Stride == 1 || PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW)) 7730b57cec5SDimitry Andric return true; 7740b57cec5SDimitry Andric 7750b57cec5SDimitry Andric return false; 7760b57cec5SDimitry Andric } 7770b57cec5SDimitry Andric 7784824e7fdSDimitry Andric static void visitPointers(Value *StartPtr, const Loop &InnermostLoop, 7794824e7fdSDimitry Andric function_ref<void(Value *)> AddPointer) { 7804824e7fdSDimitry Andric SmallPtrSet<Value *, 8> Visited; 7814824e7fdSDimitry Andric SmallVector<Value *> WorkList; 7824824e7fdSDimitry Andric WorkList.push_back(StartPtr); 7834824e7fdSDimitry Andric 7844824e7fdSDimitry Andric while (!WorkList.empty()) { 7854824e7fdSDimitry Andric Value *Ptr = WorkList.pop_back_val(); 7864824e7fdSDimitry Andric if (!Visited.insert(Ptr).second) 7874824e7fdSDimitry Andric continue; 7884824e7fdSDimitry Andric auto *PN = dyn_cast<PHINode>(Ptr); 7894824e7fdSDimitry Andric // SCEV does not look through non-header PHIs inside the loop. Such phis 7904824e7fdSDimitry Andric // can be analyzed by adding separate accesses for each incoming pointer 7914824e7fdSDimitry Andric // value. 7924824e7fdSDimitry Andric if (PN && InnermostLoop.contains(PN->getParent()) && 7934824e7fdSDimitry Andric PN->getParent() != InnermostLoop.getHeader()) { 7944824e7fdSDimitry Andric for (const Use &Inc : PN->incoming_values()) 7954824e7fdSDimitry Andric WorkList.push_back(Inc); 7964824e7fdSDimitry Andric } else 7974824e7fdSDimitry Andric AddPointer(Ptr); 7984824e7fdSDimitry Andric } 7994824e7fdSDimitry Andric } 8004824e7fdSDimitry Andric 801fcaf7f86SDimitry Andric // Walk back through the IR for a pointer, looking for a select like the 802fcaf7f86SDimitry Andric // following: 803fcaf7f86SDimitry Andric // 804fcaf7f86SDimitry Andric // %offset = select i1 %cmp, i64 %a, i64 %b 805fcaf7f86SDimitry Andric // %addr = getelementptr double, double* %base, i64 %offset 806fcaf7f86SDimitry Andric // %ld = load double, double* %addr, align 8 807fcaf7f86SDimitry Andric // 808fcaf7f86SDimitry Andric // We won't be able to form a single SCEVAddRecExpr from this since the 809fcaf7f86SDimitry Andric // address for each loop iteration depends on %cmp. We could potentially 810fcaf7f86SDimitry Andric // produce multiple valid SCEVAddRecExprs, though, and check all of them for 811fcaf7f86SDimitry Andric // memory safety/aliasing if needed. 812fcaf7f86SDimitry Andric // 813fcaf7f86SDimitry Andric // If we encounter some IR we don't yet handle, or something obviously fine 814fcaf7f86SDimitry Andric // like a constant, then we just add the SCEV for that term to the list passed 815fcaf7f86SDimitry Andric // in by the caller. If we have a node that may potentially yield a valid 816fcaf7f86SDimitry Andric // SCEVAddRecExpr then we decompose it into parts and build the SCEV terms 817fcaf7f86SDimitry Andric // ourselves before adding to the list. 818bdd1243dSDimitry Andric static void findForkedSCEVs( 819bdd1243dSDimitry Andric ScalarEvolution *SE, const Loop *L, Value *Ptr, 820bdd1243dSDimitry Andric SmallVectorImpl<PointerIntPair<const SCEV *, 1, bool>> &ScevList, 821fcaf7f86SDimitry Andric unsigned Depth) { 822fcaf7f86SDimitry Andric // If our Value is a SCEVAddRecExpr, loop invariant, not an instruction, or 823fcaf7f86SDimitry Andric // we've exceeded our limit on recursion, just return whatever we have 824fcaf7f86SDimitry Andric // regardless of whether it can be used for a forked pointer or not, along 825fcaf7f86SDimitry Andric // with an indication of whether it might be a poison or undef value. 826fcaf7f86SDimitry Andric const SCEV *Scev = SE->getSCEV(Ptr); 827fcaf7f86SDimitry Andric if (isa<SCEVAddRecExpr>(Scev) || L->isLoopInvariant(Ptr) || 828fcaf7f86SDimitry Andric !isa<Instruction>(Ptr) || Depth == 0) { 829bdd1243dSDimitry Andric ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr)); 830fcaf7f86SDimitry Andric return; 831fcaf7f86SDimitry Andric } 832fcaf7f86SDimitry Andric 833fcaf7f86SDimitry Andric Depth--; 834fcaf7f86SDimitry Andric 835bdd1243dSDimitry Andric auto UndefPoisonCheck = [](PointerIntPair<const SCEV *, 1, bool> S) { 836bdd1243dSDimitry Andric return get<1>(S); 837bdd1243dSDimitry Andric }; 838bdd1243dSDimitry Andric 839bdd1243dSDimitry Andric auto GetBinOpExpr = [&SE](unsigned Opcode, const SCEV *L, const SCEV *R) { 840bdd1243dSDimitry Andric switch (Opcode) { 841bdd1243dSDimitry Andric case Instruction::Add: 842bdd1243dSDimitry Andric return SE->getAddExpr(L, R); 843bdd1243dSDimitry Andric case Instruction::Sub: 844bdd1243dSDimitry Andric return SE->getMinusSCEV(L, R); 845bdd1243dSDimitry Andric default: 846bdd1243dSDimitry Andric llvm_unreachable("Unexpected binary operator when walking ForkedPtrs"); 847bdd1243dSDimitry Andric } 848fcaf7f86SDimitry Andric }; 849fcaf7f86SDimitry Andric 850fcaf7f86SDimitry Andric Instruction *I = cast<Instruction>(Ptr); 851fcaf7f86SDimitry Andric unsigned Opcode = I->getOpcode(); 852fcaf7f86SDimitry Andric switch (Opcode) { 853fcaf7f86SDimitry Andric case Instruction::GetElementPtr: { 854fcaf7f86SDimitry Andric GetElementPtrInst *GEP = cast<GetElementPtrInst>(I); 855fcaf7f86SDimitry Andric Type *SourceTy = GEP->getSourceElementType(); 856fcaf7f86SDimitry Andric // We only handle base + single offset GEPs here for now. 857fcaf7f86SDimitry Andric // Not dealing with preexisting gathers yet, so no vectors. 858fcaf7f86SDimitry Andric if (I->getNumOperands() != 2 || SourceTy->isVectorTy()) { 859bdd1243dSDimitry Andric ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(GEP)); 860fcaf7f86SDimitry Andric break; 861fcaf7f86SDimitry Andric } 862bdd1243dSDimitry Andric SmallVector<PointerIntPair<const SCEV *, 1, bool>, 2> BaseScevs; 863bdd1243dSDimitry Andric SmallVector<PointerIntPair<const SCEV *, 1, bool>, 2> OffsetScevs; 864fcaf7f86SDimitry Andric findForkedSCEVs(SE, L, I->getOperand(0), BaseScevs, Depth); 865fcaf7f86SDimitry Andric findForkedSCEVs(SE, L, I->getOperand(1), OffsetScevs, Depth); 866fcaf7f86SDimitry Andric 867fcaf7f86SDimitry Andric // See if we need to freeze our fork... 868fcaf7f86SDimitry Andric bool NeedsFreeze = any_of(BaseScevs, UndefPoisonCheck) || 869fcaf7f86SDimitry Andric any_of(OffsetScevs, UndefPoisonCheck); 870fcaf7f86SDimitry Andric 871fcaf7f86SDimitry Andric // Check that we only have a single fork, on either the base or the offset. 872fcaf7f86SDimitry Andric // Copy the SCEV across for the one without a fork in order to generate 873fcaf7f86SDimitry Andric // the full SCEV for both sides of the GEP. 874fcaf7f86SDimitry Andric if (OffsetScevs.size() == 2 && BaseScevs.size() == 1) 875fcaf7f86SDimitry Andric BaseScevs.push_back(BaseScevs[0]); 876fcaf7f86SDimitry Andric else if (BaseScevs.size() == 2 && OffsetScevs.size() == 1) 877fcaf7f86SDimitry Andric OffsetScevs.push_back(OffsetScevs[0]); 878fcaf7f86SDimitry Andric else { 879bdd1243dSDimitry Andric ScevList.emplace_back(Scev, NeedsFreeze); 880fcaf7f86SDimitry Andric break; 881fcaf7f86SDimitry Andric } 882fcaf7f86SDimitry Andric 883fcaf7f86SDimitry Andric // Find the pointer type we need to extend to. 884fcaf7f86SDimitry Andric Type *IntPtrTy = SE->getEffectiveSCEVType( 885fcaf7f86SDimitry Andric SE->getSCEV(GEP->getPointerOperand())->getType()); 886fcaf7f86SDimitry Andric 887fcaf7f86SDimitry Andric // Find the size of the type being pointed to. We only have a single 888fcaf7f86SDimitry Andric // index term (guarded above) so we don't need to index into arrays or 889fcaf7f86SDimitry Andric // structures, just get the size of the scalar value. 890fcaf7f86SDimitry Andric const SCEV *Size = SE->getSizeOfExpr(IntPtrTy, SourceTy); 891fcaf7f86SDimitry Andric 892fcaf7f86SDimitry Andric // Scale up the offsets by the size of the type, then add to the bases. 893fcaf7f86SDimitry Andric const SCEV *Scaled1 = SE->getMulExpr( 894bdd1243dSDimitry Andric Size, SE->getTruncateOrSignExtend(get<0>(OffsetScevs[0]), IntPtrTy)); 895fcaf7f86SDimitry Andric const SCEV *Scaled2 = SE->getMulExpr( 896bdd1243dSDimitry Andric Size, SE->getTruncateOrSignExtend(get<0>(OffsetScevs[1]), IntPtrTy)); 897bdd1243dSDimitry Andric ScevList.emplace_back(SE->getAddExpr(get<0>(BaseScevs[0]), Scaled1), 898bdd1243dSDimitry Andric NeedsFreeze); 899bdd1243dSDimitry Andric ScevList.emplace_back(SE->getAddExpr(get<0>(BaseScevs[1]), Scaled2), 900bdd1243dSDimitry Andric NeedsFreeze); 901fcaf7f86SDimitry Andric break; 902fcaf7f86SDimitry Andric } 903fcaf7f86SDimitry Andric case Instruction::Select: { 904bdd1243dSDimitry Andric SmallVector<PointerIntPair<const SCEV *, 1, bool>, 2> ChildScevs; 905fcaf7f86SDimitry Andric // A select means we've found a forked pointer, but we currently only 906fcaf7f86SDimitry Andric // support a single select per pointer so if there's another behind this 907fcaf7f86SDimitry Andric // then we just bail out and return the generic SCEV. 908fcaf7f86SDimitry Andric findForkedSCEVs(SE, L, I->getOperand(1), ChildScevs, Depth); 909fcaf7f86SDimitry Andric findForkedSCEVs(SE, L, I->getOperand(2), ChildScevs, Depth); 910fcaf7f86SDimitry Andric if (ChildScevs.size() == 2) { 911fcaf7f86SDimitry Andric ScevList.push_back(ChildScevs[0]); 912fcaf7f86SDimitry Andric ScevList.push_back(ChildScevs[1]); 913fcaf7f86SDimitry Andric } else 914bdd1243dSDimitry Andric ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr)); 915bdd1243dSDimitry Andric break; 916bdd1243dSDimitry Andric } 917bdd1243dSDimitry Andric case Instruction::Add: 918bdd1243dSDimitry Andric case Instruction::Sub: { 919bdd1243dSDimitry Andric SmallVector<PointerIntPair<const SCEV *, 1, bool>> LScevs; 920bdd1243dSDimitry Andric SmallVector<PointerIntPair<const SCEV *, 1, bool>> RScevs; 921bdd1243dSDimitry Andric findForkedSCEVs(SE, L, I->getOperand(0), LScevs, Depth); 922bdd1243dSDimitry Andric findForkedSCEVs(SE, L, I->getOperand(1), RScevs, Depth); 923bdd1243dSDimitry Andric 924bdd1243dSDimitry Andric // See if we need to freeze our fork... 925bdd1243dSDimitry Andric bool NeedsFreeze = 926bdd1243dSDimitry Andric any_of(LScevs, UndefPoisonCheck) || any_of(RScevs, UndefPoisonCheck); 927bdd1243dSDimitry Andric 928bdd1243dSDimitry Andric // Check that we only have a single fork, on either the left or right side. 929bdd1243dSDimitry Andric // Copy the SCEV across for the one without a fork in order to generate 930bdd1243dSDimitry Andric // the full SCEV for both sides of the BinOp. 931bdd1243dSDimitry Andric if (LScevs.size() == 2 && RScevs.size() == 1) 932bdd1243dSDimitry Andric RScevs.push_back(RScevs[0]); 933bdd1243dSDimitry Andric else if (RScevs.size() == 2 && LScevs.size() == 1) 934bdd1243dSDimitry Andric LScevs.push_back(LScevs[0]); 935bdd1243dSDimitry Andric else { 936bdd1243dSDimitry Andric ScevList.emplace_back(Scev, NeedsFreeze); 937bdd1243dSDimitry Andric break; 938bdd1243dSDimitry Andric } 939bdd1243dSDimitry Andric 940bdd1243dSDimitry Andric ScevList.emplace_back( 941bdd1243dSDimitry Andric GetBinOpExpr(Opcode, get<0>(LScevs[0]), get<0>(RScevs[0])), 942bdd1243dSDimitry Andric NeedsFreeze); 943bdd1243dSDimitry Andric ScevList.emplace_back( 944bdd1243dSDimitry Andric GetBinOpExpr(Opcode, get<0>(LScevs[1]), get<0>(RScevs[1])), 945bdd1243dSDimitry Andric NeedsFreeze); 946fcaf7f86SDimitry Andric break; 947fcaf7f86SDimitry Andric } 948fcaf7f86SDimitry Andric default: 949fcaf7f86SDimitry Andric // Just return the current SCEV if we haven't handled the instruction yet. 950fcaf7f86SDimitry Andric LLVM_DEBUG(dbgs() << "ForkedPtr unhandled instruction: " << *I << "\n"); 951bdd1243dSDimitry Andric ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr)); 952fcaf7f86SDimitry Andric break; 953fcaf7f86SDimitry Andric } 954fcaf7f86SDimitry Andric } 955fcaf7f86SDimitry Andric 956bdd1243dSDimitry Andric static SmallVector<PointerIntPair<const SCEV *, 1, bool>> 957fcaf7f86SDimitry Andric findForkedPointer(PredicatedScalarEvolution &PSE, 958*fe013be4SDimitry Andric const DenseMap<Value *, const SCEV *> &StridesMap, Value *Ptr, 959fcaf7f86SDimitry Andric const Loop *L) { 960fcaf7f86SDimitry Andric ScalarEvolution *SE = PSE.getSE(); 961fcaf7f86SDimitry Andric assert(SE->isSCEVable(Ptr->getType()) && "Value is not SCEVable!"); 962bdd1243dSDimitry Andric SmallVector<PointerIntPair<const SCEV *, 1, bool>> Scevs; 963fcaf7f86SDimitry Andric findForkedSCEVs(SE, L, Ptr, Scevs, MaxForkedSCEVDepth); 964fcaf7f86SDimitry Andric 965bdd1243dSDimitry Andric // For now, we will only accept a forked pointer with two possible SCEVs 966bdd1243dSDimitry Andric // that are either SCEVAddRecExprs or loop invariant. 967bdd1243dSDimitry Andric if (Scevs.size() == 2 && 968bdd1243dSDimitry Andric (isa<SCEVAddRecExpr>(get<0>(Scevs[0])) || 969bdd1243dSDimitry Andric SE->isLoopInvariant(get<0>(Scevs[0]), L)) && 970bdd1243dSDimitry Andric (isa<SCEVAddRecExpr>(get<0>(Scevs[1])) || 971bdd1243dSDimitry Andric SE->isLoopInvariant(get<0>(Scevs[1]), L))) { 972bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found forked pointer: " << *Ptr << "\n"); 973bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "\t(1) " << *get<0>(Scevs[0]) << "\n"); 974bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "\t(2) " << *get<0>(Scevs[1]) << "\n"); 975fcaf7f86SDimitry Andric return Scevs; 976bdd1243dSDimitry Andric } 977fcaf7f86SDimitry Andric 978bdd1243dSDimitry Andric return {{replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr), false}}; 979fcaf7f86SDimitry Andric } 980fcaf7f86SDimitry Andric 9810b57cec5SDimitry Andric bool AccessAnalysis::createCheckForAccess(RuntimePointerChecking &RtCheck, 98281ad6265SDimitry Andric MemAccessInfo Access, Type *AccessTy, 983*fe013be4SDimitry Andric const DenseMap<Value *, const SCEV *> &StridesMap, 9840b57cec5SDimitry Andric DenseMap<Value *, unsigned> &DepSetId, 9850b57cec5SDimitry Andric Loop *TheLoop, unsigned &RunningDepId, 9860b57cec5SDimitry Andric unsigned ASId, bool ShouldCheckWrap, 9870b57cec5SDimitry Andric bool Assume) { 9880b57cec5SDimitry Andric Value *Ptr = Access.getPointer(); 9890b57cec5SDimitry Andric 990bdd1243dSDimitry Andric SmallVector<PointerIntPair<const SCEV *, 1, bool>> TranslatedPtrs = 991fcaf7f86SDimitry Andric findForkedPointer(PSE, StridesMap, Ptr, TheLoop); 99281ad6265SDimitry Andric 99381ad6265SDimitry Andric for (auto &P : TranslatedPtrs) { 994bdd1243dSDimitry Andric const SCEV *PtrExpr = get<0>(P); 99581ad6265SDimitry Andric if (!hasComputableBounds(PSE, Ptr, PtrExpr, TheLoop, Assume)) 9960b57cec5SDimitry Andric return false; 9970b57cec5SDimitry Andric 9980b57cec5SDimitry Andric // When we run after a failing dependency check we have to make sure 9990b57cec5SDimitry Andric // we don't have wrapping pointers. 100081ad6265SDimitry Andric if (ShouldCheckWrap) { 100181ad6265SDimitry Andric // Skip wrap checking when translating pointers. 100281ad6265SDimitry Andric if (TranslatedPtrs.size() > 1) 100381ad6265SDimitry Andric return false; 100481ad6265SDimitry Andric 100581ad6265SDimitry Andric if (!isNoWrap(PSE, StridesMap, Ptr, AccessTy, TheLoop)) { 10060b57cec5SDimitry Andric auto *Expr = PSE.getSCEV(Ptr); 10070b57cec5SDimitry Andric if (!Assume || !isa<SCEVAddRecExpr>(Expr)) 10080b57cec5SDimitry Andric return false; 10090b57cec5SDimitry Andric PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW); 10100b57cec5SDimitry Andric } 101181ad6265SDimitry Andric } 101281ad6265SDimitry Andric // If there's only one option for Ptr, look it up after bounds and wrap 101381ad6265SDimitry Andric // checking, because assumptions might have been added to PSE. 101481ad6265SDimitry Andric if (TranslatedPtrs.size() == 1) 1015bdd1243dSDimitry Andric TranslatedPtrs[0] = {replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr), 1016bdd1243dSDimitry Andric false}; 101781ad6265SDimitry Andric } 101881ad6265SDimitry Andric 1019bdd1243dSDimitry Andric for (auto [PtrExpr, NeedsFreeze] : TranslatedPtrs) { 10200b57cec5SDimitry Andric // The id of the dependence set. 10210b57cec5SDimitry Andric unsigned DepId; 10220b57cec5SDimitry Andric 10230b57cec5SDimitry Andric if (isDependencyCheckNeeded()) { 10240b57cec5SDimitry Andric Value *Leader = DepCands.getLeaderValue(Access).getPointer(); 10250b57cec5SDimitry Andric unsigned &LeaderId = DepSetId[Leader]; 10260b57cec5SDimitry Andric if (!LeaderId) 10270b57cec5SDimitry Andric LeaderId = RunningDepId++; 10280b57cec5SDimitry Andric DepId = LeaderId; 10290b57cec5SDimitry Andric } else 10300b57cec5SDimitry Andric // Each access has its own dependence set. 10310b57cec5SDimitry Andric DepId = RunningDepId++; 10320b57cec5SDimitry Andric 10330b57cec5SDimitry Andric bool IsWrite = Access.getInt(); 103481ad6265SDimitry Andric RtCheck.insert(TheLoop, Ptr, PtrExpr, AccessTy, IsWrite, DepId, ASId, PSE, 1035bdd1243dSDimitry Andric NeedsFreeze); 10360b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n'); 103781ad6265SDimitry Andric } 10380b57cec5SDimitry Andric 10390b57cec5SDimitry Andric return true; 10400b57cec5SDimitry Andric } 10410b57cec5SDimitry Andric 10420b57cec5SDimitry Andric bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck, 10430b57cec5SDimitry Andric ScalarEvolution *SE, Loop *TheLoop, 1044*fe013be4SDimitry Andric const DenseMap<Value *, const SCEV *> &StridesMap, 104581ad6265SDimitry Andric Value *&UncomputablePtr, bool ShouldCheckWrap) { 10460b57cec5SDimitry Andric // Find pointers with computable bounds. We are going to use this information 10470b57cec5SDimitry Andric // to place a runtime bound check. 10480b57cec5SDimitry Andric bool CanDoRT = true; 10490b57cec5SDimitry Andric 10505ffd83dbSDimitry Andric bool MayNeedRTCheck = false; 10510b57cec5SDimitry Andric if (!IsRTCheckAnalysisNeeded) return true; 10520b57cec5SDimitry Andric 10530b57cec5SDimitry Andric bool IsDepCheckNeeded = isDependencyCheckNeeded(); 10540b57cec5SDimitry Andric 10550b57cec5SDimitry Andric // We assign a consecutive id to access from different alias sets. 10560b57cec5SDimitry Andric // Accesses between different groups doesn't need to be checked. 10575ffd83dbSDimitry Andric unsigned ASId = 0; 10580b57cec5SDimitry Andric for (auto &AS : AST) { 10590b57cec5SDimitry Andric int NumReadPtrChecks = 0; 10600b57cec5SDimitry Andric int NumWritePtrChecks = 0; 10610b57cec5SDimitry Andric bool CanDoAliasSetRT = true; 10625ffd83dbSDimitry Andric ++ASId; 10630b57cec5SDimitry Andric 10640b57cec5SDimitry Andric // We assign consecutive id to access from different dependence sets. 10650b57cec5SDimitry Andric // Accesses within the same set don't need a runtime check. 10660b57cec5SDimitry Andric unsigned RunningDepId = 1; 10670b57cec5SDimitry Andric DenseMap<Value *, unsigned> DepSetId; 10680b57cec5SDimitry Andric 1069fcaf7f86SDimitry Andric SmallVector<std::pair<MemAccessInfo, Type *>, 4> Retries; 10700b57cec5SDimitry Andric 10711106035dSDimitry Andric // First, count how many write and read accesses are in the alias set. Also 10721106035dSDimitry Andric // collect MemAccessInfos for later. 10731106035dSDimitry Andric SmallVector<MemAccessInfo, 4> AccessInfos; 1074e8d8bef9SDimitry Andric for (const auto &A : AS) { 10750b57cec5SDimitry Andric Value *Ptr = A.getValue(); 10760b57cec5SDimitry Andric bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true)); 10770b57cec5SDimitry Andric 10780b57cec5SDimitry Andric if (IsWrite) 10790b57cec5SDimitry Andric ++NumWritePtrChecks; 10800b57cec5SDimitry Andric else 10810b57cec5SDimitry Andric ++NumReadPtrChecks; 10821106035dSDimitry Andric AccessInfos.emplace_back(Ptr, IsWrite); 10830b57cec5SDimitry Andric } 10840b57cec5SDimitry Andric 10851106035dSDimitry Andric // We do not need runtime checks for this alias set, if there are no writes 10861106035dSDimitry Andric // or a single write and no reads. 10871106035dSDimitry Andric if (NumWritePtrChecks == 0 || 10881106035dSDimitry Andric (NumWritePtrChecks == 1 && NumReadPtrChecks == 0)) { 10895ffd83dbSDimitry Andric assert((AS.size() <= 1 || 10905ffd83dbSDimitry Andric all_of(AS, 10915ffd83dbSDimitry Andric [this](auto AC) { 10925ffd83dbSDimitry Andric MemAccessInfo AccessWrite(AC.getValue(), true); 10931106035dSDimitry Andric return DepCands.findValue(AccessWrite) == DepCands.end(); 10945ffd83dbSDimitry Andric })) && 10955ffd83dbSDimitry Andric "Can only skip updating CanDoRT below, if all entries in AS " 10965ffd83dbSDimitry Andric "are reads or there is at most 1 entry"); 10975ffd83dbSDimitry Andric continue; 10985ffd83dbSDimitry Andric } 10991106035dSDimitry Andric 11001106035dSDimitry Andric for (auto &Access : AccessInfos) { 1101fcaf7f86SDimitry Andric for (const auto &AccessTy : Accesses[Access]) { 110281ad6265SDimitry Andric if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap, 110381ad6265SDimitry Andric DepSetId, TheLoop, RunningDepId, ASId, 110481ad6265SDimitry Andric ShouldCheckWrap, false)) { 11051106035dSDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" 11061106035dSDimitry Andric << *Access.getPointer() << '\n'); 1107fcaf7f86SDimitry Andric Retries.push_back({Access, AccessTy}); 11081106035dSDimitry Andric CanDoAliasSetRT = false; 11095ffd83dbSDimitry Andric } 11101106035dSDimitry Andric } 111181ad6265SDimitry Andric } 11121106035dSDimitry Andric 11131106035dSDimitry Andric // Note that this function computes CanDoRT and MayNeedRTCheck 11141106035dSDimitry Andric // independently. For example CanDoRT=false, MayNeedRTCheck=false means that 11151106035dSDimitry Andric // we have a pointer for which we couldn't find the bounds but we don't 11161106035dSDimitry Andric // actually need to emit any checks so it does not matter. 11171106035dSDimitry Andric // 11181106035dSDimitry Andric // We need runtime checks for this alias set, if there are at least 2 11191106035dSDimitry Andric // dependence sets (in which case RunningDepId > 2) or if we need to re-try 11201106035dSDimitry Andric // any bound checks (because in that case the number of dependence sets is 11211106035dSDimitry Andric // incomplete). 11221106035dSDimitry Andric bool NeedsAliasSetRTCheck = RunningDepId > 2 || !Retries.empty(); 11230b57cec5SDimitry Andric 11240b57cec5SDimitry Andric // We need to perform run-time alias checks, but some pointers had bounds 11250b57cec5SDimitry Andric // that couldn't be checked. 11260b57cec5SDimitry Andric if (NeedsAliasSetRTCheck && !CanDoAliasSetRT) { 11270b57cec5SDimitry Andric // Reset the CanDoSetRt flag and retry all accesses that have failed. 11280b57cec5SDimitry Andric // We know that we need these checks, so we can now be more aggressive 11290b57cec5SDimitry Andric // and add further checks if required (overflow checks). 11300b57cec5SDimitry Andric CanDoAliasSetRT = true; 1131fcaf7f86SDimitry Andric for (auto Retry : Retries) { 1132fcaf7f86SDimitry Andric MemAccessInfo Access = Retry.first; 1133fcaf7f86SDimitry Andric Type *AccessTy = Retry.second; 113481ad6265SDimitry Andric if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap, 113581ad6265SDimitry Andric DepSetId, TheLoop, RunningDepId, ASId, 11360b57cec5SDimitry Andric ShouldCheckWrap, /*Assume=*/true)) { 11370b57cec5SDimitry Andric CanDoAliasSetRT = false; 113881ad6265SDimitry Andric UncomputablePtr = Access.getPointer(); 11390b57cec5SDimitry Andric break; 11400b57cec5SDimitry Andric } 11410b57cec5SDimitry Andric } 114281ad6265SDimitry Andric } 11430b57cec5SDimitry Andric 11440b57cec5SDimitry Andric CanDoRT &= CanDoAliasSetRT; 11455ffd83dbSDimitry Andric MayNeedRTCheck |= NeedsAliasSetRTCheck; 11460b57cec5SDimitry Andric ++ASId; 11470b57cec5SDimitry Andric } 11480b57cec5SDimitry Andric 11490b57cec5SDimitry Andric // If the pointers that we would use for the bounds comparison have different 11500b57cec5SDimitry Andric // address spaces, assume the values aren't directly comparable, so we can't 11510b57cec5SDimitry Andric // use them for the runtime check. We also have to assume they could 11520b57cec5SDimitry Andric // overlap. In the future there should be metadata for whether address spaces 11530b57cec5SDimitry Andric // are disjoint. 11540b57cec5SDimitry Andric unsigned NumPointers = RtCheck.Pointers.size(); 11550b57cec5SDimitry Andric for (unsigned i = 0; i < NumPointers; ++i) { 11560b57cec5SDimitry Andric for (unsigned j = i + 1; j < NumPointers; ++j) { 11570b57cec5SDimitry Andric // Only need to check pointers between two different dependency sets. 11580b57cec5SDimitry Andric if (RtCheck.Pointers[i].DependencySetId == 11590b57cec5SDimitry Andric RtCheck.Pointers[j].DependencySetId) 11600b57cec5SDimitry Andric continue; 11610b57cec5SDimitry Andric // Only need to check pointers in the same alias set. 11620b57cec5SDimitry Andric if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId) 11630b57cec5SDimitry Andric continue; 11640b57cec5SDimitry Andric 11650b57cec5SDimitry Andric Value *PtrI = RtCheck.Pointers[i].PointerValue; 11660b57cec5SDimitry Andric Value *PtrJ = RtCheck.Pointers[j].PointerValue; 11670b57cec5SDimitry Andric 11680b57cec5SDimitry Andric unsigned ASi = PtrI->getType()->getPointerAddressSpace(); 11690b57cec5SDimitry Andric unsigned ASj = PtrJ->getType()->getPointerAddressSpace(); 11700b57cec5SDimitry Andric if (ASi != ASj) { 11710b57cec5SDimitry Andric LLVM_DEBUG( 11720b57cec5SDimitry Andric dbgs() << "LAA: Runtime check would require comparison between" 11730b57cec5SDimitry Andric " different address spaces\n"); 11740b57cec5SDimitry Andric return false; 11750b57cec5SDimitry Andric } 11760b57cec5SDimitry Andric } 11770b57cec5SDimitry Andric } 11780b57cec5SDimitry Andric 11795ffd83dbSDimitry Andric if (MayNeedRTCheck && CanDoRT) 11800b57cec5SDimitry Andric RtCheck.generateChecks(DepCands, IsDepCheckNeeded); 11810b57cec5SDimitry Andric 11820b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks() 11830b57cec5SDimitry Andric << " pointer comparisons.\n"); 11840b57cec5SDimitry Andric 11855ffd83dbSDimitry Andric // If we can do run-time checks, but there are no checks, no runtime checks 11865ffd83dbSDimitry Andric // are needed. This can happen when all pointers point to the same underlying 11875ffd83dbSDimitry Andric // object for example. 11885ffd83dbSDimitry Andric RtCheck.Need = CanDoRT ? RtCheck.getNumberOfChecks() != 0 : MayNeedRTCheck; 11890b57cec5SDimitry Andric 11905ffd83dbSDimitry Andric bool CanDoRTIfNeeded = !RtCheck.Need || CanDoRT; 11910b57cec5SDimitry Andric if (!CanDoRTIfNeeded) 11920b57cec5SDimitry Andric RtCheck.reset(); 11930b57cec5SDimitry Andric return CanDoRTIfNeeded; 11940b57cec5SDimitry Andric } 11950b57cec5SDimitry Andric 11960b57cec5SDimitry Andric void AccessAnalysis::processMemAccesses() { 11970b57cec5SDimitry Andric // We process the set twice: first we process read-write pointers, last we 11980b57cec5SDimitry Andric // process read-only pointers. This allows us to skip dependence tests for 11990b57cec5SDimitry Andric // read-only pointers. 12000b57cec5SDimitry Andric 12010b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Processing memory accesses...\n"); 12020b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " AST: "; AST.dump()); 12030b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n"); 12040b57cec5SDimitry Andric LLVM_DEBUG({ 12050b57cec5SDimitry Andric for (auto A : Accesses) 120681ad6265SDimitry Andric dbgs() << "\t" << *A.first.getPointer() << " (" 120781ad6265SDimitry Andric << (A.first.getInt() 120881ad6265SDimitry Andric ? "write" 120981ad6265SDimitry Andric : (ReadOnlyPtr.count(A.first.getPointer()) ? "read-only" 121081ad6265SDimitry Andric : "read")) 121181ad6265SDimitry Andric << ")\n"; 12120b57cec5SDimitry Andric }); 12130b57cec5SDimitry Andric 12140b57cec5SDimitry Andric // The AliasSetTracker has nicely partitioned our pointers by metadata 12150b57cec5SDimitry Andric // compatibility and potential for underlying-object overlap. As a result, we 12160b57cec5SDimitry Andric // only need to check for potential pointer dependencies within each alias 12170b57cec5SDimitry Andric // set. 1218e8d8bef9SDimitry Andric for (const auto &AS : AST) { 12190b57cec5SDimitry Andric // Note that both the alias-set tracker and the alias sets themselves used 12200b57cec5SDimitry Andric // linked lists internally and so the iteration order here is deterministic 12210b57cec5SDimitry Andric // (matching the original instruction order within each set). 12220b57cec5SDimitry Andric 12230b57cec5SDimitry Andric bool SetHasWrite = false; 12240b57cec5SDimitry Andric 12250b57cec5SDimitry Andric // Map of pointers to last access encountered. 12260b57cec5SDimitry Andric typedef DenseMap<const Value*, MemAccessInfo> UnderlyingObjToAccessMap; 12270b57cec5SDimitry Andric UnderlyingObjToAccessMap ObjToLastAccess; 12280b57cec5SDimitry Andric 12290b57cec5SDimitry Andric // Set of access to check after all writes have been processed. 123081ad6265SDimitry Andric PtrAccessMap DeferredAccesses; 12310b57cec5SDimitry Andric 12320b57cec5SDimitry Andric // Iterate over each alias set twice, once to process read/write pointers, 12330b57cec5SDimitry Andric // and then to process read-only pointers. 12340b57cec5SDimitry Andric for (int SetIteration = 0; SetIteration < 2; ++SetIteration) { 12350b57cec5SDimitry Andric bool UseDeferred = SetIteration > 0; 123681ad6265SDimitry Andric PtrAccessMap &S = UseDeferred ? DeferredAccesses : Accesses; 12370b57cec5SDimitry Andric 1238e8d8bef9SDimitry Andric for (const auto &AV : AS) { 12390b57cec5SDimitry Andric Value *Ptr = AV.getValue(); 12400b57cec5SDimitry Andric 12410b57cec5SDimitry Andric // For a single memory access in AliasSetTracker, Accesses may contain 12420b57cec5SDimitry Andric // both read and write, and they both need to be handled for CheckDeps. 1243e8d8bef9SDimitry Andric for (const auto &AC : S) { 124481ad6265SDimitry Andric if (AC.first.getPointer() != Ptr) 12450b57cec5SDimitry Andric continue; 12460b57cec5SDimitry Andric 124781ad6265SDimitry Andric bool IsWrite = AC.first.getInt(); 12480b57cec5SDimitry Andric 12490b57cec5SDimitry Andric // If we're using the deferred access set, then it contains only 12500b57cec5SDimitry Andric // reads. 12510b57cec5SDimitry Andric bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite; 12520b57cec5SDimitry Andric if (UseDeferred && !IsReadOnlyPtr) 12530b57cec5SDimitry Andric continue; 12540b57cec5SDimitry Andric // Otherwise, the pointer must be in the PtrAccessSet, either as a 12550b57cec5SDimitry Andric // read or a write. 12560b57cec5SDimitry Andric assert(((IsReadOnlyPtr && UseDeferred) || IsWrite || 12570b57cec5SDimitry Andric S.count(MemAccessInfo(Ptr, false))) && 12580b57cec5SDimitry Andric "Alias-set pointer not in the access set?"); 12590b57cec5SDimitry Andric 12600b57cec5SDimitry Andric MemAccessInfo Access(Ptr, IsWrite); 12610b57cec5SDimitry Andric DepCands.insert(Access); 12620b57cec5SDimitry Andric 12630b57cec5SDimitry Andric // Memorize read-only pointers for later processing and skip them in 12640b57cec5SDimitry Andric // the first round (they need to be checked after we have seen all 12650b57cec5SDimitry Andric // write pointers). Note: we also mark pointer that are not 12660b57cec5SDimitry Andric // consecutive as "read-only" pointers (so that we check 12670b57cec5SDimitry Andric // "a[b[i]] +="). Hence, we need the second check for "!IsWrite". 12680b57cec5SDimitry Andric if (!UseDeferred && IsReadOnlyPtr) { 126981ad6265SDimitry Andric // We only use the pointer keys, the types vector values don't 127081ad6265SDimitry Andric // matter. 127181ad6265SDimitry Andric DeferredAccesses.insert({Access, {}}); 12720b57cec5SDimitry Andric continue; 12730b57cec5SDimitry Andric } 12740b57cec5SDimitry Andric 12750b57cec5SDimitry Andric // If this is a write - check other reads and writes for conflicts. If 12760b57cec5SDimitry Andric // this is a read only check other writes for conflicts (but only if 12770b57cec5SDimitry Andric // there is no other write to the ptr - this is an optimization to 12780b57cec5SDimitry Andric // catch "a[i] = a[i] + " without having to do a dependence check). 12790b57cec5SDimitry Andric if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) { 12800b57cec5SDimitry Andric CheckDeps.push_back(Access); 12810b57cec5SDimitry Andric IsRTCheckAnalysisNeeded = true; 12820b57cec5SDimitry Andric } 12830b57cec5SDimitry Andric 12840b57cec5SDimitry Andric if (IsWrite) 12850b57cec5SDimitry Andric SetHasWrite = true; 12860b57cec5SDimitry Andric 12870b57cec5SDimitry Andric // Create sets of pointers connected by a shared alias set and 12880b57cec5SDimitry Andric // underlying object. 12890b57cec5SDimitry Andric typedef SmallVector<const Value *, 16> ValueVector; 12900b57cec5SDimitry Andric ValueVector TempObjects; 12910b57cec5SDimitry Andric 1292e8d8bef9SDimitry Andric getUnderlyingObjects(Ptr, TempObjects, LI); 12930b57cec5SDimitry Andric LLVM_DEBUG(dbgs() 12940b57cec5SDimitry Andric << "Underlying objects for pointer " << *Ptr << "\n"); 12950b57cec5SDimitry Andric for (const Value *UnderlyingObj : TempObjects) { 12960b57cec5SDimitry Andric // nullptr never alias, don't join sets for pointer that have "null" 12970b57cec5SDimitry Andric // in their UnderlyingObjects list. 12980b57cec5SDimitry Andric if (isa<ConstantPointerNull>(UnderlyingObj) && 12990b57cec5SDimitry Andric !NullPointerIsDefined( 13000b57cec5SDimitry Andric TheLoop->getHeader()->getParent(), 13010b57cec5SDimitry Andric UnderlyingObj->getType()->getPointerAddressSpace())) 13020b57cec5SDimitry Andric continue; 13030b57cec5SDimitry Andric 13040b57cec5SDimitry Andric UnderlyingObjToAccessMap::iterator Prev = 13050b57cec5SDimitry Andric ObjToLastAccess.find(UnderlyingObj); 13060b57cec5SDimitry Andric if (Prev != ObjToLastAccess.end()) 13070b57cec5SDimitry Andric DepCands.unionSets(Access, Prev->second); 13080b57cec5SDimitry Andric 13090b57cec5SDimitry Andric ObjToLastAccess[UnderlyingObj] = Access; 13100b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " " << *UnderlyingObj << "\n"); 13110b57cec5SDimitry Andric } 13120b57cec5SDimitry Andric } 13130b57cec5SDimitry Andric } 13140b57cec5SDimitry Andric } 13150b57cec5SDimitry Andric } 13160b57cec5SDimitry Andric } 13170b57cec5SDimitry Andric 13180b57cec5SDimitry Andric /// Return true if an AddRec pointer \p Ptr is unsigned non-wrapping, 13190b57cec5SDimitry Andric /// i.e. monotonically increasing/decreasing. 13200b57cec5SDimitry Andric static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR, 13210b57cec5SDimitry Andric PredicatedScalarEvolution &PSE, const Loop *L) { 1322*fe013be4SDimitry Andric 13230b57cec5SDimitry Andric // FIXME: This should probably only return true for NUW. 13240b57cec5SDimitry Andric if (AR->getNoWrapFlags(SCEV::NoWrapMask)) 13250b57cec5SDimitry Andric return true; 13260b57cec5SDimitry Andric 1327*fe013be4SDimitry Andric if (PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW)) 1328*fe013be4SDimitry Andric return true; 1329*fe013be4SDimitry Andric 13300b57cec5SDimitry Andric // Scalar evolution does not propagate the non-wrapping flags to values that 13310b57cec5SDimitry Andric // are derived from a non-wrapping induction variable because non-wrapping 13320b57cec5SDimitry Andric // could be flow-sensitive. 13330b57cec5SDimitry Andric // 13340b57cec5SDimitry Andric // Look through the potentially overflowing instruction to try to prove 13350b57cec5SDimitry Andric // non-wrapping for the *specific* value of Ptr. 13360b57cec5SDimitry Andric 13370b57cec5SDimitry Andric // The arithmetic implied by an inbounds GEP can't overflow. 13380b57cec5SDimitry Andric auto *GEP = dyn_cast<GetElementPtrInst>(Ptr); 13390b57cec5SDimitry Andric if (!GEP || !GEP->isInBounds()) 13400b57cec5SDimitry Andric return false; 13410b57cec5SDimitry Andric 13420b57cec5SDimitry Andric // Make sure there is only one non-const index and analyze that. 13430b57cec5SDimitry Andric Value *NonConstIndex = nullptr; 1344e8d8bef9SDimitry Andric for (Value *Index : GEP->indices()) 13450b57cec5SDimitry Andric if (!isa<ConstantInt>(Index)) { 13460b57cec5SDimitry Andric if (NonConstIndex) 13470b57cec5SDimitry Andric return false; 13480b57cec5SDimitry Andric NonConstIndex = Index; 13490b57cec5SDimitry Andric } 13500b57cec5SDimitry Andric if (!NonConstIndex) 13510b57cec5SDimitry Andric // The recurrence is on the pointer, ignore for now. 13520b57cec5SDimitry Andric return false; 13530b57cec5SDimitry Andric 13540b57cec5SDimitry Andric // The index in GEP is signed. It is non-wrapping if it's derived from a NSW 13550b57cec5SDimitry Andric // AddRec using a NSW operation. 13560b57cec5SDimitry Andric if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex)) 13570b57cec5SDimitry Andric if (OBO->hasNoSignedWrap() && 13580b57cec5SDimitry Andric // Assume constant for other the operand so that the AddRec can be 13590b57cec5SDimitry Andric // easily found. 13600b57cec5SDimitry Andric isa<ConstantInt>(OBO->getOperand(1))) { 13610b57cec5SDimitry Andric auto *OpScev = PSE.getSCEV(OBO->getOperand(0)); 13620b57cec5SDimitry Andric 13630b57cec5SDimitry Andric if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev)) 13640b57cec5SDimitry Andric return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW); 13650b57cec5SDimitry Andric } 13660b57cec5SDimitry Andric 13670b57cec5SDimitry Andric return false; 13680b57cec5SDimitry Andric } 13690b57cec5SDimitry Andric 13700b57cec5SDimitry Andric /// Check whether the access through \p Ptr has a constant stride. 1371bdd1243dSDimitry Andric std::optional<int64_t> llvm::getPtrStride(PredicatedScalarEvolution &PSE, 1372bdd1243dSDimitry Andric Type *AccessTy, Value *Ptr, 1373bdd1243dSDimitry Andric const Loop *Lp, 1374*fe013be4SDimitry Andric const DenseMap<Value *, const SCEV *> &StridesMap, 1375bdd1243dSDimitry Andric bool Assume, bool ShouldCheckWrap) { 13760b57cec5SDimitry Andric Type *Ty = Ptr->getType(); 13770b57cec5SDimitry Andric assert(Ty->isPointerTy() && "Unexpected non-ptr"); 13780b57cec5SDimitry Andric 13794824e7fdSDimitry Andric if (isa<ScalableVectorType>(AccessTy)) { 13804824e7fdSDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Bad stride - Scalable object: " << *AccessTy 13814824e7fdSDimitry Andric << "\n"); 1382bdd1243dSDimitry Andric return std::nullopt; 13830b57cec5SDimitry Andric } 13840b57cec5SDimitry Andric 13850b57cec5SDimitry Andric const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr); 13860b57cec5SDimitry Andric 13870b57cec5SDimitry Andric const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev); 13880b57cec5SDimitry Andric if (Assume && !AR) 13890b57cec5SDimitry Andric AR = PSE.getAsAddRec(Ptr); 13900b57cec5SDimitry Andric 13910b57cec5SDimitry Andric if (!AR) { 13920b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer " << *Ptr 13930b57cec5SDimitry Andric << " SCEV: " << *PtrScev << "\n"); 1394bdd1243dSDimitry Andric return std::nullopt; 13950b57cec5SDimitry Andric } 13960b57cec5SDimitry Andric 13970b57cec5SDimitry Andric // The access function must stride over the innermost loop. 13980b57cec5SDimitry Andric if (Lp != AR->getLoop()) { 13990b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " 14000b57cec5SDimitry Andric << *Ptr << " SCEV: " << *AR << "\n"); 1401bdd1243dSDimitry Andric return std::nullopt; 14020b57cec5SDimitry Andric } 14030b57cec5SDimitry Andric 14040b57cec5SDimitry Andric // Check the step is constant. 14050b57cec5SDimitry Andric const SCEV *Step = AR->getStepRecurrence(*PSE.getSE()); 14060b57cec5SDimitry Andric 14070b57cec5SDimitry Andric // Calculate the pointer stride and check if it is constant. 14080b57cec5SDimitry Andric const SCEVConstant *C = dyn_cast<SCEVConstant>(Step); 14090b57cec5SDimitry Andric if (!C) { 14100b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr 14110b57cec5SDimitry Andric << " SCEV: " << *AR << "\n"); 1412bdd1243dSDimitry Andric return std::nullopt; 14130b57cec5SDimitry Andric } 14140b57cec5SDimitry Andric 14150b57cec5SDimitry Andric auto &DL = Lp->getHeader()->getModule()->getDataLayout(); 14164824e7fdSDimitry Andric TypeSize AllocSize = DL.getTypeAllocSize(AccessTy); 1417bdd1243dSDimitry Andric int64_t Size = AllocSize.getFixedValue(); 14180b57cec5SDimitry Andric const APInt &APStepVal = C->getAPInt(); 14190b57cec5SDimitry Andric 14200b57cec5SDimitry Andric // Huge step value - give up. 14210b57cec5SDimitry Andric if (APStepVal.getBitWidth() > 64) 1422bdd1243dSDimitry Andric return std::nullopt; 14230b57cec5SDimitry Andric 14240b57cec5SDimitry Andric int64_t StepVal = APStepVal.getSExtValue(); 14250b57cec5SDimitry Andric 14260b57cec5SDimitry Andric // Strided access. 14270b57cec5SDimitry Andric int64_t Stride = StepVal / Size; 14280b57cec5SDimitry Andric int64_t Rem = StepVal % Size; 14290b57cec5SDimitry Andric if (Rem) 1430bdd1243dSDimitry Andric return std::nullopt; 14310b57cec5SDimitry Andric 1432*fe013be4SDimitry Andric if (!ShouldCheckWrap) 1433*fe013be4SDimitry Andric return Stride; 1434*fe013be4SDimitry Andric 1435*fe013be4SDimitry Andric // The address calculation must not wrap. Otherwise, a dependence could be 1436*fe013be4SDimitry Andric // inverted. 1437*fe013be4SDimitry Andric if (isNoWrapAddRec(Ptr, AR, PSE, Lp)) 1438*fe013be4SDimitry Andric return Stride; 1439*fe013be4SDimitry Andric 1440*fe013be4SDimitry Andric // An inbounds getelementptr that is a AddRec with a unit stride 1441*fe013be4SDimitry Andric // cannot wrap per definition. If it did, the result would be poison 1442*fe013be4SDimitry Andric // and any memory access dependent on it would be immediate UB 1443*fe013be4SDimitry Andric // when executed. 1444*fe013be4SDimitry Andric if (auto *GEP = dyn_cast<GetElementPtrInst>(Ptr); 1445*fe013be4SDimitry Andric GEP && GEP->isInBounds() && (Stride == 1 || Stride == -1)) 1446*fe013be4SDimitry Andric return Stride; 1447*fe013be4SDimitry Andric 1448*fe013be4SDimitry Andric // If the null pointer is undefined, then a access sequence which would 1449*fe013be4SDimitry Andric // otherwise access it can be assumed not to unsigned wrap. Note that this 1450*fe013be4SDimitry Andric // assumes the object in memory is aligned to the natural alignment. 1451*fe013be4SDimitry Andric unsigned AddrSpace = Ty->getPointerAddressSpace(); 1452*fe013be4SDimitry Andric if (!NullPointerIsDefined(Lp->getHeader()->getParent(), AddrSpace) && 1453*fe013be4SDimitry Andric (Stride == 1 || Stride == -1)) 1454*fe013be4SDimitry Andric return Stride; 1455*fe013be4SDimitry Andric 14560b57cec5SDimitry Andric if (Assume) { 1457*fe013be4SDimitry Andric PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW); 1458*fe013be4SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Pointer may wrap:\n" 14590b57cec5SDimitry Andric << "LAA: Pointer: " << *Ptr << "\n" 14600b57cec5SDimitry Andric << "LAA: SCEV: " << *AR << "\n" 14610b57cec5SDimitry Andric << "LAA: Added an overflow assumption\n"); 14620b57cec5SDimitry Andric return Stride; 14630b57cec5SDimitry Andric } 1464*fe013be4SDimitry Andric LLVM_DEBUG( 1465*fe013be4SDimitry Andric dbgs() << "LAA: Bad stride - Pointer may wrap in the address space " 1466*fe013be4SDimitry Andric << *Ptr << " SCEV: " << *AR << "\n"); 1467*fe013be4SDimitry Andric return std::nullopt; 1468*fe013be4SDimitry Andric } 14690b57cec5SDimitry Andric 1470bdd1243dSDimitry Andric std::optional<int> llvm::getPointersDiff(Type *ElemTyA, Value *PtrA, 1471bdd1243dSDimitry Andric Type *ElemTyB, Value *PtrB, 1472bdd1243dSDimitry Andric const DataLayout &DL, 1473fe6060f1SDimitry Andric ScalarEvolution &SE, bool StrictCheck, 1474fe6060f1SDimitry Andric bool CheckType) { 1475fe6060f1SDimitry Andric assert(PtrA && PtrB && "Expected non-nullptr pointers."); 1476fe6060f1SDimitry Andric 1477fe6060f1SDimitry Andric // Make sure that A and B are different pointers. 1478fe6060f1SDimitry Andric if (PtrA == PtrB) 1479fe6060f1SDimitry Andric return 0; 1480fe6060f1SDimitry Andric 1481fe6060f1SDimitry Andric // Make sure that the element types are the same if required. 1482fe6060f1SDimitry Andric if (CheckType && ElemTyA != ElemTyB) 1483bdd1243dSDimitry Andric return std::nullopt; 1484fe6060f1SDimitry Andric 1485fe6060f1SDimitry Andric unsigned ASA = PtrA->getType()->getPointerAddressSpace(); 1486fe6060f1SDimitry Andric unsigned ASB = PtrB->getType()->getPointerAddressSpace(); 1487fe6060f1SDimitry Andric 1488fe6060f1SDimitry Andric // Check that the address spaces match. 1489fe6060f1SDimitry Andric if (ASA != ASB) 1490bdd1243dSDimitry Andric return std::nullopt; 1491fe6060f1SDimitry Andric unsigned IdxWidth = DL.getIndexSizeInBits(ASA); 1492fe6060f1SDimitry Andric 1493fe6060f1SDimitry Andric APInt OffsetA(IdxWidth, 0), OffsetB(IdxWidth, 0); 1494fe6060f1SDimitry Andric Value *PtrA1 = PtrA->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetA); 1495fe6060f1SDimitry Andric Value *PtrB1 = PtrB->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetB); 1496fe6060f1SDimitry Andric 1497fe6060f1SDimitry Andric int Val; 1498fe6060f1SDimitry Andric if (PtrA1 == PtrB1) { 1499fe6060f1SDimitry Andric // Retrieve the address space again as pointer stripping now tracks through 1500fe6060f1SDimitry Andric // `addrspacecast`. 1501fe6060f1SDimitry Andric ASA = cast<PointerType>(PtrA1->getType())->getAddressSpace(); 1502fe6060f1SDimitry Andric ASB = cast<PointerType>(PtrB1->getType())->getAddressSpace(); 1503fe6060f1SDimitry Andric // Check that the address spaces match and that the pointers are valid. 1504fe6060f1SDimitry Andric if (ASA != ASB) 1505bdd1243dSDimitry Andric return std::nullopt; 1506fe6060f1SDimitry Andric 1507fe6060f1SDimitry Andric IdxWidth = DL.getIndexSizeInBits(ASA); 1508fe6060f1SDimitry Andric OffsetA = OffsetA.sextOrTrunc(IdxWidth); 1509fe6060f1SDimitry Andric OffsetB = OffsetB.sextOrTrunc(IdxWidth); 1510fe6060f1SDimitry Andric 1511fe6060f1SDimitry Andric OffsetB -= OffsetA; 1512fe6060f1SDimitry Andric Val = OffsetB.getSExtValue(); 1513fe6060f1SDimitry Andric } else { 1514fe6060f1SDimitry Andric // Otherwise compute the distance with SCEV between the base pointers. 1515fe6060f1SDimitry Andric const SCEV *PtrSCEVA = SE.getSCEV(PtrA); 1516fe6060f1SDimitry Andric const SCEV *PtrSCEVB = SE.getSCEV(PtrB); 1517fe6060f1SDimitry Andric const auto *Diff = 1518fe6060f1SDimitry Andric dyn_cast<SCEVConstant>(SE.getMinusSCEV(PtrSCEVB, PtrSCEVA)); 1519fe6060f1SDimitry Andric if (!Diff) 1520bdd1243dSDimitry Andric return std::nullopt; 1521fe6060f1SDimitry Andric Val = Diff->getAPInt().getSExtValue(); 1522fe6060f1SDimitry Andric } 1523fe6060f1SDimitry Andric int Size = DL.getTypeStoreSize(ElemTyA); 1524fe6060f1SDimitry Andric int Dist = Val / Size; 1525fe6060f1SDimitry Andric 1526fe6060f1SDimitry Andric // Ensure that the calculated distance matches the type-based one after all 1527fe6060f1SDimitry Andric // the bitcasts removal in the provided pointers. 1528fe6060f1SDimitry Andric if (!StrictCheck || Dist * Size == Val) 1529fe6060f1SDimitry Andric return Dist; 1530bdd1243dSDimitry Andric return std::nullopt; 1531fe6060f1SDimitry Andric } 1532fe6060f1SDimitry Andric 1533fe6060f1SDimitry Andric bool llvm::sortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy, 1534fe6060f1SDimitry Andric const DataLayout &DL, ScalarEvolution &SE, 15350b57cec5SDimitry Andric SmallVectorImpl<unsigned> &SortedIndices) { 15360b57cec5SDimitry Andric assert(llvm::all_of( 15370b57cec5SDimitry Andric VL, [](const Value *V) { return V->getType()->isPointerTy(); }) && 15380b57cec5SDimitry Andric "Expected list of pointer operands."); 15390b57cec5SDimitry Andric // Walk over the pointers, and map each of them to an offset relative to 15400b57cec5SDimitry Andric // first pointer in the array. 15410b57cec5SDimitry Andric Value *Ptr0 = VL[0]; 15420b57cec5SDimitry Andric 1543fe6060f1SDimitry Andric using DistOrdPair = std::pair<int64_t, int>; 1544972a253aSDimitry Andric auto Compare = llvm::less_first(); 1545fe6060f1SDimitry Andric std::set<DistOrdPair, decltype(Compare)> Offsets(Compare); 1546fe6060f1SDimitry Andric Offsets.emplace(0, 0); 1547fe6060f1SDimitry Andric int Cnt = 1; 1548fe6060f1SDimitry Andric bool IsConsecutive = true; 1549fe6060f1SDimitry Andric for (auto *Ptr : VL.drop_front()) { 1550bdd1243dSDimitry Andric std::optional<int> Diff = getPointersDiff(ElemTy, Ptr0, ElemTy, Ptr, DL, SE, 1551fe6060f1SDimitry Andric /*StrictCheck=*/true); 15520b57cec5SDimitry Andric if (!Diff) 15530b57cec5SDimitry Andric return false; 15540b57cec5SDimitry Andric 15550b57cec5SDimitry Andric // Check if the pointer with the same offset is found. 1556fe6060f1SDimitry Andric int64_t Offset = *Diff; 1557fe6060f1SDimitry Andric auto Res = Offsets.emplace(Offset, Cnt); 1558fe6060f1SDimitry Andric if (!Res.second) 15590b57cec5SDimitry Andric return false; 1560fe6060f1SDimitry Andric // Consecutive order if the inserted element is the last one. 1561fe6060f1SDimitry Andric IsConsecutive = IsConsecutive && std::next(Res.first) == Offsets.end(); 1562fe6060f1SDimitry Andric ++Cnt; 15630b57cec5SDimitry Andric } 15640b57cec5SDimitry Andric SortedIndices.clear(); 1565fe6060f1SDimitry Andric if (!IsConsecutive) { 1566fe6060f1SDimitry Andric // Fill SortedIndices array only if it is non-consecutive. 15670b57cec5SDimitry Andric SortedIndices.resize(VL.size()); 1568fe6060f1SDimitry Andric Cnt = 0; 1569fe6060f1SDimitry Andric for (const std::pair<int64_t, int> &Pair : Offsets) { 1570fe6060f1SDimitry Andric SortedIndices[Cnt] = Pair.second; 1571fe6060f1SDimitry Andric ++Cnt; 15720b57cec5SDimitry Andric } 1573fe6060f1SDimitry Andric } 1574fe6060f1SDimitry Andric return true; 15750b57cec5SDimitry Andric } 15760b57cec5SDimitry Andric 15770b57cec5SDimitry Andric /// Returns true if the memory operations \p A and \p B are consecutive. 15780b57cec5SDimitry Andric bool llvm::isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL, 15790b57cec5SDimitry Andric ScalarEvolution &SE, bool CheckType) { 15800b57cec5SDimitry Andric Value *PtrA = getLoadStorePointerOperand(A); 15810b57cec5SDimitry Andric Value *PtrB = getLoadStorePointerOperand(B); 1582fe6060f1SDimitry Andric if (!PtrA || !PtrB) 15830b57cec5SDimitry Andric return false; 1584fe6060f1SDimitry Andric Type *ElemTyA = getLoadStoreType(A); 1585fe6060f1SDimitry Andric Type *ElemTyB = getLoadStoreType(B); 1586bdd1243dSDimitry Andric std::optional<int> Diff = 1587bdd1243dSDimitry Andric getPointersDiff(ElemTyA, PtrA, ElemTyB, PtrB, DL, SE, 1588fe6060f1SDimitry Andric /*StrictCheck=*/true, CheckType); 1589fe6060f1SDimitry Andric return Diff && *Diff == 1; 15900b57cec5SDimitry Andric } 15910b57cec5SDimitry Andric 1592349cc55cSDimitry Andric void MemoryDepChecker::addAccess(StoreInst *SI) { 1593349cc55cSDimitry Andric visitPointers(SI->getPointerOperand(), *InnermostLoop, 1594349cc55cSDimitry Andric [this, SI](Value *Ptr) { 1595349cc55cSDimitry Andric Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx); 1596349cc55cSDimitry Andric InstMap.push_back(SI); 1597349cc55cSDimitry Andric ++AccessIdx; 1598349cc55cSDimitry Andric }); 1599349cc55cSDimitry Andric } 1600349cc55cSDimitry Andric 1601349cc55cSDimitry Andric void MemoryDepChecker::addAccess(LoadInst *LI) { 1602349cc55cSDimitry Andric visitPointers(LI->getPointerOperand(), *InnermostLoop, 1603349cc55cSDimitry Andric [this, LI](Value *Ptr) { 1604349cc55cSDimitry Andric Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx); 1605349cc55cSDimitry Andric InstMap.push_back(LI); 1606349cc55cSDimitry Andric ++AccessIdx; 1607349cc55cSDimitry Andric }); 1608349cc55cSDimitry Andric } 1609349cc55cSDimitry Andric 16100b57cec5SDimitry Andric MemoryDepChecker::VectorizationSafetyStatus 16110b57cec5SDimitry Andric MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) { 16120b57cec5SDimitry Andric switch (Type) { 16130b57cec5SDimitry Andric case NoDep: 16140b57cec5SDimitry Andric case Forward: 16150b57cec5SDimitry Andric case BackwardVectorizable: 16160b57cec5SDimitry Andric return VectorizationSafetyStatus::Safe; 16170b57cec5SDimitry Andric 16180b57cec5SDimitry Andric case Unknown: 16190b57cec5SDimitry Andric return VectorizationSafetyStatus::PossiblySafeWithRtChecks; 16200b57cec5SDimitry Andric case ForwardButPreventsForwarding: 16210b57cec5SDimitry Andric case Backward: 16220b57cec5SDimitry Andric case BackwardVectorizableButPreventsForwarding: 16230b57cec5SDimitry Andric return VectorizationSafetyStatus::Unsafe; 16240b57cec5SDimitry Andric } 16250b57cec5SDimitry Andric llvm_unreachable("unexpected DepType!"); 16260b57cec5SDimitry Andric } 16270b57cec5SDimitry Andric 16280b57cec5SDimitry Andric bool MemoryDepChecker::Dependence::isBackward() const { 16290b57cec5SDimitry Andric switch (Type) { 16300b57cec5SDimitry Andric case NoDep: 16310b57cec5SDimitry Andric case Forward: 16320b57cec5SDimitry Andric case ForwardButPreventsForwarding: 16330b57cec5SDimitry Andric case Unknown: 16340b57cec5SDimitry Andric return false; 16350b57cec5SDimitry Andric 16360b57cec5SDimitry Andric case BackwardVectorizable: 16370b57cec5SDimitry Andric case Backward: 16380b57cec5SDimitry Andric case BackwardVectorizableButPreventsForwarding: 16390b57cec5SDimitry Andric return true; 16400b57cec5SDimitry Andric } 16410b57cec5SDimitry Andric llvm_unreachable("unexpected DepType!"); 16420b57cec5SDimitry Andric } 16430b57cec5SDimitry Andric 16440b57cec5SDimitry Andric bool MemoryDepChecker::Dependence::isPossiblyBackward() const { 16450b57cec5SDimitry Andric return isBackward() || Type == Unknown; 16460b57cec5SDimitry Andric } 16470b57cec5SDimitry Andric 16480b57cec5SDimitry Andric bool MemoryDepChecker::Dependence::isForward() const { 16490b57cec5SDimitry Andric switch (Type) { 16500b57cec5SDimitry Andric case Forward: 16510b57cec5SDimitry Andric case ForwardButPreventsForwarding: 16520b57cec5SDimitry Andric return true; 16530b57cec5SDimitry Andric 16540b57cec5SDimitry Andric case NoDep: 16550b57cec5SDimitry Andric case Unknown: 16560b57cec5SDimitry Andric case BackwardVectorizable: 16570b57cec5SDimitry Andric case Backward: 16580b57cec5SDimitry Andric case BackwardVectorizableButPreventsForwarding: 16590b57cec5SDimitry Andric return false; 16600b57cec5SDimitry Andric } 16610b57cec5SDimitry Andric llvm_unreachable("unexpected DepType!"); 16620b57cec5SDimitry Andric } 16630b57cec5SDimitry Andric 16640b57cec5SDimitry Andric bool MemoryDepChecker::couldPreventStoreLoadForward(uint64_t Distance, 16650b57cec5SDimitry Andric uint64_t TypeByteSize) { 16660b57cec5SDimitry Andric // If loads occur at a distance that is not a multiple of a feasible vector 16670b57cec5SDimitry Andric // factor store-load forwarding does not take place. 16680b57cec5SDimitry Andric // Positive dependences might cause troubles because vectorizing them might 16690b57cec5SDimitry Andric // prevent store-load forwarding making vectorized code run a lot slower. 16700b57cec5SDimitry Andric // a[i] = a[i-3] ^ a[i-8]; 16710b57cec5SDimitry Andric // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and 16720b57cec5SDimitry Andric // hence on your typical architecture store-load forwarding does not take 16730b57cec5SDimitry Andric // place. Vectorizing in such cases does not make sense. 16740b57cec5SDimitry Andric // Store-load forwarding distance. 16750b57cec5SDimitry Andric 16760b57cec5SDimitry Andric // After this many iterations store-to-load forwarding conflicts should not 16770b57cec5SDimitry Andric // cause any slowdowns. 16780b57cec5SDimitry Andric const uint64_t NumItersForStoreLoadThroughMemory = 8 * TypeByteSize; 16790b57cec5SDimitry Andric // Maximum vector factor. 16800b57cec5SDimitry Andric uint64_t MaxVFWithoutSLForwardIssues = std::min( 16810b57cec5SDimitry Andric VectorizerParams::MaxVectorWidth * TypeByteSize, MaxSafeDepDistBytes); 16820b57cec5SDimitry Andric 16830b57cec5SDimitry Andric // Compute the smallest VF at which the store and load would be misaligned. 16840b57cec5SDimitry Andric for (uint64_t VF = 2 * TypeByteSize; VF <= MaxVFWithoutSLForwardIssues; 16850b57cec5SDimitry Andric VF *= 2) { 16860b57cec5SDimitry Andric // If the number of vector iteration between the store and the load are 16870b57cec5SDimitry Andric // small we could incur conflicts. 16880b57cec5SDimitry Andric if (Distance % VF && Distance / VF < NumItersForStoreLoadThroughMemory) { 1689e8d8bef9SDimitry Andric MaxVFWithoutSLForwardIssues = (VF >> 1); 16900b57cec5SDimitry Andric break; 16910b57cec5SDimitry Andric } 16920b57cec5SDimitry Andric } 16930b57cec5SDimitry Andric 16940b57cec5SDimitry Andric if (MaxVFWithoutSLForwardIssues < 2 * TypeByteSize) { 16950b57cec5SDimitry Andric LLVM_DEBUG( 16960b57cec5SDimitry Andric dbgs() << "LAA: Distance " << Distance 16970b57cec5SDimitry Andric << " that could cause a store-load forwarding conflict\n"); 16980b57cec5SDimitry Andric return true; 16990b57cec5SDimitry Andric } 17000b57cec5SDimitry Andric 17010b57cec5SDimitry Andric if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes && 17020b57cec5SDimitry Andric MaxVFWithoutSLForwardIssues != 17030b57cec5SDimitry Andric VectorizerParams::MaxVectorWidth * TypeByteSize) 17040b57cec5SDimitry Andric MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues; 17050b57cec5SDimitry Andric return false; 17060b57cec5SDimitry Andric } 17070b57cec5SDimitry Andric 17080b57cec5SDimitry Andric void MemoryDepChecker::mergeInStatus(VectorizationSafetyStatus S) { 17090b57cec5SDimitry Andric if (Status < S) 17100b57cec5SDimitry Andric Status = S; 17110b57cec5SDimitry Andric } 17120b57cec5SDimitry Andric 1713bdd1243dSDimitry Andric /// Given a dependence-distance \p Dist between two 17140b57cec5SDimitry Andric /// memory accesses, that have the same stride whose absolute value is given 17150b57cec5SDimitry Andric /// in \p Stride, and that have the same type size \p TypeByteSize, 17160b57cec5SDimitry Andric /// in a loop whose takenCount is \p BackedgeTakenCount, check if it is 17170b57cec5SDimitry Andric /// possible to prove statically that the dependence distance is larger 17180b57cec5SDimitry Andric /// than the range that the accesses will travel through the execution of 17190b57cec5SDimitry Andric /// the loop. If so, return true; false otherwise. This is useful for 17200b57cec5SDimitry Andric /// example in loops such as the following (PR31098): 17210b57cec5SDimitry Andric /// for (i = 0; i < D; ++i) { 17220b57cec5SDimitry Andric /// = out[i]; 17230b57cec5SDimitry Andric /// out[i+D] = 17240b57cec5SDimitry Andric /// } 17250b57cec5SDimitry Andric static bool isSafeDependenceDistance(const DataLayout &DL, ScalarEvolution &SE, 17260b57cec5SDimitry Andric const SCEV &BackedgeTakenCount, 17270b57cec5SDimitry Andric const SCEV &Dist, uint64_t Stride, 17280b57cec5SDimitry Andric uint64_t TypeByteSize) { 17290b57cec5SDimitry Andric 17300b57cec5SDimitry Andric // If we can prove that 17310b57cec5SDimitry Andric // (**) |Dist| > BackedgeTakenCount * Step 17320b57cec5SDimitry Andric // where Step is the absolute stride of the memory accesses in bytes, 17330b57cec5SDimitry Andric // then there is no dependence. 17340b57cec5SDimitry Andric // 17350b57cec5SDimitry Andric // Rationale: 17360b57cec5SDimitry Andric // We basically want to check if the absolute distance (|Dist/Step|) 17370b57cec5SDimitry Andric // is >= the loop iteration count (or > BackedgeTakenCount). 17380b57cec5SDimitry Andric // This is equivalent to the Strong SIV Test (Practical Dependence Testing, 17390b57cec5SDimitry Andric // Section 4.2.1); Note, that for vectorization it is sufficient to prove 17400b57cec5SDimitry Andric // that the dependence distance is >= VF; This is checked elsewhere. 1741bdd1243dSDimitry Andric // But in some cases we can prune dependence distances early, and 17420b57cec5SDimitry Andric // even before selecting the VF, and without a runtime test, by comparing 17430b57cec5SDimitry Andric // the distance against the loop iteration count. Since the vectorized code 17440b57cec5SDimitry Andric // will be executed only if LoopCount >= VF, proving distance >= LoopCount 17450b57cec5SDimitry Andric // also guarantees that distance >= VF. 17460b57cec5SDimitry Andric // 17470b57cec5SDimitry Andric const uint64_t ByteStride = Stride * TypeByteSize; 17480b57cec5SDimitry Andric const SCEV *Step = SE.getConstant(BackedgeTakenCount.getType(), ByteStride); 17490b57cec5SDimitry Andric const SCEV *Product = SE.getMulExpr(&BackedgeTakenCount, Step); 17500b57cec5SDimitry Andric 17510b57cec5SDimitry Andric const SCEV *CastedDist = &Dist; 17520b57cec5SDimitry Andric const SCEV *CastedProduct = Product; 175381ad6265SDimitry Andric uint64_t DistTypeSizeBits = DL.getTypeSizeInBits(Dist.getType()); 175481ad6265SDimitry Andric uint64_t ProductTypeSizeBits = DL.getTypeSizeInBits(Product->getType()); 17550b57cec5SDimitry Andric 17560b57cec5SDimitry Andric // The dependence distance can be positive/negative, so we sign extend Dist; 17570b57cec5SDimitry Andric // The multiplication of the absolute stride in bytes and the 17580b57cec5SDimitry Andric // backedgeTakenCount is non-negative, so we zero extend Product. 175981ad6265SDimitry Andric if (DistTypeSizeBits > ProductTypeSizeBits) 17600b57cec5SDimitry Andric CastedProduct = SE.getZeroExtendExpr(Product, Dist.getType()); 17610b57cec5SDimitry Andric else 17620b57cec5SDimitry Andric CastedDist = SE.getNoopOrSignExtend(&Dist, Product->getType()); 17630b57cec5SDimitry Andric 17640b57cec5SDimitry Andric // Is Dist - (BackedgeTakenCount * Step) > 0 ? 17650b57cec5SDimitry Andric // (If so, then we have proven (**) because |Dist| >= Dist) 17660b57cec5SDimitry Andric const SCEV *Minus = SE.getMinusSCEV(CastedDist, CastedProduct); 17670b57cec5SDimitry Andric if (SE.isKnownPositive(Minus)) 17680b57cec5SDimitry Andric return true; 17690b57cec5SDimitry Andric 17700b57cec5SDimitry Andric // Second try: Is -Dist - (BackedgeTakenCount * Step) > 0 ? 17710b57cec5SDimitry Andric // (If so, then we have proven (**) because |Dist| >= -1*Dist) 17720b57cec5SDimitry Andric const SCEV *NegDist = SE.getNegativeSCEV(CastedDist); 17730b57cec5SDimitry Andric Minus = SE.getMinusSCEV(NegDist, CastedProduct); 17740b57cec5SDimitry Andric if (SE.isKnownPositive(Minus)) 17750b57cec5SDimitry Andric return true; 17760b57cec5SDimitry Andric 17770b57cec5SDimitry Andric return false; 17780b57cec5SDimitry Andric } 17790b57cec5SDimitry Andric 17800b57cec5SDimitry Andric /// Check the dependence for two accesses with the same stride \p Stride. 17810b57cec5SDimitry Andric /// \p Distance is the positive distance and \p TypeByteSize is type size in 17820b57cec5SDimitry Andric /// bytes. 17830b57cec5SDimitry Andric /// 17840b57cec5SDimitry Andric /// \returns true if they are independent. 17850b57cec5SDimitry Andric static bool areStridedAccessesIndependent(uint64_t Distance, uint64_t Stride, 17860b57cec5SDimitry Andric uint64_t TypeByteSize) { 17870b57cec5SDimitry Andric assert(Stride > 1 && "The stride must be greater than 1"); 17880b57cec5SDimitry Andric assert(TypeByteSize > 0 && "The type size in byte must be non-zero"); 17890b57cec5SDimitry Andric assert(Distance > 0 && "The distance must be non-zero"); 17900b57cec5SDimitry Andric 17910b57cec5SDimitry Andric // Skip if the distance is not multiple of type byte size. 17920b57cec5SDimitry Andric if (Distance % TypeByteSize) 17930b57cec5SDimitry Andric return false; 17940b57cec5SDimitry Andric 17950b57cec5SDimitry Andric uint64_t ScaledDist = Distance / TypeByteSize; 17960b57cec5SDimitry Andric 17970b57cec5SDimitry Andric // No dependence if the scaled distance is not multiple of the stride. 17980b57cec5SDimitry Andric // E.g. 17990b57cec5SDimitry Andric // for (i = 0; i < 1024 ; i += 4) 18000b57cec5SDimitry Andric // A[i+2] = A[i] + 1; 18010b57cec5SDimitry Andric // 18020b57cec5SDimitry Andric // Two accesses in memory (scaled distance is 2, stride is 4): 18030b57cec5SDimitry Andric // | A[0] | | | | A[4] | | | | 18040b57cec5SDimitry Andric // | | | A[2] | | | | A[6] | | 18050b57cec5SDimitry Andric // 18060b57cec5SDimitry Andric // E.g. 18070b57cec5SDimitry Andric // for (i = 0; i < 1024 ; i += 3) 18080b57cec5SDimitry Andric // A[i+4] = A[i] + 1; 18090b57cec5SDimitry Andric // 18100b57cec5SDimitry Andric // Two accesses in memory (scaled distance is 4, stride is 3): 18110b57cec5SDimitry Andric // | A[0] | | | A[3] | | | A[6] | | | 18120b57cec5SDimitry Andric // | | | | | A[4] | | | A[7] | | 18130b57cec5SDimitry Andric return ScaledDist % Stride; 18140b57cec5SDimitry Andric } 18150b57cec5SDimitry Andric 18160b57cec5SDimitry Andric MemoryDepChecker::Dependence::DepType 18170b57cec5SDimitry Andric MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx, 18180b57cec5SDimitry Andric const MemAccessInfo &B, unsigned BIdx, 1819*fe013be4SDimitry Andric const DenseMap<Value *, const SCEV *> &Strides) { 18200b57cec5SDimitry Andric assert (AIdx < BIdx && "Must pass arguments in program order"); 18210b57cec5SDimitry Andric 1822bdd1243dSDimitry Andric auto [APtr, AIsWrite] = A; 1823bdd1243dSDimitry Andric auto [BPtr, BIsWrite] = B; 182481ad6265SDimitry Andric Type *ATy = getLoadStoreType(InstMap[AIdx]); 182581ad6265SDimitry Andric Type *BTy = getLoadStoreType(InstMap[BIdx]); 18260b57cec5SDimitry Andric 18270b57cec5SDimitry Andric // Two reads are independent. 18280b57cec5SDimitry Andric if (!AIsWrite && !BIsWrite) 18290b57cec5SDimitry Andric return Dependence::NoDep; 18300b57cec5SDimitry Andric 18310b57cec5SDimitry Andric // We cannot check pointers in different address spaces. 18320b57cec5SDimitry Andric if (APtr->getType()->getPointerAddressSpace() != 18330b57cec5SDimitry Andric BPtr->getType()->getPointerAddressSpace()) 18340b57cec5SDimitry Andric return Dependence::Unknown; 18350b57cec5SDimitry Andric 1836349cc55cSDimitry Andric int64_t StrideAPtr = 1837bdd1243dSDimitry Andric getPtrStride(PSE, ATy, APtr, InnermostLoop, Strides, true).value_or(0); 1838349cc55cSDimitry Andric int64_t StrideBPtr = 1839bdd1243dSDimitry Andric getPtrStride(PSE, BTy, BPtr, InnermostLoop, Strides, true).value_or(0); 18400b57cec5SDimitry Andric 18410b57cec5SDimitry Andric const SCEV *Src = PSE.getSCEV(APtr); 18420b57cec5SDimitry Andric const SCEV *Sink = PSE.getSCEV(BPtr); 18430b57cec5SDimitry Andric 18440b57cec5SDimitry Andric // If the induction step is negative we have to invert source and sink of the 18450b57cec5SDimitry Andric // dependence. 18460b57cec5SDimitry Andric if (StrideAPtr < 0) { 18470b57cec5SDimitry Andric std::swap(APtr, BPtr); 1848349cc55cSDimitry Andric std::swap(ATy, BTy); 18490b57cec5SDimitry Andric std::swap(Src, Sink); 18500b57cec5SDimitry Andric std::swap(AIsWrite, BIsWrite); 18510b57cec5SDimitry Andric std::swap(AIdx, BIdx); 18520b57cec5SDimitry Andric std::swap(StrideAPtr, StrideBPtr); 18530b57cec5SDimitry Andric } 18540b57cec5SDimitry Andric 1855bdd1243dSDimitry Andric ScalarEvolution &SE = *PSE.getSE(); 1856bdd1243dSDimitry Andric const SCEV *Dist = SE.getMinusSCEV(Sink, Src); 18570b57cec5SDimitry Andric 18580b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink 18590b57cec5SDimitry Andric << "(Induction step: " << StrideAPtr << ")\n"); 18600b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to " 18610b57cec5SDimitry Andric << *InstMap[BIdx] << ": " << *Dist << "\n"); 18620b57cec5SDimitry Andric 18630b57cec5SDimitry Andric // Need accesses with constant stride. We don't want to vectorize 18640b57cec5SDimitry Andric // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in 18650b57cec5SDimitry Andric // the address space. 18660b57cec5SDimitry Andric if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){ 18670b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Pointer access with non-constant stride\n"); 18680b57cec5SDimitry Andric return Dependence::Unknown; 18690b57cec5SDimitry Andric } 18700b57cec5SDimitry Andric 18710b57cec5SDimitry Andric auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout(); 18720b57cec5SDimitry Andric uint64_t TypeByteSize = DL.getTypeAllocSize(ATy); 18730eae32dcSDimitry Andric bool HasSameSize = 18740eae32dcSDimitry Andric DL.getTypeStoreSizeInBits(ATy) == DL.getTypeStoreSizeInBits(BTy); 18750b57cec5SDimitry Andric uint64_t Stride = std::abs(StrideAPtr); 1876bdd1243dSDimitry Andric 18770eae32dcSDimitry Andric if (!isa<SCEVCouldNotCompute>(Dist) && HasSameSize && 1878bdd1243dSDimitry Andric isSafeDependenceDistance(DL, SE, *(PSE.getBackedgeTakenCount()), *Dist, 1879bdd1243dSDimitry Andric Stride, TypeByteSize)) 18800b57cec5SDimitry Andric return Dependence::NoDep; 18810b57cec5SDimitry Andric 1882bdd1243dSDimitry Andric const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist); 1883bdd1243dSDimitry Andric if (!C) { 18840b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n"); 18850b57cec5SDimitry Andric FoundNonConstantDistanceDependence = true; 18860b57cec5SDimitry Andric return Dependence::Unknown; 18870b57cec5SDimitry Andric } 18880b57cec5SDimitry Andric 18890b57cec5SDimitry Andric const APInt &Val = C->getAPInt(); 18900b57cec5SDimitry Andric int64_t Distance = Val.getSExtValue(); 18910b57cec5SDimitry Andric 18920b57cec5SDimitry Andric // Attempt to prove strided accesses independent. 18930eae32dcSDimitry Andric if (std::abs(Distance) > 0 && Stride > 1 && HasSameSize && 18940b57cec5SDimitry Andric areStridedAccessesIndependent(std::abs(Distance), Stride, TypeByteSize)) { 18950b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Strided accesses are independent\n"); 18960b57cec5SDimitry Andric return Dependence::NoDep; 18970b57cec5SDimitry Andric } 18980b57cec5SDimitry Andric 18990b57cec5SDimitry Andric // Negative distances are not plausible dependencies. 19000b57cec5SDimitry Andric if (Val.isNegative()) { 19010b57cec5SDimitry Andric bool IsTrueDataDependence = (AIsWrite && !BIsWrite); 19020b57cec5SDimitry Andric if (IsTrueDataDependence && EnableForwardingConflictDetection && 19030b57cec5SDimitry Andric (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) || 19040eae32dcSDimitry Andric !HasSameSize)) { 19050b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Forward but may prevent st->ld forwarding\n"); 19060b57cec5SDimitry Andric return Dependence::ForwardButPreventsForwarding; 19070b57cec5SDimitry Andric } 19080b57cec5SDimitry Andric 19090b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Dependence is negative\n"); 19100b57cec5SDimitry Andric return Dependence::Forward; 19110b57cec5SDimitry Andric } 19120b57cec5SDimitry Andric 19130b57cec5SDimitry Andric // Write to the same location with the same size. 19140b57cec5SDimitry Andric if (Val == 0) { 19150eae32dcSDimitry Andric if (HasSameSize) 19160b57cec5SDimitry Andric return Dependence::Forward; 19170b57cec5SDimitry Andric LLVM_DEBUG( 19180eae32dcSDimitry Andric dbgs() << "LAA: Zero dependence difference but different type sizes\n"); 19190b57cec5SDimitry Andric return Dependence::Unknown; 19200b57cec5SDimitry Andric } 19210b57cec5SDimitry Andric 19220b57cec5SDimitry Andric assert(Val.isStrictlyPositive() && "Expect a positive value"); 19230b57cec5SDimitry Andric 19240eae32dcSDimitry Andric if (!HasSameSize) { 19250eae32dcSDimitry Andric LLVM_DEBUG(dbgs() << "LAA: ReadWrite-Write positive dependency with " 19260eae32dcSDimitry Andric "different type sizes\n"); 19270b57cec5SDimitry Andric return Dependence::Unknown; 19280b57cec5SDimitry Andric } 19290b57cec5SDimitry Andric 19300b57cec5SDimitry Andric // Bail out early if passed-in parameters make vectorization not feasible. 19310b57cec5SDimitry Andric unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ? 19320b57cec5SDimitry Andric VectorizerParams::VectorizationFactor : 1); 19330b57cec5SDimitry Andric unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ? 19340b57cec5SDimitry Andric VectorizerParams::VectorizationInterleave : 1); 19350b57cec5SDimitry Andric // The minimum number of iterations for a vectorized/unrolled version. 19360b57cec5SDimitry Andric unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U); 19370b57cec5SDimitry Andric 19380b57cec5SDimitry Andric // It's not vectorizable if the distance is smaller than the minimum distance 19390b57cec5SDimitry Andric // needed for a vectroized/unrolled version. Vectorizing one iteration in 19400b57cec5SDimitry Andric // front needs TypeByteSize * Stride. Vectorizing the last iteration needs 19410b57cec5SDimitry Andric // TypeByteSize (No need to plus the last gap distance). 19420b57cec5SDimitry Andric // 19430b57cec5SDimitry Andric // E.g. Assume one char is 1 byte in memory and one int is 4 bytes. 19440b57cec5SDimitry Andric // foo(int *A) { 19450b57cec5SDimitry Andric // int *B = (int *)((char *)A + 14); 19460b57cec5SDimitry Andric // for (i = 0 ; i < 1024 ; i += 2) 19470b57cec5SDimitry Andric // B[i] = A[i] + 1; 19480b57cec5SDimitry Andric // } 19490b57cec5SDimitry Andric // 19500b57cec5SDimitry Andric // Two accesses in memory (stride is 2): 19510b57cec5SDimitry Andric // | A[0] | | A[2] | | A[4] | | A[6] | | 19520b57cec5SDimitry Andric // | B[0] | | B[2] | | B[4] | 19530b57cec5SDimitry Andric // 19540b57cec5SDimitry Andric // Distance needs for vectorizing iterations except the last iteration: 19550b57cec5SDimitry Andric // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4. 19560b57cec5SDimitry Andric // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4. 19570b57cec5SDimitry Andric // 19580b57cec5SDimitry Andric // If MinNumIter is 2, it is vectorizable as the minimum distance needed is 19590b57cec5SDimitry Andric // 12, which is less than distance. 19600b57cec5SDimitry Andric // 19610b57cec5SDimitry Andric // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4), 19620b57cec5SDimitry Andric // the minimum distance needed is 28, which is greater than distance. It is 19630b57cec5SDimitry Andric // not safe to do vectorization. 19640b57cec5SDimitry Andric uint64_t MinDistanceNeeded = 19650b57cec5SDimitry Andric TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize; 19660b57cec5SDimitry Andric if (MinDistanceNeeded > static_cast<uint64_t>(Distance)) { 19670b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Failure because of positive distance " 19680b57cec5SDimitry Andric << Distance << '\n'); 19690b57cec5SDimitry Andric return Dependence::Backward; 19700b57cec5SDimitry Andric } 19710b57cec5SDimitry Andric 19720b57cec5SDimitry Andric // Unsafe if the minimum distance needed is greater than max safe distance. 19730b57cec5SDimitry Andric if (MinDistanceNeeded > MaxSafeDepDistBytes) { 19740b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Failure because it needs at least " 1975bdd1243dSDimitry Andric << MinDistanceNeeded << " size in bytes\n"); 19760b57cec5SDimitry Andric return Dependence::Backward; 19770b57cec5SDimitry Andric } 19780b57cec5SDimitry Andric 19790b57cec5SDimitry Andric // Positive distance bigger than max vectorization factor. 19800b57cec5SDimitry Andric // FIXME: Should use max factor instead of max distance in bytes, which could 19810b57cec5SDimitry Andric // not handle different types. 19820b57cec5SDimitry Andric // E.g. Assume one char is 1 byte in memory and one int is 4 bytes. 19830b57cec5SDimitry Andric // void foo (int *A, char *B) { 19840b57cec5SDimitry Andric // for (unsigned i = 0; i < 1024; i++) { 19850b57cec5SDimitry Andric // A[i+2] = A[i] + 1; 19860b57cec5SDimitry Andric // B[i+2] = B[i] + 1; 19870b57cec5SDimitry Andric // } 19880b57cec5SDimitry Andric // } 19890b57cec5SDimitry Andric // 19900b57cec5SDimitry Andric // This case is currently unsafe according to the max safe distance. If we 19910b57cec5SDimitry Andric // analyze the two accesses on array B, the max safe dependence distance 19920b57cec5SDimitry Andric // is 2. Then we analyze the accesses on array A, the minimum distance needed 19930b57cec5SDimitry Andric // is 8, which is less than 2 and forbidden vectorization, But actually 19940b57cec5SDimitry Andric // both A and B could be vectorized by 2 iterations. 19950b57cec5SDimitry Andric MaxSafeDepDistBytes = 19960b57cec5SDimitry Andric std::min(static_cast<uint64_t>(Distance), MaxSafeDepDistBytes); 19970b57cec5SDimitry Andric 19980b57cec5SDimitry Andric bool IsTrueDataDependence = (!AIsWrite && BIsWrite); 19990b57cec5SDimitry Andric if (IsTrueDataDependence && EnableForwardingConflictDetection && 20000b57cec5SDimitry Andric couldPreventStoreLoadForward(Distance, TypeByteSize)) 20010b57cec5SDimitry Andric return Dependence::BackwardVectorizableButPreventsForwarding; 20020b57cec5SDimitry Andric 20030b57cec5SDimitry Andric uint64_t MaxVF = MaxSafeDepDistBytes / (TypeByteSize * Stride); 20040b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue() 20050b57cec5SDimitry Andric << " with max VF = " << MaxVF << '\n'); 20060b57cec5SDimitry Andric uint64_t MaxVFInBits = MaxVF * TypeByteSize * 8; 2007e8d8bef9SDimitry Andric MaxSafeVectorWidthInBits = std::min(MaxSafeVectorWidthInBits, MaxVFInBits); 20080b57cec5SDimitry Andric return Dependence::BackwardVectorizable; 20090b57cec5SDimitry Andric } 20100b57cec5SDimitry Andric 20110b57cec5SDimitry Andric bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets, 20120b57cec5SDimitry Andric MemAccessInfoList &CheckDeps, 2013*fe013be4SDimitry Andric const DenseMap<Value *, const SCEV *> &Strides) { 20140b57cec5SDimitry Andric 20150b57cec5SDimitry Andric MaxSafeDepDistBytes = -1; 20160b57cec5SDimitry Andric SmallPtrSet<MemAccessInfo, 8> Visited; 20170b57cec5SDimitry Andric for (MemAccessInfo CurAccess : CheckDeps) { 20180b57cec5SDimitry Andric if (Visited.count(CurAccess)) 20190b57cec5SDimitry Andric continue; 20200b57cec5SDimitry Andric 20210b57cec5SDimitry Andric // Get the relevant memory access set. 20220b57cec5SDimitry Andric EquivalenceClasses<MemAccessInfo>::iterator I = 20230b57cec5SDimitry Andric AccessSets.findValue(AccessSets.getLeaderValue(CurAccess)); 20240b57cec5SDimitry Andric 20250b57cec5SDimitry Andric // Check accesses within this set. 20260b57cec5SDimitry Andric EquivalenceClasses<MemAccessInfo>::member_iterator AI = 20270b57cec5SDimitry Andric AccessSets.member_begin(I); 20280b57cec5SDimitry Andric EquivalenceClasses<MemAccessInfo>::member_iterator AE = 20290b57cec5SDimitry Andric AccessSets.member_end(); 20300b57cec5SDimitry Andric 20310b57cec5SDimitry Andric // Check every access pair. 20320b57cec5SDimitry Andric while (AI != AE) { 20330b57cec5SDimitry Andric Visited.insert(*AI); 20348bcb0991SDimitry Andric bool AIIsWrite = AI->getInt(); 20358bcb0991SDimitry Andric // Check loads only against next equivalent class, but stores also against 20368bcb0991SDimitry Andric // other stores in the same equivalence class - to the same address. 20378bcb0991SDimitry Andric EquivalenceClasses<MemAccessInfo>::member_iterator OI = 20388bcb0991SDimitry Andric (AIIsWrite ? AI : std::next(AI)); 20390b57cec5SDimitry Andric while (OI != AE) { 20400b57cec5SDimitry Andric // Check every accessing instruction pair in program order. 20410b57cec5SDimitry Andric for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(), 20420b57cec5SDimitry Andric I1E = Accesses[*AI].end(); I1 != I1E; ++I1) 20438bcb0991SDimitry Andric // Scan all accesses of another equivalence class, but only the next 20448bcb0991SDimitry Andric // accesses of the same equivalent class. 20458bcb0991SDimitry Andric for (std::vector<unsigned>::iterator 20468bcb0991SDimitry Andric I2 = (OI == AI ? std::next(I1) : Accesses[*OI].begin()), 20478bcb0991SDimitry Andric I2E = (OI == AI ? I1E : Accesses[*OI].end()); 20488bcb0991SDimitry Andric I2 != I2E; ++I2) { 20490b57cec5SDimitry Andric auto A = std::make_pair(&*AI, *I1); 20500b57cec5SDimitry Andric auto B = std::make_pair(&*OI, *I2); 20510b57cec5SDimitry Andric 20520b57cec5SDimitry Andric assert(*I1 != *I2); 20530b57cec5SDimitry Andric if (*I1 > *I2) 20540b57cec5SDimitry Andric std::swap(A, B); 20550b57cec5SDimitry Andric 20560b57cec5SDimitry Andric Dependence::DepType Type = 20570b57cec5SDimitry Andric isDependent(*A.first, A.second, *B.first, B.second, Strides); 20580b57cec5SDimitry Andric mergeInStatus(Dependence::isSafeForVectorization(Type)); 20590b57cec5SDimitry Andric 20600b57cec5SDimitry Andric // Gather dependences unless we accumulated MaxDependences 20610b57cec5SDimitry Andric // dependences. In that case return as soon as we find the first 20620b57cec5SDimitry Andric // unsafe dependence. This puts a limit on this quadratic 20630b57cec5SDimitry Andric // algorithm. 20640b57cec5SDimitry Andric if (RecordDependences) { 20650b57cec5SDimitry Andric if (Type != Dependence::NoDep) 20660b57cec5SDimitry Andric Dependences.push_back(Dependence(A.second, B.second, Type)); 20670b57cec5SDimitry Andric 20680b57cec5SDimitry Andric if (Dependences.size() >= MaxDependences) { 20690b57cec5SDimitry Andric RecordDependences = false; 20700b57cec5SDimitry Andric Dependences.clear(); 20710b57cec5SDimitry Andric LLVM_DEBUG(dbgs() 20720b57cec5SDimitry Andric << "Too many dependences, stopped recording\n"); 20730b57cec5SDimitry Andric } 20740b57cec5SDimitry Andric } 20750b57cec5SDimitry Andric if (!RecordDependences && !isSafeForVectorization()) 20760b57cec5SDimitry Andric return false; 20770b57cec5SDimitry Andric } 20780b57cec5SDimitry Andric ++OI; 20790b57cec5SDimitry Andric } 20800b57cec5SDimitry Andric AI++; 20810b57cec5SDimitry Andric } 20820b57cec5SDimitry Andric } 20830b57cec5SDimitry Andric 20840b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Total Dependences: " << Dependences.size() << "\n"); 20850b57cec5SDimitry Andric return isSafeForVectorization(); 20860b57cec5SDimitry Andric } 20870b57cec5SDimitry Andric 20880b57cec5SDimitry Andric SmallVector<Instruction *, 4> 20890b57cec5SDimitry Andric MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const { 20900b57cec5SDimitry Andric MemAccessInfo Access(Ptr, isWrite); 20910b57cec5SDimitry Andric auto &IndexVector = Accesses.find(Access)->second; 20920b57cec5SDimitry Andric 20930b57cec5SDimitry Andric SmallVector<Instruction *, 4> Insts; 20940b57cec5SDimitry Andric transform(IndexVector, 20950b57cec5SDimitry Andric std::back_inserter(Insts), 20960b57cec5SDimitry Andric [&](unsigned Idx) { return this->InstMap[Idx]; }); 20970b57cec5SDimitry Andric return Insts; 20980b57cec5SDimitry Andric } 20990b57cec5SDimitry Andric 21000b57cec5SDimitry Andric const char *MemoryDepChecker::Dependence::DepName[] = { 21010b57cec5SDimitry Andric "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward", 21020b57cec5SDimitry Andric "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"}; 21030b57cec5SDimitry Andric 21040b57cec5SDimitry Andric void MemoryDepChecker::Dependence::print( 21050b57cec5SDimitry Andric raw_ostream &OS, unsigned Depth, 21060b57cec5SDimitry Andric const SmallVectorImpl<Instruction *> &Instrs) const { 21070b57cec5SDimitry Andric OS.indent(Depth) << DepName[Type] << ":\n"; 21080b57cec5SDimitry Andric OS.indent(Depth + 2) << *Instrs[Source] << " -> \n"; 21090b57cec5SDimitry Andric OS.indent(Depth + 2) << *Instrs[Destination] << "\n"; 21100b57cec5SDimitry Andric } 21110b57cec5SDimitry Andric 21120b57cec5SDimitry Andric bool LoopAccessInfo::canAnalyzeLoop() { 21130b57cec5SDimitry Andric // We need to have a loop header. 21140b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found a loop in " 21150b57cec5SDimitry Andric << TheLoop->getHeader()->getParent()->getName() << ": " 21160b57cec5SDimitry Andric << TheLoop->getHeader()->getName() << '\n'); 21170b57cec5SDimitry Andric 21180b57cec5SDimitry Andric // We can only analyze innermost loops. 2119e8d8bef9SDimitry Andric if (!TheLoop->isInnermost()) { 21200b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: loop is not the innermost loop\n"); 21210b57cec5SDimitry Andric recordAnalysis("NotInnerMostLoop") << "loop is not the innermost loop"; 21220b57cec5SDimitry Andric return false; 21230b57cec5SDimitry Andric } 21240b57cec5SDimitry Andric 21250b57cec5SDimitry Andric // We must have a single backedge. 21260b57cec5SDimitry Andric if (TheLoop->getNumBackEdges() != 1) { 21270b57cec5SDimitry Andric LLVM_DEBUG( 21280b57cec5SDimitry Andric dbgs() << "LAA: loop control flow is not understood by analyzer\n"); 21290b57cec5SDimitry Andric recordAnalysis("CFGNotUnderstood") 21300b57cec5SDimitry Andric << "loop control flow is not understood by analyzer"; 21310b57cec5SDimitry Andric return false; 21320b57cec5SDimitry Andric } 21330b57cec5SDimitry Andric 21340b57cec5SDimitry Andric // ScalarEvolution needs to be able to find the exit count. 21350b57cec5SDimitry Andric const SCEV *ExitCount = PSE->getBackedgeTakenCount(); 2136e8d8bef9SDimitry Andric if (isa<SCEVCouldNotCompute>(ExitCount)) { 21370b57cec5SDimitry Andric recordAnalysis("CantComputeNumberOfIterations") 21380b57cec5SDimitry Andric << "could not determine number of loop iterations"; 21390b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n"); 21400b57cec5SDimitry Andric return false; 21410b57cec5SDimitry Andric } 21420b57cec5SDimitry Andric 21430b57cec5SDimitry Andric return true; 21440b57cec5SDimitry Andric } 21450b57cec5SDimitry Andric 21465ffd83dbSDimitry Andric void LoopAccessInfo::analyzeLoop(AAResults *AA, LoopInfo *LI, 21470b57cec5SDimitry Andric const TargetLibraryInfo *TLI, 21480b57cec5SDimitry Andric DominatorTree *DT) { 21490b57cec5SDimitry Andric // Holds the Load and Store instructions. 21500b57cec5SDimitry Andric SmallVector<LoadInst *, 16> Loads; 21510b57cec5SDimitry Andric SmallVector<StoreInst *, 16> Stores; 21520b57cec5SDimitry Andric 21530b57cec5SDimitry Andric // Holds all the different accesses in the loop. 21540b57cec5SDimitry Andric unsigned NumReads = 0; 21550b57cec5SDimitry Andric unsigned NumReadWrites = 0; 21560b57cec5SDimitry Andric 21570b57cec5SDimitry Andric bool HasComplexMemInst = false; 21580b57cec5SDimitry Andric 21590b57cec5SDimitry Andric // A runtime check is only legal to insert if there are no convergent calls. 21600b57cec5SDimitry Andric HasConvergentOp = false; 21610b57cec5SDimitry Andric 21620b57cec5SDimitry Andric PtrRtChecking->Pointers.clear(); 21630b57cec5SDimitry Andric PtrRtChecking->Need = false; 21640b57cec5SDimitry Andric 21650b57cec5SDimitry Andric const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel(); 21660b57cec5SDimitry Andric 21675ffd83dbSDimitry Andric const bool EnableMemAccessVersioningOfLoop = 21685ffd83dbSDimitry Andric EnableMemAccessVersioning && 21695ffd83dbSDimitry Andric !TheLoop->getHeader()->getParent()->hasOptSize(); 21705ffd83dbSDimitry Andric 2171bdd1243dSDimitry Andric // Traverse blocks in fixed RPOT order, regardless of their storage in the 2172bdd1243dSDimitry Andric // loop info, as it may be arbitrary. 2173bdd1243dSDimitry Andric LoopBlocksRPO RPOT(TheLoop); 2174bdd1243dSDimitry Andric RPOT.perform(LI); 2175bdd1243dSDimitry Andric for (BasicBlock *BB : RPOT) { 21760b57cec5SDimitry Andric // Scan the BB and collect legal loads and stores. Also detect any 21770b57cec5SDimitry Andric // convergent instructions. 21780b57cec5SDimitry Andric for (Instruction &I : *BB) { 21790b57cec5SDimitry Andric if (auto *Call = dyn_cast<CallBase>(&I)) { 21800b57cec5SDimitry Andric if (Call->isConvergent()) 21810b57cec5SDimitry Andric HasConvergentOp = true; 21820b57cec5SDimitry Andric } 21830b57cec5SDimitry Andric 21840b57cec5SDimitry Andric // With both a non-vectorizable memory instruction and a convergent 21850b57cec5SDimitry Andric // operation, found in this loop, no reason to continue the search. 21860b57cec5SDimitry Andric if (HasComplexMemInst && HasConvergentOp) { 21870b57cec5SDimitry Andric CanVecMem = false; 21880b57cec5SDimitry Andric return; 21890b57cec5SDimitry Andric } 21900b57cec5SDimitry Andric 21910b57cec5SDimitry Andric // Avoid hitting recordAnalysis multiple times. 21920b57cec5SDimitry Andric if (HasComplexMemInst) 21930b57cec5SDimitry Andric continue; 21940b57cec5SDimitry Andric 21950b57cec5SDimitry Andric // If this is a load, save it. If this instruction can read from memory 21960b57cec5SDimitry Andric // but is not a load, then we quit. Notice that we don't handle function 21970b57cec5SDimitry Andric // calls that read or write. 21980b57cec5SDimitry Andric if (I.mayReadFromMemory()) { 21990b57cec5SDimitry Andric // Many math library functions read the rounding mode. We will only 22000b57cec5SDimitry Andric // vectorize a loop if it contains known function calls that don't set 22010b57cec5SDimitry Andric // the flag. Therefore, it is safe to ignore this read from memory. 22020b57cec5SDimitry Andric auto *Call = dyn_cast<CallInst>(&I); 22030b57cec5SDimitry Andric if (Call && getVectorIntrinsicIDForCall(Call, TLI)) 22040b57cec5SDimitry Andric continue; 22050b57cec5SDimitry Andric 22060b57cec5SDimitry Andric // If the function has an explicit vectorized counterpart, we can safely 22070b57cec5SDimitry Andric // assume that it can be vectorized. 22080b57cec5SDimitry Andric if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() && 22095ffd83dbSDimitry Andric !VFDatabase::getMappings(*Call).empty()) 22100b57cec5SDimitry Andric continue; 22110b57cec5SDimitry Andric 22120b57cec5SDimitry Andric auto *Ld = dyn_cast<LoadInst>(&I); 22130b57cec5SDimitry Andric if (!Ld) { 22140b57cec5SDimitry Andric recordAnalysis("CantVectorizeInstruction", Ld) 22150b57cec5SDimitry Andric << "instruction cannot be vectorized"; 22160b57cec5SDimitry Andric HasComplexMemInst = true; 22170b57cec5SDimitry Andric continue; 22180b57cec5SDimitry Andric } 22190b57cec5SDimitry Andric if (!Ld->isSimple() && !IsAnnotatedParallel) { 22200b57cec5SDimitry Andric recordAnalysis("NonSimpleLoad", Ld) 22210b57cec5SDimitry Andric << "read with atomic ordering or volatile read"; 22220b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found a non-simple load.\n"); 22230b57cec5SDimitry Andric HasComplexMemInst = true; 22240b57cec5SDimitry Andric continue; 22250b57cec5SDimitry Andric } 22260b57cec5SDimitry Andric NumLoads++; 22270b57cec5SDimitry Andric Loads.push_back(Ld); 22280b57cec5SDimitry Andric DepChecker->addAccess(Ld); 22295ffd83dbSDimitry Andric if (EnableMemAccessVersioningOfLoop) 22300b57cec5SDimitry Andric collectStridedAccess(Ld); 22310b57cec5SDimitry Andric continue; 22320b57cec5SDimitry Andric } 22330b57cec5SDimitry Andric 22340b57cec5SDimitry Andric // Save 'store' instructions. Abort if other instructions write to memory. 22350b57cec5SDimitry Andric if (I.mayWriteToMemory()) { 22360b57cec5SDimitry Andric auto *St = dyn_cast<StoreInst>(&I); 22370b57cec5SDimitry Andric if (!St) { 22380b57cec5SDimitry Andric recordAnalysis("CantVectorizeInstruction", St) 22390b57cec5SDimitry Andric << "instruction cannot be vectorized"; 22400b57cec5SDimitry Andric HasComplexMemInst = true; 22410b57cec5SDimitry Andric continue; 22420b57cec5SDimitry Andric } 22430b57cec5SDimitry Andric if (!St->isSimple() && !IsAnnotatedParallel) { 22440b57cec5SDimitry Andric recordAnalysis("NonSimpleStore", St) 22450b57cec5SDimitry Andric << "write with atomic ordering or volatile write"; 22460b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found a non-simple store.\n"); 22470b57cec5SDimitry Andric HasComplexMemInst = true; 22480b57cec5SDimitry Andric continue; 22490b57cec5SDimitry Andric } 22500b57cec5SDimitry Andric NumStores++; 22510b57cec5SDimitry Andric Stores.push_back(St); 22520b57cec5SDimitry Andric DepChecker->addAccess(St); 22535ffd83dbSDimitry Andric if (EnableMemAccessVersioningOfLoop) 22540b57cec5SDimitry Andric collectStridedAccess(St); 22550b57cec5SDimitry Andric } 22560b57cec5SDimitry Andric } // Next instr. 22570b57cec5SDimitry Andric } // Next block. 22580b57cec5SDimitry Andric 22590b57cec5SDimitry Andric if (HasComplexMemInst) { 22600b57cec5SDimitry Andric CanVecMem = false; 22610b57cec5SDimitry Andric return; 22620b57cec5SDimitry Andric } 22630b57cec5SDimitry Andric 22640b57cec5SDimitry Andric // Now we have two lists that hold the loads and the stores. 22650b57cec5SDimitry Andric // Next, we find the pointers that they use. 22660b57cec5SDimitry Andric 22670b57cec5SDimitry Andric // Check if we see any stores. If there are no stores, then we don't 22680b57cec5SDimitry Andric // care if the pointers are *restrict*. 22690b57cec5SDimitry Andric if (!Stores.size()) { 22700b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found a read-only loop!\n"); 22710b57cec5SDimitry Andric CanVecMem = true; 22720b57cec5SDimitry Andric return; 22730b57cec5SDimitry Andric } 22740b57cec5SDimitry Andric 22750b57cec5SDimitry Andric MemoryDepChecker::DepCandidates DependentAccesses; 2276e8d8bef9SDimitry Andric AccessAnalysis Accesses(TheLoop, AA, LI, DependentAccesses, *PSE); 22770b57cec5SDimitry Andric 2278e8d8bef9SDimitry Andric // Holds the analyzed pointers. We don't want to call getUnderlyingObjects 22790b57cec5SDimitry Andric // multiple times on the same object. If the ptr is accessed twice, once 22800b57cec5SDimitry Andric // for read and once for write, it will only appear once (on the write 22810b57cec5SDimitry Andric // list). This is okay, since we are going to check for conflicts between 22820b57cec5SDimitry Andric // writes and between reads and writes, but not between reads and reads. 228381ad6265SDimitry Andric SmallSet<std::pair<Value *, Type *>, 16> Seen; 22840b57cec5SDimitry Andric 22850b57cec5SDimitry Andric // Record uniform store addresses to identify if we have multiple stores 22860b57cec5SDimitry Andric // to the same address. 228781ad6265SDimitry Andric SmallPtrSet<Value *, 16> UniformStores; 22880b57cec5SDimitry Andric 22890b57cec5SDimitry Andric for (StoreInst *ST : Stores) { 22900b57cec5SDimitry Andric Value *Ptr = ST->getPointerOperand(); 22910b57cec5SDimitry Andric 2292*fe013be4SDimitry Andric if (isInvariant(Ptr)) { 229381ad6265SDimitry Andric // Record store instructions to loop invariant addresses 229481ad6265SDimitry Andric StoresToInvariantAddresses.push_back(ST); 22950b57cec5SDimitry Andric HasDependenceInvolvingLoopInvariantAddress |= 22960b57cec5SDimitry Andric !UniformStores.insert(Ptr).second; 229781ad6265SDimitry Andric } 22980b57cec5SDimitry Andric 22990b57cec5SDimitry Andric // If we did *not* see this pointer before, insert it to the read-write 23000b57cec5SDimitry Andric // list. At this phase it is only a 'write' list. 230181ad6265SDimitry Andric Type *AccessTy = getLoadStoreType(ST); 230281ad6265SDimitry Andric if (Seen.insert({Ptr, AccessTy}).second) { 23030b57cec5SDimitry Andric ++NumReadWrites; 23040b57cec5SDimitry Andric 23050b57cec5SDimitry Andric MemoryLocation Loc = MemoryLocation::get(ST); 23060b57cec5SDimitry Andric // The TBAA metadata could have a control dependency on the predication 23070b57cec5SDimitry Andric // condition, so we cannot rely on it when determining whether or not we 23080b57cec5SDimitry Andric // need runtime pointer checks. 23090b57cec5SDimitry Andric if (blockNeedsPredication(ST->getParent(), TheLoop, DT)) 23100b57cec5SDimitry Andric Loc.AATags.TBAA = nullptr; 23110b57cec5SDimitry Andric 2312349cc55cSDimitry Andric visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop, 231381ad6265SDimitry Andric [&Accesses, AccessTy, Loc](Value *Ptr) { 2314349cc55cSDimitry Andric MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr); 231581ad6265SDimitry Andric Accesses.addStore(NewLoc, AccessTy); 2316349cc55cSDimitry Andric }); 23170b57cec5SDimitry Andric } 23180b57cec5SDimitry Andric } 23190b57cec5SDimitry Andric 23200b57cec5SDimitry Andric if (IsAnnotatedParallel) { 23210b57cec5SDimitry Andric LLVM_DEBUG( 23220b57cec5SDimitry Andric dbgs() << "LAA: A loop annotated parallel, ignore memory dependency " 23230b57cec5SDimitry Andric << "checks.\n"); 23240b57cec5SDimitry Andric CanVecMem = true; 23250b57cec5SDimitry Andric return; 23260b57cec5SDimitry Andric } 23270b57cec5SDimitry Andric 23280b57cec5SDimitry Andric for (LoadInst *LD : Loads) { 23290b57cec5SDimitry Andric Value *Ptr = LD->getPointerOperand(); 23300b57cec5SDimitry Andric // If we did *not* see this pointer before, insert it to the 23310b57cec5SDimitry Andric // read list. If we *did* see it before, then it is already in 23320b57cec5SDimitry Andric // the read-write list. This allows us to vectorize expressions 23330b57cec5SDimitry Andric // such as A[i] += x; Because the address of A[i] is a read-write 23340b57cec5SDimitry Andric // pointer. This only works if the index of A[i] is consecutive. 23350b57cec5SDimitry Andric // If the address of i is unknown (for example A[B[i]]) then we may 23360b57cec5SDimitry Andric // read a few words, modify, and write a few words, and some of the 23370b57cec5SDimitry Andric // words may be written to the same address. 23380b57cec5SDimitry Andric bool IsReadOnlyPtr = false; 233981ad6265SDimitry Andric Type *AccessTy = getLoadStoreType(LD); 234081ad6265SDimitry Andric if (Seen.insert({Ptr, AccessTy}).second || 2341bdd1243dSDimitry Andric !getPtrStride(*PSE, LD->getType(), Ptr, TheLoop, SymbolicStrides).value_or(0)) { 23420b57cec5SDimitry Andric ++NumReads; 23430b57cec5SDimitry Andric IsReadOnlyPtr = true; 23440b57cec5SDimitry Andric } 23450b57cec5SDimitry Andric 23460b57cec5SDimitry Andric // See if there is an unsafe dependency between a load to a uniform address and 23470b57cec5SDimitry Andric // store to the same uniform address. 23480b57cec5SDimitry Andric if (UniformStores.count(Ptr)) { 23490b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found an unsafe dependency between a uniform " 23500b57cec5SDimitry Andric "load and uniform store to the same address!\n"); 23510b57cec5SDimitry Andric HasDependenceInvolvingLoopInvariantAddress = true; 23520b57cec5SDimitry Andric } 23530b57cec5SDimitry Andric 23540b57cec5SDimitry Andric MemoryLocation Loc = MemoryLocation::get(LD); 23550b57cec5SDimitry Andric // The TBAA metadata could have a control dependency on the predication 23560b57cec5SDimitry Andric // condition, so we cannot rely on it when determining whether or not we 23570b57cec5SDimitry Andric // need runtime pointer checks. 23580b57cec5SDimitry Andric if (blockNeedsPredication(LD->getParent(), TheLoop, DT)) 23590b57cec5SDimitry Andric Loc.AATags.TBAA = nullptr; 23600b57cec5SDimitry Andric 2361349cc55cSDimitry Andric visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop, 236281ad6265SDimitry Andric [&Accesses, AccessTy, Loc, IsReadOnlyPtr](Value *Ptr) { 2363349cc55cSDimitry Andric MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr); 236481ad6265SDimitry Andric Accesses.addLoad(NewLoc, AccessTy, IsReadOnlyPtr); 2365349cc55cSDimitry Andric }); 23660b57cec5SDimitry Andric } 23670b57cec5SDimitry Andric 23680b57cec5SDimitry Andric // If we write (or read-write) to a single destination and there are no 23690b57cec5SDimitry Andric // other reads in this loop then is it safe to vectorize. 23700b57cec5SDimitry Andric if (NumReadWrites == 1 && NumReads == 0) { 23710b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found a write-only loop!\n"); 23720b57cec5SDimitry Andric CanVecMem = true; 23730b57cec5SDimitry Andric return; 23740b57cec5SDimitry Andric } 23750b57cec5SDimitry Andric 23760b57cec5SDimitry Andric // Build dependence sets and check whether we need a runtime pointer bounds 23770b57cec5SDimitry Andric // check. 23780b57cec5SDimitry Andric Accesses.buildDependenceSets(); 23790b57cec5SDimitry Andric 23800b57cec5SDimitry Andric // Find pointers with computable bounds. We are going to use this information 23810b57cec5SDimitry Andric // to place a runtime bound check. 238281ad6265SDimitry Andric Value *UncomputablePtr = nullptr; 238381ad6265SDimitry Andric bool CanDoRTIfNeeded = 238481ad6265SDimitry Andric Accesses.canCheckPtrAtRT(*PtrRtChecking, PSE->getSE(), TheLoop, 238581ad6265SDimitry Andric SymbolicStrides, UncomputablePtr, false); 23860b57cec5SDimitry Andric if (!CanDoRTIfNeeded) { 238781ad6265SDimitry Andric auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr); 238881ad6265SDimitry Andric recordAnalysis("CantIdentifyArrayBounds", I) 238981ad6265SDimitry Andric << "cannot identify array bounds"; 23900b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because we can't find " 23910b57cec5SDimitry Andric << "the array bounds.\n"); 23920b57cec5SDimitry Andric CanVecMem = false; 23930b57cec5SDimitry Andric return; 23940b57cec5SDimitry Andric } 23950b57cec5SDimitry Andric 23960b57cec5SDimitry Andric LLVM_DEBUG( 23970b57cec5SDimitry Andric dbgs() << "LAA: May be able to perform a memory runtime check if needed.\n"); 23980b57cec5SDimitry Andric 23990b57cec5SDimitry Andric CanVecMem = true; 24000b57cec5SDimitry Andric if (Accesses.isDependencyCheckNeeded()) { 24010b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Checking memory dependencies\n"); 24020b57cec5SDimitry Andric CanVecMem = DepChecker->areDepsSafe( 24030b57cec5SDimitry Andric DependentAccesses, Accesses.getDependenciesToCheck(), SymbolicStrides); 24040b57cec5SDimitry Andric MaxSafeDepDistBytes = DepChecker->getMaxSafeDepDistBytes(); 24050b57cec5SDimitry Andric 24060b57cec5SDimitry Andric if (!CanVecMem && DepChecker->shouldRetryWithRuntimeCheck()) { 24070b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Retrying with memory checks\n"); 24080b57cec5SDimitry Andric 24090b57cec5SDimitry Andric // Clear the dependency checks. We assume they are not needed. 24100b57cec5SDimitry Andric Accesses.resetDepChecks(*DepChecker); 24110b57cec5SDimitry Andric 24120b57cec5SDimitry Andric PtrRtChecking->reset(); 24130b57cec5SDimitry Andric PtrRtChecking->Need = true; 24140b57cec5SDimitry Andric 24150b57cec5SDimitry Andric auto *SE = PSE->getSE(); 241681ad6265SDimitry Andric UncomputablePtr = nullptr; 241781ad6265SDimitry Andric CanDoRTIfNeeded = Accesses.canCheckPtrAtRT( 241881ad6265SDimitry Andric *PtrRtChecking, SE, TheLoop, SymbolicStrides, UncomputablePtr, true); 24190b57cec5SDimitry Andric 24200b57cec5SDimitry Andric // Check that we found the bounds for the pointer. 24210b57cec5SDimitry Andric if (!CanDoRTIfNeeded) { 242281ad6265SDimitry Andric auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr); 242381ad6265SDimitry Andric recordAnalysis("CantCheckMemDepsAtRunTime", I) 24240b57cec5SDimitry Andric << "cannot check memory dependencies at runtime"; 24250b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n"); 24260b57cec5SDimitry Andric CanVecMem = false; 24270b57cec5SDimitry Andric return; 24280b57cec5SDimitry Andric } 24290b57cec5SDimitry Andric 24300b57cec5SDimitry Andric CanVecMem = true; 24310b57cec5SDimitry Andric } 24320b57cec5SDimitry Andric } 24330b57cec5SDimitry Andric 24340b57cec5SDimitry Andric if (HasConvergentOp) { 24350b57cec5SDimitry Andric recordAnalysis("CantInsertRuntimeCheckWithConvergent") 24360b57cec5SDimitry Andric << "cannot add control dependency to convergent operation"; 24370b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because a runtime check " 24380b57cec5SDimitry Andric "would be needed with a convergent operation\n"); 24390b57cec5SDimitry Andric CanVecMem = false; 24400b57cec5SDimitry Andric return; 24410b57cec5SDimitry Andric } 24420b57cec5SDimitry Andric 24430b57cec5SDimitry Andric if (CanVecMem) 24440b57cec5SDimitry Andric LLVM_DEBUG( 24450b57cec5SDimitry Andric dbgs() << "LAA: No unsafe dependent memory operations in loop. We" 24460b57cec5SDimitry Andric << (PtrRtChecking->Need ? "" : " don't") 24470b57cec5SDimitry Andric << " need runtime memory checks.\n"); 244881ad6265SDimitry Andric else 244981ad6265SDimitry Andric emitUnsafeDependenceRemark(); 245081ad6265SDimitry Andric } 245181ad6265SDimitry Andric 245281ad6265SDimitry Andric void LoopAccessInfo::emitUnsafeDependenceRemark() { 245381ad6265SDimitry Andric auto Deps = getDepChecker().getDependences(); 245481ad6265SDimitry Andric if (!Deps) 245581ad6265SDimitry Andric return; 2456bdd1243dSDimitry Andric auto Found = llvm::find_if(*Deps, [](const MemoryDepChecker::Dependence &D) { 245781ad6265SDimitry Andric return MemoryDepChecker::Dependence::isSafeForVectorization(D.Type) != 245881ad6265SDimitry Andric MemoryDepChecker::VectorizationSafetyStatus::Safe; 245981ad6265SDimitry Andric }); 246081ad6265SDimitry Andric if (Found == Deps->end()) 246181ad6265SDimitry Andric return; 246281ad6265SDimitry Andric MemoryDepChecker::Dependence Dep = *Found; 246381ad6265SDimitry Andric 246481ad6265SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n"); 246581ad6265SDimitry Andric 246681ad6265SDimitry Andric // Emit remark for first unsafe dependence 246781ad6265SDimitry Andric OptimizationRemarkAnalysis &R = 246881ad6265SDimitry Andric recordAnalysis("UnsafeDep", Dep.getDestination(*this)) 24690b57cec5SDimitry Andric << "unsafe dependent memory operations in loop. Use " 24700b57cec5SDimitry Andric "#pragma loop distribute(enable) to allow loop distribution " 24710b57cec5SDimitry Andric "to attempt to isolate the offending operations into a separate " 24720b57cec5SDimitry Andric "loop"; 247381ad6265SDimitry Andric 247481ad6265SDimitry Andric switch (Dep.Type) { 247581ad6265SDimitry Andric case MemoryDepChecker::Dependence::NoDep: 247681ad6265SDimitry Andric case MemoryDepChecker::Dependence::Forward: 247781ad6265SDimitry Andric case MemoryDepChecker::Dependence::BackwardVectorizable: 247881ad6265SDimitry Andric llvm_unreachable("Unexpected dependence"); 247981ad6265SDimitry Andric case MemoryDepChecker::Dependence::Backward: 248081ad6265SDimitry Andric R << "\nBackward loop carried data dependence."; 248181ad6265SDimitry Andric break; 248281ad6265SDimitry Andric case MemoryDepChecker::Dependence::ForwardButPreventsForwarding: 248381ad6265SDimitry Andric R << "\nForward loop carried data dependence that prevents " 248481ad6265SDimitry Andric "store-to-load forwarding."; 248581ad6265SDimitry Andric break; 248681ad6265SDimitry Andric case MemoryDepChecker::Dependence::BackwardVectorizableButPreventsForwarding: 248781ad6265SDimitry Andric R << "\nBackward loop carried data dependence that prevents " 248881ad6265SDimitry Andric "store-to-load forwarding."; 248981ad6265SDimitry Andric break; 249081ad6265SDimitry Andric case MemoryDepChecker::Dependence::Unknown: 249181ad6265SDimitry Andric R << "\nUnknown data dependence."; 249281ad6265SDimitry Andric break; 249381ad6265SDimitry Andric } 249481ad6265SDimitry Andric 249581ad6265SDimitry Andric if (Instruction *I = Dep.getSource(*this)) { 249681ad6265SDimitry Andric DebugLoc SourceLoc = I->getDebugLoc(); 249781ad6265SDimitry Andric if (auto *DD = dyn_cast_or_null<Instruction>(getPointerOperand(I))) 249881ad6265SDimitry Andric SourceLoc = DD->getDebugLoc(); 249981ad6265SDimitry Andric if (SourceLoc) 250081ad6265SDimitry Andric R << " Memory location is the same as accessed at " 250181ad6265SDimitry Andric << ore::NV("Location", SourceLoc); 25020b57cec5SDimitry Andric } 25030b57cec5SDimitry Andric } 25040b57cec5SDimitry Andric 25050b57cec5SDimitry Andric bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop, 25060b57cec5SDimitry Andric DominatorTree *DT) { 25070b57cec5SDimitry Andric assert(TheLoop->contains(BB) && "Unknown block used"); 25080b57cec5SDimitry Andric 25090b57cec5SDimitry Andric // Blocks that do not dominate the latch need predication. 25100b57cec5SDimitry Andric BasicBlock* Latch = TheLoop->getLoopLatch(); 25110b57cec5SDimitry Andric return !DT->dominates(BB, Latch); 25120b57cec5SDimitry Andric } 25130b57cec5SDimitry Andric 25140b57cec5SDimitry Andric OptimizationRemarkAnalysis &LoopAccessInfo::recordAnalysis(StringRef RemarkName, 25150b57cec5SDimitry Andric Instruction *I) { 25160b57cec5SDimitry Andric assert(!Report && "Multiple reports generated"); 25170b57cec5SDimitry Andric 25180b57cec5SDimitry Andric Value *CodeRegion = TheLoop->getHeader(); 25190b57cec5SDimitry Andric DebugLoc DL = TheLoop->getStartLoc(); 25200b57cec5SDimitry Andric 25210b57cec5SDimitry Andric if (I) { 25220b57cec5SDimitry Andric CodeRegion = I->getParent(); 25230b57cec5SDimitry Andric // If there is no debug location attached to the instruction, revert back to 25240b57cec5SDimitry Andric // using the loop's. 25250b57cec5SDimitry Andric if (I->getDebugLoc()) 25260b57cec5SDimitry Andric DL = I->getDebugLoc(); 25270b57cec5SDimitry Andric } 25280b57cec5SDimitry Andric 25298bcb0991SDimitry Andric Report = std::make_unique<OptimizationRemarkAnalysis>(DEBUG_TYPE, RemarkName, DL, 25300b57cec5SDimitry Andric CodeRegion); 25310b57cec5SDimitry Andric return *Report; 25320b57cec5SDimitry Andric } 25330b57cec5SDimitry Andric 2534*fe013be4SDimitry Andric bool LoopAccessInfo::isInvariant(Value *V) const { 25350b57cec5SDimitry Andric auto *SE = PSE->getSE(); 25360b57cec5SDimitry Andric // TODO: Is this really what we want? Even without FP SCEV, we may want some 2537*fe013be4SDimitry Andric // trivially loop-invariant FP values to be considered invariant. 25380b57cec5SDimitry Andric if (!SE->isSCEVable(V->getType())) 25390b57cec5SDimitry Andric return false; 2540*fe013be4SDimitry Andric const SCEV *S = SE->getSCEV(V); 2541*fe013be4SDimitry Andric return SE->isLoopInvariant(S, TheLoop); 2542*fe013be4SDimitry Andric } 2543*fe013be4SDimitry Andric 2544*fe013be4SDimitry Andric /// Find the operand of the GEP that should be checked for consecutive 2545*fe013be4SDimitry Andric /// stores. This ignores trailing indices that have no effect on the final 2546*fe013be4SDimitry Andric /// pointer. 2547*fe013be4SDimitry Andric static unsigned getGEPInductionOperand(const GetElementPtrInst *Gep) { 2548*fe013be4SDimitry Andric const DataLayout &DL = Gep->getModule()->getDataLayout(); 2549*fe013be4SDimitry Andric unsigned LastOperand = Gep->getNumOperands() - 1; 2550*fe013be4SDimitry Andric TypeSize GEPAllocSize = DL.getTypeAllocSize(Gep->getResultElementType()); 2551*fe013be4SDimitry Andric 2552*fe013be4SDimitry Andric // Walk backwards and try to peel off zeros. 2553*fe013be4SDimitry Andric while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) { 2554*fe013be4SDimitry Andric // Find the type we're currently indexing into. 2555*fe013be4SDimitry Andric gep_type_iterator GEPTI = gep_type_begin(Gep); 2556*fe013be4SDimitry Andric std::advance(GEPTI, LastOperand - 2); 2557*fe013be4SDimitry Andric 2558*fe013be4SDimitry Andric // If it's a type with the same allocation size as the result of the GEP we 2559*fe013be4SDimitry Andric // can peel off the zero index. 2560*fe013be4SDimitry Andric if (DL.getTypeAllocSize(GEPTI.getIndexedType()) != GEPAllocSize) 2561*fe013be4SDimitry Andric break; 2562*fe013be4SDimitry Andric --LastOperand; 2563*fe013be4SDimitry Andric } 2564*fe013be4SDimitry Andric 2565*fe013be4SDimitry Andric return LastOperand; 2566*fe013be4SDimitry Andric } 2567*fe013be4SDimitry Andric 2568*fe013be4SDimitry Andric /// If the argument is a GEP, then returns the operand identified by 2569*fe013be4SDimitry Andric /// getGEPInductionOperand. However, if there is some other non-loop-invariant 2570*fe013be4SDimitry Andric /// operand, it returns that instead. 2571*fe013be4SDimitry Andric static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE, Loop *Lp) { 2572*fe013be4SDimitry Andric GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 2573*fe013be4SDimitry Andric if (!GEP) 2574*fe013be4SDimitry Andric return Ptr; 2575*fe013be4SDimitry Andric 2576*fe013be4SDimitry Andric unsigned InductionOperand = getGEPInductionOperand(GEP); 2577*fe013be4SDimitry Andric 2578*fe013be4SDimitry Andric // Check that all of the gep indices are uniform except for our induction 2579*fe013be4SDimitry Andric // operand. 2580*fe013be4SDimitry Andric for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) 2581*fe013be4SDimitry Andric if (i != InductionOperand && 2582*fe013be4SDimitry Andric !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp)) 2583*fe013be4SDimitry Andric return Ptr; 2584*fe013be4SDimitry Andric return GEP->getOperand(InductionOperand); 2585*fe013be4SDimitry Andric } 2586*fe013be4SDimitry Andric 2587*fe013be4SDimitry Andric /// If a value has only one user that is a CastInst, return it. 2588*fe013be4SDimitry Andric static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) { 2589*fe013be4SDimitry Andric Value *UniqueCast = nullptr; 2590*fe013be4SDimitry Andric for (User *U : Ptr->users()) { 2591*fe013be4SDimitry Andric CastInst *CI = dyn_cast<CastInst>(U); 2592*fe013be4SDimitry Andric if (CI && CI->getType() == Ty) { 2593*fe013be4SDimitry Andric if (!UniqueCast) 2594*fe013be4SDimitry Andric UniqueCast = CI; 2595*fe013be4SDimitry Andric else 2596*fe013be4SDimitry Andric return nullptr; 2597*fe013be4SDimitry Andric } 2598*fe013be4SDimitry Andric } 2599*fe013be4SDimitry Andric return UniqueCast; 2600*fe013be4SDimitry Andric } 2601*fe013be4SDimitry Andric 2602*fe013be4SDimitry Andric /// Get the stride of a pointer access in a loop. Looks for symbolic 2603*fe013be4SDimitry Andric /// strides "a[i*stride]". Returns the symbolic stride, or null otherwise. 2604*fe013be4SDimitry Andric static const SCEV *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) { 2605*fe013be4SDimitry Andric auto *PtrTy = dyn_cast<PointerType>(Ptr->getType()); 2606*fe013be4SDimitry Andric if (!PtrTy || PtrTy->isAggregateType()) 2607*fe013be4SDimitry Andric return nullptr; 2608*fe013be4SDimitry Andric 2609*fe013be4SDimitry Andric // Try to remove a gep instruction to make the pointer (actually index at this 2610*fe013be4SDimitry Andric // point) easier analyzable. If OrigPtr is equal to Ptr we are analyzing the 2611*fe013be4SDimitry Andric // pointer, otherwise, we are analyzing the index. 2612*fe013be4SDimitry Andric Value *OrigPtr = Ptr; 2613*fe013be4SDimitry Andric 2614*fe013be4SDimitry Andric // The size of the pointer access. 2615*fe013be4SDimitry Andric int64_t PtrAccessSize = 1; 2616*fe013be4SDimitry Andric 2617*fe013be4SDimitry Andric Ptr = stripGetElementPtr(Ptr, SE, Lp); 2618*fe013be4SDimitry Andric const SCEV *V = SE->getSCEV(Ptr); 2619*fe013be4SDimitry Andric 2620*fe013be4SDimitry Andric if (Ptr != OrigPtr) 2621*fe013be4SDimitry Andric // Strip off casts. 2622*fe013be4SDimitry Andric while (const SCEVIntegralCastExpr *C = dyn_cast<SCEVIntegralCastExpr>(V)) 2623*fe013be4SDimitry Andric V = C->getOperand(); 2624*fe013be4SDimitry Andric 2625*fe013be4SDimitry Andric const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V); 2626*fe013be4SDimitry Andric if (!S) 2627*fe013be4SDimitry Andric return nullptr; 2628*fe013be4SDimitry Andric 2629*fe013be4SDimitry Andric // If the pointer is invariant then there is no stride and it makes no 2630*fe013be4SDimitry Andric // sense to add it here. 2631*fe013be4SDimitry Andric if (Lp != S->getLoop()) 2632*fe013be4SDimitry Andric return nullptr; 2633*fe013be4SDimitry Andric 2634*fe013be4SDimitry Andric V = S->getStepRecurrence(*SE); 2635*fe013be4SDimitry Andric if (!V) 2636*fe013be4SDimitry Andric return nullptr; 2637*fe013be4SDimitry Andric 2638*fe013be4SDimitry Andric // Strip off the size of access multiplication if we are still analyzing the 2639*fe013be4SDimitry Andric // pointer. 2640*fe013be4SDimitry Andric if (OrigPtr == Ptr) { 2641*fe013be4SDimitry Andric if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) { 2642*fe013be4SDimitry Andric if (M->getOperand(0)->getSCEVType() != scConstant) 2643*fe013be4SDimitry Andric return nullptr; 2644*fe013be4SDimitry Andric 2645*fe013be4SDimitry Andric const APInt &APStepVal = cast<SCEVConstant>(M->getOperand(0))->getAPInt(); 2646*fe013be4SDimitry Andric 2647*fe013be4SDimitry Andric // Huge step value - give up. 2648*fe013be4SDimitry Andric if (APStepVal.getBitWidth() > 64) 2649*fe013be4SDimitry Andric return nullptr; 2650*fe013be4SDimitry Andric 2651*fe013be4SDimitry Andric int64_t StepVal = APStepVal.getSExtValue(); 2652*fe013be4SDimitry Andric if (PtrAccessSize != StepVal) 2653*fe013be4SDimitry Andric return nullptr; 2654*fe013be4SDimitry Andric V = M->getOperand(1); 2655*fe013be4SDimitry Andric } 2656*fe013be4SDimitry Andric } 2657*fe013be4SDimitry Andric 2658*fe013be4SDimitry Andric // Note that the restriction after this loop invariant check are only 2659*fe013be4SDimitry Andric // profitability restrictions. 2660*fe013be4SDimitry Andric if (!SE->isLoopInvariant(V, Lp)) 2661*fe013be4SDimitry Andric return nullptr; 2662*fe013be4SDimitry Andric 2663*fe013be4SDimitry Andric // Look for the loop invariant symbolic value. 2664*fe013be4SDimitry Andric const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V); 2665*fe013be4SDimitry Andric if (!U) { 2666*fe013be4SDimitry Andric const auto *C = dyn_cast<SCEVIntegralCastExpr>(V); 2667*fe013be4SDimitry Andric if (!C) 2668*fe013be4SDimitry Andric return nullptr; 2669*fe013be4SDimitry Andric U = dyn_cast<SCEVUnknown>(C->getOperand()); 2670*fe013be4SDimitry Andric if (!U) 2671*fe013be4SDimitry Andric return nullptr; 2672*fe013be4SDimitry Andric 2673*fe013be4SDimitry Andric // Match legacy behavior - this is not needed for correctness 2674*fe013be4SDimitry Andric if (!getUniqueCastUse(U->getValue(), Lp, V->getType())) 2675*fe013be4SDimitry Andric return nullptr; 2676*fe013be4SDimitry Andric } 2677*fe013be4SDimitry Andric 2678*fe013be4SDimitry Andric return V; 26790b57cec5SDimitry Andric } 26800b57cec5SDimitry Andric 26810b57cec5SDimitry Andric void LoopAccessInfo::collectStridedAccess(Value *MemAccess) { 2682e8d8bef9SDimitry Andric Value *Ptr = getLoadStorePointerOperand(MemAccess); 2683e8d8bef9SDimitry Andric if (!Ptr) 26840b57cec5SDimitry Andric return; 26850b57cec5SDimitry Andric 2686*fe013be4SDimitry Andric // Note: getStrideFromPointer is a *profitability* heuristic. We 2687*fe013be4SDimitry Andric // could broaden the scope of values returned here - to anything 2688*fe013be4SDimitry Andric // which happens to be loop invariant and contributes to the 2689*fe013be4SDimitry Andric // computation of an interesting IV - but we chose not to as we 2690*fe013be4SDimitry Andric // don't have a cost model here, and broadening the scope exposes 2691*fe013be4SDimitry Andric // far too many unprofitable cases. 2692*fe013be4SDimitry Andric const SCEV *StrideExpr = getStrideFromPointer(Ptr, PSE->getSE(), TheLoop); 2693*fe013be4SDimitry Andric if (!StrideExpr) 26940b57cec5SDimitry Andric return; 26950b57cec5SDimitry Andric 26960b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found a strided access that is a candidate for " 26970b57cec5SDimitry Andric "versioning:"); 2698*fe013be4SDimitry Andric LLVM_DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *StrideExpr << "\n"); 2699*fe013be4SDimitry Andric 2700*fe013be4SDimitry Andric if (!SpeculateUnitStride) { 2701*fe013be4SDimitry Andric LLVM_DEBUG(dbgs() << " Chose not to due to -laa-speculate-unit-stride\n"); 2702*fe013be4SDimitry Andric return; 2703*fe013be4SDimitry Andric } 27040b57cec5SDimitry Andric 27050b57cec5SDimitry Andric // Avoid adding the "Stride == 1" predicate when we know that 27060b57cec5SDimitry Andric // Stride >= Trip-Count. Such a predicate will effectively optimize a single 27070b57cec5SDimitry Andric // or zero iteration loop, as Trip-Count <= Stride == 1. 27080b57cec5SDimitry Andric // 27090b57cec5SDimitry Andric // TODO: We are currently not making a very informed decision on when it is 27100b57cec5SDimitry Andric // beneficial to apply stride versioning. It might make more sense that the 27110b57cec5SDimitry Andric // users of this analysis (such as the vectorizer) will trigger it, based on 27120b57cec5SDimitry Andric // their specific cost considerations; For example, in cases where stride 27130b57cec5SDimitry Andric // versioning does not help resolving memory accesses/dependences, the 27140b57cec5SDimitry Andric // vectorizer should evaluate the cost of the runtime test, and the benefit 27150b57cec5SDimitry Andric // of various possible stride specializations, considering the alternatives 27160b57cec5SDimitry Andric // of using gather/scatters (if available). 27170b57cec5SDimitry Andric 27180b57cec5SDimitry Andric const SCEV *BETakenCount = PSE->getBackedgeTakenCount(); 27190b57cec5SDimitry Andric 27200b57cec5SDimitry Andric // Match the types so we can compare the stride and the BETakenCount. 27210b57cec5SDimitry Andric // The Stride can be positive/negative, so we sign extend Stride; 27220b57cec5SDimitry Andric // The backedgeTakenCount is non-negative, so we zero extend BETakenCount. 27230b57cec5SDimitry Andric const DataLayout &DL = TheLoop->getHeader()->getModule()->getDataLayout(); 272481ad6265SDimitry Andric uint64_t StrideTypeSizeBits = DL.getTypeSizeInBits(StrideExpr->getType()); 272581ad6265SDimitry Andric uint64_t BETypeSizeBits = DL.getTypeSizeInBits(BETakenCount->getType()); 27260b57cec5SDimitry Andric const SCEV *CastedStride = StrideExpr; 27270b57cec5SDimitry Andric const SCEV *CastedBECount = BETakenCount; 27280b57cec5SDimitry Andric ScalarEvolution *SE = PSE->getSE(); 272981ad6265SDimitry Andric if (BETypeSizeBits >= StrideTypeSizeBits) 27300b57cec5SDimitry Andric CastedStride = SE->getNoopOrSignExtend(StrideExpr, BETakenCount->getType()); 27310b57cec5SDimitry Andric else 27320b57cec5SDimitry Andric CastedBECount = SE->getZeroExtendExpr(BETakenCount, StrideExpr->getType()); 27330b57cec5SDimitry Andric const SCEV *StrideMinusBETaken = SE->getMinusSCEV(CastedStride, CastedBECount); 27340b57cec5SDimitry Andric // Since TripCount == BackEdgeTakenCount + 1, checking: 27350b57cec5SDimitry Andric // "Stride >= TripCount" is equivalent to checking: 27360b57cec5SDimitry Andric // Stride - BETakenCount > 0 27370b57cec5SDimitry Andric if (SE->isKnownPositive(StrideMinusBETaken)) { 27380b57cec5SDimitry Andric LLVM_DEBUG( 27390b57cec5SDimitry Andric dbgs() << "LAA: Stride>=TripCount; No point in versioning as the " 27400b57cec5SDimitry Andric "Stride==1 predicate will imply that the loop executes " 27410b57cec5SDimitry Andric "at most once.\n"); 27420b57cec5SDimitry Andric return; 27430b57cec5SDimitry Andric } 274481ad6265SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found a strided access that we can version.\n"); 27450b57cec5SDimitry Andric 2746*fe013be4SDimitry Andric // Strip back off the integer cast, and check that our result is a 2747*fe013be4SDimitry Andric // SCEVUnknown as we expect. 2748*fe013be4SDimitry Andric const SCEV *StrideBase = StrideExpr; 2749*fe013be4SDimitry Andric if (const auto *C = dyn_cast<SCEVIntegralCastExpr>(StrideBase)) 2750*fe013be4SDimitry Andric StrideBase = C->getOperand(); 2751*fe013be4SDimitry Andric SymbolicStrides[Ptr] = cast<SCEVUnknown>(StrideBase); 27520b57cec5SDimitry Andric } 27530b57cec5SDimitry Andric 27540b57cec5SDimitry Andric LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE, 27555ffd83dbSDimitry Andric const TargetLibraryInfo *TLI, AAResults *AA, 27560b57cec5SDimitry Andric DominatorTree *DT, LoopInfo *LI) 27578bcb0991SDimitry Andric : PSE(std::make_unique<PredicatedScalarEvolution>(*SE, *L)), 275881ad6265SDimitry Andric PtrRtChecking(nullptr), 275904eeddc0SDimitry Andric DepChecker(std::make_unique<MemoryDepChecker>(*PSE, L)), TheLoop(L) { 276081ad6265SDimitry Andric PtrRtChecking = std::make_unique<RuntimePointerChecking>(*DepChecker, SE); 276181ad6265SDimitry Andric if (canAnalyzeLoop()) { 27620b57cec5SDimitry Andric analyzeLoop(AA, LI, TLI, DT); 27630b57cec5SDimitry Andric } 276481ad6265SDimitry Andric } 27650b57cec5SDimitry Andric 27660b57cec5SDimitry Andric void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const { 27670b57cec5SDimitry Andric if (CanVecMem) { 27680b57cec5SDimitry Andric OS.indent(Depth) << "Memory dependences are safe"; 27690b57cec5SDimitry Andric if (MaxSafeDepDistBytes != -1ULL) 27700b57cec5SDimitry Andric OS << " with a maximum dependence distance of " << MaxSafeDepDistBytes 27710b57cec5SDimitry Andric << " bytes"; 27720b57cec5SDimitry Andric if (PtrRtChecking->Need) 27730b57cec5SDimitry Andric OS << " with run-time checks"; 27740b57cec5SDimitry Andric OS << "\n"; 27750b57cec5SDimitry Andric } 27760b57cec5SDimitry Andric 27770b57cec5SDimitry Andric if (HasConvergentOp) 27780b57cec5SDimitry Andric OS.indent(Depth) << "Has convergent operation in loop\n"; 27790b57cec5SDimitry Andric 27800b57cec5SDimitry Andric if (Report) 27810b57cec5SDimitry Andric OS.indent(Depth) << "Report: " << Report->getMsg() << "\n"; 27820b57cec5SDimitry Andric 27830b57cec5SDimitry Andric if (auto *Dependences = DepChecker->getDependences()) { 27840b57cec5SDimitry Andric OS.indent(Depth) << "Dependences:\n"; 2785fcaf7f86SDimitry Andric for (const auto &Dep : *Dependences) { 27860b57cec5SDimitry Andric Dep.print(OS, Depth + 2, DepChecker->getMemoryInstructions()); 27870b57cec5SDimitry Andric OS << "\n"; 27880b57cec5SDimitry Andric } 27890b57cec5SDimitry Andric } else 27900b57cec5SDimitry Andric OS.indent(Depth) << "Too many dependences, not recorded\n"; 27910b57cec5SDimitry Andric 27920b57cec5SDimitry Andric // List the pair of accesses need run-time checks to prove independence. 27930b57cec5SDimitry Andric PtrRtChecking->print(OS, Depth); 27940b57cec5SDimitry Andric OS << "\n"; 27950b57cec5SDimitry Andric 27960b57cec5SDimitry Andric OS.indent(Depth) << "Non vectorizable stores to invariant address were " 27970b57cec5SDimitry Andric << (HasDependenceInvolvingLoopInvariantAddress ? "" : "not ") 27980b57cec5SDimitry Andric << "found in loop.\n"; 27990b57cec5SDimitry Andric 28000b57cec5SDimitry Andric OS.indent(Depth) << "SCEV assumptions:\n"; 280181ad6265SDimitry Andric PSE->getPredicate().print(OS, Depth); 28020b57cec5SDimitry Andric 28030b57cec5SDimitry Andric OS << "\n"; 28040b57cec5SDimitry Andric 28050b57cec5SDimitry Andric OS.indent(Depth) << "Expressions re-written:\n"; 28060b57cec5SDimitry Andric PSE->print(OS, Depth); 28070b57cec5SDimitry Andric } 28080b57cec5SDimitry Andric 2809bdd1243dSDimitry Andric const LoopAccessInfo &LoopAccessInfoManager::getInfo(Loop &L) { 2810bdd1243dSDimitry Andric auto I = LoopAccessInfoMap.insert({&L, nullptr}); 2811bdd1243dSDimitry Andric 2812bdd1243dSDimitry Andric if (I.second) 2813bdd1243dSDimitry Andric I.first->second = 2814bdd1243dSDimitry Andric std::make_unique<LoopAccessInfo>(&L, &SE, TLI, &AA, &DT, &LI); 2815bdd1243dSDimitry Andric 2816bdd1243dSDimitry Andric return *I.first->second; 2817bdd1243dSDimitry Andric } 2818bdd1243dSDimitry Andric 2819*fe013be4SDimitry Andric bool LoopAccessInfoManager::invalidate( 2820*fe013be4SDimitry Andric Function &F, const PreservedAnalyses &PA, 2821*fe013be4SDimitry Andric FunctionAnalysisManager::Invalidator &Inv) { 2822*fe013be4SDimitry Andric // Check whether our analysis is preserved. 2823*fe013be4SDimitry Andric auto PAC = PA.getChecker<LoopAccessAnalysis>(); 2824*fe013be4SDimitry Andric if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>()) 2825*fe013be4SDimitry Andric // If not, give up now. 2826*fe013be4SDimitry Andric return true; 2827480093f4SDimitry Andric 2828*fe013be4SDimitry Andric // Check whether the analyses we depend on became invalid for any reason. 2829*fe013be4SDimitry Andric // Skip checking TargetLibraryAnalysis as it is immutable and can't become 2830*fe013be4SDimitry Andric // invalid. 2831*fe013be4SDimitry Andric return Inv.invalidate<AAManager>(F, PA) || 2832*fe013be4SDimitry Andric Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) || 2833*fe013be4SDimitry Andric Inv.invalidate<LoopAnalysis>(F, PA) || 2834*fe013be4SDimitry Andric Inv.invalidate<DominatorTreeAnalysis>(F, PA); 28350b57cec5SDimitry Andric } 28360b57cec5SDimitry Andric 2837bdd1243dSDimitry Andric LoopAccessInfoManager LoopAccessAnalysis::run(Function &F, 2838*fe013be4SDimitry Andric FunctionAnalysisManager &FAM) { 2839*fe013be4SDimitry Andric auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F); 2840*fe013be4SDimitry Andric auto &AA = FAM.getResult<AAManager>(F); 2841*fe013be4SDimitry Andric auto &DT = FAM.getResult<DominatorTreeAnalysis>(F); 2842*fe013be4SDimitry Andric auto &LI = FAM.getResult<LoopAnalysis>(F); 2843*fe013be4SDimitry Andric auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F); 2844*fe013be4SDimitry Andric return LoopAccessInfoManager(SE, AA, DT, LI, &TLI); 2845bdd1243dSDimitry Andric } 2846bdd1243dSDimitry Andric 28470b57cec5SDimitry Andric AnalysisKey LoopAccessAnalysis::Key; 2848