xref: /freebsd-src/contrib/llvm-project/llvm/lib/Analysis/LoopAccessAnalysis.cpp (revision 972a253a57b6f144b0e4a3e2080a2a0076ec55a0)
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 
905 static SmallVector<std::pair<const SCEV *, bool>>
906 findForkedPointer(PredicatedScalarEvolution &PSE,
907                   const ValueToValueMap &StridesMap, Value *Ptr,
908                   const Loop *L) {
909   ScalarEvolution *SE = PSE.getSE();
910   assert(SE->isSCEVable(Ptr->getType()) && "Value is not SCEVable!");
911   SmallVector<std::pair<const SCEV *, bool>> Scevs;
912   findForkedSCEVs(SE, L, Ptr, Scevs, MaxForkedSCEVDepth);
913 
914   // For now, we will only accept a forked pointer with two possible SCEVs.
915   if (Scevs.size() == 2)
916     return Scevs;
917 
918   return {
919       std::make_pair(replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr), false)};
920 }
921 
922 bool AccessAnalysis::createCheckForAccess(RuntimePointerChecking &RtCheck,
923                                           MemAccessInfo Access, Type *AccessTy,
924                                           const ValueToValueMap &StridesMap,
925                                           DenseMap<Value *, unsigned> &DepSetId,
926                                           Loop *TheLoop, unsigned &RunningDepId,
927                                           unsigned ASId, bool ShouldCheckWrap,
928                                           bool Assume) {
929   Value *Ptr = Access.getPointer();
930 
931   SmallVector<std::pair<const SCEV *, bool>> TranslatedPtrs =
932       findForkedPointer(PSE, StridesMap, Ptr, TheLoop);
933 
934   for (auto &P : TranslatedPtrs) {
935     const SCEV *PtrExpr = P.first;
936     if (!hasComputableBounds(PSE, Ptr, PtrExpr, TheLoop, Assume))
937       return false;
938 
939     // When we run after a failing dependency check we have to make sure
940     // we don't have wrapping pointers.
941     if (ShouldCheckWrap) {
942       // Skip wrap checking when translating pointers.
943       if (TranslatedPtrs.size() > 1)
944         return false;
945 
946       if (!isNoWrap(PSE, StridesMap, Ptr, AccessTy, TheLoop)) {
947         auto *Expr = PSE.getSCEV(Ptr);
948         if (!Assume || !isa<SCEVAddRecExpr>(Expr))
949           return false;
950         PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
951       }
952     }
953     // If there's only one option for Ptr, look it up after bounds and wrap
954     // checking, because assumptions might have been added to PSE.
955     if (TranslatedPtrs.size() == 1)
956       TranslatedPtrs[0] = std::make_pair(
957           replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr), false);
958   }
959 
960   for (auto &P : TranslatedPtrs) {
961     const SCEV *PtrExpr = P.first;
962 
963     // The id of the dependence set.
964     unsigned DepId;
965 
966     if (isDependencyCheckNeeded()) {
967       Value *Leader = DepCands.getLeaderValue(Access).getPointer();
968       unsigned &LeaderId = DepSetId[Leader];
969       if (!LeaderId)
970         LeaderId = RunningDepId++;
971       DepId = LeaderId;
972     } else
973       // Each access has its own dependence set.
974       DepId = RunningDepId++;
975 
976     bool IsWrite = Access.getInt();
977     RtCheck.insert(TheLoop, Ptr, PtrExpr, AccessTy, IsWrite, DepId, ASId, PSE,
978                    P.second);
979     LLVM_DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
980   }
981 
982   return true;
983 }
984 
985 bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
986                                      ScalarEvolution *SE, Loop *TheLoop,
987                                      const ValueToValueMap &StridesMap,
988                                      Value *&UncomputablePtr, bool ShouldCheckWrap) {
989   // Find pointers with computable bounds. We are going to use this information
990   // to place a runtime bound check.
991   bool CanDoRT = true;
992 
993   bool MayNeedRTCheck = false;
994   if (!IsRTCheckAnalysisNeeded) return true;
995 
996   bool IsDepCheckNeeded = isDependencyCheckNeeded();
997 
998   // We assign a consecutive id to access from different alias sets.
999   // Accesses between different groups doesn't need to be checked.
1000   unsigned ASId = 0;
1001   for (auto &AS : AST) {
1002     int NumReadPtrChecks = 0;
1003     int NumWritePtrChecks = 0;
1004     bool CanDoAliasSetRT = true;
1005     ++ASId;
1006 
1007     // We assign consecutive id to access from different dependence sets.
1008     // Accesses within the same set don't need a runtime check.
1009     unsigned RunningDepId = 1;
1010     DenseMap<Value *, unsigned> DepSetId;
1011 
1012     SmallVector<std::pair<MemAccessInfo, Type *>, 4> Retries;
1013 
1014     // First, count how many write and read accesses are in the alias set. Also
1015     // collect MemAccessInfos for later.
1016     SmallVector<MemAccessInfo, 4> AccessInfos;
1017     for (const auto &A : AS) {
1018       Value *Ptr = A.getValue();
1019       bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
1020 
1021       if (IsWrite)
1022         ++NumWritePtrChecks;
1023       else
1024         ++NumReadPtrChecks;
1025       AccessInfos.emplace_back(Ptr, IsWrite);
1026     }
1027 
1028     // We do not need runtime checks for this alias set, if there are no writes
1029     // or a single write and no reads.
1030     if (NumWritePtrChecks == 0 ||
1031         (NumWritePtrChecks == 1 && NumReadPtrChecks == 0)) {
1032       assert((AS.size() <= 1 ||
1033               all_of(AS,
1034                      [this](auto AC) {
1035                        MemAccessInfo AccessWrite(AC.getValue(), true);
1036                        return DepCands.findValue(AccessWrite) == DepCands.end();
1037                      })) &&
1038              "Can only skip updating CanDoRT below, if all entries in AS "
1039              "are reads or there is at most 1 entry");
1040       continue;
1041     }
1042 
1043     for (auto &Access : AccessInfos) {
1044       for (const auto &AccessTy : Accesses[Access]) {
1045         if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap,
1046                                   DepSetId, TheLoop, RunningDepId, ASId,
1047                                   ShouldCheckWrap, false)) {
1048           LLVM_DEBUG(dbgs() << "LAA: Can't find bounds for ptr:"
1049                             << *Access.getPointer() << '\n');
1050           Retries.push_back({Access, AccessTy});
1051           CanDoAliasSetRT = false;
1052         }
1053       }
1054     }
1055 
1056     // Note that this function computes CanDoRT and MayNeedRTCheck
1057     // independently. For example CanDoRT=false, MayNeedRTCheck=false means that
1058     // we have a pointer for which we couldn't find the bounds but we don't
1059     // actually need to emit any checks so it does not matter.
1060     //
1061     // We need runtime checks for this alias set, if there are at least 2
1062     // dependence sets (in which case RunningDepId > 2) or if we need to re-try
1063     // any bound checks (because in that case the number of dependence sets is
1064     // incomplete).
1065     bool NeedsAliasSetRTCheck = RunningDepId > 2 || !Retries.empty();
1066 
1067     // We need to perform run-time alias checks, but some pointers had bounds
1068     // that couldn't be checked.
1069     if (NeedsAliasSetRTCheck && !CanDoAliasSetRT) {
1070       // Reset the CanDoSetRt flag and retry all accesses that have failed.
1071       // We know that we need these checks, so we can now be more aggressive
1072       // and add further checks if required (overflow checks).
1073       CanDoAliasSetRT = true;
1074       for (auto Retry : Retries) {
1075         MemAccessInfo Access = Retry.first;
1076         Type *AccessTy = Retry.second;
1077         if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap,
1078                                   DepSetId, TheLoop, RunningDepId, ASId,
1079                                   ShouldCheckWrap, /*Assume=*/true)) {
1080           CanDoAliasSetRT = false;
1081           UncomputablePtr = Access.getPointer();
1082           break;
1083         }
1084       }
1085     }
1086 
1087     CanDoRT &= CanDoAliasSetRT;
1088     MayNeedRTCheck |= NeedsAliasSetRTCheck;
1089     ++ASId;
1090   }
1091 
1092   // If the pointers that we would use for the bounds comparison have different
1093   // address spaces, assume the values aren't directly comparable, so we can't
1094   // use them for the runtime check. We also have to assume they could
1095   // overlap. In the future there should be metadata for whether address spaces
1096   // are disjoint.
1097   unsigned NumPointers = RtCheck.Pointers.size();
1098   for (unsigned i = 0; i < NumPointers; ++i) {
1099     for (unsigned j = i + 1; j < NumPointers; ++j) {
1100       // Only need to check pointers between two different dependency sets.
1101       if (RtCheck.Pointers[i].DependencySetId ==
1102           RtCheck.Pointers[j].DependencySetId)
1103        continue;
1104       // Only need to check pointers in the same alias set.
1105       if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
1106         continue;
1107 
1108       Value *PtrI = RtCheck.Pointers[i].PointerValue;
1109       Value *PtrJ = RtCheck.Pointers[j].PointerValue;
1110 
1111       unsigned ASi = PtrI->getType()->getPointerAddressSpace();
1112       unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
1113       if (ASi != ASj) {
1114         LLVM_DEBUG(
1115             dbgs() << "LAA: Runtime check would require comparison between"
1116                       " different address spaces\n");
1117         return false;
1118       }
1119     }
1120   }
1121 
1122   if (MayNeedRTCheck && CanDoRT)
1123     RtCheck.generateChecks(DepCands, IsDepCheckNeeded);
1124 
1125   LLVM_DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks()
1126                     << " pointer comparisons.\n");
1127 
1128   // If we can do run-time checks, but there are no checks, no runtime checks
1129   // are needed. This can happen when all pointers point to the same underlying
1130   // object for example.
1131   RtCheck.Need = CanDoRT ? RtCheck.getNumberOfChecks() != 0 : MayNeedRTCheck;
1132 
1133   bool CanDoRTIfNeeded = !RtCheck.Need || CanDoRT;
1134   if (!CanDoRTIfNeeded)
1135     RtCheck.reset();
1136   return CanDoRTIfNeeded;
1137 }
1138 
1139 void AccessAnalysis::processMemAccesses() {
1140   // We process the set twice: first we process read-write pointers, last we
1141   // process read-only pointers. This allows us to skip dependence tests for
1142   // read-only pointers.
1143 
1144   LLVM_DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
1145   LLVM_DEBUG(dbgs() << "  AST: "; AST.dump());
1146   LLVM_DEBUG(dbgs() << "LAA:   Accesses(" << Accesses.size() << "):\n");
1147   LLVM_DEBUG({
1148     for (auto A : Accesses)
1149       dbgs() << "\t" << *A.first.getPointer() << " ("
1150              << (A.first.getInt()
1151                      ? "write"
1152                      : (ReadOnlyPtr.count(A.first.getPointer()) ? "read-only"
1153                                                                 : "read"))
1154              << ")\n";
1155   });
1156 
1157   // The AliasSetTracker has nicely partitioned our pointers by metadata
1158   // compatibility and potential for underlying-object overlap. As a result, we
1159   // only need to check for potential pointer dependencies within each alias
1160   // set.
1161   for (const auto &AS : AST) {
1162     // Note that both the alias-set tracker and the alias sets themselves used
1163     // linked lists internally and so the iteration order here is deterministic
1164     // (matching the original instruction order within each set).
1165 
1166     bool SetHasWrite = false;
1167 
1168     // Map of pointers to last access encountered.
1169     typedef DenseMap<const Value*, MemAccessInfo> UnderlyingObjToAccessMap;
1170     UnderlyingObjToAccessMap ObjToLastAccess;
1171 
1172     // Set of access to check after all writes have been processed.
1173     PtrAccessMap DeferredAccesses;
1174 
1175     // Iterate over each alias set twice, once to process read/write pointers,
1176     // and then to process read-only pointers.
1177     for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
1178       bool UseDeferred = SetIteration > 0;
1179       PtrAccessMap &S = UseDeferred ? DeferredAccesses : Accesses;
1180 
1181       for (const auto &AV : AS) {
1182         Value *Ptr = AV.getValue();
1183 
1184         // For a single memory access in AliasSetTracker, Accesses may contain
1185         // both read and write, and they both need to be handled for CheckDeps.
1186         for (const auto &AC : S) {
1187           if (AC.first.getPointer() != Ptr)
1188             continue;
1189 
1190           bool IsWrite = AC.first.getInt();
1191 
1192           // If we're using the deferred access set, then it contains only
1193           // reads.
1194           bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
1195           if (UseDeferred && !IsReadOnlyPtr)
1196             continue;
1197           // Otherwise, the pointer must be in the PtrAccessSet, either as a
1198           // read or a write.
1199           assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
1200                   S.count(MemAccessInfo(Ptr, false))) &&
1201                  "Alias-set pointer not in the access set?");
1202 
1203           MemAccessInfo Access(Ptr, IsWrite);
1204           DepCands.insert(Access);
1205 
1206           // Memorize read-only pointers for later processing and skip them in
1207           // the first round (they need to be checked after we have seen all
1208           // write pointers). Note: we also mark pointer that are not
1209           // consecutive as "read-only" pointers (so that we check
1210           // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
1211           if (!UseDeferred && IsReadOnlyPtr) {
1212             // We only use the pointer keys, the types vector values don't
1213             // matter.
1214             DeferredAccesses.insert({Access, {}});
1215             continue;
1216           }
1217 
1218           // If this is a write - check other reads and writes for conflicts. If
1219           // this is a read only check other writes for conflicts (but only if
1220           // there is no other write to the ptr - this is an optimization to
1221           // catch "a[i] = a[i] + " without having to do a dependence check).
1222           if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
1223             CheckDeps.push_back(Access);
1224             IsRTCheckAnalysisNeeded = true;
1225           }
1226 
1227           if (IsWrite)
1228             SetHasWrite = true;
1229 
1230           // Create sets of pointers connected by a shared alias set and
1231           // underlying object.
1232           typedef SmallVector<const Value *, 16> ValueVector;
1233           ValueVector TempObjects;
1234 
1235           getUnderlyingObjects(Ptr, TempObjects, LI);
1236           LLVM_DEBUG(dbgs()
1237                      << "Underlying objects for pointer " << *Ptr << "\n");
1238           for (const Value *UnderlyingObj : TempObjects) {
1239             // nullptr never alias, don't join sets for pointer that have "null"
1240             // in their UnderlyingObjects list.
1241             if (isa<ConstantPointerNull>(UnderlyingObj) &&
1242                 !NullPointerIsDefined(
1243                     TheLoop->getHeader()->getParent(),
1244                     UnderlyingObj->getType()->getPointerAddressSpace()))
1245               continue;
1246 
1247             UnderlyingObjToAccessMap::iterator Prev =
1248                 ObjToLastAccess.find(UnderlyingObj);
1249             if (Prev != ObjToLastAccess.end())
1250               DepCands.unionSets(Access, Prev->second);
1251 
1252             ObjToLastAccess[UnderlyingObj] = Access;
1253             LLVM_DEBUG(dbgs() << "  " << *UnderlyingObj << "\n");
1254           }
1255         }
1256       }
1257     }
1258   }
1259 }
1260 
1261 static bool isInBoundsGep(Value *Ptr) {
1262   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
1263     return GEP->isInBounds();
1264   return false;
1265 }
1266 
1267 /// Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
1268 /// i.e. monotonically increasing/decreasing.
1269 static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
1270                            PredicatedScalarEvolution &PSE, const Loop *L) {
1271   // FIXME: This should probably only return true for NUW.
1272   if (AR->getNoWrapFlags(SCEV::NoWrapMask))
1273     return true;
1274 
1275   // Scalar evolution does not propagate the non-wrapping flags to values that
1276   // are derived from a non-wrapping induction variable because non-wrapping
1277   // could be flow-sensitive.
1278   //
1279   // Look through the potentially overflowing instruction to try to prove
1280   // non-wrapping for the *specific* value of Ptr.
1281 
1282   // The arithmetic implied by an inbounds GEP can't overflow.
1283   auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
1284   if (!GEP || !GEP->isInBounds())
1285     return false;
1286 
1287   // Make sure there is only one non-const index and analyze that.
1288   Value *NonConstIndex = nullptr;
1289   for (Value *Index : GEP->indices())
1290     if (!isa<ConstantInt>(Index)) {
1291       if (NonConstIndex)
1292         return false;
1293       NonConstIndex = Index;
1294     }
1295   if (!NonConstIndex)
1296     // The recurrence is on the pointer, ignore for now.
1297     return false;
1298 
1299   // The index in GEP is signed.  It is non-wrapping if it's derived from a NSW
1300   // AddRec using a NSW operation.
1301   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
1302     if (OBO->hasNoSignedWrap() &&
1303         // Assume constant for other the operand so that the AddRec can be
1304         // easily found.
1305         isa<ConstantInt>(OBO->getOperand(1))) {
1306       auto *OpScev = PSE.getSCEV(OBO->getOperand(0));
1307 
1308       if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
1309         return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
1310     }
1311 
1312   return false;
1313 }
1314 
1315 /// Check whether the access through \p Ptr has a constant stride.
1316 int64_t llvm::getPtrStride(PredicatedScalarEvolution &PSE, Type *AccessTy,
1317                            Value *Ptr, const Loop *Lp,
1318                            const ValueToValueMap &StridesMap, bool Assume,
1319                            bool ShouldCheckWrap) {
1320   Type *Ty = Ptr->getType();
1321   assert(Ty->isPointerTy() && "Unexpected non-ptr");
1322 
1323   if (isa<ScalableVectorType>(AccessTy)) {
1324     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Scalable object: " << *AccessTy
1325                       << "\n");
1326     return 0;
1327   }
1328 
1329   const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr);
1330 
1331   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
1332   if (Assume && !AR)
1333     AR = PSE.getAsAddRec(Ptr);
1334 
1335   if (!AR) {
1336     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer " << *Ptr
1337                       << " SCEV: " << *PtrScev << "\n");
1338     return 0;
1339   }
1340 
1341   // The access function must stride over the innermost loop.
1342   if (Lp != AR->getLoop()) {
1343     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop "
1344                       << *Ptr << " SCEV: " << *AR << "\n");
1345     return 0;
1346   }
1347 
1348   // The address calculation must not wrap. Otherwise, a dependence could be
1349   // inverted.
1350   // An inbounds getelementptr that is a AddRec with a unit stride
1351   // cannot wrap per definition. The unit stride requirement is checked later.
1352   // An getelementptr without an inbounds attribute and unit stride would have
1353   // to access the pointer value "0" which is undefined behavior in address
1354   // space 0, therefore we can also vectorize this case.
1355   unsigned AddrSpace = Ty->getPointerAddressSpace();
1356   bool IsInBoundsGEP = isInBoundsGep(Ptr);
1357   bool IsNoWrapAddRec = !ShouldCheckWrap ||
1358     PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW) ||
1359     isNoWrapAddRec(Ptr, AR, PSE, Lp);
1360   if (!IsNoWrapAddRec && !IsInBoundsGEP &&
1361       NullPointerIsDefined(Lp->getHeader()->getParent(), AddrSpace)) {
1362     if (Assume) {
1363       PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
1364       IsNoWrapAddRec = true;
1365       LLVM_DEBUG(dbgs() << "LAA: Pointer may wrap in the address space:\n"
1366                         << "LAA:   Pointer: " << *Ptr << "\n"
1367                         << "LAA:   SCEV: " << *AR << "\n"
1368                         << "LAA:   Added an overflow assumption\n");
1369     } else {
1370       LLVM_DEBUG(
1371           dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
1372                  << *Ptr << " SCEV: " << *AR << "\n");
1373       return 0;
1374     }
1375   }
1376 
1377   // Check the step is constant.
1378   const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
1379 
1380   // Calculate the pointer stride and check if it is constant.
1381   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
1382   if (!C) {
1383     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr
1384                       << " SCEV: " << *AR << "\n");
1385     return 0;
1386   }
1387 
1388   auto &DL = Lp->getHeader()->getModule()->getDataLayout();
1389   TypeSize AllocSize = DL.getTypeAllocSize(AccessTy);
1390   int64_t Size = AllocSize.getFixedSize();
1391   const APInt &APStepVal = C->getAPInt();
1392 
1393   // Huge step value - give up.
1394   if (APStepVal.getBitWidth() > 64)
1395     return 0;
1396 
1397   int64_t StepVal = APStepVal.getSExtValue();
1398 
1399   // Strided access.
1400   int64_t Stride = StepVal / Size;
1401   int64_t Rem = StepVal % Size;
1402   if (Rem)
1403     return 0;
1404 
1405   // If the SCEV could wrap but we have an inbounds gep with a unit stride we
1406   // know we can't "wrap around the address space". In case of address space
1407   // zero we know that this won't happen without triggering undefined behavior.
1408   if (!IsNoWrapAddRec && Stride != 1 && Stride != -1 &&
1409       (IsInBoundsGEP || !NullPointerIsDefined(Lp->getHeader()->getParent(),
1410                                               AddrSpace))) {
1411     if (Assume) {
1412       // We can avoid this case by adding a run-time check.
1413       LLVM_DEBUG(dbgs() << "LAA: Non unit strided pointer which is not either "
1414                         << "inbounds or in address space 0 may wrap:\n"
1415                         << "LAA:   Pointer: " << *Ptr << "\n"
1416                         << "LAA:   SCEV: " << *AR << "\n"
1417                         << "LAA:   Added an overflow assumption\n");
1418       PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
1419     } else
1420       return 0;
1421   }
1422 
1423   return Stride;
1424 }
1425 
1426 Optional<int> llvm::getPointersDiff(Type *ElemTyA, Value *PtrA, Type *ElemTyB,
1427                                     Value *PtrB, const DataLayout &DL,
1428                                     ScalarEvolution &SE, bool StrictCheck,
1429                                     bool CheckType) {
1430   assert(PtrA && PtrB && "Expected non-nullptr pointers.");
1431   assert(cast<PointerType>(PtrA->getType())
1432              ->isOpaqueOrPointeeTypeMatches(ElemTyA) && "Wrong PtrA type");
1433   assert(cast<PointerType>(PtrB->getType())
1434              ->isOpaqueOrPointeeTypeMatches(ElemTyB) && "Wrong PtrB type");
1435 
1436   // Make sure that A and B are different pointers.
1437   if (PtrA == PtrB)
1438     return 0;
1439 
1440   // Make sure that the element types are the same if required.
1441   if (CheckType && ElemTyA != ElemTyB)
1442     return None;
1443 
1444   unsigned ASA = PtrA->getType()->getPointerAddressSpace();
1445   unsigned ASB = PtrB->getType()->getPointerAddressSpace();
1446 
1447   // Check that the address spaces match.
1448   if (ASA != ASB)
1449     return None;
1450   unsigned IdxWidth = DL.getIndexSizeInBits(ASA);
1451 
1452   APInt OffsetA(IdxWidth, 0), OffsetB(IdxWidth, 0);
1453   Value *PtrA1 = PtrA->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetA);
1454   Value *PtrB1 = PtrB->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetB);
1455 
1456   int Val;
1457   if (PtrA1 == PtrB1) {
1458     // Retrieve the address space again as pointer stripping now tracks through
1459     // `addrspacecast`.
1460     ASA = cast<PointerType>(PtrA1->getType())->getAddressSpace();
1461     ASB = cast<PointerType>(PtrB1->getType())->getAddressSpace();
1462     // Check that the address spaces match and that the pointers are valid.
1463     if (ASA != ASB)
1464       return None;
1465 
1466     IdxWidth = DL.getIndexSizeInBits(ASA);
1467     OffsetA = OffsetA.sextOrTrunc(IdxWidth);
1468     OffsetB = OffsetB.sextOrTrunc(IdxWidth);
1469 
1470     OffsetB -= OffsetA;
1471     Val = OffsetB.getSExtValue();
1472   } else {
1473     // Otherwise compute the distance with SCEV between the base pointers.
1474     const SCEV *PtrSCEVA = SE.getSCEV(PtrA);
1475     const SCEV *PtrSCEVB = SE.getSCEV(PtrB);
1476     const auto *Diff =
1477         dyn_cast<SCEVConstant>(SE.getMinusSCEV(PtrSCEVB, PtrSCEVA));
1478     if (!Diff)
1479       return None;
1480     Val = Diff->getAPInt().getSExtValue();
1481   }
1482   int Size = DL.getTypeStoreSize(ElemTyA);
1483   int Dist = Val / Size;
1484 
1485   // Ensure that the calculated distance matches the type-based one after all
1486   // the bitcasts removal in the provided pointers.
1487   if (!StrictCheck || Dist * Size == Val)
1488     return Dist;
1489   return None;
1490 }
1491 
1492 bool llvm::sortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy,
1493                            const DataLayout &DL, ScalarEvolution &SE,
1494                            SmallVectorImpl<unsigned> &SortedIndices) {
1495   assert(llvm::all_of(
1496              VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&
1497          "Expected list of pointer operands.");
1498   // Walk over the pointers, and map each of them to an offset relative to
1499   // first pointer in the array.
1500   Value *Ptr0 = VL[0];
1501 
1502   using DistOrdPair = std::pair<int64_t, int>;
1503   auto Compare = llvm::less_first();
1504   std::set<DistOrdPair, decltype(Compare)> Offsets(Compare);
1505   Offsets.emplace(0, 0);
1506   int Cnt = 1;
1507   bool IsConsecutive = true;
1508   for (auto *Ptr : VL.drop_front()) {
1509     Optional<int> Diff = getPointersDiff(ElemTy, Ptr0, ElemTy, Ptr, DL, SE,
1510                                          /*StrictCheck=*/true);
1511     if (!Diff)
1512       return false;
1513 
1514     // Check if the pointer with the same offset is found.
1515     int64_t Offset = *Diff;
1516     auto Res = Offsets.emplace(Offset, Cnt);
1517     if (!Res.second)
1518       return false;
1519     // Consecutive order if the inserted element is the last one.
1520     IsConsecutive = IsConsecutive && std::next(Res.first) == Offsets.end();
1521     ++Cnt;
1522   }
1523   SortedIndices.clear();
1524   if (!IsConsecutive) {
1525     // Fill SortedIndices array only if it is non-consecutive.
1526     SortedIndices.resize(VL.size());
1527     Cnt = 0;
1528     for (const std::pair<int64_t, int> &Pair : Offsets) {
1529       SortedIndices[Cnt] = Pair.second;
1530       ++Cnt;
1531     }
1532   }
1533   return true;
1534 }
1535 
1536 /// Returns true if the memory operations \p A and \p B are consecutive.
1537 bool llvm::isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL,
1538                                ScalarEvolution &SE, bool CheckType) {
1539   Value *PtrA = getLoadStorePointerOperand(A);
1540   Value *PtrB = getLoadStorePointerOperand(B);
1541   if (!PtrA || !PtrB)
1542     return false;
1543   Type *ElemTyA = getLoadStoreType(A);
1544   Type *ElemTyB = getLoadStoreType(B);
1545   Optional<int> Diff = getPointersDiff(ElemTyA, PtrA, ElemTyB, PtrB, DL, SE,
1546                                        /*StrictCheck=*/true, CheckType);
1547   return Diff && *Diff == 1;
1548 }
1549 
1550 void MemoryDepChecker::addAccess(StoreInst *SI) {
1551   visitPointers(SI->getPointerOperand(), *InnermostLoop,
1552                 [this, SI](Value *Ptr) {
1553                   Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
1554                   InstMap.push_back(SI);
1555                   ++AccessIdx;
1556                 });
1557 }
1558 
1559 void MemoryDepChecker::addAccess(LoadInst *LI) {
1560   visitPointers(LI->getPointerOperand(), *InnermostLoop,
1561                 [this, LI](Value *Ptr) {
1562                   Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
1563                   InstMap.push_back(LI);
1564                   ++AccessIdx;
1565                 });
1566 }
1567 
1568 MemoryDepChecker::VectorizationSafetyStatus
1569 MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
1570   switch (Type) {
1571   case NoDep:
1572   case Forward:
1573   case BackwardVectorizable:
1574     return VectorizationSafetyStatus::Safe;
1575 
1576   case Unknown:
1577     return VectorizationSafetyStatus::PossiblySafeWithRtChecks;
1578   case ForwardButPreventsForwarding:
1579   case Backward:
1580   case BackwardVectorizableButPreventsForwarding:
1581     return VectorizationSafetyStatus::Unsafe;
1582   }
1583   llvm_unreachable("unexpected DepType!");
1584 }
1585 
1586 bool MemoryDepChecker::Dependence::isBackward() const {
1587   switch (Type) {
1588   case NoDep:
1589   case Forward:
1590   case ForwardButPreventsForwarding:
1591   case Unknown:
1592     return false;
1593 
1594   case BackwardVectorizable:
1595   case Backward:
1596   case BackwardVectorizableButPreventsForwarding:
1597     return true;
1598   }
1599   llvm_unreachable("unexpected DepType!");
1600 }
1601 
1602 bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
1603   return isBackward() || Type == Unknown;
1604 }
1605 
1606 bool MemoryDepChecker::Dependence::isForward() const {
1607   switch (Type) {
1608   case Forward:
1609   case ForwardButPreventsForwarding:
1610     return true;
1611 
1612   case NoDep:
1613   case Unknown:
1614   case BackwardVectorizable:
1615   case Backward:
1616   case BackwardVectorizableButPreventsForwarding:
1617     return false;
1618   }
1619   llvm_unreachable("unexpected DepType!");
1620 }
1621 
1622 bool MemoryDepChecker::couldPreventStoreLoadForward(uint64_t Distance,
1623                                                     uint64_t TypeByteSize) {
1624   // If loads occur at a distance that is not a multiple of a feasible vector
1625   // factor store-load forwarding does not take place.
1626   // Positive dependences might cause troubles because vectorizing them might
1627   // prevent store-load forwarding making vectorized code run a lot slower.
1628   //   a[i] = a[i-3] ^ a[i-8];
1629   //   The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
1630   //   hence on your typical architecture store-load forwarding does not take
1631   //   place. Vectorizing in such cases does not make sense.
1632   // Store-load forwarding distance.
1633 
1634   // After this many iterations store-to-load forwarding conflicts should not
1635   // cause any slowdowns.
1636   const uint64_t NumItersForStoreLoadThroughMemory = 8 * TypeByteSize;
1637   // Maximum vector factor.
1638   uint64_t MaxVFWithoutSLForwardIssues = std::min(
1639       VectorizerParams::MaxVectorWidth * TypeByteSize, MaxSafeDepDistBytes);
1640 
1641   // Compute the smallest VF at which the store and load would be misaligned.
1642   for (uint64_t VF = 2 * TypeByteSize; VF <= MaxVFWithoutSLForwardIssues;
1643        VF *= 2) {
1644     // If the number of vector iteration between the store and the load are
1645     // small we could incur conflicts.
1646     if (Distance % VF && Distance / VF < NumItersForStoreLoadThroughMemory) {
1647       MaxVFWithoutSLForwardIssues = (VF >> 1);
1648       break;
1649     }
1650   }
1651 
1652   if (MaxVFWithoutSLForwardIssues < 2 * TypeByteSize) {
1653     LLVM_DEBUG(
1654         dbgs() << "LAA: Distance " << Distance
1655                << " that could cause a store-load forwarding conflict\n");
1656     return true;
1657   }
1658 
1659   if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
1660       MaxVFWithoutSLForwardIssues !=
1661           VectorizerParams::MaxVectorWidth * TypeByteSize)
1662     MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
1663   return false;
1664 }
1665 
1666 void MemoryDepChecker::mergeInStatus(VectorizationSafetyStatus S) {
1667   if (Status < S)
1668     Status = S;
1669 }
1670 
1671 /// Given a non-constant (unknown) dependence-distance \p Dist between two
1672 /// memory accesses, that have the same stride whose absolute value is given
1673 /// in \p Stride, and that have the same type size \p TypeByteSize,
1674 /// in a loop whose takenCount is \p BackedgeTakenCount, check if it is
1675 /// possible to prove statically that the dependence distance is larger
1676 /// than the range that the accesses will travel through the execution of
1677 /// the loop. If so, return true; false otherwise. This is useful for
1678 /// example in loops such as the following (PR31098):
1679 ///     for (i = 0; i < D; ++i) {
1680 ///                = out[i];
1681 ///       out[i+D] =
1682 ///     }
1683 static bool isSafeDependenceDistance(const DataLayout &DL, ScalarEvolution &SE,
1684                                      const SCEV &BackedgeTakenCount,
1685                                      const SCEV &Dist, uint64_t Stride,
1686                                      uint64_t TypeByteSize) {
1687 
1688   // If we can prove that
1689   //      (**) |Dist| > BackedgeTakenCount * Step
1690   // where Step is the absolute stride of the memory accesses in bytes,
1691   // then there is no dependence.
1692   //
1693   // Rationale:
1694   // We basically want to check if the absolute distance (|Dist/Step|)
1695   // is >= the loop iteration count (or > BackedgeTakenCount).
1696   // This is equivalent to the Strong SIV Test (Practical Dependence Testing,
1697   // Section 4.2.1); Note, that for vectorization it is sufficient to prove
1698   // that the dependence distance is >= VF; This is checked elsewhere.
1699   // But in some cases we can prune unknown dependence distances early, and
1700   // even before selecting the VF, and without a runtime test, by comparing
1701   // the distance against the loop iteration count. Since the vectorized code
1702   // will be executed only if LoopCount >= VF, proving distance >= LoopCount
1703   // also guarantees that distance >= VF.
1704   //
1705   const uint64_t ByteStride = Stride * TypeByteSize;
1706   const SCEV *Step = SE.getConstant(BackedgeTakenCount.getType(), ByteStride);
1707   const SCEV *Product = SE.getMulExpr(&BackedgeTakenCount, Step);
1708 
1709   const SCEV *CastedDist = &Dist;
1710   const SCEV *CastedProduct = Product;
1711   uint64_t DistTypeSizeBits = DL.getTypeSizeInBits(Dist.getType());
1712   uint64_t ProductTypeSizeBits = DL.getTypeSizeInBits(Product->getType());
1713 
1714   // The dependence distance can be positive/negative, so we sign extend Dist;
1715   // The multiplication of the absolute stride in bytes and the
1716   // backedgeTakenCount is non-negative, so we zero extend Product.
1717   if (DistTypeSizeBits > ProductTypeSizeBits)
1718     CastedProduct = SE.getZeroExtendExpr(Product, Dist.getType());
1719   else
1720     CastedDist = SE.getNoopOrSignExtend(&Dist, Product->getType());
1721 
1722   // Is  Dist - (BackedgeTakenCount * Step) > 0 ?
1723   // (If so, then we have proven (**) because |Dist| >= Dist)
1724   const SCEV *Minus = SE.getMinusSCEV(CastedDist, CastedProduct);
1725   if (SE.isKnownPositive(Minus))
1726     return true;
1727 
1728   // Second try: Is  -Dist - (BackedgeTakenCount * Step) > 0 ?
1729   // (If so, then we have proven (**) because |Dist| >= -1*Dist)
1730   const SCEV *NegDist = SE.getNegativeSCEV(CastedDist);
1731   Minus = SE.getMinusSCEV(NegDist, CastedProduct);
1732   if (SE.isKnownPositive(Minus))
1733     return true;
1734 
1735   return false;
1736 }
1737 
1738 /// Check the dependence for two accesses with the same stride \p Stride.
1739 /// \p Distance is the positive distance and \p TypeByteSize is type size in
1740 /// bytes.
1741 ///
1742 /// \returns true if they are independent.
1743 static bool areStridedAccessesIndependent(uint64_t Distance, uint64_t Stride,
1744                                           uint64_t TypeByteSize) {
1745   assert(Stride > 1 && "The stride must be greater than 1");
1746   assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
1747   assert(Distance > 0 && "The distance must be non-zero");
1748 
1749   // Skip if the distance is not multiple of type byte size.
1750   if (Distance % TypeByteSize)
1751     return false;
1752 
1753   uint64_t ScaledDist = Distance / TypeByteSize;
1754 
1755   // No dependence if the scaled distance is not multiple of the stride.
1756   // E.g.
1757   //      for (i = 0; i < 1024 ; i += 4)
1758   //        A[i+2] = A[i] + 1;
1759   //
1760   // Two accesses in memory (scaled distance is 2, stride is 4):
1761   //     | A[0] |      |      |      | A[4] |      |      |      |
1762   //     |      |      | A[2] |      |      |      | A[6] |      |
1763   //
1764   // E.g.
1765   //      for (i = 0; i < 1024 ; i += 3)
1766   //        A[i+4] = A[i] + 1;
1767   //
1768   // Two accesses in memory (scaled distance is 4, stride is 3):
1769   //     | A[0] |      |      | A[3] |      |      | A[6] |      |      |
1770   //     |      |      |      |      | A[4] |      |      | A[7] |      |
1771   return ScaledDist % Stride;
1772 }
1773 
1774 MemoryDepChecker::Dependence::DepType
1775 MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
1776                               const MemAccessInfo &B, unsigned BIdx,
1777                               const ValueToValueMap &Strides) {
1778   assert (AIdx < BIdx && "Must pass arguments in program order");
1779 
1780   Value *APtr = A.getPointer();
1781   Value *BPtr = B.getPointer();
1782   bool AIsWrite = A.getInt();
1783   bool BIsWrite = B.getInt();
1784   Type *ATy = getLoadStoreType(InstMap[AIdx]);
1785   Type *BTy = getLoadStoreType(InstMap[BIdx]);
1786 
1787   // Two reads are independent.
1788   if (!AIsWrite && !BIsWrite)
1789     return Dependence::NoDep;
1790 
1791   // We cannot check pointers in different address spaces.
1792   if (APtr->getType()->getPointerAddressSpace() !=
1793       BPtr->getType()->getPointerAddressSpace())
1794     return Dependence::Unknown;
1795 
1796   int64_t StrideAPtr =
1797       getPtrStride(PSE, ATy, APtr, InnermostLoop, Strides, true);
1798   int64_t StrideBPtr =
1799       getPtrStride(PSE, BTy, BPtr, InnermostLoop, Strides, true);
1800 
1801   const SCEV *Src = PSE.getSCEV(APtr);
1802   const SCEV *Sink = PSE.getSCEV(BPtr);
1803 
1804   // If the induction step is negative we have to invert source and sink of the
1805   // dependence.
1806   if (StrideAPtr < 0) {
1807     std::swap(APtr, BPtr);
1808     std::swap(ATy, BTy);
1809     std::swap(Src, Sink);
1810     std::swap(AIsWrite, BIsWrite);
1811     std::swap(AIdx, BIdx);
1812     std::swap(StrideAPtr, StrideBPtr);
1813   }
1814 
1815   const SCEV *Dist = PSE.getSE()->getMinusSCEV(Sink, Src);
1816 
1817   LLVM_DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
1818                     << "(Induction step: " << StrideAPtr << ")\n");
1819   LLVM_DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
1820                     << *InstMap[BIdx] << ": " << *Dist << "\n");
1821 
1822   // Need accesses with constant stride. We don't want to vectorize
1823   // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
1824   // the address space.
1825   if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
1826     LLVM_DEBUG(dbgs() << "Pointer access with non-constant stride\n");
1827     return Dependence::Unknown;
1828   }
1829 
1830   auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
1831   uint64_t TypeByteSize = DL.getTypeAllocSize(ATy);
1832   bool HasSameSize =
1833       DL.getTypeStoreSizeInBits(ATy) == DL.getTypeStoreSizeInBits(BTy);
1834   uint64_t Stride = std::abs(StrideAPtr);
1835   const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
1836   if (!C) {
1837     if (!isa<SCEVCouldNotCompute>(Dist) && HasSameSize &&
1838         isSafeDependenceDistance(DL, *(PSE.getSE()),
1839                                  *(PSE.getBackedgeTakenCount()), *Dist, Stride,
1840                                  TypeByteSize))
1841       return Dependence::NoDep;
1842 
1843     LLVM_DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
1844     FoundNonConstantDistanceDependence = true;
1845     return Dependence::Unknown;
1846   }
1847 
1848   const APInt &Val = C->getAPInt();
1849   int64_t Distance = Val.getSExtValue();
1850 
1851   // Attempt to prove strided accesses independent.
1852   if (std::abs(Distance) > 0 && Stride > 1 && HasSameSize &&
1853       areStridedAccessesIndependent(std::abs(Distance), Stride, TypeByteSize)) {
1854     LLVM_DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
1855     return Dependence::NoDep;
1856   }
1857 
1858   // Negative distances are not plausible dependencies.
1859   if (Val.isNegative()) {
1860     bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
1861     if (IsTrueDataDependence && EnableForwardingConflictDetection &&
1862         (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
1863          !HasSameSize)) {
1864       LLVM_DEBUG(dbgs() << "LAA: Forward but may prevent st->ld forwarding\n");
1865       return Dependence::ForwardButPreventsForwarding;
1866     }
1867 
1868     LLVM_DEBUG(dbgs() << "LAA: Dependence is negative\n");
1869     return Dependence::Forward;
1870   }
1871 
1872   // Write to the same location with the same size.
1873   if (Val == 0) {
1874     if (HasSameSize)
1875       return Dependence::Forward;
1876     LLVM_DEBUG(
1877         dbgs() << "LAA: Zero dependence difference but different type sizes\n");
1878     return Dependence::Unknown;
1879   }
1880 
1881   assert(Val.isStrictlyPositive() && "Expect a positive value");
1882 
1883   if (!HasSameSize) {
1884     LLVM_DEBUG(dbgs() << "LAA: ReadWrite-Write positive dependency with "
1885                          "different type sizes\n");
1886     return Dependence::Unknown;
1887   }
1888 
1889   // Bail out early if passed-in parameters make vectorization not feasible.
1890   unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
1891                            VectorizerParams::VectorizationFactor : 1);
1892   unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
1893                            VectorizerParams::VectorizationInterleave : 1);
1894   // The minimum number of iterations for a vectorized/unrolled version.
1895   unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
1896 
1897   // It's not vectorizable if the distance is smaller than the minimum distance
1898   // needed for a vectroized/unrolled version. Vectorizing one iteration in
1899   // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
1900   // TypeByteSize (No need to plus the last gap distance).
1901   //
1902   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1903   //      foo(int *A) {
1904   //        int *B = (int *)((char *)A + 14);
1905   //        for (i = 0 ; i < 1024 ; i += 2)
1906   //          B[i] = A[i] + 1;
1907   //      }
1908   //
1909   // Two accesses in memory (stride is 2):
1910   //     | A[0] |      | A[2] |      | A[4] |      | A[6] |      |
1911   //                              | B[0] |      | B[2] |      | B[4] |
1912   //
1913   // Distance needs for vectorizing iterations except the last iteration:
1914   // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
1915   // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
1916   //
1917   // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
1918   // 12, which is less than distance.
1919   //
1920   // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
1921   // the minimum distance needed is 28, which is greater than distance. It is
1922   // not safe to do vectorization.
1923   uint64_t MinDistanceNeeded =
1924       TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
1925   if (MinDistanceNeeded > static_cast<uint64_t>(Distance)) {
1926     LLVM_DEBUG(dbgs() << "LAA: Failure because of positive distance "
1927                       << Distance << '\n');
1928     return Dependence::Backward;
1929   }
1930 
1931   // Unsafe if the minimum distance needed is greater than max safe distance.
1932   if (MinDistanceNeeded > MaxSafeDepDistBytes) {
1933     LLVM_DEBUG(dbgs() << "LAA: Failure because it needs at least "
1934                       << MinDistanceNeeded << " size in bytes");
1935     return Dependence::Backward;
1936   }
1937 
1938   // Positive distance bigger than max vectorization factor.
1939   // FIXME: Should use max factor instead of max distance in bytes, which could
1940   // not handle different types.
1941   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1942   //      void foo (int *A, char *B) {
1943   //        for (unsigned i = 0; i < 1024; i++) {
1944   //          A[i+2] = A[i] + 1;
1945   //          B[i+2] = B[i] + 1;
1946   //        }
1947   //      }
1948   //
1949   // This case is currently unsafe according to the max safe distance. If we
1950   // analyze the two accesses on array B, the max safe dependence distance
1951   // is 2. Then we analyze the accesses on array A, the minimum distance needed
1952   // is 8, which is less than 2 and forbidden vectorization, But actually
1953   // both A and B could be vectorized by 2 iterations.
1954   MaxSafeDepDistBytes =
1955       std::min(static_cast<uint64_t>(Distance), MaxSafeDepDistBytes);
1956 
1957   bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
1958   if (IsTrueDataDependence && EnableForwardingConflictDetection &&
1959       couldPreventStoreLoadForward(Distance, TypeByteSize))
1960     return Dependence::BackwardVectorizableButPreventsForwarding;
1961 
1962   uint64_t MaxVF = MaxSafeDepDistBytes / (TypeByteSize * Stride);
1963   LLVM_DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
1964                     << " with max VF = " << MaxVF << '\n');
1965   uint64_t MaxVFInBits = MaxVF * TypeByteSize * 8;
1966   MaxSafeVectorWidthInBits = std::min(MaxSafeVectorWidthInBits, MaxVFInBits);
1967   return Dependence::BackwardVectorizable;
1968 }
1969 
1970 bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
1971                                    MemAccessInfoList &CheckDeps,
1972                                    const ValueToValueMap &Strides) {
1973 
1974   MaxSafeDepDistBytes = -1;
1975   SmallPtrSet<MemAccessInfo, 8> Visited;
1976   for (MemAccessInfo CurAccess : CheckDeps) {
1977     if (Visited.count(CurAccess))
1978       continue;
1979 
1980     // Get the relevant memory access set.
1981     EquivalenceClasses<MemAccessInfo>::iterator I =
1982       AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
1983 
1984     // Check accesses within this set.
1985     EquivalenceClasses<MemAccessInfo>::member_iterator AI =
1986         AccessSets.member_begin(I);
1987     EquivalenceClasses<MemAccessInfo>::member_iterator AE =
1988         AccessSets.member_end();
1989 
1990     // Check every access pair.
1991     while (AI != AE) {
1992       Visited.insert(*AI);
1993       bool AIIsWrite = AI->getInt();
1994       // Check loads only against next equivalent class, but stores also against
1995       // other stores in the same equivalence class - to the same address.
1996       EquivalenceClasses<MemAccessInfo>::member_iterator OI =
1997           (AIIsWrite ? AI : std::next(AI));
1998       while (OI != AE) {
1999         // Check every accessing instruction pair in program order.
2000         for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
2001              I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
2002           // Scan all accesses of another equivalence class, but only the next
2003           // accesses of the same equivalent class.
2004           for (std::vector<unsigned>::iterator
2005                    I2 = (OI == AI ? std::next(I1) : Accesses[*OI].begin()),
2006                    I2E = (OI == AI ? I1E : Accesses[*OI].end());
2007                I2 != I2E; ++I2) {
2008             auto A = std::make_pair(&*AI, *I1);
2009             auto B = std::make_pair(&*OI, *I2);
2010 
2011             assert(*I1 != *I2);
2012             if (*I1 > *I2)
2013               std::swap(A, B);
2014 
2015             Dependence::DepType Type =
2016                 isDependent(*A.first, A.second, *B.first, B.second, Strides);
2017             mergeInStatus(Dependence::isSafeForVectorization(Type));
2018 
2019             // Gather dependences unless we accumulated MaxDependences
2020             // dependences.  In that case return as soon as we find the first
2021             // unsafe dependence.  This puts a limit on this quadratic
2022             // algorithm.
2023             if (RecordDependences) {
2024               if (Type != Dependence::NoDep)
2025                 Dependences.push_back(Dependence(A.second, B.second, Type));
2026 
2027               if (Dependences.size() >= MaxDependences) {
2028                 RecordDependences = false;
2029                 Dependences.clear();
2030                 LLVM_DEBUG(dbgs()
2031                            << "Too many dependences, stopped recording\n");
2032               }
2033             }
2034             if (!RecordDependences && !isSafeForVectorization())
2035               return false;
2036           }
2037         ++OI;
2038       }
2039       AI++;
2040     }
2041   }
2042 
2043   LLVM_DEBUG(dbgs() << "Total Dependences: " << Dependences.size() << "\n");
2044   return isSafeForVectorization();
2045 }
2046 
2047 SmallVector<Instruction *, 4>
2048 MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
2049   MemAccessInfo Access(Ptr, isWrite);
2050   auto &IndexVector = Accesses.find(Access)->second;
2051 
2052   SmallVector<Instruction *, 4> Insts;
2053   transform(IndexVector,
2054                  std::back_inserter(Insts),
2055                  [&](unsigned Idx) { return this->InstMap[Idx]; });
2056   return Insts;
2057 }
2058 
2059 const char *MemoryDepChecker::Dependence::DepName[] = {
2060     "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
2061     "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
2062 
2063 void MemoryDepChecker::Dependence::print(
2064     raw_ostream &OS, unsigned Depth,
2065     const SmallVectorImpl<Instruction *> &Instrs) const {
2066   OS.indent(Depth) << DepName[Type] << ":\n";
2067   OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
2068   OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
2069 }
2070 
2071 bool LoopAccessInfo::canAnalyzeLoop() {
2072   // We need to have a loop header.
2073   LLVM_DEBUG(dbgs() << "LAA: Found a loop in "
2074                     << TheLoop->getHeader()->getParent()->getName() << ": "
2075                     << TheLoop->getHeader()->getName() << '\n');
2076 
2077   // We can only analyze innermost loops.
2078   if (!TheLoop->isInnermost()) {
2079     LLVM_DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
2080     recordAnalysis("NotInnerMostLoop") << "loop is not the innermost loop";
2081     return false;
2082   }
2083 
2084   // We must have a single backedge.
2085   if (TheLoop->getNumBackEdges() != 1) {
2086     LLVM_DEBUG(
2087         dbgs() << "LAA: loop control flow is not understood by analyzer\n");
2088     recordAnalysis("CFGNotUnderstood")
2089         << "loop control flow is not understood by analyzer";
2090     return false;
2091   }
2092 
2093   // ScalarEvolution needs to be able to find the exit count.
2094   const SCEV *ExitCount = PSE->getBackedgeTakenCount();
2095   if (isa<SCEVCouldNotCompute>(ExitCount)) {
2096     recordAnalysis("CantComputeNumberOfIterations")
2097         << "could not determine number of loop iterations";
2098     LLVM_DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
2099     return false;
2100   }
2101 
2102   return true;
2103 }
2104 
2105 void LoopAccessInfo::analyzeLoop(AAResults *AA, LoopInfo *LI,
2106                                  const TargetLibraryInfo *TLI,
2107                                  DominatorTree *DT) {
2108   // Holds the Load and Store instructions.
2109   SmallVector<LoadInst *, 16> Loads;
2110   SmallVector<StoreInst *, 16> Stores;
2111 
2112   // Holds all the different accesses in the loop.
2113   unsigned NumReads = 0;
2114   unsigned NumReadWrites = 0;
2115 
2116   bool HasComplexMemInst = false;
2117 
2118   // A runtime check is only legal to insert if there are no convergent calls.
2119   HasConvergentOp = false;
2120 
2121   PtrRtChecking->Pointers.clear();
2122   PtrRtChecking->Need = false;
2123 
2124   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
2125 
2126   const bool EnableMemAccessVersioningOfLoop =
2127       EnableMemAccessVersioning &&
2128       !TheLoop->getHeader()->getParent()->hasOptSize();
2129 
2130   // For each block.
2131   for (BasicBlock *BB : TheLoop->blocks()) {
2132     // Scan the BB and collect legal loads and stores. Also detect any
2133     // convergent instructions.
2134     for (Instruction &I : *BB) {
2135       if (auto *Call = dyn_cast<CallBase>(&I)) {
2136         if (Call->isConvergent())
2137           HasConvergentOp = true;
2138       }
2139 
2140       // With both a non-vectorizable memory instruction and a convergent
2141       // operation, found in this loop, no reason to continue the search.
2142       if (HasComplexMemInst && HasConvergentOp) {
2143         CanVecMem = false;
2144         return;
2145       }
2146 
2147       // Avoid hitting recordAnalysis multiple times.
2148       if (HasComplexMemInst)
2149         continue;
2150 
2151       // If this is a load, save it. If this instruction can read from memory
2152       // but is not a load, then we quit. Notice that we don't handle function
2153       // calls that read or write.
2154       if (I.mayReadFromMemory()) {
2155         // Many math library functions read the rounding mode. We will only
2156         // vectorize a loop if it contains known function calls that don't set
2157         // the flag. Therefore, it is safe to ignore this read from memory.
2158         auto *Call = dyn_cast<CallInst>(&I);
2159         if (Call && getVectorIntrinsicIDForCall(Call, TLI))
2160           continue;
2161 
2162         // If the function has an explicit vectorized counterpart, we can safely
2163         // assume that it can be vectorized.
2164         if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
2165             !VFDatabase::getMappings(*Call).empty())
2166           continue;
2167 
2168         auto *Ld = dyn_cast<LoadInst>(&I);
2169         if (!Ld) {
2170           recordAnalysis("CantVectorizeInstruction", Ld)
2171             << "instruction cannot be vectorized";
2172           HasComplexMemInst = true;
2173           continue;
2174         }
2175         if (!Ld->isSimple() && !IsAnnotatedParallel) {
2176           recordAnalysis("NonSimpleLoad", Ld)
2177               << "read with atomic ordering or volatile read";
2178           LLVM_DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
2179           HasComplexMemInst = true;
2180           continue;
2181         }
2182         NumLoads++;
2183         Loads.push_back(Ld);
2184         DepChecker->addAccess(Ld);
2185         if (EnableMemAccessVersioningOfLoop)
2186           collectStridedAccess(Ld);
2187         continue;
2188       }
2189 
2190       // Save 'store' instructions. Abort if other instructions write to memory.
2191       if (I.mayWriteToMemory()) {
2192         auto *St = dyn_cast<StoreInst>(&I);
2193         if (!St) {
2194           recordAnalysis("CantVectorizeInstruction", St)
2195               << "instruction cannot be vectorized";
2196           HasComplexMemInst = true;
2197           continue;
2198         }
2199         if (!St->isSimple() && !IsAnnotatedParallel) {
2200           recordAnalysis("NonSimpleStore", St)
2201               << "write with atomic ordering or volatile write";
2202           LLVM_DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
2203           HasComplexMemInst = true;
2204           continue;
2205         }
2206         NumStores++;
2207         Stores.push_back(St);
2208         DepChecker->addAccess(St);
2209         if (EnableMemAccessVersioningOfLoop)
2210           collectStridedAccess(St);
2211       }
2212     } // Next instr.
2213   } // Next block.
2214 
2215   if (HasComplexMemInst) {
2216     CanVecMem = false;
2217     return;
2218   }
2219 
2220   // Now we have two lists that hold the loads and the stores.
2221   // Next, we find the pointers that they use.
2222 
2223   // Check if we see any stores. If there are no stores, then we don't
2224   // care if the pointers are *restrict*.
2225   if (!Stores.size()) {
2226     LLVM_DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
2227     CanVecMem = true;
2228     return;
2229   }
2230 
2231   MemoryDepChecker::DepCandidates DependentAccesses;
2232   AccessAnalysis Accesses(TheLoop, AA, LI, DependentAccesses, *PSE);
2233 
2234   // Holds the analyzed pointers. We don't want to call getUnderlyingObjects
2235   // multiple times on the same object. If the ptr is accessed twice, once
2236   // for read and once for write, it will only appear once (on the write
2237   // list). This is okay, since we are going to check for conflicts between
2238   // writes and between reads and writes, but not between reads and reads.
2239   SmallSet<std::pair<Value *, Type *>, 16> Seen;
2240 
2241   // Record uniform store addresses to identify if we have multiple stores
2242   // to the same address.
2243   SmallPtrSet<Value *, 16> UniformStores;
2244 
2245   for (StoreInst *ST : Stores) {
2246     Value *Ptr = ST->getPointerOperand();
2247 
2248     if (isUniform(Ptr)) {
2249       // Record store instructions to loop invariant addresses
2250       StoresToInvariantAddresses.push_back(ST);
2251       HasDependenceInvolvingLoopInvariantAddress |=
2252           !UniformStores.insert(Ptr).second;
2253     }
2254 
2255     // If we did *not* see this pointer before, insert it to  the read-write
2256     // list. At this phase it is only a 'write' list.
2257     Type *AccessTy = getLoadStoreType(ST);
2258     if (Seen.insert({Ptr, AccessTy}).second) {
2259       ++NumReadWrites;
2260 
2261       MemoryLocation Loc = MemoryLocation::get(ST);
2262       // The TBAA metadata could have a control dependency on the predication
2263       // condition, so we cannot rely on it when determining whether or not we
2264       // need runtime pointer checks.
2265       if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
2266         Loc.AATags.TBAA = nullptr;
2267 
2268       visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop,
2269                     [&Accesses, AccessTy, Loc](Value *Ptr) {
2270                       MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr);
2271                       Accesses.addStore(NewLoc, AccessTy);
2272                     });
2273     }
2274   }
2275 
2276   if (IsAnnotatedParallel) {
2277     LLVM_DEBUG(
2278         dbgs() << "LAA: A loop annotated parallel, ignore memory dependency "
2279                << "checks.\n");
2280     CanVecMem = true;
2281     return;
2282   }
2283 
2284   for (LoadInst *LD : Loads) {
2285     Value *Ptr = LD->getPointerOperand();
2286     // If we did *not* see this pointer before, insert it to the
2287     // read list. If we *did* see it before, then it is already in
2288     // the read-write list. This allows us to vectorize expressions
2289     // such as A[i] += x;  Because the address of A[i] is a read-write
2290     // pointer. This only works if the index of A[i] is consecutive.
2291     // If the address of i is unknown (for example A[B[i]]) then we may
2292     // read a few words, modify, and write a few words, and some of the
2293     // words may be written to the same address.
2294     bool IsReadOnlyPtr = false;
2295     Type *AccessTy = getLoadStoreType(LD);
2296     if (Seen.insert({Ptr, AccessTy}).second ||
2297         !getPtrStride(*PSE, LD->getType(), Ptr, TheLoop, SymbolicStrides)) {
2298       ++NumReads;
2299       IsReadOnlyPtr = true;
2300     }
2301 
2302     // See if there is an unsafe dependency between a load to a uniform address and
2303     // store to the same uniform address.
2304     if (UniformStores.count(Ptr)) {
2305       LLVM_DEBUG(dbgs() << "LAA: Found an unsafe dependency between a uniform "
2306                            "load and uniform store to the same address!\n");
2307       HasDependenceInvolvingLoopInvariantAddress = true;
2308     }
2309 
2310     MemoryLocation Loc = MemoryLocation::get(LD);
2311     // The TBAA metadata could have a control dependency on the predication
2312     // condition, so we cannot rely on it when determining whether or not we
2313     // need runtime pointer checks.
2314     if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
2315       Loc.AATags.TBAA = nullptr;
2316 
2317     visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop,
2318                   [&Accesses, AccessTy, Loc, IsReadOnlyPtr](Value *Ptr) {
2319                     MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr);
2320                     Accesses.addLoad(NewLoc, AccessTy, IsReadOnlyPtr);
2321                   });
2322   }
2323 
2324   // If we write (or read-write) to a single destination and there are no
2325   // other reads in this loop then is it safe to vectorize.
2326   if (NumReadWrites == 1 && NumReads == 0) {
2327     LLVM_DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
2328     CanVecMem = true;
2329     return;
2330   }
2331 
2332   // Build dependence sets and check whether we need a runtime pointer bounds
2333   // check.
2334   Accesses.buildDependenceSets();
2335 
2336   // Find pointers with computable bounds. We are going to use this information
2337   // to place a runtime bound check.
2338   Value *UncomputablePtr = nullptr;
2339   bool CanDoRTIfNeeded =
2340       Accesses.canCheckPtrAtRT(*PtrRtChecking, PSE->getSE(), TheLoop,
2341                                SymbolicStrides, UncomputablePtr, false);
2342   if (!CanDoRTIfNeeded) {
2343     auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr);
2344     recordAnalysis("CantIdentifyArrayBounds", I)
2345         << "cannot identify array bounds";
2346     LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
2347                       << "the array bounds.\n");
2348     CanVecMem = false;
2349     return;
2350   }
2351 
2352   LLVM_DEBUG(
2353     dbgs() << "LAA: May be able to perform a memory runtime check if needed.\n");
2354 
2355   CanVecMem = true;
2356   if (Accesses.isDependencyCheckNeeded()) {
2357     LLVM_DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
2358     CanVecMem = DepChecker->areDepsSafe(
2359         DependentAccesses, Accesses.getDependenciesToCheck(), SymbolicStrides);
2360     MaxSafeDepDistBytes = DepChecker->getMaxSafeDepDistBytes();
2361 
2362     if (!CanVecMem && DepChecker->shouldRetryWithRuntimeCheck()) {
2363       LLVM_DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
2364 
2365       // Clear the dependency checks. We assume they are not needed.
2366       Accesses.resetDepChecks(*DepChecker);
2367 
2368       PtrRtChecking->reset();
2369       PtrRtChecking->Need = true;
2370 
2371       auto *SE = PSE->getSE();
2372       UncomputablePtr = nullptr;
2373       CanDoRTIfNeeded = Accesses.canCheckPtrAtRT(
2374           *PtrRtChecking, SE, TheLoop, SymbolicStrides, UncomputablePtr, true);
2375 
2376       // Check that we found the bounds for the pointer.
2377       if (!CanDoRTIfNeeded) {
2378         auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr);
2379         recordAnalysis("CantCheckMemDepsAtRunTime", I)
2380             << "cannot check memory dependencies at runtime";
2381         LLVM_DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
2382         CanVecMem = false;
2383         return;
2384       }
2385 
2386       CanVecMem = true;
2387     }
2388   }
2389 
2390   if (HasConvergentOp) {
2391     recordAnalysis("CantInsertRuntimeCheckWithConvergent")
2392       << "cannot add control dependency to convergent operation";
2393     LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because a runtime check "
2394                          "would be needed with a convergent operation\n");
2395     CanVecMem = false;
2396     return;
2397   }
2398 
2399   if (CanVecMem)
2400     LLVM_DEBUG(
2401         dbgs() << "LAA: No unsafe dependent memory operations in loop.  We"
2402                << (PtrRtChecking->Need ? "" : " don't")
2403                << " need runtime memory checks.\n");
2404   else
2405     emitUnsafeDependenceRemark();
2406 }
2407 
2408 void LoopAccessInfo::emitUnsafeDependenceRemark() {
2409   auto Deps = getDepChecker().getDependences();
2410   if (!Deps)
2411     return;
2412   auto Found = std::find_if(
2413       Deps->begin(), Deps->end(), [](const MemoryDepChecker::Dependence &D) {
2414         return MemoryDepChecker::Dependence::isSafeForVectorization(D.Type) !=
2415                MemoryDepChecker::VectorizationSafetyStatus::Safe;
2416       });
2417   if (Found == Deps->end())
2418     return;
2419   MemoryDepChecker::Dependence Dep = *Found;
2420 
2421   LLVM_DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
2422 
2423   // Emit remark for first unsafe dependence
2424   OptimizationRemarkAnalysis &R =
2425       recordAnalysis("UnsafeDep", Dep.getDestination(*this))
2426       << "unsafe dependent memory operations in loop. Use "
2427          "#pragma loop distribute(enable) to allow loop distribution "
2428          "to attempt to isolate the offending operations into a separate "
2429          "loop";
2430 
2431   switch (Dep.Type) {
2432   case MemoryDepChecker::Dependence::NoDep:
2433   case MemoryDepChecker::Dependence::Forward:
2434   case MemoryDepChecker::Dependence::BackwardVectorizable:
2435     llvm_unreachable("Unexpected dependence");
2436   case MemoryDepChecker::Dependence::Backward:
2437     R << "\nBackward loop carried data dependence.";
2438     break;
2439   case MemoryDepChecker::Dependence::ForwardButPreventsForwarding:
2440     R << "\nForward loop carried data dependence that prevents "
2441          "store-to-load forwarding.";
2442     break;
2443   case MemoryDepChecker::Dependence::BackwardVectorizableButPreventsForwarding:
2444     R << "\nBackward loop carried data dependence that prevents "
2445          "store-to-load forwarding.";
2446     break;
2447   case MemoryDepChecker::Dependence::Unknown:
2448     R << "\nUnknown data dependence.";
2449     break;
2450   }
2451 
2452   if (Instruction *I = Dep.getSource(*this)) {
2453     DebugLoc SourceLoc = I->getDebugLoc();
2454     if (auto *DD = dyn_cast_or_null<Instruction>(getPointerOperand(I)))
2455       SourceLoc = DD->getDebugLoc();
2456     if (SourceLoc)
2457       R << " Memory location is the same as accessed at "
2458         << ore::NV("Location", SourceLoc);
2459   }
2460 }
2461 
2462 bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
2463                                            DominatorTree *DT)  {
2464   assert(TheLoop->contains(BB) && "Unknown block used");
2465 
2466   // Blocks that do not dominate the latch need predication.
2467   BasicBlock* Latch = TheLoop->getLoopLatch();
2468   return !DT->dominates(BB, Latch);
2469 }
2470 
2471 OptimizationRemarkAnalysis &LoopAccessInfo::recordAnalysis(StringRef RemarkName,
2472                                                            Instruction *I) {
2473   assert(!Report && "Multiple reports generated");
2474 
2475   Value *CodeRegion = TheLoop->getHeader();
2476   DebugLoc DL = TheLoop->getStartLoc();
2477 
2478   if (I) {
2479     CodeRegion = I->getParent();
2480     // If there is no debug location attached to the instruction, revert back to
2481     // using the loop's.
2482     if (I->getDebugLoc())
2483       DL = I->getDebugLoc();
2484   }
2485 
2486   Report = std::make_unique<OptimizationRemarkAnalysis>(DEBUG_TYPE, RemarkName, DL,
2487                                                    CodeRegion);
2488   return *Report;
2489 }
2490 
2491 bool LoopAccessInfo::isUniform(Value *V) const {
2492   auto *SE = PSE->getSE();
2493   // Since we rely on SCEV for uniformity, if the type is not SCEVable, it is
2494   // never considered uniform.
2495   // TODO: Is this really what we want? Even without FP SCEV, we may want some
2496   // trivially loop-invariant FP values to be considered uniform.
2497   if (!SE->isSCEVable(V->getType()))
2498     return false;
2499   return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
2500 }
2501 
2502 void LoopAccessInfo::collectStridedAccess(Value *MemAccess) {
2503   Value *Ptr = getLoadStorePointerOperand(MemAccess);
2504   if (!Ptr)
2505     return;
2506 
2507   Value *Stride = getStrideFromPointer(Ptr, PSE->getSE(), TheLoop);
2508   if (!Stride)
2509     return;
2510 
2511   LLVM_DEBUG(dbgs() << "LAA: Found a strided access that is a candidate for "
2512                        "versioning:");
2513   LLVM_DEBUG(dbgs() << "  Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
2514 
2515   // Avoid adding the "Stride == 1" predicate when we know that
2516   // Stride >= Trip-Count. Such a predicate will effectively optimize a single
2517   // or zero iteration loop, as Trip-Count <= Stride == 1.
2518   //
2519   // TODO: We are currently not making a very informed decision on when it is
2520   // beneficial to apply stride versioning. It might make more sense that the
2521   // users of this analysis (such as the vectorizer) will trigger it, based on
2522   // their specific cost considerations; For example, in cases where stride
2523   // versioning does  not help resolving memory accesses/dependences, the
2524   // vectorizer should evaluate the cost of the runtime test, and the benefit
2525   // of various possible stride specializations, considering the alternatives
2526   // of using gather/scatters (if available).
2527 
2528   const SCEV *StrideExpr = PSE->getSCEV(Stride);
2529   const SCEV *BETakenCount = PSE->getBackedgeTakenCount();
2530 
2531   // Match the types so we can compare the stride and the BETakenCount.
2532   // The Stride can be positive/negative, so we sign extend Stride;
2533   // The backedgeTakenCount is non-negative, so we zero extend BETakenCount.
2534   const DataLayout &DL = TheLoop->getHeader()->getModule()->getDataLayout();
2535   uint64_t StrideTypeSizeBits = DL.getTypeSizeInBits(StrideExpr->getType());
2536   uint64_t BETypeSizeBits = DL.getTypeSizeInBits(BETakenCount->getType());
2537   const SCEV *CastedStride = StrideExpr;
2538   const SCEV *CastedBECount = BETakenCount;
2539   ScalarEvolution *SE = PSE->getSE();
2540   if (BETypeSizeBits >= StrideTypeSizeBits)
2541     CastedStride = SE->getNoopOrSignExtend(StrideExpr, BETakenCount->getType());
2542   else
2543     CastedBECount = SE->getZeroExtendExpr(BETakenCount, StrideExpr->getType());
2544   const SCEV *StrideMinusBETaken = SE->getMinusSCEV(CastedStride, CastedBECount);
2545   // Since TripCount == BackEdgeTakenCount + 1, checking:
2546   // "Stride >= TripCount" is equivalent to checking:
2547   // Stride - BETakenCount > 0
2548   if (SE->isKnownPositive(StrideMinusBETaken)) {
2549     LLVM_DEBUG(
2550         dbgs() << "LAA: Stride>=TripCount; No point in versioning as the "
2551                   "Stride==1 predicate will imply that the loop executes "
2552                   "at most once.\n");
2553     return;
2554   }
2555   LLVM_DEBUG(dbgs() << "LAA: Found a strided access that we can version.\n");
2556 
2557   SymbolicStrides[Ptr] = Stride;
2558   StrideSet.insert(Stride);
2559 }
2560 
2561 LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
2562                                const TargetLibraryInfo *TLI, AAResults *AA,
2563                                DominatorTree *DT, LoopInfo *LI)
2564     : PSE(std::make_unique<PredicatedScalarEvolution>(*SE, *L)),
2565       PtrRtChecking(nullptr),
2566       DepChecker(std::make_unique<MemoryDepChecker>(*PSE, L)), TheLoop(L) {
2567   PtrRtChecking = std::make_unique<RuntimePointerChecking>(*DepChecker, SE);
2568   if (canAnalyzeLoop()) {
2569     analyzeLoop(AA, LI, TLI, DT);
2570   }
2571 }
2572 
2573 void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
2574   if (CanVecMem) {
2575     OS.indent(Depth) << "Memory dependences are safe";
2576     if (MaxSafeDepDistBytes != -1ULL)
2577       OS << " with a maximum dependence distance of " << MaxSafeDepDistBytes
2578          << " bytes";
2579     if (PtrRtChecking->Need)
2580       OS << " with run-time checks";
2581     OS << "\n";
2582   }
2583 
2584   if (HasConvergentOp)
2585     OS.indent(Depth) << "Has convergent operation in loop\n";
2586 
2587   if (Report)
2588     OS.indent(Depth) << "Report: " << Report->getMsg() << "\n";
2589 
2590   if (auto *Dependences = DepChecker->getDependences()) {
2591     OS.indent(Depth) << "Dependences:\n";
2592     for (const auto &Dep : *Dependences) {
2593       Dep.print(OS, Depth + 2, DepChecker->getMemoryInstructions());
2594       OS << "\n";
2595     }
2596   } else
2597     OS.indent(Depth) << "Too many dependences, not recorded\n";
2598 
2599   // List the pair of accesses need run-time checks to prove independence.
2600   PtrRtChecking->print(OS, Depth);
2601   OS << "\n";
2602 
2603   OS.indent(Depth) << "Non vectorizable stores to invariant address were "
2604                    << (HasDependenceInvolvingLoopInvariantAddress ? "" : "not ")
2605                    << "found in loop.\n";
2606 
2607   OS.indent(Depth) << "SCEV assumptions:\n";
2608   PSE->getPredicate().print(OS, Depth);
2609 
2610   OS << "\n";
2611 
2612   OS.indent(Depth) << "Expressions re-written:\n";
2613   PSE->print(OS, Depth);
2614 }
2615 
2616 LoopAccessLegacyAnalysis::LoopAccessLegacyAnalysis() : FunctionPass(ID) {
2617   initializeLoopAccessLegacyAnalysisPass(*PassRegistry::getPassRegistry());
2618 }
2619 
2620 const LoopAccessInfo &LoopAccessLegacyAnalysis::getInfo(Loop *L) {
2621   auto &LAI = LoopAccessInfoMap[L];
2622 
2623   if (!LAI)
2624     LAI = std::make_unique<LoopAccessInfo>(L, SE, TLI, AA, DT, LI);
2625 
2626   return *LAI;
2627 }
2628 
2629 void LoopAccessLegacyAnalysis::print(raw_ostream &OS, const Module *M) const {
2630   LoopAccessLegacyAnalysis &LAA = *const_cast<LoopAccessLegacyAnalysis *>(this);
2631 
2632   for (Loop *TopLevelLoop : *LI)
2633     for (Loop *L : depth_first(TopLevelLoop)) {
2634       OS.indent(2) << L->getHeader()->getName() << ":\n";
2635       auto &LAI = LAA.getInfo(L);
2636       LAI.print(OS, 4);
2637     }
2638 }
2639 
2640 bool LoopAccessLegacyAnalysis::runOnFunction(Function &F) {
2641   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2642   auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2643   TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
2644   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2645   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2646   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2647 
2648   return false;
2649 }
2650 
2651 void LoopAccessLegacyAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
2652   AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
2653   AU.addRequiredTransitive<AAResultsWrapperPass>();
2654   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
2655   AU.addRequiredTransitive<LoopInfoWrapperPass>();
2656 
2657   AU.setPreservesAll();
2658 }
2659 
2660 char LoopAccessLegacyAnalysis::ID = 0;
2661 static const char laa_name[] = "Loop Access Analysis";
2662 #define LAA_NAME "loop-accesses"
2663 
2664 INITIALIZE_PASS_BEGIN(LoopAccessLegacyAnalysis, LAA_NAME, laa_name, false, true)
2665 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2666 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
2667 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2668 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
2669 INITIALIZE_PASS_END(LoopAccessLegacyAnalysis, LAA_NAME, laa_name, false, true)
2670 
2671 AnalysisKey LoopAccessAnalysis::Key;
2672 
2673 LoopAccessInfo LoopAccessAnalysis::run(Loop &L, LoopAnalysisManager &AM,
2674                                        LoopStandardAnalysisResults &AR) {
2675   return LoopAccessInfo(&L, &AR.SE, &AR.TLI, &AR.AA, &AR.DT, &AR.LI);
2676 }
2677 
2678 namespace llvm {
2679 
2680   Pass *createLAAPass() {
2681     return new LoopAccessLegacyAnalysis();
2682   }
2683 
2684 } // end namespace llvm
2685