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