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