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