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