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