1 //===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // The implementation for the loop memory dependence that was originally
10 // developed for the loop vectorizer.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Analysis/LoopAccessAnalysis.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/DepthFirstIterator.h"
18 #include "llvm/ADT/EquivalenceClasses.h"
19 #include "llvm/ADT/PointerIntPair.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/iterator_range.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/AliasSetTracker.h"
28 #include "llvm/Analysis/LoopAnalysisManager.h"
29 #include "llvm/Analysis/LoopInfo.h"
30 #include "llvm/Analysis/MemoryLocation.h"
31 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
32 #include "llvm/Analysis/ScalarEvolution.h"
33 #include "llvm/Analysis/ScalarEvolutionExpander.h"
34 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
35 #include "llvm/Analysis/TargetLibraryInfo.h"
36 #include "llvm/Analysis/ValueTracking.h"
37 #include "llvm/Analysis/VectorUtils.h"
38 #include "llvm/IR/BasicBlock.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/DebugLoc.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/DiagnosticInfo.h"
44 #include "llvm/IR/Dominators.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/InstrTypes.h"
47 #include "llvm/IR/Instruction.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/Operator.h"
50 #include "llvm/IR/PassManager.h"
51 #include "llvm/IR/Type.h"
52 #include "llvm/IR/Value.h"
53 #include "llvm/IR/ValueHandle.h"
54 #include "llvm/InitializePasses.h"
55 #include "llvm/Pass.h"
56 #include "llvm/Support/Casting.h"
57 #include "llvm/Support/CommandLine.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/ErrorHandling.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include <algorithm>
62 #include <cassert>
63 #include <cstdint>
64 #include <cstdlib>
65 #include <iterator>
66 #include <utility>
67 #include <vector>
68 
69 using namespace llvm;
70 
71 #define DEBUG_TYPE "loop-accesses"
72 
73 static cl::opt<unsigned, true>
74 VectorizationFactor("force-vector-width", cl::Hidden,
75                     cl::desc("Sets the SIMD width. Zero is autoselect."),
76                     cl::location(VectorizerParams::VectorizationFactor));
77 unsigned VectorizerParams::VectorizationFactor;
78 
79 static cl::opt<unsigned, true>
80 VectorizationInterleave("force-vector-interleave", cl::Hidden,
81                         cl::desc("Sets the vectorization interleave count. "
82                                  "Zero is autoselect."),
83                         cl::location(
84                             VectorizerParams::VectorizationInterleave));
85 unsigned VectorizerParams::VectorizationInterleave;
86 
87 static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
88     "runtime-memory-check-threshold", cl::Hidden,
89     cl::desc("When performing memory disambiguation checks at runtime do not "
90              "generate more than this number of comparisons (default = 8)."),
91     cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
92 unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
93 
94 /// The maximum iterations used to merge memory checks
95 static cl::opt<unsigned> MemoryCheckMergeThreshold(
96     "memory-check-merge-threshold", cl::Hidden,
97     cl::desc("Maximum number of comparisons done when trying to merge "
98              "runtime memory checks. (default = 100)"),
99     cl::init(100));
100 
101 /// Maximum SIMD width.
102 const unsigned VectorizerParams::MaxVectorWidth = 64;
103 
104 /// We collect dependences up to this threshold.
105 static cl::opt<unsigned>
106     MaxDependences("max-dependences", cl::Hidden,
107                    cl::desc("Maximum number of dependences collected by "
108                             "loop-access analysis (default = 100)"),
109                    cl::init(100));
110 
111 /// This enables versioning on the strides of symbolically striding memory
112 /// accesses in code like the following.
113 ///   for (i = 0; i < N; ++i)
114 ///     A[i * Stride1] += B[i * Stride2] ...
115 ///
116 /// Will be roughly translated to
117 ///    if (Stride1 == 1 && Stride2 == 1) {
118 ///      for (i = 0; i < N; i+=4)
119 ///       A[i:i+3] += ...
120 ///    } else
121 ///      ...
122 static cl::opt<bool> EnableMemAccessVersioning(
123     "enable-mem-access-versioning", cl::init(true), cl::Hidden,
124     cl::desc("Enable symbolic stride memory access versioning"));
125 
126 /// Enable store-to-load forwarding conflict detection. This option can
127 /// be disabled for correctness testing.
128 static cl::opt<bool> EnableForwardingConflictDetection(
129     "store-to-load-forwarding-conflict-detection", cl::Hidden,
130     cl::desc("Enable conflict detection in loop-access analysis"),
131     cl::init(true));
132 
133 bool VectorizerParams::isInterleaveForced() {
134   return ::VectorizationInterleave.getNumOccurrences() > 0;
135 }
136 
137 Value *llvm::stripIntegerCast(Value *V) {
138   if (auto *CI = dyn_cast<CastInst>(V))
139     if (CI->getOperand(0)->getType()->isIntegerTy())
140       return CI->getOperand(0);
141   return V;
142 }
143 
144 const SCEV *llvm::replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE,
145                                             const ValueToValueMap &PtrToStride,
146                                             Value *Ptr, Value *OrigPtr) {
147   const SCEV *OrigSCEV = PSE.getSCEV(Ptr);
148 
149   // If there is an entry in the map return the SCEV of the pointer with the
150   // symbolic stride replaced by one.
151   ValueToValueMap::const_iterator SI =
152       PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
153   if (SI != PtrToStride.end()) {
154     Value *StrideVal = SI->second;
155 
156     // Strip casts.
157     StrideVal = stripIntegerCast(StrideVal);
158 
159     ScalarEvolution *SE = PSE.getSE();
160     const auto *U = cast<SCEVUnknown>(SE->getSCEV(StrideVal));
161     const auto *CT =
162         static_cast<const SCEVConstant *>(SE->getOne(StrideVal->getType()));
163 
164     PSE.addPredicate(*SE->getEqualPredicate(U, CT));
165     auto *Expr = PSE.getSCEV(Ptr);
166 
167     LLVM_DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV
168                       << " by: " << *Expr << "\n");
169     return Expr;
170   }
171 
172   // Otherwise, just return the SCEV of the original pointer.
173   return OrigSCEV;
174 }
175 
176 RuntimeCheckingPtrGroup::RuntimeCheckingPtrGroup(
177     unsigned Index, RuntimePointerChecking &RtCheck)
178     : RtCheck(RtCheck), High(RtCheck.Pointers[Index].End),
179       Low(RtCheck.Pointers[Index].Start) {
180   Members.push_back(Index);
181 }
182 
183 /// Calculate Start and End points of memory access.
184 /// Let's assume A is the first access and B is a memory access on N-th loop
185 /// iteration. Then B is calculated as:
186 ///   B = A + Step*N .
187 /// Step value may be positive or negative.
188 /// N is a calculated back-edge taken count:
189 ///     N = (TripCount > 0) ? RoundDown(TripCount -1 , VF) : 0
190 /// Start and End points are calculated in the following way:
191 /// Start = UMIN(A, B) ; End = UMAX(A, B) + SizeOfElt,
192 /// where SizeOfElt is the size of single memory access in bytes.
193 ///
194 /// There is no conflict when the intervals are disjoint:
195 /// NoConflict = (P2.Start >= P1.End) || (P1.Start >= P2.End)
196 void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, bool WritePtr,
197                                     unsigned DepSetId, unsigned ASId,
198                                     const ValueToValueMap &Strides,
199                                     PredicatedScalarEvolution &PSE) {
200   // Get the stride replaced scev.
201   const SCEV *Sc = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
202   ScalarEvolution *SE = PSE.getSE();
203 
204   const SCEV *ScStart;
205   const SCEV *ScEnd;
206 
207   if (SE->isLoopInvariant(Sc, Lp))
208     ScStart = ScEnd = Sc;
209   else {
210     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
211     assert(AR && "Invalid addrec expression");
212     const SCEV *Ex = PSE.getBackedgeTakenCount();
213 
214     ScStart = AR->getStart();
215     ScEnd = AR->evaluateAtIteration(Ex, *SE);
216     const SCEV *Step = AR->getStepRecurrence(*SE);
217 
218     // For expressions with negative step, the upper bound is ScStart and the
219     // lower bound is ScEnd.
220     if (const auto *CStep = dyn_cast<SCEVConstant>(Step)) {
221       if (CStep->getValue()->isNegative())
222         std::swap(ScStart, ScEnd);
223     } else {
224       // Fallback case: the step is not constant, but we can still
225       // get the upper and lower bounds of the interval by using min/max
226       // expressions.
227       ScStart = SE->getUMinExpr(ScStart, ScEnd);
228       ScEnd = SE->getUMaxExpr(AR->getStart(), ScEnd);
229     }
230     // Add the size of the pointed element to ScEnd.
231     unsigned EltSize =
232       Ptr->getType()->getPointerElementType()->getScalarSizeInBits() / 8;
233     const SCEV *EltSizeSCEV = SE->getConstant(ScEnd->getType(), EltSize);
234     ScEnd = SE->getAddExpr(ScEnd, EltSizeSCEV);
235   }
236 
237   Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, Sc);
238 }
239 
240 SmallVector<RuntimePointerCheck, 4>
241 RuntimePointerChecking::generateChecks() const {
242   SmallVector<RuntimePointerCheck, 4> Checks;
243 
244   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
245     for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) {
246       const RuntimeCheckingPtrGroup &CGI = CheckingGroups[I];
247       const RuntimeCheckingPtrGroup &CGJ = CheckingGroups[J];
248 
249       if (needsChecking(CGI, CGJ))
250         Checks.push_back(std::make_pair(&CGI, &CGJ));
251     }
252   }
253   return Checks;
254 }
255 
256 void RuntimePointerChecking::generateChecks(
257     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
258   assert(Checks.empty() && "Checks is not empty");
259   groupChecks(DepCands, UseDependencies);
260   Checks = generateChecks();
261 }
262 
263 bool RuntimePointerChecking::needsChecking(
264     const RuntimeCheckingPtrGroup &M, const RuntimeCheckingPtrGroup &N) const {
265   for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I)
266     for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J)
267       if (needsChecking(M.Members[I], N.Members[J]))
268         return true;
269   return false;
270 }
271 
272 /// Compare \p I and \p J and return the minimum.
273 /// Return nullptr in case we couldn't find an answer.
274 static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
275                                    ScalarEvolution *SE) {
276   const SCEV *Diff = SE->getMinusSCEV(J, I);
277   const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
278 
279   if (!C)
280     return nullptr;
281   if (C->getValue()->isNegative())
282     return J;
283   return I;
284 }
285 
286 bool RuntimeCheckingPtrGroup::addPointer(unsigned Index) {
287   const SCEV *Start = RtCheck.Pointers[Index].Start;
288   const SCEV *End = RtCheck.Pointers[Index].End;
289 
290   // Compare the starts and ends with the known minimum and maximum
291   // of this set. We need to know how we compare against the min/max
292   // of the set in order to be able to emit memchecks.
293   const SCEV *Min0 = getMinFromExprs(Start, Low, RtCheck.SE);
294   if (!Min0)
295     return false;
296 
297   const SCEV *Min1 = getMinFromExprs(End, High, RtCheck.SE);
298   if (!Min1)
299     return false;
300 
301   // Update the low bound  expression if we've found a new min value.
302   if (Min0 == Start)
303     Low = Start;
304 
305   // Update the high bound expression if we've found a new max value.
306   if (Min1 != End)
307     High = End;
308 
309   Members.push_back(Index);
310   return true;
311 }
312 
313 void RuntimePointerChecking::groupChecks(
314     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
315   // We build the groups from dependency candidates equivalence classes
316   // because:
317   //    - We know that pointers in the same equivalence class share
318   //      the same underlying object and therefore there is a chance
319   //      that we can compare pointers
320   //    - We wouldn't be able to merge two pointers for which we need
321   //      to emit a memcheck. The classes in DepCands are already
322   //      conveniently built such that no two pointers in the same
323   //      class need checking against each other.
324 
325   // We use the following (greedy) algorithm to construct the groups
326   // For every pointer in the equivalence class:
327   //   For each existing group:
328   //   - if the difference between this pointer and the min/max bounds
329   //     of the group is a constant, then make the pointer part of the
330   //     group and update the min/max bounds of that group as required.
331 
332   CheckingGroups.clear();
333 
334   // If we need to check two pointers to the same underlying object
335   // with a non-constant difference, we shouldn't perform any pointer
336   // grouping with those pointers. This is because we can easily get
337   // into cases where the resulting check would return false, even when
338   // the accesses are safe.
339   //
340   // The following example shows this:
341   // for (i = 0; i < 1000; ++i)
342   //   a[5000 + i * m] = a[i] + a[i + 9000]
343   //
344   // Here grouping gives a check of (5000, 5000 + 1000 * m) against
345   // (0, 10000) which is always false. However, if m is 1, there is no
346   // dependence. Not grouping the checks for a[i] and a[i + 9000] allows
347   // us to perform an accurate check in this case.
348   //
349   // The above case requires that we have an UnknownDependence between
350   // accesses to the same underlying object. This cannot happen unless
351   // FoundNonConstantDistanceDependence is set, and therefore UseDependencies
352   // is also false. In this case we will use the fallback path and create
353   // separate checking groups for all pointers.
354 
355   // If we don't have the dependency partitions, construct a new
356   // checking pointer group for each pointer. This is also required
357   // for correctness, because in this case we can have checking between
358   // pointers to the same underlying object.
359   if (!UseDependencies) {
360     for (unsigned I = 0; I < Pointers.size(); ++I)
361       CheckingGroups.push_back(RuntimeCheckingPtrGroup(I, *this));
362     return;
363   }
364 
365   unsigned TotalComparisons = 0;
366 
367   DenseMap<Value *, unsigned> PositionMap;
368   for (unsigned Index = 0; Index < Pointers.size(); ++Index)
369     PositionMap[Pointers[Index].PointerValue] = Index;
370 
371   // We need to keep track of what pointers we've already seen so we
372   // don't process them twice.
373   SmallSet<unsigned, 2> Seen;
374 
375   // Go through all equivalence classes, get the "pointer check groups"
376   // and add them to the overall solution. We use the order in which accesses
377   // appear in 'Pointers' to enforce determinism.
378   for (unsigned I = 0; I < Pointers.size(); ++I) {
379     // We've seen this pointer before, and therefore already processed
380     // its equivalence class.
381     if (Seen.count(I))
382       continue;
383 
384     MemoryDepChecker::MemAccessInfo Access(Pointers[I].PointerValue,
385                                            Pointers[I].IsWritePtr);
386 
387     SmallVector<RuntimeCheckingPtrGroup, 2> Groups;
388     auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access));
389 
390     // Because DepCands is constructed by visiting accesses in the order in
391     // which they appear in alias sets (which is deterministic) and the
392     // iteration order within an equivalence class member is only dependent on
393     // the order in which unions and insertions are performed on the
394     // equivalence class, the iteration order is deterministic.
395     for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end();
396          MI != ME; ++MI) {
397       unsigned Pointer = PositionMap[MI->getPointer()];
398       bool Merged = false;
399       // Mark this pointer as seen.
400       Seen.insert(Pointer);
401 
402       // Go through all the existing sets and see if we can find one
403       // which can include this pointer.
404       for (RuntimeCheckingPtrGroup &Group : Groups) {
405         // Don't perform more than a certain amount of comparisons.
406         // This should limit the cost of grouping the pointers to something
407         // reasonable.  If we do end up hitting this threshold, the algorithm
408         // will create separate groups for all remaining pointers.
409         if (TotalComparisons > MemoryCheckMergeThreshold)
410           break;
411 
412         TotalComparisons++;
413 
414         if (Group.addPointer(Pointer)) {
415           Merged = true;
416           break;
417         }
418       }
419 
420       if (!Merged)
421         // We couldn't add this pointer to any existing set or the threshold
422         // for the number of comparisons has been reached. Create a new group
423         // to hold the current pointer.
424         Groups.push_back(RuntimeCheckingPtrGroup(Pointer, *this));
425     }
426 
427     // We've computed the grouped checks for this partition.
428     // Save the results and continue with the next one.
429     llvm::copy(Groups, std::back_inserter(CheckingGroups));
430   }
431 }
432 
433 bool RuntimePointerChecking::arePointersInSamePartition(
434     const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
435     unsigned PtrIdx2) {
436   return (PtrToPartition[PtrIdx1] != -1 &&
437           PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
438 }
439 
440 bool RuntimePointerChecking::needsChecking(unsigned I, unsigned J) const {
441   const PointerInfo &PointerI = Pointers[I];
442   const PointerInfo &PointerJ = Pointers[J];
443 
444   // No need to check if two readonly pointers intersect.
445   if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
446     return false;
447 
448   // Only need to check pointers between two different dependency sets.
449   if (PointerI.DependencySetId == PointerJ.DependencySetId)
450     return false;
451 
452   // Only need to check pointers in the same alias set.
453   if (PointerI.AliasSetId != PointerJ.AliasSetId)
454     return false;
455 
456   return true;
457 }
458 
459 void RuntimePointerChecking::printChecks(
460     raw_ostream &OS, const SmallVectorImpl<RuntimePointerCheck> &Checks,
461     unsigned Depth) const {
462   unsigned N = 0;
463   for (const auto &Check : Checks) {
464     const auto &First = Check.first->Members, &Second = Check.second->Members;
465 
466     OS.indent(Depth) << "Check " << N++ << ":\n";
467 
468     OS.indent(Depth + 2) << "Comparing group (" << Check.first << "):\n";
469     for (unsigned K = 0; K < First.size(); ++K)
470       OS.indent(Depth + 2) << *Pointers[First[K]].PointerValue << "\n";
471 
472     OS.indent(Depth + 2) << "Against group (" << Check.second << "):\n";
473     for (unsigned K = 0; K < Second.size(); ++K)
474       OS.indent(Depth + 2) << *Pointers[Second[K]].PointerValue << "\n";
475   }
476 }
477 
478 void RuntimePointerChecking::print(raw_ostream &OS, unsigned Depth) const {
479 
480   OS.indent(Depth) << "Run-time memory checks:\n";
481   printChecks(OS, Checks, Depth);
482 
483   OS.indent(Depth) << "Grouped accesses:\n";
484   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
485     const auto &CG = CheckingGroups[I];
486 
487     OS.indent(Depth + 2) << "Group " << &CG << ":\n";
488     OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High
489                          << ")\n";
490     for (unsigned J = 0; J < CG.Members.size(); ++J) {
491       OS.indent(Depth + 6) << "Member: " << *Pointers[CG.Members[J]].Expr
492                            << "\n";
493     }
494   }
495 }
496 
497 namespace {
498 
499 /// Analyses memory accesses in a loop.
500 ///
501 /// Checks whether run time pointer checks are needed and builds sets for data
502 /// dependence checking.
503 class AccessAnalysis {
504 public:
505   /// Read or write access location.
506   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
507   typedef SmallVector<MemAccessInfo, 8> MemAccessInfoList;
508 
509   AccessAnalysis(const DataLayout &Dl, Loop *TheLoop, AliasAnalysis *AA,
510                  LoopInfo *LI, MemoryDepChecker::DepCandidates &DA,
511                  PredicatedScalarEvolution &PSE)
512       : DL(Dl), TheLoop(TheLoop), AST(*AA), LI(LI), DepCands(DA),
513         IsRTCheckAnalysisNeeded(false), PSE(PSE) {}
514 
515   /// Register a load  and whether it is only read from.
516   void addLoad(MemoryLocation &Loc, bool IsReadOnly) {
517     Value *Ptr = const_cast<Value*>(Loc.Ptr);
518     AST.add(Ptr, LocationSize::unknown(), Loc.AATags);
519     Accesses.insert(MemAccessInfo(Ptr, false));
520     if (IsReadOnly)
521       ReadOnlyPtr.insert(Ptr);
522   }
523 
524   /// Register a store.
525   void addStore(MemoryLocation &Loc) {
526     Value *Ptr = const_cast<Value*>(Loc.Ptr);
527     AST.add(Ptr, LocationSize::unknown(), Loc.AATags);
528     Accesses.insert(MemAccessInfo(Ptr, true));
529   }
530 
531   /// Check if we can emit a run-time no-alias check for \p Access.
532   ///
533   /// Returns true if we can emit a run-time no alias check for \p Access.
534   /// If we can check this access, this also adds it to a dependence set and
535   /// adds a run-time to check for it to \p RtCheck. If \p Assume is true,
536   /// we will attempt to use additional run-time checks in order to get
537   /// the bounds of the pointer.
538   bool createCheckForAccess(RuntimePointerChecking &RtCheck,
539                             MemAccessInfo Access,
540                             const ValueToValueMap &Strides,
541                             DenseMap<Value *, unsigned> &DepSetId,
542                             Loop *TheLoop, unsigned &RunningDepId,
543                             unsigned ASId, bool ShouldCheckStride,
544                             bool Assume);
545 
546   /// Check whether we can check the pointers at runtime for
547   /// non-intersection.
548   ///
549   /// Returns true if we need no check or if we do and we can generate them
550   /// (i.e. the pointers have computable bounds).
551   bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE,
552                        Loop *TheLoop, const ValueToValueMap &Strides,
553                        bool ShouldCheckWrap = false);
554 
555   /// Goes over all memory accesses, checks whether a RT check is needed
556   /// and builds sets of dependent accesses.
557   void buildDependenceSets() {
558     processMemAccesses();
559   }
560 
561   /// Initial processing of memory accesses determined that we need to
562   /// perform dependency checking.
563   ///
564   /// Note that this can later be cleared if we retry memcheck analysis without
565   /// dependency checking (i.e. FoundNonConstantDistanceDependence).
566   bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
567 
568   /// We decided that no dependence analysis would be used.  Reset the state.
569   void resetDepChecks(MemoryDepChecker &DepChecker) {
570     CheckDeps.clear();
571     DepChecker.clearDependences();
572   }
573 
574   MemAccessInfoList &getDependenciesToCheck() { return CheckDeps; }
575 
576 private:
577   typedef SetVector<MemAccessInfo> PtrAccessSet;
578 
579   /// Go over all memory access and check whether runtime pointer checks
580   /// are needed and build sets of dependency check candidates.
581   void processMemAccesses();
582 
583   /// Set of all accesses.
584   PtrAccessSet Accesses;
585 
586   const DataLayout &DL;
587 
588   /// The loop being checked.
589   const Loop *TheLoop;
590 
591   /// List of accesses that need a further dependence check.
592   MemAccessInfoList CheckDeps;
593 
594   /// Set of pointers that are read only.
595   SmallPtrSet<Value*, 16> ReadOnlyPtr;
596 
597   /// An alias set tracker to partition the access set by underlying object and
598   //intrinsic property (such as TBAA metadata).
599   AliasSetTracker AST;
600 
601   LoopInfo *LI;
602 
603   /// Sets of potentially dependent accesses - members of one set share an
604   /// underlying pointer. The set "CheckDeps" identfies which sets really need a
605   /// dependence check.
606   MemoryDepChecker::DepCandidates &DepCands;
607 
608   /// Initial processing of memory accesses determined that we may need
609   /// to add memchecks.  Perform the analysis to determine the necessary checks.
610   ///
611   /// Note that, this is different from isDependencyCheckNeeded.  When we retry
612   /// memcheck analysis without dependency checking
613   /// (i.e. FoundNonConstantDistanceDependence), isDependencyCheckNeeded is
614   /// cleared while this remains set if we have potentially dependent accesses.
615   bool IsRTCheckAnalysisNeeded;
616 
617   /// The SCEV predicate containing all the SCEV-related assumptions.
618   PredicatedScalarEvolution &PSE;
619 };
620 
621 } // end anonymous namespace
622 
623 /// Check whether a pointer can participate in a runtime bounds check.
624 /// If \p Assume, try harder to prove that we can compute the bounds of \p Ptr
625 /// by adding run-time checks (overflow checks) if necessary.
626 static bool hasComputableBounds(PredicatedScalarEvolution &PSE,
627                                 const ValueToValueMap &Strides, Value *Ptr,
628                                 Loop *L, bool Assume) {
629   const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
630 
631   // The bounds for loop-invariant pointer is trivial.
632   if (PSE.getSE()->isLoopInvariant(PtrScev, L))
633     return true;
634 
635   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
636 
637   if (!AR && Assume)
638     AR = PSE.getAsAddRec(Ptr);
639 
640   if (!AR)
641     return false;
642 
643   return AR->isAffine();
644 }
645 
646 /// Check whether a pointer address cannot wrap.
647 static bool isNoWrap(PredicatedScalarEvolution &PSE,
648                      const ValueToValueMap &Strides, Value *Ptr, Loop *L) {
649   const SCEV *PtrScev = PSE.getSCEV(Ptr);
650   if (PSE.getSE()->isLoopInvariant(PtrScev, L))
651     return true;
652 
653   int64_t Stride = getPtrStride(PSE, Ptr, L, Strides);
654   if (Stride == 1 || PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW))
655     return true;
656 
657   return false;
658 }
659 
660 bool AccessAnalysis::createCheckForAccess(RuntimePointerChecking &RtCheck,
661                                           MemAccessInfo Access,
662                                           const ValueToValueMap &StridesMap,
663                                           DenseMap<Value *, unsigned> &DepSetId,
664                                           Loop *TheLoop, unsigned &RunningDepId,
665                                           unsigned ASId, bool ShouldCheckWrap,
666                                           bool Assume) {
667   Value *Ptr = Access.getPointer();
668 
669   if (!hasComputableBounds(PSE, StridesMap, Ptr, TheLoop, Assume))
670     return false;
671 
672   // When we run after a failing dependency check we have to make sure
673   // we don't have wrapping pointers.
674   if (ShouldCheckWrap && !isNoWrap(PSE, StridesMap, Ptr, TheLoop)) {
675     auto *Expr = PSE.getSCEV(Ptr);
676     if (!Assume || !isa<SCEVAddRecExpr>(Expr))
677       return false;
678     PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
679   }
680 
681   // The id of the dependence set.
682   unsigned DepId;
683 
684   if (isDependencyCheckNeeded()) {
685     Value *Leader = DepCands.getLeaderValue(Access).getPointer();
686     unsigned &LeaderId = DepSetId[Leader];
687     if (!LeaderId)
688       LeaderId = RunningDepId++;
689     DepId = LeaderId;
690   } else
691     // Each access has its own dependence set.
692     DepId = RunningDepId++;
693 
694   bool IsWrite = Access.getInt();
695   RtCheck.insert(TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap, PSE);
696   LLVM_DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
697 
698   return true;
699  }
700 
701 bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
702                                      ScalarEvolution *SE, Loop *TheLoop,
703                                      const ValueToValueMap &StridesMap,
704                                      bool ShouldCheckWrap) {
705   // Find pointers with computable bounds. We are going to use this information
706   // to place a runtime bound check.
707   bool CanDoRT = true;
708 
709   bool NeedRTCheck = false;
710   if (!IsRTCheckAnalysisNeeded) return true;
711 
712   bool IsDepCheckNeeded = isDependencyCheckNeeded();
713 
714   // We assign a consecutive id to access from different alias sets.
715   // Accesses between different groups doesn't need to be checked.
716   unsigned ASId = 1;
717   for (auto &AS : AST) {
718     int NumReadPtrChecks = 0;
719     int NumWritePtrChecks = 0;
720     bool CanDoAliasSetRT = true;
721 
722     // We assign consecutive id to access from different dependence sets.
723     // Accesses within the same set don't need a runtime check.
724     unsigned RunningDepId = 1;
725     DenseMap<Value *, unsigned> DepSetId;
726 
727     SmallVector<MemAccessInfo, 4> Retries;
728 
729     for (auto A : AS) {
730       Value *Ptr = A.getValue();
731       bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
732       MemAccessInfo Access(Ptr, IsWrite);
733 
734       if (IsWrite)
735         ++NumWritePtrChecks;
736       else
737         ++NumReadPtrChecks;
738 
739       if (!createCheckForAccess(RtCheck, Access, StridesMap, DepSetId, TheLoop,
740                                 RunningDepId, ASId, ShouldCheckWrap, false)) {
741         LLVM_DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" << *Ptr << '\n');
742         Retries.push_back(Access);
743         CanDoAliasSetRT = false;
744       }
745     }
746 
747     // If we have at least two writes or one write and a read then we need to
748     // check them.  But there is no need to checks if there is only one
749     // dependence set for this alias set.
750     //
751     // Note that this function computes CanDoRT and NeedRTCheck independently.
752     // For example CanDoRT=false, NeedRTCheck=false means that we have a pointer
753     // for which we couldn't find the bounds but we don't actually need to emit
754     // any checks so it does not matter.
755     bool NeedsAliasSetRTCheck = false;
756     if (!(IsDepCheckNeeded && CanDoAliasSetRT && RunningDepId == 2))
757       NeedsAliasSetRTCheck = (NumWritePtrChecks >= 2 ||
758                              (NumReadPtrChecks >= 1 && NumWritePtrChecks >= 1));
759 
760     // We need to perform run-time alias checks, but some pointers had bounds
761     // that couldn't be checked.
762     if (NeedsAliasSetRTCheck && !CanDoAliasSetRT) {
763       // Reset the CanDoSetRt flag and retry all accesses that have failed.
764       // We know that we need these checks, so we can now be more aggressive
765       // and add further checks if required (overflow checks).
766       CanDoAliasSetRT = true;
767       for (auto Access : Retries)
768         if (!createCheckForAccess(RtCheck, Access, StridesMap, DepSetId,
769                                   TheLoop, RunningDepId, ASId,
770                                   ShouldCheckWrap, /*Assume=*/true)) {
771           CanDoAliasSetRT = false;
772           break;
773         }
774     }
775 
776     CanDoRT &= CanDoAliasSetRT;
777     NeedRTCheck |= NeedsAliasSetRTCheck;
778     ++ASId;
779   }
780 
781   // If the pointers that we would use for the bounds comparison have different
782   // address spaces, assume the values aren't directly comparable, so we can't
783   // use them for the runtime check. We also have to assume they could
784   // overlap. In the future there should be metadata for whether address spaces
785   // are disjoint.
786   unsigned NumPointers = RtCheck.Pointers.size();
787   for (unsigned i = 0; i < NumPointers; ++i) {
788     for (unsigned j = i + 1; j < NumPointers; ++j) {
789       // Only need to check pointers between two different dependency sets.
790       if (RtCheck.Pointers[i].DependencySetId ==
791           RtCheck.Pointers[j].DependencySetId)
792        continue;
793       // Only need to check pointers in the same alias set.
794       if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
795         continue;
796 
797       Value *PtrI = RtCheck.Pointers[i].PointerValue;
798       Value *PtrJ = RtCheck.Pointers[j].PointerValue;
799 
800       unsigned ASi = PtrI->getType()->getPointerAddressSpace();
801       unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
802       if (ASi != ASj) {
803         LLVM_DEBUG(
804             dbgs() << "LAA: Runtime check would require comparison between"
805                       " different address spaces\n");
806         return false;
807       }
808     }
809   }
810 
811   if (NeedRTCheck && CanDoRT)
812     RtCheck.generateChecks(DepCands, IsDepCheckNeeded);
813 
814   LLVM_DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks()
815                     << " pointer comparisons.\n");
816 
817   RtCheck.Need = NeedRTCheck;
818 
819   bool CanDoRTIfNeeded = !NeedRTCheck || CanDoRT;
820   if (!CanDoRTIfNeeded)
821     RtCheck.reset();
822   return CanDoRTIfNeeded;
823 }
824 
825 void AccessAnalysis::processMemAccesses() {
826   // We process the set twice: first we process read-write pointers, last we
827   // process read-only pointers. This allows us to skip dependence tests for
828   // read-only pointers.
829 
830   LLVM_DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
831   LLVM_DEBUG(dbgs() << "  AST: "; AST.dump());
832   LLVM_DEBUG(dbgs() << "LAA:   Accesses(" << Accesses.size() << "):\n");
833   LLVM_DEBUG({
834     for (auto A : Accesses)
835       dbgs() << "\t" << *A.getPointer() << " (" <<
836                 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
837                                          "read-only" : "read")) << ")\n";
838   });
839 
840   // The AliasSetTracker has nicely partitioned our pointers by metadata
841   // compatibility and potential for underlying-object overlap. As a result, we
842   // only need to check for potential pointer dependencies within each alias
843   // set.
844   for (auto &AS : AST) {
845     // Note that both the alias-set tracker and the alias sets themselves used
846     // linked lists internally and so the iteration order here is deterministic
847     // (matching the original instruction order within each set).
848 
849     bool SetHasWrite = false;
850 
851     // Map of pointers to last access encountered.
852     typedef DenseMap<const Value*, MemAccessInfo> UnderlyingObjToAccessMap;
853     UnderlyingObjToAccessMap ObjToLastAccess;
854 
855     // Set of access to check after all writes have been processed.
856     PtrAccessSet DeferredAccesses;
857 
858     // Iterate over each alias set twice, once to process read/write pointers,
859     // and then to process read-only pointers.
860     for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
861       bool UseDeferred = SetIteration > 0;
862       PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
863 
864       for (auto AV : AS) {
865         Value *Ptr = AV.getValue();
866 
867         // For a single memory access in AliasSetTracker, Accesses may contain
868         // both read and write, and they both need to be handled for CheckDeps.
869         for (auto AC : S) {
870           if (AC.getPointer() != Ptr)
871             continue;
872 
873           bool IsWrite = AC.getInt();
874 
875           // If we're using the deferred access set, then it contains only
876           // reads.
877           bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
878           if (UseDeferred && !IsReadOnlyPtr)
879             continue;
880           // Otherwise, the pointer must be in the PtrAccessSet, either as a
881           // read or a write.
882           assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
883                   S.count(MemAccessInfo(Ptr, false))) &&
884                  "Alias-set pointer not in the access set?");
885 
886           MemAccessInfo Access(Ptr, IsWrite);
887           DepCands.insert(Access);
888 
889           // Memorize read-only pointers for later processing and skip them in
890           // the first round (they need to be checked after we have seen all
891           // write pointers). Note: we also mark pointer that are not
892           // consecutive as "read-only" pointers (so that we check
893           // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
894           if (!UseDeferred && IsReadOnlyPtr) {
895             DeferredAccesses.insert(Access);
896             continue;
897           }
898 
899           // If this is a write - check other reads and writes for conflicts. If
900           // this is a read only check other writes for conflicts (but only if
901           // there is no other write to the ptr - this is an optimization to
902           // catch "a[i] = a[i] + " without having to do a dependence check).
903           if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
904             CheckDeps.push_back(Access);
905             IsRTCheckAnalysisNeeded = true;
906           }
907 
908           if (IsWrite)
909             SetHasWrite = true;
910 
911           // Create sets of pointers connected by a shared alias set and
912           // underlying object.
913           typedef SmallVector<const Value *, 16> ValueVector;
914           ValueVector TempObjects;
915 
916           GetUnderlyingObjects(Ptr, TempObjects, DL, LI);
917           LLVM_DEBUG(dbgs()
918                      << "Underlying objects for pointer " << *Ptr << "\n");
919           for (const Value *UnderlyingObj : TempObjects) {
920             // nullptr never alias, don't join sets for pointer that have "null"
921             // in their UnderlyingObjects list.
922             if (isa<ConstantPointerNull>(UnderlyingObj) &&
923                 !NullPointerIsDefined(
924                     TheLoop->getHeader()->getParent(),
925                     UnderlyingObj->getType()->getPointerAddressSpace()))
926               continue;
927 
928             UnderlyingObjToAccessMap::iterator Prev =
929                 ObjToLastAccess.find(UnderlyingObj);
930             if (Prev != ObjToLastAccess.end())
931               DepCands.unionSets(Access, Prev->second);
932 
933             ObjToLastAccess[UnderlyingObj] = Access;
934             LLVM_DEBUG(dbgs() << "  " << *UnderlyingObj << "\n");
935           }
936         }
937       }
938     }
939   }
940 }
941 
942 static bool isInBoundsGep(Value *Ptr) {
943   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
944     return GEP->isInBounds();
945   return false;
946 }
947 
948 /// Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
949 /// i.e. monotonically increasing/decreasing.
950 static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
951                            PredicatedScalarEvolution &PSE, const Loop *L) {
952   // FIXME: This should probably only return true for NUW.
953   if (AR->getNoWrapFlags(SCEV::NoWrapMask))
954     return true;
955 
956   // Scalar evolution does not propagate the non-wrapping flags to values that
957   // are derived from a non-wrapping induction variable because non-wrapping
958   // could be flow-sensitive.
959   //
960   // Look through the potentially overflowing instruction to try to prove
961   // non-wrapping for the *specific* value of Ptr.
962 
963   // The arithmetic implied by an inbounds GEP can't overflow.
964   auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
965   if (!GEP || !GEP->isInBounds())
966     return false;
967 
968   // Make sure there is only one non-const index and analyze that.
969   Value *NonConstIndex = nullptr;
970   for (Value *Index : make_range(GEP->idx_begin(), GEP->idx_end()))
971     if (!isa<ConstantInt>(Index)) {
972       if (NonConstIndex)
973         return false;
974       NonConstIndex = Index;
975     }
976   if (!NonConstIndex)
977     // The recurrence is on the pointer, ignore for now.
978     return false;
979 
980   // The index in GEP is signed.  It is non-wrapping if it's derived from a NSW
981   // AddRec using a NSW operation.
982   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
983     if (OBO->hasNoSignedWrap() &&
984         // Assume constant for other the operand so that the AddRec can be
985         // easily found.
986         isa<ConstantInt>(OBO->getOperand(1))) {
987       auto *OpScev = PSE.getSCEV(OBO->getOperand(0));
988 
989       if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
990         return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
991     }
992 
993   return false;
994 }
995 
996 /// Check whether the access through \p Ptr has a constant stride.
997 int64_t llvm::getPtrStride(PredicatedScalarEvolution &PSE, Value *Ptr,
998                            const Loop *Lp, const ValueToValueMap &StridesMap,
999                            bool Assume, bool ShouldCheckWrap) {
1000   Type *Ty = Ptr->getType();
1001   assert(Ty->isPointerTy() && "Unexpected non-ptr");
1002 
1003   // Make sure that the pointer does not point to aggregate types.
1004   auto *PtrTy = cast<PointerType>(Ty);
1005   if (PtrTy->getElementType()->isAggregateType()) {
1006     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
1007                       << *Ptr << "\n");
1008     return 0;
1009   }
1010 
1011   const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr);
1012 
1013   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
1014   if (Assume && !AR)
1015     AR = PSE.getAsAddRec(Ptr);
1016 
1017   if (!AR) {
1018     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer " << *Ptr
1019                       << " SCEV: " << *PtrScev << "\n");
1020     return 0;
1021   }
1022 
1023   // The access function must stride over the innermost loop.
1024   if (Lp != AR->getLoop()) {
1025     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop "
1026                       << *Ptr << " SCEV: " << *AR << "\n");
1027     return 0;
1028   }
1029 
1030   // The address calculation must not wrap. Otherwise, a dependence could be
1031   // inverted.
1032   // An inbounds getelementptr that is a AddRec with a unit stride
1033   // cannot wrap per definition. The unit stride requirement is checked later.
1034   // An getelementptr without an inbounds attribute and unit stride would have
1035   // to access the pointer value "0" which is undefined behavior in address
1036   // space 0, therefore we can also vectorize this case.
1037   bool IsInBoundsGEP = isInBoundsGep(Ptr);
1038   bool IsNoWrapAddRec = !ShouldCheckWrap ||
1039     PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW) ||
1040     isNoWrapAddRec(Ptr, AR, PSE, Lp);
1041   if (!IsNoWrapAddRec && !IsInBoundsGEP &&
1042       NullPointerIsDefined(Lp->getHeader()->getParent(),
1043                            PtrTy->getAddressSpace())) {
1044     if (Assume) {
1045       PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
1046       IsNoWrapAddRec = true;
1047       LLVM_DEBUG(dbgs() << "LAA: Pointer may wrap in the address space:\n"
1048                         << "LAA:   Pointer: " << *Ptr << "\n"
1049                         << "LAA:   SCEV: " << *AR << "\n"
1050                         << "LAA:   Added an overflow assumption\n");
1051     } else {
1052       LLVM_DEBUG(
1053           dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
1054                  << *Ptr << " SCEV: " << *AR << "\n");
1055       return 0;
1056     }
1057   }
1058 
1059   // Check the step is constant.
1060   const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
1061 
1062   // Calculate the pointer stride and check if it is constant.
1063   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
1064   if (!C) {
1065     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr
1066                       << " SCEV: " << *AR << "\n");
1067     return 0;
1068   }
1069 
1070   auto &DL = Lp->getHeader()->getModule()->getDataLayout();
1071   int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
1072   const APInt &APStepVal = C->getAPInt();
1073 
1074   // Huge step value - give up.
1075   if (APStepVal.getBitWidth() > 64)
1076     return 0;
1077 
1078   int64_t StepVal = APStepVal.getSExtValue();
1079 
1080   // Strided access.
1081   int64_t Stride = StepVal / Size;
1082   int64_t Rem = StepVal % Size;
1083   if (Rem)
1084     return 0;
1085 
1086   // If the SCEV could wrap but we have an inbounds gep with a unit stride we
1087   // know we can't "wrap around the address space". In case of address space
1088   // zero we know that this won't happen without triggering undefined behavior.
1089   if (!IsNoWrapAddRec && Stride != 1 && Stride != -1 &&
1090       (IsInBoundsGEP || !NullPointerIsDefined(Lp->getHeader()->getParent(),
1091                                               PtrTy->getAddressSpace()))) {
1092     if (Assume) {
1093       // We can avoid this case by adding a run-time check.
1094       LLVM_DEBUG(dbgs() << "LAA: Non unit strided pointer which is not either "
1095                         << "inbounds or in address space 0 may wrap:\n"
1096                         << "LAA:   Pointer: " << *Ptr << "\n"
1097                         << "LAA:   SCEV: " << *AR << "\n"
1098                         << "LAA:   Added an overflow assumption\n");
1099       PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
1100     } else
1101       return 0;
1102   }
1103 
1104   return Stride;
1105 }
1106 
1107 bool llvm::sortPtrAccesses(ArrayRef<Value *> VL, const DataLayout &DL,
1108                            ScalarEvolution &SE,
1109                            SmallVectorImpl<unsigned> &SortedIndices) {
1110   assert(llvm::all_of(
1111              VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&
1112          "Expected list of pointer operands.");
1113   SmallVector<std::pair<int64_t, Value *>, 4> OffValPairs;
1114   OffValPairs.reserve(VL.size());
1115 
1116   // Walk over the pointers, and map each of them to an offset relative to
1117   // first pointer in the array.
1118   Value *Ptr0 = VL[0];
1119   const SCEV *Scev0 = SE.getSCEV(Ptr0);
1120   Value *Obj0 = GetUnderlyingObject(Ptr0, DL);
1121 
1122   llvm::SmallSet<int64_t, 4> Offsets;
1123   for (auto *Ptr : VL) {
1124     // TODO: Outline this code as a special, more time consuming, version of
1125     // computeConstantDifference() function.
1126     if (Ptr->getType()->getPointerAddressSpace() !=
1127         Ptr0->getType()->getPointerAddressSpace())
1128       return false;
1129     // If a pointer refers to a different underlying object, bail - the
1130     // pointers are by definition incomparable.
1131     Value *CurrObj = GetUnderlyingObject(Ptr, DL);
1132     if (CurrObj != Obj0)
1133       return false;
1134 
1135     const SCEV *Scev = SE.getSCEV(Ptr);
1136     const auto *Diff = dyn_cast<SCEVConstant>(SE.getMinusSCEV(Scev, Scev0));
1137     // The pointers may not have a constant offset from each other, or SCEV
1138     // may just not be smart enough to figure out they do. Regardless,
1139     // there's nothing we can do.
1140     if (!Diff)
1141       return false;
1142 
1143     // Check if the pointer with the same offset is found.
1144     int64_t Offset = Diff->getAPInt().getSExtValue();
1145     if (!Offsets.insert(Offset).second)
1146       return false;
1147     OffValPairs.emplace_back(Offset, Ptr);
1148   }
1149   SortedIndices.clear();
1150   SortedIndices.resize(VL.size());
1151   std::iota(SortedIndices.begin(), SortedIndices.end(), 0);
1152 
1153   // Sort the memory accesses and keep the order of their uses in UseOrder.
1154   llvm::stable_sort(SortedIndices, [&](unsigned Left, unsigned Right) {
1155     return OffValPairs[Left].first < OffValPairs[Right].first;
1156   });
1157 
1158   // Check if the order is consecutive already.
1159   if (llvm::all_of(SortedIndices, [&SortedIndices](const unsigned I) {
1160         return I == SortedIndices[I];
1161       }))
1162     SortedIndices.clear();
1163 
1164   return true;
1165 }
1166 
1167 /// Take the address space operand from the Load/Store instruction.
1168 /// Returns -1 if this is not a valid Load/Store instruction.
1169 static unsigned getAddressSpaceOperand(Value *I) {
1170   if (LoadInst *L = dyn_cast<LoadInst>(I))
1171     return L->getPointerAddressSpace();
1172   if (StoreInst *S = dyn_cast<StoreInst>(I))
1173     return S->getPointerAddressSpace();
1174   return -1;
1175 }
1176 
1177 /// Returns true if the memory operations \p A and \p B are consecutive.
1178 bool llvm::isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL,
1179                                ScalarEvolution &SE, bool CheckType) {
1180   Value *PtrA = getLoadStorePointerOperand(A);
1181   Value *PtrB = getLoadStorePointerOperand(B);
1182   unsigned ASA = getAddressSpaceOperand(A);
1183   unsigned ASB = getAddressSpaceOperand(B);
1184 
1185   // Check that the address spaces match and that the pointers are valid.
1186   if (!PtrA || !PtrB || (ASA != ASB))
1187     return false;
1188 
1189   // Make sure that A and B are different pointers.
1190   if (PtrA == PtrB)
1191     return false;
1192 
1193   // Make sure that A and B have the same type if required.
1194   if (CheckType && PtrA->getType() != PtrB->getType())
1195     return false;
1196 
1197   unsigned IdxWidth = DL.getIndexSizeInBits(ASA);
1198   Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1199 
1200   APInt OffsetA(IdxWidth, 0), OffsetB(IdxWidth, 0);
1201   PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetA);
1202   PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetB);
1203 
1204   // Retrieve the address space again as pointer stripping now tracks through
1205   // `addrspacecast`.
1206   ASA = cast<PointerType>(PtrA->getType())->getAddressSpace();
1207   ASB = cast<PointerType>(PtrB->getType())->getAddressSpace();
1208   // Check that the address spaces match and that the pointers are valid.
1209   if (ASA != ASB)
1210     return false;
1211 
1212   IdxWidth = DL.getIndexSizeInBits(ASA);
1213   OffsetA = OffsetA.sextOrTrunc(IdxWidth);
1214   OffsetB = OffsetB.sextOrTrunc(IdxWidth);
1215 
1216   APInt Size(IdxWidth, DL.getTypeStoreSize(Ty));
1217 
1218   //  OffsetDelta = OffsetB - OffsetA;
1219   const SCEV *OffsetSCEVA = SE.getConstant(OffsetA);
1220   const SCEV *OffsetSCEVB = SE.getConstant(OffsetB);
1221   const SCEV *OffsetDeltaSCEV = SE.getMinusSCEV(OffsetSCEVB, OffsetSCEVA);
1222   const APInt &OffsetDelta = cast<SCEVConstant>(OffsetDeltaSCEV)->getAPInt();
1223 
1224   // Check if they are based on the same pointer. That makes the offsets
1225   // sufficient.
1226   if (PtrA == PtrB)
1227     return OffsetDelta == Size;
1228 
1229   // Compute the necessary base pointer delta to have the necessary final delta
1230   // equal to the size.
1231   // BaseDelta = Size - OffsetDelta;
1232   const SCEV *SizeSCEV = SE.getConstant(Size);
1233   const SCEV *BaseDelta = SE.getMinusSCEV(SizeSCEV, OffsetDeltaSCEV);
1234 
1235   // Otherwise compute the distance with SCEV between the base pointers.
1236   const SCEV *PtrSCEVA = SE.getSCEV(PtrA);
1237   const SCEV *PtrSCEVB = SE.getSCEV(PtrB);
1238   const SCEV *X = SE.getAddExpr(PtrSCEVA, BaseDelta);
1239   return X == PtrSCEVB;
1240 }
1241 
1242 MemoryDepChecker::VectorizationSafetyStatus
1243 MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
1244   switch (Type) {
1245   case NoDep:
1246   case Forward:
1247   case BackwardVectorizable:
1248     return VectorizationSafetyStatus::Safe;
1249 
1250   case Unknown:
1251     return VectorizationSafetyStatus::PossiblySafeWithRtChecks;
1252   case ForwardButPreventsForwarding:
1253   case Backward:
1254   case BackwardVectorizableButPreventsForwarding:
1255     return VectorizationSafetyStatus::Unsafe;
1256   }
1257   llvm_unreachable("unexpected DepType!");
1258 }
1259 
1260 bool MemoryDepChecker::Dependence::isBackward() const {
1261   switch (Type) {
1262   case NoDep:
1263   case Forward:
1264   case ForwardButPreventsForwarding:
1265   case Unknown:
1266     return false;
1267 
1268   case BackwardVectorizable:
1269   case Backward:
1270   case BackwardVectorizableButPreventsForwarding:
1271     return true;
1272   }
1273   llvm_unreachable("unexpected DepType!");
1274 }
1275 
1276 bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
1277   return isBackward() || Type == Unknown;
1278 }
1279 
1280 bool MemoryDepChecker::Dependence::isForward() const {
1281   switch (Type) {
1282   case Forward:
1283   case ForwardButPreventsForwarding:
1284     return true;
1285 
1286   case NoDep:
1287   case Unknown:
1288   case BackwardVectorizable:
1289   case Backward:
1290   case BackwardVectorizableButPreventsForwarding:
1291     return false;
1292   }
1293   llvm_unreachable("unexpected DepType!");
1294 }
1295 
1296 bool MemoryDepChecker::couldPreventStoreLoadForward(uint64_t Distance,
1297                                                     uint64_t TypeByteSize) {
1298   // If loads occur at a distance that is not a multiple of a feasible vector
1299   // factor store-load forwarding does not take place.
1300   // Positive dependences might cause troubles because vectorizing them might
1301   // prevent store-load forwarding making vectorized code run a lot slower.
1302   //   a[i] = a[i-3] ^ a[i-8];
1303   //   The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
1304   //   hence on your typical architecture store-load forwarding does not take
1305   //   place. Vectorizing in such cases does not make sense.
1306   // Store-load forwarding distance.
1307 
1308   // After this many iterations store-to-load forwarding conflicts should not
1309   // cause any slowdowns.
1310   const uint64_t NumItersForStoreLoadThroughMemory = 8 * TypeByteSize;
1311   // Maximum vector factor.
1312   uint64_t MaxVFWithoutSLForwardIssues = std::min(
1313       VectorizerParams::MaxVectorWidth * TypeByteSize, MaxSafeDepDistBytes);
1314 
1315   // Compute the smallest VF at which the store and load would be misaligned.
1316   for (uint64_t VF = 2 * TypeByteSize; VF <= MaxVFWithoutSLForwardIssues;
1317        VF *= 2) {
1318     // If the number of vector iteration between the store and the load are
1319     // small we could incur conflicts.
1320     if (Distance % VF && Distance / VF < NumItersForStoreLoadThroughMemory) {
1321       MaxVFWithoutSLForwardIssues = (VF >>= 1);
1322       break;
1323     }
1324   }
1325 
1326   if (MaxVFWithoutSLForwardIssues < 2 * TypeByteSize) {
1327     LLVM_DEBUG(
1328         dbgs() << "LAA: Distance " << Distance
1329                << " that could cause a store-load forwarding conflict\n");
1330     return true;
1331   }
1332 
1333   if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
1334       MaxVFWithoutSLForwardIssues !=
1335           VectorizerParams::MaxVectorWidth * TypeByteSize)
1336     MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
1337   return false;
1338 }
1339 
1340 void MemoryDepChecker::mergeInStatus(VectorizationSafetyStatus S) {
1341   if (Status < S)
1342     Status = S;
1343 }
1344 
1345 /// Given a non-constant (unknown) dependence-distance \p Dist between two
1346 /// memory accesses, that have the same stride whose absolute value is given
1347 /// in \p Stride, and that have the same type size \p TypeByteSize,
1348 /// in a loop whose takenCount is \p BackedgeTakenCount, check if it is
1349 /// possible to prove statically that the dependence distance is larger
1350 /// than the range that the accesses will travel through the execution of
1351 /// the loop. If so, return true; false otherwise. This is useful for
1352 /// example in loops such as the following (PR31098):
1353 ///     for (i = 0; i < D; ++i) {
1354 ///                = out[i];
1355 ///       out[i+D] =
1356 ///     }
1357 static bool isSafeDependenceDistance(const DataLayout &DL, ScalarEvolution &SE,
1358                                      const SCEV &BackedgeTakenCount,
1359                                      const SCEV &Dist, uint64_t Stride,
1360                                      uint64_t TypeByteSize) {
1361 
1362   // If we can prove that
1363   //      (**) |Dist| > BackedgeTakenCount * Step
1364   // where Step is the absolute stride of the memory accesses in bytes,
1365   // then there is no dependence.
1366   //
1367   // Rationale:
1368   // We basically want to check if the absolute distance (|Dist/Step|)
1369   // is >= the loop iteration count (or > BackedgeTakenCount).
1370   // This is equivalent to the Strong SIV Test (Practical Dependence Testing,
1371   // Section 4.2.1); Note, that for vectorization it is sufficient to prove
1372   // that the dependence distance is >= VF; This is checked elsewhere.
1373   // But in some cases we can prune unknown dependence distances early, and
1374   // even before selecting the VF, and without a runtime test, by comparing
1375   // the distance against the loop iteration count. Since the vectorized code
1376   // will be executed only if LoopCount >= VF, proving distance >= LoopCount
1377   // also guarantees that distance >= VF.
1378   //
1379   const uint64_t ByteStride = Stride * TypeByteSize;
1380   const SCEV *Step = SE.getConstant(BackedgeTakenCount.getType(), ByteStride);
1381   const SCEV *Product = SE.getMulExpr(&BackedgeTakenCount, Step);
1382 
1383   const SCEV *CastedDist = &Dist;
1384   const SCEV *CastedProduct = Product;
1385   uint64_t DistTypeSize = DL.getTypeAllocSize(Dist.getType());
1386   uint64_t ProductTypeSize = DL.getTypeAllocSize(Product->getType());
1387 
1388   // The dependence distance can be positive/negative, so we sign extend Dist;
1389   // The multiplication of the absolute stride in bytes and the
1390   // backedgeTakenCount is non-negative, so we zero extend Product.
1391   if (DistTypeSize > ProductTypeSize)
1392     CastedProduct = SE.getZeroExtendExpr(Product, Dist.getType());
1393   else
1394     CastedDist = SE.getNoopOrSignExtend(&Dist, Product->getType());
1395 
1396   // Is  Dist - (BackedgeTakenCount * Step) > 0 ?
1397   // (If so, then we have proven (**) because |Dist| >= Dist)
1398   const SCEV *Minus = SE.getMinusSCEV(CastedDist, CastedProduct);
1399   if (SE.isKnownPositive(Minus))
1400     return true;
1401 
1402   // Second try: Is  -Dist - (BackedgeTakenCount * Step) > 0 ?
1403   // (If so, then we have proven (**) because |Dist| >= -1*Dist)
1404   const SCEV *NegDist = SE.getNegativeSCEV(CastedDist);
1405   Minus = SE.getMinusSCEV(NegDist, CastedProduct);
1406   if (SE.isKnownPositive(Minus))
1407     return true;
1408 
1409   return false;
1410 }
1411 
1412 /// Check the dependence for two accesses with the same stride \p Stride.
1413 /// \p Distance is the positive distance and \p TypeByteSize is type size in
1414 /// bytes.
1415 ///
1416 /// \returns true if they are independent.
1417 static bool areStridedAccessesIndependent(uint64_t Distance, uint64_t Stride,
1418                                           uint64_t TypeByteSize) {
1419   assert(Stride > 1 && "The stride must be greater than 1");
1420   assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
1421   assert(Distance > 0 && "The distance must be non-zero");
1422 
1423   // Skip if the distance is not multiple of type byte size.
1424   if (Distance % TypeByteSize)
1425     return false;
1426 
1427   uint64_t ScaledDist = Distance / TypeByteSize;
1428 
1429   // No dependence if the scaled distance is not multiple of the stride.
1430   // E.g.
1431   //      for (i = 0; i < 1024 ; i += 4)
1432   //        A[i+2] = A[i] + 1;
1433   //
1434   // Two accesses in memory (scaled distance is 2, stride is 4):
1435   //     | A[0] |      |      |      | A[4] |      |      |      |
1436   //     |      |      | A[2] |      |      |      | A[6] |      |
1437   //
1438   // E.g.
1439   //      for (i = 0; i < 1024 ; i += 3)
1440   //        A[i+4] = A[i] + 1;
1441   //
1442   // Two accesses in memory (scaled distance is 4, stride is 3):
1443   //     | A[0] |      |      | A[3] |      |      | A[6] |      |      |
1444   //     |      |      |      |      | A[4] |      |      | A[7] |      |
1445   return ScaledDist % Stride;
1446 }
1447 
1448 MemoryDepChecker::Dependence::DepType
1449 MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
1450                               const MemAccessInfo &B, unsigned BIdx,
1451                               const ValueToValueMap &Strides) {
1452   assert (AIdx < BIdx && "Must pass arguments in program order");
1453 
1454   Value *APtr = A.getPointer();
1455   Value *BPtr = B.getPointer();
1456   bool AIsWrite = A.getInt();
1457   bool BIsWrite = B.getInt();
1458 
1459   // Two reads are independent.
1460   if (!AIsWrite && !BIsWrite)
1461     return Dependence::NoDep;
1462 
1463   // We cannot check pointers in different address spaces.
1464   if (APtr->getType()->getPointerAddressSpace() !=
1465       BPtr->getType()->getPointerAddressSpace())
1466     return Dependence::Unknown;
1467 
1468   int64_t StrideAPtr = getPtrStride(PSE, APtr, InnermostLoop, Strides, true);
1469   int64_t StrideBPtr = getPtrStride(PSE, BPtr, InnermostLoop, Strides, true);
1470 
1471   const SCEV *Src = PSE.getSCEV(APtr);
1472   const SCEV *Sink = PSE.getSCEV(BPtr);
1473 
1474   // If the induction step is negative we have to invert source and sink of the
1475   // dependence.
1476   if (StrideAPtr < 0) {
1477     std::swap(APtr, BPtr);
1478     std::swap(Src, Sink);
1479     std::swap(AIsWrite, BIsWrite);
1480     std::swap(AIdx, BIdx);
1481     std::swap(StrideAPtr, StrideBPtr);
1482   }
1483 
1484   const SCEV *Dist = PSE.getSE()->getMinusSCEV(Sink, Src);
1485 
1486   LLVM_DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
1487                     << "(Induction step: " << StrideAPtr << ")\n");
1488   LLVM_DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
1489                     << *InstMap[BIdx] << ": " << *Dist << "\n");
1490 
1491   // Need accesses with constant stride. We don't want to vectorize
1492   // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
1493   // the address space.
1494   if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
1495     LLVM_DEBUG(dbgs() << "Pointer access with non-constant stride\n");
1496     return Dependence::Unknown;
1497   }
1498 
1499   Type *ATy = APtr->getType()->getPointerElementType();
1500   Type *BTy = BPtr->getType()->getPointerElementType();
1501   auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
1502   uint64_t TypeByteSize = DL.getTypeAllocSize(ATy);
1503   uint64_t Stride = std::abs(StrideAPtr);
1504   const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
1505   if (!C) {
1506     if (TypeByteSize == DL.getTypeAllocSize(BTy) &&
1507         isSafeDependenceDistance(DL, *(PSE.getSE()),
1508                                  *(PSE.getBackedgeTakenCount()), *Dist, Stride,
1509                                  TypeByteSize))
1510       return Dependence::NoDep;
1511 
1512     LLVM_DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
1513     FoundNonConstantDistanceDependence = true;
1514     return Dependence::Unknown;
1515   }
1516 
1517   const APInt &Val = C->getAPInt();
1518   int64_t Distance = Val.getSExtValue();
1519 
1520   // Attempt to prove strided accesses independent.
1521   if (std::abs(Distance) > 0 && Stride > 1 && ATy == BTy &&
1522       areStridedAccessesIndependent(std::abs(Distance), Stride, TypeByteSize)) {
1523     LLVM_DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
1524     return Dependence::NoDep;
1525   }
1526 
1527   // Negative distances are not plausible dependencies.
1528   if (Val.isNegative()) {
1529     bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
1530     if (IsTrueDataDependence && EnableForwardingConflictDetection &&
1531         (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
1532          ATy != BTy)) {
1533       LLVM_DEBUG(dbgs() << "LAA: Forward but may prevent st->ld forwarding\n");
1534       return Dependence::ForwardButPreventsForwarding;
1535     }
1536 
1537     LLVM_DEBUG(dbgs() << "LAA: Dependence is negative\n");
1538     return Dependence::Forward;
1539   }
1540 
1541   // Write to the same location with the same size.
1542   // Could be improved to assert type sizes are the same (i32 == float, etc).
1543   if (Val == 0) {
1544     if (ATy == BTy)
1545       return Dependence::Forward;
1546     LLVM_DEBUG(
1547         dbgs() << "LAA: Zero dependence difference but different types\n");
1548     return Dependence::Unknown;
1549   }
1550 
1551   assert(Val.isStrictlyPositive() && "Expect a positive value");
1552 
1553   if (ATy != BTy) {
1554     LLVM_DEBUG(
1555         dbgs()
1556         << "LAA: ReadWrite-Write positive dependency with different types\n");
1557     return Dependence::Unknown;
1558   }
1559 
1560   // Bail out early if passed-in parameters make vectorization not feasible.
1561   unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
1562                            VectorizerParams::VectorizationFactor : 1);
1563   unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
1564                            VectorizerParams::VectorizationInterleave : 1);
1565   // The minimum number of iterations for a vectorized/unrolled version.
1566   unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
1567 
1568   // It's not vectorizable if the distance is smaller than the minimum distance
1569   // needed for a vectroized/unrolled version. Vectorizing one iteration in
1570   // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
1571   // TypeByteSize (No need to plus the last gap distance).
1572   //
1573   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1574   //      foo(int *A) {
1575   //        int *B = (int *)((char *)A + 14);
1576   //        for (i = 0 ; i < 1024 ; i += 2)
1577   //          B[i] = A[i] + 1;
1578   //      }
1579   //
1580   // Two accesses in memory (stride is 2):
1581   //     | A[0] |      | A[2] |      | A[4] |      | A[6] |      |
1582   //                              | B[0] |      | B[2] |      | B[4] |
1583   //
1584   // Distance needs for vectorizing iterations except the last iteration:
1585   // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
1586   // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
1587   //
1588   // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
1589   // 12, which is less than distance.
1590   //
1591   // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
1592   // the minimum distance needed is 28, which is greater than distance. It is
1593   // not safe to do vectorization.
1594   uint64_t MinDistanceNeeded =
1595       TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
1596   if (MinDistanceNeeded > static_cast<uint64_t>(Distance)) {
1597     LLVM_DEBUG(dbgs() << "LAA: Failure because of positive distance "
1598                       << Distance << '\n');
1599     return Dependence::Backward;
1600   }
1601 
1602   // Unsafe if the minimum distance needed is greater than max safe distance.
1603   if (MinDistanceNeeded > MaxSafeDepDistBytes) {
1604     LLVM_DEBUG(dbgs() << "LAA: Failure because it needs at least "
1605                       << MinDistanceNeeded << " size in bytes");
1606     return Dependence::Backward;
1607   }
1608 
1609   // Positive distance bigger than max vectorization factor.
1610   // FIXME: Should use max factor instead of max distance in bytes, which could
1611   // not handle different types.
1612   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1613   //      void foo (int *A, char *B) {
1614   //        for (unsigned i = 0; i < 1024; i++) {
1615   //          A[i+2] = A[i] + 1;
1616   //          B[i+2] = B[i] + 1;
1617   //        }
1618   //      }
1619   //
1620   // This case is currently unsafe according to the max safe distance. If we
1621   // analyze the two accesses on array B, the max safe dependence distance
1622   // is 2. Then we analyze the accesses on array A, the minimum distance needed
1623   // is 8, which is less than 2 and forbidden vectorization, But actually
1624   // both A and B could be vectorized by 2 iterations.
1625   MaxSafeDepDistBytes =
1626       std::min(static_cast<uint64_t>(Distance), MaxSafeDepDistBytes);
1627 
1628   bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
1629   if (IsTrueDataDependence && EnableForwardingConflictDetection &&
1630       couldPreventStoreLoadForward(Distance, TypeByteSize))
1631     return Dependence::BackwardVectorizableButPreventsForwarding;
1632 
1633   uint64_t MaxVF = MaxSafeDepDistBytes / (TypeByteSize * Stride);
1634   LLVM_DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
1635                     << " with max VF = " << MaxVF << '\n');
1636   uint64_t MaxVFInBits = MaxVF * TypeByteSize * 8;
1637   MaxSafeRegisterWidth = std::min(MaxSafeRegisterWidth, MaxVFInBits);
1638   return Dependence::BackwardVectorizable;
1639 }
1640 
1641 bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
1642                                    MemAccessInfoList &CheckDeps,
1643                                    const ValueToValueMap &Strides) {
1644 
1645   MaxSafeDepDistBytes = -1;
1646   SmallPtrSet<MemAccessInfo, 8> Visited;
1647   for (MemAccessInfo CurAccess : CheckDeps) {
1648     if (Visited.count(CurAccess))
1649       continue;
1650 
1651     // Get the relevant memory access set.
1652     EquivalenceClasses<MemAccessInfo>::iterator I =
1653       AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
1654 
1655     // Check accesses within this set.
1656     EquivalenceClasses<MemAccessInfo>::member_iterator AI =
1657         AccessSets.member_begin(I);
1658     EquivalenceClasses<MemAccessInfo>::member_iterator AE =
1659         AccessSets.member_end();
1660 
1661     // Check every access pair.
1662     while (AI != AE) {
1663       Visited.insert(*AI);
1664       bool AIIsWrite = AI->getInt();
1665       // Check loads only against next equivalent class, but stores also against
1666       // other stores in the same equivalence class - to the same address.
1667       EquivalenceClasses<MemAccessInfo>::member_iterator OI =
1668           (AIIsWrite ? AI : std::next(AI));
1669       while (OI != AE) {
1670         // Check every accessing instruction pair in program order.
1671         for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
1672              I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
1673           // Scan all accesses of another equivalence class, but only the next
1674           // accesses of the same equivalent class.
1675           for (std::vector<unsigned>::iterator
1676                    I2 = (OI == AI ? std::next(I1) : Accesses[*OI].begin()),
1677                    I2E = (OI == AI ? I1E : Accesses[*OI].end());
1678                I2 != I2E; ++I2) {
1679             auto A = std::make_pair(&*AI, *I1);
1680             auto B = std::make_pair(&*OI, *I2);
1681 
1682             assert(*I1 != *I2);
1683             if (*I1 > *I2)
1684               std::swap(A, B);
1685 
1686             Dependence::DepType Type =
1687                 isDependent(*A.first, A.second, *B.first, B.second, Strides);
1688             mergeInStatus(Dependence::isSafeForVectorization(Type));
1689 
1690             // Gather dependences unless we accumulated MaxDependences
1691             // dependences.  In that case return as soon as we find the first
1692             // unsafe dependence.  This puts a limit on this quadratic
1693             // algorithm.
1694             if (RecordDependences) {
1695               if (Type != Dependence::NoDep)
1696                 Dependences.push_back(Dependence(A.second, B.second, Type));
1697 
1698               if (Dependences.size() >= MaxDependences) {
1699                 RecordDependences = false;
1700                 Dependences.clear();
1701                 LLVM_DEBUG(dbgs()
1702                            << "Too many dependences, stopped recording\n");
1703               }
1704             }
1705             if (!RecordDependences && !isSafeForVectorization())
1706               return false;
1707           }
1708         ++OI;
1709       }
1710       AI++;
1711     }
1712   }
1713 
1714   LLVM_DEBUG(dbgs() << "Total Dependences: " << Dependences.size() << "\n");
1715   return isSafeForVectorization();
1716 }
1717 
1718 SmallVector<Instruction *, 4>
1719 MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
1720   MemAccessInfo Access(Ptr, isWrite);
1721   auto &IndexVector = Accesses.find(Access)->second;
1722 
1723   SmallVector<Instruction *, 4> Insts;
1724   transform(IndexVector,
1725                  std::back_inserter(Insts),
1726                  [&](unsigned Idx) { return this->InstMap[Idx]; });
1727   return Insts;
1728 }
1729 
1730 const char *MemoryDepChecker::Dependence::DepName[] = {
1731     "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
1732     "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
1733 
1734 void MemoryDepChecker::Dependence::print(
1735     raw_ostream &OS, unsigned Depth,
1736     const SmallVectorImpl<Instruction *> &Instrs) const {
1737   OS.indent(Depth) << DepName[Type] << ":\n";
1738   OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
1739   OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
1740 }
1741 
1742 bool LoopAccessInfo::canAnalyzeLoop() {
1743   // We need to have a loop header.
1744   LLVM_DEBUG(dbgs() << "LAA: Found a loop in "
1745                     << TheLoop->getHeader()->getParent()->getName() << ": "
1746                     << TheLoop->getHeader()->getName() << '\n');
1747 
1748   // We can only analyze innermost loops.
1749   if (!TheLoop->empty()) {
1750     LLVM_DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
1751     recordAnalysis("NotInnerMostLoop") << "loop is not the innermost loop";
1752     return false;
1753   }
1754 
1755   // We must have a single backedge.
1756   if (TheLoop->getNumBackEdges() != 1) {
1757     LLVM_DEBUG(
1758         dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1759     recordAnalysis("CFGNotUnderstood")
1760         << "loop control flow is not understood by analyzer";
1761     return false;
1762   }
1763 
1764   // We must have a single exiting block.
1765   if (!TheLoop->getExitingBlock()) {
1766     LLVM_DEBUG(
1767         dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1768     recordAnalysis("CFGNotUnderstood")
1769         << "loop control flow is not understood by analyzer";
1770     return false;
1771   }
1772 
1773   // We only handle bottom-tested loops, i.e. loop in which the condition is
1774   // checked at the end of each iteration. With that we can assume that all
1775   // instructions in the loop are executed the same number of times.
1776   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
1777     LLVM_DEBUG(
1778         dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1779     recordAnalysis("CFGNotUnderstood")
1780         << "loop control flow is not understood by analyzer";
1781     return false;
1782   }
1783 
1784   // ScalarEvolution needs to be able to find the exit count.
1785   const SCEV *ExitCount = PSE->getBackedgeTakenCount();
1786   if (ExitCount == PSE->getSE()->getCouldNotCompute()) {
1787     recordAnalysis("CantComputeNumberOfIterations")
1788         << "could not determine number of loop iterations";
1789     LLVM_DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
1790     return false;
1791   }
1792 
1793   return true;
1794 }
1795 
1796 void LoopAccessInfo::analyzeLoop(AliasAnalysis *AA, LoopInfo *LI,
1797                                  const TargetLibraryInfo *TLI,
1798                                  DominatorTree *DT) {
1799   typedef SmallPtrSet<Value*, 16> ValueSet;
1800 
1801   // Holds the Load and Store instructions.
1802   SmallVector<LoadInst *, 16> Loads;
1803   SmallVector<StoreInst *, 16> Stores;
1804 
1805   // Holds all the different accesses in the loop.
1806   unsigned NumReads = 0;
1807   unsigned NumReadWrites = 0;
1808 
1809   bool HasComplexMemInst = false;
1810 
1811   // A runtime check is only legal to insert if there are no convergent calls.
1812   HasConvergentOp = false;
1813 
1814   PtrRtChecking->Pointers.clear();
1815   PtrRtChecking->Need = false;
1816 
1817   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
1818 
1819   // For each block.
1820   for (BasicBlock *BB : TheLoop->blocks()) {
1821     // Scan the BB and collect legal loads and stores. Also detect any
1822     // convergent instructions.
1823     for (Instruction &I : *BB) {
1824       if (auto *Call = dyn_cast<CallBase>(&I)) {
1825         if (Call->isConvergent())
1826           HasConvergentOp = true;
1827       }
1828 
1829       // With both a non-vectorizable memory instruction and a convergent
1830       // operation, found in this loop, no reason to continue the search.
1831       if (HasComplexMemInst && HasConvergentOp) {
1832         CanVecMem = false;
1833         return;
1834       }
1835 
1836       // Avoid hitting recordAnalysis multiple times.
1837       if (HasComplexMemInst)
1838         continue;
1839 
1840       // If this is a load, save it. If this instruction can read from memory
1841       // but is not a load, then we quit. Notice that we don't handle function
1842       // calls that read or write.
1843       if (I.mayReadFromMemory()) {
1844         // Many math library functions read the rounding mode. We will only
1845         // vectorize a loop if it contains known function calls that don't set
1846         // the flag. Therefore, it is safe to ignore this read from memory.
1847         auto *Call = dyn_cast<CallInst>(&I);
1848         if (Call && getVectorIntrinsicIDForCall(Call, TLI))
1849           continue;
1850 
1851         // If the function has an explicit vectorized counterpart, we can safely
1852         // assume that it can be vectorized.
1853         if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
1854             !VFDatabase::getMappings(*Call).empty())
1855           continue;
1856 
1857         auto *Ld = dyn_cast<LoadInst>(&I);
1858         if (!Ld) {
1859           recordAnalysis("CantVectorizeInstruction", Ld)
1860             << "instruction cannot be vectorized";
1861           HasComplexMemInst = true;
1862           continue;
1863         }
1864         if (!Ld->isSimple() && !IsAnnotatedParallel) {
1865           recordAnalysis("NonSimpleLoad", Ld)
1866               << "read with atomic ordering or volatile read";
1867           LLVM_DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
1868           HasComplexMemInst = true;
1869           continue;
1870         }
1871         NumLoads++;
1872         Loads.push_back(Ld);
1873         DepChecker->addAccess(Ld);
1874         if (EnableMemAccessVersioning)
1875           collectStridedAccess(Ld);
1876         continue;
1877       }
1878 
1879       // Save 'store' instructions. Abort if other instructions write to memory.
1880       if (I.mayWriteToMemory()) {
1881         auto *St = dyn_cast<StoreInst>(&I);
1882         if (!St) {
1883           recordAnalysis("CantVectorizeInstruction", St)
1884               << "instruction cannot be vectorized";
1885           HasComplexMemInst = true;
1886           continue;
1887         }
1888         if (!St->isSimple() && !IsAnnotatedParallel) {
1889           recordAnalysis("NonSimpleStore", St)
1890               << "write with atomic ordering or volatile write";
1891           LLVM_DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
1892           HasComplexMemInst = true;
1893           continue;
1894         }
1895         NumStores++;
1896         Stores.push_back(St);
1897         DepChecker->addAccess(St);
1898         if (EnableMemAccessVersioning)
1899           collectStridedAccess(St);
1900       }
1901     } // Next instr.
1902   } // Next block.
1903 
1904   if (HasComplexMemInst) {
1905     CanVecMem = false;
1906     return;
1907   }
1908 
1909   // Now we have two lists that hold the loads and the stores.
1910   // Next, we find the pointers that they use.
1911 
1912   // Check if we see any stores. If there are no stores, then we don't
1913   // care if the pointers are *restrict*.
1914   if (!Stores.size()) {
1915     LLVM_DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
1916     CanVecMem = true;
1917     return;
1918   }
1919 
1920   MemoryDepChecker::DepCandidates DependentAccesses;
1921   AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
1922                           TheLoop, AA, LI, DependentAccesses, *PSE);
1923 
1924   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1925   // multiple times on the same object. If the ptr is accessed twice, once
1926   // for read and once for write, it will only appear once (on the write
1927   // list). This is okay, since we are going to check for conflicts between
1928   // writes and between reads and writes, but not between reads and reads.
1929   ValueSet Seen;
1930 
1931   // Record uniform store addresses to identify if we have multiple stores
1932   // to the same address.
1933   ValueSet UniformStores;
1934 
1935   for (StoreInst *ST : Stores) {
1936     Value *Ptr = ST->getPointerOperand();
1937 
1938     if (isUniform(Ptr))
1939       HasDependenceInvolvingLoopInvariantAddress |=
1940           !UniformStores.insert(Ptr).second;
1941 
1942     // If we did *not* see this pointer before, insert it to  the read-write
1943     // list. At this phase it is only a 'write' list.
1944     if (Seen.insert(Ptr).second) {
1945       ++NumReadWrites;
1946 
1947       MemoryLocation Loc = MemoryLocation::get(ST);
1948       // The TBAA metadata could have a control dependency on the predication
1949       // condition, so we cannot rely on it when determining whether or not we
1950       // need runtime pointer checks.
1951       if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
1952         Loc.AATags.TBAA = nullptr;
1953 
1954       Accesses.addStore(Loc);
1955     }
1956   }
1957 
1958   if (IsAnnotatedParallel) {
1959     LLVM_DEBUG(
1960         dbgs() << "LAA: A loop annotated parallel, ignore memory dependency "
1961                << "checks.\n");
1962     CanVecMem = true;
1963     return;
1964   }
1965 
1966   for (LoadInst *LD : Loads) {
1967     Value *Ptr = LD->getPointerOperand();
1968     // If we did *not* see this pointer before, insert it to the
1969     // read list. If we *did* see it before, then it is already in
1970     // the read-write list. This allows us to vectorize expressions
1971     // such as A[i] += x;  Because the address of A[i] is a read-write
1972     // pointer. This only works if the index of A[i] is consecutive.
1973     // If the address of i is unknown (for example A[B[i]]) then we may
1974     // read a few words, modify, and write a few words, and some of the
1975     // words may be written to the same address.
1976     bool IsReadOnlyPtr = false;
1977     if (Seen.insert(Ptr).second ||
1978         !getPtrStride(*PSE, Ptr, TheLoop, SymbolicStrides)) {
1979       ++NumReads;
1980       IsReadOnlyPtr = true;
1981     }
1982 
1983     // See if there is an unsafe dependency between a load to a uniform address and
1984     // store to the same uniform address.
1985     if (UniformStores.count(Ptr)) {
1986       LLVM_DEBUG(dbgs() << "LAA: Found an unsafe dependency between a uniform "
1987                            "load and uniform store to the same address!\n");
1988       HasDependenceInvolvingLoopInvariantAddress = true;
1989     }
1990 
1991     MemoryLocation Loc = MemoryLocation::get(LD);
1992     // The TBAA metadata could have a control dependency on the predication
1993     // condition, so we cannot rely on it when determining whether or not we
1994     // need runtime pointer checks.
1995     if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
1996       Loc.AATags.TBAA = nullptr;
1997 
1998     Accesses.addLoad(Loc, IsReadOnlyPtr);
1999   }
2000 
2001   // If we write (or read-write) to a single destination and there are no
2002   // other reads in this loop then is it safe to vectorize.
2003   if (NumReadWrites == 1 && NumReads == 0) {
2004     LLVM_DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
2005     CanVecMem = true;
2006     return;
2007   }
2008 
2009   // Build dependence sets and check whether we need a runtime pointer bounds
2010   // check.
2011   Accesses.buildDependenceSets();
2012 
2013   // Find pointers with computable bounds. We are going to use this information
2014   // to place a runtime bound check.
2015   bool CanDoRTIfNeeded = Accesses.canCheckPtrAtRT(*PtrRtChecking, PSE->getSE(),
2016                                                   TheLoop, SymbolicStrides);
2017   if (!CanDoRTIfNeeded) {
2018     recordAnalysis("CantIdentifyArrayBounds") << "cannot identify array bounds";
2019     LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
2020                       << "the array bounds.\n");
2021     CanVecMem = false;
2022     return;
2023   }
2024 
2025   LLVM_DEBUG(
2026     dbgs() << "LAA: May be able to perform a memory runtime check if needed.\n");
2027 
2028   CanVecMem = true;
2029   if (Accesses.isDependencyCheckNeeded()) {
2030     LLVM_DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
2031     CanVecMem = DepChecker->areDepsSafe(
2032         DependentAccesses, Accesses.getDependenciesToCheck(), SymbolicStrides);
2033     MaxSafeDepDistBytes = DepChecker->getMaxSafeDepDistBytes();
2034 
2035     if (!CanVecMem && DepChecker->shouldRetryWithRuntimeCheck()) {
2036       LLVM_DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
2037 
2038       // Clear the dependency checks. We assume they are not needed.
2039       Accesses.resetDepChecks(*DepChecker);
2040 
2041       PtrRtChecking->reset();
2042       PtrRtChecking->Need = true;
2043 
2044       auto *SE = PSE->getSE();
2045       CanDoRTIfNeeded = Accesses.canCheckPtrAtRT(*PtrRtChecking, SE, TheLoop,
2046                                                  SymbolicStrides, true);
2047 
2048       // Check that we found the bounds for the pointer.
2049       if (!CanDoRTIfNeeded) {
2050         recordAnalysis("CantCheckMemDepsAtRunTime")
2051             << "cannot check memory dependencies at runtime";
2052         LLVM_DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
2053         CanVecMem = false;
2054         return;
2055       }
2056 
2057       CanVecMem = true;
2058     }
2059   }
2060 
2061   if (HasConvergentOp) {
2062     recordAnalysis("CantInsertRuntimeCheckWithConvergent")
2063       << "cannot add control dependency to convergent operation";
2064     LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because a runtime check "
2065                          "would be needed with a convergent operation\n");
2066     CanVecMem = false;
2067     return;
2068   }
2069 
2070   if (CanVecMem)
2071     LLVM_DEBUG(
2072         dbgs() << "LAA: No unsafe dependent memory operations in loop.  We"
2073                << (PtrRtChecking->Need ? "" : " don't")
2074                << " need runtime memory checks.\n");
2075   else {
2076     recordAnalysis("UnsafeMemDep")
2077         << "unsafe dependent memory operations in loop. Use "
2078            "#pragma loop distribute(enable) to allow loop distribution "
2079            "to attempt to isolate the offending operations into a separate "
2080            "loop";
2081     LLVM_DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
2082   }
2083 }
2084 
2085 bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
2086                                            DominatorTree *DT)  {
2087   assert(TheLoop->contains(BB) && "Unknown block used");
2088 
2089   // Blocks that do not dominate the latch need predication.
2090   BasicBlock* Latch = TheLoop->getLoopLatch();
2091   return !DT->dominates(BB, Latch);
2092 }
2093 
2094 OptimizationRemarkAnalysis &LoopAccessInfo::recordAnalysis(StringRef RemarkName,
2095                                                            Instruction *I) {
2096   assert(!Report && "Multiple reports generated");
2097 
2098   Value *CodeRegion = TheLoop->getHeader();
2099   DebugLoc DL = TheLoop->getStartLoc();
2100 
2101   if (I) {
2102     CodeRegion = I->getParent();
2103     // If there is no debug location attached to the instruction, revert back to
2104     // using the loop's.
2105     if (I->getDebugLoc())
2106       DL = I->getDebugLoc();
2107   }
2108 
2109   Report = std::make_unique<OptimizationRemarkAnalysis>(DEBUG_TYPE, RemarkName, DL,
2110                                                    CodeRegion);
2111   return *Report;
2112 }
2113 
2114 bool LoopAccessInfo::isUniform(Value *V) const {
2115   auto *SE = PSE->getSE();
2116   // Since we rely on SCEV for uniformity, if the type is not SCEVable, it is
2117   // never considered uniform.
2118   // TODO: Is this really what we want? Even without FP SCEV, we may want some
2119   // trivially loop-invariant FP values to be considered uniform.
2120   if (!SE->isSCEVable(V->getType()))
2121     return false;
2122   return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
2123 }
2124 
2125 void LoopAccessInfo::collectStridedAccess(Value *MemAccess) {
2126   Value *Ptr = nullptr;
2127   if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
2128     Ptr = LI->getPointerOperand();
2129   else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
2130     Ptr = SI->getPointerOperand();
2131   else
2132     return;
2133 
2134   Value *Stride = getStrideFromPointer(Ptr, PSE->getSE(), TheLoop);
2135   if (!Stride)
2136     return;
2137 
2138   LLVM_DEBUG(dbgs() << "LAA: Found a strided access that is a candidate for "
2139                        "versioning:");
2140   LLVM_DEBUG(dbgs() << "  Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
2141 
2142   // Avoid adding the "Stride == 1" predicate when we know that
2143   // Stride >= Trip-Count. Such a predicate will effectively optimize a single
2144   // or zero iteration loop, as Trip-Count <= Stride == 1.
2145   //
2146   // TODO: We are currently not making a very informed decision on when it is
2147   // beneficial to apply stride versioning. It might make more sense that the
2148   // users of this analysis (such as the vectorizer) will trigger it, based on
2149   // their specific cost considerations; For example, in cases where stride
2150   // versioning does  not help resolving memory accesses/dependences, the
2151   // vectorizer should evaluate the cost of the runtime test, and the benefit
2152   // of various possible stride specializations, considering the alternatives
2153   // of using gather/scatters (if available).
2154 
2155   const SCEV *StrideExpr = PSE->getSCEV(Stride);
2156   const SCEV *BETakenCount = PSE->getBackedgeTakenCount();
2157 
2158   // Match the types so we can compare the stride and the BETakenCount.
2159   // The Stride can be positive/negative, so we sign extend Stride;
2160   // The backedgeTakenCount is non-negative, so we zero extend BETakenCount.
2161   const DataLayout &DL = TheLoop->getHeader()->getModule()->getDataLayout();
2162   uint64_t StrideTypeSize = DL.getTypeAllocSize(StrideExpr->getType());
2163   uint64_t BETypeSize = DL.getTypeAllocSize(BETakenCount->getType());
2164   const SCEV *CastedStride = StrideExpr;
2165   const SCEV *CastedBECount = BETakenCount;
2166   ScalarEvolution *SE = PSE->getSE();
2167   if (BETypeSize >= StrideTypeSize)
2168     CastedStride = SE->getNoopOrSignExtend(StrideExpr, BETakenCount->getType());
2169   else
2170     CastedBECount = SE->getZeroExtendExpr(BETakenCount, StrideExpr->getType());
2171   const SCEV *StrideMinusBETaken = SE->getMinusSCEV(CastedStride, CastedBECount);
2172   // Since TripCount == BackEdgeTakenCount + 1, checking:
2173   // "Stride >= TripCount" is equivalent to checking:
2174   // Stride - BETakenCount > 0
2175   if (SE->isKnownPositive(StrideMinusBETaken)) {
2176     LLVM_DEBUG(
2177         dbgs() << "LAA: Stride>=TripCount; No point in versioning as the "
2178                   "Stride==1 predicate will imply that the loop executes "
2179                   "at most once.\n");
2180     return;
2181   }
2182   LLVM_DEBUG(dbgs() << "LAA: Found a strided access that we can version.");
2183 
2184   SymbolicStrides[Ptr] = Stride;
2185   StrideSet.insert(Stride);
2186 }
2187 
2188 LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
2189                                const TargetLibraryInfo *TLI, AliasAnalysis *AA,
2190                                DominatorTree *DT, LoopInfo *LI)
2191     : PSE(std::make_unique<PredicatedScalarEvolution>(*SE, *L)),
2192       PtrRtChecking(std::make_unique<RuntimePointerChecking>(SE)),
2193       DepChecker(std::make_unique<MemoryDepChecker>(*PSE, L)), TheLoop(L),
2194       NumLoads(0), NumStores(0), MaxSafeDepDistBytes(-1), CanVecMem(false),
2195       HasConvergentOp(false),
2196       HasDependenceInvolvingLoopInvariantAddress(false) {
2197   if (canAnalyzeLoop())
2198     analyzeLoop(AA, LI, TLI, DT);
2199 }
2200 
2201 void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
2202   if (CanVecMem) {
2203     OS.indent(Depth) << "Memory dependences are safe";
2204     if (MaxSafeDepDistBytes != -1ULL)
2205       OS << " with a maximum dependence distance of " << MaxSafeDepDistBytes
2206          << " bytes";
2207     if (PtrRtChecking->Need)
2208       OS << " with run-time checks";
2209     OS << "\n";
2210   }
2211 
2212   if (HasConvergentOp)
2213     OS.indent(Depth) << "Has convergent operation in loop\n";
2214 
2215   if (Report)
2216     OS.indent(Depth) << "Report: " << Report->getMsg() << "\n";
2217 
2218   if (auto *Dependences = DepChecker->getDependences()) {
2219     OS.indent(Depth) << "Dependences:\n";
2220     for (auto &Dep : *Dependences) {
2221       Dep.print(OS, Depth + 2, DepChecker->getMemoryInstructions());
2222       OS << "\n";
2223     }
2224   } else
2225     OS.indent(Depth) << "Too many dependences, not recorded\n";
2226 
2227   // List the pair of accesses need run-time checks to prove independence.
2228   PtrRtChecking->print(OS, Depth);
2229   OS << "\n";
2230 
2231   OS.indent(Depth) << "Non vectorizable stores to invariant address were "
2232                    << (HasDependenceInvolvingLoopInvariantAddress ? "" : "not ")
2233                    << "found in loop.\n";
2234 
2235   OS.indent(Depth) << "SCEV assumptions:\n";
2236   PSE->getUnionPredicate().print(OS, Depth);
2237 
2238   OS << "\n";
2239 
2240   OS.indent(Depth) << "Expressions re-written:\n";
2241   PSE->print(OS, Depth);
2242 }
2243 
2244 LoopAccessLegacyAnalysis::LoopAccessLegacyAnalysis() : FunctionPass(ID) {
2245   initializeLoopAccessLegacyAnalysisPass(*PassRegistry::getPassRegistry());
2246 }
2247 
2248 const LoopAccessInfo &LoopAccessLegacyAnalysis::getInfo(Loop *L) {
2249   auto &LAI = LoopAccessInfoMap[L];
2250 
2251   if (!LAI)
2252     LAI = std::make_unique<LoopAccessInfo>(L, SE, TLI, AA, DT, LI);
2253 
2254   return *LAI.get();
2255 }
2256 
2257 void LoopAccessLegacyAnalysis::print(raw_ostream &OS, const Module *M) const {
2258   LoopAccessLegacyAnalysis &LAA = *const_cast<LoopAccessLegacyAnalysis *>(this);
2259 
2260   for (Loop *TopLevelLoop : *LI)
2261     for (Loop *L : depth_first(TopLevelLoop)) {
2262       OS.indent(2) << L->getHeader()->getName() << ":\n";
2263       auto &LAI = LAA.getInfo(L);
2264       LAI.print(OS, 4);
2265     }
2266 }
2267 
2268 bool LoopAccessLegacyAnalysis::runOnFunction(Function &F) {
2269   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2270   auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2271   TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
2272   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2273   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2274   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2275 
2276   return false;
2277 }
2278 
2279 void LoopAccessLegacyAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
2280     AU.addRequired<ScalarEvolutionWrapperPass>();
2281     AU.addRequired<AAResultsWrapperPass>();
2282     AU.addRequired<DominatorTreeWrapperPass>();
2283     AU.addRequired<LoopInfoWrapperPass>();
2284 
2285     AU.setPreservesAll();
2286 }
2287 
2288 char LoopAccessLegacyAnalysis::ID = 0;
2289 static const char laa_name[] = "Loop Access Analysis";
2290 #define LAA_NAME "loop-accesses"
2291 
2292 INITIALIZE_PASS_BEGIN(LoopAccessLegacyAnalysis, LAA_NAME, laa_name, false, true)
2293 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2294 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
2295 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2296 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
2297 INITIALIZE_PASS_END(LoopAccessLegacyAnalysis, LAA_NAME, laa_name, false, true)
2298 
2299 AnalysisKey LoopAccessAnalysis::Key;
2300 
2301 LoopAccessInfo LoopAccessAnalysis::run(Loop &L, LoopAnalysisManager &AM,
2302                                        LoopStandardAnalysisResults &AR) {
2303   return LoopAccessInfo(&L, &AR.SE, &AR.TLI, &AR.AA, &AR.DT, &AR.LI);
2304 }
2305 
2306 namespace llvm {
2307 
2308   Pass *createLAAPass() {
2309     return new LoopAccessLegacyAnalysis();
2310   }
2311 
2312 } // end namespace llvm
2313