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