1ff0cc061SDimitry Andric //===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==//
2ff0cc061SDimitry Andric //
3ff0cc061SDimitry Andric //                     The LLVM Compiler Infrastructure
4ff0cc061SDimitry Andric //
5ff0cc061SDimitry Andric // This file is distributed under the University of Illinois Open Source
6ff0cc061SDimitry Andric // License. See LICENSE.TXT for details.
7ff0cc061SDimitry Andric //
8ff0cc061SDimitry Andric //===----------------------------------------------------------------------===//
9ff0cc061SDimitry Andric //
10ff0cc061SDimitry Andric // The implementation for the loop memory dependence that was originally
11ff0cc061SDimitry Andric // developed for the loop vectorizer.
12ff0cc061SDimitry Andric //
13ff0cc061SDimitry Andric //===----------------------------------------------------------------------===//
14ff0cc061SDimitry Andric 
15f1a29dd3SDimitry Andric #include "llvm/Analysis/LoopAccessAnalysis.h"
16d88c1a5aSDimitry Andric #include "llvm/ADT/APInt.h"
17d88c1a5aSDimitry Andric #include "llvm/ADT/DenseMap.h"
18d88c1a5aSDimitry Andric #include "llvm/ADT/DepthFirstIterator.h"
19d88c1a5aSDimitry Andric #include "llvm/ADT/EquivalenceClasses.h"
20d88c1a5aSDimitry Andric #include "llvm/ADT/PointerIntPair.h"
21f1a29dd3SDimitry Andric #include "llvm/ADT/STLExtras.h"
22d88c1a5aSDimitry Andric #include "llvm/ADT/SetVector.h"
23d88c1a5aSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
24d88c1a5aSDimitry Andric #include "llvm/ADT/SmallSet.h"
25d88c1a5aSDimitry Andric #include "llvm/ADT/SmallVector.h"
26f1a29dd3SDimitry Andric #include "llvm/ADT/iterator_range.h"
27d88c1a5aSDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
28d88c1a5aSDimitry Andric #include "llvm/Analysis/AliasSetTracker.h"
29f1a29dd3SDimitry Andric #include "llvm/Analysis/LoopAnalysisManager.h"
30ff0cc061SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
31d88c1a5aSDimitry Andric #include "llvm/Analysis/MemoryLocation.h"
322cab237bSDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
33d88c1a5aSDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
34ff0cc061SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpander.h"
35d88c1a5aSDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h"
36ff0cc061SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
37ff0cc061SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
383ca95b02SDimitry Andric #include "llvm/Analysis/VectorUtils.h"
39d88c1a5aSDimitry Andric #include "llvm/IR/BasicBlock.h"
40d88c1a5aSDimitry Andric #include "llvm/IR/Constants.h"
41d88c1a5aSDimitry Andric #include "llvm/IR/DataLayout.h"
42d88c1a5aSDimitry Andric #include "llvm/IR/DebugLoc.h"
43d88c1a5aSDimitry Andric #include "llvm/IR/DerivedTypes.h"
44ff0cc061SDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
45ff0cc061SDimitry Andric #include "llvm/IR/Dominators.h"
46d88c1a5aSDimitry Andric #include "llvm/IR/Function.h"
47f1a29dd3SDimitry Andric #include "llvm/IR/IRBuilder.h"
48d88c1a5aSDimitry Andric #include "llvm/IR/InstrTypes.h"
49d88c1a5aSDimitry Andric #include "llvm/IR/Instruction.h"
50d88c1a5aSDimitry Andric #include "llvm/IR/Instructions.h"
51d88c1a5aSDimitry Andric #include "llvm/IR/Operator.h"
523ca95b02SDimitry Andric #include "llvm/IR/PassManager.h"
53d88c1a5aSDimitry Andric #include "llvm/IR/Type.h"
54d88c1a5aSDimitry Andric #include "llvm/IR/Value.h"
55d88c1a5aSDimitry Andric #include "llvm/IR/ValueHandle.h"
56d88c1a5aSDimitry Andric #include "llvm/Pass.h"
57d88c1a5aSDimitry Andric #include "llvm/Support/Casting.h"
58d88c1a5aSDimitry Andric #include "llvm/Support/CommandLine.h"
59ff0cc061SDimitry Andric #include "llvm/Support/Debug.h"
60d88c1a5aSDimitry Andric #include "llvm/Support/ErrorHandling.h"
61ff0cc061SDimitry Andric #include "llvm/Support/raw_ostream.h"
62d88c1a5aSDimitry Andric #include <algorithm>
63d88c1a5aSDimitry Andric #include <cassert>
64d88c1a5aSDimitry Andric #include <cstdint>
65d88c1a5aSDimitry Andric #include <cstdlib>
66d88c1a5aSDimitry Andric #include <iterator>
67d88c1a5aSDimitry Andric #include <utility>
68d88c1a5aSDimitry Andric #include <vector>
69d88c1a5aSDimitry Andric 
70ff0cc061SDimitry Andric using namespace llvm;
71ff0cc061SDimitry Andric 
72ff0cc061SDimitry Andric #define DEBUG_TYPE "loop-accesses"
73ff0cc061SDimitry Andric 
74ff0cc061SDimitry Andric static cl::opt<unsigned, true>
75ff0cc061SDimitry Andric VectorizationFactor("force-vector-width", cl::Hidden,
76ff0cc061SDimitry Andric                     cl::desc("Sets the SIMD width. Zero is autoselect."),
77ff0cc061SDimitry Andric                     cl::location(VectorizerParams::VectorizationFactor));
78ff0cc061SDimitry Andric unsigned VectorizerParams::VectorizationFactor;
79ff0cc061SDimitry Andric 
80ff0cc061SDimitry Andric static cl::opt<unsigned, true>
81ff0cc061SDimitry Andric VectorizationInterleave("force-vector-interleave", cl::Hidden,
82ff0cc061SDimitry Andric                         cl::desc("Sets the vectorization interleave count. "
83ff0cc061SDimitry Andric                                  "Zero is autoselect."),
84ff0cc061SDimitry Andric                         cl::location(
85ff0cc061SDimitry Andric                             VectorizerParams::VectorizationInterleave));
86ff0cc061SDimitry Andric unsigned VectorizerParams::VectorizationInterleave;
87ff0cc061SDimitry Andric 
88ff0cc061SDimitry Andric static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
89ff0cc061SDimitry Andric     "runtime-memory-check-threshold", cl::Hidden,
90ff0cc061SDimitry Andric     cl::desc("When performing memory disambiguation checks at runtime do not "
91ff0cc061SDimitry Andric              "generate more than this number of comparisons (default = 8)."),
92ff0cc061SDimitry Andric     cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
93ff0cc061SDimitry Andric unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
94ff0cc061SDimitry Andric 
954ba319b5SDimitry Andric /// The maximum iterations used to merge memory checks
96875ed548SDimitry Andric static cl::opt<unsigned> MemoryCheckMergeThreshold(
97875ed548SDimitry Andric     "memory-check-merge-threshold", cl::Hidden,
98875ed548SDimitry Andric     cl::desc("Maximum number of comparisons done when trying to merge "
99875ed548SDimitry Andric              "runtime memory checks. (default = 100)"),
100875ed548SDimitry Andric     cl::init(100));
101875ed548SDimitry Andric 
102ff0cc061SDimitry Andric /// Maximum SIMD width.
103ff0cc061SDimitry Andric const unsigned VectorizerParams::MaxVectorWidth = 64;
104ff0cc061SDimitry Andric 
1054ba319b5SDimitry Andric /// We collect dependences up to this threshold.
1067d523365SDimitry Andric static cl::opt<unsigned>
1077d523365SDimitry Andric     MaxDependences("max-dependences", cl::Hidden,
1087d523365SDimitry Andric                    cl::desc("Maximum number of dependences collected by "
109ff0cc061SDimitry Andric                             "loop-access analysis (default = 100)"),
110ff0cc061SDimitry Andric                    cl::init(100));
111ff0cc061SDimitry Andric 
1123ca95b02SDimitry Andric /// This enables versioning on the strides of symbolically striding memory
1133ca95b02SDimitry Andric /// accesses in code like the following.
1143ca95b02SDimitry Andric ///   for (i = 0; i < N; ++i)
1153ca95b02SDimitry Andric ///     A[i * Stride1] += B[i * Stride2] ...
1163ca95b02SDimitry Andric ///
1173ca95b02SDimitry Andric /// Will be roughly translated to
1183ca95b02SDimitry Andric ///    if (Stride1 == 1 && Stride2 == 1) {
1193ca95b02SDimitry Andric ///      for (i = 0; i < N; i+=4)
1203ca95b02SDimitry Andric ///       A[i:i+3] += ...
1213ca95b02SDimitry Andric ///    } else
1223ca95b02SDimitry Andric ///      ...
1233ca95b02SDimitry Andric static cl::opt<bool> EnableMemAccessVersioning(
1243ca95b02SDimitry Andric     "enable-mem-access-versioning", cl::init(true), cl::Hidden,
1253ca95b02SDimitry Andric     cl::desc("Enable symbolic stride memory access versioning"));
1263ca95b02SDimitry Andric 
1274ba319b5SDimitry Andric /// Enable store-to-load forwarding conflict detection. This option can
1283ca95b02SDimitry Andric /// be disabled for correctness testing.
1293ca95b02SDimitry Andric static cl::opt<bool> EnableForwardingConflictDetection(
1303ca95b02SDimitry Andric     "store-to-load-forwarding-conflict-detection", cl::Hidden,
1313ca95b02SDimitry Andric     cl::desc("Enable conflict detection in loop-access analysis"),
1323ca95b02SDimitry Andric     cl::init(true));
1333ca95b02SDimitry Andric 
isInterleaveForced()134ff0cc061SDimitry Andric bool VectorizerParams::isInterleaveForced() {
135ff0cc061SDimitry Andric   return ::VectorizationInterleave.getNumOccurrences() > 0;
136ff0cc061SDimitry Andric }
137ff0cc061SDimitry Andric 
stripIntegerCast(Value * V)138ff0cc061SDimitry Andric Value *llvm::stripIntegerCast(Value *V) {
1393ca95b02SDimitry Andric   if (auto *CI = dyn_cast<CastInst>(V))
140ff0cc061SDimitry Andric     if (CI->getOperand(0)->getType()->isIntegerTy())
141ff0cc061SDimitry Andric       return CI->getOperand(0);
142ff0cc061SDimitry Andric   return V;
143ff0cc061SDimitry Andric }
144ff0cc061SDimitry Andric 
replaceSymbolicStrideSCEV(PredicatedScalarEvolution & PSE,const ValueToValueMap & PtrToStride,Value * Ptr,Value * OrigPtr)1457d523365SDimitry Andric const SCEV *llvm::replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE,
146ff0cc061SDimitry Andric                                             const ValueToValueMap &PtrToStride,
147ff0cc061SDimitry Andric                                             Value *Ptr, Value *OrigPtr) {
1487d523365SDimitry Andric   const SCEV *OrigSCEV = PSE.getSCEV(Ptr);
149ff0cc061SDimitry Andric 
150ff0cc061SDimitry Andric   // If there is an entry in the map return the SCEV of the pointer with the
151ff0cc061SDimitry Andric   // symbolic stride replaced by one.
152ff0cc061SDimitry Andric   ValueToValueMap::const_iterator SI =
153ff0cc061SDimitry Andric       PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
154ff0cc061SDimitry Andric   if (SI != PtrToStride.end()) {
155ff0cc061SDimitry Andric     Value *StrideVal = SI->second;
156ff0cc061SDimitry Andric 
157ff0cc061SDimitry Andric     // Strip casts.
158ff0cc061SDimitry Andric     StrideVal = stripIntegerCast(StrideVal);
159ff0cc061SDimitry Andric 
1607d523365SDimitry Andric     ScalarEvolution *SE = PSE.getSE();
1617d523365SDimitry Andric     const auto *U = cast<SCEVUnknown>(SE->getSCEV(StrideVal));
1627d523365SDimitry Andric     const auto *CT =
1637d523365SDimitry Andric         static_cast<const SCEVConstant *>(SE->getOne(StrideVal->getType()));
1647d523365SDimitry Andric 
1657d523365SDimitry Andric     PSE.addPredicate(*SE->getEqualPredicate(U, CT));
1667d523365SDimitry Andric     auto *Expr = PSE.getSCEV(Ptr);
1677d523365SDimitry Andric 
1684ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV
1694ba319b5SDimitry Andric                       << " by: " << *Expr << "\n");
1707d523365SDimitry Andric     return Expr;
171ff0cc061SDimitry Andric   }
172ff0cc061SDimitry Andric 
173ff0cc061SDimitry Andric   // Otherwise, just return the SCEV of the original pointer.
1747d523365SDimitry Andric   return OrigSCEV;
175ff0cc061SDimitry Andric }
176ff0cc061SDimitry Andric 
177f41fbc90SDimitry Andric /// Calculate Start and End points of memory access.
178f41fbc90SDimitry Andric /// Let's assume A is the first access and B is a memory access on N-th loop
179f41fbc90SDimitry Andric /// iteration. Then B is calculated as:
180f41fbc90SDimitry Andric ///   B = A + Step*N .
181f41fbc90SDimitry Andric /// Step value may be positive or negative.
182f41fbc90SDimitry Andric /// N is a calculated back-edge taken count:
183f41fbc90SDimitry Andric ///     N = (TripCount > 0) ? RoundDown(TripCount -1 , VF) : 0
184f41fbc90SDimitry Andric /// Start and End points are calculated in the following way:
185f41fbc90SDimitry Andric /// Start = UMIN(A, B) ; End = UMAX(A, B) + SizeOfElt,
186f41fbc90SDimitry Andric /// where SizeOfElt is the size of single memory access in bytes.
187f41fbc90SDimitry Andric ///
188f41fbc90SDimitry Andric /// There is no conflict when the intervals are disjoint:
189f41fbc90SDimitry Andric /// NoConflict = (P2.Start >= P1.End) || (P1.Start >= P2.End)
insert(Loop * Lp,Value * Ptr,bool WritePtr,unsigned DepSetId,unsigned ASId,const ValueToValueMap & Strides,PredicatedScalarEvolution & PSE)190875ed548SDimitry Andric void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, bool WritePtr,
191875ed548SDimitry Andric                                     unsigned DepSetId, unsigned ASId,
1927d523365SDimitry Andric                                     const ValueToValueMap &Strides,
1937d523365SDimitry Andric                                     PredicatedScalarEvolution &PSE) {
194ff0cc061SDimitry Andric   // Get the stride replaced scev.
1957d523365SDimitry Andric   const SCEV *Sc = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
1963ca95b02SDimitry Andric   ScalarEvolution *SE = PSE.getSE();
1973ca95b02SDimitry Andric 
1983ca95b02SDimitry Andric   const SCEV *ScStart;
1993ca95b02SDimitry Andric   const SCEV *ScEnd;
2003ca95b02SDimitry Andric 
2013ca95b02SDimitry Andric   if (SE->isLoopInvariant(Sc, Lp))
2023ca95b02SDimitry Andric     ScStart = ScEnd = Sc;
2033ca95b02SDimitry Andric   else {
204ff0cc061SDimitry Andric     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
205ff0cc061SDimitry Andric     assert(AR && "Invalid addrec expression");
2063ca95b02SDimitry Andric     const SCEV *Ex = PSE.getBackedgeTakenCount();
2077d523365SDimitry Andric 
2083ca95b02SDimitry Andric     ScStart = AR->getStart();
2093ca95b02SDimitry Andric     ScEnd = AR->evaluateAtIteration(Ex, *SE);
2107d523365SDimitry Andric     const SCEV *Step = AR->getStepRecurrence(*SE);
2117d523365SDimitry Andric 
2127d523365SDimitry Andric     // For expressions with negative step, the upper bound is ScStart and the
2137d523365SDimitry Andric     // lower bound is ScEnd.
2143ca95b02SDimitry Andric     if (const auto *CStep = dyn_cast<SCEVConstant>(Step)) {
2157d523365SDimitry Andric       if (CStep->getValue()->isNegative())
2167d523365SDimitry Andric         std::swap(ScStart, ScEnd);
2177d523365SDimitry Andric     } else {
218f41fbc90SDimitry Andric       // Fallback case: the step is not constant, but we can still
2197d523365SDimitry Andric       // get the upper and lower bounds of the interval by using min/max
2207d523365SDimitry Andric       // expressions.
2217d523365SDimitry Andric       ScStart = SE->getUMinExpr(ScStart, ScEnd);
2227d523365SDimitry Andric       ScEnd = SE->getUMaxExpr(AR->getStart(), ScEnd);
223ff0cc061SDimitry Andric     }
224f41fbc90SDimitry Andric     // Add the size of the pointed element to ScEnd.
225f41fbc90SDimitry Andric     unsigned EltSize =
226f41fbc90SDimitry Andric       Ptr->getType()->getPointerElementType()->getScalarSizeInBits() / 8;
227f41fbc90SDimitry Andric     const SCEV *EltSizeSCEV = SE->getConstant(ScEnd->getType(), EltSize);
228f41fbc90SDimitry Andric     ScEnd = SE->getAddExpr(ScEnd, EltSizeSCEV);
2293ca95b02SDimitry Andric   }
230ff0cc061SDimitry Andric 
2317d523365SDimitry Andric   Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, Sc);
2327d523365SDimitry Andric }
2337d523365SDimitry Andric 
2347d523365SDimitry Andric SmallVector<RuntimePointerChecking::PointerCheck, 4>
generateChecks() const2357d523365SDimitry Andric RuntimePointerChecking::generateChecks() const {
2367d523365SDimitry Andric   SmallVector<PointerCheck, 4> Checks;
2377d523365SDimitry Andric 
2387d523365SDimitry Andric   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
2397d523365SDimitry Andric     for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) {
2407d523365SDimitry Andric       const RuntimePointerChecking::CheckingPtrGroup &CGI = CheckingGroups[I];
2417d523365SDimitry Andric       const RuntimePointerChecking::CheckingPtrGroup &CGJ = CheckingGroups[J];
2427d523365SDimitry Andric 
2437d523365SDimitry Andric       if (needsChecking(CGI, CGJ))
2447d523365SDimitry Andric         Checks.push_back(std::make_pair(&CGI, &CGJ));
2457d523365SDimitry Andric     }
2467d523365SDimitry Andric   }
2477d523365SDimitry Andric   return Checks;
2487d523365SDimitry Andric }
2497d523365SDimitry Andric 
generateChecks(MemoryDepChecker::DepCandidates & DepCands,bool UseDependencies)2507d523365SDimitry Andric void RuntimePointerChecking::generateChecks(
2517d523365SDimitry Andric     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
2527d523365SDimitry Andric   assert(Checks.empty() && "Checks is not empty");
2537d523365SDimitry Andric   groupChecks(DepCands, UseDependencies);
2547d523365SDimitry Andric   Checks = generateChecks();
2557d523365SDimitry Andric }
2567d523365SDimitry Andric 
needsChecking(const CheckingPtrGroup & M,const CheckingPtrGroup & N) const2577d523365SDimitry Andric bool RuntimePointerChecking::needsChecking(const CheckingPtrGroup &M,
2587d523365SDimitry Andric                                            const CheckingPtrGroup &N) const {
259875ed548SDimitry Andric   for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I)
260875ed548SDimitry Andric     for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J)
2617d523365SDimitry Andric       if (needsChecking(M.Members[I], N.Members[J]))
262875ed548SDimitry Andric         return true;
263875ed548SDimitry Andric   return false;
264875ed548SDimitry Andric }
265875ed548SDimitry Andric 
266875ed548SDimitry Andric /// Compare \p I and \p J and return the minimum.
267875ed548SDimitry Andric /// Return nullptr in case we couldn't find an answer.
getMinFromExprs(const SCEV * I,const SCEV * J,ScalarEvolution * SE)268875ed548SDimitry Andric static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
269875ed548SDimitry Andric                                    ScalarEvolution *SE) {
270875ed548SDimitry Andric   const SCEV *Diff = SE->getMinusSCEV(J, I);
271875ed548SDimitry Andric   const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
272875ed548SDimitry Andric 
273875ed548SDimitry Andric   if (!C)
274875ed548SDimitry Andric     return nullptr;
275875ed548SDimitry Andric   if (C->getValue()->isNegative())
276875ed548SDimitry Andric     return J;
277875ed548SDimitry Andric   return I;
278875ed548SDimitry Andric }
279875ed548SDimitry Andric 
addPointer(unsigned Index)280875ed548SDimitry Andric bool RuntimePointerChecking::CheckingPtrGroup::addPointer(unsigned Index) {
281875ed548SDimitry Andric   const SCEV *Start = RtCheck.Pointers[Index].Start;
282875ed548SDimitry Andric   const SCEV *End = RtCheck.Pointers[Index].End;
283875ed548SDimitry Andric 
284875ed548SDimitry Andric   // Compare the starts and ends with the known minimum and maximum
285875ed548SDimitry Andric   // of this set. We need to know how we compare against the min/max
286875ed548SDimitry Andric   // of the set in order to be able to emit memchecks.
287875ed548SDimitry Andric   const SCEV *Min0 = getMinFromExprs(Start, Low, RtCheck.SE);
288875ed548SDimitry Andric   if (!Min0)
289875ed548SDimitry Andric     return false;
290875ed548SDimitry Andric 
291875ed548SDimitry Andric   const SCEV *Min1 = getMinFromExprs(End, High, RtCheck.SE);
292875ed548SDimitry Andric   if (!Min1)
293875ed548SDimitry Andric     return false;
294875ed548SDimitry Andric 
295875ed548SDimitry Andric   // Update the low bound  expression if we've found a new min value.
296875ed548SDimitry Andric   if (Min0 == Start)
297875ed548SDimitry Andric     Low = Start;
298875ed548SDimitry Andric 
299875ed548SDimitry Andric   // Update the high bound expression if we've found a new max value.
300875ed548SDimitry Andric   if (Min1 != End)
301875ed548SDimitry Andric     High = End;
302875ed548SDimitry Andric 
303875ed548SDimitry Andric   Members.push_back(Index);
304875ed548SDimitry Andric   return true;
305875ed548SDimitry Andric }
306875ed548SDimitry Andric 
groupChecks(MemoryDepChecker::DepCandidates & DepCands,bool UseDependencies)307875ed548SDimitry Andric void RuntimePointerChecking::groupChecks(
308875ed548SDimitry Andric     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
309875ed548SDimitry Andric   // We build the groups from dependency candidates equivalence classes
310875ed548SDimitry Andric   // because:
311875ed548SDimitry Andric   //    - We know that pointers in the same equivalence class share
312875ed548SDimitry Andric   //      the same underlying object and therefore there is a chance
313875ed548SDimitry Andric   //      that we can compare pointers
314875ed548SDimitry Andric   //    - We wouldn't be able to merge two pointers for which we need
315875ed548SDimitry Andric   //      to emit a memcheck. The classes in DepCands are already
316875ed548SDimitry Andric   //      conveniently built such that no two pointers in the same
317875ed548SDimitry Andric   //      class need checking against each other.
318875ed548SDimitry Andric 
319875ed548SDimitry Andric   // We use the following (greedy) algorithm to construct the groups
320875ed548SDimitry Andric   // For every pointer in the equivalence class:
321875ed548SDimitry Andric   //   For each existing group:
322875ed548SDimitry Andric   //   - if the difference between this pointer and the min/max bounds
323875ed548SDimitry Andric   //     of the group is a constant, then make the pointer part of the
324875ed548SDimitry Andric   //     group and update the min/max bounds of that group as required.
325875ed548SDimitry Andric 
326875ed548SDimitry Andric   CheckingGroups.clear();
327875ed548SDimitry Andric 
3287d523365SDimitry Andric   // If we need to check two pointers to the same underlying object
3297d523365SDimitry Andric   // with a non-constant difference, we shouldn't perform any pointer
3307d523365SDimitry Andric   // grouping with those pointers. This is because we can easily get
3317d523365SDimitry Andric   // into cases where the resulting check would return false, even when
3327d523365SDimitry Andric   // the accesses are safe.
3337d523365SDimitry Andric   //
3347d523365SDimitry Andric   // The following example shows this:
3357d523365SDimitry Andric   // for (i = 0; i < 1000; ++i)
3367d523365SDimitry Andric   //   a[5000 + i * m] = a[i] + a[i + 9000]
3377d523365SDimitry Andric   //
3387d523365SDimitry Andric   // Here grouping gives a check of (5000, 5000 + 1000 * m) against
3397d523365SDimitry Andric   // (0, 10000) which is always false. However, if m is 1, there is no
3407d523365SDimitry Andric   // dependence. Not grouping the checks for a[i] and a[i + 9000] allows
3417d523365SDimitry Andric   // us to perform an accurate check in this case.
3427d523365SDimitry Andric   //
3437d523365SDimitry Andric   // The above case requires that we have an UnknownDependence between
3447d523365SDimitry Andric   // accesses to the same underlying object. This cannot happen unless
345*b5893f02SDimitry Andric   // FoundNonConstantDistanceDependence is set, and therefore UseDependencies
3467d523365SDimitry Andric   // is also false. In this case we will use the fallback path and create
3477d523365SDimitry Andric   // separate checking groups for all pointers.
3487d523365SDimitry Andric 
349875ed548SDimitry Andric   // If we don't have the dependency partitions, construct a new
3507d523365SDimitry Andric   // checking pointer group for each pointer. This is also required
3517d523365SDimitry Andric   // for correctness, because in this case we can have checking between
3527d523365SDimitry Andric   // pointers to the same underlying object.
353875ed548SDimitry Andric   if (!UseDependencies) {
354875ed548SDimitry Andric     for (unsigned I = 0; I < Pointers.size(); ++I)
355875ed548SDimitry Andric       CheckingGroups.push_back(CheckingPtrGroup(I, *this));
356875ed548SDimitry Andric     return;
357875ed548SDimitry Andric   }
358875ed548SDimitry Andric 
359875ed548SDimitry Andric   unsigned TotalComparisons = 0;
360875ed548SDimitry Andric 
361875ed548SDimitry Andric   DenseMap<Value *, unsigned> PositionMap;
362875ed548SDimitry Andric   for (unsigned Index = 0; Index < Pointers.size(); ++Index)
363875ed548SDimitry Andric     PositionMap[Pointers[Index].PointerValue] = Index;
364875ed548SDimitry Andric 
365875ed548SDimitry Andric   // We need to keep track of what pointers we've already seen so we
366875ed548SDimitry Andric   // don't process them twice.
367875ed548SDimitry Andric   SmallSet<unsigned, 2> Seen;
368875ed548SDimitry Andric 
3697d523365SDimitry Andric   // Go through all equivalence classes, get the "pointer check groups"
370875ed548SDimitry Andric   // and add them to the overall solution. We use the order in which accesses
371875ed548SDimitry Andric   // appear in 'Pointers' to enforce determinism.
372875ed548SDimitry Andric   for (unsigned I = 0; I < Pointers.size(); ++I) {
373875ed548SDimitry Andric     // We've seen this pointer before, and therefore already processed
374875ed548SDimitry Andric     // its equivalence class.
375875ed548SDimitry Andric     if (Seen.count(I))
376875ed548SDimitry Andric       continue;
377875ed548SDimitry Andric 
378875ed548SDimitry Andric     MemoryDepChecker::MemAccessInfo Access(Pointers[I].PointerValue,
379875ed548SDimitry Andric                                            Pointers[I].IsWritePtr);
380875ed548SDimitry Andric 
381875ed548SDimitry Andric     SmallVector<CheckingPtrGroup, 2> Groups;
382875ed548SDimitry Andric     auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access));
383875ed548SDimitry Andric 
384875ed548SDimitry Andric     // Because DepCands is constructed by visiting accesses in the order in
385875ed548SDimitry Andric     // which they appear in alias sets (which is deterministic) and the
386875ed548SDimitry Andric     // iteration order within an equivalence class member is only dependent on
387875ed548SDimitry Andric     // the order in which unions and insertions are performed on the
388875ed548SDimitry Andric     // equivalence class, the iteration order is deterministic.
389875ed548SDimitry Andric     for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end();
390875ed548SDimitry Andric          MI != ME; ++MI) {
391875ed548SDimitry Andric       unsigned Pointer = PositionMap[MI->getPointer()];
392875ed548SDimitry Andric       bool Merged = false;
393875ed548SDimitry Andric       // Mark this pointer as seen.
394875ed548SDimitry Andric       Seen.insert(Pointer);
395875ed548SDimitry Andric 
396875ed548SDimitry Andric       // Go through all the existing sets and see if we can find one
397875ed548SDimitry Andric       // which can include this pointer.
398875ed548SDimitry Andric       for (CheckingPtrGroup &Group : Groups) {
399875ed548SDimitry Andric         // Don't perform more than a certain amount of comparisons.
400875ed548SDimitry Andric         // This should limit the cost of grouping the pointers to something
401875ed548SDimitry Andric         // reasonable.  If we do end up hitting this threshold, the algorithm
402875ed548SDimitry Andric         // will create separate groups for all remaining pointers.
403875ed548SDimitry Andric         if (TotalComparisons > MemoryCheckMergeThreshold)
404875ed548SDimitry Andric           break;
405875ed548SDimitry Andric 
406875ed548SDimitry Andric         TotalComparisons++;
407875ed548SDimitry Andric 
408875ed548SDimitry Andric         if (Group.addPointer(Pointer)) {
409875ed548SDimitry Andric           Merged = true;
410875ed548SDimitry Andric           break;
411875ed548SDimitry Andric         }
412875ed548SDimitry Andric       }
413875ed548SDimitry Andric 
414875ed548SDimitry Andric       if (!Merged)
415875ed548SDimitry Andric         // We couldn't add this pointer to any existing set or the threshold
416875ed548SDimitry Andric         // for the number of comparisons has been reached. Create a new group
417875ed548SDimitry Andric         // to hold the current pointer.
418875ed548SDimitry Andric         Groups.push_back(CheckingPtrGroup(Pointer, *this));
419875ed548SDimitry Andric     }
420875ed548SDimitry Andric 
421875ed548SDimitry Andric     // We've computed the grouped checks for this partition.
422875ed548SDimitry Andric     // Save the results and continue with the next one.
423*b5893f02SDimitry Andric     llvm::copy(Groups, std::back_inserter(CheckingGroups));
424875ed548SDimitry Andric   }
425875ed548SDimitry Andric }
426875ed548SDimitry Andric 
arePointersInSamePartition(const SmallVectorImpl<int> & PtrToPartition,unsigned PtrIdx1,unsigned PtrIdx2)4277d523365SDimitry Andric bool RuntimePointerChecking::arePointersInSamePartition(
4287d523365SDimitry Andric     const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
4297d523365SDimitry Andric     unsigned PtrIdx2) {
4307d523365SDimitry Andric   return (PtrToPartition[PtrIdx1] != -1 &&
4317d523365SDimitry Andric           PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
4327d523365SDimitry Andric }
4337d523365SDimitry Andric 
needsChecking(unsigned I,unsigned J) const4347d523365SDimitry Andric bool RuntimePointerChecking::needsChecking(unsigned I, unsigned J) const {
435875ed548SDimitry Andric   const PointerInfo &PointerI = Pointers[I];
436875ed548SDimitry Andric   const PointerInfo &PointerJ = Pointers[J];
437875ed548SDimitry Andric 
438ff0cc061SDimitry Andric   // No need to check if two readonly pointers intersect.
439875ed548SDimitry Andric   if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
440ff0cc061SDimitry Andric     return false;
441ff0cc061SDimitry Andric 
442ff0cc061SDimitry Andric   // Only need to check pointers between two different dependency sets.
443875ed548SDimitry Andric   if (PointerI.DependencySetId == PointerJ.DependencySetId)
444ff0cc061SDimitry Andric     return false;
445ff0cc061SDimitry Andric 
446ff0cc061SDimitry Andric   // Only need to check pointers in the same alias set.
447875ed548SDimitry Andric   if (PointerI.AliasSetId != PointerJ.AliasSetId)
448ff0cc061SDimitry Andric     return false;
449ff0cc061SDimitry Andric 
450ff0cc061SDimitry Andric   return true;
451ff0cc061SDimitry Andric }
452ff0cc061SDimitry Andric 
printChecks(raw_ostream & OS,const SmallVectorImpl<PointerCheck> & Checks,unsigned Depth) const4537d523365SDimitry Andric void RuntimePointerChecking::printChecks(
4547d523365SDimitry Andric     raw_ostream &OS, const SmallVectorImpl<PointerCheck> &Checks,
4557d523365SDimitry Andric     unsigned Depth) const {
4567d523365SDimitry Andric   unsigned N = 0;
4577d523365SDimitry Andric   for (const auto &Check : Checks) {
4587d523365SDimitry Andric     const auto &First = Check.first->Members, &Second = Check.second->Members;
4597d523365SDimitry Andric 
4607d523365SDimitry Andric     OS.indent(Depth) << "Check " << N++ << ":\n";
4617d523365SDimitry Andric 
4627d523365SDimitry Andric     OS.indent(Depth + 2) << "Comparing group (" << Check.first << "):\n";
4637d523365SDimitry Andric     for (unsigned K = 0; K < First.size(); ++K)
4647d523365SDimitry Andric       OS.indent(Depth + 2) << *Pointers[First[K]].PointerValue << "\n";
4657d523365SDimitry Andric 
4667d523365SDimitry Andric     OS.indent(Depth + 2) << "Against group (" << Check.second << "):\n";
4677d523365SDimitry Andric     for (unsigned K = 0; K < Second.size(); ++K)
4687d523365SDimitry Andric       OS.indent(Depth + 2) << *Pointers[Second[K]].PointerValue << "\n";
4697d523365SDimitry Andric   }
4707d523365SDimitry Andric }
4717d523365SDimitry Andric 
print(raw_ostream & OS,unsigned Depth) const4727d523365SDimitry Andric void RuntimePointerChecking::print(raw_ostream &OS, unsigned Depth) const {
473ff0cc061SDimitry Andric 
474ff0cc061SDimitry Andric   OS.indent(Depth) << "Run-time memory checks:\n";
4757d523365SDimitry Andric   printChecks(OS, Checks, Depth);
476ff0cc061SDimitry Andric 
477875ed548SDimitry Andric   OS.indent(Depth) << "Grouped accesses:\n";
478875ed548SDimitry Andric   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
4797d523365SDimitry Andric     const auto &CG = CheckingGroups[I];
4807d523365SDimitry Andric 
4817d523365SDimitry Andric     OS.indent(Depth + 2) << "Group " << &CG << ":\n";
4827d523365SDimitry Andric     OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High
4837d523365SDimitry Andric                          << ")\n";
4847d523365SDimitry Andric     for (unsigned J = 0; J < CG.Members.size(); ++J) {
4857d523365SDimitry Andric       OS.indent(Depth + 6) << "Member: " << *Pointers[CG.Members[J]].Expr
486875ed548SDimitry Andric                            << "\n";
487875ed548SDimitry Andric     }
488875ed548SDimitry Andric   }
489875ed548SDimitry Andric }
490875ed548SDimitry Andric 
491ff0cc061SDimitry Andric namespace {
492d88c1a5aSDimitry Andric 
4934ba319b5SDimitry Andric /// Analyses memory accesses in a loop.
494ff0cc061SDimitry Andric ///
495ff0cc061SDimitry Andric /// Checks whether run time pointer checks are needed and builds sets for data
496ff0cc061SDimitry Andric /// dependence checking.
497ff0cc061SDimitry Andric class AccessAnalysis {
498ff0cc061SDimitry Andric public:
4994ba319b5SDimitry Andric   /// Read or write access location.
500ff0cc061SDimitry Andric   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
5017a7e6055SDimitry Andric   typedef SmallVector<MemAccessInfo, 8> MemAccessInfoList;
502ff0cc061SDimitry Andric 
AccessAnalysis(const DataLayout & Dl,Loop * TheLoop,AliasAnalysis * AA,LoopInfo * LI,MemoryDepChecker::DepCandidates & DA,PredicatedScalarEvolution & PSE)5034ba319b5SDimitry Andric   AccessAnalysis(const DataLayout &Dl, Loop *TheLoop, AliasAnalysis *AA,
5044ba319b5SDimitry Andric                  LoopInfo *LI, MemoryDepChecker::DepCandidates &DA,
5057d523365SDimitry Andric                  PredicatedScalarEvolution &PSE)
5064ba319b5SDimitry Andric       : DL(Dl), TheLoop(TheLoop), AST(*AA), LI(LI), DepCands(DA),
5074ba319b5SDimitry Andric         IsRTCheckAnalysisNeeded(false), PSE(PSE) {}
508ff0cc061SDimitry Andric 
5094ba319b5SDimitry Andric   /// Register a load  and whether it is only read from.
addLoad(MemoryLocation & Loc,bool IsReadOnly)5108f0fd8f6SDimitry Andric   void addLoad(MemoryLocation &Loc, bool IsReadOnly) {
511ff0cc061SDimitry Andric     Value *Ptr = const_cast<Value*>(Loc.Ptr);
512*b5893f02SDimitry Andric     AST.add(Ptr, LocationSize::unknown(), Loc.AATags);
513ff0cc061SDimitry Andric     Accesses.insert(MemAccessInfo(Ptr, false));
514ff0cc061SDimitry Andric     if (IsReadOnly)
515ff0cc061SDimitry Andric       ReadOnlyPtr.insert(Ptr);
516ff0cc061SDimitry Andric   }
517ff0cc061SDimitry Andric 
5184ba319b5SDimitry Andric   /// Register a store.
addStore(MemoryLocation & Loc)5198f0fd8f6SDimitry Andric   void addStore(MemoryLocation &Loc) {
520ff0cc061SDimitry Andric     Value *Ptr = const_cast<Value*>(Loc.Ptr);
521*b5893f02SDimitry Andric     AST.add(Ptr, LocationSize::unknown(), Loc.AATags);
522ff0cc061SDimitry Andric     Accesses.insert(MemAccessInfo(Ptr, true));
523ff0cc061SDimitry Andric   }
524ff0cc061SDimitry Andric 
5254ba319b5SDimitry Andric   /// Check if we can emit a run-time no-alias check for \p Access.
5262cab237bSDimitry Andric   ///
5272cab237bSDimitry Andric   /// Returns true if we can emit a run-time no alias check for \p Access.
5282cab237bSDimitry Andric   /// If we can check this access, this also adds it to a dependence set and
5292cab237bSDimitry Andric   /// adds a run-time to check for it to \p RtCheck. If \p Assume is true,
5302cab237bSDimitry Andric   /// we will attempt to use additional run-time checks in order to get
5312cab237bSDimitry Andric   /// the bounds of the pointer.
5322cab237bSDimitry Andric   bool createCheckForAccess(RuntimePointerChecking &RtCheck,
5332cab237bSDimitry Andric                             MemAccessInfo Access,
5342cab237bSDimitry Andric                             const ValueToValueMap &Strides,
5352cab237bSDimitry Andric                             DenseMap<Value *, unsigned> &DepSetId,
5362cab237bSDimitry Andric                             Loop *TheLoop, unsigned &RunningDepId,
5372cab237bSDimitry Andric                             unsigned ASId, bool ShouldCheckStride,
5382cab237bSDimitry Andric                             bool Assume);
5392cab237bSDimitry Andric 
5404ba319b5SDimitry Andric   /// Check whether we can check the pointers at runtime for
541875ed548SDimitry Andric   /// non-intersection.
542875ed548SDimitry Andric   ///
543875ed548SDimitry Andric   /// Returns true if we need no check or if we do and we can generate them
544875ed548SDimitry Andric   /// (i.e. the pointers have computable bounds).
545875ed548SDimitry Andric   bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE,
546875ed548SDimitry Andric                        Loop *TheLoop, const ValueToValueMap &Strides,
5473ca95b02SDimitry Andric                        bool ShouldCheckWrap = false);
548ff0cc061SDimitry Andric 
5494ba319b5SDimitry Andric   /// Goes over all memory accesses, checks whether a RT check is needed
550ff0cc061SDimitry Andric   /// and builds sets of dependent accesses.
buildDependenceSets()551ff0cc061SDimitry Andric   void buildDependenceSets() {
552ff0cc061SDimitry Andric     processMemAccesses();
553ff0cc061SDimitry Andric   }
554ff0cc061SDimitry Andric 
5554ba319b5SDimitry Andric   /// Initial processing of memory accesses determined that we need to
556875ed548SDimitry Andric   /// perform dependency checking.
557875ed548SDimitry Andric   ///
558875ed548SDimitry Andric   /// Note that this can later be cleared if we retry memcheck analysis without
559*b5893f02SDimitry Andric   /// dependency checking (i.e. FoundNonConstantDistanceDependence).
isDependencyCheckNeeded()560ff0cc061SDimitry Andric   bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
561ff0cc061SDimitry Andric 
562ff0cc061SDimitry Andric   /// We decided that no dependence analysis would be used.  Reset the state.
resetDepChecks(MemoryDepChecker & DepChecker)563ff0cc061SDimitry Andric   void resetDepChecks(MemoryDepChecker &DepChecker) {
564ff0cc061SDimitry Andric     CheckDeps.clear();
5657d523365SDimitry Andric     DepChecker.clearDependences();
566ff0cc061SDimitry Andric   }
567ff0cc061SDimitry Andric 
getDependenciesToCheck()5687a7e6055SDimitry Andric   MemAccessInfoList &getDependenciesToCheck() { return CheckDeps; }
569ff0cc061SDimitry Andric 
570ff0cc061SDimitry Andric private:
571ff0cc061SDimitry Andric   typedef SetVector<MemAccessInfo> PtrAccessSet;
572ff0cc061SDimitry Andric 
5734ba319b5SDimitry Andric   /// Go over all memory access and check whether runtime pointer checks
574875ed548SDimitry Andric   /// are needed and build sets of dependency check candidates.
575ff0cc061SDimitry Andric   void processMemAccesses();
576ff0cc061SDimitry Andric 
577ff0cc061SDimitry Andric   /// Set of all accesses.
578ff0cc061SDimitry Andric   PtrAccessSet Accesses;
579ff0cc061SDimitry Andric 
580ff0cc061SDimitry Andric   const DataLayout &DL;
581ff0cc061SDimitry Andric 
5824ba319b5SDimitry Andric   /// The loop being checked.
5834ba319b5SDimitry Andric   const Loop *TheLoop;
5844ba319b5SDimitry Andric 
5857a7e6055SDimitry Andric   /// List of accesses that need a further dependence check.
5867a7e6055SDimitry Andric   MemAccessInfoList CheckDeps;
587ff0cc061SDimitry Andric 
588ff0cc061SDimitry Andric   /// Set of pointers that are read only.
589ff0cc061SDimitry Andric   SmallPtrSet<Value*, 16> ReadOnlyPtr;
590ff0cc061SDimitry Andric 
591ff0cc061SDimitry Andric   /// An alias set tracker to partition the access set by underlying object and
592ff0cc061SDimitry Andric   //intrinsic property (such as TBAA metadata).
593ff0cc061SDimitry Andric   AliasSetTracker AST;
594ff0cc061SDimitry Andric 
595ff0cc061SDimitry Andric   LoopInfo *LI;
596ff0cc061SDimitry Andric 
597ff0cc061SDimitry Andric   /// Sets of potentially dependent accesses - members of one set share an
598ff0cc061SDimitry Andric   /// underlying pointer. The set "CheckDeps" identfies which sets really need a
599ff0cc061SDimitry Andric   /// dependence check.
600ff0cc061SDimitry Andric   MemoryDepChecker::DepCandidates &DepCands;
601ff0cc061SDimitry Andric 
6024ba319b5SDimitry Andric   /// Initial processing of memory accesses determined that we may need
603875ed548SDimitry Andric   /// to add memchecks.  Perform the analysis to determine the necessary checks.
604875ed548SDimitry Andric   ///
605875ed548SDimitry Andric   /// Note that, this is different from isDependencyCheckNeeded.  When we retry
606875ed548SDimitry Andric   /// memcheck analysis without dependency checking
607*b5893f02SDimitry Andric   /// (i.e. FoundNonConstantDistanceDependence), isDependencyCheckNeeded is
608*b5893f02SDimitry Andric   /// cleared while this remains set if we have potentially dependent accesses.
609875ed548SDimitry Andric   bool IsRTCheckAnalysisNeeded;
6107d523365SDimitry Andric 
6117d523365SDimitry Andric   /// The SCEV predicate containing all the SCEV-related assumptions.
6127d523365SDimitry Andric   PredicatedScalarEvolution &PSE;
613ff0cc061SDimitry Andric };
614ff0cc061SDimitry Andric 
615ff0cc061SDimitry Andric } // end anonymous namespace
616ff0cc061SDimitry Andric 
6174ba319b5SDimitry Andric /// Check whether a pointer can participate in a runtime bounds check.
6182cab237bSDimitry Andric /// If \p Assume, try harder to prove that we can compute the bounds of \p Ptr
6192cab237bSDimitry Andric /// by adding run-time checks (overflow checks) if necessary.
hasComputableBounds(PredicatedScalarEvolution & PSE,const ValueToValueMap & Strides,Value * Ptr,Loop * L,bool Assume)6207d523365SDimitry Andric static bool hasComputableBounds(PredicatedScalarEvolution &PSE,
6217d523365SDimitry Andric                                 const ValueToValueMap &Strides, Value *Ptr,
6222cab237bSDimitry Andric                                 Loop *L, bool Assume) {
6237d523365SDimitry Andric   const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
6243ca95b02SDimitry Andric 
6253ca95b02SDimitry Andric   // The bounds for loop-invariant pointer is trivial.
6263ca95b02SDimitry Andric   if (PSE.getSE()->isLoopInvariant(PtrScev, L))
6273ca95b02SDimitry Andric     return true;
6283ca95b02SDimitry Andric 
629ff0cc061SDimitry Andric   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
6302cab237bSDimitry Andric 
6312cab237bSDimitry Andric   if (!AR && Assume)
6322cab237bSDimitry Andric     AR = PSE.getAsAddRec(Ptr);
6332cab237bSDimitry Andric 
634ff0cc061SDimitry Andric   if (!AR)
635ff0cc061SDimitry Andric     return false;
636ff0cc061SDimitry Andric 
637ff0cc061SDimitry Andric   return AR->isAffine();
638ff0cc061SDimitry Andric }
639ff0cc061SDimitry Andric 
6404ba319b5SDimitry Andric /// Check whether a pointer address cannot wrap.
isNoWrap(PredicatedScalarEvolution & PSE,const ValueToValueMap & Strides,Value * Ptr,Loop * L)6413ca95b02SDimitry Andric static bool isNoWrap(PredicatedScalarEvolution &PSE,
6423ca95b02SDimitry Andric                      const ValueToValueMap &Strides, Value *Ptr, Loop *L) {
6433ca95b02SDimitry Andric   const SCEV *PtrScev = PSE.getSCEV(Ptr);
6443ca95b02SDimitry Andric   if (PSE.getSE()->isLoopInvariant(PtrScev, L))
6453ca95b02SDimitry Andric     return true;
6463ca95b02SDimitry Andric 
6473ca95b02SDimitry Andric   int64_t Stride = getPtrStride(PSE, Ptr, L, Strides);
6482cab237bSDimitry Andric   if (Stride == 1 || PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW))
6492cab237bSDimitry Andric     return true;
6502cab237bSDimitry Andric 
6512cab237bSDimitry Andric   return false;
6522cab237bSDimitry Andric }
6532cab237bSDimitry Andric 
createCheckForAccess(RuntimePointerChecking & RtCheck,MemAccessInfo Access,const ValueToValueMap & StridesMap,DenseMap<Value *,unsigned> & DepSetId,Loop * TheLoop,unsigned & RunningDepId,unsigned ASId,bool ShouldCheckWrap,bool Assume)6542cab237bSDimitry Andric bool AccessAnalysis::createCheckForAccess(RuntimePointerChecking &RtCheck,
6552cab237bSDimitry Andric                                           MemAccessInfo Access,
6562cab237bSDimitry Andric                                           const ValueToValueMap &StridesMap,
6572cab237bSDimitry Andric                                           DenseMap<Value *, unsigned> &DepSetId,
6582cab237bSDimitry Andric                                           Loop *TheLoop, unsigned &RunningDepId,
6592cab237bSDimitry Andric                                           unsigned ASId, bool ShouldCheckWrap,
6602cab237bSDimitry Andric                                           bool Assume) {
6612cab237bSDimitry Andric   Value *Ptr = Access.getPointer();
6622cab237bSDimitry Andric 
6632cab237bSDimitry Andric   if (!hasComputableBounds(PSE, StridesMap, Ptr, TheLoop, Assume))
6642cab237bSDimitry Andric     return false;
6652cab237bSDimitry Andric 
6662cab237bSDimitry Andric   // When we run after a failing dependency check we have to make sure
6672cab237bSDimitry Andric   // we don't have wrapping pointers.
6682cab237bSDimitry Andric   if (ShouldCheckWrap && !isNoWrap(PSE, StridesMap, Ptr, TheLoop)) {
6692cab237bSDimitry Andric     auto *Expr = PSE.getSCEV(Ptr);
6702cab237bSDimitry Andric     if (!Assume || !isa<SCEVAddRecExpr>(Expr))
6712cab237bSDimitry Andric       return false;
6722cab237bSDimitry Andric     PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
6732cab237bSDimitry Andric   }
6742cab237bSDimitry Andric 
6752cab237bSDimitry Andric   // The id of the dependence set.
6762cab237bSDimitry Andric   unsigned DepId;
6772cab237bSDimitry Andric 
6782cab237bSDimitry Andric   if (isDependencyCheckNeeded()) {
6792cab237bSDimitry Andric     Value *Leader = DepCands.getLeaderValue(Access).getPointer();
6802cab237bSDimitry Andric     unsigned &LeaderId = DepSetId[Leader];
6812cab237bSDimitry Andric     if (!LeaderId)
6822cab237bSDimitry Andric       LeaderId = RunningDepId++;
6832cab237bSDimitry Andric     DepId = LeaderId;
6842cab237bSDimitry Andric   } else
6852cab237bSDimitry Andric     // Each access has its own dependence set.
6862cab237bSDimitry Andric     DepId = RunningDepId++;
6872cab237bSDimitry Andric 
6882cab237bSDimitry Andric   bool IsWrite = Access.getInt();
6892cab237bSDimitry Andric   RtCheck.insert(TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap, PSE);
6904ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
6912cab237bSDimitry Andric 
6922cab237bSDimitry Andric   return true;
6933ca95b02SDimitry Andric  }
6943ca95b02SDimitry Andric 
canCheckPtrAtRT(RuntimePointerChecking & RtCheck,ScalarEvolution * SE,Loop * TheLoop,const ValueToValueMap & StridesMap,bool ShouldCheckWrap)695875ed548SDimitry Andric bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
696875ed548SDimitry Andric                                      ScalarEvolution *SE, Loop *TheLoop,
697875ed548SDimitry Andric                                      const ValueToValueMap &StridesMap,
6983ca95b02SDimitry Andric                                      bool ShouldCheckWrap) {
699ff0cc061SDimitry Andric   // Find pointers with computable bounds. We are going to use this information
700ff0cc061SDimitry Andric   // to place a runtime bound check.
701ff0cc061SDimitry Andric   bool CanDoRT = true;
702ff0cc061SDimitry Andric 
703875ed548SDimitry Andric   bool NeedRTCheck = false;
704875ed548SDimitry Andric   if (!IsRTCheckAnalysisNeeded) return true;
70597bc6c73SDimitry Andric 
706ff0cc061SDimitry Andric   bool IsDepCheckNeeded = isDependencyCheckNeeded();
707ff0cc061SDimitry Andric 
708ff0cc061SDimitry Andric   // We assign a consecutive id to access from different alias sets.
709ff0cc061SDimitry Andric   // Accesses between different groups doesn't need to be checked.
710ff0cc061SDimitry Andric   unsigned ASId = 1;
711ff0cc061SDimitry Andric   for (auto &AS : AST) {
712875ed548SDimitry Andric     int NumReadPtrChecks = 0;
713875ed548SDimitry Andric     int NumWritePtrChecks = 0;
7142cab237bSDimitry Andric     bool CanDoAliasSetRT = true;
715875ed548SDimitry Andric 
716ff0cc061SDimitry Andric     // We assign consecutive id to access from different dependence sets.
717ff0cc061SDimitry Andric     // Accesses within the same set don't need a runtime check.
718ff0cc061SDimitry Andric     unsigned RunningDepId = 1;
719ff0cc061SDimitry Andric     DenseMap<Value *, unsigned> DepSetId;
720ff0cc061SDimitry Andric 
7212cab237bSDimitry Andric     SmallVector<MemAccessInfo, 4> Retries;
7222cab237bSDimitry Andric 
723ff0cc061SDimitry Andric     for (auto A : AS) {
724ff0cc061SDimitry Andric       Value *Ptr = A.getValue();
725ff0cc061SDimitry Andric       bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
726ff0cc061SDimitry Andric       MemAccessInfo Access(Ptr, IsWrite);
727ff0cc061SDimitry Andric 
728875ed548SDimitry Andric       if (IsWrite)
729875ed548SDimitry Andric         ++NumWritePtrChecks;
730875ed548SDimitry Andric       else
731875ed548SDimitry Andric         ++NumReadPtrChecks;
732875ed548SDimitry Andric 
7332cab237bSDimitry Andric       if (!createCheckForAccess(RtCheck, Access, StridesMap, DepSetId, TheLoop,
7342cab237bSDimitry Andric                                 RunningDepId, ASId, ShouldCheckWrap, false)) {
7354ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" << *Ptr << '\n');
7362cab237bSDimitry Andric         Retries.push_back(Access);
7372cab237bSDimitry Andric         CanDoAliasSetRT = false;
738ff0cc061SDimitry Andric       }
739ff0cc061SDimitry Andric     }
740ff0cc061SDimitry Andric 
741875ed548SDimitry Andric     // If we have at least two writes or one write and a read then we need to
742875ed548SDimitry Andric     // check them.  But there is no need to checks if there is only one
743875ed548SDimitry Andric     // dependence set for this alias set.
744875ed548SDimitry Andric     //
745875ed548SDimitry Andric     // Note that this function computes CanDoRT and NeedRTCheck independently.
746875ed548SDimitry Andric     // For example CanDoRT=false, NeedRTCheck=false means that we have a pointer
747875ed548SDimitry Andric     // for which we couldn't find the bounds but we don't actually need to emit
748875ed548SDimitry Andric     // any checks so it does not matter.
7492cab237bSDimitry Andric     bool NeedsAliasSetRTCheck = false;
7502cab237bSDimitry Andric     if (!(IsDepCheckNeeded && CanDoAliasSetRT && RunningDepId == 2))
7512cab237bSDimitry Andric       NeedsAliasSetRTCheck = (NumWritePtrChecks >= 2 ||
7522cab237bSDimitry Andric                              (NumReadPtrChecks >= 1 && NumWritePtrChecks >= 1));
753875ed548SDimitry Andric 
7542cab237bSDimitry Andric     // We need to perform run-time alias checks, but some pointers had bounds
7552cab237bSDimitry Andric     // that couldn't be checked.
7562cab237bSDimitry Andric     if (NeedsAliasSetRTCheck && !CanDoAliasSetRT) {
7572cab237bSDimitry Andric       // Reset the CanDoSetRt flag and retry all accesses that have failed.
7582cab237bSDimitry Andric       // We know that we need these checks, so we can now be more aggressive
7592cab237bSDimitry Andric       // and add further checks if required (overflow checks).
7602cab237bSDimitry Andric       CanDoAliasSetRT = true;
7612cab237bSDimitry Andric       for (auto Access : Retries)
7622cab237bSDimitry Andric         if (!createCheckForAccess(RtCheck, Access, StridesMap, DepSetId,
7632cab237bSDimitry Andric                                   TheLoop, RunningDepId, ASId,
7642cab237bSDimitry Andric                                   ShouldCheckWrap, /*Assume=*/true)) {
7652cab237bSDimitry Andric           CanDoAliasSetRT = false;
7662cab237bSDimitry Andric           break;
7672cab237bSDimitry Andric         }
7682cab237bSDimitry Andric     }
7692cab237bSDimitry Andric 
7702cab237bSDimitry Andric     CanDoRT &= CanDoAliasSetRT;
7712cab237bSDimitry Andric     NeedRTCheck |= NeedsAliasSetRTCheck;
772ff0cc061SDimitry Andric     ++ASId;
773ff0cc061SDimitry Andric   }
774ff0cc061SDimitry Andric 
775ff0cc061SDimitry Andric   // If the pointers that we would use for the bounds comparison have different
776ff0cc061SDimitry Andric   // address spaces, assume the values aren't directly comparable, so we can't
777ff0cc061SDimitry Andric   // use them for the runtime check. We also have to assume they could
778ff0cc061SDimitry Andric   // overlap. In the future there should be metadata for whether address spaces
779ff0cc061SDimitry Andric   // are disjoint.
780ff0cc061SDimitry Andric   unsigned NumPointers = RtCheck.Pointers.size();
781ff0cc061SDimitry Andric   for (unsigned i = 0; i < NumPointers; ++i) {
782ff0cc061SDimitry Andric     for (unsigned j = i + 1; j < NumPointers; ++j) {
783ff0cc061SDimitry Andric       // Only need to check pointers between two different dependency sets.
784875ed548SDimitry Andric       if (RtCheck.Pointers[i].DependencySetId ==
785875ed548SDimitry Andric           RtCheck.Pointers[j].DependencySetId)
786ff0cc061SDimitry Andric        continue;
787ff0cc061SDimitry Andric       // Only need to check pointers in the same alias set.
788875ed548SDimitry Andric       if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
789ff0cc061SDimitry Andric         continue;
790ff0cc061SDimitry Andric 
791875ed548SDimitry Andric       Value *PtrI = RtCheck.Pointers[i].PointerValue;
792875ed548SDimitry Andric       Value *PtrJ = RtCheck.Pointers[j].PointerValue;
793ff0cc061SDimitry Andric 
794ff0cc061SDimitry Andric       unsigned ASi = PtrI->getType()->getPointerAddressSpace();
795ff0cc061SDimitry Andric       unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
796ff0cc061SDimitry Andric       if (ASi != ASj) {
7974ba319b5SDimitry Andric         LLVM_DEBUG(
7984ba319b5SDimitry Andric             dbgs() << "LAA: Runtime check would require comparison between"
799ff0cc061SDimitry Andric                       " different address spaces\n");
800ff0cc061SDimitry Andric         return false;
801ff0cc061SDimitry Andric       }
802ff0cc061SDimitry Andric     }
803ff0cc061SDimitry Andric   }
804ff0cc061SDimitry Andric 
805875ed548SDimitry Andric   if (NeedRTCheck && CanDoRT)
8067d523365SDimitry Andric     RtCheck.generateChecks(DepCands, IsDepCheckNeeded);
807875ed548SDimitry Andric 
8084ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks()
809875ed548SDimitry Andric                     << " pointer comparisons.\n");
810875ed548SDimitry Andric 
811875ed548SDimitry Andric   RtCheck.Need = NeedRTCheck;
812875ed548SDimitry Andric 
813875ed548SDimitry Andric   bool CanDoRTIfNeeded = !NeedRTCheck || CanDoRT;
814875ed548SDimitry Andric   if (!CanDoRTIfNeeded)
815875ed548SDimitry Andric     RtCheck.reset();
816875ed548SDimitry Andric   return CanDoRTIfNeeded;
817ff0cc061SDimitry Andric }
818ff0cc061SDimitry Andric 
processMemAccesses()819ff0cc061SDimitry Andric void AccessAnalysis::processMemAccesses() {
820ff0cc061SDimitry Andric   // We process the set twice: first we process read-write pointers, last we
821ff0cc061SDimitry Andric   // process read-only pointers. This allows us to skip dependence tests for
822ff0cc061SDimitry Andric   // read-only pointers.
823ff0cc061SDimitry Andric 
8244ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
8254ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "  AST: "; AST.dump());
8264ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA:   Accesses(" << Accesses.size() << "):\n");
8274ba319b5SDimitry Andric   LLVM_DEBUG({
828ff0cc061SDimitry Andric     for (auto A : Accesses)
829ff0cc061SDimitry Andric       dbgs() << "\t" << *A.getPointer() << " (" <<
830ff0cc061SDimitry Andric                 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
831ff0cc061SDimitry Andric                                          "read-only" : "read")) << ")\n";
832ff0cc061SDimitry Andric   });
833ff0cc061SDimitry Andric 
834ff0cc061SDimitry Andric   // The AliasSetTracker has nicely partitioned our pointers by metadata
835ff0cc061SDimitry Andric   // compatibility and potential for underlying-object overlap. As a result, we
836ff0cc061SDimitry Andric   // only need to check for potential pointer dependencies within each alias
837ff0cc061SDimitry Andric   // set.
838ff0cc061SDimitry Andric   for (auto &AS : AST) {
839ff0cc061SDimitry Andric     // Note that both the alias-set tracker and the alias sets themselves used
840ff0cc061SDimitry Andric     // linked lists internally and so the iteration order here is deterministic
841ff0cc061SDimitry Andric     // (matching the original instruction order within each set).
842ff0cc061SDimitry Andric 
843ff0cc061SDimitry Andric     bool SetHasWrite = false;
844ff0cc061SDimitry Andric 
845ff0cc061SDimitry Andric     // Map of pointers to last access encountered.
846ff0cc061SDimitry Andric     typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
847ff0cc061SDimitry Andric     UnderlyingObjToAccessMap ObjToLastAccess;
848ff0cc061SDimitry Andric 
849ff0cc061SDimitry Andric     // Set of access to check after all writes have been processed.
850ff0cc061SDimitry Andric     PtrAccessSet DeferredAccesses;
851ff0cc061SDimitry Andric 
852ff0cc061SDimitry Andric     // Iterate over each alias set twice, once to process read/write pointers,
853ff0cc061SDimitry Andric     // and then to process read-only pointers.
854ff0cc061SDimitry Andric     for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
855ff0cc061SDimitry Andric       bool UseDeferred = SetIteration > 0;
856ff0cc061SDimitry Andric       PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
857ff0cc061SDimitry Andric 
858ff0cc061SDimitry Andric       for (auto AV : AS) {
859ff0cc061SDimitry Andric         Value *Ptr = AV.getValue();
860ff0cc061SDimitry Andric 
861ff0cc061SDimitry Andric         // For a single memory access in AliasSetTracker, Accesses may contain
862ff0cc061SDimitry Andric         // both read and write, and they both need to be handled for CheckDeps.
863ff0cc061SDimitry Andric         for (auto AC : S) {
864ff0cc061SDimitry Andric           if (AC.getPointer() != Ptr)
865ff0cc061SDimitry Andric             continue;
866ff0cc061SDimitry Andric 
867ff0cc061SDimitry Andric           bool IsWrite = AC.getInt();
868ff0cc061SDimitry Andric 
869ff0cc061SDimitry Andric           // If we're using the deferred access set, then it contains only
870ff0cc061SDimitry Andric           // reads.
871ff0cc061SDimitry Andric           bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
872ff0cc061SDimitry Andric           if (UseDeferred && !IsReadOnlyPtr)
873ff0cc061SDimitry Andric             continue;
874ff0cc061SDimitry Andric           // Otherwise, the pointer must be in the PtrAccessSet, either as a
875ff0cc061SDimitry Andric           // read or a write.
876ff0cc061SDimitry Andric           assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
877ff0cc061SDimitry Andric                   S.count(MemAccessInfo(Ptr, false))) &&
878ff0cc061SDimitry Andric                  "Alias-set pointer not in the access set?");
879ff0cc061SDimitry Andric 
880ff0cc061SDimitry Andric           MemAccessInfo Access(Ptr, IsWrite);
881ff0cc061SDimitry Andric           DepCands.insert(Access);
882ff0cc061SDimitry Andric 
883ff0cc061SDimitry Andric           // Memorize read-only pointers for later processing and skip them in
884ff0cc061SDimitry Andric           // the first round (they need to be checked after we have seen all
885ff0cc061SDimitry Andric           // write pointers). Note: we also mark pointer that are not
886ff0cc061SDimitry Andric           // consecutive as "read-only" pointers (so that we check
887ff0cc061SDimitry Andric           // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
888ff0cc061SDimitry Andric           if (!UseDeferred && IsReadOnlyPtr) {
889ff0cc061SDimitry Andric             DeferredAccesses.insert(Access);
890ff0cc061SDimitry Andric             continue;
891ff0cc061SDimitry Andric           }
892ff0cc061SDimitry Andric 
893ff0cc061SDimitry Andric           // If this is a write - check other reads and writes for conflicts. If
894ff0cc061SDimitry Andric           // this is a read only check other writes for conflicts (but only if
895ff0cc061SDimitry Andric           // there is no other write to the ptr - this is an optimization to
896ff0cc061SDimitry Andric           // catch "a[i] = a[i] + " without having to do a dependence check).
897ff0cc061SDimitry Andric           if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
8987a7e6055SDimitry Andric             CheckDeps.push_back(Access);
899875ed548SDimitry Andric             IsRTCheckAnalysisNeeded = true;
900ff0cc061SDimitry Andric           }
901ff0cc061SDimitry Andric 
902ff0cc061SDimitry Andric           if (IsWrite)
903ff0cc061SDimitry Andric             SetHasWrite = true;
904ff0cc061SDimitry Andric 
905ff0cc061SDimitry Andric           // Create sets of pointers connected by a shared alias set and
906ff0cc061SDimitry Andric           // underlying object.
907ff0cc061SDimitry Andric           typedef SmallVector<Value *, 16> ValueVector;
908ff0cc061SDimitry Andric           ValueVector TempObjects;
909ff0cc061SDimitry Andric 
910ff0cc061SDimitry Andric           GetUnderlyingObjects(Ptr, TempObjects, DL, LI);
9114ba319b5SDimitry Andric           LLVM_DEBUG(dbgs()
9124ba319b5SDimitry Andric                      << "Underlying objects for pointer " << *Ptr << "\n");
913ff0cc061SDimitry Andric           for (Value *UnderlyingObj : TempObjects) {
9147d523365SDimitry Andric             // nullptr never alias, don't join sets for pointer that have "null"
9157d523365SDimitry Andric             // in their UnderlyingObjects list.
9164ba319b5SDimitry Andric             if (isa<ConstantPointerNull>(UnderlyingObj) &&
9174ba319b5SDimitry Andric                 !NullPointerIsDefined(
9184ba319b5SDimitry Andric                     TheLoop->getHeader()->getParent(),
9194ba319b5SDimitry Andric                     UnderlyingObj->getType()->getPointerAddressSpace()))
9207d523365SDimitry Andric               continue;
9217d523365SDimitry Andric 
922ff0cc061SDimitry Andric             UnderlyingObjToAccessMap::iterator Prev =
923ff0cc061SDimitry Andric                 ObjToLastAccess.find(UnderlyingObj);
924ff0cc061SDimitry Andric             if (Prev != ObjToLastAccess.end())
925ff0cc061SDimitry Andric               DepCands.unionSets(Access, Prev->second);
926ff0cc061SDimitry Andric 
927ff0cc061SDimitry Andric             ObjToLastAccess[UnderlyingObj] = Access;
9284ba319b5SDimitry Andric             LLVM_DEBUG(dbgs() << "  " << *UnderlyingObj << "\n");
929ff0cc061SDimitry Andric           }
930ff0cc061SDimitry Andric         }
931ff0cc061SDimitry Andric       }
932ff0cc061SDimitry Andric     }
933ff0cc061SDimitry Andric   }
934ff0cc061SDimitry Andric }
935ff0cc061SDimitry Andric 
isInBoundsGep(Value * Ptr)936ff0cc061SDimitry Andric static bool isInBoundsGep(Value *Ptr) {
937ff0cc061SDimitry Andric   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
938ff0cc061SDimitry Andric     return GEP->isInBounds();
939ff0cc061SDimitry Andric   return false;
940ff0cc061SDimitry Andric }
941ff0cc061SDimitry Andric 
9424ba319b5SDimitry Andric /// Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
9433dac3a9bSDimitry Andric /// i.e. monotonically increasing/decreasing.
isNoWrapAddRec(Value * Ptr,const SCEVAddRecExpr * AR,PredicatedScalarEvolution & PSE,const Loop * L)9443dac3a9bSDimitry Andric static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
9453ca95b02SDimitry Andric                            PredicatedScalarEvolution &PSE, const Loop *L) {
9463dac3a9bSDimitry Andric   // FIXME: This should probably only return true for NUW.
9473dac3a9bSDimitry Andric   if (AR->getNoWrapFlags(SCEV::NoWrapMask))
9483dac3a9bSDimitry Andric     return true;
9493dac3a9bSDimitry Andric 
9503dac3a9bSDimitry Andric   // Scalar evolution does not propagate the non-wrapping flags to values that
9513dac3a9bSDimitry Andric   // are derived from a non-wrapping induction variable because non-wrapping
9523dac3a9bSDimitry Andric   // could be flow-sensitive.
9533dac3a9bSDimitry Andric   //
9543dac3a9bSDimitry Andric   // Look through the potentially overflowing instruction to try to prove
9553dac3a9bSDimitry Andric   // non-wrapping for the *specific* value of Ptr.
9563dac3a9bSDimitry Andric 
9573dac3a9bSDimitry Andric   // The arithmetic implied by an inbounds GEP can't overflow.
9583dac3a9bSDimitry Andric   auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
9593dac3a9bSDimitry Andric   if (!GEP || !GEP->isInBounds())
9603dac3a9bSDimitry Andric     return false;
9613dac3a9bSDimitry Andric 
9623dac3a9bSDimitry Andric   // Make sure there is only one non-const index and analyze that.
9633dac3a9bSDimitry Andric   Value *NonConstIndex = nullptr;
9643ca95b02SDimitry Andric   for (Value *Index : make_range(GEP->idx_begin(), GEP->idx_end()))
9653ca95b02SDimitry Andric     if (!isa<ConstantInt>(Index)) {
9663dac3a9bSDimitry Andric       if (NonConstIndex)
9673dac3a9bSDimitry Andric         return false;
9683ca95b02SDimitry Andric       NonConstIndex = Index;
9693dac3a9bSDimitry Andric     }
9703dac3a9bSDimitry Andric   if (!NonConstIndex)
9713dac3a9bSDimitry Andric     // The recurrence is on the pointer, ignore for now.
9723dac3a9bSDimitry Andric     return false;
9733dac3a9bSDimitry Andric 
9743dac3a9bSDimitry Andric   // The index in GEP is signed.  It is non-wrapping if it's derived from a NSW
9753dac3a9bSDimitry Andric   // AddRec using a NSW operation.
9763dac3a9bSDimitry Andric   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
9773dac3a9bSDimitry Andric     if (OBO->hasNoSignedWrap() &&
9783dac3a9bSDimitry Andric         // Assume constant for other the operand so that the AddRec can be
9793dac3a9bSDimitry Andric         // easily found.
9803dac3a9bSDimitry Andric         isa<ConstantInt>(OBO->getOperand(1))) {
9813ca95b02SDimitry Andric       auto *OpScev = PSE.getSCEV(OBO->getOperand(0));
9823dac3a9bSDimitry Andric 
9833dac3a9bSDimitry Andric       if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
9843dac3a9bSDimitry Andric         return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
9853dac3a9bSDimitry Andric     }
9863dac3a9bSDimitry Andric 
9873dac3a9bSDimitry Andric   return false;
9883dac3a9bSDimitry Andric }
9893dac3a9bSDimitry Andric 
9904ba319b5SDimitry Andric /// Check whether the access through \p Ptr has a constant stride.
getPtrStride(PredicatedScalarEvolution & PSE,Value * Ptr,const Loop * Lp,const ValueToValueMap & StridesMap,bool Assume,bool ShouldCheckWrap)9913ca95b02SDimitry Andric int64_t llvm::getPtrStride(PredicatedScalarEvolution &PSE, Value *Ptr,
9923ca95b02SDimitry Andric                            const Loop *Lp, const ValueToValueMap &StridesMap,
993d88c1a5aSDimitry Andric                            bool Assume, bool ShouldCheckWrap) {
9947d523365SDimitry Andric   Type *Ty = Ptr->getType();
995ff0cc061SDimitry Andric   assert(Ty->isPointerTy() && "Unexpected non-ptr");
996ff0cc061SDimitry Andric 
997ff0cc061SDimitry Andric   // Make sure that the pointer does not point to aggregate types.
9987d523365SDimitry Andric   auto *PtrTy = cast<PointerType>(Ty);
999ff0cc061SDimitry Andric   if (PtrTy->getElementType()->isAggregateType()) {
10004ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
10014ba319b5SDimitry Andric                       << *Ptr << "\n");
1002ff0cc061SDimitry Andric     return 0;
1003ff0cc061SDimitry Andric   }
1004ff0cc061SDimitry Andric 
10057d523365SDimitry Andric   const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr);
1006ff0cc061SDimitry Andric 
1007ff0cc061SDimitry Andric   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
10083ca95b02SDimitry Andric   if (Assume && !AR)
10093ca95b02SDimitry Andric     AR = PSE.getAsAddRec(Ptr);
10103ca95b02SDimitry Andric 
1011ff0cc061SDimitry Andric   if (!AR) {
10124ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer " << *Ptr
10133ca95b02SDimitry Andric                       << " SCEV: " << *PtrScev << "\n");
1014ff0cc061SDimitry Andric     return 0;
1015ff0cc061SDimitry Andric   }
1016ff0cc061SDimitry Andric 
1017ff0cc061SDimitry Andric   // The accesss function must stride over the innermost loop.
1018ff0cc061SDimitry Andric   if (Lp != AR->getLoop()) {
10194ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop "
10204ba319b5SDimitry Andric                       << *Ptr << " SCEV: " << *AR << "\n");
1021444ed5c5SDimitry Andric     return 0;
1022ff0cc061SDimitry Andric   }
1023ff0cc061SDimitry Andric 
1024ff0cc061SDimitry Andric   // The address calculation must not wrap. Otherwise, a dependence could be
1025ff0cc061SDimitry Andric   // inverted.
1026ff0cc061SDimitry Andric   // An inbounds getelementptr that is a AddRec with a unit stride
1027ff0cc061SDimitry Andric   // cannot wrap per definition. The unit stride requirement is checked later.
1028ff0cc061SDimitry Andric   // An getelementptr without an inbounds attribute and unit stride would have
1029ff0cc061SDimitry Andric   // to access the pointer value "0" which is undefined behavior in address
1030ff0cc061SDimitry Andric   // space 0, therefore we can also vectorize this case.
1031ff0cc061SDimitry Andric   bool IsInBoundsGEP = isInBoundsGep(Ptr);
1032d88c1a5aSDimitry Andric   bool IsNoWrapAddRec = !ShouldCheckWrap ||
10333ca95b02SDimitry Andric     PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW) ||
10343ca95b02SDimitry Andric     isNoWrapAddRec(Ptr, AR, PSE, Lp);
10354ba319b5SDimitry Andric   if (!IsNoWrapAddRec && !IsInBoundsGEP &&
10364ba319b5SDimitry Andric       NullPointerIsDefined(Lp->getHeader()->getParent(),
10374ba319b5SDimitry Andric                            PtrTy->getAddressSpace())) {
10383ca95b02SDimitry Andric     if (Assume) {
10393ca95b02SDimitry Andric       PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
10403ca95b02SDimitry Andric       IsNoWrapAddRec = true;
10414ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "LAA: Pointer may wrap in the address space:\n"
10423ca95b02SDimitry Andric                         << "LAA:   Pointer: " << *Ptr << "\n"
10433ca95b02SDimitry Andric                         << "LAA:   SCEV: " << *AR << "\n"
10443ca95b02SDimitry Andric                         << "LAA:   Added an overflow assumption\n");
10453ca95b02SDimitry Andric     } else {
10464ba319b5SDimitry Andric       LLVM_DEBUG(
10474ba319b5SDimitry Andric           dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
10483ca95b02SDimitry Andric                  << *Ptr << " SCEV: " << *AR << "\n");
1049ff0cc061SDimitry Andric       return 0;
1050ff0cc061SDimitry Andric     }
10513ca95b02SDimitry Andric   }
1052ff0cc061SDimitry Andric 
1053ff0cc061SDimitry Andric   // Check the step is constant.
10547d523365SDimitry Andric   const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
1055ff0cc061SDimitry Andric 
1056875ed548SDimitry Andric   // Calculate the pointer stride and check if it is constant.
1057ff0cc061SDimitry Andric   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
1058ff0cc061SDimitry Andric   if (!C) {
10594ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr
10604ba319b5SDimitry Andric                       << " SCEV: " << *AR << "\n");
1061ff0cc061SDimitry Andric     return 0;
1062ff0cc061SDimitry Andric   }
1063ff0cc061SDimitry Andric 
1064ff0cc061SDimitry Andric   auto &DL = Lp->getHeader()->getModule()->getDataLayout();
1065ff0cc061SDimitry Andric   int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
10667d523365SDimitry Andric   const APInt &APStepVal = C->getAPInt();
1067ff0cc061SDimitry Andric 
1068ff0cc061SDimitry Andric   // Huge step value - give up.
1069ff0cc061SDimitry Andric   if (APStepVal.getBitWidth() > 64)
1070ff0cc061SDimitry Andric     return 0;
1071ff0cc061SDimitry Andric 
1072ff0cc061SDimitry Andric   int64_t StepVal = APStepVal.getSExtValue();
1073ff0cc061SDimitry Andric 
1074ff0cc061SDimitry Andric   // Strided access.
1075ff0cc061SDimitry Andric   int64_t Stride = StepVal / Size;
1076ff0cc061SDimitry Andric   int64_t Rem = StepVal % Size;
1077ff0cc061SDimitry Andric   if (Rem)
1078ff0cc061SDimitry Andric     return 0;
1079ff0cc061SDimitry Andric 
1080ff0cc061SDimitry Andric   // If the SCEV could wrap but we have an inbounds gep with a unit stride we
1081ff0cc061SDimitry Andric   // know we can't "wrap around the address space". In case of address space
1082ff0cc061SDimitry Andric   // zero we know that this won't happen without triggering undefined behavior.
10834ba319b5SDimitry Andric   if (!IsNoWrapAddRec && Stride != 1 && Stride != -1 &&
10844ba319b5SDimitry Andric       (IsInBoundsGEP || !NullPointerIsDefined(Lp->getHeader()->getParent(),
10854ba319b5SDimitry Andric                                               PtrTy->getAddressSpace()))) {
10863ca95b02SDimitry Andric     if (Assume) {
10873ca95b02SDimitry Andric       // We can avoid this case by adding a run-time check.
10884ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "LAA: Non unit strided pointer which is not either "
10893ca95b02SDimitry Andric                         << "inbouds or in address space 0 may wrap:\n"
10903ca95b02SDimitry Andric                         << "LAA:   Pointer: " << *Ptr << "\n"
10913ca95b02SDimitry Andric                         << "LAA:   SCEV: " << *AR << "\n"
10923ca95b02SDimitry Andric                         << "LAA:   Added an overflow assumption\n");
10933ca95b02SDimitry Andric       PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
10943ca95b02SDimitry Andric     } else
1095ff0cc061SDimitry Andric       return 0;
10963ca95b02SDimitry Andric   }
1097ff0cc061SDimitry Andric 
1098ff0cc061SDimitry Andric   return Stride;
1099ff0cc061SDimitry Andric }
1100ff0cc061SDimitry Andric 
sortPtrAccesses(ArrayRef<Value * > VL,const DataLayout & DL,ScalarEvolution & SE,SmallVectorImpl<unsigned> & SortedIndices)11014ba319b5SDimitry Andric bool llvm::sortPtrAccesses(ArrayRef<Value *> VL, const DataLayout &DL,
11024ba319b5SDimitry Andric                            ScalarEvolution &SE,
11034ba319b5SDimitry Andric                            SmallVectorImpl<unsigned> &SortedIndices) {
11044ba319b5SDimitry Andric   assert(llvm::all_of(
11054ba319b5SDimitry Andric              VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&
11064ba319b5SDimitry Andric          "Expected list of pointer operands.");
11074ba319b5SDimitry Andric   SmallVector<std::pair<int64_t, Value *>, 4> OffValPairs;
11084ba319b5SDimitry Andric   OffValPairs.reserve(VL.size());
11094ba319b5SDimitry Andric 
11104ba319b5SDimitry Andric   // Walk over the pointers, and map each of them to an offset relative to
11114ba319b5SDimitry Andric   // first pointer in the array.
11124ba319b5SDimitry Andric   Value *Ptr0 = VL[0];
11134ba319b5SDimitry Andric   const SCEV *Scev0 = SE.getSCEV(Ptr0);
11144ba319b5SDimitry Andric   Value *Obj0 = GetUnderlyingObject(Ptr0, DL);
11154ba319b5SDimitry Andric 
11164ba319b5SDimitry Andric   llvm::SmallSet<int64_t, 4> Offsets;
11174ba319b5SDimitry Andric   for (auto *Ptr : VL) {
11184ba319b5SDimitry Andric     // TODO: Outline this code as a special, more time consuming, version of
11194ba319b5SDimitry Andric     // computeConstantDifference() function.
11204ba319b5SDimitry Andric     if (Ptr->getType()->getPointerAddressSpace() !=
11214ba319b5SDimitry Andric         Ptr0->getType()->getPointerAddressSpace())
11224ba319b5SDimitry Andric       return false;
11234ba319b5SDimitry Andric     // If a pointer refers to a different underlying object, bail - the
11244ba319b5SDimitry Andric     // pointers are by definition incomparable.
11254ba319b5SDimitry Andric     Value *CurrObj = GetUnderlyingObject(Ptr, DL);
11264ba319b5SDimitry Andric     if (CurrObj != Obj0)
11274ba319b5SDimitry Andric       return false;
11284ba319b5SDimitry Andric 
11294ba319b5SDimitry Andric     const SCEV *Scev = SE.getSCEV(Ptr);
11304ba319b5SDimitry Andric     const auto *Diff = dyn_cast<SCEVConstant>(SE.getMinusSCEV(Scev, Scev0));
11314ba319b5SDimitry Andric     // The pointers may not have a constant offset from each other, or SCEV
11324ba319b5SDimitry Andric     // may just not be smart enough to figure out they do. Regardless,
11334ba319b5SDimitry Andric     // there's nothing we can do.
11344ba319b5SDimitry Andric     if (!Diff)
11354ba319b5SDimitry Andric       return false;
11364ba319b5SDimitry Andric 
11374ba319b5SDimitry Andric     // Check if the pointer with the same offset is found.
11384ba319b5SDimitry Andric     int64_t Offset = Diff->getAPInt().getSExtValue();
11394ba319b5SDimitry Andric     if (!Offsets.insert(Offset).second)
11404ba319b5SDimitry Andric       return false;
11414ba319b5SDimitry Andric     OffValPairs.emplace_back(Offset, Ptr);
11424ba319b5SDimitry Andric   }
11434ba319b5SDimitry Andric   SortedIndices.clear();
11444ba319b5SDimitry Andric   SortedIndices.resize(VL.size());
11454ba319b5SDimitry Andric   std::iota(SortedIndices.begin(), SortedIndices.end(), 0);
11464ba319b5SDimitry Andric 
11474ba319b5SDimitry Andric   // Sort the memory accesses and keep the order of their uses in UseOrder.
11484ba319b5SDimitry Andric   std::stable_sort(SortedIndices.begin(), SortedIndices.end(),
11494ba319b5SDimitry Andric                    [&OffValPairs](unsigned Left, unsigned Right) {
11504ba319b5SDimitry Andric                      return OffValPairs[Left].first < OffValPairs[Right].first;
11514ba319b5SDimitry Andric                    });
11524ba319b5SDimitry Andric 
11534ba319b5SDimitry Andric   // Check if the order is consecutive already.
11544ba319b5SDimitry Andric   if (llvm::all_of(SortedIndices, [&SortedIndices](const unsigned I) {
11554ba319b5SDimitry Andric         return I == SortedIndices[I];
11564ba319b5SDimitry Andric       }))
11574ba319b5SDimitry Andric     SortedIndices.clear();
11584ba319b5SDimitry Andric 
11594ba319b5SDimitry Andric   return true;
11603ca95b02SDimitry Andric }
11613ca95b02SDimitry Andric 
11623ca95b02SDimitry Andric /// Take the address space operand from the Load/Store instruction.
11633ca95b02SDimitry Andric /// Returns -1 if this is not a valid Load/Store instruction.
getAddressSpaceOperand(Value * I)11643ca95b02SDimitry Andric static unsigned getAddressSpaceOperand(Value *I) {
11653ca95b02SDimitry Andric   if (LoadInst *L = dyn_cast<LoadInst>(I))
11663ca95b02SDimitry Andric     return L->getPointerAddressSpace();
11673ca95b02SDimitry Andric   if (StoreInst *S = dyn_cast<StoreInst>(I))
11683ca95b02SDimitry Andric     return S->getPointerAddressSpace();
11693ca95b02SDimitry Andric   return -1;
11703ca95b02SDimitry Andric }
11713ca95b02SDimitry Andric 
11723ca95b02SDimitry Andric /// Returns true if the memory operations \p A and \p B are consecutive.
isConsecutiveAccess(Value * A,Value * B,const DataLayout & DL,ScalarEvolution & SE,bool CheckType)11733ca95b02SDimitry Andric bool llvm::isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL,
11743ca95b02SDimitry Andric                                ScalarEvolution &SE, bool CheckType) {
11754ba319b5SDimitry Andric   Value *PtrA = getLoadStorePointerOperand(A);
11764ba319b5SDimitry Andric   Value *PtrB = getLoadStorePointerOperand(B);
11773ca95b02SDimitry Andric   unsigned ASA = getAddressSpaceOperand(A);
11783ca95b02SDimitry Andric   unsigned ASB = getAddressSpaceOperand(B);
11793ca95b02SDimitry Andric 
11803ca95b02SDimitry Andric   // Check that the address spaces match and that the pointers are valid.
11813ca95b02SDimitry Andric   if (!PtrA || !PtrB || (ASA != ASB))
11823ca95b02SDimitry Andric     return false;
11833ca95b02SDimitry Andric 
11843ca95b02SDimitry Andric   // Make sure that A and B are different pointers.
11853ca95b02SDimitry Andric   if (PtrA == PtrB)
11863ca95b02SDimitry Andric     return false;
11873ca95b02SDimitry Andric 
11883ca95b02SDimitry Andric   // Make sure that A and B have the same type if required.
11893ca95b02SDimitry Andric   if (CheckType && PtrA->getType() != PtrB->getType())
11903ca95b02SDimitry Andric     return false;
11913ca95b02SDimitry Andric 
11924ba319b5SDimitry Andric   unsigned IdxWidth = DL.getIndexSizeInBits(ASA);
11933ca95b02SDimitry Andric   Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
11944ba319b5SDimitry Andric   APInt Size(IdxWidth, DL.getTypeStoreSize(Ty));
11953ca95b02SDimitry Andric 
11964ba319b5SDimitry Andric   APInt OffsetA(IdxWidth, 0), OffsetB(IdxWidth, 0);
11973ca95b02SDimitry Andric   PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetA);
11983ca95b02SDimitry Andric   PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetB);
11993ca95b02SDimitry Andric 
12003ca95b02SDimitry Andric   //  OffsetDelta = OffsetB - OffsetA;
12013ca95b02SDimitry Andric   const SCEV *OffsetSCEVA = SE.getConstant(OffsetA);
12023ca95b02SDimitry Andric   const SCEV *OffsetSCEVB = SE.getConstant(OffsetB);
12033ca95b02SDimitry Andric   const SCEV *OffsetDeltaSCEV = SE.getMinusSCEV(OffsetSCEVB, OffsetSCEVA);
12043ca95b02SDimitry Andric   const SCEVConstant *OffsetDeltaC = dyn_cast<SCEVConstant>(OffsetDeltaSCEV);
12053ca95b02SDimitry Andric   const APInt &OffsetDelta = OffsetDeltaC->getAPInt();
12063ca95b02SDimitry Andric   // Check if they are based on the same pointer. That makes the offsets
12073ca95b02SDimitry Andric   // sufficient.
12083ca95b02SDimitry Andric   if (PtrA == PtrB)
12093ca95b02SDimitry Andric     return OffsetDelta == Size;
12103ca95b02SDimitry Andric 
12113ca95b02SDimitry Andric   // Compute the necessary base pointer delta to have the necessary final delta
12123ca95b02SDimitry Andric   // equal to the size.
12133ca95b02SDimitry Andric   // BaseDelta = Size - OffsetDelta;
12143ca95b02SDimitry Andric   const SCEV *SizeSCEV = SE.getConstant(Size);
12153ca95b02SDimitry Andric   const SCEV *BaseDelta = SE.getMinusSCEV(SizeSCEV, OffsetDeltaSCEV);
12163ca95b02SDimitry Andric 
12173ca95b02SDimitry Andric   // Otherwise compute the distance with SCEV between the base pointers.
12183ca95b02SDimitry Andric   const SCEV *PtrSCEVA = SE.getSCEV(PtrA);
12193ca95b02SDimitry Andric   const SCEV *PtrSCEVB = SE.getSCEV(PtrB);
12203ca95b02SDimitry Andric   const SCEV *X = SE.getAddExpr(PtrSCEVA, BaseDelta);
12213ca95b02SDimitry Andric   return X == PtrSCEVB;
12223ca95b02SDimitry Andric }
12233ca95b02SDimitry Andric 
1224*b5893f02SDimitry Andric MemoryDepChecker::VectorizationSafetyStatus
isSafeForVectorization(DepType Type)1225*b5893f02SDimitry Andric MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
1226ff0cc061SDimitry Andric   switch (Type) {
1227ff0cc061SDimitry Andric   case NoDep:
1228ff0cc061SDimitry Andric   case Forward:
1229ff0cc061SDimitry Andric   case BackwardVectorizable:
1230*b5893f02SDimitry Andric     return VectorizationSafetyStatus::Safe;
1231ff0cc061SDimitry Andric 
1232ff0cc061SDimitry Andric   case Unknown:
1233*b5893f02SDimitry Andric     return VectorizationSafetyStatus::PossiblySafeWithRtChecks;
1234ff0cc061SDimitry Andric   case ForwardButPreventsForwarding:
1235ff0cc061SDimitry Andric   case Backward:
1236ff0cc061SDimitry Andric   case BackwardVectorizableButPreventsForwarding:
1237*b5893f02SDimitry Andric     return VectorizationSafetyStatus::Unsafe;
1238ff0cc061SDimitry Andric   }
1239ff0cc061SDimitry Andric   llvm_unreachable("unexpected DepType!");
1240ff0cc061SDimitry Andric }
1241ff0cc061SDimitry Andric 
isBackward() const12427d523365SDimitry Andric bool MemoryDepChecker::Dependence::isBackward() const {
1243ff0cc061SDimitry Andric   switch (Type) {
1244ff0cc061SDimitry Andric   case NoDep:
1245ff0cc061SDimitry Andric   case Forward:
12467d523365SDimitry Andric   case ForwardButPreventsForwarding:
12477d523365SDimitry Andric   case Unknown:
1248ff0cc061SDimitry Andric     return false;
1249ff0cc061SDimitry Andric 
1250ff0cc061SDimitry Andric   case BackwardVectorizable:
1251ff0cc061SDimitry Andric   case Backward:
1252ff0cc061SDimitry Andric   case BackwardVectorizableButPreventsForwarding:
1253ff0cc061SDimitry Andric     return true;
1254ff0cc061SDimitry Andric   }
1255ff0cc061SDimitry Andric   llvm_unreachable("unexpected DepType!");
1256ff0cc061SDimitry Andric }
1257ff0cc061SDimitry Andric 
isPossiblyBackward() const1258ff0cc061SDimitry Andric bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
12597d523365SDimitry Andric   return isBackward() || Type == Unknown;
12607d523365SDimitry Andric }
12617d523365SDimitry Andric 
isForward() const12627d523365SDimitry Andric bool MemoryDepChecker::Dependence::isForward() const {
1263ff0cc061SDimitry Andric   switch (Type) {
1264ff0cc061SDimitry Andric   case Forward:
1265ff0cc061SDimitry Andric   case ForwardButPreventsForwarding:
12667d523365SDimitry Andric     return true;
1267ff0cc061SDimitry Andric 
12687d523365SDimitry Andric   case NoDep:
1269ff0cc061SDimitry Andric   case Unknown:
1270ff0cc061SDimitry Andric   case BackwardVectorizable:
1271ff0cc061SDimitry Andric   case Backward:
1272ff0cc061SDimitry Andric   case BackwardVectorizableButPreventsForwarding:
12737d523365SDimitry Andric     return false;
1274ff0cc061SDimitry Andric   }
1275ff0cc061SDimitry Andric   llvm_unreachable("unexpected DepType!");
1276ff0cc061SDimitry Andric }
1277ff0cc061SDimitry Andric 
couldPreventStoreLoadForward(uint64_t Distance,uint64_t TypeByteSize)12783ca95b02SDimitry Andric bool MemoryDepChecker::couldPreventStoreLoadForward(uint64_t Distance,
12793ca95b02SDimitry Andric                                                     uint64_t TypeByteSize) {
1280ff0cc061SDimitry Andric   // If loads occur at a distance that is not a multiple of a feasible vector
1281ff0cc061SDimitry Andric   // factor store-load forwarding does not take place.
1282ff0cc061SDimitry Andric   // Positive dependences might cause troubles because vectorizing them might
1283ff0cc061SDimitry Andric   // prevent store-load forwarding making vectorized code run a lot slower.
1284ff0cc061SDimitry Andric   //   a[i] = a[i-3] ^ a[i-8];
1285ff0cc061SDimitry Andric   //   The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
1286ff0cc061SDimitry Andric   //   hence on your typical architecture store-load forwarding does not take
1287ff0cc061SDimitry Andric   //   place. Vectorizing in such cases does not make sense.
1288ff0cc061SDimitry Andric   // Store-load forwarding distance.
1289ff0cc061SDimitry Andric 
12903ca95b02SDimitry Andric   // After this many iterations store-to-load forwarding conflicts should not
12913ca95b02SDimitry Andric   // cause any slowdowns.
12923ca95b02SDimitry Andric   const uint64_t NumItersForStoreLoadThroughMemory = 8 * TypeByteSize;
12933ca95b02SDimitry Andric   // Maximum vector factor.
12943ca95b02SDimitry Andric   uint64_t MaxVFWithoutSLForwardIssues = std::min(
12953ca95b02SDimitry Andric       VectorizerParams::MaxVectorWidth * TypeByteSize, MaxSafeDepDistBytes);
12963ca95b02SDimitry Andric 
12973ca95b02SDimitry Andric   // Compute the smallest VF at which the store and load would be misaligned.
12983ca95b02SDimitry Andric   for (uint64_t VF = 2 * TypeByteSize; VF <= MaxVFWithoutSLForwardIssues;
12993ca95b02SDimitry Andric        VF *= 2) {
13003ca95b02SDimitry Andric     // If the number of vector iteration between the store and the load are
13013ca95b02SDimitry Andric     // small we could incur conflicts.
13023ca95b02SDimitry Andric     if (Distance % VF && Distance / VF < NumItersForStoreLoadThroughMemory) {
13033ca95b02SDimitry Andric       MaxVFWithoutSLForwardIssues = (VF >>= 1);
1304ff0cc061SDimitry Andric       break;
1305ff0cc061SDimitry Andric     }
1306ff0cc061SDimitry Andric   }
1307ff0cc061SDimitry Andric 
1308ff0cc061SDimitry Andric   if (MaxVFWithoutSLForwardIssues < 2 * TypeByteSize) {
13094ba319b5SDimitry Andric     LLVM_DEBUG(
13104ba319b5SDimitry Andric         dbgs() << "LAA: Distance " << Distance
13113ca95b02SDimitry Andric                << " that could cause a store-load forwarding conflict\n");
1312ff0cc061SDimitry Andric     return true;
1313ff0cc061SDimitry Andric   }
1314ff0cc061SDimitry Andric 
1315ff0cc061SDimitry Andric   if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
1316ff0cc061SDimitry Andric       MaxVFWithoutSLForwardIssues !=
1317ff0cc061SDimitry Andric           VectorizerParams::MaxVectorWidth * TypeByteSize)
1318ff0cc061SDimitry Andric     MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
1319ff0cc061SDimitry Andric   return false;
1320ff0cc061SDimitry Andric }
1321ff0cc061SDimitry Andric 
mergeInStatus(VectorizationSafetyStatus S)1322*b5893f02SDimitry Andric void MemoryDepChecker::mergeInStatus(VectorizationSafetyStatus S) {
1323*b5893f02SDimitry Andric   if (Status < S)
1324*b5893f02SDimitry Andric     Status = S;
1325*b5893f02SDimitry Andric }
1326*b5893f02SDimitry Andric 
13277a7e6055SDimitry Andric /// Given a non-constant (unknown) dependence-distance \p Dist between two
13287a7e6055SDimitry Andric /// memory accesses, that have the same stride whose absolute value is given
13297a7e6055SDimitry Andric /// in \p Stride, and that have the same type size \p TypeByteSize,
13307a7e6055SDimitry Andric /// in a loop whose takenCount is \p BackedgeTakenCount, check if it is
13317a7e6055SDimitry Andric /// possible to prove statically that the dependence distance is larger
13327a7e6055SDimitry Andric /// than the range that the accesses will travel through the execution of
13337a7e6055SDimitry Andric /// the loop. If so, return true; false otherwise. This is useful for
13347a7e6055SDimitry Andric /// example in loops such as the following (PR31098):
13357a7e6055SDimitry Andric ///     for (i = 0; i < D; ++i) {
13367a7e6055SDimitry Andric ///                = out[i];
13377a7e6055SDimitry Andric ///       out[i+D] =
13387a7e6055SDimitry Andric ///     }
isSafeDependenceDistance(const DataLayout & DL,ScalarEvolution & SE,const SCEV & BackedgeTakenCount,const SCEV & Dist,uint64_t Stride,uint64_t TypeByteSize)13397a7e6055SDimitry Andric static bool isSafeDependenceDistance(const DataLayout &DL, ScalarEvolution &SE,
13407a7e6055SDimitry Andric                                      const SCEV &BackedgeTakenCount,
13417a7e6055SDimitry Andric                                      const SCEV &Dist, uint64_t Stride,
13427a7e6055SDimitry Andric                                      uint64_t TypeByteSize) {
13437a7e6055SDimitry Andric 
13447a7e6055SDimitry Andric   // If we can prove that
13457a7e6055SDimitry Andric   //      (**) |Dist| > BackedgeTakenCount * Step
13467a7e6055SDimitry Andric   // where Step is the absolute stride of the memory accesses in bytes,
13477a7e6055SDimitry Andric   // then there is no dependence.
13487a7e6055SDimitry Andric   //
13497a7e6055SDimitry Andric   // Ratioanle:
13507a7e6055SDimitry Andric   // We basically want to check if the absolute distance (|Dist/Step|)
13517a7e6055SDimitry Andric   // is >= the loop iteration count (or > BackedgeTakenCount).
13527a7e6055SDimitry Andric   // This is equivalent to the Strong SIV Test (Practical Dependence Testing,
13537a7e6055SDimitry Andric   // Section 4.2.1); Note, that for vectorization it is sufficient to prove
13547a7e6055SDimitry Andric   // that the dependence distance is >= VF; This is checked elsewhere.
13557a7e6055SDimitry Andric   // But in some cases we can prune unknown dependence distances early, and
13567a7e6055SDimitry Andric   // even before selecting the VF, and without a runtime test, by comparing
13577a7e6055SDimitry Andric   // the distance against the loop iteration count. Since the vectorized code
13587a7e6055SDimitry Andric   // will be executed only if LoopCount >= VF, proving distance >= LoopCount
13597a7e6055SDimitry Andric   // also guarantees that distance >= VF.
13607a7e6055SDimitry Andric   //
13617a7e6055SDimitry Andric   const uint64_t ByteStride = Stride * TypeByteSize;
13627a7e6055SDimitry Andric   const SCEV *Step = SE.getConstant(BackedgeTakenCount.getType(), ByteStride);
13637a7e6055SDimitry Andric   const SCEV *Product = SE.getMulExpr(&BackedgeTakenCount, Step);
13647a7e6055SDimitry Andric 
13657a7e6055SDimitry Andric   const SCEV *CastedDist = &Dist;
13667a7e6055SDimitry Andric   const SCEV *CastedProduct = Product;
13677a7e6055SDimitry Andric   uint64_t DistTypeSize = DL.getTypeAllocSize(Dist.getType());
13687a7e6055SDimitry Andric   uint64_t ProductTypeSize = DL.getTypeAllocSize(Product->getType());
13697a7e6055SDimitry Andric 
13707a7e6055SDimitry Andric   // The dependence distance can be positive/negative, so we sign extend Dist;
13717a7e6055SDimitry Andric   // The multiplication of the absolute stride in bytes and the
13727a7e6055SDimitry Andric   // backdgeTakenCount is non-negative, so we zero extend Product.
13737a7e6055SDimitry Andric   if (DistTypeSize > ProductTypeSize)
13747a7e6055SDimitry Andric     CastedProduct = SE.getZeroExtendExpr(Product, Dist.getType());
13757a7e6055SDimitry Andric   else
13767a7e6055SDimitry Andric     CastedDist = SE.getNoopOrSignExtend(&Dist, Product->getType());
13777a7e6055SDimitry Andric 
13787a7e6055SDimitry Andric   // Is  Dist - (BackedgeTakenCount * Step) > 0 ?
13797a7e6055SDimitry Andric   // (If so, then we have proven (**) because |Dist| >= Dist)
13807a7e6055SDimitry Andric   const SCEV *Minus = SE.getMinusSCEV(CastedDist, CastedProduct);
13817a7e6055SDimitry Andric   if (SE.isKnownPositive(Minus))
13827a7e6055SDimitry Andric     return true;
13837a7e6055SDimitry Andric 
13847a7e6055SDimitry Andric   // Second try: Is  -Dist - (BackedgeTakenCount * Step) > 0 ?
13857a7e6055SDimitry Andric   // (If so, then we have proven (**) because |Dist| >= -1*Dist)
13867a7e6055SDimitry Andric   const SCEV *NegDist = SE.getNegativeSCEV(CastedDist);
13877a7e6055SDimitry Andric   Minus = SE.getMinusSCEV(NegDist, CastedProduct);
13887a7e6055SDimitry Andric   if (SE.isKnownPositive(Minus))
13897a7e6055SDimitry Andric     return true;
13907a7e6055SDimitry Andric 
13917a7e6055SDimitry Andric   return false;
13927a7e6055SDimitry Andric }
13937a7e6055SDimitry Andric 
13944ba319b5SDimitry Andric /// Check the dependence for two accesses with the same stride \p Stride.
139597bc6c73SDimitry Andric /// \p Distance is the positive distance and \p TypeByteSize is type size in
139697bc6c73SDimitry Andric /// bytes.
139797bc6c73SDimitry Andric ///
139897bc6c73SDimitry Andric /// \returns true if they are independent.
areStridedAccessesIndependent(uint64_t Distance,uint64_t Stride,uint64_t TypeByteSize)13993ca95b02SDimitry Andric static bool areStridedAccessesIndependent(uint64_t Distance, uint64_t Stride,
14003ca95b02SDimitry Andric                                           uint64_t TypeByteSize) {
140197bc6c73SDimitry Andric   assert(Stride > 1 && "The stride must be greater than 1");
140297bc6c73SDimitry Andric   assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
140397bc6c73SDimitry Andric   assert(Distance > 0 && "The distance must be non-zero");
140497bc6c73SDimitry Andric 
140597bc6c73SDimitry Andric   // Skip if the distance is not multiple of type byte size.
140697bc6c73SDimitry Andric   if (Distance % TypeByteSize)
140797bc6c73SDimitry Andric     return false;
140897bc6c73SDimitry Andric 
14093ca95b02SDimitry Andric   uint64_t ScaledDist = Distance / TypeByteSize;
141097bc6c73SDimitry Andric 
141197bc6c73SDimitry Andric   // No dependence if the scaled distance is not multiple of the stride.
141297bc6c73SDimitry Andric   // E.g.
141397bc6c73SDimitry Andric   //      for (i = 0; i < 1024 ; i += 4)
141497bc6c73SDimitry Andric   //        A[i+2] = A[i] + 1;
141597bc6c73SDimitry Andric   //
141697bc6c73SDimitry Andric   // Two accesses in memory (scaled distance is 2, stride is 4):
141797bc6c73SDimitry Andric   //     | A[0] |      |      |      | A[4] |      |      |      |
141897bc6c73SDimitry Andric   //     |      |      | A[2] |      |      |      | A[6] |      |
141997bc6c73SDimitry Andric   //
142097bc6c73SDimitry Andric   // E.g.
142197bc6c73SDimitry Andric   //      for (i = 0; i < 1024 ; i += 3)
142297bc6c73SDimitry Andric   //        A[i+4] = A[i] + 1;
142397bc6c73SDimitry Andric   //
142497bc6c73SDimitry Andric   // Two accesses in memory (scaled distance is 4, stride is 3):
142597bc6c73SDimitry Andric   //     | A[0] |      |      | A[3] |      |      | A[6] |      |      |
142697bc6c73SDimitry Andric   //     |      |      |      |      | A[4] |      |      | A[7] |      |
142797bc6c73SDimitry Andric   return ScaledDist % Stride;
142897bc6c73SDimitry Andric }
142997bc6c73SDimitry Andric 
1430ff0cc061SDimitry Andric MemoryDepChecker::Dependence::DepType
isDependent(const MemAccessInfo & A,unsigned AIdx,const MemAccessInfo & B,unsigned BIdx,const ValueToValueMap & Strides)1431ff0cc061SDimitry Andric MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
1432ff0cc061SDimitry Andric                               const MemAccessInfo &B, unsigned BIdx,
1433ff0cc061SDimitry Andric                               const ValueToValueMap &Strides) {
1434ff0cc061SDimitry Andric   assert (AIdx < BIdx && "Must pass arguments in program order");
1435ff0cc061SDimitry Andric 
1436ff0cc061SDimitry Andric   Value *APtr = A.getPointer();
1437ff0cc061SDimitry Andric   Value *BPtr = B.getPointer();
1438ff0cc061SDimitry Andric   bool AIsWrite = A.getInt();
1439ff0cc061SDimitry Andric   bool BIsWrite = B.getInt();
1440ff0cc061SDimitry Andric 
1441ff0cc061SDimitry Andric   // Two reads are independent.
1442ff0cc061SDimitry Andric   if (!AIsWrite && !BIsWrite)
1443ff0cc061SDimitry Andric     return Dependence::NoDep;
1444ff0cc061SDimitry Andric 
1445ff0cc061SDimitry Andric   // We cannot check pointers in different address spaces.
1446ff0cc061SDimitry Andric   if (APtr->getType()->getPointerAddressSpace() !=
1447ff0cc061SDimitry Andric       BPtr->getType()->getPointerAddressSpace())
1448ff0cc061SDimitry Andric     return Dependence::Unknown;
1449ff0cc061SDimitry Andric 
14503ca95b02SDimitry Andric   int64_t StrideAPtr = getPtrStride(PSE, APtr, InnermostLoop, Strides, true);
14513ca95b02SDimitry Andric   int64_t StrideBPtr = getPtrStride(PSE, BPtr, InnermostLoop, Strides, true);
1452ff0cc061SDimitry Andric 
14533ca95b02SDimitry Andric   const SCEV *Src = PSE.getSCEV(APtr);
14543ca95b02SDimitry Andric   const SCEV *Sink = PSE.getSCEV(BPtr);
1455ff0cc061SDimitry Andric 
1456ff0cc061SDimitry Andric   // If the induction step is negative we have to invert source and sink of the
1457ff0cc061SDimitry Andric   // dependence.
1458ff0cc061SDimitry Andric   if (StrideAPtr < 0) {
1459ff0cc061SDimitry Andric     std::swap(APtr, BPtr);
1460ff0cc061SDimitry Andric     std::swap(Src, Sink);
1461ff0cc061SDimitry Andric     std::swap(AIsWrite, BIsWrite);
1462ff0cc061SDimitry Andric     std::swap(AIdx, BIdx);
1463ff0cc061SDimitry Andric     std::swap(StrideAPtr, StrideBPtr);
1464ff0cc061SDimitry Andric   }
1465ff0cc061SDimitry Andric 
14667d523365SDimitry Andric   const SCEV *Dist = PSE.getSE()->getMinusSCEV(Sink, Src);
1467ff0cc061SDimitry Andric 
14684ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
1469ff0cc061SDimitry Andric                     << "(Induction step: " << StrideAPtr << ")\n");
14704ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
1471ff0cc061SDimitry Andric                     << *InstMap[BIdx] << ": " << *Dist << "\n");
1472ff0cc061SDimitry Andric 
1473875ed548SDimitry Andric   // Need accesses with constant stride. We don't want to vectorize
1474ff0cc061SDimitry Andric   // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
1475ff0cc061SDimitry Andric   // the address space.
1476ff0cc061SDimitry Andric   if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
14774ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Pointer access with non-constant stride\n");
1478ff0cc061SDimitry Andric     return Dependence::Unknown;
1479ff0cc061SDimitry Andric   }
1480ff0cc061SDimitry Andric 
14817a7e6055SDimitry Andric   Type *ATy = APtr->getType()->getPointerElementType();
14827a7e6055SDimitry Andric   Type *BTy = BPtr->getType()->getPointerElementType();
14837a7e6055SDimitry Andric   auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
14847a7e6055SDimitry Andric   uint64_t TypeByteSize = DL.getTypeAllocSize(ATy);
14857a7e6055SDimitry Andric   uint64_t Stride = std::abs(StrideAPtr);
1486ff0cc061SDimitry Andric   const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
1487ff0cc061SDimitry Andric   if (!C) {
14887a7e6055SDimitry Andric     if (TypeByteSize == DL.getTypeAllocSize(BTy) &&
14897a7e6055SDimitry Andric         isSafeDependenceDistance(DL, *(PSE.getSE()),
14907a7e6055SDimitry Andric                                  *(PSE.getBackedgeTakenCount()), *Dist, Stride,
14917a7e6055SDimitry Andric                                  TypeByteSize))
14927a7e6055SDimitry Andric       return Dependence::NoDep;
14937a7e6055SDimitry Andric 
14944ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
1495*b5893f02SDimitry Andric     FoundNonConstantDistanceDependence = true;
1496ff0cc061SDimitry Andric     return Dependence::Unknown;
1497ff0cc061SDimitry Andric   }
1498ff0cc061SDimitry Andric 
14993ca95b02SDimitry Andric   const APInt &Val = C->getAPInt();
15003ca95b02SDimitry Andric   int64_t Distance = Val.getSExtValue();
15013ca95b02SDimitry Andric 
15023ca95b02SDimitry Andric   // Attempt to prove strided accesses independent.
15033ca95b02SDimitry Andric   if (std::abs(Distance) > 0 && Stride > 1 && ATy == BTy &&
15043ca95b02SDimitry Andric       areStridedAccessesIndependent(std::abs(Distance), Stride, TypeByteSize)) {
15054ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
15063ca95b02SDimitry Andric     return Dependence::NoDep;
15073ca95b02SDimitry Andric   }
1508ff0cc061SDimitry Andric 
1509ff0cc061SDimitry Andric   // Negative distances are not plausible dependencies.
1510ff0cc061SDimitry Andric   if (Val.isNegative()) {
1511ff0cc061SDimitry Andric     bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
15123ca95b02SDimitry Andric     if (IsTrueDataDependence && EnableForwardingConflictDetection &&
1513ff0cc061SDimitry Andric         (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
15143ca95b02SDimitry Andric          ATy != BTy)) {
15154ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "LAA: Forward but may prevent st->ld forwarding\n");
1516ff0cc061SDimitry Andric       return Dependence::ForwardButPreventsForwarding;
15173ca95b02SDimitry Andric     }
1518ff0cc061SDimitry Andric 
15194ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Dependence is negative\n");
1520ff0cc061SDimitry Andric     return Dependence::Forward;
1521ff0cc061SDimitry Andric   }
1522ff0cc061SDimitry Andric 
1523ff0cc061SDimitry Andric   // Write to the same location with the same size.
1524ff0cc061SDimitry Andric   // Could be improved to assert type sizes are the same (i32 == float, etc).
1525ff0cc061SDimitry Andric   if (Val == 0) {
1526ff0cc061SDimitry Andric     if (ATy == BTy)
15277d523365SDimitry Andric       return Dependence::Forward;
15284ba319b5SDimitry Andric     LLVM_DEBUG(
15294ba319b5SDimitry Andric         dbgs() << "LAA: Zero dependence difference but different types\n");
1530ff0cc061SDimitry Andric     return Dependence::Unknown;
1531ff0cc061SDimitry Andric   }
1532ff0cc061SDimitry Andric 
1533ff0cc061SDimitry Andric   assert(Val.isStrictlyPositive() && "Expect a positive value");
1534ff0cc061SDimitry Andric 
1535ff0cc061SDimitry Andric   if (ATy != BTy) {
15364ba319b5SDimitry Andric     LLVM_DEBUG(
15374ba319b5SDimitry Andric         dbgs()
15384ba319b5SDimitry Andric         << "LAA: ReadWrite-Write positive dependency with different types\n");
1539ff0cc061SDimitry Andric     return Dependence::Unknown;
1540ff0cc061SDimitry Andric   }
1541ff0cc061SDimitry Andric 
1542ff0cc061SDimitry Andric   // Bail out early if passed-in parameters make vectorization not feasible.
1543ff0cc061SDimitry Andric   unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
1544ff0cc061SDimitry Andric                            VectorizerParams::VectorizationFactor : 1);
1545ff0cc061SDimitry Andric   unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
1546ff0cc061SDimitry Andric                            VectorizerParams::VectorizationInterleave : 1);
154797bc6c73SDimitry Andric   // The minimum number of iterations for a vectorized/unrolled version.
154897bc6c73SDimitry Andric   unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
1549ff0cc061SDimitry Andric 
155097bc6c73SDimitry Andric   // It's not vectorizable if the distance is smaller than the minimum distance
155197bc6c73SDimitry Andric   // needed for a vectroized/unrolled version. Vectorizing one iteration in
155297bc6c73SDimitry Andric   // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
155397bc6c73SDimitry Andric   // TypeByteSize (No need to plus the last gap distance).
155497bc6c73SDimitry Andric   //
155597bc6c73SDimitry Andric   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
155697bc6c73SDimitry Andric   //      foo(int *A) {
155797bc6c73SDimitry Andric   //        int *B = (int *)((char *)A + 14);
155897bc6c73SDimitry Andric   //        for (i = 0 ; i < 1024 ; i += 2)
155997bc6c73SDimitry Andric   //          B[i] = A[i] + 1;
156097bc6c73SDimitry Andric   //      }
156197bc6c73SDimitry Andric   //
156297bc6c73SDimitry Andric   // Two accesses in memory (stride is 2):
156397bc6c73SDimitry Andric   //     | A[0] |      | A[2] |      | A[4] |      | A[6] |      |
156497bc6c73SDimitry Andric   //                              | B[0] |      | B[2] |      | B[4] |
156597bc6c73SDimitry Andric   //
156697bc6c73SDimitry Andric   // Distance needs for vectorizing iterations except the last iteration:
156797bc6c73SDimitry Andric   // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
156897bc6c73SDimitry Andric   // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
156997bc6c73SDimitry Andric   //
157097bc6c73SDimitry Andric   // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
157197bc6c73SDimitry Andric   // 12, which is less than distance.
157297bc6c73SDimitry Andric   //
157397bc6c73SDimitry Andric   // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
157497bc6c73SDimitry Andric   // the minimum distance needed is 28, which is greater than distance. It is
157597bc6c73SDimitry Andric   // not safe to do vectorization.
15763ca95b02SDimitry Andric   uint64_t MinDistanceNeeded =
157797bc6c73SDimitry Andric       TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
15783ca95b02SDimitry Andric   if (MinDistanceNeeded > static_cast<uint64_t>(Distance)) {
15794ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Failure because of positive distance "
15804ba319b5SDimitry Andric                       << Distance << '\n');
158197bc6c73SDimitry Andric     return Dependence::Backward;
158297bc6c73SDimitry Andric   }
158397bc6c73SDimitry Andric 
158497bc6c73SDimitry Andric   // Unsafe if the minimum distance needed is greater than max safe distance.
158597bc6c73SDimitry Andric   if (MinDistanceNeeded > MaxSafeDepDistBytes) {
15864ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Failure because it needs at least "
158797bc6c73SDimitry Andric                       << MinDistanceNeeded << " size in bytes");
1588ff0cc061SDimitry Andric     return Dependence::Backward;
1589ff0cc061SDimitry Andric   }
1590ff0cc061SDimitry Andric 
1591ff0cc061SDimitry Andric   // Positive distance bigger than max vectorization factor.
159297bc6c73SDimitry Andric   // FIXME: Should use max factor instead of max distance in bytes, which could
159397bc6c73SDimitry Andric   // not handle different types.
159497bc6c73SDimitry Andric   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
159597bc6c73SDimitry Andric   //      void foo (int *A, char *B) {
159697bc6c73SDimitry Andric   //        for (unsigned i = 0; i < 1024; i++) {
159797bc6c73SDimitry Andric   //          A[i+2] = A[i] + 1;
159897bc6c73SDimitry Andric   //          B[i+2] = B[i] + 1;
159997bc6c73SDimitry Andric   //        }
160097bc6c73SDimitry Andric   //      }
160197bc6c73SDimitry Andric   //
160297bc6c73SDimitry Andric   // This case is currently unsafe according to the max safe distance. If we
160397bc6c73SDimitry Andric   // analyze the two accesses on array B, the max safe dependence distance
160497bc6c73SDimitry Andric   // is 2. Then we analyze the accesses on array A, the minimum distance needed
160597bc6c73SDimitry Andric   // is 8, which is less than 2 and forbidden vectorization, But actually
160697bc6c73SDimitry Andric   // both A and B could be vectorized by 2 iterations.
160797bc6c73SDimitry Andric   MaxSafeDepDistBytes =
16083ca95b02SDimitry Andric       std::min(static_cast<uint64_t>(Distance), MaxSafeDepDistBytes);
1609ff0cc061SDimitry Andric 
1610ff0cc061SDimitry Andric   bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
16113ca95b02SDimitry Andric   if (IsTrueDataDependence && EnableForwardingConflictDetection &&
1612ff0cc061SDimitry Andric       couldPreventStoreLoadForward(Distance, TypeByteSize))
1613ff0cc061SDimitry Andric     return Dependence::BackwardVectorizableButPreventsForwarding;
1614ff0cc061SDimitry Andric 
16152cab237bSDimitry Andric   uint64_t MaxVF = MaxSafeDepDistBytes / (TypeByteSize * Stride);
16164ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
16172cab237bSDimitry Andric                     << " with max VF = " << MaxVF << '\n');
16182cab237bSDimitry Andric   uint64_t MaxVFInBits = MaxVF * TypeByteSize * 8;
16192cab237bSDimitry Andric   MaxSafeRegisterWidth = std::min(MaxSafeRegisterWidth, MaxVFInBits);
1620ff0cc061SDimitry Andric   return Dependence::BackwardVectorizable;
1621ff0cc061SDimitry Andric }
1622ff0cc061SDimitry Andric 
areDepsSafe(DepCandidates & AccessSets,MemAccessInfoList & CheckDeps,const ValueToValueMap & Strides)1623ff0cc061SDimitry Andric bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
16247a7e6055SDimitry Andric                                    MemAccessInfoList &CheckDeps,
1625ff0cc061SDimitry Andric                                    const ValueToValueMap &Strides) {
1626ff0cc061SDimitry Andric 
16273ca95b02SDimitry Andric   MaxSafeDepDistBytes = -1;
16287a7e6055SDimitry Andric   SmallPtrSet<MemAccessInfo, 8> Visited;
16297a7e6055SDimitry Andric   for (MemAccessInfo CurAccess : CheckDeps) {
16307a7e6055SDimitry Andric     if (Visited.count(CurAccess))
16317a7e6055SDimitry Andric       continue;
1632ff0cc061SDimitry Andric 
1633ff0cc061SDimitry Andric     // Get the relevant memory access set.
1634ff0cc061SDimitry Andric     EquivalenceClasses<MemAccessInfo>::iterator I =
1635ff0cc061SDimitry Andric       AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
1636ff0cc061SDimitry Andric 
1637ff0cc061SDimitry Andric     // Check accesses within this set.
16383ca95b02SDimitry Andric     EquivalenceClasses<MemAccessInfo>::member_iterator AI =
16393ca95b02SDimitry Andric         AccessSets.member_begin(I);
16403ca95b02SDimitry Andric     EquivalenceClasses<MemAccessInfo>::member_iterator AE =
16413ca95b02SDimitry Andric         AccessSets.member_end();
1642ff0cc061SDimitry Andric 
1643ff0cc061SDimitry Andric     // Check every access pair.
1644ff0cc061SDimitry Andric     while (AI != AE) {
16457a7e6055SDimitry Andric       Visited.insert(*AI);
1646ff0cc061SDimitry Andric       EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
1647ff0cc061SDimitry Andric       while (OI != AE) {
1648ff0cc061SDimitry Andric         // Check every accessing instruction pair in program order.
1649ff0cc061SDimitry Andric         for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
1650ff0cc061SDimitry Andric              I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
1651ff0cc061SDimitry Andric           for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
1652ff0cc061SDimitry Andric                I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
1653ff0cc061SDimitry Andric             auto A = std::make_pair(&*AI, *I1);
1654ff0cc061SDimitry Andric             auto B = std::make_pair(&*OI, *I2);
1655ff0cc061SDimitry Andric 
1656ff0cc061SDimitry Andric             assert(*I1 != *I2);
1657ff0cc061SDimitry Andric             if (*I1 > *I2)
1658ff0cc061SDimitry Andric               std::swap(A, B);
1659ff0cc061SDimitry Andric 
1660ff0cc061SDimitry Andric             Dependence::DepType Type =
1661ff0cc061SDimitry Andric                 isDependent(*A.first, A.second, *B.first, B.second, Strides);
1662*b5893f02SDimitry Andric             mergeInStatus(Dependence::isSafeForVectorization(Type));
1663ff0cc061SDimitry Andric 
16647d523365SDimitry Andric             // Gather dependences unless we accumulated MaxDependences
1665ff0cc061SDimitry Andric             // dependences.  In that case return as soon as we find the first
1666ff0cc061SDimitry Andric             // unsafe dependence.  This puts a limit on this quadratic
1667ff0cc061SDimitry Andric             // algorithm.
16687d523365SDimitry Andric             if (RecordDependences) {
16697d523365SDimitry Andric               if (Type != Dependence::NoDep)
16707d523365SDimitry Andric                 Dependences.push_back(Dependence(A.second, B.second, Type));
1671ff0cc061SDimitry Andric 
16727d523365SDimitry Andric               if (Dependences.size() >= MaxDependences) {
16737d523365SDimitry Andric                 RecordDependences = false;
16747d523365SDimitry Andric                 Dependences.clear();
16754ba319b5SDimitry Andric                 LLVM_DEBUG(dbgs()
16764ba319b5SDimitry Andric                            << "Too many dependences, stopped recording\n");
1677ff0cc061SDimitry Andric               }
1678ff0cc061SDimitry Andric             }
1679*b5893f02SDimitry Andric             if (!RecordDependences && !isSafeForVectorization())
1680ff0cc061SDimitry Andric               return false;
1681ff0cc061SDimitry Andric           }
1682ff0cc061SDimitry Andric         ++OI;
1683ff0cc061SDimitry Andric       }
1684ff0cc061SDimitry Andric       AI++;
1685ff0cc061SDimitry Andric     }
1686ff0cc061SDimitry Andric   }
1687ff0cc061SDimitry Andric 
16884ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Total Dependences: " << Dependences.size() << "\n");
1689*b5893f02SDimitry Andric   return isSafeForVectorization();
1690ff0cc061SDimitry Andric }
1691ff0cc061SDimitry Andric 
1692ff0cc061SDimitry Andric SmallVector<Instruction *, 4>
getInstructionsForAccess(Value * Ptr,bool isWrite) const1693ff0cc061SDimitry Andric MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
1694ff0cc061SDimitry Andric   MemAccessInfo Access(Ptr, isWrite);
1695ff0cc061SDimitry Andric   auto &IndexVector = Accesses.find(Access)->second;
1696ff0cc061SDimitry Andric 
1697ff0cc061SDimitry Andric   SmallVector<Instruction *, 4> Insts;
1698d88c1a5aSDimitry Andric   transform(IndexVector,
1699ff0cc061SDimitry Andric                  std::back_inserter(Insts),
1700ff0cc061SDimitry Andric                  [&](unsigned Idx) { return this->InstMap[Idx]; });
1701ff0cc061SDimitry Andric   return Insts;
1702ff0cc061SDimitry Andric }
1703ff0cc061SDimitry Andric 
1704ff0cc061SDimitry Andric const char *MemoryDepChecker::Dependence::DepName[] = {
1705ff0cc061SDimitry Andric     "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
1706ff0cc061SDimitry Andric     "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
1707ff0cc061SDimitry Andric 
print(raw_ostream & OS,unsigned Depth,const SmallVectorImpl<Instruction * > & Instrs) const1708ff0cc061SDimitry Andric void MemoryDepChecker::Dependence::print(
1709ff0cc061SDimitry Andric     raw_ostream &OS, unsigned Depth,
1710ff0cc061SDimitry Andric     const SmallVectorImpl<Instruction *> &Instrs) const {
1711ff0cc061SDimitry Andric   OS.indent(Depth) << DepName[Type] << ":\n";
1712ff0cc061SDimitry Andric   OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
1713ff0cc061SDimitry Andric   OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
1714ff0cc061SDimitry Andric }
1715ff0cc061SDimitry Andric 
canAnalyzeLoop()1716ff0cc061SDimitry Andric bool LoopAccessInfo::canAnalyzeLoop() {
1717ff0cc061SDimitry Andric   // We need to have a loop header.
17184ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Found a loop in "
17193ca95b02SDimitry Andric                     << TheLoop->getHeader()->getParent()->getName() << ": "
17203ca95b02SDimitry Andric                     << TheLoop->getHeader()->getName() << '\n');
1721ff0cc061SDimitry Andric 
1722ff0cc061SDimitry Andric   // We can only analyze innermost loops.
1723ff0cc061SDimitry Andric   if (!TheLoop->empty()) {
17244ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
1725d88c1a5aSDimitry Andric     recordAnalysis("NotInnerMostLoop") << "loop is not the innermost loop";
1726ff0cc061SDimitry Andric     return false;
1727ff0cc061SDimitry Andric   }
1728ff0cc061SDimitry Andric 
1729ff0cc061SDimitry Andric   // We must have a single backedge.
1730ff0cc061SDimitry Andric   if (TheLoop->getNumBackEdges() != 1) {
17314ba319b5SDimitry Andric     LLVM_DEBUG(
17324ba319b5SDimitry Andric         dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1733d88c1a5aSDimitry Andric     recordAnalysis("CFGNotUnderstood")
1734d88c1a5aSDimitry Andric         << "loop control flow is not understood by analyzer";
1735ff0cc061SDimitry Andric     return false;
1736ff0cc061SDimitry Andric   }
1737ff0cc061SDimitry Andric 
1738ff0cc061SDimitry Andric   // We must have a single exiting block.
1739ff0cc061SDimitry Andric   if (!TheLoop->getExitingBlock()) {
17404ba319b5SDimitry Andric     LLVM_DEBUG(
17414ba319b5SDimitry Andric         dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1742d88c1a5aSDimitry Andric     recordAnalysis("CFGNotUnderstood")
1743d88c1a5aSDimitry Andric         << "loop control flow is not understood by analyzer";
1744ff0cc061SDimitry Andric     return false;
1745ff0cc061SDimitry Andric   }
1746ff0cc061SDimitry Andric 
1747ff0cc061SDimitry Andric   // We only handle bottom-tested loops, i.e. loop in which the condition is
1748ff0cc061SDimitry Andric   // checked at the end of each iteration. With that we can assume that all
1749ff0cc061SDimitry Andric   // instructions in the loop are executed the same number of times.
1750ff0cc061SDimitry Andric   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
17514ba319b5SDimitry Andric     LLVM_DEBUG(
17524ba319b5SDimitry Andric         dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1753d88c1a5aSDimitry Andric     recordAnalysis("CFGNotUnderstood")
1754d88c1a5aSDimitry Andric         << "loop control flow is not understood by analyzer";
1755ff0cc061SDimitry Andric     return false;
1756ff0cc061SDimitry Andric   }
1757ff0cc061SDimitry Andric 
1758ff0cc061SDimitry Andric   // ScalarEvolution needs to be able to find the exit count.
17593ca95b02SDimitry Andric   const SCEV *ExitCount = PSE->getBackedgeTakenCount();
17603ca95b02SDimitry Andric   if (ExitCount == PSE->getSE()->getCouldNotCompute()) {
1761d88c1a5aSDimitry Andric     recordAnalysis("CantComputeNumberOfIterations")
1762d88c1a5aSDimitry Andric         << "could not determine number of loop iterations";
17634ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
1764ff0cc061SDimitry Andric     return false;
1765ff0cc061SDimitry Andric   }
1766ff0cc061SDimitry Andric 
1767ff0cc061SDimitry Andric   return true;
1768ff0cc061SDimitry Andric }
1769ff0cc061SDimitry Andric 
analyzeLoop(AliasAnalysis * AA,LoopInfo * LI,const TargetLibraryInfo * TLI,DominatorTree * DT)17703ca95b02SDimitry Andric void LoopAccessInfo::analyzeLoop(AliasAnalysis *AA, LoopInfo *LI,
17713ca95b02SDimitry Andric                                  const TargetLibraryInfo *TLI,
17723ca95b02SDimitry Andric                                  DominatorTree *DT) {
1773ff0cc061SDimitry Andric   typedef SmallPtrSet<Value*, 16> ValueSet;
1774ff0cc061SDimitry Andric 
17753ca95b02SDimitry Andric   // Holds the Load and Store instructions.
17763ca95b02SDimitry Andric   SmallVector<LoadInst *, 16> Loads;
17773ca95b02SDimitry Andric   SmallVector<StoreInst *, 16> Stores;
1778ff0cc061SDimitry Andric 
1779ff0cc061SDimitry Andric   // Holds all the different accesses in the loop.
1780ff0cc061SDimitry Andric   unsigned NumReads = 0;
1781ff0cc061SDimitry Andric   unsigned NumReadWrites = 0;
1782ff0cc061SDimitry Andric 
17833ca95b02SDimitry Andric   PtrRtChecking->Pointers.clear();
17843ca95b02SDimitry Andric   PtrRtChecking->Need = false;
1785ff0cc061SDimitry Andric 
1786ff0cc061SDimitry Andric   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
1787ff0cc061SDimitry Andric 
1788ff0cc061SDimitry Andric   // For each block.
17893ca95b02SDimitry Andric   for (BasicBlock *BB : TheLoop->blocks()) {
1790ff0cc061SDimitry Andric     // Scan the BB and collect legal loads and stores.
17913ca95b02SDimitry Andric     for (Instruction &I : *BB) {
1792ff0cc061SDimitry Andric       // If this is a load, save it. If this instruction can read from memory
1793ff0cc061SDimitry Andric       // but is not a load, then we quit. Notice that we don't handle function
1794ff0cc061SDimitry Andric       // calls that read or write.
17953ca95b02SDimitry Andric       if (I.mayReadFromMemory()) {
1796ff0cc061SDimitry Andric         // Many math library functions read the rounding mode. We will only
1797ff0cc061SDimitry Andric         // vectorize a loop if it contains known function calls that don't set
1798ff0cc061SDimitry Andric         // the flag. Therefore, it is safe to ignore this read from memory.
17993ca95b02SDimitry Andric         auto *Call = dyn_cast<CallInst>(&I);
18003ca95b02SDimitry Andric         if (Call && getVectorIntrinsicIDForCall(Call, TLI))
1801ff0cc061SDimitry Andric           continue;
1802ff0cc061SDimitry Andric 
1803ff0cc061SDimitry Andric         // If the function has an explicit vectorized counterpart, we can safely
1804ff0cc061SDimitry Andric         // assume that it can be vectorized.
1805ff0cc061SDimitry Andric         if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
1806ff0cc061SDimitry Andric             TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
1807ff0cc061SDimitry Andric           continue;
1808ff0cc061SDimitry Andric 
18093ca95b02SDimitry Andric         auto *Ld = dyn_cast<LoadInst>(&I);
1810ff0cc061SDimitry Andric         if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
1811d88c1a5aSDimitry Andric           recordAnalysis("NonSimpleLoad", Ld)
1812d88c1a5aSDimitry Andric               << "read with atomic ordering or volatile read";
18134ba319b5SDimitry Andric           LLVM_DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
1814ff0cc061SDimitry Andric           CanVecMem = false;
1815ff0cc061SDimitry Andric           return;
1816ff0cc061SDimitry Andric         }
1817ff0cc061SDimitry Andric         NumLoads++;
1818ff0cc061SDimitry Andric         Loads.push_back(Ld);
18193ca95b02SDimitry Andric         DepChecker->addAccess(Ld);
18203ca95b02SDimitry Andric         if (EnableMemAccessVersioning)
18213ca95b02SDimitry Andric           collectStridedAccess(Ld);
1822ff0cc061SDimitry Andric         continue;
1823ff0cc061SDimitry Andric       }
1824ff0cc061SDimitry Andric 
1825ff0cc061SDimitry Andric       // Save 'store' instructions. Abort if other instructions write to memory.
18263ca95b02SDimitry Andric       if (I.mayWriteToMemory()) {
18273ca95b02SDimitry Andric         auto *St = dyn_cast<StoreInst>(&I);
1828ff0cc061SDimitry Andric         if (!St) {
1829d88c1a5aSDimitry Andric           recordAnalysis("CantVectorizeInstruction", St)
1830d88c1a5aSDimitry Andric               << "instruction cannot be vectorized";
1831ff0cc061SDimitry Andric           CanVecMem = false;
1832ff0cc061SDimitry Andric           return;
1833ff0cc061SDimitry Andric         }
1834ff0cc061SDimitry Andric         if (!St->isSimple() && !IsAnnotatedParallel) {
1835d88c1a5aSDimitry Andric           recordAnalysis("NonSimpleStore", St)
1836d88c1a5aSDimitry Andric               << "write with atomic ordering or volatile write";
18374ba319b5SDimitry Andric           LLVM_DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
1838ff0cc061SDimitry Andric           CanVecMem = false;
1839ff0cc061SDimitry Andric           return;
1840ff0cc061SDimitry Andric         }
1841ff0cc061SDimitry Andric         NumStores++;
1842ff0cc061SDimitry Andric         Stores.push_back(St);
18433ca95b02SDimitry Andric         DepChecker->addAccess(St);
18443ca95b02SDimitry Andric         if (EnableMemAccessVersioning)
18453ca95b02SDimitry Andric           collectStridedAccess(St);
1846ff0cc061SDimitry Andric       }
1847ff0cc061SDimitry Andric     } // Next instr.
1848ff0cc061SDimitry Andric   } // Next block.
1849ff0cc061SDimitry Andric 
1850ff0cc061SDimitry Andric   // Now we have two lists that hold the loads and the stores.
1851ff0cc061SDimitry Andric   // Next, we find the pointers that they use.
1852ff0cc061SDimitry Andric 
1853ff0cc061SDimitry Andric   // Check if we see any stores. If there are no stores, then we don't
1854ff0cc061SDimitry Andric   // care if the pointers are *restrict*.
1855ff0cc061SDimitry Andric   if (!Stores.size()) {
18564ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
1857ff0cc061SDimitry Andric     CanVecMem = true;
1858ff0cc061SDimitry Andric     return;
1859ff0cc061SDimitry Andric   }
1860ff0cc061SDimitry Andric 
1861ff0cc061SDimitry Andric   MemoryDepChecker::DepCandidates DependentAccesses;
1862ff0cc061SDimitry Andric   AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
18634ba319b5SDimitry Andric                           TheLoop, AA, LI, DependentAccesses, *PSE);
1864ff0cc061SDimitry Andric 
1865ff0cc061SDimitry Andric   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1866ff0cc061SDimitry Andric   // multiple times on the same object. If the ptr is accessed twice, once
1867ff0cc061SDimitry Andric   // for read and once for write, it will only appear once (on the write
1868ff0cc061SDimitry Andric   // list). This is okay, since we are going to check for conflicts between
1869ff0cc061SDimitry Andric   // writes and between reads and writes, but not between reads and reads.
1870ff0cc061SDimitry Andric   ValueSet Seen;
1871ff0cc061SDimitry Andric 
1872*b5893f02SDimitry Andric   // Record uniform store addresses to identify if we have multiple stores
1873*b5893f02SDimitry Andric   // to the same address.
1874*b5893f02SDimitry Andric   ValueSet UniformStores;
1875*b5893f02SDimitry Andric 
18763ca95b02SDimitry Andric   for (StoreInst *ST : Stores) {
1877ff0cc061SDimitry Andric     Value *Ptr = ST->getPointerOperand();
1878*b5893f02SDimitry Andric 
1879*b5893f02SDimitry Andric     if (isUniform(Ptr))
1880*b5893f02SDimitry Andric       HasDependenceInvolvingLoopInvariantAddress |=
1881*b5893f02SDimitry Andric           !UniformStores.insert(Ptr).second;
1882*b5893f02SDimitry Andric 
1883ff0cc061SDimitry Andric     // If we did *not* see this pointer before, insert it to  the read-write
1884ff0cc061SDimitry Andric     // list. At this phase it is only a 'write' list.
1885ff0cc061SDimitry Andric     if (Seen.insert(Ptr).second) {
1886ff0cc061SDimitry Andric       ++NumReadWrites;
1887ff0cc061SDimitry Andric 
18888f0fd8f6SDimitry Andric       MemoryLocation Loc = MemoryLocation::get(ST);
1889ff0cc061SDimitry Andric       // The TBAA metadata could have a control dependency on the predication
1890ff0cc061SDimitry Andric       // condition, so we cannot rely on it when determining whether or not we
1891ff0cc061SDimitry Andric       // need runtime pointer checks.
1892ff0cc061SDimitry Andric       if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
1893ff0cc061SDimitry Andric         Loc.AATags.TBAA = nullptr;
1894ff0cc061SDimitry Andric 
1895ff0cc061SDimitry Andric       Accesses.addStore(Loc);
1896ff0cc061SDimitry Andric     }
1897ff0cc061SDimitry Andric   }
1898ff0cc061SDimitry Andric 
1899ff0cc061SDimitry Andric   if (IsAnnotatedParallel) {
19004ba319b5SDimitry Andric     LLVM_DEBUG(
19014ba319b5SDimitry Andric         dbgs() << "LAA: A loop annotated parallel, ignore memory dependency "
1902ff0cc061SDimitry Andric                << "checks.\n");
1903ff0cc061SDimitry Andric     CanVecMem = true;
1904ff0cc061SDimitry Andric     return;
1905ff0cc061SDimitry Andric   }
1906ff0cc061SDimitry Andric 
19073ca95b02SDimitry Andric   for (LoadInst *LD : Loads) {
1908ff0cc061SDimitry Andric     Value *Ptr = LD->getPointerOperand();
1909ff0cc061SDimitry Andric     // If we did *not* see this pointer before, insert it to the
1910ff0cc061SDimitry Andric     // read list. If we *did* see it before, then it is already in
1911ff0cc061SDimitry Andric     // the read-write list. This allows us to vectorize expressions
1912ff0cc061SDimitry Andric     // such as A[i] += x;  Because the address of A[i] is a read-write
1913ff0cc061SDimitry Andric     // pointer. This only works if the index of A[i] is consecutive.
1914ff0cc061SDimitry Andric     // If the address of i is unknown (for example A[B[i]]) then we may
1915ff0cc061SDimitry Andric     // read a few words, modify, and write a few words, and some of the
1916ff0cc061SDimitry Andric     // words may be written to the same address.
1917ff0cc061SDimitry Andric     bool IsReadOnlyPtr = false;
19183ca95b02SDimitry Andric     if (Seen.insert(Ptr).second ||
19193ca95b02SDimitry Andric         !getPtrStride(*PSE, Ptr, TheLoop, SymbolicStrides)) {
1920ff0cc061SDimitry Andric       ++NumReads;
1921ff0cc061SDimitry Andric       IsReadOnlyPtr = true;
1922ff0cc061SDimitry Andric     }
1923ff0cc061SDimitry Andric 
1924*b5893f02SDimitry Andric     // See if there is an unsafe dependency between a load to a uniform address and
1925*b5893f02SDimitry Andric     // store to the same uniform address.
1926*b5893f02SDimitry Andric     if (UniformStores.count(Ptr)) {
1927*b5893f02SDimitry Andric       LLVM_DEBUG(dbgs() << "LAA: Found an unsafe dependency between a uniform "
1928*b5893f02SDimitry Andric                            "load and uniform store to the same address!\n");
1929*b5893f02SDimitry Andric       HasDependenceInvolvingLoopInvariantAddress = true;
1930*b5893f02SDimitry Andric     }
1931*b5893f02SDimitry Andric 
19328f0fd8f6SDimitry Andric     MemoryLocation Loc = MemoryLocation::get(LD);
1933ff0cc061SDimitry Andric     // The TBAA metadata could have a control dependency on the predication
1934ff0cc061SDimitry Andric     // condition, so we cannot rely on it when determining whether or not we
1935ff0cc061SDimitry Andric     // need runtime pointer checks.
1936ff0cc061SDimitry Andric     if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
1937ff0cc061SDimitry Andric       Loc.AATags.TBAA = nullptr;
1938ff0cc061SDimitry Andric 
1939ff0cc061SDimitry Andric     Accesses.addLoad(Loc, IsReadOnlyPtr);
1940ff0cc061SDimitry Andric   }
1941ff0cc061SDimitry Andric 
1942ff0cc061SDimitry Andric   // If we write (or read-write) to a single destination and there are no
1943ff0cc061SDimitry Andric   // other reads in this loop then is it safe to vectorize.
1944ff0cc061SDimitry Andric   if (NumReadWrites == 1 && NumReads == 0) {
19454ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
1946ff0cc061SDimitry Andric     CanVecMem = true;
1947ff0cc061SDimitry Andric     return;
1948ff0cc061SDimitry Andric   }
1949ff0cc061SDimitry Andric 
1950ff0cc061SDimitry Andric   // Build dependence sets and check whether we need a runtime pointer bounds
1951ff0cc061SDimitry Andric   // check.
1952ff0cc061SDimitry Andric   Accesses.buildDependenceSets();
1953ff0cc061SDimitry Andric 
1954ff0cc061SDimitry Andric   // Find pointers with computable bounds. We are going to use this information
1955ff0cc061SDimitry Andric   // to place a runtime bound check.
19563ca95b02SDimitry Andric   bool CanDoRTIfNeeded = Accesses.canCheckPtrAtRT(*PtrRtChecking, PSE->getSE(),
19573ca95b02SDimitry Andric                                                   TheLoop, SymbolicStrides);
1958875ed548SDimitry Andric   if (!CanDoRTIfNeeded) {
1959d88c1a5aSDimitry Andric     recordAnalysis("CantIdentifyArrayBounds") << "cannot identify array bounds";
19604ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
1961875ed548SDimitry Andric                       << "the array bounds.\n");
1962ff0cc061SDimitry Andric     CanVecMem = false;
1963ff0cc061SDimitry Andric     return;
1964ff0cc061SDimitry Andric   }
1965ff0cc061SDimitry Andric 
19664ba319b5SDimitry Andric   LLVM_DEBUG(
19674ba319b5SDimitry Andric       dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
1968ff0cc061SDimitry Andric 
1969ff0cc061SDimitry Andric   CanVecMem = true;
1970ff0cc061SDimitry Andric   if (Accesses.isDependencyCheckNeeded()) {
19714ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
19723ca95b02SDimitry Andric     CanVecMem = DepChecker->areDepsSafe(
19733ca95b02SDimitry Andric         DependentAccesses, Accesses.getDependenciesToCheck(), SymbolicStrides);
19743ca95b02SDimitry Andric     MaxSafeDepDistBytes = DepChecker->getMaxSafeDepDistBytes();
1975ff0cc061SDimitry Andric 
19763ca95b02SDimitry Andric     if (!CanVecMem && DepChecker->shouldRetryWithRuntimeCheck()) {
19774ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
1978ff0cc061SDimitry Andric 
1979ff0cc061SDimitry Andric       // Clear the dependency checks. We assume they are not needed.
19803ca95b02SDimitry Andric       Accesses.resetDepChecks(*DepChecker);
1981ff0cc061SDimitry Andric 
19823ca95b02SDimitry Andric       PtrRtChecking->reset();
19833ca95b02SDimitry Andric       PtrRtChecking->Need = true;
1984ff0cc061SDimitry Andric 
19853ca95b02SDimitry Andric       auto *SE = PSE->getSE();
19863ca95b02SDimitry Andric       CanDoRTIfNeeded = Accesses.canCheckPtrAtRT(*PtrRtChecking, SE, TheLoop,
19873ca95b02SDimitry Andric                                                  SymbolicStrides, true);
198897bc6c73SDimitry Andric 
1989ff0cc061SDimitry Andric       // Check that we found the bounds for the pointer.
1990875ed548SDimitry Andric       if (!CanDoRTIfNeeded) {
1991d88c1a5aSDimitry Andric         recordAnalysis("CantCheckMemDepsAtRunTime")
1992d88c1a5aSDimitry Andric             << "cannot check memory dependencies at runtime";
19934ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
1994ff0cc061SDimitry Andric         CanVecMem = false;
1995ff0cc061SDimitry Andric         return;
1996ff0cc061SDimitry Andric       }
1997ff0cc061SDimitry Andric 
1998ff0cc061SDimitry Andric       CanVecMem = true;
1999ff0cc061SDimitry Andric     }
2000ff0cc061SDimitry Andric   }
2001ff0cc061SDimitry Andric 
2002ff0cc061SDimitry Andric   if (CanVecMem)
20034ba319b5SDimitry Andric     LLVM_DEBUG(
20044ba319b5SDimitry Andric         dbgs() << "LAA: No unsafe dependent memory operations in loop.  We"
20053ca95b02SDimitry Andric                << (PtrRtChecking->Need ? "" : " don't")
2006875ed548SDimitry Andric                << " need runtime memory checks.\n");
2007ff0cc061SDimitry Andric   else {
2008d88c1a5aSDimitry Andric     recordAnalysis("UnsafeMemDep")
20093ca95b02SDimitry Andric         << "unsafe dependent memory operations in loop. Use "
20103ca95b02SDimitry Andric            "#pragma loop distribute(enable) to allow loop distribution "
20113ca95b02SDimitry Andric            "to attempt to isolate the offending operations into a separate "
2012d88c1a5aSDimitry Andric            "loop";
20134ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
2014ff0cc061SDimitry Andric   }
2015ff0cc061SDimitry Andric }
2016ff0cc061SDimitry Andric 
blockNeedsPredication(BasicBlock * BB,Loop * TheLoop,DominatorTree * DT)2017ff0cc061SDimitry Andric bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
2018ff0cc061SDimitry Andric                                            DominatorTree *DT)  {
2019ff0cc061SDimitry Andric   assert(TheLoop->contains(BB) && "Unknown block used");
2020ff0cc061SDimitry Andric 
2021ff0cc061SDimitry Andric   // Blocks that do not dominate the latch need predication.
2022ff0cc061SDimitry Andric   BasicBlock* Latch = TheLoop->getLoopLatch();
2023ff0cc061SDimitry Andric   return !DT->dominates(BB, Latch);
2024ff0cc061SDimitry Andric }
2025ff0cc061SDimitry Andric 
recordAnalysis(StringRef RemarkName,Instruction * I)2026d88c1a5aSDimitry Andric OptimizationRemarkAnalysis &LoopAccessInfo::recordAnalysis(StringRef RemarkName,
2027d88c1a5aSDimitry Andric                                                            Instruction *I) {
2028ff0cc061SDimitry Andric   assert(!Report && "Multiple reports generated");
2029d88c1a5aSDimitry Andric 
2030d88c1a5aSDimitry Andric   Value *CodeRegion = TheLoop->getHeader();
2031d88c1a5aSDimitry Andric   DebugLoc DL = TheLoop->getStartLoc();
2032d88c1a5aSDimitry Andric 
2033d88c1a5aSDimitry Andric   if (I) {
2034d88c1a5aSDimitry Andric     CodeRegion = I->getParent();
2035d88c1a5aSDimitry Andric     // If there is no debug location attached to the instruction, revert back to
2036d88c1a5aSDimitry Andric     // using the loop's.
2037d88c1a5aSDimitry Andric     if (I->getDebugLoc())
2038d88c1a5aSDimitry Andric       DL = I->getDebugLoc();
2039d88c1a5aSDimitry Andric   }
2040d88c1a5aSDimitry Andric 
2041d88c1a5aSDimitry Andric   Report = make_unique<OptimizationRemarkAnalysis>(DEBUG_TYPE, RemarkName, DL,
2042d88c1a5aSDimitry Andric                                                    CodeRegion);
2043d88c1a5aSDimitry Andric   return *Report;
2044ff0cc061SDimitry Andric }
2045ff0cc061SDimitry Andric 
isUniform(Value * V) const2046ff0cc061SDimitry Andric bool LoopAccessInfo::isUniform(Value *V) const {
2047d88c1a5aSDimitry Andric   auto *SE = PSE->getSE();
2048d88c1a5aSDimitry Andric   // Since we rely on SCEV for uniformity, if the type is not SCEVable, it is
2049d88c1a5aSDimitry Andric   // never considered uniform.
2050d88c1a5aSDimitry Andric   // TODO: Is this really what we want? Even without FP SCEV, we may want some
2051d88c1a5aSDimitry Andric   // trivially loop-invariant FP values to be considered uniform.
2052d88c1a5aSDimitry Andric   if (!SE->isSCEVable(V->getType()))
2053d88c1a5aSDimitry Andric     return false;
2054d88c1a5aSDimitry Andric   return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
2055ff0cc061SDimitry Andric }
2056ff0cc061SDimitry Andric 
2057ff0cc061SDimitry Andric // FIXME: this function is currently a duplicate of the one in
2058ff0cc061SDimitry Andric // LoopVectorize.cpp.
getFirstInst(Instruction * FirstInst,Value * V,Instruction * Loc)2059ff0cc061SDimitry Andric static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
2060ff0cc061SDimitry Andric                                  Instruction *Loc) {
2061ff0cc061SDimitry Andric   if (FirstInst)
2062ff0cc061SDimitry Andric     return FirstInst;
2063ff0cc061SDimitry Andric   if (Instruction *I = dyn_cast<Instruction>(V))
2064ff0cc061SDimitry Andric     return I->getParent() == Loc->getParent() ? I : nullptr;
2065ff0cc061SDimitry Andric   return nullptr;
2066ff0cc061SDimitry Andric }
2067ff0cc061SDimitry Andric 
20687d523365SDimitry Andric namespace {
2069d88c1a5aSDimitry Andric 
20704ba319b5SDimitry Andric /// IR Values for the lower and upper bounds of a pointer evolution.  We
20717d523365SDimitry Andric /// need to use value-handles because SCEV expansion can invalidate previously
20727d523365SDimitry Andric /// expanded values.  Thus expansion of a pointer can invalidate the bounds for
20737d523365SDimitry Andric /// a previous one.
20747d523365SDimitry Andric struct PointerBounds {
20757d523365SDimitry Andric   TrackingVH<Value> Start;
20767d523365SDimitry Andric   TrackingVH<Value> End;
20777d523365SDimitry Andric };
2078d88c1a5aSDimitry Andric 
20797d523365SDimitry Andric } // end anonymous namespace
2080ff0cc061SDimitry Andric 
20814ba319b5SDimitry Andric /// Expand code for the lower and upper bound of the pointer group \p CG
20827d523365SDimitry Andric /// in \p TheLoop.  \return the values for the bounds.
20837d523365SDimitry Andric static PointerBounds
expandBounds(const RuntimePointerChecking::CheckingPtrGroup * CG,Loop * TheLoop,Instruction * Loc,SCEVExpander & Exp,ScalarEvolution * SE,const RuntimePointerChecking & PtrRtChecking)20847d523365SDimitry Andric expandBounds(const RuntimePointerChecking::CheckingPtrGroup *CG, Loop *TheLoop,
20857d523365SDimitry Andric              Instruction *Loc, SCEVExpander &Exp, ScalarEvolution *SE,
20867d523365SDimitry Andric              const RuntimePointerChecking &PtrRtChecking) {
20877d523365SDimitry Andric   Value *Ptr = PtrRtChecking.Pointers[CG->Members[0]].PointerValue;
2088ff0cc061SDimitry Andric   const SCEV *Sc = SE->getSCEV(Ptr);
2089ff0cc061SDimitry Andric 
2090ff0cc061SDimitry Andric   unsigned AS = Ptr->getType()->getPointerAddressSpace();
20917d523365SDimitry Andric   LLVMContext &Ctx = Loc->getContext();
2092ff0cc061SDimitry Andric 
2093ff0cc061SDimitry Andric   // Use this type for pointer arithmetic.
2094ff0cc061SDimitry Andric   Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
2095ff0cc061SDimitry Andric 
2096d88c1a5aSDimitry Andric   if (SE->isLoopInvariant(Sc, TheLoop)) {
20974ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:"
20984ba319b5SDimitry Andric                       << *Ptr << "\n");
2099d88c1a5aSDimitry Andric     // Ptr could be in the loop body. If so, expand a new one at the correct
2100d88c1a5aSDimitry Andric     // location.
2101d88c1a5aSDimitry Andric     Instruction *Inst = dyn_cast<Instruction>(Ptr);
2102d88c1a5aSDimitry Andric     Value *NewPtr = (Inst && TheLoop->contains(Inst))
2103d88c1a5aSDimitry Andric                         ? Exp.expandCodeFor(Sc, PtrArithTy, Loc)
2104d88c1a5aSDimitry Andric                         : Ptr;
21057a7e6055SDimitry Andric     // We must return a half-open range, which means incrementing Sc.
21067a7e6055SDimitry Andric     const SCEV *ScPlusOne = SE->getAddExpr(Sc, SE->getOne(PtrArithTy));
21077a7e6055SDimitry Andric     Value *NewPtrPlusOne = Exp.expandCodeFor(ScPlusOne, PtrArithTy, Loc);
21087a7e6055SDimitry Andric     return {NewPtr, NewPtrPlusOne};
2109d88c1a5aSDimitry Andric   } else {
2110d88c1a5aSDimitry Andric     Value *Start = nullptr, *End = nullptr;
21114ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
21127d523365SDimitry Andric     Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc);
21137d523365SDimitry Andric     End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc);
21144ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High
21154ba319b5SDimitry Andric                       << "\n");
21167d523365SDimitry Andric     return {Start, End};
2117ff0cc061SDimitry Andric   }
2118ff0cc061SDimitry Andric }
2119ff0cc061SDimitry Andric 
21204ba319b5SDimitry Andric /// Turns a collection of checks into a collection of expanded upper and
21217d523365SDimitry Andric /// lower bounds for both pointers in the check.
expandBounds(const SmallVectorImpl<RuntimePointerChecking::PointerCheck> & PointerChecks,Loop * L,Instruction * Loc,ScalarEvolution * SE,SCEVExpander & Exp,const RuntimePointerChecking & PtrRtChecking)21227d523365SDimitry Andric static SmallVector<std::pair<PointerBounds, PointerBounds>, 4> expandBounds(
21237d523365SDimitry Andric     const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks,
21247d523365SDimitry Andric     Loop *L, Instruction *Loc, ScalarEvolution *SE, SCEVExpander &Exp,
21257d523365SDimitry Andric     const RuntimePointerChecking &PtrRtChecking) {
21267d523365SDimitry Andric   SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds;
21277d523365SDimitry Andric 
21287d523365SDimitry Andric   // Here we're relying on the SCEV Expander's cache to only emit code for the
21297d523365SDimitry Andric   // same bounds once.
2130d88c1a5aSDimitry Andric   transform(
2131d88c1a5aSDimitry Andric       PointerChecks, std::back_inserter(ChecksWithBounds),
21327d523365SDimitry Andric       [&](const RuntimePointerChecking::PointerCheck &Check) {
21337d523365SDimitry Andric         PointerBounds
21347d523365SDimitry Andric           First = expandBounds(Check.first, L, Loc, Exp, SE, PtrRtChecking),
21357d523365SDimitry Andric           Second = expandBounds(Check.second, L, Loc, Exp, SE, PtrRtChecking);
21367d523365SDimitry Andric         return std::make_pair(First, Second);
21377d523365SDimitry Andric       });
21387d523365SDimitry Andric 
21397d523365SDimitry Andric   return ChecksWithBounds;
21407d523365SDimitry Andric }
21417d523365SDimitry Andric 
addRuntimeChecks(Instruction * Loc,const SmallVectorImpl<RuntimePointerChecking::PointerCheck> & PointerChecks) const21427d523365SDimitry Andric std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeChecks(
21437d523365SDimitry Andric     Instruction *Loc,
21447d523365SDimitry Andric     const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks)
21457d523365SDimitry Andric     const {
21463ca95b02SDimitry Andric   const DataLayout &DL = TheLoop->getHeader()->getModule()->getDataLayout();
21473ca95b02SDimitry Andric   auto *SE = PSE->getSE();
21487d523365SDimitry Andric   SCEVExpander Exp(*SE, DL, "induction");
21497d523365SDimitry Andric   auto ExpandedChecks =
21503ca95b02SDimitry Andric       expandBounds(PointerChecks, TheLoop, Loc, SE, Exp, *PtrRtChecking);
21517d523365SDimitry Andric 
21527d523365SDimitry Andric   LLVMContext &Ctx = Loc->getContext();
21537d523365SDimitry Andric   Instruction *FirstInst = nullptr;
2154ff0cc061SDimitry Andric   IRBuilder<> ChkBuilder(Loc);
2155ff0cc061SDimitry Andric   // Our instructions might fold to a constant.
2156ff0cc061SDimitry Andric   Value *MemoryRuntimeCheck = nullptr;
2157875ed548SDimitry Andric 
21587d523365SDimitry Andric   for (const auto &Check : ExpandedChecks) {
21597d523365SDimitry Andric     const PointerBounds &A = Check.first, &B = Check.second;
21607d523365SDimitry Andric     // Check if two pointers (A and B) conflict where conflict is computed as:
21617d523365SDimitry Andric     // start(A) <= end(B) && start(B) <= end(A)
21627d523365SDimitry Andric     unsigned AS0 = A.Start->getType()->getPointerAddressSpace();
21637d523365SDimitry Andric     unsigned AS1 = B.Start->getType()->getPointerAddressSpace();
2164ff0cc061SDimitry Andric 
21657d523365SDimitry Andric     assert((AS0 == B.End->getType()->getPointerAddressSpace()) &&
21667d523365SDimitry Andric            (AS1 == A.End->getType()->getPointerAddressSpace()) &&
2167ff0cc061SDimitry Andric            "Trying to bounds check pointers with different address spaces");
2168ff0cc061SDimitry Andric 
2169ff0cc061SDimitry Andric     Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
2170ff0cc061SDimitry Andric     Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
2171ff0cc061SDimitry Andric 
21727d523365SDimitry Andric     Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc");
21737d523365SDimitry Andric     Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc");
21747d523365SDimitry Andric     Value *End0 =   ChkBuilder.CreateBitCast(A.End,   PtrArithTy1, "bc");
21757d523365SDimitry Andric     Value *End1 =   ChkBuilder.CreateBitCast(B.End,   PtrArithTy0, "bc");
2176ff0cc061SDimitry Andric 
2177f41fbc90SDimitry Andric     // [A|B].Start points to the first accessed byte under base [A|B].
2178f41fbc90SDimitry Andric     // [A|B].End points to the last accessed byte, plus one.
2179f41fbc90SDimitry Andric     // There is no conflict when the intervals are disjoint:
2180f41fbc90SDimitry Andric     // NoConflict = (B.Start >= A.End) || (A.Start >= B.End)
2181f41fbc90SDimitry Andric     //
2182f41fbc90SDimitry Andric     // bound0 = (B.Start < A.End)
2183f41fbc90SDimitry Andric     // bound1 = (A.Start < B.End)
2184f41fbc90SDimitry Andric     //  IsConflict = bound0 & bound1
2185f41fbc90SDimitry Andric     Value *Cmp0 = ChkBuilder.CreateICmpULT(Start0, End1, "bound0");
2186ff0cc061SDimitry Andric     FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
2187f41fbc90SDimitry Andric     Value *Cmp1 = ChkBuilder.CreateICmpULT(Start1, End0, "bound1");
2188ff0cc061SDimitry Andric     FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
2189ff0cc061SDimitry Andric     Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
2190ff0cc061SDimitry Andric     FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
2191ff0cc061SDimitry Andric     if (MemoryRuntimeCheck) {
21927d523365SDimitry Andric       IsConflict =
21937d523365SDimitry Andric           ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
2194ff0cc061SDimitry Andric       FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
2195ff0cc061SDimitry Andric     }
2196ff0cc061SDimitry Andric     MemoryRuntimeCheck = IsConflict;
2197ff0cc061SDimitry Andric   }
2198ff0cc061SDimitry Andric 
2199ff0cc061SDimitry Andric   if (!MemoryRuntimeCheck)
2200ff0cc061SDimitry Andric     return std::make_pair(nullptr, nullptr);
2201ff0cc061SDimitry Andric 
2202ff0cc061SDimitry Andric   // We have to do this trickery because the IRBuilder might fold the check to a
2203ff0cc061SDimitry Andric   // constant expression in which case there is no Instruction anchored in a
2204ff0cc061SDimitry Andric   // the block.
2205ff0cc061SDimitry Andric   Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
2206ff0cc061SDimitry Andric                                                  ConstantInt::getTrue(Ctx));
2207ff0cc061SDimitry Andric   ChkBuilder.Insert(Check, "memcheck.conflict");
2208ff0cc061SDimitry Andric   FirstInst = getFirstInst(FirstInst, Check, Loc);
2209ff0cc061SDimitry Andric   return std::make_pair(FirstInst, Check);
2210ff0cc061SDimitry Andric }
2211ff0cc061SDimitry Andric 
22127d523365SDimitry Andric std::pair<Instruction *, Instruction *>
addRuntimeChecks(Instruction * Loc) const22137d523365SDimitry Andric LoopAccessInfo::addRuntimeChecks(Instruction *Loc) const {
22143ca95b02SDimitry Andric   if (!PtrRtChecking->Need)
22157d523365SDimitry Andric     return std::make_pair(nullptr, nullptr);
22167d523365SDimitry Andric 
22173ca95b02SDimitry Andric   return addRuntimeChecks(Loc, PtrRtChecking->getChecks());
22183ca95b02SDimitry Andric }
22193ca95b02SDimitry Andric 
collectStridedAccess(Value * MemAccess)22203ca95b02SDimitry Andric void LoopAccessInfo::collectStridedAccess(Value *MemAccess) {
22213ca95b02SDimitry Andric   Value *Ptr = nullptr;
22223ca95b02SDimitry Andric   if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
22233ca95b02SDimitry Andric     Ptr = LI->getPointerOperand();
22243ca95b02SDimitry Andric   else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
22253ca95b02SDimitry Andric     Ptr = SI->getPointerOperand();
22263ca95b02SDimitry Andric   else
22273ca95b02SDimitry Andric     return;
22283ca95b02SDimitry Andric 
22293ca95b02SDimitry Andric   Value *Stride = getStrideFromPointer(Ptr, PSE->getSE(), TheLoop);
22303ca95b02SDimitry Andric   if (!Stride)
22313ca95b02SDimitry Andric     return;
22323ca95b02SDimitry Andric 
22334ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Found a strided access that is a candidate for "
22342cab237bSDimitry Andric                        "versioning:");
22354ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
22362cab237bSDimitry Andric 
22372cab237bSDimitry Andric   // Avoid adding the "Stride == 1" predicate when we know that
22382cab237bSDimitry Andric   // Stride >= Trip-Count. Such a predicate will effectively optimize a single
22392cab237bSDimitry Andric   // or zero iteration loop, as Trip-Count <= Stride == 1.
22402cab237bSDimitry Andric   //
22412cab237bSDimitry Andric   // TODO: We are currently not making a very informed decision on when it is
22422cab237bSDimitry Andric   // beneficial to apply stride versioning. It might make more sense that the
22432cab237bSDimitry Andric   // users of this analysis (such as the vectorizer) will trigger it, based on
22442cab237bSDimitry Andric   // their specific cost considerations; For example, in cases where stride
22452cab237bSDimitry Andric   // versioning does  not help resolving memory accesses/dependences, the
22462cab237bSDimitry Andric   // vectorizer should evaluate the cost of the runtime test, and the benefit
22472cab237bSDimitry Andric   // of various possible stride specializations, considering the alternatives
22482cab237bSDimitry Andric   // of using gather/scatters (if available).
22492cab237bSDimitry Andric 
22502cab237bSDimitry Andric   const SCEV *StrideExpr = PSE->getSCEV(Stride);
22512cab237bSDimitry Andric   const SCEV *BETakenCount = PSE->getBackedgeTakenCount();
22522cab237bSDimitry Andric 
22532cab237bSDimitry Andric   // Match the types so we can compare the stride and the BETakenCount.
22542cab237bSDimitry Andric   // The Stride can be positive/negative, so we sign extend Stride;
22552cab237bSDimitry Andric   // The backdgeTakenCount is non-negative, so we zero extend BETakenCount.
22562cab237bSDimitry Andric   const DataLayout &DL = TheLoop->getHeader()->getModule()->getDataLayout();
22572cab237bSDimitry Andric   uint64_t StrideTypeSize = DL.getTypeAllocSize(StrideExpr->getType());
22582cab237bSDimitry Andric   uint64_t BETypeSize = DL.getTypeAllocSize(BETakenCount->getType());
22592cab237bSDimitry Andric   const SCEV *CastedStride = StrideExpr;
22602cab237bSDimitry Andric   const SCEV *CastedBECount = BETakenCount;
22612cab237bSDimitry Andric   ScalarEvolution *SE = PSE->getSE();
22622cab237bSDimitry Andric   if (BETypeSize >= StrideTypeSize)
22632cab237bSDimitry Andric     CastedStride = SE->getNoopOrSignExtend(StrideExpr, BETakenCount->getType());
22642cab237bSDimitry Andric   else
22652cab237bSDimitry Andric     CastedBECount = SE->getZeroExtendExpr(BETakenCount, StrideExpr->getType());
22662cab237bSDimitry Andric   const SCEV *StrideMinusBETaken = SE->getMinusSCEV(CastedStride, CastedBECount);
22672cab237bSDimitry Andric   // Since TripCount == BackEdgeTakenCount + 1, checking:
22682cab237bSDimitry Andric   // "Stride >= TripCount" is equivalent to checking:
22692cab237bSDimitry Andric   // Stride - BETakenCount > 0
22702cab237bSDimitry Andric   if (SE->isKnownPositive(StrideMinusBETaken)) {
22714ba319b5SDimitry Andric     LLVM_DEBUG(
22724ba319b5SDimitry Andric         dbgs() << "LAA: Stride>=TripCount; No point in versioning as the "
22732cab237bSDimitry Andric                   "Stride==1 predicate will imply that the loop executes "
22742cab237bSDimitry Andric                   "at most once.\n");
22752cab237bSDimitry Andric     return;
22762cab237bSDimitry Andric   }
22774ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Found a strided access that we can version.");
22782cab237bSDimitry Andric 
22793ca95b02SDimitry Andric   SymbolicStrides[Ptr] = Stride;
22803ca95b02SDimitry Andric   StrideSet.insert(Stride);
22817d523365SDimitry Andric }
22827d523365SDimitry Andric 
LoopAccessInfo(Loop * L,ScalarEvolution * SE,const TargetLibraryInfo * TLI,AliasAnalysis * AA,DominatorTree * DT,LoopInfo * LI)2283ff0cc061SDimitry Andric LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
2284ff0cc061SDimitry Andric                                const TargetLibraryInfo *TLI, AliasAnalysis *AA,
22853ca95b02SDimitry Andric                                DominatorTree *DT, LoopInfo *LI)
22863ca95b02SDimitry Andric     : PSE(llvm::make_unique<PredicatedScalarEvolution>(*SE, *L)),
22873ca95b02SDimitry Andric       PtrRtChecking(llvm::make_unique<RuntimePointerChecking>(SE)),
22883ca95b02SDimitry Andric       DepChecker(llvm::make_unique<MemoryDepChecker>(*PSE, L)), TheLoop(L),
22893ca95b02SDimitry Andric       NumLoads(0), NumStores(0), MaxSafeDepDistBytes(-1), CanVecMem(false),
2290*b5893f02SDimitry Andric       HasDependenceInvolvingLoopInvariantAddress(false) {
2291ff0cc061SDimitry Andric   if (canAnalyzeLoop())
22923ca95b02SDimitry Andric     analyzeLoop(AA, LI, TLI, DT);
2293ff0cc061SDimitry Andric }
2294ff0cc061SDimitry Andric 
print(raw_ostream & OS,unsigned Depth) const2295ff0cc061SDimitry Andric void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
2296ff0cc061SDimitry Andric   if (CanVecMem) {
22973ca95b02SDimitry Andric     OS.indent(Depth) << "Memory dependences are safe";
22983ca95b02SDimitry Andric     if (MaxSafeDepDistBytes != -1ULL)
22993ca95b02SDimitry Andric       OS << " with a maximum dependence distance of " << MaxSafeDepDistBytes
23003ca95b02SDimitry Andric          << " bytes";
23013ca95b02SDimitry Andric     if (PtrRtChecking->Need)
23023ca95b02SDimitry Andric       OS << " with run-time checks";
23033ca95b02SDimitry Andric     OS << "\n";
2304ff0cc061SDimitry Andric   }
2305ff0cc061SDimitry Andric 
2306ff0cc061SDimitry Andric   if (Report)
2307d88c1a5aSDimitry Andric     OS.indent(Depth) << "Report: " << Report->getMsg() << "\n";
2308ff0cc061SDimitry Andric 
23093ca95b02SDimitry Andric   if (auto *Dependences = DepChecker->getDependences()) {
23107d523365SDimitry Andric     OS.indent(Depth) << "Dependences:\n";
23117d523365SDimitry Andric     for (auto &Dep : *Dependences) {
23123ca95b02SDimitry Andric       Dep.print(OS, Depth + 2, DepChecker->getMemoryInstructions());
2313ff0cc061SDimitry Andric       OS << "\n";
2314ff0cc061SDimitry Andric     }
2315ff0cc061SDimitry Andric   } else
23167d523365SDimitry Andric     OS.indent(Depth) << "Too many dependences, not recorded\n";
2317ff0cc061SDimitry Andric 
2318ff0cc061SDimitry Andric   // List the pair of accesses need run-time checks to prove independence.
23193ca95b02SDimitry Andric   PtrRtChecking->print(OS, Depth);
2320ff0cc061SDimitry Andric   OS << "\n";
2321ff0cc061SDimitry Andric 
2322*b5893f02SDimitry Andric   OS.indent(Depth) << "Non vectorizable stores to invariant address were "
2323*b5893f02SDimitry Andric                    << (HasDependenceInvolvingLoopInvariantAddress ? "" : "not ")
2324ff0cc061SDimitry Andric                    << "found in loop.\n";
23257d523365SDimitry Andric 
23267d523365SDimitry Andric   OS.indent(Depth) << "SCEV assumptions:\n";
23273ca95b02SDimitry Andric   PSE->getUnionPredicate().print(OS, Depth);
23283ca95b02SDimitry Andric 
23293ca95b02SDimitry Andric   OS << "\n";
23303ca95b02SDimitry Andric 
23313ca95b02SDimitry Andric   OS.indent(Depth) << "Expressions re-written:\n";
23323ca95b02SDimitry Andric   PSE->print(OS, Depth);
2333ff0cc061SDimitry Andric }
2334ff0cc061SDimitry Andric 
getInfo(Loop * L)23353ca95b02SDimitry Andric const LoopAccessInfo &LoopAccessLegacyAnalysis::getInfo(Loop *L) {
2336ff0cc061SDimitry Andric   auto &LAI = LoopAccessInfoMap[L];
2337ff0cc061SDimitry Andric 
23383ca95b02SDimitry Andric   if (!LAI)
23393ca95b02SDimitry Andric     LAI = llvm::make_unique<LoopAccessInfo>(L, SE, TLI, AA, DT, LI);
2340ff0cc061SDimitry Andric 
2341ff0cc061SDimitry Andric   return *LAI.get();
2342ff0cc061SDimitry Andric }
2343ff0cc061SDimitry Andric 
print(raw_ostream & OS,const Module * M) const23443ca95b02SDimitry Andric void LoopAccessLegacyAnalysis::print(raw_ostream &OS, const Module *M) const {
23453ca95b02SDimitry Andric   LoopAccessLegacyAnalysis &LAA = *const_cast<LoopAccessLegacyAnalysis *>(this);
2346ff0cc061SDimitry Andric 
2347ff0cc061SDimitry Andric   for (Loop *TopLevelLoop : *LI)
2348ff0cc061SDimitry Andric     for (Loop *L : depth_first(TopLevelLoop)) {
2349ff0cc061SDimitry Andric       OS.indent(2) << L->getHeader()->getName() << ":\n";
23503ca95b02SDimitry Andric       auto &LAI = LAA.getInfo(L);
2351ff0cc061SDimitry Andric       LAI.print(OS, 4);
2352ff0cc061SDimitry Andric     }
2353ff0cc061SDimitry Andric }
2354ff0cc061SDimitry Andric 
runOnFunction(Function & F)23553ca95b02SDimitry Andric bool LoopAccessLegacyAnalysis::runOnFunction(Function &F) {
23567d523365SDimitry Andric   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2357ff0cc061SDimitry Andric   auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2358ff0cc061SDimitry Andric   TLI = TLIP ? &TLIP->getTLI() : nullptr;
23597d523365SDimitry Andric   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2360ff0cc061SDimitry Andric   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2361ff0cc061SDimitry Andric   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2362ff0cc061SDimitry Andric 
2363ff0cc061SDimitry Andric   return false;
2364ff0cc061SDimitry Andric }
2365ff0cc061SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const23663ca95b02SDimitry Andric void LoopAccessLegacyAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
23677d523365SDimitry Andric     AU.addRequired<ScalarEvolutionWrapperPass>();
23687d523365SDimitry Andric     AU.addRequired<AAResultsWrapperPass>();
2369ff0cc061SDimitry Andric     AU.addRequired<DominatorTreeWrapperPass>();
2370ff0cc061SDimitry Andric     AU.addRequired<LoopInfoWrapperPass>();
2371ff0cc061SDimitry Andric 
2372ff0cc061SDimitry Andric     AU.setPreservesAll();
2373ff0cc061SDimitry Andric }
2374ff0cc061SDimitry Andric 
23753ca95b02SDimitry Andric char LoopAccessLegacyAnalysis::ID = 0;
2376ff0cc061SDimitry Andric static const char laa_name[] = "Loop Access Analysis";
2377ff0cc061SDimitry Andric #define LAA_NAME "loop-accesses"
2378ff0cc061SDimitry Andric 
23793ca95b02SDimitry Andric INITIALIZE_PASS_BEGIN(LoopAccessLegacyAnalysis, LAA_NAME, laa_name, false, true)
23807d523365SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
23817d523365SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
2382ff0cc061SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2383ff0cc061SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
23843ca95b02SDimitry Andric INITIALIZE_PASS_END(LoopAccessLegacyAnalysis, LAA_NAME, laa_name, false, true)
23853ca95b02SDimitry Andric 
2386d88c1a5aSDimitry Andric AnalysisKey LoopAccessAnalysis::Key;
23873ca95b02SDimitry Andric 
run(Loop & L,LoopAnalysisManager & AM,LoopStandardAnalysisResults & AR)2388f1a29dd3SDimitry Andric LoopAccessInfo LoopAccessAnalysis::run(Loop &L, LoopAnalysisManager &AM,
2389f1a29dd3SDimitry Andric                                        LoopStandardAnalysisResults &AR) {
2390f1a29dd3SDimitry Andric   return LoopAccessInfo(&L, &AR.SE, &AR.TLI, &AR.AA, &AR.DT, &AR.LI);
23913ca95b02SDimitry Andric }
2392ff0cc061SDimitry Andric 
2393ff0cc061SDimitry Andric namespace llvm {
2394d88c1a5aSDimitry Andric 
createLAAPass()2395ff0cc061SDimitry Andric   Pass *createLAAPass() {
23963ca95b02SDimitry Andric     return new LoopAccessLegacyAnalysis();
2397ff0cc061SDimitry Andric   }
2398d88c1a5aSDimitry Andric 
2399d88c1a5aSDimitry Andric } // end namespace llvm
2400