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