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