10456327cSAdam Nemet //===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==//
20456327cSAdam Nemet //
30456327cSAdam Nemet //                     The LLVM Compiler Infrastructure
40456327cSAdam Nemet //
50456327cSAdam Nemet // This file is distributed under the University of Illinois Open Source
60456327cSAdam Nemet // License. See LICENSE.TXT for details.
70456327cSAdam Nemet //
80456327cSAdam Nemet //===----------------------------------------------------------------------===//
90456327cSAdam Nemet //
100456327cSAdam Nemet // The implementation for the loop memory dependence that was originally
110456327cSAdam Nemet // developed for the loop vectorizer.
120456327cSAdam Nemet //
130456327cSAdam Nemet //===----------------------------------------------------------------------===//
140456327cSAdam Nemet 
150456327cSAdam Nemet #include "llvm/Analysis/LoopAccessAnalysis.h"
160456327cSAdam Nemet #include "llvm/Analysis/LoopInfo.h"
177206d7a5SAdam Nemet #include "llvm/Analysis/ScalarEvolutionExpander.h"
18799003bfSBenjamin Kramer #include "llvm/Analysis/TargetLibraryInfo.h"
190456327cSAdam Nemet #include "llvm/Analysis/ValueTracking.h"
200456327cSAdam Nemet #include "llvm/IR/DiagnosticInfo.h"
210456327cSAdam Nemet #include "llvm/IR/Dominators.h"
227206d7a5SAdam Nemet #include "llvm/IR/IRBuilder.h"
230456327cSAdam Nemet #include "llvm/Support/Debug.h"
24799003bfSBenjamin Kramer #include "llvm/Support/raw_ostream.h"
25b447ac64SDavid Blaikie #include "llvm/Analysis/VectorUtils.h"
260456327cSAdam Nemet using namespace llvm;
270456327cSAdam Nemet 
28339f42b3SAdam Nemet #define DEBUG_TYPE "loop-accesses"
290456327cSAdam Nemet 
30f219c647SAdam Nemet static cl::opt<unsigned, true>
31f219c647SAdam Nemet VectorizationFactor("force-vector-width", cl::Hidden,
32f219c647SAdam Nemet                     cl::desc("Sets the SIMD width. Zero is autoselect."),
33f219c647SAdam Nemet                     cl::location(VectorizerParams::VectorizationFactor));
341d862af7SAdam Nemet unsigned VectorizerParams::VectorizationFactor;
35f219c647SAdam Nemet 
36f219c647SAdam Nemet static cl::opt<unsigned, true>
37f219c647SAdam Nemet VectorizationInterleave("force-vector-interleave", cl::Hidden,
38f219c647SAdam Nemet                         cl::desc("Sets the vectorization interleave count. "
39f219c647SAdam Nemet                                  "Zero is autoselect."),
40f219c647SAdam Nemet                         cl::location(
41f219c647SAdam Nemet                             VectorizerParams::VectorizationInterleave));
421d862af7SAdam Nemet unsigned VectorizerParams::VectorizationInterleave;
43f219c647SAdam Nemet 
441d862af7SAdam Nemet static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
451d862af7SAdam Nemet     "runtime-memory-check-threshold", cl::Hidden,
461d862af7SAdam Nemet     cl::desc("When performing memory disambiguation checks at runtime do not "
471d862af7SAdam Nemet              "generate more than this number of comparisons (default = 8)."),
481d862af7SAdam Nemet     cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
491d862af7SAdam Nemet unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
50f219c647SAdam Nemet 
511b6b50a9SSilviu Baranga /// \brief The maximum iterations used to merge memory checks
521b6b50a9SSilviu Baranga static cl::opt<unsigned> MemoryCheckMergeThreshold(
531b6b50a9SSilviu Baranga     "memory-check-merge-threshold", cl::Hidden,
541b6b50a9SSilviu Baranga     cl::desc("Maximum number of comparisons done when trying to merge "
551b6b50a9SSilviu Baranga              "runtime memory checks. (default = 100)"),
561b6b50a9SSilviu Baranga     cl::init(100));
571b6b50a9SSilviu Baranga 
58f219c647SAdam Nemet /// Maximum SIMD width.
59f219c647SAdam Nemet const unsigned VectorizerParams::MaxVectorWidth = 64;
60f219c647SAdam Nemet 
61a2df750fSAdam Nemet /// \brief We collect dependences up to this threshold.
62a2df750fSAdam Nemet static cl::opt<unsigned>
63a2df750fSAdam Nemet     MaxDependences("max-dependences", cl::Hidden,
64a2df750fSAdam Nemet                    cl::desc("Maximum number of dependences collected by "
659c926579SAdam Nemet                             "loop-access analysis (default = 100)"),
669c926579SAdam Nemet                    cl::init(100));
679c926579SAdam Nemet 
68f219c647SAdam Nemet bool VectorizerParams::isInterleaveForced() {
69f219c647SAdam Nemet   return ::VectorizationInterleave.getNumOccurrences() > 0;
70f219c647SAdam Nemet }
71f219c647SAdam Nemet 
722bd6e984SAdam Nemet void LoopAccessReport::emitAnalysis(const LoopAccessReport &Message,
730456327cSAdam Nemet                                     const Function *TheFunction,
74339f42b3SAdam Nemet                                     const Loop *TheLoop,
75339f42b3SAdam Nemet                                     const char *PassName) {
760456327cSAdam Nemet   DebugLoc DL = TheLoop->getStartLoc();
773e87634fSAdam Nemet   if (const Instruction *I = Message.getInstr())
780456327cSAdam Nemet     DL = I->getDebugLoc();
79339f42b3SAdam Nemet   emitOptimizationRemarkAnalysis(TheFunction->getContext(), PassName,
800456327cSAdam Nemet                                  *TheFunction, DL, Message.str());
810456327cSAdam Nemet }
820456327cSAdam Nemet 
830456327cSAdam Nemet Value *llvm::stripIntegerCast(Value *V) {
840456327cSAdam Nemet   if (CastInst *CI = dyn_cast<CastInst>(V))
850456327cSAdam Nemet     if (CI->getOperand(0)->getType()->isIntegerTy())
860456327cSAdam Nemet       return CI->getOperand(0);
870456327cSAdam Nemet   return V;
880456327cSAdam Nemet }
890456327cSAdam Nemet 
909cd9a7e3SSilviu Baranga const SCEV *llvm::replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE,
918bc61df9SAdam Nemet                                             const ValueToValueMap &PtrToStride,
920456327cSAdam Nemet                                             Value *Ptr, Value *OrigPtr) {
939cd9a7e3SSilviu Baranga   const SCEV *OrigSCEV = PSE.getSCEV(Ptr);
940456327cSAdam Nemet 
950456327cSAdam Nemet   // If there is an entry in the map return the SCEV of the pointer with the
960456327cSAdam Nemet   // symbolic stride replaced by one.
978bc61df9SAdam Nemet   ValueToValueMap::const_iterator SI =
988bc61df9SAdam Nemet       PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
990456327cSAdam Nemet   if (SI != PtrToStride.end()) {
1000456327cSAdam Nemet     Value *StrideVal = SI->second;
1010456327cSAdam Nemet 
1020456327cSAdam Nemet     // Strip casts.
1030456327cSAdam Nemet     StrideVal = stripIntegerCast(StrideVal);
1040456327cSAdam Nemet 
1050456327cSAdam Nemet     // Replace symbolic stride by one.
1060456327cSAdam Nemet     Value *One = ConstantInt::get(StrideVal->getType(), 1);
1070456327cSAdam Nemet     ValueToValueMap RewriteMap;
1080456327cSAdam Nemet     RewriteMap[StrideVal] = One;
1090456327cSAdam Nemet 
1109cd9a7e3SSilviu Baranga     ScalarEvolution *SE = PSE.getSE();
111e3c0534bSSilviu Baranga     const auto *U = cast<SCEVUnknown>(SE->getSCEV(StrideVal));
112e3c0534bSSilviu Baranga     const auto *CT =
113e3c0534bSSilviu Baranga         static_cast<const SCEVConstant *>(SE->getOne(StrideVal->getType()));
114e3c0534bSSilviu Baranga 
1159cd9a7e3SSilviu Baranga     PSE.addPredicate(*SE->getEqualPredicate(U, CT));
1169cd9a7e3SSilviu Baranga     auto *Expr = PSE.getSCEV(Ptr);
117e3c0534bSSilviu Baranga 
1189cd9a7e3SSilviu Baranga     DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *Expr
1190456327cSAdam Nemet                  << "\n");
1209cd9a7e3SSilviu Baranga     return Expr;
1210456327cSAdam Nemet   }
1220456327cSAdam Nemet 
1230456327cSAdam Nemet   // Otherwise, just return the SCEV of the original pointer.
124e3c0534bSSilviu Baranga   return OrigSCEV;
1250456327cSAdam Nemet }
1260456327cSAdam Nemet 
1277cdebac0SAdam Nemet void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, bool WritePtr,
1287cdebac0SAdam Nemet                                     unsigned DepSetId, unsigned ASId,
129e3c0534bSSilviu Baranga                                     const ValueToValueMap &Strides,
1309cd9a7e3SSilviu Baranga                                     PredicatedScalarEvolution &PSE) {
1310456327cSAdam Nemet   // Get the stride replaced scev.
1329cd9a7e3SSilviu Baranga   const SCEV *Sc = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
133279784ffSAdam Nemet   ScalarEvolution *SE = PSE.getSE();
134279784ffSAdam Nemet 
135279784ffSAdam Nemet   const SCEV *ScStart;
136279784ffSAdam Nemet   const SCEV *ScEnd;
137279784ffSAdam Nemet 
13859a65504SAdam Nemet   if (SE->isLoopInvariant(Sc, Lp))
139279784ffSAdam Nemet     ScStart = ScEnd = Sc;
140279784ffSAdam Nemet   else {
1410456327cSAdam Nemet     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
1420456327cSAdam Nemet     assert(AR && "Invalid addrec expression");
143*6f444dfdSSilviu Baranga     const SCEV *Ex = PSE.getBackedgeTakenCount();
1440e5804a6SSilviu Baranga 
145279784ffSAdam Nemet     ScStart = AR->getStart();
146279784ffSAdam Nemet     ScEnd = AR->evaluateAtIteration(Ex, *SE);
1470e5804a6SSilviu Baranga     const SCEV *Step = AR->getStepRecurrence(*SE);
1480e5804a6SSilviu Baranga 
1490e5804a6SSilviu Baranga     // For expressions with negative step, the upper bound is ScStart and the
1500e5804a6SSilviu Baranga     // lower bound is ScEnd.
1510e5804a6SSilviu Baranga     if (const SCEVConstant *CStep = dyn_cast<const SCEVConstant>(Step)) {
1520e5804a6SSilviu Baranga       if (CStep->getValue()->isNegative())
1530e5804a6SSilviu Baranga         std::swap(ScStart, ScEnd);
1540e5804a6SSilviu Baranga     } else {
1550e5804a6SSilviu Baranga       // Fallback case: the step is not constant, but the we can still
1560e5804a6SSilviu Baranga       // get the upper and lower bounds of the interval by using min/max
1570e5804a6SSilviu Baranga       // expressions.
1580e5804a6SSilviu Baranga       ScStart = SE->getUMinExpr(ScStart, ScEnd);
1590e5804a6SSilviu Baranga       ScEnd = SE->getUMaxExpr(AR->getStart(), ScEnd);
1600e5804a6SSilviu Baranga     }
161279784ffSAdam Nemet   }
1620e5804a6SSilviu Baranga 
1630e5804a6SSilviu Baranga   Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, Sc);
1641b6b50a9SSilviu Baranga }
1651b6b50a9SSilviu Baranga 
166bbe1f1deSAdam Nemet SmallVector<RuntimePointerChecking::PointerCheck, 4>
16738530887SAdam Nemet RuntimePointerChecking::generateChecks() const {
168bbe1f1deSAdam Nemet   SmallVector<PointerCheck, 4> Checks;
169bbe1f1deSAdam Nemet 
1707c52e052SAdam Nemet   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
1717c52e052SAdam Nemet     for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) {
1727c52e052SAdam Nemet       const RuntimePointerChecking::CheckingPtrGroup &CGI = CheckingGroups[I];
1737c52e052SAdam Nemet       const RuntimePointerChecking::CheckingPtrGroup &CGJ = CheckingGroups[J];
174bbe1f1deSAdam Nemet 
17538530887SAdam Nemet       if (needsChecking(CGI, CGJ))
176bbe1f1deSAdam Nemet         Checks.push_back(std::make_pair(&CGI, &CGJ));
177bbe1f1deSAdam Nemet     }
178bbe1f1deSAdam Nemet   }
179bbe1f1deSAdam Nemet   return Checks;
180bbe1f1deSAdam Nemet }
181bbe1f1deSAdam Nemet 
18215840393SAdam Nemet void RuntimePointerChecking::generateChecks(
18315840393SAdam Nemet     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
18415840393SAdam Nemet   assert(Checks.empty() && "Checks is not empty");
18515840393SAdam Nemet   groupChecks(DepCands, UseDependencies);
18615840393SAdam Nemet   Checks = generateChecks();
18715840393SAdam Nemet }
18815840393SAdam Nemet 
189651a5a24SAdam Nemet bool RuntimePointerChecking::needsChecking(const CheckingPtrGroup &M,
190651a5a24SAdam Nemet                                            const CheckingPtrGroup &N) const {
1911b6b50a9SSilviu Baranga   for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I)
1921b6b50a9SSilviu Baranga     for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J)
193651a5a24SAdam Nemet       if (needsChecking(M.Members[I], N.Members[J]))
1941b6b50a9SSilviu Baranga         return true;
1951b6b50a9SSilviu Baranga   return false;
1961b6b50a9SSilviu Baranga }
1971b6b50a9SSilviu Baranga 
1981b6b50a9SSilviu Baranga /// Compare \p I and \p J and return the minimum.
1991b6b50a9SSilviu Baranga /// Return nullptr in case we couldn't find an answer.
2001b6b50a9SSilviu Baranga static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
2011b6b50a9SSilviu Baranga                                    ScalarEvolution *SE) {
2021b6b50a9SSilviu Baranga   const SCEV *Diff = SE->getMinusSCEV(J, I);
2031b6b50a9SSilviu Baranga   const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
2041b6b50a9SSilviu Baranga 
2051b6b50a9SSilviu Baranga   if (!C)
2061b6b50a9SSilviu Baranga     return nullptr;
2071b6b50a9SSilviu Baranga   if (C->getValue()->isNegative())
2081b6b50a9SSilviu Baranga     return J;
2091b6b50a9SSilviu Baranga   return I;
2101b6b50a9SSilviu Baranga }
2111b6b50a9SSilviu Baranga 
2127cdebac0SAdam Nemet bool RuntimePointerChecking::CheckingPtrGroup::addPointer(unsigned Index) {
2139f7dedc3SAdam Nemet   const SCEV *Start = RtCheck.Pointers[Index].Start;
2149f7dedc3SAdam Nemet   const SCEV *End = RtCheck.Pointers[Index].End;
2159f7dedc3SAdam Nemet 
2161b6b50a9SSilviu Baranga   // Compare the starts and ends with the known minimum and maximum
2171b6b50a9SSilviu Baranga   // of this set. We need to know how we compare against the min/max
2181b6b50a9SSilviu Baranga   // of the set in order to be able to emit memchecks.
2199f7dedc3SAdam Nemet   const SCEV *Min0 = getMinFromExprs(Start, Low, RtCheck.SE);
2201b6b50a9SSilviu Baranga   if (!Min0)
2211b6b50a9SSilviu Baranga     return false;
2221b6b50a9SSilviu Baranga 
2239f7dedc3SAdam Nemet   const SCEV *Min1 = getMinFromExprs(End, High, RtCheck.SE);
2241b6b50a9SSilviu Baranga   if (!Min1)
2251b6b50a9SSilviu Baranga     return false;
2261b6b50a9SSilviu Baranga 
2271b6b50a9SSilviu Baranga   // Update the low bound  expression if we've found a new min value.
2289f7dedc3SAdam Nemet   if (Min0 == Start)
2299f7dedc3SAdam Nemet     Low = Start;
2301b6b50a9SSilviu Baranga 
2311b6b50a9SSilviu Baranga   // Update the high bound expression if we've found a new max value.
2329f7dedc3SAdam Nemet   if (Min1 != End)
2339f7dedc3SAdam Nemet     High = End;
2341b6b50a9SSilviu Baranga 
2351b6b50a9SSilviu Baranga   Members.push_back(Index);
2361b6b50a9SSilviu Baranga   return true;
2371b6b50a9SSilviu Baranga }
2381b6b50a9SSilviu Baranga 
2397cdebac0SAdam Nemet void RuntimePointerChecking::groupChecks(
2407cdebac0SAdam Nemet     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
2411b6b50a9SSilviu Baranga   // We build the groups from dependency candidates equivalence classes
2421b6b50a9SSilviu Baranga   // because:
2431b6b50a9SSilviu Baranga   //    - We know that pointers in the same equivalence class share
2441b6b50a9SSilviu Baranga   //      the same underlying object and therefore there is a chance
2451b6b50a9SSilviu Baranga   //      that we can compare pointers
2461b6b50a9SSilviu Baranga   //    - We wouldn't be able to merge two pointers for which we need
2471b6b50a9SSilviu Baranga   //      to emit a memcheck. The classes in DepCands are already
2481b6b50a9SSilviu Baranga   //      conveniently built such that no two pointers in the same
2491b6b50a9SSilviu Baranga   //      class need checking against each other.
2501b6b50a9SSilviu Baranga 
2511b6b50a9SSilviu Baranga   // We use the following (greedy) algorithm to construct the groups
2521b6b50a9SSilviu Baranga   // For every pointer in the equivalence class:
2531b6b50a9SSilviu Baranga   //   For each existing group:
2541b6b50a9SSilviu Baranga   //   - if the difference between this pointer and the min/max bounds
2551b6b50a9SSilviu Baranga   //     of the group is a constant, then make the pointer part of the
2561b6b50a9SSilviu Baranga   //     group and update the min/max bounds of that group as required.
2571b6b50a9SSilviu Baranga 
2581b6b50a9SSilviu Baranga   CheckingGroups.clear();
2591b6b50a9SSilviu Baranga 
26048250600SSilviu Baranga   // If we need to check two pointers to the same underlying object
26148250600SSilviu Baranga   // with a non-constant difference, we shouldn't perform any pointer
26248250600SSilviu Baranga   // grouping with those pointers. This is because we can easily get
26348250600SSilviu Baranga   // into cases where the resulting check would return false, even when
26448250600SSilviu Baranga   // the accesses are safe.
26548250600SSilviu Baranga   //
26648250600SSilviu Baranga   // The following example shows this:
26748250600SSilviu Baranga   // for (i = 0; i < 1000; ++i)
26848250600SSilviu Baranga   //   a[5000 + i * m] = a[i] + a[i + 9000]
26948250600SSilviu Baranga   //
27048250600SSilviu Baranga   // Here grouping gives a check of (5000, 5000 + 1000 * m) against
27148250600SSilviu Baranga   // (0, 10000) which is always false. However, if m is 1, there is no
27248250600SSilviu Baranga   // dependence. Not grouping the checks for a[i] and a[i + 9000] allows
27348250600SSilviu Baranga   // us to perform an accurate check in this case.
27448250600SSilviu Baranga   //
27548250600SSilviu Baranga   // The above case requires that we have an UnknownDependence between
27648250600SSilviu Baranga   // accesses to the same underlying object. This cannot happen unless
27748250600SSilviu Baranga   // ShouldRetryWithRuntimeCheck is set, and therefore UseDependencies
27848250600SSilviu Baranga   // is also false. In this case we will use the fallback path and create
27948250600SSilviu Baranga   // separate checking groups for all pointers.
28048250600SSilviu Baranga 
2811b6b50a9SSilviu Baranga   // If we don't have the dependency partitions, construct a new
28248250600SSilviu Baranga   // checking pointer group for each pointer. This is also required
28348250600SSilviu Baranga   // for correctness, because in this case we can have checking between
28448250600SSilviu Baranga   // pointers to the same underlying object.
2851b6b50a9SSilviu Baranga   if (!UseDependencies) {
2861b6b50a9SSilviu Baranga     for (unsigned I = 0; I < Pointers.size(); ++I)
2871b6b50a9SSilviu Baranga       CheckingGroups.push_back(CheckingPtrGroup(I, *this));
2881b6b50a9SSilviu Baranga     return;
2891b6b50a9SSilviu Baranga   }
2901b6b50a9SSilviu Baranga 
2911b6b50a9SSilviu Baranga   unsigned TotalComparisons = 0;
2921b6b50a9SSilviu Baranga 
2931b6b50a9SSilviu Baranga   DenseMap<Value *, unsigned> PositionMap;
2949f7dedc3SAdam Nemet   for (unsigned Index = 0; Index < Pointers.size(); ++Index)
2959f7dedc3SAdam Nemet     PositionMap[Pointers[Index].PointerValue] = Index;
2961b6b50a9SSilviu Baranga 
297ce3877fcSSilviu Baranga   // We need to keep track of what pointers we've already seen so we
298ce3877fcSSilviu Baranga   // don't process them twice.
299ce3877fcSSilviu Baranga   SmallSet<unsigned, 2> Seen;
300ce3877fcSSilviu Baranga 
301e4b9f507SSanjay Patel   // Go through all equivalence classes, get the "pointer check groups"
302ce3877fcSSilviu Baranga   // and add them to the overall solution. We use the order in which accesses
303ce3877fcSSilviu Baranga   // appear in 'Pointers' to enforce determinism.
304ce3877fcSSilviu Baranga   for (unsigned I = 0; I < Pointers.size(); ++I) {
305ce3877fcSSilviu Baranga     // We've seen this pointer before, and therefore already processed
306ce3877fcSSilviu Baranga     // its equivalence class.
307ce3877fcSSilviu Baranga     if (Seen.count(I))
3081b6b50a9SSilviu Baranga       continue;
3091b6b50a9SSilviu Baranga 
3109f7dedc3SAdam Nemet     MemoryDepChecker::MemAccessInfo Access(Pointers[I].PointerValue,
3119f7dedc3SAdam Nemet                                            Pointers[I].IsWritePtr);
3121b6b50a9SSilviu Baranga 
313ce3877fcSSilviu Baranga     SmallVector<CheckingPtrGroup, 2> Groups;
314ce3877fcSSilviu Baranga     auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access));
315ce3877fcSSilviu Baranga 
316a647c30fSSilviu Baranga     // Because DepCands is constructed by visiting accesses in the order in
317a647c30fSSilviu Baranga     // which they appear in alias sets (which is deterministic) and the
318a647c30fSSilviu Baranga     // iteration order within an equivalence class member is only dependent on
319a647c30fSSilviu Baranga     // the order in which unions and insertions are performed on the
320a647c30fSSilviu Baranga     // equivalence class, the iteration order is deterministic.
321ce3877fcSSilviu Baranga     for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end();
3221b6b50a9SSilviu Baranga          MI != ME; ++MI) {
3231b6b50a9SSilviu Baranga       unsigned Pointer = PositionMap[MI->getPointer()];
3241b6b50a9SSilviu Baranga       bool Merged = false;
325ce3877fcSSilviu Baranga       // Mark this pointer as seen.
326ce3877fcSSilviu Baranga       Seen.insert(Pointer);
3271b6b50a9SSilviu Baranga 
3281b6b50a9SSilviu Baranga       // Go through all the existing sets and see if we can find one
3291b6b50a9SSilviu Baranga       // which can include this pointer.
3301b6b50a9SSilviu Baranga       for (CheckingPtrGroup &Group : Groups) {
3311b6b50a9SSilviu Baranga         // Don't perform more than a certain amount of comparisons.
3321b6b50a9SSilviu Baranga         // This should limit the cost of grouping the pointers to something
3331b6b50a9SSilviu Baranga         // reasonable.  If we do end up hitting this threshold, the algorithm
3341b6b50a9SSilviu Baranga         // will create separate groups for all remaining pointers.
3351b6b50a9SSilviu Baranga         if (TotalComparisons > MemoryCheckMergeThreshold)
3361b6b50a9SSilviu Baranga           break;
3371b6b50a9SSilviu Baranga 
3381b6b50a9SSilviu Baranga         TotalComparisons++;
3391b6b50a9SSilviu Baranga 
3401b6b50a9SSilviu Baranga         if (Group.addPointer(Pointer)) {
3411b6b50a9SSilviu Baranga           Merged = true;
3421b6b50a9SSilviu Baranga           break;
3431b6b50a9SSilviu Baranga         }
3441b6b50a9SSilviu Baranga       }
3451b6b50a9SSilviu Baranga 
3461b6b50a9SSilviu Baranga       if (!Merged)
3471b6b50a9SSilviu Baranga         // We couldn't add this pointer to any existing set or the threshold
3481b6b50a9SSilviu Baranga         // for the number of comparisons has been reached. Create a new group
3491b6b50a9SSilviu Baranga         // to hold the current pointer.
3501b6b50a9SSilviu Baranga         Groups.push_back(CheckingPtrGroup(Pointer, *this));
3511b6b50a9SSilviu Baranga     }
3521b6b50a9SSilviu Baranga 
3531b6b50a9SSilviu Baranga     // We've computed the grouped checks for this partition.
3541b6b50a9SSilviu Baranga     // Save the results and continue with the next one.
3551b6b50a9SSilviu Baranga     std::copy(Groups.begin(), Groups.end(), std::back_inserter(CheckingGroups));
3561b6b50a9SSilviu Baranga   }
3570456327cSAdam Nemet }
3580456327cSAdam Nemet 
359041e6debSAdam Nemet bool RuntimePointerChecking::arePointersInSamePartition(
360041e6debSAdam Nemet     const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
361041e6debSAdam Nemet     unsigned PtrIdx2) {
362041e6debSAdam Nemet   return (PtrToPartition[PtrIdx1] != -1 &&
363041e6debSAdam Nemet           PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
364041e6debSAdam Nemet }
365041e6debSAdam Nemet 
366651a5a24SAdam Nemet bool RuntimePointerChecking::needsChecking(unsigned I, unsigned J) const {
3679f7dedc3SAdam Nemet   const PointerInfo &PointerI = Pointers[I];
3689f7dedc3SAdam Nemet   const PointerInfo &PointerJ = Pointers[J];
3699f7dedc3SAdam Nemet 
370a8945b77SAdam Nemet   // No need to check if two readonly pointers intersect.
3719f7dedc3SAdam Nemet   if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
372a8945b77SAdam Nemet     return false;
373a8945b77SAdam Nemet 
374a8945b77SAdam Nemet   // Only need to check pointers between two different dependency sets.
3759f7dedc3SAdam Nemet   if (PointerI.DependencySetId == PointerJ.DependencySetId)
376a8945b77SAdam Nemet     return false;
377a8945b77SAdam Nemet 
378a8945b77SAdam Nemet   // Only need to check pointers in the same alias set.
3799f7dedc3SAdam Nemet   if (PointerI.AliasSetId != PointerJ.AliasSetId)
380a8945b77SAdam Nemet     return false;
381a8945b77SAdam Nemet 
382a8945b77SAdam Nemet   return true;
383a8945b77SAdam Nemet }
384a8945b77SAdam Nemet 
38554f0b83eSAdam Nemet void RuntimePointerChecking::printChecks(
38654f0b83eSAdam Nemet     raw_ostream &OS, const SmallVectorImpl<PointerCheck> &Checks,
38754f0b83eSAdam Nemet     unsigned Depth) const {
38854f0b83eSAdam Nemet   unsigned N = 0;
38954f0b83eSAdam Nemet   for (const auto &Check : Checks) {
39054f0b83eSAdam Nemet     const auto &First = Check.first->Members, &Second = Check.second->Members;
39154f0b83eSAdam Nemet 
39254f0b83eSAdam Nemet     OS.indent(Depth) << "Check " << N++ << ":\n";
39354f0b83eSAdam Nemet 
39454f0b83eSAdam Nemet     OS.indent(Depth + 2) << "Comparing group (" << Check.first << "):\n";
39554f0b83eSAdam Nemet     for (unsigned K = 0; K < First.size(); ++K)
39654f0b83eSAdam Nemet       OS.indent(Depth + 2) << *Pointers[First[K]].PointerValue << "\n";
39754f0b83eSAdam Nemet 
39854f0b83eSAdam Nemet     OS.indent(Depth + 2) << "Against group (" << Check.second << "):\n";
39954f0b83eSAdam Nemet     for (unsigned K = 0; K < Second.size(); ++K)
40054f0b83eSAdam Nemet       OS.indent(Depth + 2) << *Pointers[Second[K]].PointerValue << "\n";
40154f0b83eSAdam Nemet   }
40254f0b83eSAdam Nemet }
40354f0b83eSAdam Nemet 
4043a91e947SAdam Nemet void RuntimePointerChecking::print(raw_ostream &OS, unsigned Depth) const {
405e91cc6efSAdam Nemet 
406e91cc6efSAdam Nemet   OS.indent(Depth) << "Run-time memory checks:\n";
40715840393SAdam Nemet   printChecks(OS, Checks, Depth);
4081b6b50a9SSilviu Baranga 
4091b6b50a9SSilviu Baranga   OS.indent(Depth) << "Grouped accesses:\n";
4101b6b50a9SSilviu Baranga   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
41154f0b83eSAdam Nemet     const auto &CG = CheckingGroups[I];
41254f0b83eSAdam Nemet 
41354f0b83eSAdam Nemet     OS.indent(Depth + 2) << "Group " << &CG << ":\n";
41454f0b83eSAdam Nemet     OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High
41554f0b83eSAdam Nemet                          << ")\n";
41654f0b83eSAdam Nemet     for (unsigned J = 0; J < CG.Members.size(); ++J) {
41754f0b83eSAdam Nemet       OS.indent(Depth + 6) << "Member: " << *Pointers[CG.Members[J]].Expr
4181b6b50a9SSilviu Baranga                            << "\n";
4191b6b50a9SSilviu Baranga     }
420e91cc6efSAdam Nemet   }
421e91cc6efSAdam Nemet }
422e91cc6efSAdam Nemet 
4230456327cSAdam Nemet namespace {
4240456327cSAdam Nemet /// \brief Analyses memory accesses in a loop.
4250456327cSAdam Nemet ///
4260456327cSAdam Nemet /// Checks whether run time pointer checks are needed and builds sets for data
4270456327cSAdam Nemet /// dependence checking.
4280456327cSAdam Nemet class AccessAnalysis {
4290456327cSAdam Nemet public:
4300456327cSAdam Nemet   /// \brief Read or write access location.
4310456327cSAdam Nemet   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
4320456327cSAdam Nemet   typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
4330456327cSAdam Nemet 
434e2b885c4SAdam Nemet   AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA, LoopInfo *LI,
4359cd9a7e3SSilviu Baranga                  MemoryDepChecker::DepCandidates &DA,
4369cd9a7e3SSilviu Baranga                  PredicatedScalarEvolution &PSE)
437e3c0534bSSilviu Baranga       : DL(Dl), AST(*AA), LI(LI), DepCands(DA), IsRTCheckAnalysisNeeded(false),
4389cd9a7e3SSilviu Baranga         PSE(PSE) {}
4390456327cSAdam Nemet 
4400456327cSAdam Nemet   /// \brief Register a load  and whether it is only read from.
441ac80dc75SChandler Carruth   void addLoad(MemoryLocation &Loc, bool IsReadOnly) {
4420456327cSAdam Nemet     Value *Ptr = const_cast<Value*>(Loc.Ptr);
443ecbd1682SChandler Carruth     AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
4440456327cSAdam Nemet     Accesses.insert(MemAccessInfo(Ptr, false));
4450456327cSAdam Nemet     if (IsReadOnly)
4460456327cSAdam Nemet       ReadOnlyPtr.insert(Ptr);
4470456327cSAdam Nemet   }
4480456327cSAdam Nemet 
4490456327cSAdam Nemet   /// \brief Register a store.
450ac80dc75SChandler Carruth   void addStore(MemoryLocation &Loc) {
4510456327cSAdam Nemet     Value *Ptr = const_cast<Value*>(Loc.Ptr);
452ecbd1682SChandler Carruth     AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
4530456327cSAdam Nemet     Accesses.insert(MemAccessInfo(Ptr, true));
4540456327cSAdam Nemet   }
4550456327cSAdam Nemet 
4560456327cSAdam Nemet   /// \brief Check whether we can check the pointers at runtime for
457ee61474aSAdam Nemet   /// non-intersection.
458ee61474aSAdam Nemet   ///
459ee61474aSAdam Nemet   /// Returns true if we need no check or if we do and we can generate them
460ee61474aSAdam Nemet   /// (i.e. the pointers have computable bounds).
4617cdebac0SAdam Nemet   bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE,
4627cdebac0SAdam Nemet                        Loop *TheLoop, const ValueToValueMap &Strides,
4630456327cSAdam Nemet                        bool ShouldCheckStride = false);
4640456327cSAdam Nemet 
4650456327cSAdam Nemet   /// \brief Goes over all memory accesses, checks whether a RT check is needed
4660456327cSAdam Nemet   /// and builds sets of dependent accesses.
4670456327cSAdam Nemet   void buildDependenceSets() {
4680456327cSAdam Nemet     processMemAccesses();
4690456327cSAdam Nemet   }
4700456327cSAdam Nemet 
4715dc3b2cfSAdam Nemet   /// \brief Initial processing of memory accesses determined that we need to
4725dc3b2cfSAdam Nemet   /// perform dependency checking.
4735dc3b2cfSAdam Nemet   ///
4745dc3b2cfSAdam Nemet   /// Note that this can later be cleared if we retry memcheck analysis without
4755dc3b2cfSAdam Nemet   /// dependency checking (i.e. ShouldRetryWithRuntimeCheck).
4760456327cSAdam Nemet   bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
477df3dc5b9SAdam Nemet 
478df3dc5b9SAdam Nemet   /// We decided that no dependence analysis would be used.  Reset the state.
479df3dc5b9SAdam Nemet   void resetDepChecks(MemoryDepChecker &DepChecker) {
480df3dc5b9SAdam Nemet     CheckDeps.clear();
481a2df750fSAdam Nemet     DepChecker.clearDependences();
482df3dc5b9SAdam Nemet   }
4830456327cSAdam Nemet 
4840456327cSAdam Nemet   MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
4850456327cSAdam Nemet 
4860456327cSAdam Nemet private:
4870456327cSAdam Nemet   typedef SetVector<MemAccessInfo> PtrAccessSet;
4880456327cSAdam Nemet 
4890456327cSAdam Nemet   /// \brief Go over all memory access and check whether runtime pointer checks
490b41d2d3fSAdam Nemet   /// are needed and build sets of dependency check candidates.
4910456327cSAdam Nemet   void processMemAccesses();
4920456327cSAdam Nemet 
4930456327cSAdam Nemet   /// Set of all accesses.
4940456327cSAdam Nemet   PtrAccessSet Accesses;
4950456327cSAdam Nemet 
496a28d91d8SMehdi Amini   const DataLayout &DL;
497a28d91d8SMehdi Amini 
4980456327cSAdam Nemet   /// Set of accesses that need a further dependence check.
4990456327cSAdam Nemet   MemAccessInfoSet CheckDeps;
5000456327cSAdam Nemet 
5010456327cSAdam Nemet   /// Set of pointers that are read only.
5020456327cSAdam Nemet   SmallPtrSet<Value*, 16> ReadOnlyPtr;
5030456327cSAdam Nemet 
5040456327cSAdam Nemet   /// An alias set tracker to partition the access set by underlying object and
5050456327cSAdam Nemet   //intrinsic property (such as TBAA metadata).
5060456327cSAdam Nemet   AliasSetTracker AST;
5070456327cSAdam Nemet 
508e2b885c4SAdam Nemet   LoopInfo *LI;
509e2b885c4SAdam Nemet 
5100456327cSAdam Nemet   /// Sets of potentially dependent accesses - members of one set share an
5110456327cSAdam Nemet   /// underlying pointer. The set "CheckDeps" identfies which sets really need a
5120456327cSAdam Nemet   /// dependence check.
513dee666bcSAdam Nemet   MemoryDepChecker::DepCandidates &DepCands;
5140456327cSAdam Nemet 
5155dc3b2cfSAdam Nemet   /// \brief Initial processing of memory accesses determined that we may need
5165dc3b2cfSAdam Nemet   /// to add memchecks.  Perform the analysis to determine the necessary checks.
5175dc3b2cfSAdam Nemet   ///
5185dc3b2cfSAdam Nemet   /// Note that, this is different from isDependencyCheckNeeded.  When we retry
5195dc3b2cfSAdam Nemet   /// memcheck analysis without dependency checking
5205dc3b2cfSAdam Nemet   /// (i.e. ShouldRetryWithRuntimeCheck), isDependencyCheckNeeded is cleared
5215dc3b2cfSAdam Nemet   /// while this remains set if we have potentially dependent accesses.
5225dc3b2cfSAdam Nemet   bool IsRTCheckAnalysisNeeded;
523e3c0534bSSilviu Baranga 
524e3c0534bSSilviu Baranga   /// The SCEV predicate containing all the SCEV-related assumptions.
5259cd9a7e3SSilviu Baranga   PredicatedScalarEvolution &PSE;
5260456327cSAdam Nemet };
5270456327cSAdam Nemet 
5280456327cSAdam Nemet } // end anonymous namespace
5290456327cSAdam Nemet 
5300456327cSAdam Nemet /// \brief Check whether a pointer can participate in a runtime bounds check.
5319cd9a7e3SSilviu Baranga static bool hasComputableBounds(PredicatedScalarEvolution &PSE,
532e3c0534bSSilviu Baranga                                 const ValueToValueMap &Strides, Value *Ptr,
5339cd9a7e3SSilviu Baranga                                 Loop *L) {
5349cd9a7e3SSilviu Baranga   const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
535279784ffSAdam Nemet 
536279784ffSAdam Nemet   // The bounds for loop-invariant pointer is trivial.
537279784ffSAdam Nemet   if (PSE.getSE()->isLoopInvariant(PtrScev, L))
538279784ffSAdam Nemet     return true;
539279784ffSAdam Nemet 
5400456327cSAdam Nemet   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
5410456327cSAdam Nemet   if (!AR)
5420456327cSAdam Nemet     return false;
5430456327cSAdam Nemet 
5440456327cSAdam Nemet   return AR->isAffine();
5450456327cSAdam Nemet }
5460456327cSAdam Nemet 
5477cdebac0SAdam Nemet bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
5487cdebac0SAdam Nemet                                      ScalarEvolution *SE, Loop *TheLoop,
5497cdebac0SAdam Nemet                                      const ValueToValueMap &StridesMap,
5507cdebac0SAdam Nemet                                      bool ShouldCheckStride) {
5510456327cSAdam Nemet   // Find pointers with computable bounds. We are going to use this information
5520456327cSAdam Nemet   // to place a runtime bound check.
5530456327cSAdam Nemet   bool CanDoRT = true;
5540456327cSAdam Nemet 
555ee61474aSAdam Nemet   bool NeedRTCheck = false;
5565dc3b2cfSAdam Nemet   if (!IsRTCheckAnalysisNeeded) return true;
55798a13719SSilviu Baranga 
5580456327cSAdam Nemet   bool IsDepCheckNeeded = isDependencyCheckNeeded();
5590456327cSAdam Nemet 
5600456327cSAdam Nemet   // We assign a consecutive id to access from different alias sets.
5610456327cSAdam Nemet   // Accesses between different groups doesn't need to be checked.
5620456327cSAdam Nemet   unsigned ASId = 1;
5630456327cSAdam Nemet   for (auto &AS : AST) {
564424edc6cSAdam Nemet     int NumReadPtrChecks = 0;
565424edc6cSAdam Nemet     int NumWritePtrChecks = 0;
566424edc6cSAdam Nemet 
5670456327cSAdam Nemet     // We assign consecutive id to access from different dependence sets.
5680456327cSAdam Nemet     // Accesses within the same set don't need a runtime check.
5690456327cSAdam Nemet     unsigned RunningDepId = 1;
5700456327cSAdam Nemet     DenseMap<Value *, unsigned> DepSetId;
5710456327cSAdam Nemet 
5720456327cSAdam Nemet     for (auto A : AS) {
5730456327cSAdam Nemet       Value *Ptr = A.getValue();
5740456327cSAdam Nemet       bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
5750456327cSAdam Nemet       MemAccessInfo Access(Ptr, IsWrite);
5760456327cSAdam Nemet 
577424edc6cSAdam Nemet       if (IsWrite)
578424edc6cSAdam Nemet         ++NumWritePtrChecks;
579424edc6cSAdam Nemet       else
580424edc6cSAdam Nemet         ++NumReadPtrChecks;
581424edc6cSAdam Nemet 
5829cd9a7e3SSilviu Baranga       if (hasComputableBounds(PSE, StridesMap, Ptr, TheLoop) &&
583a28d91d8SMehdi Amini           // When we run after a failing dependency check we have to make sure
584a28d91d8SMehdi Amini           // we don't have wrapping pointers.
5850456327cSAdam Nemet           (!ShouldCheckStride ||
5869cd9a7e3SSilviu Baranga            isStridedPtr(PSE, Ptr, TheLoop, StridesMap) == 1)) {
5870456327cSAdam Nemet         // The id of the dependence set.
5880456327cSAdam Nemet         unsigned DepId;
5890456327cSAdam Nemet 
5900456327cSAdam Nemet         if (IsDepCheckNeeded) {
5910456327cSAdam Nemet           Value *Leader = DepCands.getLeaderValue(Access).getPointer();
5920456327cSAdam Nemet           unsigned &LeaderId = DepSetId[Leader];
5930456327cSAdam Nemet           if (!LeaderId)
5940456327cSAdam Nemet             LeaderId = RunningDepId++;
5950456327cSAdam Nemet           DepId = LeaderId;
5960456327cSAdam Nemet         } else
5970456327cSAdam Nemet           // Each access has its own dependence set.
5980456327cSAdam Nemet           DepId = RunningDepId++;
5990456327cSAdam Nemet 
6009cd9a7e3SSilviu Baranga         RtCheck.insert(TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap, PSE);
6010456327cSAdam Nemet 
602339f42b3SAdam Nemet         DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
6030456327cSAdam Nemet       } else {
604f10ca278SAdam Nemet         DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" << *Ptr << '\n');
6050456327cSAdam Nemet         CanDoRT = false;
6060456327cSAdam Nemet       }
6070456327cSAdam Nemet     }
6080456327cSAdam Nemet 
609424edc6cSAdam Nemet     // If we have at least two writes or one write and a read then we need to
610424edc6cSAdam Nemet     // check them.  But there is no need to checks if there is only one
611424edc6cSAdam Nemet     // dependence set for this alias set.
612424edc6cSAdam Nemet     //
613424edc6cSAdam Nemet     // Note that this function computes CanDoRT and NeedRTCheck independently.
614424edc6cSAdam Nemet     // For example CanDoRT=false, NeedRTCheck=false means that we have a pointer
615424edc6cSAdam Nemet     // for which we couldn't find the bounds but we don't actually need to emit
616424edc6cSAdam Nemet     // any checks so it does not matter.
617424edc6cSAdam Nemet     if (!(IsDepCheckNeeded && CanDoRT && RunningDepId == 2))
618424edc6cSAdam Nemet       NeedRTCheck |= (NumWritePtrChecks >= 2 || (NumReadPtrChecks >= 1 &&
619424edc6cSAdam Nemet                                                  NumWritePtrChecks >= 1));
620424edc6cSAdam Nemet 
6210456327cSAdam Nemet     ++ASId;
6220456327cSAdam Nemet   }
6230456327cSAdam Nemet 
6240456327cSAdam Nemet   // If the pointers that we would use for the bounds comparison have different
6250456327cSAdam Nemet   // address spaces, assume the values aren't directly comparable, so we can't
6260456327cSAdam Nemet   // use them for the runtime check. We also have to assume they could
6270456327cSAdam Nemet   // overlap. In the future there should be metadata for whether address spaces
6280456327cSAdam Nemet   // are disjoint.
6290456327cSAdam Nemet   unsigned NumPointers = RtCheck.Pointers.size();
6300456327cSAdam Nemet   for (unsigned i = 0; i < NumPointers; ++i) {
6310456327cSAdam Nemet     for (unsigned j = i + 1; j < NumPointers; ++j) {
6320456327cSAdam Nemet       // Only need to check pointers between two different dependency sets.
6339f7dedc3SAdam Nemet       if (RtCheck.Pointers[i].DependencySetId ==
6349f7dedc3SAdam Nemet           RtCheck.Pointers[j].DependencySetId)
6350456327cSAdam Nemet        continue;
6360456327cSAdam Nemet       // Only need to check pointers in the same alias set.
6379f7dedc3SAdam Nemet       if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
6380456327cSAdam Nemet         continue;
6390456327cSAdam Nemet 
6409f7dedc3SAdam Nemet       Value *PtrI = RtCheck.Pointers[i].PointerValue;
6419f7dedc3SAdam Nemet       Value *PtrJ = RtCheck.Pointers[j].PointerValue;
6420456327cSAdam Nemet 
6430456327cSAdam Nemet       unsigned ASi = PtrI->getType()->getPointerAddressSpace();
6440456327cSAdam Nemet       unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
6450456327cSAdam Nemet       if (ASi != ASj) {
646339f42b3SAdam Nemet         DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
6470456327cSAdam Nemet                        " different address spaces\n");
6480456327cSAdam Nemet         return false;
6490456327cSAdam Nemet       }
6500456327cSAdam Nemet     }
6510456327cSAdam Nemet   }
6520456327cSAdam Nemet 
6531b6b50a9SSilviu Baranga   if (NeedRTCheck && CanDoRT)
65415840393SAdam Nemet     RtCheck.generateChecks(DepCands, IsDepCheckNeeded);
6551b6b50a9SSilviu Baranga 
656155e8741SAdam Nemet   DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks()
657ee61474aSAdam Nemet                << " pointer comparisons.\n");
658ee61474aSAdam Nemet 
659ee61474aSAdam Nemet   RtCheck.Need = NeedRTCheck;
660ee61474aSAdam Nemet 
661ee61474aSAdam Nemet   bool CanDoRTIfNeeded = !NeedRTCheck || CanDoRT;
662ee61474aSAdam Nemet   if (!CanDoRTIfNeeded)
663ee61474aSAdam Nemet     RtCheck.reset();
664ee61474aSAdam Nemet   return CanDoRTIfNeeded;
6650456327cSAdam Nemet }
6660456327cSAdam Nemet 
6670456327cSAdam Nemet void AccessAnalysis::processMemAccesses() {
6680456327cSAdam Nemet   // We process the set twice: first we process read-write pointers, last we
6690456327cSAdam Nemet   // process read-only pointers. This allows us to skip dependence tests for
6700456327cSAdam Nemet   // read-only pointers.
6710456327cSAdam Nemet 
672339f42b3SAdam Nemet   DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
6730456327cSAdam Nemet   DEBUG(dbgs() << "  AST: "; AST.dump());
6749c926579SAdam Nemet   DEBUG(dbgs() << "LAA:   Accesses(" << Accesses.size() << "):\n");
6750456327cSAdam Nemet   DEBUG({
6760456327cSAdam Nemet     for (auto A : Accesses)
6770456327cSAdam Nemet       dbgs() << "\t" << *A.getPointer() << " (" <<
6780456327cSAdam Nemet                 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
6790456327cSAdam Nemet                                          "read-only" : "read")) << ")\n";
6800456327cSAdam Nemet   });
6810456327cSAdam Nemet 
6820456327cSAdam Nemet   // The AliasSetTracker has nicely partitioned our pointers by metadata
6830456327cSAdam Nemet   // compatibility and potential for underlying-object overlap. As a result, we
6840456327cSAdam Nemet   // only need to check for potential pointer dependencies within each alias
6850456327cSAdam Nemet   // set.
6860456327cSAdam Nemet   for (auto &AS : AST) {
6870456327cSAdam Nemet     // Note that both the alias-set tracker and the alias sets themselves used
6880456327cSAdam Nemet     // linked lists internally and so the iteration order here is deterministic
6890456327cSAdam Nemet     // (matching the original instruction order within each set).
6900456327cSAdam Nemet 
6910456327cSAdam Nemet     bool SetHasWrite = false;
6920456327cSAdam Nemet 
6930456327cSAdam Nemet     // Map of pointers to last access encountered.
6940456327cSAdam Nemet     typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
6950456327cSAdam Nemet     UnderlyingObjToAccessMap ObjToLastAccess;
6960456327cSAdam Nemet 
6970456327cSAdam Nemet     // Set of access to check after all writes have been processed.
6980456327cSAdam Nemet     PtrAccessSet DeferredAccesses;
6990456327cSAdam Nemet 
7000456327cSAdam Nemet     // Iterate over each alias set twice, once to process read/write pointers,
7010456327cSAdam Nemet     // and then to process read-only pointers.
7020456327cSAdam Nemet     for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
7030456327cSAdam Nemet       bool UseDeferred = SetIteration > 0;
7040456327cSAdam Nemet       PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
7050456327cSAdam Nemet 
7060456327cSAdam Nemet       for (auto AV : AS) {
7070456327cSAdam Nemet         Value *Ptr = AV.getValue();
7080456327cSAdam Nemet 
7090456327cSAdam Nemet         // For a single memory access in AliasSetTracker, Accesses may contain
7100456327cSAdam Nemet         // both read and write, and they both need to be handled for CheckDeps.
7110456327cSAdam Nemet         for (auto AC : S) {
7120456327cSAdam Nemet           if (AC.getPointer() != Ptr)
7130456327cSAdam Nemet             continue;
7140456327cSAdam Nemet 
7150456327cSAdam Nemet           bool IsWrite = AC.getInt();
7160456327cSAdam Nemet 
7170456327cSAdam Nemet           // If we're using the deferred access set, then it contains only
7180456327cSAdam Nemet           // reads.
7190456327cSAdam Nemet           bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
7200456327cSAdam Nemet           if (UseDeferred && !IsReadOnlyPtr)
7210456327cSAdam Nemet             continue;
7220456327cSAdam Nemet           // Otherwise, the pointer must be in the PtrAccessSet, either as a
7230456327cSAdam Nemet           // read or a write.
7240456327cSAdam Nemet           assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
7250456327cSAdam Nemet                   S.count(MemAccessInfo(Ptr, false))) &&
7260456327cSAdam Nemet                  "Alias-set pointer not in the access set?");
7270456327cSAdam Nemet 
7280456327cSAdam Nemet           MemAccessInfo Access(Ptr, IsWrite);
7290456327cSAdam Nemet           DepCands.insert(Access);
7300456327cSAdam Nemet 
7310456327cSAdam Nemet           // Memorize read-only pointers for later processing and skip them in
7320456327cSAdam Nemet           // the first round (they need to be checked after we have seen all
7330456327cSAdam Nemet           // write pointers). Note: we also mark pointer that are not
7340456327cSAdam Nemet           // consecutive as "read-only" pointers (so that we check
7350456327cSAdam Nemet           // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
7360456327cSAdam Nemet           if (!UseDeferred && IsReadOnlyPtr) {
7370456327cSAdam Nemet             DeferredAccesses.insert(Access);
7380456327cSAdam Nemet             continue;
7390456327cSAdam Nemet           }
7400456327cSAdam Nemet 
7410456327cSAdam Nemet           // If this is a write - check other reads and writes for conflicts. If
7420456327cSAdam Nemet           // this is a read only check other writes for conflicts (but only if
7430456327cSAdam Nemet           // there is no other write to the ptr - this is an optimization to
7440456327cSAdam Nemet           // catch "a[i] = a[i] + " without having to do a dependence check).
7450456327cSAdam Nemet           if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
7460456327cSAdam Nemet             CheckDeps.insert(Access);
7475dc3b2cfSAdam Nemet             IsRTCheckAnalysisNeeded = true;
7480456327cSAdam Nemet           }
7490456327cSAdam Nemet 
7500456327cSAdam Nemet           if (IsWrite)
7510456327cSAdam Nemet             SetHasWrite = true;
7520456327cSAdam Nemet 
7530456327cSAdam Nemet           // Create sets of pointers connected by a shared alias set and
7540456327cSAdam Nemet           // underlying object.
7550456327cSAdam Nemet           typedef SmallVector<Value *, 16> ValueVector;
7560456327cSAdam Nemet           ValueVector TempObjects;
757e2b885c4SAdam Nemet 
758e2b885c4SAdam Nemet           GetUnderlyingObjects(Ptr, TempObjects, DL, LI);
759e2b885c4SAdam Nemet           DEBUG(dbgs() << "Underlying objects for pointer " << *Ptr << "\n");
7600456327cSAdam Nemet           for (Value *UnderlyingObj : TempObjects) {
761afd13519SMehdi Amini             // nullptr never alias, don't join sets for pointer that have "null"
762afd13519SMehdi Amini             // in their UnderlyingObjects list.
763afd13519SMehdi Amini             if (isa<ConstantPointerNull>(UnderlyingObj))
764afd13519SMehdi Amini               continue;
765afd13519SMehdi Amini 
7660456327cSAdam Nemet             UnderlyingObjToAccessMap::iterator Prev =
7670456327cSAdam Nemet                 ObjToLastAccess.find(UnderlyingObj);
7680456327cSAdam Nemet             if (Prev != ObjToLastAccess.end())
7690456327cSAdam Nemet               DepCands.unionSets(Access, Prev->second);
7700456327cSAdam Nemet 
7710456327cSAdam Nemet             ObjToLastAccess[UnderlyingObj] = Access;
772e2b885c4SAdam Nemet             DEBUG(dbgs() << "  " << *UnderlyingObj << "\n");
7730456327cSAdam Nemet           }
7740456327cSAdam Nemet         }
7750456327cSAdam Nemet       }
7760456327cSAdam Nemet     }
7770456327cSAdam Nemet   }
7780456327cSAdam Nemet }
7790456327cSAdam Nemet 
7800456327cSAdam Nemet static bool isInBoundsGep(Value *Ptr) {
7810456327cSAdam Nemet   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
7820456327cSAdam Nemet     return GEP->isInBounds();
7830456327cSAdam Nemet   return false;
7840456327cSAdam Nemet }
7850456327cSAdam Nemet 
786c4866d29SAdam Nemet /// \brief Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
787c4866d29SAdam Nemet /// i.e. monotonically increasing/decreasing.
788c4866d29SAdam Nemet static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
789ea63a7f5SSilviu Baranga                            PredicatedScalarEvolution &PSE, const Loop *L) {
790c4866d29SAdam Nemet   // FIXME: This should probably only return true for NUW.
791c4866d29SAdam Nemet   if (AR->getNoWrapFlags(SCEV::NoWrapMask))
792c4866d29SAdam Nemet     return true;
793c4866d29SAdam Nemet 
794c4866d29SAdam Nemet   // Scalar evolution does not propagate the non-wrapping flags to values that
795c4866d29SAdam Nemet   // are derived from a non-wrapping induction variable because non-wrapping
796c4866d29SAdam Nemet   // could be flow-sensitive.
797c4866d29SAdam Nemet   //
798c4866d29SAdam Nemet   // Look through the potentially overflowing instruction to try to prove
799c4866d29SAdam Nemet   // non-wrapping for the *specific* value of Ptr.
800c4866d29SAdam Nemet 
801c4866d29SAdam Nemet   // The arithmetic implied by an inbounds GEP can't overflow.
802c4866d29SAdam Nemet   auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
803c4866d29SAdam Nemet   if (!GEP || !GEP->isInBounds())
804c4866d29SAdam Nemet     return false;
805c4866d29SAdam Nemet 
806c4866d29SAdam Nemet   // Make sure there is only one non-const index and analyze that.
807c4866d29SAdam Nemet   Value *NonConstIndex = nullptr;
808c4866d29SAdam Nemet   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
809c4866d29SAdam Nemet     if (!isa<ConstantInt>(*Index)) {
810c4866d29SAdam Nemet       if (NonConstIndex)
811c4866d29SAdam Nemet         return false;
812c4866d29SAdam Nemet       NonConstIndex = *Index;
813c4866d29SAdam Nemet     }
814c4866d29SAdam Nemet   if (!NonConstIndex)
815c4866d29SAdam Nemet     // The recurrence is on the pointer, ignore for now.
816c4866d29SAdam Nemet     return false;
817c4866d29SAdam Nemet 
818c4866d29SAdam Nemet   // The index in GEP is signed.  It is non-wrapping if it's derived from a NSW
819c4866d29SAdam Nemet   // AddRec using a NSW operation.
820c4866d29SAdam Nemet   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
821c4866d29SAdam Nemet     if (OBO->hasNoSignedWrap() &&
822c4866d29SAdam Nemet         // Assume constant for other the operand so that the AddRec can be
823c4866d29SAdam Nemet         // easily found.
824c4866d29SAdam Nemet         isa<ConstantInt>(OBO->getOperand(1))) {
825ea63a7f5SSilviu Baranga       auto *OpScev = PSE.getSCEV(OBO->getOperand(0));
826c4866d29SAdam Nemet 
827c4866d29SAdam Nemet       if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
828c4866d29SAdam Nemet         return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
829c4866d29SAdam Nemet     }
830c4866d29SAdam Nemet 
831c4866d29SAdam Nemet   return false;
832c4866d29SAdam Nemet }
833c4866d29SAdam Nemet 
8340456327cSAdam Nemet /// \brief Check whether the access through \p Ptr has a constant stride.
8359cd9a7e3SSilviu Baranga int llvm::isStridedPtr(PredicatedScalarEvolution &PSE, Value *Ptr,
836ea63a7f5SSilviu Baranga                        const Loop *Lp, const ValueToValueMap &StridesMap,
837ea63a7f5SSilviu Baranga                        bool Assume) {
838e3dcce97SCraig Topper   Type *Ty = Ptr->getType();
8390456327cSAdam Nemet   assert(Ty->isPointerTy() && "Unexpected non-ptr");
8400456327cSAdam Nemet 
8410456327cSAdam Nemet   // Make sure that the pointer does not point to aggregate types.
842e3dcce97SCraig Topper   auto *PtrTy = cast<PointerType>(Ty);
8430456327cSAdam Nemet   if (PtrTy->getElementType()->isAggregateType()) {
844ea63a7f5SSilviu Baranga     DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type" << *Ptr
845ea63a7f5SSilviu Baranga                  << "\n");
8460456327cSAdam Nemet     return 0;
8470456327cSAdam Nemet   }
8480456327cSAdam Nemet 
8499cd9a7e3SSilviu Baranga   const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr);
8500456327cSAdam Nemet 
8510456327cSAdam Nemet   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
852ea63a7f5SSilviu Baranga   if (Assume && !AR)
853d68ed854SSilviu Baranga     AR = PSE.getAsAddRec(Ptr);
854ea63a7f5SSilviu Baranga 
8550456327cSAdam Nemet   if (!AR) {
856ea63a7f5SSilviu Baranga     DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer " << *Ptr
857ea63a7f5SSilviu Baranga                  << " SCEV: " << *PtrScev << "\n");
8580456327cSAdam Nemet     return 0;
8590456327cSAdam Nemet   }
8600456327cSAdam Nemet 
8610456327cSAdam Nemet   // The accesss function must stride over the innermost loop.
8620456327cSAdam Nemet   if (Lp != AR->getLoop()) {
863339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
864ea63a7f5SSilviu Baranga           *Ptr << " SCEV: " << *AR << "\n");
865a02ce98bSKyle Butt     return 0;
8660456327cSAdam Nemet   }
8670456327cSAdam Nemet 
8680456327cSAdam Nemet   // The address calculation must not wrap. Otherwise, a dependence could be
8690456327cSAdam Nemet   // inverted.
8700456327cSAdam Nemet   // An inbounds getelementptr that is a AddRec with a unit stride
8710456327cSAdam Nemet   // cannot wrap per definition. The unit stride requirement is checked later.
8720456327cSAdam Nemet   // An getelementptr without an inbounds attribute and unit stride would have
8730456327cSAdam Nemet   // to access the pointer value "0" which is undefined behavior in address
8740456327cSAdam Nemet   // space 0, therefore we can also vectorize this case.
8750456327cSAdam Nemet   bool IsInBoundsGEP = isInBoundsGep(Ptr);
876ea63a7f5SSilviu Baranga   bool IsNoWrapAddRec =
877ea63a7f5SSilviu Baranga       PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW) ||
878ea63a7f5SSilviu Baranga       isNoWrapAddRec(Ptr, AR, PSE, Lp);
8790456327cSAdam Nemet   bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
8800456327cSAdam Nemet   if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
881ea63a7f5SSilviu Baranga     if (Assume) {
882ea63a7f5SSilviu Baranga       PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
883ea63a7f5SSilviu Baranga       IsNoWrapAddRec = true;
884ea63a7f5SSilviu Baranga       DEBUG(dbgs() << "LAA: Pointer may wrap in the address space:\n"
885ea63a7f5SSilviu Baranga                    << "LAA:   Pointer: " << *Ptr << "\n"
886ea63a7f5SSilviu Baranga                    << "LAA:   SCEV: " << *AR << "\n"
887ea63a7f5SSilviu Baranga                    << "LAA:   Added an overflow assumption\n");
888ea63a7f5SSilviu Baranga     } else {
889339f42b3SAdam Nemet       DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
890ea63a7f5SSilviu Baranga                    << *Ptr << " SCEV: " << *AR << "\n");
8910456327cSAdam Nemet       return 0;
8920456327cSAdam Nemet     }
893ea63a7f5SSilviu Baranga   }
8940456327cSAdam Nemet 
8950456327cSAdam Nemet   // Check the step is constant.
8969cd9a7e3SSilviu Baranga   const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
8970456327cSAdam Nemet 
898943befedSAdam Nemet   // Calculate the pointer stride and check if it is constant.
8990456327cSAdam Nemet   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
9000456327cSAdam Nemet   if (!C) {
901339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
902ea63a7f5SSilviu Baranga           " SCEV: " << *AR << "\n");
9030456327cSAdam Nemet     return 0;
9040456327cSAdam Nemet   }
9050456327cSAdam Nemet 
906a28d91d8SMehdi Amini   auto &DL = Lp->getHeader()->getModule()->getDataLayout();
907a28d91d8SMehdi Amini   int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
9080de2feceSSanjoy Das   const APInt &APStepVal = C->getAPInt();
9090456327cSAdam Nemet 
9100456327cSAdam Nemet   // Huge step value - give up.
9110456327cSAdam Nemet   if (APStepVal.getBitWidth() > 64)
9120456327cSAdam Nemet     return 0;
9130456327cSAdam Nemet 
9140456327cSAdam Nemet   int64_t StepVal = APStepVal.getSExtValue();
9150456327cSAdam Nemet 
9160456327cSAdam Nemet   // Strided access.
9170456327cSAdam Nemet   int64_t Stride = StepVal / Size;
9180456327cSAdam Nemet   int64_t Rem = StepVal % Size;
9190456327cSAdam Nemet   if (Rem)
9200456327cSAdam Nemet     return 0;
9210456327cSAdam Nemet 
9220456327cSAdam Nemet   // If the SCEV could wrap but we have an inbounds gep with a unit stride we
9230456327cSAdam Nemet   // know we can't "wrap around the address space". In case of address space
9240456327cSAdam Nemet   // zero we know that this won't happen without triggering undefined behavior.
9250456327cSAdam Nemet   if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
926ea63a7f5SSilviu Baranga       Stride != 1 && Stride != -1) {
927ea63a7f5SSilviu Baranga     if (Assume) {
928ea63a7f5SSilviu Baranga       // We can avoid this case by adding a run-time check.
929ea63a7f5SSilviu Baranga       DEBUG(dbgs() << "LAA: Non unit strided pointer which is not either "
930ea63a7f5SSilviu Baranga                    << "inbouds or in address space 0 may wrap:\n"
931ea63a7f5SSilviu Baranga                    << "LAA:   Pointer: " << *Ptr << "\n"
932ea63a7f5SSilviu Baranga                    << "LAA:   SCEV: " << *AR << "\n"
933ea63a7f5SSilviu Baranga                    << "LAA:   Added an overflow assumption\n");
934ea63a7f5SSilviu Baranga       PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
935ea63a7f5SSilviu Baranga     } else
9360456327cSAdam Nemet       return 0;
937ea63a7f5SSilviu Baranga   }
9380456327cSAdam Nemet 
9390456327cSAdam Nemet   return Stride;
9400456327cSAdam Nemet }
9410456327cSAdam Nemet 
942f1c00a22SHaicheng Wu /// Take the pointer operand from the Load/Store instruction.
943f1c00a22SHaicheng Wu /// Returns NULL if this is not a valid Load/Store instruction.
944f1c00a22SHaicheng Wu static Value *getPointerOperand(Value *I) {
945f1c00a22SHaicheng Wu   if (LoadInst *LI = dyn_cast<LoadInst>(I))
946f1c00a22SHaicheng Wu     return LI->getPointerOperand();
947f1c00a22SHaicheng Wu   if (StoreInst *SI = dyn_cast<StoreInst>(I))
948f1c00a22SHaicheng Wu     return SI->getPointerOperand();
949f1c00a22SHaicheng Wu   return nullptr;
950f1c00a22SHaicheng Wu }
951f1c00a22SHaicheng Wu 
952f1c00a22SHaicheng Wu /// Take the address space operand from the Load/Store instruction.
953f1c00a22SHaicheng Wu /// Returns -1 if this is not a valid Load/Store instruction.
954f1c00a22SHaicheng Wu static unsigned getAddressSpaceOperand(Value *I) {
955f1c00a22SHaicheng Wu   if (LoadInst *L = dyn_cast<LoadInst>(I))
956f1c00a22SHaicheng Wu     return L->getPointerAddressSpace();
957f1c00a22SHaicheng Wu   if (StoreInst *S = dyn_cast<StoreInst>(I))
958f1c00a22SHaicheng Wu     return S->getPointerAddressSpace();
959f1c00a22SHaicheng Wu   return -1;
960f1c00a22SHaicheng Wu }
961f1c00a22SHaicheng Wu 
962f1c00a22SHaicheng Wu /// Returns true if the memory operations \p A and \p B are consecutive.
963f1c00a22SHaicheng Wu bool llvm::isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL,
964f1c00a22SHaicheng Wu                                ScalarEvolution &SE, bool CheckType) {
965f1c00a22SHaicheng Wu   Value *PtrA = getPointerOperand(A);
966f1c00a22SHaicheng Wu   Value *PtrB = getPointerOperand(B);
967f1c00a22SHaicheng Wu   unsigned ASA = getAddressSpaceOperand(A);
968f1c00a22SHaicheng Wu   unsigned ASB = getAddressSpaceOperand(B);
969f1c00a22SHaicheng Wu 
970f1c00a22SHaicheng Wu   // Check that the address spaces match and that the pointers are valid.
971f1c00a22SHaicheng Wu   if (!PtrA || !PtrB || (ASA != ASB))
972f1c00a22SHaicheng Wu     return false;
973f1c00a22SHaicheng Wu 
974f1c00a22SHaicheng Wu   // Make sure that A and B are different pointers.
975f1c00a22SHaicheng Wu   if (PtrA == PtrB)
976f1c00a22SHaicheng Wu     return false;
977f1c00a22SHaicheng Wu 
978f1c00a22SHaicheng Wu   // Make sure that A and B have the same type if required.
979f1c00a22SHaicheng Wu   if(CheckType && PtrA->getType() != PtrB->getType())
980f1c00a22SHaicheng Wu       return false;
981f1c00a22SHaicheng Wu 
982f1c00a22SHaicheng Wu   unsigned PtrBitWidth = DL.getPointerSizeInBits(ASA);
983f1c00a22SHaicheng Wu   Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
984f1c00a22SHaicheng Wu   APInt Size(PtrBitWidth, DL.getTypeStoreSize(Ty));
985f1c00a22SHaicheng Wu 
986f1c00a22SHaicheng Wu   APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
987f1c00a22SHaicheng Wu   PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetA);
988f1c00a22SHaicheng Wu   PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetB);
989f1c00a22SHaicheng Wu 
990f1c00a22SHaicheng Wu   //  OffsetDelta = OffsetB - OffsetA;
991f1c00a22SHaicheng Wu   const SCEV *OffsetSCEVA = SE.getConstant(OffsetA);
992f1c00a22SHaicheng Wu   const SCEV *OffsetSCEVB = SE.getConstant(OffsetB);
993f1c00a22SHaicheng Wu   const SCEV *OffsetDeltaSCEV = SE.getMinusSCEV(OffsetSCEVB, OffsetSCEVA);
994f1c00a22SHaicheng Wu   const SCEVConstant *OffsetDeltaC = dyn_cast<SCEVConstant>(OffsetDeltaSCEV);
995f1c00a22SHaicheng Wu   const APInt &OffsetDelta = OffsetDeltaC->getAPInt();
996f1c00a22SHaicheng Wu   // Check if they are based on the same pointer. That makes the offsets
997f1c00a22SHaicheng Wu   // sufficient.
998f1c00a22SHaicheng Wu   if (PtrA == PtrB)
999f1c00a22SHaicheng Wu     return OffsetDelta == Size;
1000f1c00a22SHaicheng Wu 
1001f1c00a22SHaicheng Wu   // Compute the necessary base pointer delta to have the necessary final delta
1002f1c00a22SHaicheng Wu   // equal to the size.
1003f1c00a22SHaicheng Wu   // BaseDelta = Size - OffsetDelta;
1004f1c00a22SHaicheng Wu   const SCEV *SizeSCEV = SE.getConstant(Size);
1005f1c00a22SHaicheng Wu   const SCEV *BaseDelta = SE.getMinusSCEV(SizeSCEV, OffsetDeltaSCEV);
1006f1c00a22SHaicheng Wu 
1007f1c00a22SHaicheng Wu   // Otherwise compute the distance with SCEV between the base pointers.
1008f1c00a22SHaicheng Wu   const SCEV *PtrSCEVA = SE.getSCEV(PtrA);
1009f1c00a22SHaicheng Wu   const SCEV *PtrSCEVB = SE.getSCEV(PtrB);
1010f1c00a22SHaicheng Wu   const SCEV *X = SE.getAddExpr(PtrSCEVA, BaseDelta);
1011f1c00a22SHaicheng Wu   return X == PtrSCEVB;
1012f1c00a22SHaicheng Wu }
1013f1c00a22SHaicheng Wu 
10149c926579SAdam Nemet bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
10159c926579SAdam Nemet   switch (Type) {
10169c926579SAdam Nemet   case NoDep:
10179c926579SAdam Nemet   case Forward:
10189c926579SAdam Nemet   case BackwardVectorizable:
10199c926579SAdam Nemet     return true;
10209c926579SAdam Nemet 
10219c926579SAdam Nemet   case Unknown:
10229c926579SAdam Nemet   case ForwardButPreventsForwarding:
10239c926579SAdam Nemet   case Backward:
10249c926579SAdam Nemet   case BackwardVectorizableButPreventsForwarding:
10259c926579SAdam Nemet     return false;
10269c926579SAdam Nemet   }
1027d388e930SDavid Majnemer   llvm_unreachable("unexpected DepType!");
10289c926579SAdam Nemet }
10299c926579SAdam Nemet 
1030397f5829SAdam Nemet bool MemoryDepChecker::Dependence::isBackward() const {
10319c926579SAdam Nemet   switch (Type) {
10329c926579SAdam Nemet   case NoDep:
10339c926579SAdam Nemet   case Forward:
10349c926579SAdam Nemet   case ForwardButPreventsForwarding:
1035397f5829SAdam Nemet   case Unknown:
10369c926579SAdam Nemet     return false;
10379c926579SAdam Nemet 
10389c926579SAdam Nemet   case BackwardVectorizable:
10399c926579SAdam Nemet   case Backward:
10409c926579SAdam Nemet   case BackwardVectorizableButPreventsForwarding:
10419c926579SAdam Nemet     return true;
10429c926579SAdam Nemet   }
1043d388e930SDavid Majnemer   llvm_unreachable("unexpected DepType!");
10449c926579SAdam Nemet }
10459c926579SAdam Nemet 
1046397f5829SAdam Nemet bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
1047397f5829SAdam Nemet   return isBackward() || Type == Unknown;
1048397f5829SAdam Nemet }
1049397f5829SAdam Nemet 
1050397f5829SAdam Nemet bool MemoryDepChecker::Dependence::isForward() const {
1051397f5829SAdam Nemet   switch (Type) {
1052397f5829SAdam Nemet   case Forward:
1053397f5829SAdam Nemet   case ForwardButPreventsForwarding:
1054397f5829SAdam Nemet     return true;
1055397f5829SAdam Nemet 
1056397f5829SAdam Nemet   case NoDep:
1057397f5829SAdam Nemet   case Unknown:
1058397f5829SAdam Nemet   case BackwardVectorizable:
1059397f5829SAdam Nemet   case Backward:
1060397f5829SAdam Nemet   case BackwardVectorizableButPreventsForwarding:
1061397f5829SAdam Nemet     return false;
1062397f5829SAdam Nemet   }
1063397f5829SAdam Nemet   llvm_unreachable("unexpected DepType!");
1064397f5829SAdam Nemet }
1065397f5829SAdam Nemet 
10660456327cSAdam Nemet bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
10670456327cSAdam Nemet                                                     unsigned TypeByteSize) {
10680456327cSAdam Nemet   // If loads occur at a distance that is not a multiple of a feasible vector
10690456327cSAdam Nemet   // factor store-load forwarding does not take place.
10700456327cSAdam Nemet   // Positive dependences might cause troubles because vectorizing them might
10710456327cSAdam Nemet   // prevent store-load forwarding making vectorized code run a lot slower.
10720456327cSAdam Nemet   //   a[i] = a[i-3] ^ a[i-8];
10730456327cSAdam Nemet   //   The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
10740456327cSAdam Nemet   //   hence on your typical architecture store-load forwarding does not take
10750456327cSAdam Nemet   //   place. Vectorizing in such cases does not make sense.
10760456327cSAdam Nemet   // Store-load forwarding distance.
10770456327cSAdam Nemet   const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
10780456327cSAdam Nemet   // Maximum vector factor.
1079f219c647SAdam Nemet   unsigned MaxVFWithoutSLForwardIssues =
1080f219c647SAdam Nemet     VectorizerParams::MaxVectorWidth * TypeByteSize;
10810456327cSAdam Nemet   if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
10820456327cSAdam Nemet     MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
10830456327cSAdam Nemet 
10840456327cSAdam Nemet   for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
10850456327cSAdam Nemet        vf *= 2) {
10860456327cSAdam Nemet     if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
10870456327cSAdam Nemet       MaxVFWithoutSLForwardIssues = (vf >>=1);
10880456327cSAdam Nemet       break;
10890456327cSAdam Nemet     }
10900456327cSAdam Nemet   }
10910456327cSAdam Nemet 
10920456327cSAdam Nemet   if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
1093339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Distance " << Distance <<
109404d4163eSAdam Nemet           " that could cause a store-load forwarding conflict\n");
10950456327cSAdam Nemet     return true;
10960456327cSAdam Nemet   }
10970456327cSAdam Nemet 
10980456327cSAdam Nemet   if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
1099f219c647SAdam Nemet       MaxVFWithoutSLForwardIssues !=
1100f219c647SAdam Nemet       VectorizerParams::MaxVectorWidth * TypeByteSize)
11010456327cSAdam Nemet     MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
11020456327cSAdam Nemet   return false;
11030456327cSAdam Nemet }
11040456327cSAdam Nemet 
1105751004a6SHao Liu /// \brief Check the dependence for two accesses with the same stride \p Stride.
1106751004a6SHao Liu /// \p Distance is the positive distance and \p TypeByteSize is type size in
1107751004a6SHao Liu /// bytes.
1108751004a6SHao Liu ///
1109751004a6SHao Liu /// \returns true if they are independent.
1110751004a6SHao Liu static bool areStridedAccessesIndependent(unsigned Distance, unsigned Stride,
1111751004a6SHao Liu                                           unsigned TypeByteSize) {
1112751004a6SHao Liu   assert(Stride > 1 && "The stride must be greater than 1");
1113751004a6SHao Liu   assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
1114751004a6SHao Liu   assert(Distance > 0 && "The distance must be non-zero");
1115751004a6SHao Liu 
1116751004a6SHao Liu   // Skip if the distance is not multiple of type byte size.
1117751004a6SHao Liu   if (Distance % TypeByteSize)
1118751004a6SHao Liu     return false;
1119751004a6SHao Liu 
1120751004a6SHao Liu   unsigned ScaledDist = Distance / TypeByteSize;
1121751004a6SHao Liu 
1122751004a6SHao Liu   // No dependence if the scaled distance is not multiple of the stride.
1123751004a6SHao Liu   // E.g.
1124751004a6SHao Liu   //      for (i = 0; i < 1024 ; i += 4)
1125751004a6SHao Liu   //        A[i+2] = A[i] + 1;
1126751004a6SHao Liu   //
1127751004a6SHao Liu   // Two accesses in memory (scaled distance is 2, stride is 4):
1128751004a6SHao Liu   //     | A[0] |      |      |      | A[4] |      |      |      |
1129751004a6SHao Liu   //     |      |      | A[2] |      |      |      | A[6] |      |
1130751004a6SHao Liu   //
1131751004a6SHao Liu   // E.g.
1132751004a6SHao Liu   //      for (i = 0; i < 1024 ; i += 3)
1133751004a6SHao Liu   //        A[i+4] = A[i] + 1;
1134751004a6SHao Liu   //
1135751004a6SHao Liu   // Two accesses in memory (scaled distance is 4, stride is 3):
1136751004a6SHao Liu   //     | A[0] |      |      | A[3] |      |      | A[6] |      |      |
1137751004a6SHao Liu   //     |      |      |      |      | A[4] |      |      | A[7] |      |
1138751004a6SHao Liu   return ScaledDist % Stride;
1139751004a6SHao Liu }
1140751004a6SHao Liu 
11419c926579SAdam Nemet MemoryDepChecker::Dependence::DepType
11429c926579SAdam Nemet MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
11430456327cSAdam Nemet                               const MemAccessInfo &B, unsigned BIdx,
11448bc61df9SAdam Nemet                               const ValueToValueMap &Strides) {
11450456327cSAdam Nemet   assert (AIdx < BIdx && "Must pass arguments in program order");
11460456327cSAdam Nemet 
11470456327cSAdam Nemet   Value *APtr = A.getPointer();
11480456327cSAdam Nemet   Value *BPtr = B.getPointer();
11490456327cSAdam Nemet   bool AIsWrite = A.getInt();
11500456327cSAdam Nemet   bool BIsWrite = B.getInt();
11510456327cSAdam Nemet 
11520456327cSAdam Nemet   // Two reads are independent.
11530456327cSAdam Nemet   if (!AIsWrite && !BIsWrite)
11549c926579SAdam Nemet     return Dependence::NoDep;
11550456327cSAdam Nemet 
11560456327cSAdam Nemet   // We cannot check pointers in different address spaces.
11570456327cSAdam Nemet   if (APtr->getType()->getPointerAddressSpace() !=
11580456327cSAdam Nemet       BPtr->getType()->getPointerAddressSpace())
11599c926579SAdam Nemet     return Dependence::Unknown;
11600456327cSAdam Nemet 
11619cd9a7e3SSilviu Baranga   const SCEV *AScev = replaceSymbolicStrideSCEV(PSE, Strides, APtr);
11629cd9a7e3SSilviu Baranga   const SCEV *BScev = replaceSymbolicStrideSCEV(PSE, Strides, BPtr);
11630456327cSAdam Nemet 
1164ea63a7f5SSilviu Baranga   int StrideAPtr = isStridedPtr(PSE, APtr, InnermostLoop, Strides, true);
1165ea63a7f5SSilviu Baranga   int StrideBPtr = isStridedPtr(PSE, BPtr, InnermostLoop, Strides, true);
11660456327cSAdam Nemet 
11670456327cSAdam Nemet   const SCEV *Src = AScev;
11680456327cSAdam Nemet   const SCEV *Sink = BScev;
11690456327cSAdam Nemet 
11700456327cSAdam Nemet   // If the induction step is negative we have to invert source and sink of the
11710456327cSAdam Nemet   // dependence.
11720456327cSAdam Nemet   if (StrideAPtr < 0) {
11730456327cSAdam Nemet     //Src = BScev;
11740456327cSAdam Nemet     //Sink = AScev;
11750456327cSAdam Nemet     std::swap(APtr, BPtr);
11760456327cSAdam Nemet     std::swap(Src, Sink);
11770456327cSAdam Nemet     std::swap(AIsWrite, BIsWrite);
11780456327cSAdam Nemet     std::swap(AIdx, BIdx);
11790456327cSAdam Nemet     std::swap(StrideAPtr, StrideBPtr);
11800456327cSAdam Nemet   }
11810456327cSAdam Nemet 
11829cd9a7e3SSilviu Baranga   const SCEV *Dist = PSE.getSE()->getMinusSCEV(Sink, Src);
11830456327cSAdam Nemet 
1184339f42b3SAdam Nemet   DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
11850456327cSAdam Nemet                << "(Induction step: " << StrideAPtr << ")\n");
1186339f42b3SAdam Nemet   DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
11870456327cSAdam Nemet                << *InstMap[BIdx] << ": " << *Dist << "\n");
11880456327cSAdam Nemet 
1189943befedSAdam Nemet   // Need accesses with constant stride. We don't want to vectorize
11900456327cSAdam Nemet   // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
11910456327cSAdam Nemet   // the address space.
11920456327cSAdam Nemet   if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
1193943befedSAdam Nemet     DEBUG(dbgs() << "Pointer access with non-constant stride\n");
11949c926579SAdam Nemet     return Dependence::Unknown;
11950456327cSAdam Nemet   }
11960456327cSAdam Nemet 
11970456327cSAdam Nemet   const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
11980456327cSAdam Nemet   if (!C) {
1199339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
12000456327cSAdam Nemet     ShouldRetryWithRuntimeCheck = true;
12019c926579SAdam Nemet     return Dependence::Unknown;
12020456327cSAdam Nemet   }
12030456327cSAdam Nemet 
12040456327cSAdam Nemet   Type *ATy = APtr->getType()->getPointerElementType();
12050456327cSAdam Nemet   Type *BTy = BPtr->getType()->getPointerElementType();
1206a28d91d8SMehdi Amini   auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
1207a28d91d8SMehdi Amini   unsigned TypeByteSize = DL.getTypeAllocSize(ATy);
12080456327cSAdam Nemet 
12090456327cSAdam Nemet   // Negative distances are not plausible dependencies.
12100de2feceSSanjoy Das   const APInt &Val = C->getAPInt();
12110456327cSAdam Nemet   if (Val.isNegative()) {
12120456327cSAdam Nemet     bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
12130456327cSAdam Nemet     if (IsTrueDataDependence &&
12140456327cSAdam Nemet         (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
1215b8486e5aSAdam Nemet          ATy != BTy)) {
1216b8486e5aSAdam Nemet       DEBUG(dbgs() << "LAA: Forward but may prevent st->ld forwarding\n");
12179c926579SAdam Nemet       return Dependence::ForwardButPreventsForwarding;
1218b8486e5aSAdam Nemet     }
12190456327cSAdam Nemet 
1220339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
12219c926579SAdam Nemet     return Dependence::Forward;
12220456327cSAdam Nemet   }
12230456327cSAdam Nemet 
12240456327cSAdam Nemet   // Write to the same location with the same size.
12250456327cSAdam Nemet   // Could be improved to assert type sizes are the same (i32 == float, etc).
12260456327cSAdam Nemet   if (Val == 0) {
12270456327cSAdam Nemet     if (ATy == BTy)
1228d7037c56SAdam Nemet       return Dependence::Forward;
1229339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
12309c926579SAdam Nemet     return Dependence::Unknown;
12310456327cSAdam Nemet   }
12320456327cSAdam Nemet 
12330456327cSAdam Nemet   assert(Val.isStrictlyPositive() && "Expect a positive value");
12340456327cSAdam Nemet 
12350456327cSAdam Nemet   if (ATy != BTy) {
123604d4163eSAdam Nemet     DEBUG(dbgs() <<
1237339f42b3SAdam Nemet           "LAA: ReadWrite-Write positive dependency with different types\n");
12389c926579SAdam Nemet     return Dependence::Unknown;
12390456327cSAdam Nemet   }
12400456327cSAdam Nemet 
12410456327cSAdam Nemet   unsigned Distance = (unsigned) Val.getZExtValue();
12420456327cSAdam Nemet 
1243751004a6SHao Liu   unsigned Stride = std::abs(StrideAPtr);
1244751004a6SHao Liu   if (Stride > 1 &&
12450131a569SAdam Nemet       areStridedAccessesIndependent(Distance, Stride, TypeByteSize)) {
12460131a569SAdam Nemet     DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
1247751004a6SHao Liu     return Dependence::NoDep;
12480131a569SAdam Nemet   }
1249751004a6SHao Liu 
12500456327cSAdam Nemet   // Bail out early if passed-in parameters make vectorization not feasible.
1251f219c647SAdam Nemet   unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
1252f219c647SAdam Nemet                            VectorizerParams::VectorizationFactor : 1);
1253f219c647SAdam Nemet   unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
1254f219c647SAdam Nemet                            VectorizerParams::VectorizationInterleave : 1);
1255751004a6SHao Liu   // The minimum number of iterations for a vectorized/unrolled version.
1256751004a6SHao Liu   unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
12570456327cSAdam Nemet 
1258751004a6SHao Liu   // It's not vectorizable if the distance is smaller than the minimum distance
1259751004a6SHao Liu   // needed for a vectroized/unrolled version. Vectorizing one iteration in
1260751004a6SHao Liu   // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
1261751004a6SHao Liu   // TypeByteSize (No need to plus the last gap distance).
1262751004a6SHao Liu   //
1263751004a6SHao Liu   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1264751004a6SHao Liu   //      foo(int *A) {
1265751004a6SHao Liu   //        int *B = (int *)((char *)A + 14);
1266751004a6SHao Liu   //        for (i = 0 ; i < 1024 ; i += 2)
1267751004a6SHao Liu   //          B[i] = A[i] + 1;
1268751004a6SHao Liu   //      }
1269751004a6SHao Liu   //
1270751004a6SHao Liu   // Two accesses in memory (stride is 2):
1271751004a6SHao Liu   //     | A[0] |      | A[2] |      | A[4] |      | A[6] |      |
1272751004a6SHao Liu   //                              | B[0] |      | B[2] |      | B[4] |
1273751004a6SHao Liu   //
1274751004a6SHao Liu   // Distance needs for vectorizing iterations except the last iteration:
1275751004a6SHao Liu   // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
1276751004a6SHao Liu   // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
1277751004a6SHao Liu   //
1278751004a6SHao Liu   // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
1279751004a6SHao Liu   // 12, which is less than distance.
1280751004a6SHao Liu   //
1281751004a6SHao Liu   // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
1282751004a6SHao Liu   // the minimum distance needed is 28, which is greater than distance. It is
1283751004a6SHao Liu   // not safe to do vectorization.
1284751004a6SHao Liu   unsigned MinDistanceNeeded =
1285751004a6SHao Liu       TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
1286751004a6SHao Liu   if (MinDistanceNeeded > Distance) {
1287751004a6SHao Liu     DEBUG(dbgs() << "LAA: Failure because of positive distance " << Distance
1288751004a6SHao Liu                  << '\n');
1289751004a6SHao Liu     return Dependence::Backward;
1290751004a6SHao Liu   }
1291751004a6SHao Liu 
1292751004a6SHao Liu   // Unsafe if the minimum distance needed is greater than max safe distance.
1293751004a6SHao Liu   if (MinDistanceNeeded > MaxSafeDepDistBytes) {
1294751004a6SHao Liu     DEBUG(dbgs() << "LAA: Failure because it needs at least "
1295751004a6SHao Liu                  << MinDistanceNeeded << " size in bytes");
12969c926579SAdam Nemet     return Dependence::Backward;
12970456327cSAdam Nemet   }
12980456327cSAdam Nemet 
12999cc0c399SAdam Nemet   // Positive distance bigger than max vectorization factor.
1300751004a6SHao Liu   // FIXME: Should use max factor instead of max distance in bytes, which could
1301751004a6SHao Liu   // not handle different types.
1302751004a6SHao Liu   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1303751004a6SHao Liu   //      void foo (int *A, char *B) {
1304751004a6SHao Liu   //        for (unsigned i = 0; i < 1024; i++) {
1305751004a6SHao Liu   //          A[i+2] = A[i] + 1;
1306751004a6SHao Liu   //          B[i+2] = B[i] + 1;
1307751004a6SHao Liu   //        }
1308751004a6SHao Liu   //      }
1309751004a6SHao Liu   //
1310751004a6SHao Liu   // This case is currently unsafe according to the max safe distance. If we
1311751004a6SHao Liu   // analyze the two accesses on array B, the max safe dependence distance
1312751004a6SHao Liu   // is 2. Then we analyze the accesses on array A, the minimum distance needed
1313751004a6SHao Liu   // is 8, which is less than 2 and forbidden vectorization, But actually
1314751004a6SHao Liu   // both A and B could be vectorized by 2 iterations.
1315751004a6SHao Liu   MaxSafeDepDistBytes =
1316751004a6SHao Liu       Distance < MaxSafeDepDistBytes ? Distance : MaxSafeDepDistBytes;
13170456327cSAdam Nemet 
13180456327cSAdam Nemet   bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
13190456327cSAdam Nemet   if (IsTrueDataDependence &&
13200456327cSAdam Nemet       couldPreventStoreLoadForward(Distance, TypeByteSize))
13219c926579SAdam Nemet     return Dependence::BackwardVectorizableButPreventsForwarding;
13220456327cSAdam Nemet 
1323751004a6SHao Liu   DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
1324751004a6SHao Liu                << " with max VF = "
1325751004a6SHao Liu                << MaxSafeDepDistBytes / (TypeByteSize * Stride) << '\n');
13260456327cSAdam Nemet 
13279c926579SAdam Nemet   return Dependence::BackwardVectorizable;
13280456327cSAdam Nemet }
13290456327cSAdam Nemet 
1330dee666bcSAdam Nemet bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
13310456327cSAdam Nemet                                    MemAccessInfoSet &CheckDeps,
13328bc61df9SAdam Nemet                                    const ValueToValueMap &Strides) {
13330456327cSAdam Nemet 
13340456327cSAdam Nemet   MaxSafeDepDistBytes = -1U;
13350456327cSAdam Nemet   while (!CheckDeps.empty()) {
13360456327cSAdam Nemet     MemAccessInfo CurAccess = *CheckDeps.begin();
13370456327cSAdam Nemet 
13380456327cSAdam Nemet     // Get the relevant memory access set.
13390456327cSAdam Nemet     EquivalenceClasses<MemAccessInfo>::iterator I =
13400456327cSAdam Nemet       AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
13410456327cSAdam Nemet 
13420456327cSAdam Nemet     // Check accesses within this set.
13437a083814SRichard Trieu     EquivalenceClasses<MemAccessInfo>::member_iterator AI =
13447a083814SRichard Trieu         AccessSets.member_begin(I);
13457a083814SRichard Trieu     EquivalenceClasses<MemAccessInfo>::member_iterator AE =
13467a083814SRichard Trieu         AccessSets.member_end();
13470456327cSAdam Nemet 
13480456327cSAdam Nemet     // Check every access pair.
13490456327cSAdam Nemet     while (AI != AE) {
13500456327cSAdam Nemet       CheckDeps.erase(*AI);
13510456327cSAdam Nemet       EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
13520456327cSAdam Nemet       while (OI != AE) {
13530456327cSAdam Nemet         // Check every accessing instruction pair in program order.
13540456327cSAdam Nemet         for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
13550456327cSAdam Nemet              I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
13560456327cSAdam Nemet           for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
13570456327cSAdam Nemet                I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
13589c926579SAdam Nemet             auto A = std::make_pair(&*AI, *I1);
13599c926579SAdam Nemet             auto B = std::make_pair(&*OI, *I2);
13609c926579SAdam Nemet 
13619c926579SAdam Nemet             assert(*I1 != *I2);
13629c926579SAdam Nemet             if (*I1 > *I2)
13639c926579SAdam Nemet               std::swap(A, B);
13649c926579SAdam Nemet 
13659c926579SAdam Nemet             Dependence::DepType Type =
13669c926579SAdam Nemet                 isDependent(*A.first, A.second, *B.first, B.second, Strides);
13679c926579SAdam Nemet             SafeForVectorization &= Dependence::isSafeForVectorization(Type);
13689c926579SAdam Nemet 
1369a2df750fSAdam Nemet             // Gather dependences unless we accumulated MaxDependences
13709c926579SAdam Nemet             // dependences.  In that case return as soon as we find the first
13719c926579SAdam Nemet             // unsafe dependence.  This puts a limit on this quadratic
13729c926579SAdam Nemet             // algorithm.
1373a2df750fSAdam Nemet             if (RecordDependences) {
1374a2df750fSAdam Nemet               if (Type != Dependence::NoDep)
1375a2df750fSAdam Nemet                 Dependences.push_back(Dependence(A.second, B.second, Type));
13769c926579SAdam Nemet 
1377a2df750fSAdam Nemet               if (Dependences.size() >= MaxDependences) {
1378a2df750fSAdam Nemet                 RecordDependences = false;
1379a2df750fSAdam Nemet                 Dependences.clear();
13809c926579SAdam Nemet                 DEBUG(dbgs() << "Too many dependences, stopped recording\n");
13819c926579SAdam Nemet               }
13829c926579SAdam Nemet             }
1383a2df750fSAdam Nemet             if (!RecordDependences && !SafeForVectorization)
13840456327cSAdam Nemet               return false;
13850456327cSAdam Nemet           }
13860456327cSAdam Nemet         ++OI;
13870456327cSAdam Nemet       }
13880456327cSAdam Nemet       AI++;
13890456327cSAdam Nemet     }
13900456327cSAdam Nemet   }
13919c926579SAdam Nemet 
1392a2df750fSAdam Nemet   DEBUG(dbgs() << "Total Dependences: " << Dependences.size() << "\n");
13939c926579SAdam Nemet   return SafeForVectorization;
13940456327cSAdam Nemet }
13950456327cSAdam Nemet 
1396ec1e2bb6SAdam Nemet SmallVector<Instruction *, 4>
1397ec1e2bb6SAdam Nemet MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
1398ec1e2bb6SAdam Nemet   MemAccessInfo Access(Ptr, isWrite);
1399ec1e2bb6SAdam Nemet   auto &IndexVector = Accesses.find(Access)->second;
1400ec1e2bb6SAdam Nemet 
1401ec1e2bb6SAdam Nemet   SmallVector<Instruction *, 4> Insts;
1402ec1e2bb6SAdam Nemet   std::transform(IndexVector.begin(), IndexVector.end(),
1403ec1e2bb6SAdam Nemet                  std::back_inserter(Insts),
1404ec1e2bb6SAdam Nemet                  [&](unsigned Idx) { return this->InstMap[Idx]; });
1405ec1e2bb6SAdam Nemet   return Insts;
1406ec1e2bb6SAdam Nemet }
1407ec1e2bb6SAdam Nemet 
140858913d65SAdam Nemet const char *MemoryDepChecker::Dependence::DepName[] = {
140958913d65SAdam Nemet     "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
141058913d65SAdam Nemet     "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
141158913d65SAdam Nemet 
141258913d65SAdam Nemet void MemoryDepChecker::Dependence::print(
141358913d65SAdam Nemet     raw_ostream &OS, unsigned Depth,
141458913d65SAdam Nemet     const SmallVectorImpl<Instruction *> &Instrs) const {
141558913d65SAdam Nemet   OS.indent(Depth) << DepName[Type] << ":\n";
141658913d65SAdam Nemet   OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
141758913d65SAdam Nemet   OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
141858913d65SAdam Nemet }
141958913d65SAdam Nemet 
1420929c38e8SAdam Nemet bool LoopAccessInfo::canAnalyzeLoop() {
14218dcb3b6aSAdam Nemet   // We need to have a loop header.
1422d8968f09SAdam Nemet   DEBUG(dbgs() << "LAA: Found a loop in "
1423d8968f09SAdam Nemet                << TheLoop->getHeader()->getParent()->getName() << ": "
1424d8968f09SAdam Nemet                << TheLoop->getHeader()->getName() << '\n');
14258dcb3b6aSAdam Nemet 
1426929c38e8SAdam Nemet   // We can only analyze innermost loops.
1427929c38e8SAdam Nemet   if (!TheLoop->empty()) {
14288dcb3b6aSAdam Nemet     DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
14292bd6e984SAdam Nemet     emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
1430929c38e8SAdam Nemet     return false;
1431929c38e8SAdam Nemet   }
1432929c38e8SAdam Nemet 
1433929c38e8SAdam Nemet   // We must have a single backedge.
1434929c38e8SAdam Nemet   if (TheLoop->getNumBackEdges() != 1) {
14358dcb3b6aSAdam Nemet     DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1436929c38e8SAdam Nemet     emitAnalysis(
14372bd6e984SAdam Nemet         LoopAccessReport() <<
1438929c38e8SAdam Nemet         "loop control flow is not understood by analyzer");
1439929c38e8SAdam Nemet     return false;
1440929c38e8SAdam Nemet   }
1441929c38e8SAdam Nemet 
1442929c38e8SAdam Nemet   // We must have a single exiting block.
1443929c38e8SAdam Nemet   if (!TheLoop->getExitingBlock()) {
14448dcb3b6aSAdam Nemet     DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1445929c38e8SAdam Nemet     emitAnalysis(
14462bd6e984SAdam Nemet         LoopAccessReport() <<
1447929c38e8SAdam Nemet         "loop control flow is not understood by analyzer");
1448929c38e8SAdam Nemet     return false;
1449929c38e8SAdam Nemet   }
1450929c38e8SAdam Nemet 
1451929c38e8SAdam Nemet   // We only handle bottom-tested loops, i.e. loop in which the condition is
1452929c38e8SAdam Nemet   // checked at the end of each iteration. With that we can assume that all
1453929c38e8SAdam Nemet   // instructions in the loop are executed the same number of times.
1454929c38e8SAdam Nemet   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
14558dcb3b6aSAdam Nemet     DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1456929c38e8SAdam Nemet     emitAnalysis(
14572bd6e984SAdam Nemet         LoopAccessReport() <<
1458929c38e8SAdam Nemet         "loop control flow is not understood by analyzer");
1459929c38e8SAdam Nemet     return false;
1460929c38e8SAdam Nemet   }
1461929c38e8SAdam Nemet 
1462929c38e8SAdam Nemet   // ScalarEvolution needs to be able to find the exit count.
1463*6f444dfdSSilviu Baranga   const SCEV *ExitCount = PSE.getBackedgeTakenCount();
14649cd9a7e3SSilviu Baranga   if (ExitCount == PSE.getSE()->getCouldNotCompute()) {
14659cd9a7e3SSilviu Baranga     emitAnalysis(LoopAccessReport()
14669cd9a7e3SSilviu Baranga                  << "could not determine number of loop iterations");
1467929c38e8SAdam Nemet     DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
1468929c38e8SAdam Nemet     return false;
1469929c38e8SAdam Nemet   }
1470929c38e8SAdam Nemet 
1471929c38e8SAdam Nemet   return true;
1472929c38e8SAdam Nemet }
1473929c38e8SAdam Nemet 
14748bc61df9SAdam Nemet void LoopAccessInfo::analyzeLoop(const ValueToValueMap &Strides) {
14750456327cSAdam Nemet 
14760456327cSAdam Nemet   typedef SmallVector<Value*, 16> ValueVector;
14770456327cSAdam Nemet   typedef SmallPtrSet<Value*, 16> ValueSet;
14780456327cSAdam Nemet 
14790456327cSAdam Nemet   // Holds the Load and Store *instructions*.
14800456327cSAdam Nemet   ValueVector Loads;
14810456327cSAdam Nemet   ValueVector Stores;
14820456327cSAdam Nemet 
14830456327cSAdam Nemet   // Holds all the different accesses in the loop.
14840456327cSAdam Nemet   unsigned NumReads = 0;
14850456327cSAdam Nemet   unsigned NumReadWrites = 0;
14860456327cSAdam Nemet 
14877cdebac0SAdam Nemet   PtrRtChecking.Pointers.clear();
14887cdebac0SAdam Nemet   PtrRtChecking.Need = false;
14890456327cSAdam Nemet 
14900456327cSAdam Nemet   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
14910456327cSAdam Nemet 
14920456327cSAdam Nemet   // For each block.
14930456327cSAdam Nemet   for (Loop::block_iterator bb = TheLoop->block_begin(),
14940456327cSAdam Nemet        be = TheLoop->block_end(); bb != be; ++bb) {
14950456327cSAdam Nemet 
14960456327cSAdam Nemet     // Scan the BB and collect legal loads and stores.
14970456327cSAdam Nemet     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
14980456327cSAdam Nemet          ++it) {
14990456327cSAdam Nemet 
15000456327cSAdam Nemet       // If this is a load, save it. If this instruction can read from memory
15010456327cSAdam Nemet       // but is not a load, then we quit. Notice that we don't handle function
15020456327cSAdam Nemet       // calls that read or write.
15030456327cSAdam Nemet       if (it->mayReadFromMemory()) {
15040456327cSAdam Nemet         // Many math library functions read the rounding mode. We will only
15050456327cSAdam Nemet         // vectorize a loop if it contains known function calls that don't set
15060456327cSAdam Nemet         // the flag. Therefore, it is safe to ignore this read from memory.
15070456327cSAdam Nemet         CallInst *Call = dyn_cast<CallInst>(it);
15080456327cSAdam Nemet         if (Call && getIntrinsicIDForCall(Call, TLI))
15090456327cSAdam Nemet           continue;
15100456327cSAdam Nemet 
15119b3cf604SMichael Zolotukhin         // If the function has an explicit vectorized counterpart, we can safely
15129b3cf604SMichael Zolotukhin         // assume that it can be vectorized.
15139b3cf604SMichael Zolotukhin         if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
15149b3cf604SMichael Zolotukhin             TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
15159b3cf604SMichael Zolotukhin           continue;
15169b3cf604SMichael Zolotukhin 
15170456327cSAdam Nemet         LoadInst *Ld = dyn_cast<LoadInst>(it);
15180456327cSAdam Nemet         if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
15192bd6e984SAdam Nemet           emitAnalysis(LoopAccessReport(Ld)
15200456327cSAdam Nemet                        << "read with atomic ordering or volatile read");
1521339f42b3SAdam Nemet           DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
1522436018c3SAdam Nemet           CanVecMem = false;
1523436018c3SAdam Nemet           return;
15240456327cSAdam Nemet         }
15250456327cSAdam Nemet         NumLoads++;
15260456327cSAdam Nemet         Loads.push_back(Ld);
15270456327cSAdam Nemet         DepChecker.addAccess(Ld);
15280456327cSAdam Nemet         continue;
15290456327cSAdam Nemet       }
15300456327cSAdam Nemet 
15310456327cSAdam Nemet       // Save 'store' instructions. Abort if other instructions write to memory.
15320456327cSAdam Nemet       if (it->mayWriteToMemory()) {
15330456327cSAdam Nemet         StoreInst *St = dyn_cast<StoreInst>(it);
15340456327cSAdam Nemet         if (!St) {
15355a82c916SDuncan P. N. Exon Smith           emitAnalysis(LoopAccessReport(&*it) <<
153604d4163eSAdam Nemet                        "instruction cannot be vectorized");
1537436018c3SAdam Nemet           CanVecMem = false;
1538436018c3SAdam Nemet           return;
15390456327cSAdam Nemet         }
15400456327cSAdam Nemet         if (!St->isSimple() && !IsAnnotatedParallel) {
15412bd6e984SAdam Nemet           emitAnalysis(LoopAccessReport(St)
15420456327cSAdam Nemet                        << "write with atomic ordering or volatile write");
1543339f42b3SAdam Nemet           DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
1544436018c3SAdam Nemet           CanVecMem = false;
1545436018c3SAdam Nemet           return;
15460456327cSAdam Nemet         }
15470456327cSAdam Nemet         NumStores++;
15480456327cSAdam Nemet         Stores.push_back(St);
15490456327cSAdam Nemet         DepChecker.addAccess(St);
15500456327cSAdam Nemet       }
15510456327cSAdam Nemet     } // Next instr.
15520456327cSAdam Nemet   } // Next block.
15530456327cSAdam Nemet 
15540456327cSAdam Nemet   // Now we have two lists that hold the loads and the stores.
15550456327cSAdam Nemet   // Next, we find the pointers that they use.
15560456327cSAdam Nemet 
15570456327cSAdam Nemet   // Check if we see any stores. If there are no stores, then we don't
15580456327cSAdam Nemet   // care if the pointers are *restrict*.
15590456327cSAdam Nemet   if (!Stores.size()) {
1560339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
1561436018c3SAdam Nemet     CanVecMem = true;
1562436018c3SAdam Nemet     return;
15630456327cSAdam Nemet   }
15640456327cSAdam Nemet 
1565dee666bcSAdam Nemet   MemoryDepChecker::DepCandidates DependentAccesses;
1566a28d91d8SMehdi Amini   AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
15679cd9a7e3SSilviu Baranga                           AA, LI, DependentAccesses, PSE);
15680456327cSAdam Nemet 
15690456327cSAdam Nemet   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
15700456327cSAdam Nemet   // multiple times on the same object. If the ptr is accessed twice, once
15710456327cSAdam Nemet   // for read and once for write, it will only appear once (on the write
15720456327cSAdam Nemet   // list). This is okay, since we are going to check for conflicts between
15730456327cSAdam Nemet   // writes and between reads and writes, but not between reads and reads.
15740456327cSAdam Nemet   ValueSet Seen;
15750456327cSAdam Nemet 
15760456327cSAdam Nemet   ValueVector::iterator I, IE;
15770456327cSAdam Nemet   for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
15780456327cSAdam Nemet     StoreInst *ST = cast<StoreInst>(*I);
15790456327cSAdam Nemet     Value* Ptr = ST->getPointerOperand();
1580ce48250fSAdam Nemet     // Check for store to loop invariant address.
1581ce48250fSAdam Nemet     StoreToLoopInvariantAddress |= isUniform(Ptr);
15820456327cSAdam Nemet     // If we did *not* see this pointer before, insert it to  the read-write
15830456327cSAdam Nemet     // list. At this phase it is only a 'write' list.
15840456327cSAdam Nemet     if (Seen.insert(Ptr).second) {
15850456327cSAdam Nemet       ++NumReadWrites;
15860456327cSAdam Nemet 
1587ac80dc75SChandler Carruth       MemoryLocation Loc = MemoryLocation::get(ST);
15880456327cSAdam Nemet       // The TBAA metadata could have a control dependency on the predication
15890456327cSAdam Nemet       // condition, so we cannot rely on it when determining whether or not we
15900456327cSAdam Nemet       // need runtime pointer checks.
159101abb2c3SAdam Nemet       if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
15920456327cSAdam Nemet         Loc.AATags.TBAA = nullptr;
15930456327cSAdam Nemet 
15940456327cSAdam Nemet       Accesses.addStore(Loc);
15950456327cSAdam Nemet     }
15960456327cSAdam Nemet   }
15970456327cSAdam Nemet 
15980456327cSAdam Nemet   if (IsAnnotatedParallel) {
159904d4163eSAdam Nemet     DEBUG(dbgs()
1600339f42b3SAdam Nemet           << "LAA: A loop annotated parallel, ignore memory dependency "
16010456327cSAdam Nemet           << "checks.\n");
1602436018c3SAdam Nemet     CanVecMem = true;
1603436018c3SAdam Nemet     return;
16040456327cSAdam Nemet   }
16050456327cSAdam Nemet 
16060456327cSAdam Nemet   for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
16070456327cSAdam Nemet     LoadInst *LD = cast<LoadInst>(*I);
16080456327cSAdam Nemet     Value* Ptr = LD->getPointerOperand();
16090456327cSAdam Nemet     // If we did *not* see this pointer before, insert it to the
16100456327cSAdam Nemet     // read list. If we *did* see it before, then it is already in
16110456327cSAdam Nemet     // the read-write list. This allows us to vectorize expressions
16120456327cSAdam Nemet     // such as A[i] += x;  Because the address of A[i] is a read-write
16130456327cSAdam Nemet     // pointer. This only works if the index of A[i] is consecutive.
16140456327cSAdam Nemet     // If the address of i is unknown (for example A[B[i]]) then we may
16150456327cSAdam Nemet     // read a few words, modify, and write a few words, and some of the
16160456327cSAdam Nemet     // words may be written to the same address.
16170456327cSAdam Nemet     bool IsReadOnlyPtr = false;
16189cd9a7e3SSilviu Baranga     if (Seen.insert(Ptr).second || !isStridedPtr(PSE, Ptr, TheLoop, Strides)) {
16190456327cSAdam Nemet       ++NumReads;
16200456327cSAdam Nemet       IsReadOnlyPtr = true;
16210456327cSAdam Nemet     }
16220456327cSAdam Nemet 
1623ac80dc75SChandler Carruth     MemoryLocation Loc = MemoryLocation::get(LD);
16240456327cSAdam Nemet     // The TBAA metadata could have a control dependency on the predication
16250456327cSAdam Nemet     // condition, so we cannot rely on it when determining whether or not we
16260456327cSAdam Nemet     // need runtime pointer checks.
162701abb2c3SAdam Nemet     if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
16280456327cSAdam Nemet       Loc.AATags.TBAA = nullptr;
16290456327cSAdam Nemet 
16300456327cSAdam Nemet     Accesses.addLoad(Loc, IsReadOnlyPtr);
16310456327cSAdam Nemet   }
16320456327cSAdam Nemet 
16330456327cSAdam Nemet   // If we write (or read-write) to a single destination and there are no
16340456327cSAdam Nemet   // other reads in this loop then is it safe to vectorize.
16350456327cSAdam Nemet   if (NumReadWrites == 1 && NumReads == 0) {
1636339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
1637436018c3SAdam Nemet     CanVecMem = true;
1638436018c3SAdam Nemet     return;
16390456327cSAdam Nemet   }
16400456327cSAdam Nemet 
16410456327cSAdam Nemet   // Build dependence sets and check whether we need a runtime pointer bounds
16420456327cSAdam Nemet   // check.
16430456327cSAdam Nemet   Accesses.buildDependenceSets();
16440456327cSAdam Nemet 
16450456327cSAdam Nemet   // Find pointers with computable bounds. We are going to use this information
16460456327cSAdam Nemet   // to place a runtime bound check.
1647ee61474aSAdam Nemet   bool CanDoRTIfNeeded =
16489cd9a7e3SSilviu Baranga       Accesses.canCheckPtrAtRT(PtrRtChecking, PSE.getSE(), TheLoop, Strides);
1649ee61474aSAdam Nemet   if (!CanDoRTIfNeeded) {
16502bd6e984SAdam Nemet     emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
1651ee61474aSAdam Nemet     DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
1652ee61474aSAdam Nemet                  << "the array bounds.\n");
1653436018c3SAdam Nemet     CanVecMem = false;
1654436018c3SAdam Nemet     return;
16550456327cSAdam Nemet   }
16560456327cSAdam Nemet 
1657ee61474aSAdam Nemet   DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
16580456327cSAdam Nemet 
1659436018c3SAdam Nemet   CanVecMem = true;
16600456327cSAdam Nemet   if (Accesses.isDependencyCheckNeeded()) {
1661339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
16620456327cSAdam Nemet     CanVecMem = DepChecker.areDepsSafe(
16630456327cSAdam Nemet         DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
16640456327cSAdam Nemet     MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
16650456327cSAdam Nemet 
16660456327cSAdam Nemet     if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
1667339f42b3SAdam Nemet       DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
16680456327cSAdam Nemet 
16690456327cSAdam Nemet       // Clear the dependency checks. We assume they are not needed.
1670df3dc5b9SAdam Nemet       Accesses.resetDepChecks(DepChecker);
16710456327cSAdam Nemet 
16727cdebac0SAdam Nemet       PtrRtChecking.reset();
16737cdebac0SAdam Nemet       PtrRtChecking.Need = true;
16740456327cSAdam Nemet 
16759cd9a7e3SSilviu Baranga       auto *SE = PSE.getSE();
1676ee61474aSAdam Nemet       CanDoRTIfNeeded =
16777cdebac0SAdam Nemet           Accesses.canCheckPtrAtRT(PtrRtChecking, SE, TheLoop, Strides, true);
167898a13719SSilviu Baranga 
1679949e91a6SAdam Nemet       // Check that we found the bounds for the pointer.
1680ee61474aSAdam Nemet       if (!CanDoRTIfNeeded) {
16812bd6e984SAdam Nemet         emitAnalysis(LoopAccessReport()
16820456327cSAdam Nemet                      << "cannot check memory dependencies at runtime");
1683b6dc76ffSAdam Nemet         DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
1684b6dc76ffSAdam Nemet         CanVecMem = false;
1685b6dc76ffSAdam Nemet         return;
1686b6dc76ffSAdam Nemet       }
1687b6dc76ffSAdam Nemet 
16880456327cSAdam Nemet       CanVecMem = true;
16890456327cSAdam Nemet     }
16900456327cSAdam Nemet   }
16910456327cSAdam Nemet 
16924bb90a71SAdam Nemet   if (CanVecMem)
16934bb90a71SAdam Nemet     DEBUG(dbgs() << "LAA: No unsafe dependent memory operations in loop.  We"
16947cdebac0SAdam Nemet                  << (PtrRtChecking.Need ? "" : " don't")
16950f67c6c1SAdam Nemet                  << " need runtime memory checks.\n");
16964bb90a71SAdam Nemet   else {
16972bd6e984SAdam Nemet     emitAnalysis(LoopAccessReport() <<
169804d4163eSAdam Nemet                  "unsafe dependent memory operations in loop");
16994bb90a71SAdam Nemet     DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
17004bb90a71SAdam Nemet   }
17010456327cSAdam Nemet }
17020456327cSAdam Nemet 
170301abb2c3SAdam Nemet bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
170401abb2c3SAdam Nemet                                            DominatorTree *DT)  {
17050456327cSAdam Nemet   assert(TheLoop->contains(BB) && "Unknown block used");
17060456327cSAdam Nemet 
17070456327cSAdam Nemet   // Blocks that do not dominate the latch need predication.
17080456327cSAdam Nemet   BasicBlock* Latch = TheLoop->getLoopLatch();
17090456327cSAdam Nemet   return !DT->dominates(BB, Latch);
17100456327cSAdam Nemet }
17110456327cSAdam Nemet 
17122bd6e984SAdam Nemet void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
1713c922853bSAdam Nemet   assert(!Report && "Multiple reports generated");
1714c922853bSAdam Nemet   Report = Message;
17150456327cSAdam Nemet }
17160456327cSAdam Nemet 
171757ac766eSAdam Nemet bool LoopAccessInfo::isUniform(Value *V) const {
17189cd9a7e3SSilviu Baranga   return (PSE.getSE()->isLoopInvariant(PSE.getSE()->getSCEV(V), TheLoop));
17190456327cSAdam Nemet }
17207206d7a5SAdam Nemet 
17217206d7a5SAdam Nemet // FIXME: this function is currently a duplicate of the one in
17227206d7a5SAdam Nemet // LoopVectorize.cpp.
17237206d7a5SAdam Nemet static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
17247206d7a5SAdam Nemet                                  Instruction *Loc) {
17257206d7a5SAdam Nemet   if (FirstInst)
17267206d7a5SAdam Nemet     return FirstInst;
17277206d7a5SAdam Nemet   if (Instruction *I = dyn_cast<Instruction>(V))
17287206d7a5SAdam Nemet     return I->getParent() == Loc->getParent() ? I : nullptr;
17297206d7a5SAdam Nemet   return nullptr;
17307206d7a5SAdam Nemet }
17317206d7a5SAdam Nemet 
1732039b1042SBenjamin Kramer namespace {
17334e533ef7SAdam Nemet /// \brief IR Values for the lower and upper bounds of a pointer evolution.  We
17344e533ef7SAdam Nemet /// need to use value-handles because SCEV expansion can invalidate previously
17354e533ef7SAdam Nemet /// expanded values.  Thus expansion of a pointer can invalidate the bounds for
17364e533ef7SAdam Nemet /// a previous one.
17371da7df37SAdam Nemet struct PointerBounds {
17384e533ef7SAdam Nemet   TrackingVH<Value> Start;
17394e533ef7SAdam Nemet   TrackingVH<Value> End;
17401da7df37SAdam Nemet };
1741039b1042SBenjamin Kramer } // end anonymous namespace
17427206d7a5SAdam Nemet 
17431da7df37SAdam Nemet /// \brief Expand code for the lower and upper bound of the pointer group \p CG
17441da7df37SAdam Nemet /// in \p TheLoop.  \return the values for the bounds.
17451da7df37SAdam Nemet static PointerBounds
17461da7df37SAdam Nemet expandBounds(const RuntimePointerChecking::CheckingPtrGroup *CG, Loop *TheLoop,
17471da7df37SAdam Nemet              Instruction *Loc, SCEVExpander &Exp, ScalarEvolution *SE,
17481da7df37SAdam Nemet              const RuntimePointerChecking &PtrRtChecking) {
17491da7df37SAdam Nemet   Value *Ptr = PtrRtChecking.Pointers[CG->Members[0]].PointerValue;
17507206d7a5SAdam Nemet   const SCEV *Sc = SE->getSCEV(Ptr);
17517206d7a5SAdam Nemet 
17527206d7a5SAdam Nemet   if (SE->isLoopInvariant(Sc, TheLoop)) {
17531b6b50a9SSilviu Baranga     DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" << *Ptr
17541b6b50a9SSilviu Baranga                  << "\n");
17551da7df37SAdam Nemet     return {Ptr, Ptr};
17567206d7a5SAdam Nemet   } else {
17577206d7a5SAdam Nemet     unsigned AS = Ptr->getType()->getPointerAddressSpace();
17581da7df37SAdam Nemet     LLVMContext &Ctx = Loc->getContext();
17597206d7a5SAdam Nemet 
17607206d7a5SAdam Nemet     // Use this type for pointer arithmetic.
17617206d7a5SAdam Nemet     Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
17621b6b50a9SSilviu Baranga     Value *Start = nullptr, *End = nullptr;
17637206d7a5SAdam Nemet 
17641b6b50a9SSilviu Baranga     DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
17651da7df37SAdam Nemet     Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc);
17661da7df37SAdam Nemet     End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc);
17671da7df37SAdam Nemet     DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High << "\n");
17681da7df37SAdam Nemet     return {Start, End};
17697206d7a5SAdam Nemet   }
17707206d7a5SAdam Nemet }
17717206d7a5SAdam Nemet 
17721da7df37SAdam Nemet /// \brief Turns a collection of checks into a collection of expanded upper and
17731da7df37SAdam Nemet /// lower bounds for both pointers in the check.
17741da7df37SAdam Nemet static SmallVector<std::pair<PointerBounds, PointerBounds>, 4> expandBounds(
17751da7df37SAdam Nemet     const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks,
17761da7df37SAdam Nemet     Loop *L, Instruction *Loc, ScalarEvolution *SE, SCEVExpander &Exp,
17771da7df37SAdam Nemet     const RuntimePointerChecking &PtrRtChecking) {
17781da7df37SAdam Nemet   SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds;
17791da7df37SAdam Nemet 
17801da7df37SAdam Nemet   // Here we're relying on the SCEV Expander's cache to only emit code for the
17811da7df37SAdam Nemet   // same bounds once.
17821da7df37SAdam Nemet   std::transform(
17831da7df37SAdam Nemet       PointerChecks.begin(), PointerChecks.end(),
17841da7df37SAdam Nemet       std::back_inserter(ChecksWithBounds),
17851da7df37SAdam Nemet       [&](const RuntimePointerChecking::PointerCheck &Check) {
178694abbbd6SNAKAMURA Takumi         PointerBounds
178794abbbd6SNAKAMURA Takumi           First = expandBounds(Check.first, L, Loc, Exp, SE, PtrRtChecking),
178894abbbd6SNAKAMURA Takumi           Second = expandBounds(Check.second, L, Loc, Exp, SE, PtrRtChecking);
178994abbbd6SNAKAMURA Takumi         return std::make_pair(First, Second);
17901da7df37SAdam Nemet       });
17911da7df37SAdam Nemet 
17921da7df37SAdam Nemet   return ChecksWithBounds;
17931da7df37SAdam Nemet }
17941da7df37SAdam Nemet 
17955b0a4795SAdam Nemet std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeChecks(
17961da7df37SAdam Nemet     Instruction *Loc,
17971da7df37SAdam Nemet     const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks)
17981da7df37SAdam Nemet     const {
17999cd9a7e3SSilviu Baranga   auto *SE = PSE.getSE();
18001da7df37SAdam Nemet   SCEVExpander Exp(*SE, DL, "induction");
18011da7df37SAdam Nemet   auto ExpandedChecks =
18021da7df37SAdam Nemet       expandBounds(PointerChecks, TheLoop, Loc, SE, Exp, PtrRtChecking);
18031da7df37SAdam Nemet 
18041da7df37SAdam Nemet   LLVMContext &Ctx = Loc->getContext();
18051da7df37SAdam Nemet   Instruction *FirstInst = nullptr;
18067206d7a5SAdam Nemet   IRBuilder<> ChkBuilder(Loc);
18077206d7a5SAdam Nemet   // Our instructions might fold to a constant.
18087206d7a5SAdam Nemet   Value *MemoryRuntimeCheck = nullptr;
18091b6b50a9SSilviu Baranga 
18101da7df37SAdam Nemet   for (const auto &Check : ExpandedChecks) {
18111da7df37SAdam Nemet     const PointerBounds &A = Check.first, &B = Check.second;
1812cdb791cdSAdam Nemet     // Check if two pointers (A and B) conflict where conflict is computed as:
1813cdb791cdSAdam Nemet     // start(A) <= end(B) && start(B) <= end(A)
18141da7df37SAdam Nemet     unsigned AS0 = A.Start->getType()->getPointerAddressSpace();
18151da7df37SAdam Nemet     unsigned AS1 = B.Start->getType()->getPointerAddressSpace();
18167206d7a5SAdam Nemet 
18171da7df37SAdam Nemet     assert((AS0 == B.End->getType()->getPointerAddressSpace()) &&
18181da7df37SAdam Nemet            (AS1 == A.End->getType()->getPointerAddressSpace()) &&
18197206d7a5SAdam Nemet            "Trying to bounds check pointers with different address spaces");
18207206d7a5SAdam Nemet 
18217206d7a5SAdam Nemet     Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
18227206d7a5SAdam Nemet     Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
18237206d7a5SAdam Nemet 
18241da7df37SAdam Nemet     Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc");
18251da7df37SAdam Nemet     Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc");
18261da7df37SAdam Nemet     Value *End0 =   ChkBuilder.CreateBitCast(A.End,   PtrArithTy1, "bc");
18271da7df37SAdam Nemet     Value *End1 =   ChkBuilder.CreateBitCast(B.End,   PtrArithTy0, "bc");
18287206d7a5SAdam Nemet 
18297206d7a5SAdam Nemet     Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
18307206d7a5SAdam Nemet     FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
18317206d7a5SAdam Nemet     Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
18327206d7a5SAdam Nemet     FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
18337206d7a5SAdam Nemet     Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
18347206d7a5SAdam Nemet     FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
18357206d7a5SAdam Nemet     if (MemoryRuntimeCheck) {
18361da7df37SAdam Nemet       IsConflict =
18371da7df37SAdam Nemet           ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
18387206d7a5SAdam Nemet       FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
18397206d7a5SAdam Nemet     }
18407206d7a5SAdam Nemet     MemoryRuntimeCheck = IsConflict;
18417206d7a5SAdam Nemet   }
18427206d7a5SAdam Nemet 
184390fec840SAdam Nemet   if (!MemoryRuntimeCheck)
184490fec840SAdam Nemet     return std::make_pair(nullptr, nullptr);
184590fec840SAdam Nemet 
18467206d7a5SAdam Nemet   // We have to do this trickery because the IRBuilder might fold the check to a
18477206d7a5SAdam Nemet   // constant expression in which case there is no Instruction anchored in a
18487206d7a5SAdam Nemet   // the block.
18497206d7a5SAdam Nemet   Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
18507206d7a5SAdam Nemet                                                  ConstantInt::getTrue(Ctx));
18517206d7a5SAdam Nemet   ChkBuilder.Insert(Check, "memcheck.conflict");
18527206d7a5SAdam Nemet   FirstInst = getFirstInst(FirstInst, Check, Loc);
18537206d7a5SAdam Nemet   return std::make_pair(FirstInst, Check);
18547206d7a5SAdam Nemet }
18553bfd93d7SAdam Nemet 
18565b0a4795SAdam Nemet std::pair<Instruction *, Instruction *>
18575b0a4795SAdam Nemet LoopAccessInfo::addRuntimeChecks(Instruction *Loc) const {
18581da7df37SAdam Nemet   if (!PtrRtChecking.Need)
18591da7df37SAdam Nemet     return std::make_pair(nullptr, nullptr);
18601da7df37SAdam Nemet 
18615b0a4795SAdam Nemet   return addRuntimeChecks(Loc, PtrRtChecking.getChecks());
18621da7df37SAdam Nemet }
18631da7df37SAdam Nemet 
18643bfd93d7SAdam Nemet LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
1865a28d91d8SMehdi Amini                                const DataLayout &DL,
18663bfd93d7SAdam Nemet                                const TargetLibraryInfo *TLI, AliasAnalysis *AA,
1867e2b885c4SAdam Nemet                                DominatorTree *DT, LoopInfo *LI,
18688bc61df9SAdam Nemet                                const ValueToValueMap &Strides)
1869ea63a7f5SSilviu Baranga     : PSE(*SE, *L), PtrRtChecking(SE), DepChecker(PSE, L), TheLoop(L), DL(DL),
18707cdebac0SAdam Nemet       TLI(TLI), AA(AA), DT(DT), LI(LI), NumLoads(0), NumStores(0),
1871ce48250fSAdam Nemet       MaxSafeDepDistBytes(-1U), CanVecMem(false),
1872ce48250fSAdam Nemet       StoreToLoopInvariantAddress(false) {
1873929c38e8SAdam Nemet   if (canAnalyzeLoop())
18743bfd93d7SAdam Nemet     analyzeLoop(Strides);
18753bfd93d7SAdam Nemet }
18763bfd93d7SAdam Nemet 
1877e91cc6efSAdam Nemet void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1878e91cc6efSAdam Nemet   if (CanVecMem) {
18797cdebac0SAdam Nemet     if (PtrRtChecking.Need)
1880e91cc6efSAdam Nemet       OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
188126da8e98SAdam Nemet     else
188226da8e98SAdam Nemet       OS.indent(Depth) << "Memory dependences are safe\n";
1883e91cc6efSAdam Nemet   }
1884e91cc6efSAdam Nemet 
1885e91cc6efSAdam Nemet   if (Report)
1886e91cc6efSAdam Nemet     OS.indent(Depth) << "Report: " << Report->str() << "\n";
1887e91cc6efSAdam Nemet 
1888a2df750fSAdam Nemet   if (auto *Dependences = DepChecker.getDependences()) {
1889a2df750fSAdam Nemet     OS.indent(Depth) << "Dependences:\n";
1890a2df750fSAdam Nemet     for (auto &Dep : *Dependences) {
189158913d65SAdam Nemet       Dep.print(OS, Depth + 2, DepChecker.getMemoryInstructions());
189258913d65SAdam Nemet       OS << "\n";
189358913d65SAdam Nemet     }
189458913d65SAdam Nemet   } else
1895a2df750fSAdam Nemet     OS.indent(Depth) << "Too many dependences, not recorded\n";
1896e91cc6efSAdam Nemet 
1897e91cc6efSAdam Nemet   // List the pair of accesses need run-time checks to prove independence.
18987cdebac0SAdam Nemet   PtrRtChecking.print(OS, Depth);
1899e91cc6efSAdam Nemet   OS << "\n";
1900c3384320SAdam Nemet 
1901c3384320SAdam Nemet   OS.indent(Depth) << "Store to invariant address was "
1902c3384320SAdam Nemet                    << (StoreToLoopInvariantAddress ? "" : "not ")
1903c3384320SAdam Nemet                    << "found in loop.\n";
1904e3c0534bSSilviu Baranga 
1905e3c0534bSSilviu Baranga   OS.indent(Depth) << "SCEV assumptions:\n";
19069cd9a7e3SSilviu Baranga   PSE.getUnionPredicate().print(OS, Depth);
1907e91cc6efSAdam Nemet }
1908e91cc6efSAdam Nemet 
19098bc61df9SAdam Nemet const LoopAccessInfo &
19108bc61df9SAdam Nemet LoopAccessAnalysis::getInfo(Loop *L, const ValueToValueMap &Strides) {
19113bfd93d7SAdam Nemet   auto &LAI = LoopAccessInfoMap[L];
19123bfd93d7SAdam Nemet 
19133bfd93d7SAdam Nemet #ifndef NDEBUG
19143bfd93d7SAdam Nemet   assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
19153bfd93d7SAdam Nemet          "Symbolic strides changed for loop");
19163bfd93d7SAdam Nemet #endif
19173bfd93d7SAdam Nemet 
19183bfd93d7SAdam Nemet   if (!LAI) {
1919a28d91d8SMehdi Amini     const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
1920e3c0534bSSilviu Baranga     LAI =
1921e3c0534bSSilviu Baranga         llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, LI, Strides);
19223bfd93d7SAdam Nemet #ifndef NDEBUG
19233bfd93d7SAdam Nemet     LAI->NumSymbolicStrides = Strides.size();
19243bfd93d7SAdam Nemet #endif
19253bfd93d7SAdam Nemet   }
19263bfd93d7SAdam Nemet   return *LAI.get();
19273bfd93d7SAdam Nemet }
19283bfd93d7SAdam Nemet 
1929e91cc6efSAdam Nemet void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
1930e91cc6efSAdam Nemet   LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
1931e91cc6efSAdam Nemet 
1932e91cc6efSAdam Nemet   ValueToValueMap NoSymbolicStrides;
1933e91cc6efSAdam Nemet 
1934e91cc6efSAdam Nemet   for (Loop *TopLevelLoop : *LI)
1935e91cc6efSAdam Nemet     for (Loop *L : depth_first(TopLevelLoop)) {
1936e91cc6efSAdam Nemet       OS.indent(2) << L->getHeader()->getName() << ":\n";
1937e91cc6efSAdam Nemet       auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
1938e91cc6efSAdam Nemet       LAI.print(OS, 4);
1939e91cc6efSAdam Nemet     }
1940e91cc6efSAdam Nemet }
1941e91cc6efSAdam Nemet 
19423bfd93d7SAdam Nemet bool LoopAccessAnalysis::runOnFunction(Function &F) {
19432f1fd165SChandler Carruth   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
19443bfd93d7SAdam Nemet   auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
19453bfd93d7SAdam Nemet   TLI = TLIP ? &TLIP->getTLI() : nullptr;
19467b560d40SChandler Carruth   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
19473bfd93d7SAdam Nemet   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1948e2b885c4SAdam Nemet   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
19493bfd93d7SAdam Nemet 
19503bfd93d7SAdam Nemet   return false;
19513bfd93d7SAdam Nemet }
19523bfd93d7SAdam Nemet 
19533bfd93d7SAdam Nemet void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
19542f1fd165SChandler Carruth     AU.addRequired<ScalarEvolutionWrapperPass>();
19557b560d40SChandler Carruth     AU.addRequired<AAResultsWrapperPass>();
19563bfd93d7SAdam Nemet     AU.addRequired<DominatorTreeWrapperPass>();
1957e91cc6efSAdam Nemet     AU.addRequired<LoopInfoWrapperPass>();
19583bfd93d7SAdam Nemet 
19593bfd93d7SAdam Nemet     AU.setPreservesAll();
19603bfd93d7SAdam Nemet }
19613bfd93d7SAdam Nemet 
19623bfd93d7SAdam Nemet char LoopAccessAnalysis::ID = 0;
19633bfd93d7SAdam Nemet static const char laa_name[] = "Loop Access Analysis";
19643bfd93d7SAdam Nemet #define LAA_NAME "loop-accesses"
19653bfd93d7SAdam Nemet 
19663bfd93d7SAdam Nemet INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
19677b560d40SChandler Carruth INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
19682f1fd165SChandler Carruth INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
19693bfd93d7SAdam Nemet INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1970e91cc6efSAdam Nemet INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
19713bfd93d7SAdam Nemet INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
19723bfd93d7SAdam Nemet 
19733bfd93d7SAdam Nemet namespace llvm {
19743bfd93d7SAdam Nemet   Pass *createLAAPass() {
19753bfd93d7SAdam Nemet     return new LoopAccessAnalysis();
19763bfd93d7SAdam Nemet   }
19773bfd93d7SAdam Nemet }
1978