[LoopAccesses] Add canAnalyzeLoop
[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/ValueTracking.h"
19 #include "llvm/IR/DiagnosticInfo.h"
20 #include "llvm/IR/Dominators.h"
21 #include "llvm/IR/IRBuilder.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Transforms/Utils/VectorUtils.h"
24 using namespace llvm;
25
26 #define DEBUG_TYPE "loop-accesses"
27
28 static cl::opt<unsigned, true>
29 VectorizationFactor("force-vector-width", cl::Hidden,
30                     cl::desc("Sets the SIMD width. Zero is autoselect."),
31                     cl::location(VectorizerParams::VectorizationFactor));
32 unsigned VectorizerParams::VectorizationFactor = 0;
33
34 static cl::opt<unsigned, true>
35 VectorizationInterleave("force-vector-interleave", cl::Hidden,
36                         cl::desc("Sets the vectorization interleave count. "
37                                  "Zero is autoselect."),
38                         cl::location(
39                             VectorizerParams::VectorizationInterleave));
40 unsigned VectorizerParams::VectorizationInterleave = 0;
41
42 /// When performing memory disambiguation checks at runtime do not make more
43 /// than this number of comparisons.
44 const unsigned VectorizerParams::RuntimeMemoryCheckThreshold = 8;
45
46 /// Maximum SIMD width.
47 const unsigned VectorizerParams::MaxVectorWidth = 64;
48
49 bool VectorizerParams::isInterleaveForced() {
50   return ::VectorizationInterleave.getNumOccurrences() > 0;
51 }
52
53 void VectorizationReport::emitAnalysis(VectorizationReport &Message,
54                                        const Function *TheFunction,
55                                        const Loop *TheLoop,
56                                        const char *PassName) {
57   DebugLoc DL = TheLoop->getStartLoc();
58   if (Instruction *I = Message.getInstr())
59     DL = I->getDebugLoc();
60   emitOptimizationRemarkAnalysis(TheFunction->getContext(), PassName,
61                                  *TheFunction, DL, Message.str());
62 }
63
64 Value *llvm::stripIntegerCast(Value *V) {
65   if (CastInst *CI = dyn_cast<CastInst>(V))
66     if (CI->getOperand(0)->getType()->isIntegerTy())
67       return CI->getOperand(0);
68   return V;
69 }
70
71 const SCEV *llvm::replaceSymbolicStrideSCEV(ScalarEvolution *SE,
72                                             ValueToValueMap &PtrToStride,
73                                             Value *Ptr, Value *OrigPtr) {
74
75   const SCEV *OrigSCEV = SE->getSCEV(Ptr);
76
77   // If there is an entry in the map return the SCEV of the pointer with the
78   // symbolic stride replaced by one.
79   ValueToValueMap::iterator SI = PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
80   if (SI != PtrToStride.end()) {
81     Value *StrideVal = SI->second;
82
83     // Strip casts.
84     StrideVal = stripIntegerCast(StrideVal);
85
86     // Replace symbolic stride by one.
87     Value *One = ConstantInt::get(StrideVal->getType(), 1);
88     ValueToValueMap RewriteMap;
89     RewriteMap[StrideVal] = One;
90
91     const SCEV *ByOne =
92         SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
93     DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
94                  << "\n");
95     return ByOne;
96   }
97
98   // Otherwise, just return the SCEV of the original pointer.
99   return SE->getSCEV(Ptr);
100 }
101
102 void LoopAccessInfo::RuntimePointerCheck::insert(ScalarEvolution *SE, Loop *Lp,
103                                                  Value *Ptr, bool WritePtr,
104                                                  unsigned DepSetId,
105                                                  unsigned ASId,
106                                                  ValueToValueMap &Strides) {
107   // Get the stride replaced scev.
108   const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
109   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
110   assert(AR && "Invalid addrec expression");
111   const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
112   const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
113   Pointers.push_back(Ptr);
114   Starts.push_back(AR->getStart());
115   Ends.push_back(ScEnd);
116   IsWritePtr.push_back(WritePtr);
117   DependencySetId.push_back(DepSetId);
118   AliasSetId.push_back(ASId);
119 }
120
121 bool LoopAccessInfo::RuntimePointerCheck::needsChecking(unsigned I,
122                                                         unsigned J) const {
123   // No need to check if two readonly pointers intersect.
124   if (!IsWritePtr[I] && !IsWritePtr[J])
125     return false;
126
127   // Only need to check pointers between two different dependency sets.
128   if (DependencySetId[I] == DependencySetId[J])
129     return false;
130
131   // Only need to check pointers in the same alias set.
132   if (AliasSetId[I] != AliasSetId[J])
133     return false;
134
135   return true;
136 }
137
138 namespace {
139 /// \brief Analyses memory accesses in a loop.
140 ///
141 /// Checks whether run time pointer checks are needed and builds sets for data
142 /// dependence checking.
143 class AccessAnalysis {
144 public:
145   /// \brief Read or write access location.
146   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
147   typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
148
149   /// \brief Set of potential dependent memory accesses.
150   typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
151
152   AccessAnalysis(const DataLayout *Dl, AliasAnalysis *AA, DepCandidates &DA) :
153     DL(Dl), AST(*AA), DepCands(DA), IsRTCheckNeeded(false) {}
154
155   /// \brief Register a load  and whether it is only read from.
156   void addLoad(AliasAnalysis::Location &Loc, bool IsReadOnly) {
157     Value *Ptr = const_cast<Value*>(Loc.Ptr);
158     AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
159     Accesses.insert(MemAccessInfo(Ptr, false));
160     if (IsReadOnly)
161       ReadOnlyPtr.insert(Ptr);
162   }
163
164   /// \brief Register a store.
165   void addStore(AliasAnalysis::Location &Loc) {
166     Value *Ptr = const_cast<Value*>(Loc.Ptr);
167     AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
168     Accesses.insert(MemAccessInfo(Ptr, true));
169   }
170
171   /// \brief Check whether we can check the pointers at runtime for
172   /// non-intersection.
173   bool canCheckPtrAtRT(LoopAccessInfo::RuntimePointerCheck &RtCheck,
174                        unsigned &NumComparisons,
175                        ScalarEvolution *SE, Loop *TheLoop,
176                        ValueToValueMap &Strides,
177                        bool ShouldCheckStride = false);
178
179   /// \brief Goes over all memory accesses, checks whether a RT check is needed
180   /// and builds sets of dependent accesses.
181   void buildDependenceSets() {
182     processMemAccesses();
183   }
184
185   bool isRTCheckNeeded() { return IsRTCheckNeeded; }
186
187   bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
188   void resetDepChecks() { CheckDeps.clear(); }
189
190   MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
191
192 private:
193   typedef SetVector<MemAccessInfo> PtrAccessSet;
194
195   /// \brief Go over all memory access and check whether runtime pointer checks
196   /// are needed /// and build sets of dependency check candidates.
197   void processMemAccesses();
198
199   /// Set of all accesses.
200   PtrAccessSet Accesses;
201
202   /// Set of accesses that need a further dependence check.
203   MemAccessInfoSet CheckDeps;
204
205   /// Set of pointers that are read only.
206   SmallPtrSet<Value*, 16> ReadOnlyPtr;
207
208   const DataLayout *DL;
209
210   /// An alias set tracker to partition the access set by underlying object and
211   //intrinsic property (such as TBAA metadata).
212   AliasSetTracker AST;
213
214   /// Sets of potentially dependent accesses - members of one set share an
215   /// underlying pointer. The set "CheckDeps" identfies which sets really need a
216   /// dependence check.
217   DepCandidates &DepCands;
218
219   bool IsRTCheckNeeded;
220 };
221
222 } // end anonymous namespace
223
224 /// \brief Check whether a pointer can participate in a runtime bounds check.
225 static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides,
226                                 Value *Ptr) {
227   const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
228   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
229   if (!AR)
230     return false;
231
232   return AR->isAffine();
233 }
234
235 /// \brief Check the stride of the pointer and ensure that it does not wrap in
236 /// the address space.
237 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
238                         const Loop *Lp, ValueToValueMap &StridesMap);
239
240 bool AccessAnalysis::canCheckPtrAtRT(
241     LoopAccessInfo::RuntimePointerCheck &RtCheck,
242     unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop,
243     ValueToValueMap &StridesMap, bool ShouldCheckStride) {
244   // Find pointers with computable bounds. We are going to use this information
245   // to place a runtime bound check.
246   bool CanDoRT = true;
247
248   bool IsDepCheckNeeded = isDependencyCheckNeeded();
249   NumComparisons = 0;
250
251   // We assign a consecutive id to access from different alias sets.
252   // Accesses between different groups doesn't need to be checked.
253   unsigned ASId = 1;
254   for (auto &AS : AST) {
255     unsigned NumReadPtrChecks = 0;
256     unsigned NumWritePtrChecks = 0;
257
258     // We assign consecutive id to access from different dependence sets.
259     // Accesses within the same set don't need a runtime check.
260     unsigned RunningDepId = 1;
261     DenseMap<Value *, unsigned> DepSetId;
262
263     for (auto A : AS) {
264       Value *Ptr = A.getValue();
265       bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
266       MemAccessInfo Access(Ptr, IsWrite);
267
268       if (IsWrite)
269         ++NumWritePtrChecks;
270       else
271         ++NumReadPtrChecks;
272
273       if (hasComputableBounds(SE, StridesMap, Ptr) &&
274           // When we run after a failing dependency check we have to make sure we
275           // don't have wrapping pointers.
276           (!ShouldCheckStride ||
277            isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) {
278         // The id of the dependence set.
279         unsigned DepId;
280
281         if (IsDepCheckNeeded) {
282           Value *Leader = DepCands.getLeaderValue(Access).getPointer();
283           unsigned &LeaderId = DepSetId[Leader];
284           if (!LeaderId)
285             LeaderId = RunningDepId++;
286           DepId = LeaderId;
287         } else
288           // Each access has its own dependence set.
289           DepId = RunningDepId++;
290
291         RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
292
293         DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
294       } else {
295         CanDoRT = false;
296       }
297     }
298
299     if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
300       NumComparisons += 0; // Only one dependence set.
301     else {
302       NumComparisons += (NumWritePtrChecks * (NumReadPtrChecks +
303                                               NumWritePtrChecks - 1));
304     }
305
306     ++ASId;
307   }
308
309   // If the pointers that we would use for the bounds comparison have different
310   // address spaces, assume the values aren't directly comparable, so we can't
311   // use them for the runtime check. We also have to assume they could
312   // overlap. In the future there should be metadata for whether address spaces
313   // are disjoint.
314   unsigned NumPointers = RtCheck.Pointers.size();
315   for (unsigned i = 0; i < NumPointers; ++i) {
316     for (unsigned j = i + 1; j < NumPointers; ++j) {
317       // Only need to check pointers between two different dependency sets.
318       if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
319        continue;
320       // Only need to check pointers in the same alias set.
321       if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j])
322         continue;
323
324       Value *PtrI = RtCheck.Pointers[i];
325       Value *PtrJ = RtCheck.Pointers[j];
326
327       unsigned ASi = PtrI->getType()->getPointerAddressSpace();
328       unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
329       if (ASi != ASj) {
330         DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
331                        " different address spaces\n");
332         return false;
333       }
334     }
335   }
336
337   return CanDoRT;
338 }
339
340 void AccessAnalysis::processMemAccesses() {
341   // We process the set twice: first we process read-write pointers, last we
342   // process read-only pointers. This allows us to skip dependence tests for
343   // read-only pointers.
344
345   DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
346   DEBUG(dbgs() << "  AST: "; AST.dump());
347   DEBUG(dbgs() << "LAA:   Accesses:\n");
348   DEBUG({
349     for (auto A : Accesses)
350       dbgs() << "\t" << *A.getPointer() << " (" <<
351                 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
352                                          "read-only" : "read")) << ")\n";
353   });
354
355   // The AliasSetTracker has nicely partitioned our pointers by metadata
356   // compatibility and potential for underlying-object overlap. As a result, we
357   // only need to check for potential pointer dependencies within each alias
358   // set.
359   for (auto &AS : AST) {
360     // Note that both the alias-set tracker and the alias sets themselves used
361     // linked lists internally and so the iteration order here is deterministic
362     // (matching the original instruction order within each set).
363
364     bool SetHasWrite = false;
365
366     // Map of pointers to last access encountered.
367     typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
368     UnderlyingObjToAccessMap ObjToLastAccess;
369
370     // Set of access to check after all writes have been processed.
371     PtrAccessSet DeferredAccesses;
372
373     // Iterate over each alias set twice, once to process read/write pointers,
374     // and then to process read-only pointers.
375     for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
376       bool UseDeferred = SetIteration > 0;
377       PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
378
379       for (auto AV : AS) {
380         Value *Ptr = AV.getValue();
381
382         // For a single memory access in AliasSetTracker, Accesses may contain
383         // both read and write, and they both need to be handled for CheckDeps.
384         for (auto AC : S) {
385           if (AC.getPointer() != Ptr)
386             continue;
387
388           bool IsWrite = AC.getInt();
389
390           // If we're using the deferred access set, then it contains only
391           // reads.
392           bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
393           if (UseDeferred && !IsReadOnlyPtr)
394             continue;
395           // Otherwise, the pointer must be in the PtrAccessSet, either as a
396           // read or a write.
397           assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
398                   S.count(MemAccessInfo(Ptr, false))) &&
399                  "Alias-set pointer not in the access set?");
400
401           MemAccessInfo Access(Ptr, IsWrite);
402           DepCands.insert(Access);
403
404           // Memorize read-only pointers for later processing and skip them in
405           // the first round (they need to be checked after we have seen all
406           // write pointers). Note: we also mark pointer that are not
407           // consecutive as "read-only" pointers (so that we check
408           // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
409           if (!UseDeferred && IsReadOnlyPtr) {
410             DeferredAccesses.insert(Access);
411             continue;
412           }
413
414           // If this is a write - check other reads and writes for conflicts. If
415           // this is a read only check other writes for conflicts (but only if
416           // there is no other write to the ptr - this is an optimization to
417           // catch "a[i] = a[i] + " without having to do a dependence check).
418           if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
419             CheckDeps.insert(Access);
420             IsRTCheckNeeded = true;
421           }
422
423           if (IsWrite)
424             SetHasWrite = true;
425
426           // Create sets of pointers connected by a shared alias set and
427           // underlying object.
428           typedef SmallVector<Value *, 16> ValueVector;
429           ValueVector TempObjects;
430           GetUnderlyingObjects(Ptr, TempObjects, DL);
431           for (Value *UnderlyingObj : TempObjects) {
432             UnderlyingObjToAccessMap::iterator Prev =
433                 ObjToLastAccess.find(UnderlyingObj);
434             if (Prev != ObjToLastAccess.end())
435               DepCands.unionSets(Access, Prev->second);
436
437             ObjToLastAccess[UnderlyingObj] = Access;
438           }
439         }
440       }
441     }
442   }
443 }
444
445 namespace {
446 /// \brief Checks memory dependences among accesses to the same underlying
447 /// object to determine whether there vectorization is legal or not (and at
448 /// which vectorization factor).
449 ///
450 /// This class works under the assumption that we already checked that memory
451 /// locations with different underlying pointers are "must-not alias".
452 /// We use the ScalarEvolution framework to symbolically evalutate access
453 /// functions pairs. Since we currently don't restructure the loop we can rely
454 /// on the program order of memory accesses to determine their safety.
455 /// At the moment we will only deem accesses as safe for:
456 ///  * A negative constant distance assuming program order.
457 ///
458 ///      Safe: tmp = a[i + 1];     OR     a[i + 1] = x;
459 ///            a[i] = tmp;                y = a[i];
460 ///
461 ///   The latter case is safe because later checks guarantuee that there can't
462 ///   be a cycle through a phi node (that is, we check that "x" and "y" is not
463 ///   the same variable: a header phi can only be an induction or a reduction, a
464 ///   reduction can't have a memory sink, an induction can't have a memory
465 ///   source). This is important and must not be violated (or we have to
466 ///   resort to checking for cycles through memory).
467 ///
468 ///  * A positive constant distance assuming program order that is bigger
469 ///    than the biggest memory access.
470 ///
471 ///     tmp = a[i]        OR              b[i] = x
472 ///     a[i+2] = tmp                      y = b[i+2];
473 ///
474 ///     Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
475 ///
476 ///  * Zero distances and all accesses have the same size.
477 ///
478 class MemoryDepChecker {
479 public:
480   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
481   typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
482
483   MemoryDepChecker(ScalarEvolution *Se, const DataLayout *Dl, const Loop *L)
484       : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0),
485         ShouldRetryWithRuntimeCheck(false) {}
486
487   /// \brief Register the location (instructions are given increasing numbers)
488   /// of a write access.
489   void addAccess(StoreInst *SI) {
490     Value *Ptr = SI->getPointerOperand();
491     Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
492     InstMap.push_back(SI);
493     ++AccessIdx;
494   }
495
496   /// \brief Register the location (instructions are given increasing numbers)
497   /// of a write access.
498   void addAccess(LoadInst *LI) {
499     Value *Ptr = LI->getPointerOperand();
500     Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
501     InstMap.push_back(LI);
502     ++AccessIdx;
503   }
504
505   /// \brief Check whether the dependencies between the accesses are safe.
506   ///
507   /// Only checks sets with elements in \p CheckDeps.
508   bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
509                    MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides);
510
511   /// \brief The maximum number of bytes of a vector register we can vectorize
512   /// the accesses safely with.
513   unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
514
515   /// \brief In same cases when the dependency check fails we can still
516   /// vectorize the loop with a dynamic array access check.
517   bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
518
519 private:
520   ScalarEvolution *SE;
521   const DataLayout *DL;
522   const Loop *InnermostLoop;
523
524   /// \brief Maps access locations (ptr, read/write) to program order.
525   DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
526
527   /// \brief Memory access instructions in program order.
528   SmallVector<Instruction *, 16> InstMap;
529
530   /// \brief The program order index to be used for the next instruction.
531   unsigned AccessIdx;
532
533   // We can access this many bytes in parallel safely.
534   unsigned MaxSafeDepDistBytes;
535
536   /// \brief If we see a non-constant dependence distance we can still try to
537   /// vectorize this loop with runtime checks.
538   bool ShouldRetryWithRuntimeCheck;
539
540   /// \brief Check whether there is a plausible dependence between the two
541   /// accesses.
542   ///
543   /// Access \p A must happen before \p B in program order. The two indices
544   /// identify the index into the program order map.
545   ///
546   /// This function checks  whether there is a plausible dependence (or the
547   /// absence of such can't be proved) between the two accesses. If there is a
548   /// plausible dependence but the dependence distance is bigger than one
549   /// element access it records this distance in \p MaxSafeDepDistBytes (if this
550   /// distance is smaller than any other distance encountered so far).
551   /// Otherwise, this function returns true signaling a possible dependence.
552   bool isDependent(const MemAccessInfo &A, unsigned AIdx,
553                    const MemAccessInfo &B, unsigned BIdx,
554                    ValueToValueMap &Strides);
555
556   /// \brief Check whether the data dependence could prevent store-load
557   /// forwarding.
558   bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
559 };
560
561 } // end anonymous namespace
562
563 static bool isInBoundsGep(Value *Ptr) {
564   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
565     return GEP->isInBounds();
566   return false;
567 }
568
569 /// \brief Check whether the access through \p Ptr has a constant stride.
570 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
571                         const Loop *Lp, ValueToValueMap &StridesMap) {
572   const Type *Ty = Ptr->getType();
573   assert(Ty->isPointerTy() && "Unexpected non-ptr");
574
575   // Make sure that the pointer does not point to aggregate types.
576   const PointerType *PtrTy = cast<PointerType>(Ty);
577   if (PtrTy->getElementType()->isAggregateType()) {
578     DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
579           << *Ptr << "\n");
580     return 0;
581   }
582
583   const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
584
585   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
586   if (!AR) {
587     DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
588           << *Ptr << " SCEV: " << *PtrScev << "\n");
589     return 0;
590   }
591
592   // The accesss function must stride over the innermost loop.
593   if (Lp != AR->getLoop()) {
594     DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
595           *Ptr << " SCEV: " << *PtrScev << "\n");
596   }
597
598   // The address calculation must not wrap. Otherwise, a dependence could be
599   // inverted.
600   // An inbounds getelementptr that is a AddRec with a unit stride
601   // cannot wrap per definition. The unit stride requirement is checked later.
602   // An getelementptr without an inbounds attribute and unit stride would have
603   // to access the pointer value "0" which is undefined behavior in address
604   // space 0, therefore we can also vectorize this case.
605   bool IsInBoundsGEP = isInBoundsGep(Ptr);
606   bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
607   bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
608   if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
609     DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
610           << *Ptr << " SCEV: " << *PtrScev << "\n");
611     return 0;
612   }
613
614   // Check the step is constant.
615   const SCEV *Step = AR->getStepRecurrence(*SE);
616
617   // Calculate the pointer stride and check if it is consecutive.
618   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
619   if (!C) {
620     DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
621           " SCEV: " << *PtrScev << "\n");
622     return 0;
623   }
624
625   int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
626   const APInt &APStepVal = C->getValue()->getValue();
627
628   // Huge step value - give up.
629   if (APStepVal.getBitWidth() > 64)
630     return 0;
631
632   int64_t StepVal = APStepVal.getSExtValue();
633
634   // Strided access.
635   int64_t Stride = StepVal / Size;
636   int64_t Rem = StepVal % Size;
637   if (Rem)
638     return 0;
639
640   // If the SCEV could wrap but we have an inbounds gep with a unit stride we
641   // know we can't "wrap around the address space". In case of address space
642   // zero we know that this won't happen without triggering undefined behavior.
643   if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
644       Stride != 1 && Stride != -1)
645     return 0;
646
647   return Stride;
648 }
649
650 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
651                                                     unsigned TypeByteSize) {
652   // If loads occur at a distance that is not a multiple of a feasible vector
653   // factor store-load forwarding does not take place.
654   // Positive dependences might cause troubles because vectorizing them might
655   // prevent store-load forwarding making vectorized code run a lot slower.
656   //   a[i] = a[i-3] ^ a[i-8];
657   //   The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
658   //   hence on your typical architecture store-load forwarding does not take
659   //   place. Vectorizing in such cases does not make sense.
660   // Store-load forwarding distance.
661   const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
662   // Maximum vector factor.
663   unsigned MaxVFWithoutSLForwardIssues =
664     VectorizerParams::MaxVectorWidth * TypeByteSize;
665   if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
666     MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
667
668   for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
669        vf *= 2) {
670     if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
671       MaxVFWithoutSLForwardIssues = (vf >>=1);
672       break;
673     }
674   }
675
676   if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
677     DEBUG(dbgs() << "LAA: Distance " << Distance <<
678           " that could cause a store-load forwarding conflict\n");
679     return true;
680   }
681
682   if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
683       MaxVFWithoutSLForwardIssues !=
684       VectorizerParams::MaxVectorWidth * TypeByteSize)
685     MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
686   return false;
687 }
688
689 bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
690                                    const MemAccessInfo &B, unsigned BIdx,
691                                    ValueToValueMap &Strides) {
692   assert (AIdx < BIdx && "Must pass arguments in program order");
693
694   Value *APtr = A.getPointer();
695   Value *BPtr = B.getPointer();
696   bool AIsWrite = A.getInt();
697   bool BIsWrite = B.getInt();
698
699   // Two reads are independent.
700   if (!AIsWrite && !BIsWrite)
701     return false;
702
703   // We cannot check pointers in different address spaces.
704   if (APtr->getType()->getPointerAddressSpace() !=
705       BPtr->getType()->getPointerAddressSpace())
706     return true;
707
708   const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
709   const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
710
711   int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides);
712   int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides);
713
714   const SCEV *Src = AScev;
715   const SCEV *Sink = BScev;
716
717   // If the induction step is negative we have to invert source and sink of the
718   // dependence.
719   if (StrideAPtr < 0) {
720     //Src = BScev;
721     //Sink = AScev;
722     std::swap(APtr, BPtr);
723     std::swap(Src, Sink);
724     std::swap(AIsWrite, BIsWrite);
725     std::swap(AIdx, BIdx);
726     std::swap(StrideAPtr, StrideBPtr);
727   }
728
729   const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
730
731   DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
732         << "(Induction step: " << StrideAPtr <<  ")\n");
733   DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
734         << *InstMap[BIdx] << ": " << *Dist << "\n");
735
736   // Need consecutive accesses. We don't want to vectorize
737   // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
738   // the address space.
739   if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
740     DEBUG(dbgs() << "Non-consecutive pointer access\n");
741     return true;
742   }
743
744   const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
745   if (!C) {
746     DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
747     ShouldRetryWithRuntimeCheck = true;
748     return true;
749   }
750
751   Type *ATy = APtr->getType()->getPointerElementType();
752   Type *BTy = BPtr->getType()->getPointerElementType();
753   unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
754
755   // Negative distances are not plausible dependencies.
756   const APInt &Val = C->getValue()->getValue();
757   if (Val.isNegative()) {
758     bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
759     if (IsTrueDataDependence &&
760         (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
761          ATy != BTy))
762       return true;
763
764     DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
765     return false;
766   }
767
768   // Write to the same location with the same size.
769   // Could be improved to assert type sizes are the same (i32 == float, etc).
770   if (Val == 0) {
771     if (ATy == BTy)
772       return false;
773     DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
774     return true;
775   }
776
777   assert(Val.isStrictlyPositive() && "Expect a positive value");
778
779   // Positive distance bigger than max vectorization factor.
780   if (ATy != BTy) {
781     DEBUG(dbgs() <<
782           "LAA: ReadWrite-Write positive dependency with different types\n");
783     return false;
784   }
785
786   unsigned Distance = (unsigned) Val.getZExtValue();
787
788   // Bail out early if passed-in parameters make vectorization not feasible.
789   unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
790                            VectorizerParams::VectorizationFactor : 1);
791   unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
792                            VectorizerParams::VectorizationInterleave : 1);
793
794   // The distance must be bigger than the size needed for a vectorized version
795   // of the operation and the size of the vectorized operation must not be
796   // bigger than the currrent maximum size.
797   if (Distance < 2*TypeByteSize ||
798       2*TypeByteSize > MaxSafeDepDistBytes ||
799       Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
800     DEBUG(dbgs() << "LAA: Failure because of Positive distance "
801         << Val.getSExtValue() << '\n');
802     return true;
803   }
804
805   MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
806     Distance : MaxSafeDepDistBytes;
807
808   bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
809   if (IsTrueDataDependence &&
810       couldPreventStoreLoadForward(Distance, TypeByteSize))
811      return true;
812
813   DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue() <<
814         " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
815
816   return false;
817 }
818
819 bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
820                                    MemAccessInfoSet &CheckDeps,
821                                    ValueToValueMap &Strides) {
822
823   MaxSafeDepDistBytes = -1U;
824   while (!CheckDeps.empty()) {
825     MemAccessInfo CurAccess = *CheckDeps.begin();
826
827     // Get the relevant memory access set.
828     EquivalenceClasses<MemAccessInfo>::iterator I =
829       AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
830
831     // Check accesses within this set.
832     EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
833     AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
834
835     // Check every access pair.
836     while (AI != AE) {
837       CheckDeps.erase(*AI);
838       EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
839       while (OI != AE) {
840         // Check every accessing instruction pair in program order.
841         for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
842              I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
843           for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
844                I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
845             if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
846               return false;
847             if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
848               return false;
849           }
850         ++OI;
851       }
852       AI++;
853     }
854   }
855   return true;
856 }
857
858 bool LoopAccessInfo::canAnalyzeLoop() {
859     // We can only analyze innermost loops.
860   if (!TheLoop->empty()) {
861     emitAnalysis(VectorizationReport() << "loop is not the innermost loop");
862     return false;
863   }
864
865   // We must have a single backedge.
866   if (TheLoop->getNumBackEdges() != 1) {
867     emitAnalysis(
868         VectorizationReport() <<
869         "loop control flow is not understood by analyzer");
870     return false;
871   }
872
873   // We must have a single exiting block.
874   if (!TheLoop->getExitingBlock()) {
875     emitAnalysis(
876         VectorizationReport() <<
877         "loop control flow is not understood by analyzer");
878     return false;
879   }
880
881   // We only handle bottom-tested loops, i.e. loop in which the condition is
882   // checked at the end of each iteration. With that we can assume that all
883   // instructions in the loop are executed the same number of times.
884   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
885     emitAnalysis(
886         VectorizationReport() <<
887         "loop control flow is not understood by analyzer");
888     return false;
889   }
890
891   // We need to have a loop header.
892   DEBUG(dbgs() << "LAA: Found a loop: " <<
893         TheLoop->getHeader()->getName() << '\n');
894
895   // ScalarEvolution needs to be able to find the exit count.
896   const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
897   if (ExitCount == SE->getCouldNotCompute()) {
898     emitAnalysis(VectorizationReport() <<
899                  "could not determine number of loop iterations");
900     DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
901     return false;
902   }
903
904   return true;
905 }
906
907 void LoopAccessInfo::analyzeLoop(ValueToValueMap &Strides) {
908
909   typedef SmallVector<Value*, 16> ValueVector;
910   typedef SmallPtrSet<Value*, 16> ValueSet;
911
912   // Holds the Load and Store *instructions*.
913   ValueVector Loads;
914   ValueVector Stores;
915
916   // Holds all the different accesses in the loop.
917   unsigned NumReads = 0;
918   unsigned NumReadWrites = 0;
919
920   PtrRtCheck.Pointers.clear();
921   PtrRtCheck.Need = false;
922
923   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
924   MemoryDepChecker DepChecker(SE, DL, TheLoop);
925
926   // For each block.
927   for (Loop::block_iterator bb = TheLoop->block_begin(),
928        be = TheLoop->block_end(); bb != be; ++bb) {
929
930     // Scan the BB and collect legal loads and stores.
931     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
932          ++it) {
933
934       // If this is a load, save it. If this instruction can read from memory
935       // but is not a load, then we quit. Notice that we don't handle function
936       // calls that read or write.
937       if (it->mayReadFromMemory()) {
938         // Many math library functions read the rounding mode. We will only
939         // vectorize a loop if it contains known function calls that don't set
940         // the flag. Therefore, it is safe to ignore this read from memory.
941         CallInst *Call = dyn_cast<CallInst>(it);
942         if (Call && getIntrinsicIDForCall(Call, TLI))
943           continue;
944
945         LoadInst *Ld = dyn_cast<LoadInst>(it);
946         if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
947           emitAnalysis(VectorizationReport(Ld)
948                        << "read with atomic ordering or volatile read");
949           DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
950           CanVecMem = false;
951           return;
952         }
953         NumLoads++;
954         Loads.push_back(Ld);
955         DepChecker.addAccess(Ld);
956         continue;
957       }
958
959       // Save 'store' instructions. Abort if other instructions write to memory.
960       if (it->mayWriteToMemory()) {
961         StoreInst *St = dyn_cast<StoreInst>(it);
962         if (!St) {
963           emitAnalysis(VectorizationReport(it) <<
964                        "instruction cannot be vectorized");
965           CanVecMem = false;
966           return;
967         }
968         if (!St->isSimple() && !IsAnnotatedParallel) {
969           emitAnalysis(VectorizationReport(St)
970                        << "write with atomic ordering or volatile write");
971           DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
972           CanVecMem = false;
973           return;
974         }
975         NumStores++;
976         Stores.push_back(St);
977         DepChecker.addAccess(St);
978       }
979     } // Next instr.
980   } // Next block.
981
982   // Now we have two lists that hold the loads and the stores.
983   // Next, we find the pointers that they use.
984
985   // Check if we see any stores. If there are no stores, then we don't
986   // care if the pointers are *restrict*.
987   if (!Stores.size()) {
988     DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
989     CanVecMem = true;
990     return;
991   }
992
993   AccessAnalysis::DepCandidates DependentAccesses;
994   AccessAnalysis Accesses(DL, AA, DependentAccesses);
995
996   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
997   // multiple times on the same object. If the ptr is accessed twice, once
998   // for read and once for write, it will only appear once (on the write
999   // list). This is okay, since we are going to check for conflicts between
1000   // writes and between reads and writes, but not between reads and reads.
1001   ValueSet Seen;
1002
1003   ValueVector::iterator I, IE;
1004   for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1005     StoreInst *ST = cast<StoreInst>(*I);
1006     Value* Ptr = ST->getPointerOperand();
1007
1008     if (isUniform(Ptr)) {
1009       emitAnalysis(
1010           VectorizationReport(ST)
1011           << "write to a loop invariant address could not be vectorized");
1012       DEBUG(dbgs() << "LAA: We don't allow storing to uniform addresses\n");
1013       CanVecMem = false;
1014       return;
1015     }
1016
1017     // If we did *not* see this pointer before, insert it to  the read-write
1018     // list. At this phase it is only a 'write' list.
1019     if (Seen.insert(Ptr).second) {
1020       ++NumReadWrites;
1021
1022       AliasAnalysis::Location Loc = AA->getLocation(ST);
1023       // The TBAA metadata could have a control dependency on the predication
1024       // condition, so we cannot rely on it when determining whether or not we
1025       // need runtime pointer checks.
1026       if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
1027         Loc.AATags.TBAA = nullptr;
1028
1029       Accesses.addStore(Loc);
1030     }
1031   }
1032
1033   if (IsAnnotatedParallel) {
1034     DEBUG(dbgs()
1035           << "LAA: A loop annotated parallel, ignore memory dependency "
1036           << "checks.\n");
1037     CanVecMem = true;
1038     return;
1039   }
1040
1041   for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1042     LoadInst *LD = cast<LoadInst>(*I);
1043     Value* Ptr = LD->getPointerOperand();
1044     // If we did *not* see this pointer before, insert it to the
1045     // read list. If we *did* see it before, then it is already in
1046     // the read-write list. This allows us to vectorize expressions
1047     // such as A[i] += x;  Because the address of A[i] is a read-write
1048     // pointer. This only works if the index of A[i] is consecutive.
1049     // If the address of i is unknown (for example A[B[i]]) then we may
1050     // read a few words, modify, and write a few words, and some of the
1051     // words may be written to the same address.
1052     bool IsReadOnlyPtr = false;
1053     if (Seen.insert(Ptr).second ||
1054         !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) {
1055       ++NumReads;
1056       IsReadOnlyPtr = true;
1057     }
1058
1059     AliasAnalysis::Location Loc = AA->getLocation(LD);
1060     // The TBAA metadata could have a control dependency on the predication
1061     // condition, so we cannot rely on it when determining whether or not we
1062     // need runtime pointer checks.
1063     if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
1064       Loc.AATags.TBAA = nullptr;
1065
1066     Accesses.addLoad(Loc, IsReadOnlyPtr);
1067   }
1068
1069   // If we write (or read-write) to a single destination and there are no
1070   // other reads in this loop then is it safe to vectorize.
1071   if (NumReadWrites == 1 && NumReads == 0) {
1072     DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
1073     CanVecMem = true;
1074     return;
1075   }
1076
1077   // Build dependence sets and check whether we need a runtime pointer bounds
1078   // check.
1079   Accesses.buildDependenceSets();
1080   bool NeedRTCheck = Accesses.isRTCheckNeeded();
1081
1082   // Find pointers with computable bounds. We are going to use this information
1083   // to place a runtime bound check.
1084   unsigned NumComparisons = 0;
1085   bool CanDoRT = false;
1086   if (NeedRTCheck)
1087     CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
1088                                        Strides);
1089
1090   DEBUG(dbgs() << "LAA: We need to do " << NumComparisons <<
1091         " pointer comparisons.\n");
1092
1093   // If we only have one set of dependences to check pointers among we don't
1094   // need a runtime check.
1095   if (NumComparisons == 0 && NeedRTCheck)
1096     NeedRTCheck = false;
1097
1098   // Check that we did not collect too many pointers or found an unsizeable
1099   // pointer.
1100   if (!CanDoRT ||
1101       NumComparisons > VectorizerParams::RuntimeMemoryCheckThreshold) {
1102     PtrRtCheck.reset();
1103     CanDoRT = false;
1104   }
1105
1106   if (CanDoRT) {
1107     DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
1108   }
1109
1110   if (NeedRTCheck && !CanDoRT) {
1111     emitAnalysis(VectorizationReport() << "cannot identify array bounds");
1112     DEBUG(dbgs() << "LAA: We can't vectorize because we can't find " <<
1113           "the array bounds.\n");
1114     PtrRtCheck.reset();
1115     CanVecMem = false;
1116     return;
1117   }
1118
1119   PtrRtCheck.Need = NeedRTCheck;
1120
1121   CanVecMem = true;
1122   if (Accesses.isDependencyCheckNeeded()) {
1123     DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
1124     CanVecMem = DepChecker.areDepsSafe(
1125         DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1126     MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1127
1128     if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
1129       DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
1130       NeedRTCheck = true;
1131
1132       // Clear the dependency checks. We assume they are not needed.
1133       Accesses.resetDepChecks();
1134
1135       PtrRtCheck.reset();
1136       PtrRtCheck.Need = true;
1137
1138       CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
1139                                          TheLoop, Strides, true);
1140       // Check that we did not collect too many pointers or found an unsizeable
1141       // pointer.
1142       if (!CanDoRT ||
1143           NumComparisons > VectorizerParams::RuntimeMemoryCheckThreshold) {
1144         if (!CanDoRT && NumComparisons > 0)
1145           emitAnalysis(VectorizationReport()
1146                        << "cannot check memory dependencies at runtime");
1147         else
1148           emitAnalysis(VectorizationReport()
1149                        << NumComparisons << " exceeds limit of "
1150                        << VectorizerParams::RuntimeMemoryCheckThreshold
1151                        << " dependent memory operations checked at runtime");
1152         DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
1153         PtrRtCheck.reset();
1154         CanVecMem = false;
1155         return;
1156       }
1157
1158       CanVecMem = true;
1159     }
1160   }
1161
1162   if (!CanVecMem)
1163     emitAnalysis(VectorizationReport() <<
1164                  "unsafe dependent memory operations in loop");
1165
1166   DEBUG(dbgs() << "LAA: We" << (NeedRTCheck ? "" : " don't") <<
1167         " need a runtime memory check.\n");
1168 }
1169
1170 bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1171                                            DominatorTree *DT)  {
1172   assert(TheLoop->contains(BB) && "Unknown block used");
1173
1174   // Blocks that do not dominate the latch need predication.
1175   BasicBlock* Latch = TheLoop->getLoopLatch();
1176   return !DT->dominates(BB, Latch);
1177 }
1178
1179 void LoopAccessInfo::emitAnalysis(VectorizationReport &Message) {
1180   assert(!Report && "Multiple reports generated");
1181   Report = Message;
1182 }
1183
1184 bool LoopAccessInfo::isUniform(Value *V) {
1185   return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1186 }
1187
1188 // FIXME: this function is currently a duplicate of the one in
1189 // LoopVectorize.cpp.
1190 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1191                                  Instruction *Loc) {
1192   if (FirstInst)
1193     return FirstInst;
1194   if (Instruction *I = dyn_cast<Instruction>(V))
1195     return I->getParent() == Loc->getParent() ? I : nullptr;
1196   return nullptr;
1197 }
1198
1199 std::pair<Instruction *, Instruction *>
1200 LoopAccessInfo::addRuntimeCheck(Instruction *Loc) {
1201   Instruction *tnullptr = nullptr;
1202   if (!PtrRtCheck.Need)
1203     return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1204
1205   unsigned NumPointers = PtrRtCheck.Pointers.size();
1206   SmallVector<TrackingVH<Value> , 2> Starts;
1207   SmallVector<TrackingVH<Value> , 2> Ends;
1208
1209   LLVMContext &Ctx = Loc->getContext();
1210   SCEVExpander Exp(*SE, "induction");
1211   Instruction *FirstInst = nullptr;
1212
1213   for (unsigned i = 0; i < NumPointers; ++i) {
1214     Value *Ptr = PtrRtCheck.Pointers[i];
1215     const SCEV *Sc = SE->getSCEV(Ptr);
1216
1217     if (SE->isLoopInvariant(Sc, TheLoop)) {
1218       DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" <<
1219             *Ptr <<"\n");
1220       Starts.push_back(Ptr);
1221       Ends.push_back(Ptr);
1222     } else {
1223       DEBUG(dbgs() << "LAA: Adding RT check for range:" << *Ptr << '\n');
1224       unsigned AS = Ptr->getType()->getPointerAddressSpace();
1225
1226       // Use this type for pointer arithmetic.
1227       Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1228
1229       Value *Start = Exp.expandCodeFor(PtrRtCheck.Starts[i], PtrArithTy, Loc);
1230       Value *End = Exp.expandCodeFor(PtrRtCheck.Ends[i], PtrArithTy, Loc);
1231       Starts.push_back(Start);
1232       Ends.push_back(End);
1233     }
1234   }
1235
1236   IRBuilder<> ChkBuilder(Loc);
1237   // Our instructions might fold to a constant.
1238   Value *MemoryRuntimeCheck = nullptr;
1239   for (unsigned i = 0; i < NumPointers; ++i) {
1240     for (unsigned j = i+1; j < NumPointers; ++j) {
1241       if (!PtrRtCheck.needsChecking(i, j))
1242         continue;
1243
1244       unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1245       unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1246
1247       assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1248              (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1249              "Trying to bounds check pointers with different address spaces");
1250
1251       Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1252       Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1253
1254       Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1255       Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1256       Value *End0 =   ChkBuilder.CreateBitCast(Ends[i],   PtrArithTy1, "bc");
1257       Value *End1 =   ChkBuilder.CreateBitCast(Ends[j],   PtrArithTy0, "bc");
1258
1259       Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1260       FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1261       Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1262       FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1263       Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1264       FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1265       if (MemoryRuntimeCheck) {
1266         IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1267                                          "conflict.rdx");
1268         FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1269       }
1270       MemoryRuntimeCheck = IsConflict;
1271     }
1272   }
1273
1274   // We have to do this trickery because the IRBuilder might fold the check to a
1275   // constant expression in which case there is no Instruction anchored in a
1276   // the block.
1277   Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1278                                                  ConstantInt::getTrue(Ctx));
1279   ChkBuilder.Insert(Check, "memcheck.conflict");
1280   FirstInst = getFirstInst(FirstInst, Check, Loc);
1281   return std::make_pair(FirstInst, Check);
1282 }
1283
1284 LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
1285                                const DataLayout *DL,
1286                                const TargetLibraryInfo *TLI, AliasAnalysis *AA,
1287                                DominatorTree *DT, ValueToValueMap &Strides)
1288     : TheLoop(L), SE(SE), DL(DL), TLI(TLI), AA(AA), DT(DT), NumLoads(0),
1289       NumStores(0), MaxSafeDepDistBytes(-1U), CanVecMem(false) {
1290   if (canAnalyzeLoop())
1291     analyzeLoop(Strides);
1292 }
1293
1294 LoopAccessInfo &LoopAccessAnalysis::getInfo(Loop *L, ValueToValueMap &Strides) {
1295   auto &LAI = LoopAccessInfoMap[L];
1296
1297 #ifndef NDEBUG
1298   assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
1299          "Symbolic strides changed for loop");
1300 #endif
1301
1302   if (!LAI) {
1303     LAI = llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, Strides);
1304 #ifndef NDEBUG
1305     LAI->NumSymbolicStrides = Strides.size();
1306 #endif
1307   }
1308   return *LAI.get();
1309 }
1310
1311 bool LoopAccessAnalysis::runOnFunction(Function &F) {
1312   SE = &getAnalysis<ScalarEvolution>();
1313   DL = F.getParent()->getDataLayout();
1314   auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1315   TLI = TLIP ? &TLIP->getTLI() : nullptr;
1316   AA = &getAnalysis<AliasAnalysis>();
1317   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1318
1319   return false;
1320 }
1321
1322 void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
1323     AU.addRequired<ScalarEvolution>();
1324     AU.addRequired<AliasAnalysis>();
1325     AU.addRequired<DominatorTreeWrapperPass>();
1326
1327     AU.setPreservesAll();
1328 }
1329
1330 char LoopAccessAnalysis::ID = 0;
1331 static const char laa_name[] = "Loop Access Analysis";
1332 #define LAA_NAME "loop-accesses"
1333
1334 INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1335 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1336 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1337 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1338 INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1339
1340 namespace llvm {
1341   Pass *createLAAPass() {
1342     return new LoopAccessAnalysis();
1343   }
1344 }