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