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