[LAA] Add missing debug output after r239285
[oota-llvm.git] / lib / Analysis / LoopAccessAnalysis.cpp
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/ScalarEvolutionExpander.h"
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 #include "llvm/Analysis/ValueTracking.h"
20 #include "llvm/IR/DiagnosticInfo.h"
21 #include "llvm/IR/Dominators.h"
22 #include "llvm/IR/IRBuilder.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Analysis/VectorUtils.h"
26 using namespace llvm;
27
28 #define DEBUG_TYPE "loop-accesses"
29
30 static cl::opt<unsigned, true>
31 VectorizationFactor("force-vector-width", cl::Hidden,
32                     cl::desc("Sets the SIMD width. Zero is autoselect."),
33                     cl::location(VectorizerParams::VectorizationFactor));
34 unsigned VectorizerParams::VectorizationFactor;
35
36 static cl::opt<unsigned, true>
37 VectorizationInterleave("force-vector-interleave", cl::Hidden,
38                         cl::desc("Sets the vectorization interleave count. "
39                                  "Zero is autoselect."),
40                         cl::location(
41                             VectorizerParams::VectorizationInterleave));
42 unsigned VectorizerParams::VectorizationInterleave;
43
44 static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
45     "runtime-memory-check-threshold", cl::Hidden,
46     cl::desc("When performing memory disambiguation checks at runtime do not "
47              "generate more than this number of comparisons (default = 8)."),
48     cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
49 unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
50
51 /// \brief The maximum iterations used to merge memory checks
52 static cl::opt<unsigned> MemoryCheckMergeThreshold(
53     "memory-check-merge-threshold", cl::Hidden,
54     cl::desc("Maximum number of comparisons done when trying to merge "
55              "runtime memory checks. (default = 100)"),
56     cl::init(100));
57
58 /// Maximum SIMD width.
59 const unsigned VectorizerParams::MaxVectorWidth = 64;
60
61 /// \brief We collect interesting dependences up to this threshold.
62 static cl::opt<unsigned> MaxInterestingDependence(
63     "max-interesting-dependences", cl::Hidden,
64     cl::desc("Maximum number of interesting dependences collected by "
65              "loop-access analysis (default = 100)"),
66     cl::init(100));
67
68 bool VectorizerParams::isInterleaveForced() {
69   return ::VectorizationInterleave.getNumOccurrences() > 0;
70 }
71
72 void LoopAccessReport::emitAnalysis(const LoopAccessReport &Message,
73                                     const Function *TheFunction,
74                                     const Loop *TheLoop,
75                                     const char *PassName) {
76   DebugLoc DL = TheLoop->getStartLoc();
77   if (const Instruction *I = Message.getInstr())
78     DL = I->getDebugLoc();
79   emitOptimizationRemarkAnalysis(TheFunction->getContext(), PassName,
80                                  *TheFunction, DL, Message.str());
81 }
82
83 Value *llvm::stripIntegerCast(Value *V) {
84   if (CastInst *CI = dyn_cast<CastInst>(V))
85     if (CI->getOperand(0)->getType()->isIntegerTy())
86       return CI->getOperand(0);
87   return V;
88 }
89
90 const SCEV *llvm::replaceSymbolicStrideSCEV(ScalarEvolution *SE,
91                                             const ValueToValueMap &PtrToStride,
92                                             Value *Ptr, Value *OrigPtr) {
93
94   const SCEV *OrigSCEV = SE->getSCEV(Ptr);
95
96   // If there is an entry in the map return the SCEV of the pointer with the
97   // symbolic stride replaced by one.
98   ValueToValueMap::const_iterator SI =
99       PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
100   if (SI != PtrToStride.end()) {
101     Value *StrideVal = SI->second;
102
103     // Strip casts.
104     StrideVal = stripIntegerCast(StrideVal);
105
106     // Replace symbolic stride by one.
107     Value *One = ConstantInt::get(StrideVal->getType(), 1);
108     ValueToValueMap RewriteMap;
109     RewriteMap[StrideVal] = One;
110
111     const SCEV *ByOne =
112         SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
113     DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
114                  << "\n");
115     return ByOne;
116   }
117
118   // Otherwise, just return the SCEV of the original pointer.
119   return SE->getSCEV(Ptr);
120 }
121
122 void LoopAccessInfo::RuntimePointerCheck::insert(
123     Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId, unsigned ASId,
124     const ValueToValueMap &Strides) {
125   // Get the stride replaced scev.
126   const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
127   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
128   assert(AR && "Invalid addrec expression");
129   const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
130   const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
131   Pointers.push_back(Ptr);
132   Starts.push_back(AR->getStart());
133   Ends.push_back(ScEnd);
134   IsWritePtr.push_back(WritePtr);
135   DependencySetId.push_back(DepSetId);
136   AliasSetId.push_back(ASId);
137   Exprs.push_back(Sc);
138 }
139
140 bool LoopAccessInfo::RuntimePointerCheck::needsChecking(
141     const CheckingPtrGroup &M, const CheckingPtrGroup &N,
142     const SmallVectorImpl<int> *PtrPartition) const {
143   for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I)
144     for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J)
145       if (needsChecking(M.Members[I], N.Members[J], PtrPartition))
146         return true;
147   return false;
148 }
149
150 /// Compare \p I and \p J and return the minimum.
151 /// Return nullptr in case we couldn't find an answer.
152 static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
153                                    ScalarEvolution *SE) {
154   const SCEV *Diff = SE->getMinusSCEV(J, I);
155   const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
156
157   if (!C)
158     return nullptr;
159   if (C->getValue()->isNegative())
160     return J;
161   return I;
162 }
163
164 bool LoopAccessInfo::RuntimePointerCheck::CheckingPtrGroup::addPointer(
165     unsigned Index) {
166   // Compare the starts and ends with the known minimum and maximum
167   // of this set. We need to know how we compare against the min/max
168   // of the set in order to be able to emit memchecks.
169   const SCEV *Min0 = getMinFromExprs(RtCheck.Starts[Index], Low, RtCheck.SE);
170   if (!Min0)
171     return false;
172
173   const SCEV *Min1 = getMinFromExprs(RtCheck.Ends[Index], High, RtCheck.SE);
174   if (!Min1)
175     return false;
176
177   // Update the low bound  expression if we've found a new min value.
178   if (Min0 == RtCheck.Starts[Index])
179     Low = RtCheck.Starts[Index];
180
181   // Update the high bound expression if we've found a new max value.
182   if (Min1 != RtCheck.Ends[Index])
183     High = RtCheck.Ends[Index];
184
185   Members.push_back(Index);
186   return true;
187 }
188
189 void LoopAccessInfo::RuntimePointerCheck::groupChecks(
190     MemoryDepChecker::DepCandidates &DepCands,
191     bool UseDependencies) {
192   // We build the groups from dependency candidates equivalence classes
193   // because:
194   //    - We know that pointers in the same equivalence class share
195   //      the same underlying object and therefore there is a chance
196   //      that we can compare pointers
197   //    - We wouldn't be able to merge two pointers for which we need
198   //      to emit a memcheck. The classes in DepCands are already
199   //      conveniently built such that no two pointers in the same
200   //      class need checking against each other.
201
202   // We use the following (greedy) algorithm to construct the groups
203   // For every pointer in the equivalence class:
204   //   For each existing group:
205   //   - if the difference between this pointer and the min/max bounds
206   //     of the group is a constant, then make the pointer part of the
207   //     group and update the min/max bounds of that group as required.
208
209   CheckingGroups.clear();
210
211   // If we don't have the dependency partitions, construct a new
212   // checking pointer group for each pointer.
213   if (!UseDependencies) {
214     for (unsigned I = 0; I < Pointers.size(); ++I)
215       CheckingGroups.push_back(CheckingPtrGroup(I, *this));
216     return;
217   }
218
219   unsigned TotalComparisons = 0;
220
221   DenseMap<Value *, unsigned> PositionMap;
222   for (unsigned Pointer = 0; Pointer < Pointers.size(); ++Pointer)
223     PositionMap[Pointers[Pointer]] = Pointer;
224
225   // Go through all equivalence classes, get the the "pointer check groups"
226   // and add them to the overall solution.
227   for (auto DI = DepCands.begin(), DE = DepCands.end(); DI != DE; ++DI) {
228     if (!DI->isLeader())
229       continue;
230
231     SmallVector<CheckingPtrGroup, 2> Groups;
232
233     for (auto MI = DepCands.member_begin(DI), ME = DepCands.member_end();
234          MI != ME; ++MI) {
235       unsigned Pointer = PositionMap[MI->getPointer()];
236       bool Merged = false;
237
238       // Go through all the existing sets and see if we can find one
239       // which can include this pointer.
240       for (CheckingPtrGroup &Group : Groups) {
241         // Don't perform more than a certain amount of comparisons.
242         // This should limit the cost of grouping the pointers to something
243         // reasonable.  If we do end up hitting this threshold, the algorithm
244         // will create separate groups for all remaining pointers.
245         if (TotalComparisons > MemoryCheckMergeThreshold)
246           break;
247
248         TotalComparisons++;
249
250         if (Group.addPointer(Pointer)) {
251           Merged = true;
252           break;
253         }
254       }
255
256       if (!Merged)
257         // We couldn't add this pointer to any existing set or the threshold
258         // for the number of comparisons has been reached. Create a new group
259         // to hold the current pointer.
260         Groups.push_back(CheckingPtrGroup(Pointer, *this));
261     }
262
263     // We've computed the grouped checks for this partition.
264     // Save the results and continue with the next one.
265     std::copy(Groups.begin(), Groups.end(), std::back_inserter(CheckingGroups));
266   }
267 }
268
269 bool LoopAccessInfo::RuntimePointerCheck::needsChecking(
270     unsigned I, unsigned J, const SmallVectorImpl<int> *PtrPartition) const {
271   // No need to check if two readonly pointers intersect.
272   if (!IsWritePtr[I] && !IsWritePtr[J])
273     return false;
274
275   // Only need to check pointers between two different dependency sets.
276   if (DependencySetId[I] == DependencySetId[J])
277     return false;
278
279   // Only need to check pointers in the same alias set.
280   if (AliasSetId[I] != AliasSetId[J])
281     return false;
282
283   // If PtrPartition is set omit checks between pointers of the same partition.
284   // Partition number -1 means that the pointer is used in multiple partitions.
285   // In this case we can't omit the check.
286   if (PtrPartition && (*PtrPartition)[I] != -1 &&
287       (*PtrPartition)[I] == (*PtrPartition)[J])
288     return false;
289
290   return true;
291 }
292
293 void LoopAccessInfo::RuntimePointerCheck::print(
294     raw_ostream &OS, unsigned Depth,
295     const SmallVectorImpl<int> *PtrPartition) const {
296
297   OS.indent(Depth) << "Run-time memory checks:\n";
298
299   unsigned N = 0;
300   for (unsigned I = 0; I < CheckingGroups.size(); ++I)
301     for (unsigned J = I + 1; J < CheckingGroups.size(); ++J)
302       if (needsChecking(CheckingGroups[I], CheckingGroups[J], PtrPartition)) {
303         OS.indent(Depth) << "Check " << N++ << ":\n";
304         OS.indent(Depth + 2) << "Comparing group " << I << ":\n";
305
306         for (unsigned K = 0; K < CheckingGroups[I].Members.size(); ++K) {
307           OS.indent(Depth + 2) << *Pointers[CheckingGroups[I].Members[K]]
308                                << "\n";
309           if (PtrPartition)
310             OS << " (Partition: "
311                << (*PtrPartition)[CheckingGroups[I].Members[K]] << ")"
312                << "\n";
313         }
314
315         OS.indent(Depth + 2) << "Against group " << J << ":\n";
316
317         for (unsigned K = 0; K < CheckingGroups[J].Members.size(); ++K) {
318           OS.indent(Depth + 2) << *Pointers[CheckingGroups[J].Members[K]]
319                                << "\n";
320           if (PtrPartition)
321             OS << " (Partition: "
322                << (*PtrPartition)[CheckingGroups[J].Members[K]] << ")"
323                << "\n";
324         }
325       }
326
327   OS.indent(Depth) << "Grouped accesses:\n";
328   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
329     OS.indent(Depth + 2) << "Group " << I << ":\n";
330     OS.indent(Depth + 4) << "(Low: " << *CheckingGroups[I].Low
331                          << " High: " << *CheckingGroups[I].High << ")\n";
332     for (unsigned J = 0; J < CheckingGroups[I].Members.size(); ++J) {
333       OS.indent(Depth + 6) << "Member: " << *Exprs[CheckingGroups[I].Members[J]]
334                            << "\n";
335     }
336   }
337 }
338
339 unsigned LoopAccessInfo::RuntimePointerCheck::getNumberOfChecks(
340     const SmallVectorImpl<int> *PtrPartition) const {
341
342   unsigned NumPartitions = CheckingGroups.size();
343   unsigned CheckCount = 0;
344
345   for (unsigned I = 0; I < NumPartitions; ++I)
346     for (unsigned J = I + 1; J < NumPartitions; ++J)
347       if (needsChecking(CheckingGroups[I], CheckingGroups[J], PtrPartition))
348         CheckCount++;
349   return CheckCount;
350 }
351
352 bool LoopAccessInfo::RuntimePointerCheck::needsAnyChecking(
353     const SmallVectorImpl<int> *PtrPartition) const {
354   unsigned NumPointers = Pointers.size();
355
356   for (unsigned I = 0; I < NumPointers; ++I)
357     for (unsigned J = I + 1; J < NumPointers; ++J)
358       if (needsChecking(I, J, PtrPartition))
359         return true;
360   return false;
361 }
362
363 namespace {
364 /// \brief Analyses memory accesses in a loop.
365 ///
366 /// Checks whether run time pointer checks are needed and builds sets for data
367 /// dependence checking.
368 class AccessAnalysis {
369 public:
370   /// \brief Read or write access location.
371   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
372   typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
373
374   AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA, LoopInfo *LI,
375                  MemoryDepChecker::DepCandidates &DA)
376       : DL(Dl), AST(*AA), LI(LI), DepCands(DA), IsRTCheckNeeded(false) {}
377
378   /// \brief Register a load  and whether it is only read from.
379   void addLoad(MemoryLocation &Loc, bool IsReadOnly) {
380     Value *Ptr = const_cast<Value*>(Loc.Ptr);
381     AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
382     Accesses.insert(MemAccessInfo(Ptr, false));
383     if (IsReadOnly)
384       ReadOnlyPtr.insert(Ptr);
385   }
386
387   /// \brief Register a store.
388   void addStore(MemoryLocation &Loc) {
389     Value *Ptr = const_cast<Value*>(Loc.Ptr);
390     AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
391     Accesses.insert(MemAccessInfo(Ptr, true));
392   }
393
394   /// \brief Check whether we can check the pointers at runtime for
395   /// non-intersection. Returns true when we have 0 pointers
396   /// (a check on 0 pointers for non-intersection will always return true).
397   bool canCheckPtrAtRT(LoopAccessInfo::RuntimePointerCheck &RtCheck,
398                        bool &NeedRTCheck, ScalarEvolution *SE, Loop *TheLoop,
399                        const ValueToValueMap &Strides,
400                        bool ShouldCheckStride = false);
401
402   /// \brief Goes over all memory accesses, checks whether a RT check is needed
403   /// and builds sets of dependent accesses.
404   void buildDependenceSets() {
405     processMemAccesses();
406   }
407
408   bool isRTCheckNeeded() { return IsRTCheckNeeded; }
409
410   bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
411
412   /// We decided that no dependence analysis would be used.  Reset the state.
413   void resetDepChecks(MemoryDepChecker &DepChecker) {
414     CheckDeps.clear();
415     DepChecker.clearInterestingDependences();
416   }
417
418   MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
419
420 private:
421   typedef SetVector<MemAccessInfo> PtrAccessSet;
422
423   /// \brief Go over all memory access and check whether runtime pointer checks
424   /// are needed /// and build sets of dependency check candidates.
425   void processMemAccesses();
426
427   /// Set of all accesses.
428   PtrAccessSet Accesses;
429
430   const DataLayout &DL;
431
432   /// Set of accesses that need a further dependence check.
433   MemAccessInfoSet CheckDeps;
434
435   /// Set of pointers that are read only.
436   SmallPtrSet<Value*, 16> ReadOnlyPtr;
437
438   /// An alias set tracker to partition the access set by underlying object and
439   //intrinsic property (such as TBAA metadata).
440   AliasSetTracker AST;
441
442   LoopInfo *LI;
443
444   /// Sets of potentially dependent accesses - members of one set share an
445   /// underlying pointer. The set "CheckDeps" identfies which sets really need a
446   /// dependence check.
447   MemoryDepChecker::DepCandidates &DepCands;
448
449   bool IsRTCheckNeeded;
450 };
451
452 } // end anonymous namespace
453
454 /// \brief Check whether a pointer can participate in a runtime bounds check.
455 static bool hasComputableBounds(ScalarEvolution *SE,
456                                 const ValueToValueMap &Strides, Value *Ptr) {
457   const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
458   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
459   if (!AR)
460     return false;
461
462   return AR->isAffine();
463 }
464
465 bool AccessAnalysis::canCheckPtrAtRT(
466     LoopAccessInfo::RuntimePointerCheck &RtCheck, bool &NeedRTCheck,
467     ScalarEvolution *SE, Loop *TheLoop, const ValueToValueMap &StridesMap,
468     bool ShouldCheckStride) {
469   // Find pointers with computable bounds. We are going to use this information
470   // to place a runtime bound check.
471   bool CanDoRT = true;
472
473   NeedRTCheck = false;
474   if (!IsRTCheckNeeded) return true;
475
476   bool IsDepCheckNeeded = isDependencyCheckNeeded();
477
478   // We assign a consecutive id to access from different alias sets.
479   // Accesses between different groups doesn't need to be checked.
480   unsigned ASId = 1;
481   for (auto &AS : AST) {
482     // We assign consecutive id to access from different dependence sets.
483     // Accesses within the same set don't need a runtime check.
484     unsigned RunningDepId = 1;
485     DenseMap<Value *, unsigned> DepSetId;
486
487     for (auto A : AS) {
488       Value *Ptr = A.getValue();
489       bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
490       MemAccessInfo Access(Ptr, IsWrite);
491
492       if (hasComputableBounds(SE, StridesMap, Ptr) &&
493           // When we run after a failing dependency check we have to make sure
494           // we don't have wrapping pointers.
495           (!ShouldCheckStride ||
496            isStridedPtr(SE, Ptr, TheLoop, StridesMap) == 1)) {
497         // The id of the dependence set.
498         unsigned DepId;
499
500         if (IsDepCheckNeeded) {
501           Value *Leader = DepCands.getLeaderValue(Access).getPointer();
502           unsigned &LeaderId = DepSetId[Leader];
503           if (!LeaderId)
504             LeaderId = RunningDepId++;
505           DepId = LeaderId;
506         } else
507           // Each access has its own dependence set.
508           DepId = RunningDepId++;
509
510         RtCheck.insert(TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
511
512         DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
513       } else {
514         DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" << *Ptr << '\n');
515         CanDoRT = false;
516       }
517     }
518
519     ++ASId;
520   }
521
522   // We need a runtime check if there are any accesses that need checking.
523   // However, some accesses cannot be checked (for example because we
524   // can't determine their bounds). In these cases we would need a check
525   // but wouldn't be able to add it.
526   NeedRTCheck = !CanDoRT || RtCheck.needsAnyChecking(nullptr);
527
528   // If the pointers that we would use for the bounds comparison have different
529   // address spaces, assume the values aren't directly comparable, so we can't
530   // use them for the runtime check. We also have to assume they could
531   // overlap. In the future there should be metadata for whether address spaces
532   // are disjoint.
533   unsigned NumPointers = RtCheck.Pointers.size();
534   for (unsigned i = 0; i < NumPointers; ++i) {
535     for (unsigned j = i + 1; j < NumPointers; ++j) {
536       // Only need to check pointers between two different dependency sets.
537       if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
538        continue;
539       // Only need to check pointers in the same alias set.
540       if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j])
541         continue;
542
543       Value *PtrI = RtCheck.Pointers[i];
544       Value *PtrJ = RtCheck.Pointers[j];
545
546       unsigned ASi = PtrI->getType()->getPointerAddressSpace();
547       unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
548       if (ASi != ASj) {
549         DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
550                        " different address spaces\n");
551         return false;
552       }
553     }
554   }
555
556   if (NeedRTCheck && CanDoRT)
557     RtCheck.groupChecks(DepCands, IsDepCheckNeeded);
558
559   return CanDoRT;
560 }
561
562 void AccessAnalysis::processMemAccesses() {
563   // We process the set twice: first we process read-write pointers, last we
564   // process read-only pointers. This allows us to skip dependence tests for
565   // read-only pointers.
566
567   DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
568   DEBUG(dbgs() << "  AST: "; AST.dump());
569   DEBUG(dbgs() << "LAA:   Accesses(" << Accesses.size() << "):\n");
570   DEBUG({
571     for (auto A : Accesses)
572       dbgs() << "\t" << *A.getPointer() << " (" <<
573                 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
574                                          "read-only" : "read")) << ")\n";
575   });
576
577   // The AliasSetTracker has nicely partitioned our pointers by metadata
578   // compatibility and potential for underlying-object overlap. As a result, we
579   // only need to check for potential pointer dependencies within each alias
580   // set.
581   for (auto &AS : AST) {
582     // Note that both the alias-set tracker and the alias sets themselves used
583     // linked lists internally and so the iteration order here is deterministic
584     // (matching the original instruction order within each set).
585
586     bool SetHasWrite = false;
587
588     // Map of pointers to last access encountered.
589     typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
590     UnderlyingObjToAccessMap ObjToLastAccess;
591
592     // Set of access to check after all writes have been processed.
593     PtrAccessSet DeferredAccesses;
594
595     // Iterate over each alias set twice, once to process read/write pointers,
596     // and then to process read-only pointers.
597     for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
598       bool UseDeferred = SetIteration > 0;
599       PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
600
601       for (auto AV : AS) {
602         Value *Ptr = AV.getValue();
603
604         // For a single memory access in AliasSetTracker, Accesses may contain
605         // both read and write, and they both need to be handled for CheckDeps.
606         for (auto AC : S) {
607           if (AC.getPointer() != Ptr)
608             continue;
609
610           bool IsWrite = AC.getInt();
611
612           // If we're using the deferred access set, then it contains only
613           // reads.
614           bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
615           if (UseDeferred && !IsReadOnlyPtr)
616             continue;
617           // Otherwise, the pointer must be in the PtrAccessSet, either as a
618           // read or a write.
619           assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
620                   S.count(MemAccessInfo(Ptr, false))) &&
621                  "Alias-set pointer not in the access set?");
622
623           MemAccessInfo Access(Ptr, IsWrite);
624           DepCands.insert(Access);
625
626           // Memorize read-only pointers for later processing and skip them in
627           // the first round (they need to be checked after we have seen all
628           // write pointers). Note: we also mark pointer that are not
629           // consecutive as "read-only" pointers (so that we check
630           // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
631           if (!UseDeferred && IsReadOnlyPtr) {
632             DeferredAccesses.insert(Access);
633             continue;
634           }
635
636           // If this is a write - check other reads and writes for conflicts. If
637           // this is a read only check other writes for conflicts (but only if
638           // there is no other write to the ptr - this is an optimization to
639           // catch "a[i] = a[i] + " without having to do a dependence check).
640           if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
641             CheckDeps.insert(Access);
642             IsRTCheckNeeded = true;
643           }
644
645           if (IsWrite)
646             SetHasWrite = true;
647
648           // Create sets of pointers connected by a shared alias set and
649           // underlying object.
650           typedef SmallVector<Value *, 16> ValueVector;
651           ValueVector TempObjects;
652
653           GetUnderlyingObjects(Ptr, TempObjects, DL, LI);
654           DEBUG(dbgs() << "Underlying objects for pointer " << *Ptr << "\n");
655           for (Value *UnderlyingObj : TempObjects) {
656             UnderlyingObjToAccessMap::iterator Prev =
657                 ObjToLastAccess.find(UnderlyingObj);
658             if (Prev != ObjToLastAccess.end())
659               DepCands.unionSets(Access, Prev->second);
660
661             ObjToLastAccess[UnderlyingObj] = Access;
662             DEBUG(dbgs() << "  " << *UnderlyingObj << "\n");
663           }
664         }
665       }
666     }
667   }
668 }
669
670 static bool isInBoundsGep(Value *Ptr) {
671   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
672     return GEP->isInBounds();
673   return false;
674 }
675
676 /// \brief Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
677 /// i.e. monotonically increasing/decreasing.
678 static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
679                            ScalarEvolution *SE, const Loop *L) {
680   // FIXME: This should probably only return true for NUW.
681   if (AR->getNoWrapFlags(SCEV::NoWrapMask))
682     return true;
683
684   // Scalar evolution does not propagate the non-wrapping flags to values that
685   // are derived from a non-wrapping induction variable because non-wrapping
686   // could be flow-sensitive.
687   //
688   // Look through the potentially overflowing instruction to try to prove
689   // non-wrapping for the *specific* value of Ptr.
690
691   // The arithmetic implied by an inbounds GEP can't overflow.
692   auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
693   if (!GEP || !GEP->isInBounds())
694     return false;
695
696   // Make sure there is only one non-const index and analyze that.
697   Value *NonConstIndex = nullptr;
698   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
699     if (!isa<ConstantInt>(*Index)) {
700       if (NonConstIndex)
701         return false;
702       NonConstIndex = *Index;
703     }
704   if (!NonConstIndex)
705     // The recurrence is on the pointer, ignore for now.
706     return false;
707
708   // The index in GEP is signed.  It is non-wrapping if it's derived from a NSW
709   // AddRec using a NSW operation.
710   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
711     if (OBO->hasNoSignedWrap() &&
712         // Assume constant for other the operand so that the AddRec can be
713         // easily found.
714         isa<ConstantInt>(OBO->getOperand(1))) {
715       auto *OpScev = SE->getSCEV(OBO->getOperand(0));
716
717       if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
718         return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
719     }
720
721   return false;
722 }
723
724 /// \brief Check whether the access through \p Ptr has a constant stride.
725 int llvm::isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
726                        const ValueToValueMap &StridesMap) {
727   const Type *Ty = Ptr->getType();
728   assert(Ty->isPointerTy() && "Unexpected non-ptr");
729
730   // Make sure that the pointer does not point to aggregate types.
731   const PointerType *PtrTy = cast<PointerType>(Ty);
732   if (PtrTy->getElementType()->isAggregateType()) {
733     DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
734           << *Ptr << "\n");
735     return 0;
736   }
737
738   const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
739
740   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
741   if (!AR) {
742     DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
743           << *Ptr << " SCEV: " << *PtrScev << "\n");
744     return 0;
745   }
746
747   // The accesss function must stride over the innermost loop.
748   if (Lp != AR->getLoop()) {
749     DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
750           *Ptr << " SCEV: " << *PtrScev << "\n");
751   }
752
753   // The address calculation must not wrap. Otherwise, a dependence could be
754   // inverted.
755   // An inbounds getelementptr that is a AddRec with a unit stride
756   // cannot wrap per definition. The unit stride requirement is checked later.
757   // An getelementptr without an inbounds attribute and unit stride would have
758   // to access the pointer value "0" which is undefined behavior in address
759   // space 0, therefore we can also vectorize this case.
760   bool IsInBoundsGEP = isInBoundsGep(Ptr);
761   bool IsNoWrapAddRec = isNoWrapAddRec(Ptr, AR, SE, Lp);
762   bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
763   if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
764     DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
765           << *Ptr << " SCEV: " << *PtrScev << "\n");
766     return 0;
767   }
768
769   // Check the step is constant.
770   const SCEV *Step = AR->getStepRecurrence(*SE);
771
772   // Calculate the pointer stride and check if it is consecutive.
773   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
774   if (!C) {
775     DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
776           " SCEV: " << *PtrScev << "\n");
777     return 0;
778   }
779
780   auto &DL = Lp->getHeader()->getModule()->getDataLayout();
781   int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
782   const APInt &APStepVal = C->getValue()->getValue();
783
784   // Huge step value - give up.
785   if (APStepVal.getBitWidth() > 64)
786     return 0;
787
788   int64_t StepVal = APStepVal.getSExtValue();
789
790   // Strided access.
791   int64_t Stride = StepVal / Size;
792   int64_t Rem = StepVal % Size;
793   if (Rem)
794     return 0;
795
796   // If the SCEV could wrap but we have an inbounds gep with a unit stride we
797   // know we can't "wrap around the address space". In case of address space
798   // zero we know that this won't happen without triggering undefined behavior.
799   if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
800       Stride != 1 && Stride != -1)
801     return 0;
802
803   return Stride;
804 }
805
806 bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
807   switch (Type) {
808   case NoDep:
809   case Forward:
810   case BackwardVectorizable:
811     return true;
812
813   case Unknown:
814   case ForwardButPreventsForwarding:
815   case Backward:
816   case BackwardVectorizableButPreventsForwarding:
817     return false;
818   }
819   llvm_unreachable("unexpected DepType!");
820 }
821
822 bool MemoryDepChecker::Dependence::isInterestingDependence(DepType Type) {
823   switch (Type) {
824   case NoDep:
825   case Forward:
826     return false;
827
828   case BackwardVectorizable:
829   case Unknown:
830   case ForwardButPreventsForwarding:
831   case Backward:
832   case BackwardVectorizableButPreventsForwarding:
833     return true;
834   }
835   llvm_unreachable("unexpected DepType!");
836 }
837
838 bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
839   switch (Type) {
840   case NoDep:
841   case Forward:
842   case ForwardButPreventsForwarding:
843     return false;
844
845   case Unknown:
846   case BackwardVectorizable:
847   case Backward:
848   case BackwardVectorizableButPreventsForwarding:
849     return true;
850   }
851   llvm_unreachable("unexpected DepType!");
852 }
853
854 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
855                                                     unsigned TypeByteSize) {
856   // If loads occur at a distance that is not a multiple of a feasible vector
857   // factor store-load forwarding does not take place.
858   // Positive dependences might cause troubles because vectorizing them might
859   // prevent store-load forwarding making vectorized code run a lot slower.
860   //   a[i] = a[i-3] ^ a[i-8];
861   //   The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
862   //   hence on your typical architecture store-load forwarding does not take
863   //   place. Vectorizing in such cases does not make sense.
864   // Store-load forwarding distance.
865   const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
866   // Maximum vector factor.
867   unsigned MaxVFWithoutSLForwardIssues =
868     VectorizerParams::MaxVectorWidth * TypeByteSize;
869   if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
870     MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
871
872   for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
873        vf *= 2) {
874     if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
875       MaxVFWithoutSLForwardIssues = (vf >>=1);
876       break;
877     }
878   }
879
880   if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
881     DEBUG(dbgs() << "LAA: Distance " << Distance <<
882           " that could cause a store-load forwarding conflict\n");
883     return true;
884   }
885
886   if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
887       MaxVFWithoutSLForwardIssues !=
888       VectorizerParams::MaxVectorWidth * TypeByteSize)
889     MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
890   return false;
891 }
892
893 /// \brief Check the dependence for two accesses with the same stride \p Stride.
894 /// \p Distance is the positive distance and \p TypeByteSize is type size in
895 /// bytes.
896 ///
897 /// \returns true if they are independent.
898 static bool areStridedAccessesIndependent(unsigned Distance, unsigned Stride,
899                                           unsigned TypeByteSize) {
900   assert(Stride > 1 && "The stride must be greater than 1");
901   assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
902   assert(Distance > 0 && "The distance must be non-zero");
903
904   // Skip if the distance is not multiple of type byte size.
905   if (Distance % TypeByteSize)
906     return false;
907
908   unsigned ScaledDist = Distance / TypeByteSize;
909
910   // No dependence if the scaled distance is not multiple of the stride.
911   // E.g.
912   //      for (i = 0; i < 1024 ; i += 4)
913   //        A[i+2] = A[i] + 1;
914   //
915   // Two accesses in memory (scaled distance is 2, stride is 4):
916   //     | A[0] |      |      |      | A[4] |      |      |      |
917   //     |      |      | A[2] |      |      |      | A[6] |      |
918   //
919   // E.g.
920   //      for (i = 0; i < 1024 ; i += 3)
921   //        A[i+4] = A[i] + 1;
922   //
923   // Two accesses in memory (scaled distance is 4, stride is 3):
924   //     | A[0] |      |      | A[3] |      |      | A[6] |      |      |
925   //     |      |      |      |      | A[4] |      |      | A[7] |      |
926   return ScaledDist % Stride;
927 }
928
929 MemoryDepChecker::Dependence::DepType
930 MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
931                               const MemAccessInfo &B, unsigned BIdx,
932                               const ValueToValueMap &Strides) {
933   assert (AIdx < BIdx && "Must pass arguments in program order");
934
935   Value *APtr = A.getPointer();
936   Value *BPtr = B.getPointer();
937   bool AIsWrite = A.getInt();
938   bool BIsWrite = B.getInt();
939
940   // Two reads are independent.
941   if (!AIsWrite && !BIsWrite)
942     return Dependence::NoDep;
943
944   // We cannot check pointers in different address spaces.
945   if (APtr->getType()->getPointerAddressSpace() !=
946       BPtr->getType()->getPointerAddressSpace())
947     return Dependence::Unknown;
948
949   const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
950   const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
951
952   int StrideAPtr = isStridedPtr(SE, APtr, InnermostLoop, Strides);
953   int StrideBPtr = isStridedPtr(SE, BPtr, InnermostLoop, Strides);
954
955   const SCEV *Src = AScev;
956   const SCEV *Sink = BScev;
957
958   // If the induction step is negative we have to invert source and sink of the
959   // dependence.
960   if (StrideAPtr < 0) {
961     //Src = BScev;
962     //Sink = AScev;
963     std::swap(APtr, BPtr);
964     std::swap(Src, Sink);
965     std::swap(AIsWrite, BIsWrite);
966     std::swap(AIdx, BIdx);
967     std::swap(StrideAPtr, StrideBPtr);
968   }
969
970   const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
971
972   DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
973         << "(Induction step: " << StrideAPtr <<  ")\n");
974   DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
975         << *InstMap[BIdx] << ": " << *Dist << "\n");
976
977   // Need consecutive accesses. We don't want to vectorize
978   // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
979   // the address space.
980   if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
981     DEBUG(dbgs() << "Non-consecutive pointer access\n");
982     return Dependence::Unknown;
983   }
984
985   const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
986   if (!C) {
987     DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
988     ShouldRetryWithRuntimeCheck = true;
989     return Dependence::Unknown;
990   }
991
992   Type *ATy = APtr->getType()->getPointerElementType();
993   Type *BTy = BPtr->getType()->getPointerElementType();
994   auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
995   unsigned TypeByteSize = DL.getTypeAllocSize(ATy);
996
997   // Negative distances are not plausible dependencies.
998   const APInt &Val = C->getValue()->getValue();
999   if (Val.isNegative()) {
1000     bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
1001     if (IsTrueDataDependence &&
1002         (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
1003          ATy != BTy))
1004       return Dependence::ForwardButPreventsForwarding;
1005
1006     DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
1007     return Dependence::Forward;
1008   }
1009
1010   // Write to the same location with the same size.
1011   // Could be improved to assert type sizes are the same (i32 == float, etc).
1012   if (Val == 0) {
1013     if (ATy == BTy)
1014       return Dependence::NoDep;
1015     DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
1016     return Dependence::Unknown;
1017   }
1018
1019   assert(Val.isStrictlyPositive() && "Expect a positive value");
1020
1021   if (ATy != BTy) {
1022     DEBUG(dbgs() <<
1023           "LAA: ReadWrite-Write positive dependency with different types\n");
1024     return Dependence::Unknown;
1025   }
1026
1027   unsigned Distance = (unsigned) Val.getZExtValue();
1028
1029   unsigned Stride = std::abs(StrideAPtr);
1030   if (Stride > 1 &&
1031       areStridedAccessesIndependent(Distance, Stride, TypeByteSize)) {
1032     DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
1033     return Dependence::NoDep;
1034   }
1035
1036   // Bail out early if passed-in parameters make vectorization not feasible.
1037   unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
1038                            VectorizerParams::VectorizationFactor : 1);
1039   unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
1040                            VectorizerParams::VectorizationInterleave : 1);
1041   // The minimum number of iterations for a vectorized/unrolled version.
1042   unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
1043
1044   // It's not vectorizable if the distance is smaller than the minimum distance
1045   // needed for a vectroized/unrolled version. Vectorizing one iteration in
1046   // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
1047   // TypeByteSize (No need to plus the last gap distance).
1048   //
1049   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1050   //      foo(int *A) {
1051   //        int *B = (int *)((char *)A + 14);
1052   //        for (i = 0 ; i < 1024 ; i += 2)
1053   //          B[i] = A[i] + 1;
1054   //      }
1055   //
1056   // Two accesses in memory (stride is 2):
1057   //     | A[0] |      | A[2] |      | A[4] |      | A[6] |      |
1058   //                              | B[0] |      | B[2] |      | B[4] |
1059   //
1060   // Distance needs for vectorizing iterations except the last iteration:
1061   // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
1062   // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
1063   //
1064   // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
1065   // 12, which is less than distance.
1066   //
1067   // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
1068   // the minimum distance needed is 28, which is greater than distance. It is
1069   // not safe to do vectorization.
1070   unsigned MinDistanceNeeded =
1071       TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
1072   if (MinDistanceNeeded > Distance) {
1073     DEBUG(dbgs() << "LAA: Failure because of positive distance " << Distance
1074                  << '\n');
1075     return Dependence::Backward;
1076   }
1077
1078   // Unsafe if the minimum distance needed is greater than max safe distance.
1079   if (MinDistanceNeeded > MaxSafeDepDistBytes) {
1080     DEBUG(dbgs() << "LAA: Failure because it needs at least "
1081                  << MinDistanceNeeded << " size in bytes");
1082     return Dependence::Backward;
1083   }
1084
1085   // Positive distance bigger than max vectorization factor.
1086   // FIXME: Should use max factor instead of max distance in bytes, which could
1087   // not handle different types.
1088   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1089   //      void foo (int *A, char *B) {
1090   //        for (unsigned i = 0; i < 1024; i++) {
1091   //          A[i+2] = A[i] + 1;
1092   //          B[i+2] = B[i] + 1;
1093   //        }
1094   //      }
1095   //
1096   // This case is currently unsafe according to the max safe distance. If we
1097   // analyze the two accesses on array B, the max safe dependence distance
1098   // is 2. Then we analyze the accesses on array A, the minimum distance needed
1099   // is 8, which is less than 2 and forbidden vectorization, But actually
1100   // both A and B could be vectorized by 2 iterations.
1101   MaxSafeDepDistBytes =
1102       Distance < MaxSafeDepDistBytes ? Distance : MaxSafeDepDistBytes;
1103
1104   bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
1105   if (IsTrueDataDependence &&
1106       couldPreventStoreLoadForward(Distance, TypeByteSize))
1107     return Dependence::BackwardVectorizableButPreventsForwarding;
1108
1109   DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
1110                << " with max VF = "
1111                << MaxSafeDepDistBytes / (TypeByteSize * Stride) << '\n');
1112
1113   return Dependence::BackwardVectorizable;
1114 }
1115
1116 bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
1117                                    MemAccessInfoSet &CheckDeps,
1118                                    const ValueToValueMap &Strides) {
1119
1120   MaxSafeDepDistBytes = -1U;
1121   while (!CheckDeps.empty()) {
1122     MemAccessInfo CurAccess = *CheckDeps.begin();
1123
1124     // Get the relevant memory access set.
1125     EquivalenceClasses<MemAccessInfo>::iterator I =
1126       AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
1127
1128     // Check accesses within this set.
1129     EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
1130     AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
1131
1132     // Check every access pair.
1133     while (AI != AE) {
1134       CheckDeps.erase(*AI);
1135       EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
1136       while (OI != AE) {
1137         // Check every accessing instruction pair in program order.
1138         for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
1139              I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
1140           for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
1141                I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
1142             auto A = std::make_pair(&*AI, *I1);
1143             auto B = std::make_pair(&*OI, *I2);
1144
1145             assert(*I1 != *I2);
1146             if (*I1 > *I2)
1147               std::swap(A, B);
1148
1149             Dependence::DepType Type =
1150                 isDependent(*A.first, A.second, *B.first, B.second, Strides);
1151             SafeForVectorization &= Dependence::isSafeForVectorization(Type);
1152
1153             // Gather dependences unless we accumulated MaxInterestingDependence
1154             // dependences.  In that case return as soon as we find the first
1155             // unsafe dependence.  This puts a limit on this quadratic
1156             // algorithm.
1157             if (RecordInterestingDependences) {
1158               if (Dependence::isInterestingDependence(Type))
1159                 InterestingDependences.push_back(
1160                     Dependence(A.second, B.second, Type));
1161
1162               if (InterestingDependences.size() >= MaxInterestingDependence) {
1163                 RecordInterestingDependences = false;
1164                 InterestingDependences.clear();
1165                 DEBUG(dbgs() << "Too many dependences, stopped recording\n");
1166               }
1167             }
1168             if (!RecordInterestingDependences && !SafeForVectorization)
1169               return false;
1170           }
1171         ++OI;
1172       }
1173       AI++;
1174     }
1175   }
1176
1177   DEBUG(dbgs() << "Total Interesting Dependences: "
1178                << InterestingDependences.size() << "\n");
1179   return SafeForVectorization;
1180 }
1181
1182 SmallVector<Instruction *, 4>
1183 MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
1184   MemAccessInfo Access(Ptr, isWrite);
1185   auto &IndexVector = Accesses.find(Access)->second;
1186
1187   SmallVector<Instruction *, 4> Insts;
1188   std::transform(IndexVector.begin(), IndexVector.end(),
1189                  std::back_inserter(Insts),
1190                  [&](unsigned Idx) { return this->InstMap[Idx]; });
1191   return Insts;
1192 }
1193
1194 const char *MemoryDepChecker::Dependence::DepName[] = {
1195     "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
1196     "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
1197
1198 void MemoryDepChecker::Dependence::print(
1199     raw_ostream &OS, unsigned Depth,
1200     const SmallVectorImpl<Instruction *> &Instrs) const {
1201   OS.indent(Depth) << DepName[Type] << ":\n";
1202   OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
1203   OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
1204 }
1205
1206 bool LoopAccessInfo::canAnalyzeLoop() {
1207   // We need to have a loop header.
1208   DEBUG(dbgs() << "LAA: Found a loop: " <<
1209         TheLoop->getHeader()->getName() << '\n');
1210
1211     // We can only analyze innermost loops.
1212   if (!TheLoop->empty()) {
1213     DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
1214     emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
1215     return false;
1216   }
1217
1218   // We must have a single backedge.
1219   if (TheLoop->getNumBackEdges() != 1) {
1220     DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1221     emitAnalysis(
1222         LoopAccessReport() <<
1223         "loop control flow is not understood by analyzer");
1224     return false;
1225   }
1226
1227   // We must have a single exiting block.
1228   if (!TheLoop->getExitingBlock()) {
1229     DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1230     emitAnalysis(
1231         LoopAccessReport() <<
1232         "loop control flow is not understood by analyzer");
1233     return false;
1234   }
1235
1236   // We only handle bottom-tested loops, i.e. loop in which the condition is
1237   // checked at the end of each iteration. With that we can assume that all
1238   // instructions in the loop are executed the same number of times.
1239   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
1240     DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1241     emitAnalysis(
1242         LoopAccessReport() <<
1243         "loop control flow is not understood by analyzer");
1244     return false;
1245   }
1246
1247   // ScalarEvolution needs to be able to find the exit count.
1248   const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
1249   if (ExitCount == SE->getCouldNotCompute()) {
1250     emitAnalysis(LoopAccessReport() <<
1251                  "could not determine number of loop iterations");
1252     DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
1253     return false;
1254   }
1255
1256   return true;
1257 }
1258
1259 void LoopAccessInfo::analyzeLoop(const ValueToValueMap &Strides) {
1260
1261   typedef SmallVector<Value*, 16> ValueVector;
1262   typedef SmallPtrSet<Value*, 16> ValueSet;
1263
1264   // Holds the Load and Store *instructions*.
1265   ValueVector Loads;
1266   ValueVector Stores;
1267
1268   // Holds all the different accesses in the loop.
1269   unsigned NumReads = 0;
1270   unsigned NumReadWrites = 0;
1271
1272   PtrRtCheck.Pointers.clear();
1273   PtrRtCheck.Need = false;
1274
1275   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
1276
1277   // For each block.
1278   for (Loop::block_iterator bb = TheLoop->block_begin(),
1279        be = TheLoop->block_end(); bb != be; ++bb) {
1280
1281     // Scan the BB and collect legal loads and stores.
1282     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1283          ++it) {
1284
1285       // If this is a load, save it. If this instruction can read from memory
1286       // but is not a load, then we quit. Notice that we don't handle function
1287       // calls that read or write.
1288       if (it->mayReadFromMemory()) {
1289         // Many math library functions read the rounding mode. We will only
1290         // vectorize a loop if it contains known function calls that don't set
1291         // the flag. Therefore, it is safe to ignore this read from memory.
1292         CallInst *Call = dyn_cast<CallInst>(it);
1293         if (Call && getIntrinsicIDForCall(Call, TLI))
1294           continue;
1295
1296         // If the function has an explicit vectorized counterpart, we can safely
1297         // assume that it can be vectorized.
1298         if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
1299             TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
1300           continue;
1301
1302         LoadInst *Ld = dyn_cast<LoadInst>(it);
1303         if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
1304           emitAnalysis(LoopAccessReport(Ld)
1305                        << "read with atomic ordering or volatile read");
1306           DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
1307           CanVecMem = false;
1308           return;
1309         }
1310         NumLoads++;
1311         Loads.push_back(Ld);
1312         DepChecker.addAccess(Ld);
1313         continue;
1314       }
1315
1316       // Save 'store' instructions. Abort if other instructions write to memory.
1317       if (it->mayWriteToMemory()) {
1318         StoreInst *St = dyn_cast<StoreInst>(it);
1319         if (!St) {
1320           emitAnalysis(LoopAccessReport(it) <<
1321                        "instruction cannot be vectorized");
1322           CanVecMem = false;
1323           return;
1324         }
1325         if (!St->isSimple() && !IsAnnotatedParallel) {
1326           emitAnalysis(LoopAccessReport(St)
1327                        << "write with atomic ordering or volatile write");
1328           DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
1329           CanVecMem = false;
1330           return;
1331         }
1332         NumStores++;
1333         Stores.push_back(St);
1334         DepChecker.addAccess(St);
1335       }
1336     } // Next instr.
1337   } // Next block.
1338
1339   // Now we have two lists that hold the loads and the stores.
1340   // Next, we find the pointers that they use.
1341
1342   // Check if we see any stores. If there are no stores, then we don't
1343   // care if the pointers are *restrict*.
1344   if (!Stores.size()) {
1345     DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
1346     CanVecMem = true;
1347     return;
1348   }
1349
1350   MemoryDepChecker::DepCandidates DependentAccesses;
1351   AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
1352                           AA, LI, DependentAccesses);
1353
1354   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1355   // multiple times on the same object. If the ptr is accessed twice, once
1356   // for read and once for write, it will only appear once (on the write
1357   // list). This is okay, since we are going to check for conflicts between
1358   // writes and between reads and writes, but not between reads and reads.
1359   ValueSet Seen;
1360
1361   ValueVector::iterator I, IE;
1362   for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1363     StoreInst *ST = cast<StoreInst>(*I);
1364     Value* Ptr = ST->getPointerOperand();
1365     // Check for store to loop invariant address.
1366     StoreToLoopInvariantAddress |= isUniform(Ptr);
1367     // If we did *not* see this pointer before, insert it to  the read-write
1368     // list. At this phase it is only a 'write' list.
1369     if (Seen.insert(Ptr).second) {
1370       ++NumReadWrites;
1371
1372       MemoryLocation Loc = MemoryLocation::get(ST);
1373       // The TBAA metadata could have a control dependency on the predication
1374       // condition, so we cannot rely on it when determining whether or not we
1375       // need runtime pointer checks.
1376       if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
1377         Loc.AATags.TBAA = nullptr;
1378
1379       Accesses.addStore(Loc);
1380     }
1381   }
1382
1383   if (IsAnnotatedParallel) {
1384     DEBUG(dbgs()
1385           << "LAA: A loop annotated parallel, ignore memory dependency "
1386           << "checks.\n");
1387     CanVecMem = true;
1388     return;
1389   }
1390
1391   for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1392     LoadInst *LD = cast<LoadInst>(*I);
1393     Value* Ptr = LD->getPointerOperand();
1394     // If we did *not* see this pointer before, insert it to the
1395     // read list. If we *did* see it before, then it is already in
1396     // the read-write list. This allows us to vectorize expressions
1397     // such as A[i] += x;  Because the address of A[i] is a read-write
1398     // pointer. This only works if the index of A[i] is consecutive.
1399     // If the address of i is unknown (for example A[B[i]]) then we may
1400     // read a few words, modify, and write a few words, and some of the
1401     // words may be written to the same address.
1402     bool IsReadOnlyPtr = false;
1403     if (Seen.insert(Ptr).second || !isStridedPtr(SE, Ptr, TheLoop, Strides)) {
1404       ++NumReads;
1405       IsReadOnlyPtr = true;
1406     }
1407
1408     MemoryLocation Loc = MemoryLocation::get(LD);
1409     // The TBAA metadata could have a control dependency on the predication
1410     // condition, so we cannot rely on it when determining whether or not we
1411     // need runtime pointer checks.
1412     if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
1413       Loc.AATags.TBAA = nullptr;
1414
1415     Accesses.addLoad(Loc, IsReadOnlyPtr);
1416   }
1417
1418   // If we write (or read-write) to a single destination and there are no
1419   // other reads in this loop then is it safe to vectorize.
1420   if (NumReadWrites == 1 && NumReads == 0) {
1421     DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
1422     CanVecMem = true;
1423     return;
1424   }
1425
1426   // Build dependence sets and check whether we need a runtime pointer bounds
1427   // check.
1428   Accesses.buildDependenceSets();
1429
1430   // Find pointers with computable bounds. We are going to use this information
1431   // to place a runtime bound check.
1432   bool NeedRTCheck;
1433   bool CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck,
1434                                           NeedRTCheck, SE,
1435                                           TheLoop, Strides);
1436
1437   DEBUG(dbgs() << "LAA: We need to do "
1438                << PtrRtCheck.getNumberOfChecks(nullptr)
1439                << " pointer comparisons.\n");
1440
1441   // Check that we found the bounds for the pointer.
1442   if (CanDoRT)
1443     DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
1444   else if (NeedRTCheck) {
1445     emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
1446     DEBUG(dbgs() << "LAA: We can't vectorize because we can't find " <<
1447           "the array bounds.\n");
1448     PtrRtCheck.reset();
1449     CanVecMem = false;
1450     return;
1451   }
1452
1453   PtrRtCheck.Need = NeedRTCheck;
1454
1455   CanVecMem = true;
1456   if (Accesses.isDependencyCheckNeeded()) {
1457     DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
1458     CanVecMem = DepChecker.areDepsSafe(
1459         DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1460     MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1461
1462     if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
1463       DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
1464       NeedRTCheck = true;
1465
1466       // Clear the dependency checks. We assume they are not needed.
1467       Accesses.resetDepChecks(DepChecker);
1468
1469       PtrRtCheck.reset();
1470       PtrRtCheck.Need = true;
1471
1472       CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NeedRTCheck, SE,
1473                                          TheLoop, Strides, true);
1474
1475       // Check that we found the bounds for the pointer.
1476       if (NeedRTCheck && !CanDoRT) {
1477         emitAnalysis(LoopAccessReport()
1478                      << "cannot check memory dependencies at runtime");
1479         DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
1480         PtrRtCheck.reset();
1481         CanVecMem = false;
1482         return;
1483       }
1484
1485       CanVecMem = true;
1486     }
1487   }
1488
1489   if (CanVecMem)
1490     DEBUG(dbgs() << "LAA: No unsafe dependent memory operations in loop.  We"
1491                  << (NeedRTCheck ? "" : " don't")
1492                  << " need a runtime memory check.\n");
1493   else {
1494     emitAnalysis(LoopAccessReport() <<
1495                  "unsafe dependent memory operations in loop");
1496     DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
1497   }
1498 }
1499
1500 bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1501                                            DominatorTree *DT)  {
1502   assert(TheLoop->contains(BB) && "Unknown block used");
1503
1504   // Blocks that do not dominate the latch need predication.
1505   BasicBlock* Latch = TheLoop->getLoopLatch();
1506   return !DT->dominates(BB, Latch);
1507 }
1508
1509 void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
1510   assert(!Report && "Multiple reports generated");
1511   Report = Message;
1512 }
1513
1514 bool LoopAccessInfo::isUniform(Value *V) const {
1515   return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1516 }
1517
1518 // FIXME: this function is currently a duplicate of the one in
1519 // LoopVectorize.cpp.
1520 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1521                                  Instruction *Loc) {
1522   if (FirstInst)
1523     return FirstInst;
1524   if (Instruction *I = dyn_cast<Instruction>(V))
1525     return I->getParent() == Loc->getParent() ? I : nullptr;
1526   return nullptr;
1527 }
1528
1529 std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeCheck(
1530     Instruction *Loc, const SmallVectorImpl<int> *PtrPartition) const {
1531   if (!PtrRtCheck.Need)
1532     return std::make_pair(nullptr, nullptr);
1533
1534   SmallVector<TrackingVH<Value>, 2> Starts;
1535   SmallVector<TrackingVH<Value>, 2> Ends;
1536
1537   LLVMContext &Ctx = Loc->getContext();
1538   SCEVExpander Exp(*SE, DL, "induction");
1539   Instruction *FirstInst = nullptr;
1540
1541   for (unsigned i = 0; i < PtrRtCheck.CheckingGroups.size(); ++i) {
1542     const RuntimePointerCheck::CheckingPtrGroup &CG =
1543         PtrRtCheck.CheckingGroups[i];
1544     Value *Ptr = PtrRtCheck.Pointers[CG.Members[0]];
1545     const SCEV *Sc = SE->getSCEV(Ptr);
1546
1547     if (SE->isLoopInvariant(Sc, TheLoop)) {
1548       DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" << *Ptr
1549                    << "\n");
1550       Starts.push_back(Ptr);
1551       Ends.push_back(Ptr);
1552     } else {
1553       unsigned AS = Ptr->getType()->getPointerAddressSpace();
1554
1555       // Use this type for pointer arithmetic.
1556       Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1557       Value *Start = nullptr, *End = nullptr;
1558
1559       DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
1560       Start = Exp.expandCodeFor(CG.Low, PtrArithTy, Loc);
1561       End = Exp.expandCodeFor(CG.High, PtrArithTy, Loc);
1562       DEBUG(dbgs() << "Start: " << *CG.Low << " End: " << *CG.High << "\n");
1563       Starts.push_back(Start);
1564       Ends.push_back(End);
1565     }
1566   }
1567
1568   IRBuilder<> ChkBuilder(Loc);
1569   // Our instructions might fold to a constant.
1570   Value *MemoryRuntimeCheck = nullptr;
1571   for (unsigned i = 0; i < PtrRtCheck.CheckingGroups.size(); ++i) {
1572     for (unsigned j = i + 1; j < PtrRtCheck.CheckingGroups.size(); ++j) {
1573       const RuntimePointerCheck::CheckingPtrGroup &CGI =
1574           PtrRtCheck.CheckingGroups[i];
1575       const RuntimePointerCheck::CheckingPtrGroup &CGJ =
1576           PtrRtCheck.CheckingGroups[j];
1577
1578       if (!PtrRtCheck.needsChecking(CGI, CGJ, PtrPartition))
1579         continue;
1580
1581       unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1582       unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1583
1584       assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1585              (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1586              "Trying to bounds check pointers with different address spaces");
1587
1588       Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1589       Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1590
1591       Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1592       Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1593       Value *End0 =   ChkBuilder.CreateBitCast(Ends[i],   PtrArithTy1, "bc");
1594       Value *End1 =   ChkBuilder.CreateBitCast(Ends[j],   PtrArithTy0, "bc");
1595
1596       Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1597       FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1598       Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1599       FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1600       Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1601       FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1602       if (MemoryRuntimeCheck) {
1603         IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1604                                          "conflict.rdx");
1605         FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1606       }
1607       MemoryRuntimeCheck = IsConflict;
1608     }
1609   }
1610
1611   if (!MemoryRuntimeCheck)
1612     return std::make_pair(nullptr, nullptr);
1613
1614   // We have to do this trickery because the IRBuilder might fold the check to a
1615   // constant expression in which case there is no Instruction anchored in a
1616   // the block.
1617   Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1618                                                  ConstantInt::getTrue(Ctx));
1619   ChkBuilder.Insert(Check, "memcheck.conflict");
1620   FirstInst = getFirstInst(FirstInst, Check, Loc);
1621   return std::make_pair(FirstInst, Check);
1622 }
1623
1624 LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
1625                                const DataLayout &DL,
1626                                const TargetLibraryInfo *TLI, AliasAnalysis *AA,
1627                                DominatorTree *DT, LoopInfo *LI,
1628                                const ValueToValueMap &Strides)
1629     : PtrRtCheck(SE), DepChecker(SE, L), TheLoop(L), SE(SE), DL(DL), TLI(TLI),
1630       AA(AA), DT(DT), LI(LI), NumLoads(0), NumStores(0),
1631       MaxSafeDepDistBytes(-1U), CanVecMem(false),
1632       StoreToLoopInvariantAddress(false) {
1633   if (canAnalyzeLoop())
1634     analyzeLoop(Strides);
1635 }
1636
1637 void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1638   if (CanVecMem) {
1639     if (PtrRtCheck.Need)
1640       OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
1641     else
1642       OS.indent(Depth) << "Memory dependences are safe\n";
1643   }
1644
1645   if (Report)
1646     OS.indent(Depth) << "Report: " << Report->str() << "\n";
1647
1648   if (auto *InterestingDependences = DepChecker.getInterestingDependences()) {
1649     OS.indent(Depth) << "Interesting Dependences:\n";
1650     for (auto &Dep : *InterestingDependences) {
1651       Dep.print(OS, Depth + 2, DepChecker.getMemoryInstructions());
1652       OS << "\n";
1653     }
1654   } else
1655     OS.indent(Depth) << "Too many interesting dependences, not recorded\n";
1656
1657   // List the pair of accesses need run-time checks to prove independence.
1658   PtrRtCheck.print(OS, Depth);
1659   OS << "\n";
1660
1661   OS.indent(Depth) << "Store to invariant address was "
1662                    << (StoreToLoopInvariantAddress ? "" : "not ")
1663                    << "found in loop.\n";
1664 }
1665
1666 const LoopAccessInfo &
1667 LoopAccessAnalysis::getInfo(Loop *L, const ValueToValueMap &Strides) {
1668   auto &LAI = LoopAccessInfoMap[L];
1669
1670 #ifndef NDEBUG
1671   assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
1672          "Symbolic strides changed for loop");
1673 #endif
1674
1675   if (!LAI) {
1676     const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
1677     LAI = llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, LI,
1678                                             Strides);
1679 #ifndef NDEBUG
1680     LAI->NumSymbolicStrides = Strides.size();
1681 #endif
1682   }
1683   return *LAI.get();
1684 }
1685
1686 void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
1687   LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
1688
1689   ValueToValueMap NoSymbolicStrides;
1690
1691   for (Loop *TopLevelLoop : *LI)
1692     for (Loop *L : depth_first(TopLevelLoop)) {
1693       OS.indent(2) << L->getHeader()->getName() << ":\n";
1694       auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
1695       LAI.print(OS, 4);
1696     }
1697 }
1698
1699 bool LoopAccessAnalysis::runOnFunction(Function &F) {
1700   SE = &getAnalysis<ScalarEvolution>();
1701   auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1702   TLI = TLIP ? &TLIP->getTLI() : nullptr;
1703   AA = &getAnalysis<AliasAnalysis>();
1704   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1705   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1706
1707   return false;
1708 }
1709
1710 void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
1711     AU.addRequired<ScalarEvolution>();
1712     AU.addRequired<AliasAnalysis>();
1713     AU.addRequired<DominatorTreeWrapperPass>();
1714     AU.addRequired<LoopInfoWrapperPass>();
1715
1716     AU.setPreservesAll();
1717 }
1718
1719 char LoopAccessAnalysis::ID = 0;
1720 static const char laa_name[] = "Loop Access Analysis";
1721 #define LAA_NAME "loop-accesses"
1722
1723 INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1724 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1725 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1726 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1727 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
1728 INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1729
1730 namespace llvm {
1731   Pass *createLAAPass() {
1732     return new LoopAccessAnalysis();
1733   }
1734 }