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);
1330456327cSAdam Nemet   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
1340456327cSAdam Nemet   assert(AR && "Invalid addrec expression");
1359cd9a7e3SSilviu Baranga   ScalarEvolution *SE = PSE.getSE();
1360456327cSAdam Nemet   const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
1370e5804a6SSilviu Baranga 
1380e5804a6SSilviu Baranga   const SCEV *ScStart = AR->getStart();
1390456327cSAdam Nemet   const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
1400e5804a6SSilviu Baranga   const SCEV *Step = AR->getStepRecurrence(*SE);
1410e5804a6SSilviu Baranga 
1420e5804a6SSilviu Baranga   // For expressions with negative step, the upper bound is ScStart and the
1430e5804a6SSilviu Baranga   // lower bound is ScEnd.
1440e5804a6SSilviu Baranga   if (const SCEVConstant *CStep = dyn_cast<const SCEVConstant>(Step)) {
1450e5804a6SSilviu Baranga     if (CStep->getValue()->isNegative())
1460e5804a6SSilviu Baranga       std::swap(ScStart, ScEnd);
1470e5804a6SSilviu Baranga   } else {
1480e5804a6SSilviu Baranga     // Fallback case: the step is not constant, but the we can still
1490e5804a6SSilviu Baranga     // get the upper and lower bounds of the interval by using min/max
1500e5804a6SSilviu Baranga     // expressions.
1510e5804a6SSilviu Baranga     ScStart = SE->getUMinExpr(ScStart, ScEnd);
1520e5804a6SSilviu Baranga     ScEnd = SE->getUMaxExpr(AR->getStart(), ScEnd);
1530e5804a6SSilviu Baranga   }
1540e5804a6SSilviu Baranga 
1550e5804a6SSilviu Baranga   Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, Sc);
1561b6b50a9SSilviu Baranga }
1571b6b50a9SSilviu Baranga 
158bbe1f1deSAdam Nemet SmallVector<RuntimePointerChecking::PointerCheck, 4>
15938530887SAdam Nemet RuntimePointerChecking::generateChecks() const {
160bbe1f1deSAdam Nemet   SmallVector<PointerCheck, 4> Checks;
161bbe1f1deSAdam Nemet 
1627c52e052SAdam Nemet   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
1637c52e052SAdam Nemet     for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) {
1647c52e052SAdam Nemet       const RuntimePointerChecking::CheckingPtrGroup &CGI = CheckingGroups[I];
1657c52e052SAdam Nemet       const RuntimePointerChecking::CheckingPtrGroup &CGJ = CheckingGroups[J];
166bbe1f1deSAdam Nemet 
16738530887SAdam Nemet       if (needsChecking(CGI, CGJ))
168bbe1f1deSAdam Nemet         Checks.push_back(std::make_pair(&CGI, &CGJ));
169bbe1f1deSAdam Nemet     }
170bbe1f1deSAdam Nemet   }
171bbe1f1deSAdam Nemet   return Checks;
172bbe1f1deSAdam Nemet }
173bbe1f1deSAdam Nemet 
17415840393SAdam Nemet void RuntimePointerChecking::generateChecks(
17515840393SAdam Nemet     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
17615840393SAdam Nemet   assert(Checks.empty() && "Checks is not empty");
17715840393SAdam Nemet   groupChecks(DepCands, UseDependencies);
17815840393SAdam Nemet   Checks = generateChecks();
17915840393SAdam Nemet }
18015840393SAdam Nemet 
181651a5a24SAdam Nemet bool RuntimePointerChecking::needsChecking(const CheckingPtrGroup &M,
182651a5a24SAdam Nemet                                            const CheckingPtrGroup &N) const {
1831b6b50a9SSilviu Baranga   for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I)
1841b6b50a9SSilviu Baranga     for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J)
185651a5a24SAdam Nemet       if (needsChecking(M.Members[I], N.Members[J]))
1861b6b50a9SSilviu Baranga         return true;
1871b6b50a9SSilviu Baranga   return false;
1881b6b50a9SSilviu Baranga }
1891b6b50a9SSilviu Baranga 
1901b6b50a9SSilviu Baranga /// Compare \p I and \p J and return the minimum.
1911b6b50a9SSilviu Baranga /// Return nullptr in case we couldn't find an answer.
1921b6b50a9SSilviu Baranga static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
1931b6b50a9SSilviu Baranga                                    ScalarEvolution *SE) {
1941b6b50a9SSilviu Baranga   const SCEV *Diff = SE->getMinusSCEV(J, I);
1951b6b50a9SSilviu Baranga   const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
1961b6b50a9SSilviu Baranga 
1971b6b50a9SSilviu Baranga   if (!C)
1981b6b50a9SSilviu Baranga     return nullptr;
1991b6b50a9SSilviu Baranga   if (C->getValue()->isNegative())
2001b6b50a9SSilviu Baranga     return J;
2011b6b50a9SSilviu Baranga   return I;
2021b6b50a9SSilviu Baranga }
2031b6b50a9SSilviu Baranga 
2047cdebac0SAdam Nemet bool RuntimePointerChecking::CheckingPtrGroup::addPointer(unsigned Index) {
2059f7dedc3SAdam Nemet   const SCEV *Start = RtCheck.Pointers[Index].Start;
2069f7dedc3SAdam Nemet   const SCEV *End = RtCheck.Pointers[Index].End;
2079f7dedc3SAdam Nemet 
2081b6b50a9SSilviu Baranga   // Compare the starts and ends with the known minimum and maximum
2091b6b50a9SSilviu Baranga   // of this set. We need to know how we compare against the min/max
2101b6b50a9SSilviu Baranga   // of the set in order to be able to emit memchecks.
2119f7dedc3SAdam Nemet   const SCEV *Min0 = getMinFromExprs(Start, Low, RtCheck.SE);
2121b6b50a9SSilviu Baranga   if (!Min0)
2131b6b50a9SSilviu Baranga     return false;
2141b6b50a9SSilviu Baranga 
2159f7dedc3SAdam Nemet   const SCEV *Min1 = getMinFromExprs(End, High, RtCheck.SE);
2161b6b50a9SSilviu Baranga   if (!Min1)
2171b6b50a9SSilviu Baranga     return false;
2181b6b50a9SSilviu Baranga 
2191b6b50a9SSilviu Baranga   // Update the low bound  expression if we've found a new min value.
2209f7dedc3SAdam Nemet   if (Min0 == Start)
2219f7dedc3SAdam Nemet     Low = Start;
2221b6b50a9SSilviu Baranga 
2231b6b50a9SSilviu Baranga   // Update the high bound expression if we've found a new max value.
2249f7dedc3SAdam Nemet   if (Min1 != End)
2259f7dedc3SAdam Nemet     High = End;
2261b6b50a9SSilviu Baranga 
2271b6b50a9SSilviu Baranga   Members.push_back(Index);
2281b6b50a9SSilviu Baranga   return true;
2291b6b50a9SSilviu Baranga }
2301b6b50a9SSilviu Baranga 
2317cdebac0SAdam Nemet void RuntimePointerChecking::groupChecks(
2327cdebac0SAdam Nemet     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
2331b6b50a9SSilviu Baranga   // We build the groups from dependency candidates equivalence classes
2341b6b50a9SSilviu Baranga   // because:
2351b6b50a9SSilviu Baranga   //    - We know that pointers in the same equivalence class share
2361b6b50a9SSilviu Baranga   //      the same underlying object and therefore there is a chance
2371b6b50a9SSilviu Baranga   //      that we can compare pointers
2381b6b50a9SSilviu Baranga   //    - We wouldn't be able to merge two pointers for which we need
2391b6b50a9SSilviu Baranga   //      to emit a memcheck. The classes in DepCands are already
2401b6b50a9SSilviu Baranga   //      conveniently built such that no two pointers in the same
2411b6b50a9SSilviu Baranga   //      class need checking against each other.
2421b6b50a9SSilviu Baranga 
2431b6b50a9SSilviu Baranga   // We use the following (greedy) algorithm to construct the groups
2441b6b50a9SSilviu Baranga   // For every pointer in the equivalence class:
2451b6b50a9SSilviu Baranga   //   For each existing group:
2461b6b50a9SSilviu Baranga   //   - if the difference between this pointer and the min/max bounds
2471b6b50a9SSilviu Baranga   //     of the group is a constant, then make the pointer part of the
2481b6b50a9SSilviu Baranga   //     group and update the min/max bounds of that group as required.
2491b6b50a9SSilviu Baranga 
2501b6b50a9SSilviu Baranga   CheckingGroups.clear();
2511b6b50a9SSilviu Baranga 
25248250600SSilviu Baranga   // If we need to check two pointers to the same underlying object
25348250600SSilviu Baranga   // with a non-constant difference, we shouldn't perform any pointer
25448250600SSilviu Baranga   // grouping with those pointers. This is because we can easily get
25548250600SSilviu Baranga   // into cases where the resulting check would return false, even when
25648250600SSilviu Baranga   // the accesses are safe.
25748250600SSilviu Baranga   //
25848250600SSilviu Baranga   // The following example shows this:
25948250600SSilviu Baranga   // for (i = 0; i < 1000; ++i)
26048250600SSilviu Baranga   //   a[5000 + i * m] = a[i] + a[i + 9000]
26148250600SSilviu Baranga   //
26248250600SSilviu Baranga   // Here grouping gives a check of (5000, 5000 + 1000 * m) against
26348250600SSilviu Baranga   // (0, 10000) which is always false. However, if m is 1, there is no
26448250600SSilviu Baranga   // dependence. Not grouping the checks for a[i] and a[i + 9000] allows
26548250600SSilviu Baranga   // us to perform an accurate check in this case.
26648250600SSilviu Baranga   //
26748250600SSilviu Baranga   // The above case requires that we have an UnknownDependence between
26848250600SSilviu Baranga   // accesses to the same underlying object. This cannot happen unless
26948250600SSilviu Baranga   // ShouldRetryWithRuntimeCheck is set, and therefore UseDependencies
27048250600SSilviu Baranga   // is also false. In this case we will use the fallback path and create
27148250600SSilviu Baranga   // separate checking groups for all pointers.
27248250600SSilviu Baranga 
2731b6b50a9SSilviu Baranga   // If we don't have the dependency partitions, construct a new
27448250600SSilviu Baranga   // checking pointer group for each pointer. This is also required
27548250600SSilviu Baranga   // for correctness, because in this case we can have checking between
27648250600SSilviu Baranga   // pointers to the same underlying object.
2771b6b50a9SSilviu Baranga   if (!UseDependencies) {
2781b6b50a9SSilviu Baranga     for (unsigned I = 0; I < Pointers.size(); ++I)
2791b6b50a9SSilviu Baranga       CheckingGroups.push_back(CheckingPtrGroup(I, *this));
2801b6b50a9SSilviu Baranga     return;
2811b6b50a9SSilviu Baranga   }
2821b6b50a9SSilviu Baranga 
2831b6b50a9SSilviu Baranga   unsigned TotalComparisons = 0;
2841b6b50a9SSilviu Baranga 
2851b6b50a9SSilviu Baranga   DenseMap<Value *, unsigned> PositionMap;
2869f7dedc3SAdam Nemet   for (unsigned Index = 0; Index < Pointers.size(); ++Index)
2879f7dedc3SAdam Nemet     PositionMap[Pointers[Index].PointerValue] = Index;
2881b6b50a9SSilviu Baranga 
289ce3877fcSSilviu Baranga   // We need to keep track of what pointers we've already seen so we
290ce3877fcSSilviu Baranga   // don't process them twice.
291ce3877fcSSilviu Baranga   SmallSet<unsigned, 2> Seen;
292ce3877fcSSilviu Baranga 
293e4b9f507SSanjay Patel   // Go through all equivalence classes, get the "pointer check groups"
294ce3877fcSSilviu Baranga   // and add them to the overall solution. We use the order in which accesses
295ce3877fcSSilviu Baranga   // appear in 'Pointers' to enforce determinism.
296ce3877fcSSilviu Baranga   for (unsigned I = 0; I < Pointers.size(); ++I) {
297ce3877fcSSilviu Baranga     // We've seen this pointer before, and therefore already processed
298ce3877fcSSilviu Baranga     // its equivalence class.
299ce3877fcSSilviu Baranga     if (Seen.count(I))
3001b6b50a9SSilviu Baranga       continue;
3011b6b50a9SSilviu Baranga 
3029f7dedc3SAdam Nemet     MemoryDepChecker::MemAccessInfo Access(Pointers[I].PointerValue,
3039f7dedc3SAdam Nemet                                            Pointers[I].IsWritePtr);
3041b6b50a9SSilviu Baranga 
305ce3877fcSSilviu Baranga     SmallVector<CheckingPtrGroup, 2> Groups;
306ce3877fcSSilviu Baranga     auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access));
307ce3877fcSSilviu Baranga 
308a647c30fSSilviu Baranga     // Because DepCands is constructed by visiting accesses in the order in
309a647c30fSSilviu Baranga     // which they appear in alias sets (which is deterministic) and the
310a647c30fSSilviu Baranga     // iteration order within an equivalence class member is only dependent on
311a647c30fSSilviu Baranga     // the order in which unions and insertions are performed on the
312a647c30fSSilviu Baranga     // equivalence class, the iteration order is deterministic.
313ce3877fcSSilviu Baranga     for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end();
3141b6b50a9SSilviu Baranga          MI != ME; ++MI) {
3151b6b50a9SSilviu Baranga       unsigned Pointer = PositionMap[MI->getPointer()];
3161b6b50a9SSilviu Baranga       bool Merged = false;
317ce3877fcSSilviu Baranga       // Mark this pointer as seen.
318ce3877fcSSilviu Baranga       Seen.insert(Pointer);
3191b6b50a9SSilviu Baranga 
3201b6b50a9SSilviu Baranga       // Go through all the existing sets and see if we can find one
3211b6b50a9SSilviu Baranga       // which can include this pointer.
3221b6b50a9SSilviu Baranga       for (CheckingPtrGroup &Group : Groups) {
3231b6b50a9SSilviu Baranga         // Don't perform more than a certain amount of comparisons.
3241b6b50a9SSilviu Baranga         // This should limit the cost of grouping the pointers to something
3251b6b50a9SSilviu Baranga         // reasonable.  If we do end up hitting this threshold, the algorithm
3261b6b50a9SSilviu Baranga         // will create separate groups for all remaining pointers.
3271b6b50a9SSilviu Baranga         if (TotalComparisons > MemoryCheckMergeThreshold)
3281b6b50a9SSilviu Baranga           break;
3291b6b50a9SSilviu Baranga 
3301b6b50a9SSilviu Baranga         TotalComparisons++;
3311b6b50a9SSilviu Baranga 
3321b6b50a9SSilviu Baranga         if (Group.addPointer(Pointer)) {
3331b6b50a9SSilviu Baranga           Merged = true;
3341b6b50a9SSilviu Baranga           break;
3351b6b50a9SSilviu Baranga         }
3361b6b50a9SSilviu Baranga       }
3371b6b50a9SSilviu Baranga 
3381b6b50a9SSilviu Baranga       if (!Merged)
3391b6b50a9SSilviu Baranga         // We couldn't add this pointer to any existing set or the threshold
3401b6b50a9SSilviu Baranga         // for the number of comparisons has been reached. Create a new group
3411b6b50a9SSilviu Baranga         // to hold the current pointer.
3421b6b50a9SSilviu Baranga         Groups.push_back(CheckingPtrGroup(Pointer, *this));
3431b6b50a9SSilviu Baranga     }
3441b6b50a9SSilviu Baranga 
3451b6b50a9SSilviu Baranga     // We've computed the grouped checks for this partition.
3461b6b50a9SSilviu Baranga     // Save the results and continue with the next one.
3471b6b50a9SSilviu Baranga     std::copy(Groups.begin(), Groups.end(), std::back_inserter(CheckingGroups));
3481b6b50a9SSilviu Baranga   }
3490456327cSAdam Nemet }
3500456327cSAdam Nemet 
351041e6debSAdam Nemet bool RuntimePointerChecking::arePointersInSamePartition(
352041e6debSAdam Nemet     const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
353041e6debSAdam Nemet     unsigned PtrIdx2) {
354041e6debSAdam Nemet   return (PtrToPartition[PtrIdx1] != -1 &&
355041e6debSAdam Nemet           PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
356041e6debSAdam Nemet }
357041e6debSAdam Nemet 
358651a5a24SAdam Nemet bool RuntimePointerChecking::needsChecking(unsigned I, unsigned J) const {
3599f7dedc3SAdam Nemet   const PointerInfo &PointerI = Pointers[I];
3609f7dedc3SAdam Nemet   const PointerInfo &PointerJ = Pointers[J];
3619f7dedc3SAdam Nemet 
362a8945b77SAdam Nemet   // No need to check if two readonly pointers intersect.
3639f7dedc3SAdam Nemet   if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
364a8945b77SAdam Nemet     return false;
365a8945b77SAdam Nemet 
366a8945b77SAdam Nemet   // Only need to check pointers between two different dependency sets.
3679f7dedc3SAdam Nemet   if (PointerI.DependencySetId == PointerJ.DependencySetId)
368a8945b77SAdam Nemet     return false;
369a8945b77SAdam Nemet 
370a8945b77SAdam Nemet   // Only need to check pointers in the same alias set.
3719f7dedc3SAdam Nemet   if (PointerI.AliasSetId != PointerJ.AliasSetId)
372a8945b77SAdam Nemet     return false;
373a8945b77SAdam Nemet 
374a8945b77SAdam Nemet   return true;
375a8945b77SAdam Nemet }
376a8945b77SAdam Nemet 
37754f0b83eSAdam Nemet void RuntimePointerChecking::printChecks(
37854f0b83eSAdam Nemet     raw_ostream &OS, const SmallVectorImpl<PointerCheck> &Checks,
37954f0b83eSAdam Nemet     unsigned Depth) const {
38054f0b83eSAdam Nemet   unsigned N = 0;
38154f0b83eSAdam Nemet   for (const auto &Check : Checks) {
38254f0b83eSAdam Nemet     const auto &First = Check.first->Members, &Second = Check.second->Members;
38354f0b83eSAdam Nemet 
38454f0b83eSAdam Nemet     OS.indent(Depth) << "Check " << N++ << ":\n";
38554f0b83eSAdam Nemet 
38654f0b83eSAdam Nemet     OS.indent(Depth + 2) << "Comparing group (" << Check.first << "):\n";
38754f0b83eSAdam Nemet     for (unsigned K = 0; K < First.size(); ++K)
38854f0b83eSAdam Nemet       OS.indent(Depth + 2) << *Pointers[First[K]].PointerValue << "\n";
38954f0b83eSAdam Nemet 
39054f0b83eSAdam Nemet     OS.indent(Depth + 2) << "Against group (" << Check.second << "):\n";
39154f0b83eSAdam Nemet     for (unsigned K = 0; K < Second.size(); ++K)
39254f0b83eSAdam Nemet       OS.indent(Depth + 2) << *Pointers[Second[K]].PointerValue << "\n";
39354f0b83eSAdam Nemet   }
39454f0b83eSAdam Nemet }
39554f0b83eSAdam Nemet 
3963a91e947SAdam Nemet void RuntimePointerChecking::print(raw_ostream &OS, unsigned Depth) const {
397e91cc6efSAdam Nemet 
398e91cc6efSAdam Nemet   OS.indent(Depth) << "Run-time memory checks:\n";
39915840393SAdam Nemet   printChecks(OS, Checks, Depth);
4001b6b50a9SSilviu Baranga 
4011b6b50a9SSilviu Baranga   OS.indent(Depth) << "Grouped accesses:\n";
4021b6b50a9SSilviu Baranga   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
40354f0b83eSAdam Nemet     const auto &CG = CheckingGroups[I];
40454f0b83eSAdam Nemet 
40554f0b83eSAdam Nemet     OS.indent(Depth + 2) << "Group " << &CG << ":\n";
40654f0b83eSAdam Nemet     OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High
40754f0b83eSAdam Nemet                          << ")\n";
40854f0b83eSAdam Nemet     for (unsigned J = 0; J < CG.Members.size(); ++J) {
40954f0b83eSAdam Nemet       OS.indent(Depth + 6) << "Member: " << *Pointers[CG.Members[J]].Expr
4101b6b50a9SSilviu Baranga                            << "\n";
4111b6b50a9SSilviu Baranga     }
412e91cc6efSAdam Nemet   }
413e91cc6efSAdam Nemet }
414e91cc6efSAdam Nemet 
4150456327cSAdam Nemet namespace {
4160456327cSAdam Nemet /// \brief Analyses memory accesses in a loop.
4170456327cSAdam Nemet ///
4180456327cSAdam Nemet /// Checks whether run time pointer checks are needed and builds sets for data
4190456327cSAdam Nemet /// dependence checking.
4200456327cSAdam Nemet class AccessAnalysis {
4210456327cSAdam Nemet public:
4220456327cSAdam Nemet   /// \brief Read or write access location.
4230456327cSAdam Nemet   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
4240456327cSAdam Nemet   typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
4250456327cSAdam Nemet 
426e2b885c4SAdam Nemet   AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA, LoopInfo *LI,
4279cd9a7e3SSilviu Baranga                  MemoryDepChecker::DepCandidates &DA,
4289cd9a7e3SSilviu Baranga                  PredicatedScalarEvolution &PSE)
429e3c0534bSSilviu Baranga       : DL(Dl), AST(*AA), LI(LI), DepCands(DA), IsRTCheckAnalysisNeeded(false),
4309cd9a7e3SSilviu Baranga         PSE(PSE) {}
4310456327cSAdam Nemet 
4320456327cSAdam Nemet   /// \brief Register a load  and whether it is only read from.
433ac80dc75SChandler Carruth   void addLoad(MemoryLocation &Loc, bool IsReadOnly) {
4340456327cSAdam Nemet     Value *Ptr = const_cast<Value*>(Loc.Ptr);
435ecbd1682SChandler Carruth     AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
4360456327cSAdam Nemet     Accesses.insert(MemAccessInfo(Ptr, false));
4370456327cSAdam Nemet     if (IsReadOnly)
4380456327cSAdam Nemet       ReadOnlyPtr.insert(Ptr);
4390456327cSAdam Nemet   }
4400456327cSAdam Nemet 
4410456327cSAdam Nemet   /// \brief Register a store.
442ac80dc75SChandler Carruth   void addStore(MemoryLocation &Loc) {
4430456327cSAdam Nemet     Value *Ptr = const_cast<Value*>(Loc.Ptr);
444ecbd1682SChandler Carruth     AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
4450456327cSAdam Nemet     Accesses.insert(MemAccessInfo(Ptr, true));
4460456327cSAdam Nemet   }
4470456327cSAdam Nemet 
4480456327cSAdam Nemet   /// \brief Check whether we can check the pointers at runtime for
449ee61474aSAdam Nemet   /// non-intersection.
450ee61474aSAdam Nemet   ///
451ee61474aSAdam Nemet   /// Returns true if we need no check or if we do and we can generate them
452ee61474aSAdam Nemet   /// (i.e. the pointers have computable bounds).
4537cdebac0SAdam Nemet   bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE,
4547cdebac0SAdam Nemet                        Loop *TheLoop, const ValueToValueMap &Strides,
4550456327cSAdam Nemet                        bool ShouldCheckStride = false);
4560456327cSAdam Nemet 
4570456327cSAdam Nemet   /// \brief Goes over all memory accesses, checks whether a RT check is needed
4580456327cSAdam Nemet   /// and builds sets of dependent accesses.
4590456327cSAdam Nemet   void buildDependenceSets() {
4600456327cSAdam Nemet     processMemAccesses();
4610456327cSAdam Nemet   }
4620456327cSAdam Nemet 
4635dc3b2cfSAdam Nemet   /// \brief Initial processing of memory accesses determined that we need to
4645dc3b2cfSAdam Nemet   /// perform dependency checking.
4655dc3b2cfSAdam Nemet   ///
4665dc3b2cfSAdam Nemet   /// Note that this can later be cleared if we retry memcheck analysis without
4675dc3b2cfSAdam Nemet   /// dependency checking (i.e. ShouldRetryWithRuntimeCheck).
4680456327cSAdam Nemet   bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
469df3dc5b9SAdam Nemet 
470df3dc5b9SAdam Nemet   /// We decided that no dependence analysis would be used.  Reset the state.
471df3dc5b9SAdam Nemet   void resetDepChecks(MemoryDepChecker &DepChecker) {
472df3dc5b9SAdam Nemet     CheckDeps.clear();
473a2df750fSAdam Nemet     DepChecker.clearDependences();
474df3dc5b9SAdam Nemet   }
4750456327cSAdam Nemet 
4760456327cSAdam Nemet   MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
4770456327cSAdam Nemet 
4780456327cSAdam Nemet private:
4790456327cSAdam Nemet   typedef SetVector<MemAccessInfo> PtrAccessSet;
4800456327cSAdam Nemet 
4810456327cSAdam Nemet   /// \brief Go over all memory access and check whether runtime pointer checks
482b41d2d3fSAdam Nemet   /// are needed and build sets of dependency check candidates.
4830456327cSAdam Nemet   void processMemAccesses();
4840456327cSAdam Nemet 
4850456327cSAdam Nemet   /// Set of all accesses.
4860456327cSAdam Nemet   PtrAccessSet Accesses;
4870456327cSAdam Nemet 
488a28d91d8SMehdi Amini   const DataLayout &DL;
489a28d91d8SMehdi Amini 
4900456327cSAdam Nemet   /// Set of accesses that need a further dependence check.
4910456327cSAdam Nemet   MemAccessInfoSet CheckDeps;
4920456327cSAdam Nemet 
4930456327cSAdam Nemet   /// Set of pointers that are read only.
4940456327cSAdam Nemet   SmallPtrSet<Value*, 16> ReadOnlyPtr;
4950456327cSAdam Nemet 
4960456327cSAdam Nemet   /// An alias set tracker to partition the access set by underlying object and
4970456327cSAdam Nemet   //intrinsic property (such as TBAA metadata).
4980456327cSAdam Nemet   AliasSetTracker AST;
4990456327cSAdam Nemet 
500e2b885c4SAdam Nemet   LoopInfo *LI;
501e2b885c4SAdam Nemet 
5020456327cSAdam Nemet   /// Sets of potentially dependent accesses - members of one set share an
5030456327cSAdam Nemet   /// underlying pointer. The set "CheckDeps" identfies which sets really need a
5040456327cSAdam Nemet   /// dependence check.
505dee666bcSAdam Nemet   MemoryDepChecker::DepCandidates &DepCands;
5060456327cSAdam Nemet 
5075dc3b2cfSAdam Nemet   /// \brief Initial processing of memory accesses determined that we may need
5085dc3b2cfSAdam Nemet   /// to add memchecks.  Perform the analysis to determine the necessary checks.
5095dc3b2cfSAdam Nemet   ///
5105dc3b2cfSAdam Nemet   /// Note that, this is different from isDependencyCheckNeeded.  When we retry
5115dc3b2cfSAdam Nemet   /// memcheck analysis without dependency checking
5125dc3b2cfSAdam Nemet   /// (i.e. ShouldRetryWithRuntimeCheck), isDependencyCheckNeeded is cleared
5135dc3b2cfSAdam Nemet   /// while this remains set if we have potentially dependent accesses.
5145dc3b2cfSAdam Nemet   bool IsRTCheckAnalysisNeeded;
515e3c0534bSSilviu Baranga 
516e3c0534bSSilviu Baranga   /// The SCEV predicate containing all the SCEV-related assumptions.
5179cd9a7e3SSilviu Baranga   PredicatedScalarEvolution &PSE;
5180456327cSAdam Nemet };
5190456327cSAdam Nemet 
5200456327cSAdam Nemet } // end anonymous namespace
5210456327cSAdam Nemet 
5220456327cSAdam Nemet /// \brief Check whether a pointer can participate in a runtime bounds check.
5239cd9a7e3SSilviu Baranga static bool hasComputableBounds(PredicatedScalarEvolution &PSE,
524e3c0534bSSilviu Baranga                                 const ValueToValueMap &Strides, Value *Ptr,
5259cd9a7e3SSilviu Baranga                                 Loop *L) {
5269cd9a7e3SSilviu Baranga   const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
5270456327cSAdam Nemet   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
5280456327cSAdam Nemet   if (!AR)
5290456327cSAdam Nemet     return false;
5300456327cSAdam Nemet 
5310456327cSAdam Nemet   return AR->isAffine();
5320456327cSAdam Nemet }
5330456327cSAdam Nemet 
5347cdebac0SAdam Nemet bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
5357cdebac0SAdam Nemet                                      ScalarEvolution *SE, Loop *TheLoop,
5367cdebac0SAdam Nemet                                      const ValueToValueMap &StridesMap,
5377cdebac0SAdam Nemet                                      bool ShouldCheckStride) {
5380456327cSAdam Nemet   // Find pointers with computable bounds. We are going to use this information
5390456327cSAdam Nemet   // to place a runtime bound check.
5400456327cSAdam Nemet   bool CanDoRT = true;
5410456327cSAdam Nemet 
542ee61474aSAdam Nemet   bool NeedRTCheck = false;
5435dc3b2cfSAdam Nemet   if (!IsRTCheckAnalysisNeeded) return true;
54498a13719SSilviu Baranga 
5450456327cSAdam Nemet   bool IsDepCheckNeeded = isDependencyCheckNeeded();
5460456327cSAdam Nemet 
5470456327cSAdam Nemet   // We assign a consecutive id to access from different alias sets.
5480456327cSAdam Nemet   // Accesses between different groups doesn't need to be checked.
5490456327cSAdam Nemet   unsigned ASId = 1;
5500456327cSAdam Nemet   for (auto &AS : AST) {
551424edc6cSAdam Nemet     int NumReadPtrChecks = 0;
552424edc6cSAdam Nemet     int NumWritePtrChecks = 0;
553424edc6cSAdam Nemet 
5540456327cSAdam Nemet     // We assign consecutive id to access from different dependence sets.
5550456327cSAdam Nemet     // Accesses within the same set don't need a runtime check.
5560456327cSAdam Nemet     unsigned RunningDepId = 1;
5570456327cSAdam Nemet     DenseMap<Value *, unsigned> DepSetId;
5580456327cSAdam Nemet 
5590456327cSAdam Nemet     for (auto A : AS) {
5600456327cSAdam Nemet       Value *Ptr = A.getValue();
5610456327cSAdam Nemet       bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
5620456327cSAdam Nemet       MemAccessInfo Access(Ptr, IsWrite);
5630456327cSAdam Nemet 
564424edc6cSAdam Nemet       if (IsWrite)
565424edc6cSAdam Nemet         ++NumWritePtrChecks;
566424edc6cSAdam Nemet       else
567424edc6cSAdam Nemet         ++NumReadPtrChecks;
568424edc6cSAdam Nemet 
5699cd9a7e3SSilviu Baranga       if (hasComputableBounds(PSE, StridesMap, Ptr, TheLoop) &&
570a28d91d8SMehdi Amini           // When we run after a failing dependency check we have to make sure
571a28d91d8SMehdi Amini           // we don't have wrapping pointers.
5720456327cSAdam Nemet           (!ShouldCheckStride ||
5739cd9a7e3SSilviu Baranga            isStridedPtr(PSE, Ptr, TheLoop, StridesMap) == 1)) {
5740456327cSAdam Nemet         // The id of the dependence set.
5750456327cSAdam Nemet         unsigned DepId;
5760456327cSAdam Nemet 
5770456327cSAdam Nemet         if (IsDepCheckNeeded) {
5780456327cSAdam Nemet           Value *Leader = DepCands.getLeaderValue(Access).getPointer();
5790456327cSAdam Nemet           unsigned &LeaderId = DepSetId[Leader];
5800456327cSAdam Nemet           if (!LeaderId)
5810456327cSAdam Nemet             LeaderId = RunningDepId++;
5820456327cSAdam Nemet           DepId = LeaderId;
5830456327cSAdam Nemet         } else
5840456327cSAdam Nemet           // Each access has its own dependence set.
5850456327cSAdam Nemet           DepId = RunningDepId++;
5860456327cSAdam Nemet 
5879cd9a7e3SSilviu Baranga         RtCheck.insert(TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap, PSE);
5880456327cSAdam Nemet 
589339f42b3SAdam Nemet         DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
5900456327cSAdam Nemet       } else {
591f10ca278SAdam Nemet         DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" << *Ptr << '\n');
5920456327cSAdam Nemet         CanDoRT = false;
5930456327cSAdam Nemet       }
5940456327cSAdam Nemet     }
5950456327cSAdam Nemet 
596424edc6cSAdam Nemet     // If we have at least two writes or one write and a read then we need to
597424edc6cSAdam Nemet     // check them.  But there is no need to checks if there is only one
598424edc6cSAdam Nemet     // dependence set for this alias set.
599424edc6cSAdam Nemet     //
600424edc6cSAdam Nemet     // Note that this function computes CanDoRT and NeedRTCheck independently.
601424edc6cSAdam Nemet     // For example CanDoRT=false, NeedRTCheck=false means that we have a pointer
602424edc6cSAdam Nemet     // for which we couldn't find the bounds but we don't actually need to emit
603424edc6cSAdam Nemet     // any checks so it does not matter.
604424edc6cSAdam Nemet     if (!(IsDepCheckNeeded && CanDoRT && RunningDepId == 2))
605424edc6cSAdam Nemet       NeedRTCheck |= (NumWritePtrChecks >= 2 || (NumReadPtrChecks >= 1 &&
606424edc6cSAdam Nemet                                                  NumWritePtrChecks >= 1));
607424edc6cSAdam Nemet 
6080456327cSAdam Nemet     ++ASId;
6090456327cSAdam Nemet   }
6100456327cSAdam Nemet 
6110456327cSAdam Nemet   // If the pointers that we would use for the bounds comparison have different
6120456327cSAdam Nemet   // address spaces, assume the values aren't directly comparable, so we can't
6130456327cSAdam Nemet   // use them for the runtime check. We also have to assume they could
6140456327cSAdam Nemet   // overlap. In the future there should be metadata for whether address spaces
6150456327cSAdam Nemet   // are disjoint.
6160456327cSAdam Nemet   unsigned NumPointers = RtCheck.Pointers.size();
6170456327cSAdam Nemet   for (unsigned i = 0; i < NumPointers; ++i) {
6180456327cSAdam Nemet     for (unsigned j = i + 1; j < NumPointers; ++j) {
6190456327cSAdam Nemet       // Only need to check pointers between two different dependency sets.
6209f7dedc3SAdam Nemet       if (RtCheck.Pointers[i].DependencySetId ==
6219f7dedc3SAdam Nemet           RtCheck.Pointers[j].DependencySetId)
6220456327cSAdam Nemet        continue;
6230456327cSAdam Nemet       // Only need to check pointers in the same alias set.
6249f7dedc3SAdam Nemet       if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
6250456327cSAdam Nemet         continue;
6260456327cSAdam Nemet 
6279f7dedc3SAdam Nemet       Value *PtrI = RtCheck.Pointers[i].PointerValue;
6289f7dedc3SAdam Nemet       Value *PtrJ = RtCheck.Pointers[j].PointerValue;
6290456327cSAdam Nemet 
6300456327cSAdam Nemet       unsigned ASi = PtrI->getType()->getPointerAddressSpace();
6310456327cSAdam Nemet       unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
6320456327cSAdam Nemet       if (ASi != ASj) {
633339f42b3SAdam Nemet         DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
6340456327cSAdam Nemet                        " different address spaces\n");
6350456327cSAdam Nemet         return false;
6360456327cSAdam Nemet       }
6370456327cSAdam Nemet     }
6380456327cSAdam Nemet   }
6390456327cSAdam Nemet 
6401b6b50a9SSilviu Baranga   if (NeedRTCheck && CanDoRT)
64115840393SAdam Nemet     RtCheck.generateChecks(DepCands, IsDepCheckNeeded);
6421b6b50a9SSilviu Baranga 
643155e8741SAdam Nemet   DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks()
644ee61474aSAdam Nemet                << " pointer comparisons.\n");
645ee61474aSAdam Nemet 
646ee61474aSAdam Nemet   RtCheck.Need = NeedRTCheck;
647ee61474aSAdam Nemet 
648ee61474aSAdam Nemet   bool CanDoRTIfNeeded = !NeedRTCheck || CanDoRT;
649ee61474aSAdam Nemet   if (!CanDoRTIfNeeded)
650ee61474aSAdam Nemet     RtCheck.reset();
651ee61474aSAdam Nemet   return CanDoRTIfNeeded;
6520456327cSAdam Nemet }
6530456327cSAdam Nemet 
6540456327cSAdam Nemet void AccessAnalysis::processMemAccesses() {
6550456327cSAdam Nemet   // We process the set twice: first we process read-write pointers, last we
6560456327cSAdam Nemet   // process read-only pointers. This allows us to skip dependence tests for
6570456327cSAdam Nemet   // read-only pointers.
6580456327cSAdam Nemet 
659339f42b3SAdam Nemet   DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
6600456327cSAdam Nemet   DEBUG(dbgs() << "  AST: "; AST.dump());
6619c926579SAdam Nemet   DEBUG(dbgs() << "LAA:   Accesses(" << Accesses.size() << "):\n");
6620456327cSAdam Nemet   DEBUG({
6630456327cSAdam Nemet     for (auto A : Accesses)
6640456327cSAdam Nemet       dbgs() << "\t" << *A.getPointer() << " (" <<
6650456327cSAdam Nemet                 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
6660456327cSAdam Nemet                                          "read-only" : "read")) << ")\n";
6670456327cSAdam Nemet   });
6680456327cSAdam Nemet 
6690456327cSAdam Nemet   // The AliasSetTracker has nicely partitioned our pointers by metadata
6700456327cSAdam Nemet   // compatibility and potential for underlying-object overlap. As a result, we
6710456327cSAdam Nemet   // only need to check for potential pointer dependencies within each alias
6720456327cSAdam Nemet   // set.
6730456327cSAdam Nemet   for (auto &AS : AST) {
6740456327cSAdam Nemet     // Note that both the alias-set tracker and the alias sets themselves used
6750456327cSAdam Nemet     // linked lists internally and so the iteration order here is deterministic
6760456327cSAdam Nemet     // (matching the original instruction order within each set).
6770456327cSAdam Nemet 
6780456327cSAdam Nemet     bool SetHasWrite = false;
6790456327cSAdam Nemet 
6800456327cSAdam Nemet     // Map of pointers to last access encountered.
6810456327cSAdam Nemet     typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
6820456327cSAdam Nemet     UnderlyingObjToAccessMap ObjToLastAccess;
6830456327cSAdam Nemet 
6840456327cSAdam Nemet     // Set of access to check after all writes have been processed.
6850456327cSAdam Nemet     PtrAccessSet DeferredAccesses;
6860456327cSAdam Nemet 
6870456327cSAdam Nemet     // Iterate over each alias set twice, once to process read/write pointers,
6880456327cSAdam Nemet     // and then to process read-only pointers.
6890456327cSAdam Nemet     for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
6900456327cSAdam Nemet       bool UseDeferred = SetIteration > 0;
6910456327cSAdam Nemet       PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
6920456327cSAdam Nemet 
6930456327cSAdam Nemet       for (auto AV : AS) {
6940456327cSAdam Nemet         Value *Ptr = AV.getValue();
6950456327cSAdam Nemet 
6960456327cSAdam Nemet         // For a single memory access in AliasSetTracker, Accesses may contain
6970456327cSAdam Nemet         // both read and write, and they both need to be handled for CheckDeps.
6980456327cSAdam Nemet         for (auto AC : S) {
6990456327cSAdam Nemet           if (AC.getPointer() != Ptr)
7000456327cSAdam Nemet             continue;
7010456327cSAdam Nemet 
7020456327cSAdam Nemet           bool IsWrite = AC.getInt();
7030456327cSAdam Nemet 
7040456327cSAdam Nemet           // If we're using the deferred access set, then it contains only
7050456327cSAdam Nemet           // reads.
7060456327cSAdam Nemet           bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
7070456327cSAdam Nemet           if (UseDeferred && !IsReadOnlyPtr)
7080456327cSAdam Nemet             continue;
7090456327cSAdam Nemet           // Otherwise, the pointer must be in the PtrAccessSet, either as a
7100456327cSAdam Nemet           // read or a write.
7110456327cSAdam Nemet           assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
7120456327cSAdam Nemet                   S.count(MemAccessInfo(Ptr, false))) &&
7130456327cSAdam Nemet                  "Alias-set pointer not in the access set?");
7140456327cSAdam Nemet 
7150456327cSAdam Nemet           MemAccessInfo Access(Ptr, IsWrite);
7160456327cSAdam Nemet           DepCands.insert(Access);
7170456327cSAdam Nemet 
7180456327cSAdam Nemet           // Memorize read-only pointers for later processing and skip them in
7190456327cSAdam Nemet           // the first round (they need to be checked after we have seen all
7200456327cSAdam Nemet           // write pointers). Note: we also mark pointer that are not
7210456327cSAdam Nemet           // consecutive as "read-only" pointers (so that we check
7220456327cSAdam Nemet           // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
7230456327cSAdam Nemet           if (!UseDeferred && IsReadOnlyPtr) {
7240456327cSAdam Nemet             DeferredAccesses.insert(Access);
7250456327cSAdam Nemet             continue;
7260456327cSAdam Nemet           }
7270456327cSAdam Nemet 
7280456327cSAdam Nemet           // If this is a write - check other reads and writes for conflicts. If
7290456327cSAdam Nemet           // this is a read only check other writes for conflicts (but only if
7300456327cSAdam Nemet           // there is no other write to the ptr - this is an optimization to
7310456327cSAdam Nemet           // catch "a[i] = a[i] + " without having to do a dependence check).
7320456327cSAdam Nemet           if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
7330456327cSAdam Nemet             CheckDeps.insert(Access);
7345dc3b2cfSAdam Nemet             IsRTCheckAnalysisNeeded = true;
7350456327cSAdam Nemet           }
7360456327cSAdam Nemet 
7370456327cSAdam Nemet           if (IsWrite)
7380456327cSAdam Nemet             SetHasWrite = true;
7390456327cSAdam Nemet 
7400456327cSAdam Nemet           // Create sets of pointers connected by a shared alias set and
7410456327cSAdam Nemet           // underlying object.
7420456327cSAdam Nemet           typedef SmallVector<Value *, 16> ValueVector;
7430456327cSAdam Nemet           ValueVector TempObjects;
744e2b885c4SAdam Nemet 
745e2b885c4SAdam Nemet           GetUnderlyingObjects(Ptr, TempObjects, DL, LI);
746e2b885c4SAdam Nemet           DEBUG(dbgs() << "Underlying objects for pointer " << *Ptr << "\n");
7470456327cSAdam Nemet           for (Value *UnderlyingObj : TempObjects) {
748afd13519SMehdi Amini             // nullptr never alias, don't join sets for pointer that have "null"
749afd13519SMehdi Amini             // in their UnderlyingObjects list.
750afd13519SMehdi Amini             if (isa<ConstantPointerNull>(UnderlyingObj))
751afd13519SMehdi Amini               continue;
752afd13519SMehdi Amini 
7530456327cSAdam Nemet             UnderlyingObjToAccessMap::iterator Prev =
7540456327cSAdam Nemet                 ObjToLastAccess.find(UnderlyingObj);
7550456327cSAdam Nemet             if (Prev != ObjToLastAccess.end())
7560456327cSAdam Nemet               DepCands.unionSets(Access, Prev->second);
7570456327cSAdam Nemet 
7580456327cSAdam Nemet             ObjToLastAccess[UnderlyingObj] = Access;
759e2b885c4SAdam Nemet             DEBUG(dbgs() << "  " << *UnderlyingObj << "\n");
7600456327cSAdam Nemet           }
7610456327cSAdam Nemet         }
7620456327cSAdam Nemet       }
7630456327cSAdam Nemet     }
7640456327cSAdam Nemet   }
7650456327cSAdam Nemet }
7660456327cSAdam Nemet 
7670456327cSAdam Nemet static bool isInBoundsGep(Value *Ptr) {
7680456327cSAdam Nemet   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
7690456327cSAdam Nemet     return GEP->isInBounds();
7700456327cSAdam Nemet   return false;
7710456327cSAdam Nemet }
7720456327cSAdam Nemet 
773c4866d29SAdam Nemet /// \brief Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
774c4866d29SAdam Nemet /// i.e. monotonically increasing/decreasing.
775c4866d29SAdam Nemet static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
776c4866d29SAdam Nemet                            ScalarEvolution *SE, const Loop *L) {
777c4866d29SAdam Nemet   // FIXME: This should probably only return true for NUW.
778c4866d29SAdam Nemet   if (AR->getNoWrapFlags(SCEV::NoWrapMask))
779c4866d29SAdam Nemet     return true;
780c4866d29SAdam Nemet 
781c4866d29SAdam Nemet   // Scalar evolution does not propagate the non-wrapping flags to values that
782c4866d29SAdam Nemet   // are derived from a non-wrapping induction variable because non-wrapping
783c4866d29SAdam Nemet   // could be flow-sensitive.
784c4866d29SAdam Nemet   //
785c4866d29SAdam Nemet   // Look through the potentially overflowing instruction to try to prove
786c4866d29SAdam Nemet   // non-wrapping for the *specific* value of Ptr.
787c4866d29SAdam Nemet 
788c4866d29SAdam Nemet   // The arithmetic implied by an inbounds GEP can't overflow.
789c4866d29SAdam Nemet   auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
790c4866d29SAdam Nemet   if (!GEP || !GEP->isInBounds())
791c4866d29SAdam Nemet     return false;
792c4866d29SAdam Nemet 
793c4866d29SAdam Nemet   // Make sure there is only one non-const index and analyze that.
794c4866d29SAdam Nemet   Value *NonConstIndex = nullptr;
795c4866d29SAdam Nemet   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
796c4866d29SAdam Nemet     if (!isa<ConstantInt>(*Index)) {
797c4866d29SAdam Nemet       if (NonConstIndex)
798c4866d29SAdam Nemet         return false;
799c4866d29SAdam Nemet       NonConstIndex = *Index;
800c4866d29SAdam Nemet     }
801c4866d29SAdam Nemet   if (!NonConstIndex)
802c4866d29SAdam Nemet     // The recurrence is on the pointer, ignore for now.
803c4866d29SAdam Nemet     return false;
804c4866d29SAdam Nemet 
805c4866d29SAdam Nemet   // The index in GEP is signed.  It is non-wrapping if it's derived from a NSW
806c4866d29SAdam Nemet   // AddRec using a NSW operation.
807c4866d29SAdam Nemet   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
808c4866d29SAdam Nemet     if (OBO->hasNoSignedWrap() &&
809c4866d29SAdam Nemet         // Assume constant for other the operand so that the AddRec can be
810c4866d29SAdam Nemet         // easily found.
811c4866d29SAdam Nemet         isa<ConstantInt>(OBO->getOperand(1))) {
812c4866d29SAdam Nemet       auto *OpScev = SE->getSCEV(OBO->getOperand(0));
813c4866d29SAdam Nemet 
814c4866d29SAdam Nemet       if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
815c4866d29SAdam Nemet         return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
816c4866d29SAdam Nemet     }
817c4866d29SAdam Nemet 
818c4866d29SAdam Nemet   return false;
819c4866d29SAdam Nemet }
820c4866d29SAdam Nemet 
8210456327cSAdam Nemet /// \brief Check whether the access through \p Ptr has a constant stride.
8229cd9a7e3SSilviu Baranga int llvm::isStridedPtr(PredicatedScalarEvolution &PSE, Value *Ptr,
8239cd9a7e3SSilviu Baranga                        const Loop *Lp, const ValueToValueMap &StridesMap) {
824e3dcce97SCraig Topper   Type *Ty = Ptr->getType();
8250456327cSAdam Nemet   assert(Ty->isPointerTy() && "Unexpected non-ptr");
8260456327cSAdam Nemet 
8270456327cSAdam Nemet   // Make sure that the pointer does not point to aggregate types.
828e3dcce97SCraig Topper   auto *PtrTy = cast<PointerType>(Ty);
8290456327cSAdam Nemet   if (PtrTy->getElementType()->isAggregateType()) {
830339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
831339f42b3SAdam Nemet           << *Ptr << "\n");
8320456327cSAdam Nemet     return 0;
8330456327cSAdam Nemet   }
8340456327cSAdam Nemet 
8359cd9a7e3SSilviu Baranga   const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr);
8360456327cSAdam Nemet 
8370456327cSAdam Nemet   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
8380456327cSAdam Nemet   if (!AR) {
839339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
84004d4163eSAdam Nemet           << *Ptr << " SCEV: " << *PtrScev << "\n");
8410456327cSAdam Nemet     return 0;
8420456327cSAdam Nemet   }
8430456327cSAdam Nemet 
8440456327cSAdam Nemet   // The accesss function must stride over the innermost loop.
8450456327cSAdam Nemet   if (Lp != AR->getLoop()) {
846339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
84704d4163eSAdam Nemet           *Ptr << " SCEV: " << *PtrScev << "\n");
848a02ce98bSKyle Butt     return 0;
8490456327cSAdam Nemet   }
8500456327cSAdam Nemet 
8510456327cSAdam Nemet   // The address calculation must not wrap. Otherwise, a dependence could be
8520456327cSAdam Nemet   // inverted.
8530456327cSAdam Nemet   // An inbounds getelementptr that is a AddRec with a unit stride
8540456327cSAdam Nemet   // cannot wrap per definition. The unit stride requirement is checked later.
8550456327cSAdam Nemet   // An getelementptr without an inbounds attribute and unit stride would have
8560456327cSAdam Nemet   // to access the pointer value "0" which is undefined behavior in address
8570456327cSAdam Nemet   // space 0, therefore we can also vectorize this case.
8580456327cSAdam Nemet   bool IsInBoundsGEP = isInBoundsGep(Ptr);
8599cd9a7e3SSilviu Baranga   bool IsNoWrapAddRec = isNoWrapAddRec(Ptr, AR, PSE.getSE(), Lp);
8600456327cSAdam Nemet   bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
8610456327cSAdam Nemet   if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
862339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
8630456327cSAdam Nemet                  << *Ptr << " SCEV: " << *PtrScev << "\n");
8640456327cSAdam Nemet     return 0;
8650456327cSAdam Nemet   }
8660456327cSAdam Nemet 
8670456327cSAdam Nemet   // Check the step is constant.
8689cd9a7e3SSilviu Baranga   const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
8690456327cSAdam Nemet 
870943befedSAdam Nemet   // Calculate the pointer stride and check if it is constant.
8710456327cSAdam Nemet   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
8720456327cSAdam Nemet   if (!C) {
873339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
87404d4163eSAdam Nemet           " SCEV: " << *PtrScev << "\n");
8750456327cSAdam Nemet     return 0;
8760456327cSAdam Nemet   }
8770456327cSAdam Nemet 
878a28d91d8SMehdi Amini   auto &DL = Lp->getHeader()->getModule()->getDataLayout();
879a28d91d8SMehdi Amini   int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
8800de2feceSSanjoy Das   const APInt &APStepVal = C->getAPInt();
8810456327cSAdam Nemet 
8820456327cSAdam Nemet   // Huge step value - give up.
8830456327cSAdam Nemet   if (APStepVal.getBitWidth() > 64)
8840456327cSAdam Nemet     return 0;
8850456327cSAdam Nemet 
8860456327cSAdam Nemet   int64_t StepVal = APStepVal.getSExtValue();
8870456327cSAdam Nemet 
8880456327cSAdam Nemet   // Strided access.
8890456327cSAdam Nemet   int64_t Stride = StepVal / Size;
8900456327cSAdam Nemet   int64_t Rem = StepVal % Size;
8910456327cSAdam Nemet   if (Rem)
8920456327cSAdam Nemet     return 0;
8930456327cSAdam Nemet 
8940456327cSAdam Nemet   // If the SCEV could wrap but we have an inbounds gep with a unit stride we
8950456327cSAdam Nemet   // know we can't "wrap around the address space". In case of address space
8960456327cSAdam Nemet   // zero we know that this won't happen without triggering undefined behavior.
8970456327cSAdam Nemet   if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
8980456327cSAdam Nemet       Stride != 1 && Stride != -1)
8990456327cSAdam Nemet     return 0;
9000456327cSAdam Nemet 
9010456327cSAdam Nemet   return Stride;
9020456327cSAdam Nemet }
9030456327cSAdam Nemet 
904*f1c00a22SHaicheng Wu /// Take the pointer operand from the Load/Store instruction.
905*f1c00a22SHaicheng Wu /// Returns NULL if this is not a valid Load/Store instruction.
906*f1c00a22SHaicheng Wu static Value *getPointerOperand(Value *I) {
907*f1c00a22SHaicheng Wu   if (LoadInst *LI = dyn_cast<LoadInst>(I))
908*f1c00a22SHaicheng Wu     return LI->getPointerOperand();
909*f1c00a22SHaicheng Wu   if (StoreInst *SI = dyn_cast<StoreInst>(I))
910*f1c00a22SHaicheng Wu     return SI->getPointerOperand();
911*f1c00a22SHaicheng Wu   return nullptr;
912*f1c00a22SHaicheng Wu }
913*f1c00a22SHaicheng Wu 
914*f1c00a22SHaicheng Wu /// Take the address space operand from the Load/Store instruction.
915*f1c00a22SHaicheng Wu /// Returns -1 if this is not a valid Load/Store instruction.
916*f1c00a22SHaicheng Wu static unsigned getAddressSpaceOperand(Value *I) {
917*f1c00a22SHaicheng Wu   if (LoadInst *L = dyn_cast<LoadInst>(I))
918*f1c00a22SHaicheng Wu     return L->getPointerAddressSpace();
919*f1c00a22SHaicheng Wu   if (StoreInst *S = dyn_cast<StoreInst>(I))
920*f1c00a22SHaicheng Wu     return S->getPointerAddressSpace();
921*f1c00a22SHaicheng Wu   return -1;
922*f1c00a22SHaicheng Wu }
923*f1c00a22SHaicheng Wu 
924*f1c00a22SHaicheng Wu /// Returns true if the memory operations \p A and \p B are consecutive.
925*f1c00a22SHaicheng Wu bool llvm::isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL,
926*f1c00a22SHaicheng Wu                                ScalarEvolution &SE, bool CheckType) {
927*f1c00a22SHaicheng Wu   Value *PtrA = getPointerOperand(A);
928*f1c00a22SHaicheng Wu   Value *PtrB = getPointerOperand(B);
929*f1c00a22SHaicheng Wu   unsigned ASA = getAddressSpaceOperand(A);
930*f1c00a22SHaicheng Wu   unsigned ASB = getAddressSpaceOperand(B);
931*f1c00a22SHaicheng Wu 
932*f1c00a22SHaicheng Wu   // Check that the address spaces match and that the pointers are valid.
933*f1c00a22SHaicheng Wu   if (!PtrA || !PtrB || (ASA != ASB))
934*f1c00a22SHaicheng Wu     return false;
935*f1c00a22SHaicheng Wu 
936*f1c00a22SHaicheng Wu   // Make sure that A and B are different pointers.
937*f1c00a22SHaicheng Wu   if (PtrA == PtrB)
938*f1c00a22SHaicheng Wu     return false;
939*f1c00a22SHaicheng Wu 
940*f1c00a22SHaicheng Wu   // Make sure that A and B have the same type if required.
941*f1c00a22SHaicheng Wu   if(CheckType && PtrA->getType() != PtrB->getType())
942*f1c00a22SHaicheng Wu       return false;
943*f1c00a22SHaicheng Wu 
944*f1c00a22SHaicheng Wu   unsigned PtrBitWidth = DL.getPointerSizeInBits(ASA);
945*f1c00a22SHaicheng Wu   Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
946*f1c00a22SHaicheng Wu   APInt Size(PtrBitWidth, DL.getTypeStoreSize(Ty));
947*f1c00a22SHaicheng Wu 
948*f1c00a22SHaicheng Wu   APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
949*f1c00a22SHaicheng Wu   PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetA);
950*f1c00a22SHaicheng Wu   PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetB);
951*f1c00a22SHaicheng Wu 
952*f1c00a22SHaicheng Wu   //  OffsetDelta = OffsetB - OffsetA;
953*f1c00a22SHaicheng Wu   const SCEV *OffsetSCEVA = SE.getConstant(OffsetA);
954*f1c00a22SHaicheng Wu   const SCEV *OffsetSCEVB = SE.getConstant(OffsetB);
955*f1c00a22SHaicheng Wu   const SCEV *OffsetDeltaSCEV = SE.getMinusSCEV(OffsetSCEVB, OffsetSCEVA);
956*f1c00a22SHaicheng Wu   const SCEVConstant *OffsetDeltaC = dyn_cast<SCEVConstant>(OffsetDeltaSCEV);
957*f1c00a22SHaicheng Wu   const APInt &OffsetDelta = OffsetDeltaC->getAPInt();
958*f1c00a22SHaicheng Wu   // Check if they are based on the same pointer. That makes the offsets
959*f1c00a22SHaicheng Wu   // sufficient.
960*f1c00a22SHaicheng Wu   if (PtrA == PtrB)
961*f1c00a22SHaicheng Wu     return OffsetDelta == Size;
962*f1c00a22SHaicheng Wu 
963*f1c00a22SHaicheng Wu   // Compute the necessary base pointer delta to have the necessary final delta
964*f1c00a22SHaicheng Wu   // equal to the size.
965*f1c00a22SHaicheng Wu   // BaseDelta = Size - OffsetDelta;
966*f1c00a22SHaicheng Wu   const SCEV *SizeSCEV = SE.getConstant(Size);
967*f1c00a22SHaicheng Wu   const SCEV *BaseDelta = SE.getMinusSCEV(SizeSCEV, OffsetDeltaSCEV);
968*f1c00a22SHaicheng Wu 
969*f1c00a22SHaicheng Wu   // Otherwise compute the distance with SCEV between the base pointers.
970*f1c00a22SHaicheng Wu   const SCEV *PtrSCEVA = SE.getSCEV(PtrA);
971*f1c00a22SHaicheng Wu   const SCEV *PtrSCEVB = SE.getSCEV(PtrB);
972*f1c00a22SHaicheng Wu   const SCEV *X = SE.getAddExpr(PtrSCEVA, BaseDelta);
973*f1c00a22SHaicheng Wu   return X == PtrSCEVB;
974*f1c00a22SHaicheng Wu }
975*f1c00a22SHaicheng Wu 
9769c926579SAdam Nemet bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
9779c926579SAdam Nemet   switch (Type) {
9789c926579SAdam Nemet   case NoDep:
9799c926579SAdam Nemet   case Forward:
9809c926579SAdam Nemet   case BackwardVectorizable:
9819c926579SAdam Nemet     return true;
9829c926579SAdam Nemet 
9839c926579SAdam Nemet   case Unknown:
9849c926579SAdam Nemet   case ForwardButPreventsForwarding:
9859c926579SAdam Nemet   case Backward:
9869c926579SAdam Nemet   case BackwardVectorizableButPreventsForwarding:
9879c926579SAdam Nemet     return false;
9889c926579SAdam Nemet   }
989d388e930SDavid Majnemer   llvm_unreachable("unexpected DepType!");
9909c926579SAdam Nemet }
9919c926579SAdam Nemet 
992397f5829SAdam Nemet bool MemoryDepChecker::Dependence::isBackward() const {
9939c926579SAdam Nemet   switch (Type) {
9949c926579SAdam Nemet   case NoDep:
9959c926579SAdam Nemet   case Forward:
9969c926579SAdam Nemet   case ForwardButPreventsForwarding:
997397f5829SAdam Nemet   case Unknown:
9989c926579SAdam Nemet     return false;
9999c926579SAdam Nemet 
10009c926579SAdam Nemet   case BackwardVectorizable:
10019c926579SAdam Nemet   case Backward:
10029c926579SAdam Nemet   case BackwardVectorizableButPreventsForwarding:
10039c926579SAdam Nemet     return true;
10049c926579SAdam Nemet   }
1005d388e930SDavid Majnemer   llvm_unreachable("unexpected DepType!");
10069c926579SAdam Nemet }
10079c926579SAdam Nemet 
1008397f5829SAdam Nemet bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
1009397f5829SAdam Nemet   return isBackward() || Type == Unknown;
1010397f5829SAdam Nemet }
1011397f5829SAdam Nemet 
1012397f5829SAdam Nemet bool MemoryDepChecker::Dependence::isForward() const {
1013397f5829SAdam Nemet   switch (Type) {
1014397f5829SAdam Nemet   case Forward:
1015397f5829SAdam Nemet   case ForwardButPreventsForwarding:
1016397f5829SAdam Nemet     return true;
1017397f5829SAdam Nemet 
1018397f5829SAdam Nemet   case NoDep:
1019397f5829SAdam Nemet   case Unknown:
1020397f5829SAdam Nemet   case BackwardVectorizable:
1021397f5829SAdam Nemet   case Backward:
1022397f5829SAdam Nemet   case BackwardVectorizableButPreventsForwarding:
1023397f5829SAdam Nemet     return false;
1024397f5829SAdam Nemet   }
1025397f5829SAdam Nemet   llvm_unreachable("unexpected DepType!");
1026397f5829SAdam Nemet }
1027397f5829SAdam Nemet 
10280456327cSAdam Nemet bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
10290456327cSAdam Nemet                                                     unsigned TypeByteSize) {
10300456327cSAdam Nemet   // If loads occur at a distance that is not a multiple of a feasible vector
10310456327cSAdam Nemet   // factor store-load forwarding does not take place.
10320456327cSAdam Nemet   // Positive dependences might cause troubles because vectorizing them might
10330456327cSAdam Nemet   // prevent store-load forwarding making vectorized code run a lot slower.
10340456327cSAdam Nemet   //   a[i] = a[i-3] ^ a[i-8];
10350456327cSAdam Nemet   //   The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
10360456327cSAdam Nemet   //   hence on your typical architecture store-load forwarding does not take
10370456327cSAdam Nemet   //   place. Vectorizing in such cases does not make sense.
10380456327cSAdam Nemet   // Store-load forwarding distance.
10390456327cSAdam Nemet   const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
10400456327cSAdam Nemet   // Maximum vector factor.
1041f219c647SAdam Nemet   unsigned MaxVFWithoutSLForwardIssues =
1042f219c647SAdam Nemet     VectorizerParams::MaxVectorWidth * TypeByteSize;
10430456327cSAdam Nemet   if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
10440456327cSAdam Nemet     MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
10450456327cSAdam Nemet 
10460456327cSAdam Nemet   for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
10470456327cSAdam Nemet        vf *= 2) {
10480456327cSAdam Nemet     if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
10490456327cSAdam Nemet       MaxVFWithoutSLForwardIssues = (vf >>=1);
10500456327cSAdam Nemet       break;
10510456327cSAdam Nemet     }
10520456327cSAdam Nemet   }
10530456327cSAdam Nemet 
10540456327cSAdam Nemet   if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
1055339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Distance " << Distance <<
105604d4163eSAdam Nemet           " that could cause a store-load forwarding conflict\n");
10570456327cSAdam Nemet     return true;
10580456327cSAdam Nemet   }
10590456327cSAdam Nemet 
10600456327cSAdam Nemet   if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
1061f219c647SAdam Nemet       MaxVFWithoutSLForwardIssues !=
1062f219c647SAdam Nemet       VectorizerParams::MaxVectorWidth * TypeByteSize)
10630456327cSAdam Nemet     MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
10640456327cSAdam Nemet   return false;
10650456327cSAdam Nemet }
10660456327cSAdam Nemet 
1067751004a6SHao Liu /// \brief Check the dependence for two accesses with the same stride \p Stride.
1068751004a6SHao Liu /// \p Distance is the positive distance and \p TypeByteSize is type size in
1069751004a6SHao Liu /// bytes.
1070751004a6SHao Liu ///
1071751004a6SHao Liu /// \returns true if they are independent.
1072751004a6SHao Liu static bool areStridedAccessesIndependent(unsigned Distance, unsigned Stride,
1073751004a6SHao Liu                                           unsigned TypeByteSize) {
1074751004a6SHao Liu   assert(Stride > 1 && "The stride must be greater than 1");
1075751004a6SHao Liu   assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
1076751004a6SHao Liu   assert(Distance > 0 && "The distance must be non-zero");
1077751004a6SHao Liu 
1078751004a6SHao Liu   // Skip if the distance is not multiple of type byte size.
1079751004a6SHao Liu   if (Distance % TypeByteSize)
1080751004a6SHao Liu     return false;
1081751004a6SHao Liu 
1082751004a6SHao Liu   unsigned ScaledDist = Distance / TypeByteSize;
1083751004a6SHao Liu 
1084751004a6SHao Liu   // No dependence if the scaled distance is not multiple of the stride.
1085751004a6SHao Liu   // E.g.
1086751004a6SHao Liu   //      for (i = 0; i < 1024 ; i += 4)
1087751004a6SHao Liu   //        A[i+2] = A[i] + 1;
1088751004a6SHao Liu   //
1089751004a6SHao Liu   // Two accesses in memory (scaled distance is 2, stride is 4):
1090751004a6SHao Liu   //     | A[0] |      |      |      | A[4] |      |      |      |
1091751004a6SHao Liu   //     |      |      | A[2] |      |      |      | A[6] |      |
1092751004a6SHao Liu   //
1093751004a6SHao Liu   // E.g.
1094751004a6SHao Liu   //      for (i = 0; i < 1024 ; i += 3)
1095751004a6SHao Liu   //        A[i+4] = A[i] + 1;
1096751004a6SHao Liu   //
1097751004a6SHao Liu   // Two accesses in memory (scaled distance is 4, stride is 3):
1098751004a6SHao Liu   //     | A[0] |      |      | A[3] |      |      | A[6] |      |      |
1099751004a6SHao Liu   //     |      |      |      |      | A[4] |      |      | A[7] |      |
1100751004a6SHao Liu   return ScaledDist % Stride;
1101751004a6SHao Liu }
1102751004a6SHao Liu 
11039c926579SAdam Nemet MemoryDepChecker::Dependence::DepType
11049c926579SAdam Nemet MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
11050456327cSAdam Nemet                               const MemAccessInfo &B, unsigned BIdx,
11068bc61df9SAdam Nemet                               const ValueToValueMap &Strides) {
11070456327cSAdam Nemet   assert (AIdx < BIdx && "Must pass arguments in program order");
11080456327cSAdam Nemet 
11090456327cSAdam Nemet   Value *APtr = A.getPointer();
11100456327cSAdam Nemet   Value *BPtr = B.getPointer();
11110456327cSAdam Nemet   bool AIsWrite = A.getInt();
11120456327cSAdam Nemet   bool BIsWrite = B.getInt();
11130456327cSAdam Nemet 
11140456327cSAdam Nemet   // Two reads are independent.
11150456327cSAdam Nemet   if (!AIsWrite && !BIsWrite)
11169c926579SAdam Nemet     return Dependence::NoDep;
11170456327cSAdam Nemet 
11180456327cSAdam Nemet   // We cannot check pointers in different address spaces.
11190456327cSAdam Nemet   if (APtr->getType()->getPointerAddressSpace() !=
11200456327cSAdam Nemet       BPtr->getType()->getPointerAddressSpace())
11219c926579SAdam Nemet     return Dependence::Unknown;
11220456327cSAdam Nemet 
11239cd9a7e3SSilviu Baranga   const SCEV *AScev = replaceSymbolicStrideSCEV(PSE, Strides, APtr);
11249cd9a7e3SSilviu Baranga   const SCEV *BScev = replaceSymbolicStrideSCEV(PSE, Strides, BPtr);
11250456327cSAdam Nemet 
11269cd9a7e3SSilviu Baranga   int StrideAPtr = isStridedPtr(PSE, APtr, InnermostLoop, Strides);
11279cd9a7e3SSilviu Baranga   int StrideBPtr = isStridedPtr(PSE, BPtr, InnermostLoop, Strides);
11280456327cSAdam Nemet 
11290456327cSAdam Nemet   const SCEV *Src = AScev;
11300456327cSAdam Nemet   const SCEV *Sink = BScev;
11310456327cSAdam Nemet 
11320456327cSAdam Nemet   // If the induction step is negative we have to invert source and sink of the
11330456327cSAdam Nemet   // dependence.
11340456327cSAdam Nemet   if (StrideAPtr < 0) {
11350456327cSAdam Nemet     //Src = BScev;
11360456327cSAdam Nemet     //Sink = AScev;
11370456327cSAdam Nemet     std::swap(APtr, BPtr);
11380456327cSAdam Nemet     std::swap(Src, Sink);
11390456327cSAdam Nemet     std::swap(AIsWrite, BIsWrite);
11400456327cSAdam Nemet     std::swap(AIdx, BIdx);
11410456327cSAdam Nemet     std::swap(StrideAPtr, StrideBPtr);
11420456327cSAdam Nemet   }
11430456327cSAdam Nemet 
11449cd9a7e3SSilviu Baranga   const SCEV *Dist = PSE.getSE()->getMinusSCEV(Sink, Src);
11450456327cSAdam Nemet 
1146339f42b3SAdam Nemet   DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
11470456327cSAdam Nemet                << "(Induction step: " << StrideAPtr << ")\n");
1148339f42b3SAdam Nemet   DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
11490456327cSAdam Nemet                << *InstMap[BIdx] << ": " << *Dist << "\n");
11500456327cSAdam Nemet 
1151943befedSAdam Nemet   // Need accesses with constant stride. We don't want to vectorize
11520456327cSAdam Nemet   // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
11530456327cSAdam Nemet   // the address space.
11540456327cSAdam Nemet   if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
1155943befedSAdam Nemet     DEBUG(dbgs() << "Pointer access with non-constant stride\n");
11569c926579SAdam Nemet     return Dependence::Unknown;
11570456327cSAdam Nemet   }
11580456327cSAdam Nemet 
11590456327cSAdam Nemet   const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
11600456327cSAdam Nemet   if (!C) {
1161339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
11620456327cSAdam Nemet     ShouldRetryWithRuntimeCheck = true;
11639c926579SAdam Nemet     return Dependence::Unknown;
11640456327cSAdam Nemet   }
11650456327cSAdam Nemet 
11660456327cSAdam Nemet   Type *ATy = APtr->getType()->getPointerElementType();
11670456327cSAdam Nemet   Type *BTy = BPtr->getType()->getPointerElementType();
1168a28d91d8SMehdi Amini   auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
1169a28d91d8SMehdi Amini   unsigned TypeByteSize = DL.getTypeAllocSize(ATy);
11700456327cSAdam Nemet 
11710456327cSAdam Nemet   // Negative distances are not plausible dependencies.
11720de2feceSSanjoy Das   const APInt &Val = C->getAPInt();
11730456327cSAdam Nemet   if (Val.isNegative()) {
11740456327cSAdam Nemet     bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
11750456327cSAdam Nemet     if (IsTrueDataDependence &&
11760456327cSAdam Nemet         (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
11770456327cSAdam Nemet          ATy != BTy))
11789c926579SAdam Nemet       return Dependence::ForwardButPreventsForwarding;
11790456327cSAdam Nemet 
1180339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
11819c926579SAdam Nemet     return Dependence::Forward;
11820456327cSAdam Nemet   }
11830456327cSAdam Nemet 
11840456327cSAdam Nemet   // Write to the same location with the same size.
11850456327cSAdam Nemet   // Could be improved to assert type sizes are the same (i32 == float, etc).
11860456327cSAdam Nemet   if (Val == 0) {
11870456327cSAdam Nemet     if (ATy == BTy)
1188d7037c56SAdam Nemet       return Dependence::Forward;
1189339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
11909c926579SAdam Nemet     return Dependence::Unknown;
11910456327cSAdam Nemet   }
11920456327cSAdam Nemet 
11930456327cSAdam Nemet   assert(Val.isStrictlyPositive() && "Expect a positive value");
11940456327cSAdam Nemet 
11950456327cSAdam Nemet   if (ATy != BTy) {
119604d4163eSAdam Nemet     DEBUG(dbgs() <<
1197339f42b3SAdam Nemet           "LAA: ReadWrite-Write positive dependency with different types\n");
11989c926579SAdam Nemet     return Dependence::Unknown;
11990456327cSAdam Nemet   }
12000456327cSAdam Nemet 
12010456327cSAdam Nemet   unsigned Distance = (unsigned) Val.getZExtValue();
12020456327cSAdam Nemet 
1203751004a6SHao Liu   unsigned Stride = std::abs(StrideAPtr);
1204751004a6SHao Liu   if (Stride > 1 &&
12050131a569SAdam Nemet       areStridedAccessesIndependent(Distance, Stride, TypeByteSize)) {
12060131a569SAdam Nemet     DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
1207751004a6SHao Liu     return Dependence::NoDep;
12080131a569SAdam Nemet   }
1209751004a6SHao Liu 
12100456327cSAdam Nemet   // Bail out early if passed-in parameters make vectorization not feasible.
1211f219c647SAdam Nemet   unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
1212f219c647SAdam Nemet                            VectorizerParams::VectorizationFactor : 1);
1213f219c647SAdam Nemet   unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
1214f219c647SAdam Nemet                            VectorizerParams::VectorizationInterleave : 1);
1215751004a6SHao Liu   // The minimum number of iterations for a vectorized/unrolled version.
1216751004a6SHao Liu   unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
12170456327cSAdam Nemet 
1218751004a6SHao Liu   // It's not vectorizable if the distance is smaller than the minimum distance
1219751004a6SHao Liu   // needed for a vectroized/unrolled version. Vectorizing one iteration in
1220751004a6SHao Liu   // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
1221751004a6SHao Liu   // TypeByteSize (No need to plus the last gap distance).
1222751004a6SHao Liu   //
1223751004a6SHao Liu   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1224751004a6SHao Liu   //      foo(int *A) {
1225751004a6SHao Liu   //        int *B = (int *)((char *)A + 14);
1226751004a6SHao Liu   //        for (i = 0 ; i < 1024 ; i += 2)
1227751004a6SHao Liu   //          B[i] = A[i] + 1;
1228751004a6SHao Liu   //      }
1229751004a6SHao Liu   //
1230751004a6SHao Liu   // Two accesses in memory (stride is 2):
1231751004a6SHao Liu   //     | A[0] |      | A[2] |      | A[4] |      | A[6] |      |
1232751004a6SHao Liu   //                              | B[0] |      | B[2] |      | B[4] |
1233751004a6SHao Liu   //
1234751004a6SHao Liu   // Distance needs for vectorizing iterations except the last iteration:
1235751004a6SHao Liu   // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
1236751004a6SHao Liu   // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
1237751004a6SHao Liu   //
1238751004a6SHao Liu   // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
1239751004a6SHao Liu   // 12, which is less than distance.
1240751004a6SHao Liu   //
1241751004a6SHao Liu   // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
1242751004a6SHao Liu   // the minimum distance needed is 28, which is greater than distance. It is
1243751004a6SHao Liu   // not safe to do vectorization.
1244751004a6SHao Liu   unsigned MinDistanceNeeded =
1245751004a6SHao Liu       TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
1246751004a6SHao Liu   if (MinDistanceNeeded > Distance) {
1247751004a6SHao Liu     DEBUG(dbgs() << "LAA: Failure because of positive distance " << Distance
1248751004a6SHao Liu                  << '\n');
1249751004a6SHao Liu     return Dependence::Backward;
1250751004a6SHao Liu   }
1251751004a6SHao Liu 
1252751004a6SHao Liu   // Unsafe if the minimum distance needed is greater than max safe distance.
1253751004a6SHao Liu   if (MinDistanceNeeded > MaxSafeDepDistBytes) {
1254751004a6SHao Liu     DEBUG(dbgs() << "LAA: Failure because it needs at least "
1255751004a6SHao Liu                  << MinDistanceNeeded << " size in bytes");
12569c926579SAdam Nemet     return Dependence::Backward;
12570456327cSAdam Nemet   }
12580456327cSAdam Nemet 
12599cc0c399SAdam Nemet   // Positive distance bigger than max vectorization factor.
1260751004a6SHao Liu   // FIXME: Should use max factor instead of max distance in bytes, which could
1261751004a6SHao Liu   // not handle different types.
1262751004a6SHao Liu   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1263751004a6SHao Liu   //      void foo (int *A, char *B) {
1264751004a6SHao Liu   //        for (unsigned i = 0; i < 1024; i++) {
1265751004a6SHao Liu   //          A[i+2] = A[i] + 1;
1266751004a6SHao Liu   //          B[i+2] = B[i] + 1;
1267751004a6SHao Liu   //        }
1268751004a6SHao Liu   //      }
1269751004a6SHao Liu   //
1270751004a6SHao Liu   // This case is currently unsafe according to the max safe distance. If we
1271751004a6SHao Liu   // analyze the two accesses on array B, the max safe dependence distance
1272751004a6SHao Liu   // is 2. Then we analyze the accesses on array A, the minimum distance needed
1273751004a6SHao Liu   // is 8, which is less than 2 and forbidden vectorization, But actually
1274751004a6SHao Liu   // both A and B could be vectorized by 2 iterations.
1275751004a6SHao Liu   MaxSafeDepDistBytes =
1276751004a6SHao Liu       Distance < MaxSafeDepDistBytes ? Distance : MaxSafeDepDistBytes;
12770456327cSAdam Nemet 
12780456327cSAdam Nemet   bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
12790456327cSAdam Nemet   if (IsTrueDataDependence &&
12800456327cSAdam Nemet       couldPreventStoreLoadForward(Distance, TypeByteSize))
12819c926579SAdam Nemet     return Dependence::BackwardVectorizableButPreventsForwarding;
12820456327cSAdam Nemet 
1283751004a6SHao Liu   DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
1284751004a6SHao Liu                << " with max VF = "
1285751004a6SHao Liu                << MaxSafeDepDistBytes / (TypeByteSize * Stride) << '\n');
12860456327cSAdam Nemet 
12879c926579SAdam Nemet   return Dependence::BackwardVectorizable;
12880456327cSAdam Nemet }
12890456327cSAdam Nemet 
1290dee666bcSAdam Nemet bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
12910456327cSAdam Nemet                                    MemAccessInfoSet &CheckDeps,
12928bc61df9SAdam Nemet                                    const ValueToValueMap &Strides) {
12930456327cSAdam Nemet 
12940456327cSAdam Nemet   MaxSafeDepDistBytes = -1U;
12950456327cSAdam Nemet   while (!CheckDeps.empty()) {
12960456327cSAdam Nemet     MemAccessInfo CurAccess = *CheckDeps.begin();
12970456327cSAdam Nemet 
12980456327cSAdam Nemet     // Get the relevant memory access set.
12990456327cSAdam Nemet     EquivalenceClasses<MemAccessInfo>::iterator I =
13000456327cSAdam Nemet       AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
13010456327cSAdam Nemet 
13020456327cSAdam Nemet     // Check accesses within this set.
13030456327cSAdam Nemet     EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
13040456327cSAdam Nemet     AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
13050456327cSAdam Nemet 
13060456327cSAdam Nemet     // Check every access pair.
13070456327cSAdam Nemet     while (AI != AE) {
13080456327cSAdam Nemet       CheckDeps.erase(*AI);
13090456327cSAdam Nemet       EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
13100456327cSAdam Nemet       while (OI != AE) {
13110456327cSAdam Nemet         // Check every accessing instruction pair in program order.
13120456327cSAdam Nemet         for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
13130456327cSAdam Nemet              I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
13140456327cSAdam Nemet           for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
13150456327cSAdam Nemet                I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
13169c926579SAdam Nemet             auto A = std::make_pair(&*AI, *I1);
13179c926579SAdam Nemet             auto B = std::make_pair(&*OI, *I2);
13189c926579SAdam Nemet 
13199c926579SAdam Nemet             assert(*I1 != *I2);
13209c926579SAdam Nemet             if (*I1 > *I2)
13219c926579SAdam Nemet               std::swap(A, B);
13229c926579SAdam Nemet 
13239c926579SAdam Nemet             Dependence::DepType Type =
13249c926579SAdam Nemet                 isDependent(*A.first, A.second, *B.first, B.second, Strides);
13259c926579SAdam Nemet             SafeForVectorization &= Dependence::isSafeForVectorization(Type);
13269c926579SAdam Nemet 
1327a2df750fSAdam Nemet             // Gather dependences unless we accumulated MaxDependences
13289c926579SAdam Nemet             // dependences.  In that case return as soon as we find the first
13299c926579SAdam Nemet             // unsafe dependence.  This puts a limit on this quadratic
13309c926579SAdam Nemet             // algorithm.
1331a2df750fSAdam Nemet             if (RecordDependences) {
1332a2df750fSAdam Nemet               if (Type != Dependence::NoDep)
1333a2df750fSAdam Nemet                 Dependences.push_back(Dependence(A.second, B.second, Type));
13349c926579SAdam Nemet 
1335a2df750fSAdam Nemet               if (Dependences.size() >= MaxDependences) {
1336a2df750fSAdam Nemet                 RecordDependences = false;
1337a2df750fSAdam Nemet                 Dependences.clear();
13389c926579SAdam Nemet                 DEBUG(dbgs() << "Too many dependences, stopped recording\n");
13399c926579SAdam Nemet               }
13409c926579SAdam Nemet             }
1341a2df750fSAdam Nemet             if (!RecordDependences && !SafeForVectorization)
13420456327cSAdam Nemet               return false;
13430456327cSAdam Nemet           }
13440456327cSAdam Nemet         ++OI;
13450456327cSAdam Nemet       }
13460456327cSAdam Nemet       AI++;
13470456327cSAdam Nemet     }
13480456327cSAdam Nemet   }
13499c926579SAdam Nemet 
1350a2df750fSAdam Nemet   DEBUG(dbgs() << "Total Dependences: " << Dependences.size() << "\n");
13519c926579SAdam Nemet   return SafeForVectorization;
13520456327cSAdam Nemet }
13530456327cSAdam Nemet 
1354ec1e2bb6SAdam Nemet SmallVector<Instruction *, 4>
1355ec1e2bb6SAdam Nemet MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
1356ec1e2bb6SAdam Nemet   MemAccessInfo Access(Ptr, isWrite);
1357ec1e2bb6SAdam Nemet   auto &IndexVector = Accesses.find(Access)->second;
1358ec1e2bb6SAdam Nemet 
1359ec1e2bb6SAdam Nemet   SmallVector<Instruction *, 4> Insts;
1360ec1e2bb6SAdam Nemet   std::transform(IndexVector.begin(), IndexVector.end(),
1361ec1e2bb6SAdam Nemet                  std::back_inserter(Insts),
1362ec1e2bb6SAdam Nemet                  [&](unsigned Idx) { return this->InstMap[Idx]; });
1363ec1e2bb6SAdam Nemet   return Insts;
1364ec1e2bb6SAdam Nemet }
1365ec1e2bb6SAdam Nemet 
136658913d65SAdam Nemet const char *MemoryDepChecker::Dependence::DepName[] = {
136758913d65SAdam Nemet     "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
136858913d65SAdam Nemet     "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
136958913d65SAdam Nemet 
137058913d65SAdam Nemet void MemoryDepChecker::Dependence::print(
137158913d65SAdam Nemet     raw_ostream &OS, unsigned Depth,
137258913d65SAdam Nemet     const SmallVectorImpl<Instruction *> &Instrs) const {
137358913d65SAdam Nemet   OS.indent(Depth) << DepName[Type] << ":\n";
137458913d65SAdam Nemet   OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
137558913d65SAdam Nemet   OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
137658913d65SAdam Nemet }
137758913d65SAdam Nemet 
1378929c38e8SAdam Nemet bool LoopAccessInfo::canAnalyzeLoop() {
13798dcb3b6aSAdam Nemet   // We need to have a loop header.
1380d8968f09SAdam Nemet   DEBUG(dbgs() << "LAA: Found a loop in "
1381d8968f09SAdam Nemet                << TheLoop->getHeader()->getParent()->getName() << ": "
1382d8968f09SAdam Nemet                << TheLoop->getHeader()->getName() << '\n');
13838dcb3b6aSAdam Nemet 
1384929c38e8SAdam Nemet   // We can only analyze innermost loops.
1385929c38e8SAdam Nemet   if (!TheLoop->empty()) {
13868dcb3b6aSAdam Nemet     DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
13872bd6e984SAdam Nemet     emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
1388929c38e8SAdam Nemet     return false;
1389929c38e8SAdam Nemet   }
1390929c38e8SAdam Nemet 
1391929c38e8SAdam Nemet   // We must have a single backedge.
1392929c38e8SAdam Nemet   if (TheLoop->getNumBackEdges() != 1) {
13938dcb3b6aSAdam Nemet     DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1394929c38e8SAdam Nemet     emitAnalysis(
13952bd6e984SAdam Nemet         LoopAccessReport() <<
1396929c38e8SAdam Nemet         "loop control flow is not understood by analyzer");
1397929c38e8SAdam Nemet     return false;
1398929c38e8SAdam Nemet   }
1399929c38e8SAdam Nemet 
1400929c38e8SAdam Nemet   // We must have a single exiting block.
1401929c38e8SAdam Nemet   if (!TheLoop->getExitingBlock()) {
14028dcb3b6aSAdam Nemet     DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1403929c38e8SAdam Nemet     emitAnalysis(
14042bd6e984SAdam Nemet         LoopAccessReport() <<
1405929c38e8SAdam Nemet         "loop control flow is not understood by analyzer");
1406929c38e8SAdam Nemet     return false;
1407929c38e8SAdam Nemet   }
1408929c38e8SAdam Nemet 
1409929c38e8SAdam Nemet   // We only handle bottom-tested loops, i.e. loop in which the condition is
1410929c38e8SAdam Nemet   // checked at the end of each iteration. With that we can assume that all
1411929c38e8SAdam Nemet   // instructions in the loop are executed the same number of times.
1412929c38e8SAdam Nemet   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
14138dcb3b6aSAdam Nemet     DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1414929c38e8SAdam Nemet     emitAnalysis(
14152bd6e984SAdam Nemet         LoopAccessReport() <<
1416929c38e8SAdam Nemet         "loop control flow is not understood by analyzer");
1417929c38e8SAdam Nemet     return false;
1418929c38e8SAdam Nemet   }
1419929c38e8SAdam Nemet 
1420929c38e8SAdam Nemet   // ScalarEvolution needs to be able to find the exit count.
14219cd9a7e3SSilviu Baranga   const SCEV *ExitCount = PSE.getSE()->getBackedgeTakenCount(TheLoop);
14229cd9a7e3SSilviu Baranga   if (ExitCount == PSE.getSE()->getCouldNotCompute()) {
14239cd9a7e3SSilviu Baranga     emitAnalysis(LoopAccessReport()
14249cd9a7e3SSilviu Baranga                  << "could not determine number of loop iterations");
1425929c38e8SAdam Nemet     DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
1426929c38e8SAdam Nemet     return false;
1427929c38e8SAdam Nemet   }
1428929c38e8SAdam Nemet 
1429929c38e8SAdam Nemet   return true;
1430929c38e8SAdam Nemet }
1431929c38e8SAdam Nemet 
14328bc61df9SAdam Nemet void LoopAccessInfo::analyzeLoop(const ValueToValueMap &Strides) {
14330456327cSAdam Nemet 
14340456327cSAdam Nemet   typedef SmallVector<Value*, 16> ValueVector;
14350456327cSAdam Nemet   typedef SmallPtrSet<Value*, 16> ValueSet;
14360456327cSAdam Nemet 
14370456327cSAdam Nemet   // Holds the Load and Store *instructions*.
14380456327cSAdam Nemet   ValueVector Loads;
14390456327cSAdam Nemet   ValueVector Stores;
14400456327cSAdam Nemet 
14410456327cSAdam Nemet   // Holds all the different accesses in the loop.
14420456327cSAdam Nemet   unsigned NumReads = 0;
14430456327cSAdam Nemet   unsigned NumReadWrites = 0;
14440456327cSAdam Nemet 
14457cdebac0SAdam Nemet   PtrRtChecking.Pointers.clear();
14467cdebac0SAdam Nemet   PtrRtChecking.Need = false;
14470456327cSAdam Nemet 
14480456327cSAdam Nemet   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
14490456327cSAdam Nemet 
14500456327cSAdam Nemet   // For each block.
14510456327cSAdam Nemet   for (Loop::block_iterator bb = TheLoop->block_begin(),
14520456327cSAdam Nemet        be = TheLoop->block_end(); bb != be; ++bb) {
14530456327cSAdam Nemet 
14540456327cSAdam Nemet     // Scan the BB and collect legal loads and stores.
14550456327cSAdam Nemet     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
14560456327cSAdam Nemet          ++it) {
14570456327cSAdam Nemet 
14580456327cSAdam Nemet       // If this is a load, save it. If this instruction can read from memory
14590456327cSAdam Nemet       // but is not a load, then we quit. Notice that we don't handle function
14600456327cSAdam Nemet       // calls that read or write.
14610456327cSAdam Nemet       if (it->mayReadFromMemory()) {
14620456327cSAdam Nemet         // Many math library functions read the rounding mode. We will only
14630456327cSAdam Nemet         // vectorize a loop if it contains known function calls that don't set
14640456327cSAdam Nemet         // the flag. Therefore, it is safe to ignore this read from memory.
14650456327cSAdam Nemet         CallInst *Call = dyn_cast<CallInst>(it);
14660456327cSAdam Nemet         if (Call && getIntrinsicIDForCall(Call, TLI))
14670456327cSAdam Nemet           continue;
14680456327cSAdam Nemet 
14699b3cf604SMichael Zolotukhin         // If the function has an explicit vectorized counterpart, we can safely
14709b3cf604SMichael Zolotukhin         // assume that it can be vectorized.
14719b3cf604SMichael Zolotukhin         if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
14729b3cf604SMichael Zolotukhin             TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
14739b3cf604SMichael Zolotukhin           continue;
14749b3cf604SMichael Zolotukhin 
14750456327cSAdam Nemet         LoadInst *Ld = dyn_cast<LoadInst>(it);
14760456327cSAdam Nemet         if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
14772bd6e984SAdam Nemet           emitAnalysis(LoopAccessReport(Ld)
14780456327cSAdam Nemet                        << "read with atomic ordering or volatile read");
1479339f42b3SAdam Nemet           DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
1480436018c3SAdam Nemet           CanVecMem = false;
1481436018c3SAdam Nemet           return;
14820456327cSAdam Nemet         }
14830456327cSAdam Nemet         NumLoads++;
14840456327cSAdam Nemet         Loads.push_back(Ld);
14850456327cSAdam Nemet         DepChecker.addAccess(Ld);
14860456327cSAdam Nemet         continue;
14870456327cSAdam Nemet       }
14880456327cSAdam Nemet 
14890456327cSAdam Nemet       // Save 'store' instructions. Abort if other instructions write to memory.
14900456327cSAdam Nemet       if (it->mayWriteToMemory()) {
14910456327cSAdam Nemet         StoreInst *St = dyn_cast<StoreInst>(it);
14920456327cSAdam Nemet         if (!St) {
14935a82c916SDuncan P. N. Exon Smith           emitAnalysis(LoopAccessReport(&*it) <<
149404d4163eSAdam Nemet                        "instruction cannot be vectorized");
1495436018c3SAdam Nemet           CanVecMem = false;
1496436018c3SAdam Nemet           return;
14970456327cSAdam Nemet         }
14980456327cSAdam Nemet         if (!St->isSimple() && !IsAnnotatedParallel) {
14992bd6e984SAdam Nemet           emitAnalysis(LoopAccessReport(St)
15000456327cSAdam Nemet                        << "write with atomic ordering or volatile write");
1501339f42b3SAdam Nemet           DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
1502436018c3SAdam Nemet           CanVecMem = false;
1503436018c3SAdam Nemet           return;
15040456327cSAdam Nemet         }
15050456327cSAdam Nemet         NumStores++;
15060456327cSAdam Nemet         Stores.push_back(St);
15070456327cSAdam Nemet         DepChecker.addAccess(St);
15080456327cSAdam Nemet       }
15090456327cSAdam Nemet     } // Next instr.
15100456327cSAdam Nemet   } // Next block.
15110456327cSAdam Nemet 
15120456327cSAdam Nemet   // Now we have two lists that hold the loads and the stores.
15130456327cSAdam Nemet   // Next, we find the pointers that they use.
15140456327cSAdam Nemet 
15150456327cSAdam Nemet   // Check if we see any stores. If there are no stores, then we don't
15160456327cSAdam Nemet   // care if the pointers are *restrict*.
15170456327cSAdam Nemet   if (!Stores.size()) {
1518339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
1519436018c3SAdam Nemet     CanVecMem = true;
1520436018c3SAdam Nemet     return;
15210456327cSAdam Nemet   }
15220456327cSAdam Nemet 
1523dee666bcSAdam Nemet   MemoryDepChecker::DepCandidates DependentAccesses;
1524a28d91d8SMehdi Amini   AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
15259cd9a7e3SSilviu Baranga                           AA, LI, DependentAccesses, PSE);
15260456327cSAdam Nemet 
15270456327cSAdam Nemet   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
15280456327cSAdam Nemet   // multiple times on the same object. If the ptr is accessed twice, once
15290456327cSAdam Nemet   // for read and once for write, it will only appear once (on the write
15300456327cSAdam Nemet   // list). This is okay, since we are going to check for conflicts between
15310456327cSAdam Nemet   // writes and between reads and writes, but not between reads and reads.
15320456327cSAdam Nemet   ValueSet Seen;
15330456327cSAdam Nemet 
15340456327cSAdam Nemet   ValueVector::iterator I, IE;
15350456327cSAdam Nemet   for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
15360456327cSAdam Nemet     StoreInst *ST = cast<StoreInst>(*I);
15370456327cSAdam Nemet     Value* Ptr = ST->getPointerOperand();
1538ce48250fSAdam Nemet     // Check for store to loop invariant address.
1539ce48250fSAdam Nemet     StoreToLoopInvariantAddress |= isUniform(Ptr);
15400456327cSAdam Nemet     // If we did *not* see this pointer before, insert it to  the read-write
15410456327cSAdam Nemet     // list. At this phase it is only a 'write' list.
15420456327cSAdam Nemet     if (Seen.insert(Ptr).second) {
15430456327cSAdam Nemet       ++NumReadWrites;
15440456327cSAdam Nemet 
1545ac80dc75SChandler Carruth       MemoryLocation Loc = MemoryLocation::get(ST);
15460456327cSAdam Nemet       // The TBAA metadata could have a control dependency on the predication
15470456327cSAdam Nemet       // condition, so we cannot rely on it when determining whether or not we
15480456327cSAdam Nemet       // need runtime pointer checks.
154901abb2c3SAdam Nemet       if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
15500456327cSAdam Nemet         Loc.AATags.TBAA = nullptr;
15510456327cSAdam Nemet 
15520456327cSAdam Nemet       Accesses.addStore(Loc);
15530456327cSAdam Nemet     }
15540456327cSAdam Nemet   }
15550456327cSAdam Nemet 
15560456327cSAdam Nemet   if (IsAnnotatedParallel) {
155704d4163eSAdam Nemet     DEBUG(dbgs()
1558339f42b3SAdam Nemet           << "LAA: A loop annotated parallel, ignore memory dependency "
15590456327cSAdam Nemet           << "checks.\n");
1560436018c3SAdam Nemet     CanVecMem = true;
1561436018c3SAdam Nemet     return;
15620456327cSAdam Nemet   }
15630456327cSAdam Nemet 
15640456327cSAdam Nemet   for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
15650456327cSAdam Nemet     LoadInst *LD = cast<LoadInst>(*I);
15660456327cSAdam Nemet     Value* Ptr = LD->getPointerOperand();
15670456327cSAdam Nemet     // If we did *not* see this pointer before, insert it to the
15680456327cSAdam Nemet     // read list. If we *did* see it before, then it is already in
15690456327cSAdam Nemet     // the read-write list. This allows us to vectorize expressions
15700456327cSAdam Nemet     // such as A[i] += x;  Because the address of A[i] is a read-write
15710456327cSAdam Nemet     // pointer. This only works if the index of A[i] is consecutive.
15720456327cSAdam Nemet     // If the address of i is unknown (for example A[B[i]]) then we may
15730456327cSAdam Nemet     // read a few words, modify, and write a few words, and some of the
15740456327cSAdam Nemet     // words may be written to the same address.
15750456327cSAdam Nemet     bool IsReadOnlyPtr = false;
15769cd9a7e3SSilviu Baranga     if (Seen.insert(Ptr).second || !isStridedPtr(PSE, Ptr, TheLoop, Strides)) {
15770456327cSAdam Nemet       ++NumReads;
15780456327cSAdam Nemet       IsReadOnlyPtr = true;
15790456327cSAdam Nemet     }
15800456327cSAdam Nemet 
1581ac80dc75SChandler Carruth     MemoryLocation Loc = MemoryLocation::get(LD);
15820456327cSAdam Nemet     // The TBAA metadata could have a control dependency on the predication
15830456327cSAdam Nemet     // condition, so we cannot rely on it when determining whether or not we
15840456327cSAdam Nemet     // need runtime pointer checks.
158501abb2c3SAdam Nemet     if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
15860456327cSAdam Nemet       Loc.AATags.TBAA = nullptr;
15870456327cSAdam Nemet 
15880456327cSAdam Nemet     Accesses.addLoad(Loc, IsReadOnlyPtr);
15890456327cSAdam Nemet   }
15900456327cSAdam Nemet 
15910456327cSAdam Nemet   // If we write (or read-write) to a single destination and there are no
15920456327cSAdam Nemet   // other reads in this loop then is it safe to vectorize.
15930456327cSAdam Nemet   if (NumReadWrites == 1 && NumReads == 0) {
1594339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
1595436018c3SAdam Nemet     CanVecMem = true;
1596436018c3SAdam Nemet     return;
15970456327cSAdam Nemet   }
15980456327cSAdam Nemet 
15990456327cSAdam Nemet   // Build dependence sets and check whether we need a runtime pointer bounds
16000456327cSAdam Nemet   // check.
16010456327cSAdam Nemet   Accesses.buildDependenceSets();
16020456327cSAdam Nemet 
16030456327cSAdam Nemet   // Find pointers with computable bounds. We are going to use this information
16040456327cSAdam Nemet   // to place a runtime bound check.
1605ee61474aSAdam Nemet   bool CanDoRTIfNeeded =
16069cd9a7e3SSilviu Baranga       Accesses.canCheckPtrAtRT(PtrRtChecking, PSE.getSE(), TheLoop, Strides);
1607ee61474aSAdam Nemet   if (!CanDoRTIfNeeded) {
16082bd6e984SAdam Nemet     emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
1609ee61474aSAdam Nemet     DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
1610ee61474aSAdam Nemet                  << "the array bounds.\n");
1611436018c3SAdam Nemet     CanVecMem = false;
1612436018c3SAdam Nemet     return;
16130456327cSAdam Nemet   }
16140456327cSAdam Nemet 
1615ee61474aSAdam Nemet   DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
16160456327cSAdam Nemet 
1617436018c3SAdam Nemet   CanVecMem = true;
16180456327cSAdam Nemet   if (Accesses.isDependencyCheckNeeded()) {
1619339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
16200456327cSAdam Nemet     CanVecMem = DepChecker.areDepsSafe(
16210456327cSAdam Nemet         DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
16220456327cSAdam Nemet     MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
16230456327cSAdam Nemet 
16240456327cSAdam Nemet     if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
1625339f42b3SAdam Nemet       DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
16260456327cSAdam Nemet 
16270456327cSAdam Nemet       // Clear the dependency checks. We assume they are not needed.
1628df3dc5b9SAdam Nemet       Accesses.resetDepChecks(DepChecker);
16290456327cSAdam Nemet 
16307cdebac0SAdam Nemet       PtrRtChecking.reset();
16317cdebac0SAdam Nemet       PtrRtChecking.Need = true;
16320456327cSAdam Nemet 
16339cd9a7e3SSilviu Baranga       auto *SE = PSE.getSE();
1634ee61474aSAdam Nemet       CanDoRTIfNeeded =
16357cdebac0SAdam Nemet           Accesses.canCheckPtrAtRT(PtrRtChecking, SE, TheLoop, Strides, true);
163698a13719SSilviu Baranga 
1637949e91a6SAdam Nemet       // Check that we found the bounds for the pointer.
1638ee61474aSAdam Nemet       if (!CanDoRTIfNeeded) {
16392bd6e984SAdam Nemet         emitAnalysis(LoopAccessReport()
16400456327cSAdam Nemet                      << "cannot check memory dependencies at runtime");
1641b6dc76ffSAdam Nemet         DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
1642b6dc76ffSAdam Nemet         CanVecMem = false;
1643b6dc76ffSAdam Nemet         return;
1644b6dc76ffSAdam Nemet       }
1645b6dc76ffSAdam Nemet 
16460456327cSAdam Nemet       CanVecMem = true;
16470456327cSAdam Nemet     }
16480456327cSAdam Nemet   }
16490456327cSAdam Nemet 
16504bb90a71SAdam Nemet   if (CanVecMem)
16514bb90a71SAdam Nemet     DEBUG(dbgs() << "LAA: No unsafe dependent memory operations in loop.  We"
16527cdebac0SAdam Nemet                  << (PtrRtChecking.Need ? "" : " don't")
16530f67c6c1SAdam Nemet                  << " need runtime memory checks.\n");
16544bb90a71SAdam Nemet   else {
16552bd6e984SAdam Nemet     emitAnalysis(LoopAccessReport() <<
165604d4163eSAdam Nemet                  "unsafe dependent memory operations in loop");
16574bb90a71SAdam Nemet     DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
16584bb90a71SAdam Nemet   }
16590456327cSAdam Nemet }
16600456327cSAdam Nemet 
166101abb2c3SAdam Nemet bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
166201abb2c3SAdam Nemet                                            DominatorTree *DT)  {
16630456327cSAdam Nemet   assert(TheLoop->contains(BB) && "Unknown block used");
16640456327cSAdam Nemet 
16650456327cSAdam Nemet   // Blocks that do not dominate the latch need predication.
16660456327cSAdam Nemet   BasicBlock* Latch = TheLoop->getLoopLatch();
16670456327cSAdam Nemet   return !DT->dominates(BB, Latch);
16680456327cSAdam Nemet }
16690456327cSAdam Nemet 
16702bd6e984SAdam Nemet void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
1671c922853bSAdam Nemet   assert(!Report && "Multiple reports generated");
1672c922853bSAdam Nemet   Report = Message;
16730456327cSAdam Nemet }
16740456327cSAdam Nemet 
167557ac766eSAdam Nemet bool LoopAccessInfo::isUniform(Value *V) const {
16769cd9a7e3SSilviu Baranga   return (PSE.getSE()->isLoopInvariant(PSE.getSE()->getSCEV(V), TheLoop));
16770456327cSAdam Nemet }
16787206d7a5SAdam Nemet 
16797206d7a5SAdam Nemet // FIXME: this function is currently a duplicate of the one in
16807206d7a5SAdam Nemet // LoopVectorize.cpp.
16817206d7a5SAdam Nemet static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
16827206d7a5SAdam Nemet                                  Instruction *Loc) {
16837206d7a5SAdam Nemet   if (FirstInst)
16847206d7a5SAdam Nemet     return FirstInst;
16857206d7a5SAdam Nemet   if (Instruction *I = dyn_cast<Instruction>(V))
16867206d7a5SAdam Nemet     return I->getParent() == Loc->getParent() ? I : nullptr;
16877206d7a5SAdam Nemet   return nullptr;
16887206d7a5SAdam Nemet }
16897206d7a5SAdam Nemet 
1690039b1042SBenjamin Kramer namespace {
16914e533ef7SAdam Nemet /// \brief IR Values for the lower and upper bounds of a pointer evolution.  We
16924e533ef7SAdam Nemet /// need to use value-handles because SCEV expansion can invalidate previously
16934e533ef7SAdam Nemet /// expanded values.  Thus expansion of a pointer can invalidate the bounds for
16944e533ef7SAdam Nemet /// a previous one.
16951da7df37SAdam Nemet struct PointerBounds {
16964e533ef7SAdam Nemet   TrackingVH<Value> Start;
16974e533ef7SAdam Nemet   TrackingVH<Value> End;
16981da7df37SAdam Nemet };
1699039b1042SBenjamin Kramer } // end anonymous namespace
17007206d7a5SAdam Nemet 
17011da7df37SAdam Nemet /// \brief Expand code for the lower and upper bound of the pointer group \p CG
17021da7df37SAdam Nemet /// in \p TheLoop.  \return the values for the bounds.
17031da7df37SAdam Nemet static PointerBounds
17041da7df37SAdam Nemet expandBounds(const RuntimePointerChecking::CheckingPtrGroup *CG, Loop *TheLoop,
17051da7df37SAdam Nemet              Instruction *Loc, SCEVExpander &Exp, ScalarEvolution *SE,
17061da7df37SAdam Nemet              const RuntimePointerChecking &PtrRtChecking) {
17071da7df37SAdam Nemet   Value *Ptr = PtrRtChecking.Pointers[CG->Members[0]].PointerValue;
17087206d7a5SAdam Nemet   const SCEV *Sc = SE->getSCEV(Ptr);
17097206d7a5SAdam Nemet 
17107206d7a5SAdam Nemet   if (SE->isLoopInvariant(Sc, TheLoop)) {
17111b6b50a9SSilviu Baranga     DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" << *Ptr
17121b6b50a9SSilviu Baranga                  << "\n");
17131da7df37SAdam Nemet     return {Ptr, Ptr};
17147206d7a5SAdam Nemet   } else {
17157206d7a5SAdam Nemet     unsigned AS = Ptr->getType()->getPointerAddressSpace();
17161da7df37SAdam Nemet     LLVMContext &Ctx = Loc->getContext();
17177206d7a5SAdam Nemet 
17187206d7a5SAdam Nemet     // Use this type for pointer arithmetic.
17197206d7a5SAdam Nemet     Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
17201b6b50a9SSilviu Baranga     Value *Start = nullptr, *End = nullptr;
17217206d7a5SAdam Nemet 
17221b6b50a9SSilviu Baranga     DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
17231da7df37SAdam Nemet     Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc);
17241da7df37SAdam Nemet     End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc);
17251da7df37SAdam Nemet     DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High << "\n");
17261da7df37SAdam Nemet     return {Start, End};
17277206d7a5SAdam Nemet   }
17287206d7a5SAdam Nemet }
17297206d7a5SAdam Nemet 
17301da7df37SAdam Nemet /// \brief Turns a collection of checks into a collection of expanded upper and
17311da7df37SAdam Nemet /// lower bounds for both pointers in the check.
17321da7df37SAdam Nemet static SmallVector<std::pair<PointerBounds, PointerBounds>, 4> expandBounds(
17331da7df37SAdam Nemet     const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks,
17341da7df37SAdam Nemet     Loop *L, Instruction *Loc, ScalarEvolution *SE, SCEVExpander &Exp,
17351da7df37SAdam Nemet     const RuntimePointerChecking &PtrRtChecking) {
17361da7df37SAdam Nemet   SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds;
17371da7df37SAdam Nemet 
17381da7df37SAdam Nemet   // Here we're relying on the SCEV Expander's cache to only emit code for the
17391da7df37SAdam Nemet   // same bounds once.
17401da7df37SAdam Nemet   std::transform(
17411da7df37SAdam Nemet       PointerChecks.begin(), PointerChecks.end(),
17421da7df37SAdam Nemet       std::back_inserter(ChecksWithBounds),
17431da7df37SAdam Nemet       [&](const RuntimePointerChecking::PointerCheck &Check) {
174494abbbd6SNAKAMURA Takumi         PointerBounds
174594abbbd6SNAKAMURA Takumi           First = expandBounds(Check.first, L, Loc, Exp, SE, PtrRtChecking),
174694abbbd6SNAKAMURA Takumi           Second = expandBounds(Check.second, L, Loc, Exp, SE, PtrRtChecking);
174794abbbd6SNAKAMURA Takumi         return std::make_pair(First, Second);
17481da7df37SAdam Nemet       });
17491da7df37SAdam Nemet 
17501da7df37SAdam Nemet   return ChecksWithBounds;
17511da7df37SAdam Nemet }
17521da7df37SAdam Nemet 
17535b0a4795SAdam Nemet std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeChecks(
17541da7df37SAdam Nemet     Instruction *Loc,
17551da7df37SAdam Nemet     const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks)
17561da7df37SAdam Nemet     const {
17579cd9a7e3SSilviu Baranga   auto *SE = PSE.getSE();
17581da7df37SAdam Nemet   SCEVExpander Exp(*SE, DL, "induction");
17591da7df37SAdam Nemet   auto ExpandedChecks =
17601da7df37SAdam Nemet       expandBounds(PointerChecks, TheLoop, Loc, SE, Exp, PtrRtChecking);
17611da7df37SAdam Nemet 
17621da7df37SAdam Nemet   LLVMContext &Ctx = Loc->getContext();
17631da7df37SAdam Nemet   Instruction *FirstInst = nullptr;
17647206d7a5SAdam Nemet   IRBuilder<> ChkBuilder(Loc);
17657206d7a5SAdam Nemet   // Our instructions might fold to a constant.
17667206d7a5SAdam Nemet   Value *MemoryRuntimeCheck = nullptr;
17671b6b50a9SSilviu Baranga 
17681da7df37SAdam Nemet   for (const auto &Check : ExpandedChecks) {
17691da7df37SAdam Nemet     const PointerBounds &A = Check.first, &B = Check.second;
1770cdb791cdSAdam Nemet     // Check if two pointers (A and B) conflict where conflict is computed as:
1771cdb791cdSAdam Nemet     // start(A) <= end(B) && start(B) <= end(A)
17721da7df37SAdam Nemet     unsigned AS0 = A.Start->getType()->getPointerAddressSpace();
17731da7df37SAdam Nemet     unsigned AS1 = B.Start->getType()->getPointerAddressSpace();
17747206d7a5SAdam Nemet 
17751da7df37SAdam Nemet     assert((AS0 == B.End->getType()->getPointerAddressSpace()) &&
17761da7df37SAdam Nemet            (AS1 == A.End->getType()->getPointerAddressSpace()) &&
17777206d7a5SAdam Nemet            "Trying to bounds check pointers with different address spaces");
17787206d7a5SAdam Nemet 
17797206d7a5SAdam Nemet     Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
17807206d7a5SAdam Nemet     Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
17817206d7a5SAdam Nemet 
17821da7df37SAdam Nemet     Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc");
17831da7df37SAdam Nemet     Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc");
17841da7df37SAdam Nemet     Value *End0 =   ChkBuilder.CreateBitCast(A.End,   PtrArithTy1, "bc");
17851da7df37SAdam Nemet     Value *End1 =   ChkBuilder.CreateBitCast(B.End,   PtrArithTy0, "bc");
17867206d7a5SAdam Nemet 
17877206d7a5SAdam Nemet     Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
17887206d7a5SAdam Nemet     FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
17897206d7a5SAdam Nemet     Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
17907206d7a5SAdam Nemet     FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
17917206d7a5SAdam Nemet     Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
17927206d7a5SAdam Nemet     FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
17937206d7a5SAdam Nemet     if (MemoryRuntimeCheck) {
17941da7df37SAdam Nemet       IsConflict =
17951da7df37SAdam Nemet           ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
17967206d7a5SAdam Nemet       FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
17977206d7a5SAdam Nemet     }
17987206d7a5SAdam Nemet     MemoryRuntimeCheck = IsConflict;
17997206d7a5SAdam Nemet   }
18007206d7a5SAdam Nemet 
180190fec840SAdam Nemet   if (!MemoryRuntimeCheck)
180290fec840SAdam Nemet     return std::make_pair(nullptr, nullptr);
180390fec840SAdam Nemet 
18047206d7a5SAdam Nemet   // We have to do this trickery because the IRBuilder might fold the check to a
18057206d7a5SAdam Nemet   // constant expression in which case there is no Instruction anchored in a
18067206d7a5SAdam Nemet   // the block.
18077206d7a5SAdam Nemet   Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
18087206d7a5SAdam Nemet                                                  ConstantInt::getTrue(Ctx));
18097206d7a5SAdam Nemet   ChkBuilder.Insert(Check, "memcheck.conflict");
18107206d7a5SAdam Nemet   FirstInst = getFirstInst(FirstInst, Check, Loc);
18117206d7a5SAdam Nemet   return std::make_pair(FirstInst, Check);
18127206d7a5SAdam Nemet }
18133bfd93d7SAdam Nemet 
18145b0a4795SAdam Nemet std::pair<Instruction *, Instruction *>
18155b0a4795SAdam Nemet LoopAccessInfo::addRuntimeChecks(Instruction *Loc) const {
18161da7df37SAdam Nemet   if (!PtrRtChecking.Need)
18171da7df37SAdam Nemet     return std::make_pair(nullptr, nullptr);
18181da7df37SAdam Nemet 
18195b0a4795SAdam Nemet   return addRuntimeChecks(Loc, PtrRtChecking.getChecks());
18201da7df37SAdam Nemet }
18211da7df37SAdam Nemet 
18223bfd93d7SAdam Nemet LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
1823a28d91d8SMehdi Amini                                const DataLayout &DL,
18243bfd93d7SAdam Nemet                                const TargetLibraryInfo *TLI, AliasAnalysis *AA,
1825e2b885c4SAdam Nemet                                DominatorTree *DT, LoopInfo *LI,
18268bc61df9SAdam Nemet                                const ValueToValueMap &Strides)
18279cd9a7e3SSilviu Baranga     : PSE(*SE), PtrRtChecking(SE), DepChecker(PSE, L), TheLoop(L), DL(DL),
18287cdebac0SAdam Nemet       TLI(TLI), AA(AA), DT(DT), LI(LI), NumLoads(0), NumStores(0),
1829ce48250fSAdam Nemet       MaxSafeDepDistBytes(-1U), CanVecMem(false),
1830ce48250fSAdam Nemet       StoreToLoopInvariantAddress(false) {
1831929c38e8SAdam Nemet   if (canAnalyzeLoop())
18323bfd93d7SAdam Nemet     analyzeLoop(Strides);
18333bfd93d7SAdam Nemet }
18343bfd93d7SAdam Nemet 
1835e91cc6efSAdam Nemet void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1836e91cc6efSAdam Nemet   if (CanVecMem) {
18377cdebac0SAdam Nemet     if (PtrRtChecking.Need)
1838e91cc6efSAdam Nemet       OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
183926da8e98SAdam Nemet     else
184026da8e98SAdam Nemet       OS.indent(Depth) << "Memory dependences are safe\n";
1841e91cc6efSAdam Nemet   }
1842e91cc6efSAdam Nemet 
1843e91cc6efSAdam Nemet   if (Report)
1844e91cc6efSAdam Nemet     OS.indent(Depth) << "Report: " << Report->str() << "\n";
1845e91cc6efSAdam Nemet 
1846a2df750fSAdam Nemet   if (auto *Dependences = DepChecker.getDependences()) {
1847a2df750fSAdam Nemet     OS.indent(Depth) << "Dependences:\n";
1848a2df750fSAdam Nemet     for (auto &Dep : *Dependences) {
184958913d65SAdam Nemet       Dep.print(OS, Depth + 2, DepChecker.getMemoryInstructions());
185058913d65SAdam Nemet       OS << "\n";
185158913d65SAdam Nemet     }
185258913d65SAdam Nemet   } else
1853a2df750fSAdam Nemet     OS.indent(Depth) << "Too many dependences, not recorded\n";
1854e91cc6efSAdam Nemet 
1855e91cc6efSAdam Nemet   // List the pair of accesses need run-time checks to prove independence.
18567cdebac0SAdam Nemet   PtrRtChecking.print(OS, Depth);
1857e91cc6efSAdam Nemet   OS << "\n";
1858c3384320SAdam Nemet 
1859c3384320SAdam Nemet   OS.indent(Depth) << "Store to invariant address was "
1860c3384320SAdam Nemet                    << (StoreToLoopInvariantAddress ? "" : "not ")
1861c3384320SAdam Nemet                    << "found in loop.\n";
1862e3c0534bSSilviu Baranga 
1863e3c0534bSSilviu Baranga   OS.indent(Depth) << "SCEV assumptions:\n";
18649cd9a7e3SSilviu Baranga   PSE.getUnionPredicate().print(OS, Depth);
1865e91cc6efSAdam Nemet }
1866e91cc6efSAdam Nemet 
18678bc61df9SAdam Nemet const LoopAccessInfo &
18688bc61df9SAdam Nemet LoopAccessAnalysis::getInfo(Loop *L, const ValueToValueMap &Strides) {
18693bfd93d7SAdam Nemet   auto &LAI = LoopAccessInfoMap[L];
18703bfd93d7SAdam Nemet 
18713bfd93d7SAdam Nemet #ifndef NDEBUG
18723bfd93d7SAdam Nemet   assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
18733bfd93d7SAdam Nemet          "Symbolic strides changed for loop");
18743bfd93d7SAdam Nemet #endif
18753bfd93d7SAdam Nemet 
18763bfd93d7SAdam Nemet   if (!LAI) {
1877a28d91d8SMehdi Amini     const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
1878e3c0534bSSilviu Baranga     LAI =
1879e3c0534bSSilviu Baranga         llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, LI, Strides);
18803bfd93d7SAdam Nemet #ifndef NDEBUG
18813bfd93d7SAdam Nemet     LAI->NumSymbolicStrides = Strides.size();
18823bfd93d7SAdam Nemet #endif
18833bfd93d7SAdam Nemet   }
18843bfd93d7SAdam Nemet   return *LAI.get();
18853bfd93d7SAdam Nemet }
18863bfd93d7SAdam Nemet 
1887e91cc6efSAdam Nemet void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
1888e91cc6efSAdam Nemet   LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
1889e91cc6efSAdam Nemet 
1890e91cc6efSAdam Nemet   ValueToValueMap NoSymbolicStrides;
1891e91cc6efSAdam Nemet 
1892e91cc6efSAdam Nemet   for (Loop *TopLevelLoop : *LI)
1893e91cc6efSAdam Nemet     for (Loop *L : depth_first(TopLevelLoop)) {
1894e91cc6efSAdam Nemet       OS.indent(2) << L->getHeader()->getName() << ":\n";
1895e91cc6efSAdam Nemet       auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
1896e91cc6efSAdam Nemet       LAI.print(OS, 4);
1897e91cc6efSAdam Nemet     }
1898e91cc6efSAdam Nemet }
1899e91cc6efSAdam Nemet 
19003bfd93d7SAdam Nemet bool LoopAccessAnalysis::runOnFunction(Function &F) {
19012f1fd165SChandler Carruth   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
19023bfd93d7SAdam Nemet   auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
19033bfd93d7SAdam Nemet   TLI = TLIP ? &TLIP->getTLI() : nullptr;
19047b560d40SChandler Carruth   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
19053bfd93d7SAdam Nemet   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1906e2b885c4SAdam Nemet   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
19073bfd93d7SAdam Nemet 
19083bfd93d7SAdam Nemet   return false;
19093bfd93d7SAdam Nemet }
19103bfd93d7SAdam Nemet 
19113bfd93d7SAdam Nemet void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
19122f1fd165SChandler Carruth     AU.addRequired<ScalarEvolutionWrapperPass>();
19137b560d40SChandler Carruth     AU.addRequired<AAResultsWrapperPass>();
19143bfd93d7SAdam Nemet     AU.addRequired<DominatorTreeWrapperPass>();
1915e91cc6efSAdam Nemet     AU.addRequired<LoopInfoWrapperPass>();
19163bfd93d7SAdam Nemet 
19173bfd93d7SAdam Nemet     AU.setPreservesAll();
19183bfd93d7SAdam Nemet }
19193bfd93d7SAdam Nemet 
19203bfd93d7SAdam Nemet char LoopAccessAnalysis::ID = 0;
19213bfd93d7SAdam Nemet static const char laa_name[] = "Loop Access Analysis";
19223bfd93d7SAdam Nemet #define LAA_NAME "loop-accesses"
19233bfd93d7SAdam Nemet 
19243bfd93d7SAdam Nemet INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
19257b560d40SChandler Carruth INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
19262f1fd165SChandler Carruth INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
19273bfd93d7SAdam Nemet INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1928e91cc6efSAdam Nemet INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
19293bfd93d7SAdam Nemet INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
19303bfd93d7SAdam Nemet 
19313bfd93d7SAdam Nemet namespace llvm {
19323bfd93d7SAdam Nemet   Pass *createLAAPass() {
19333bfd93d7SAdam Nemet     return new LoopAccessAnalysis();
19343bfd93d7SAdam Nemet   }
19353bfd93d7SAdam Nemet }
1936