1 //===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // The implementation for the loop memory dependence that was originally
11 // developed for the loop vectorizer.
13 //===----------------------------------------------------------------------===//
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"
26 #define DEBUG_TYPE "loop-accesses"
28 void VectorizationReport::emitAnalysis(VectorizationReport &Message,
29 const Function *TheFunction,
31 const char *PassName) {
32 DebugLoc DL = TheLoop->getStartLoc();
33 if (Instruction *I = Message.getInstr())
34 DL = I->getDebugLoc();
35 emitOptimizationRemarkAnalysis(TheFunction->getContext(), PassName,
36 *TheFunction, DL, Message.str());
39 Value *llvm::stripIntegerCast(Value *V) {
40 if (CastInst *CI = dyn_cast<CastInst>(V))
41 if (CI->getOperand(0)->getType()->isIntegerTy())
42 return CI->getOperand(0);
46 const SCEV *llvm::replaceSymbolicStrideSCEV(ScalarEvolution *SE,
47 ValueToValueMap &PtrToStride,
48 Value *Ptr, Value *OrigPtr) {
50 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
52 // If there is an entry in the map return the SCEV of the pointer with the
53 // symbolic stride replaced by one.
54 ValueToValueMap::iterator SI = PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
55 if (SI != PtrToStride.end()) {
56 Value *StrideVal = SI->second;
59 StrideVal = stripIntegerCast(StrideVal);
61 // Replace symbolic stride by one.
62 Value *One = ConstantInt::get(StrideVal->getType(), 1);
63 ValueToValueMap RewriteMap;
64 RewriteMap[StrideVal] = One;
67 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
68 DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
73 // Otherwise, just return the SCEV of the original pointer.
74 return SE->getSCEV(Ptr);
77 void LoopAccessInfo::RuntimePointerCheck::insert(ScalarEvolution *SE, Loop *Lp,
78 Value *Ptr, bool WritePtr,
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);
96 bool LoopAccessInfo::RuntimePointerCheck::needsChecking(unsigned I,
98 // No need to check if two readonly pointers intersect.
99 if (!IsWritePtr[I] && !IsWritePtr[J])
102 // Only need to check pointers between two different dependency sets.
103 if (DependencySetId[I] == DependencySetId[J])
106 // Only need to check pointers in the same alias set.
107 if (AliasSetId[I] != AliasSetId[J])
114 /// \brief Analyses memory accesses in a loop.
116 /// Checks whether run time pointer checks are needed and builds sets for data
117 /// dependence checking.
118 class AccessAnalysis {
120 /// \brief Read or write access location.
121 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
122 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
124 /// \brief Set of potential dependent memory accesses.
125 typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
127 AccessAnalysis(const DataLayout *Dl, AliasAnalysis *AA, DepCandidates &DA) :
128 DL(Dl), AST(*AA), DepCands(DA), IsRTCheckNeeded(false) {}
130 /// \brief Register a load and whether it is only read from.
131 void addLoad(AliasAnalysis::Location &Loc, bool IsReadOnly) {
132 Value *Ptr = const_cast<Value*>(Loc.Ptr);
133 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
134 Accesses.insert(MemAccessInfo(Ptr, false));
136 ReadOnlyPtr.insert(Ptr);
139 /// \brief Register a store.
140 void addStore(AliasAnalysis::Location &Loc) {
141 Value *Ptr = const_cast<Value*>(Loc.Ptr);
142 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
143 Accesses.insert(MemAccessInfo(Ptr, true));
146 /// \brief Check whether we can check the pointers at runtime for
147 /// non-intersection.
148 bool canCheckPtrAtRT(LoopAccessInfo::RuntimePointerCheck &RtCheck,
149 unsigned &NumComparisons,
150 ScalarEvolution *SE, Loop *TheLoop,
151 ValueToValueMap &Strides,
152 bool ShouldCheckStride = false);
154 /// \brief Goes over all memory accesses, checks whether a RT check is needed
155 /// and builds sets of dependent accesses.
156 void buildDependenceSets() {
157 processMemAccesses();
160 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
162 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
163 void resetDepChecks() { CheckDeps.clear(); }
165 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
168 typedef SetVector<MemAccessInfo> PtrAccessSet;
170 /// \brief Go over all memory access and check whether runtime pointer checks
171 /// are needed /// and build sets of dependency check candidates.
172 void processMemAccesses();
174 /// Set of all accesses.
175 PtrAccessSet Accesses;
177 /// Set of accesses that need a further dependence check.
178 MemAccessInfoSet CheckDeps;
180 /// Set of pointers that are read only.
181 SmallPtrSet<Value*, 16> ReadOnlyPtr;
183 const DataLayout *DL;
185 /// An alias set tracker to partition the access set by underlying object and
186 //intrinsic property (such as TBAA metadata).
189 /// Sets of potentially dependent accesses - members of one set share an
190 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
191 /// dependence check.
192 DepCandidates &DepCands;
194 bool IsRTCheckNeeded;
197 } // end anonymous namespace
199 /// \brief Check whether a pointer can participate in a runtime bounds check.
200 static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides,
202 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
203 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
207 return AR->isAffine();
210 /// \brief Check the stride of the pointer and ensure that it does not wrap in
211 /// the address space.
212 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
213 const Loop *Lp, ValueToValueMap &StridesMap);
215 bool AccessAnalysis::canCheckPtrAtRT(
216 LoopAccessInfo::RuntimePointerCheck &RtCheck,
217 unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop,
218 ValueToValueMap &StridesMap, bool ShouldCheckStride) {
219 // Find pointers with computable bounds. We are going to use this information
220 // to place a runtime bound check.
223 bool IsDepCheckNeeded = isDependencyCheckNeeded();
226 // We assign a consecutive id to access from different alias sets.
227 // Accesses between different groups doesn't need to be checked.
229 for (auto &AS : AST) {
230 unsigned NumReadPtrChecks = 0;
231 unsigned NumWritePtrChecks = 0;
233 // We assign consecutive id to access from different dependence sets.
234 // Accesses within the same set don't need a runtime check.
235 unsigned RunningDepId = 1;
236 DenseMap<Value *, unsigned> DepSetId;
239 Value *Ptr = A.getValue();
240 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
241 MemAccessInfo Access(Ptr, IsWrite);
248 if (hasComputableBounds(SE, StridesMap, Ptr) &&
249 // When we run after a failing dependency check we have to make sure we
250 // don't have wrapping pointers.
251 (!ShouldCheckStride ||
252 isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) {
253 // The id of the dependence set.
256 if (IsDepCheckNeeded) {
257 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
258 unsigned &LeaderId = DepSetId[Leader];
260 LeaderId = RunningDepId++;
263 // Each access has its own dependence set.
264 DepId = RunningDepId++;
266 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
268 DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
274 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
275 NumComparisons += 0; // Only one dependence set.
277 NumComparisons += (NumWritePtrChecks * (NumReadPtrChecks +
278 NumWritePtrChecks - 1));
284 // If the pointers that we would use for the bounds comparison have different
285 // address spaces, assume the values aren't directly comparable, so we can't
286 // use them for the runtime check. We also have to assume they could
287 // overlap. In the future there should be metadata for whether address spaces
289 unsigned NumPointers = RtCheck.Pointers.size();
290 for (unsigned i = 0; i < NumPointers; ++i) {
291 for (unsigned j = i + 1; j < NumPointers; ++j) {
292 // Only need to check pointers between two different dependency sets.
293 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
295 // Only need to check pointers in the same alias set.
296 if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j])
299 Value *PtrI = RtCheck.Pointers[i];
300 Value *PtrJ = RtCheck.Pointers[j];
302 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
303 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
305 DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
306 " different address spaces\n");
315 void AccessAnalysis::processMemAccesses() {
316 // We process the set twice: first we process read-write pointers, last we
317 // process read-only pointers. This allows us to skip dependence tests for
318 // read-only pointers.
320 DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
321 DEBUG(dbgs() << " AST: "; AST.dump());
322 DEBUG(dbgs() << "LAA: Accesses:\n");
324 for (auto A : Accesses)
325 dbgs() << "\t" << *A.getPointer() << " (" <<
326 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
327 "read-only" : "read")) << ")\n";
330 // The AliasSetTracker has nicely partitioned our pointers by metadata
331 // compatibility and potential for underlying-object overlap. As a result, we
332 // only need to check for potential pointer dependencies within each alias
334 for (auto &AS : AST) {
335 // Note that both the alias-set tracker and the alias sets themselves used
336 // linked lists internally and so the iteration order here is deterministic
337 // (matching the original instruction order within each set).
339 bool SetHasWrite = false;
341 // Map of pointers to last access encountered.
342 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
343 UnderlyingObjToAccessMap ObjToLastAccess;
345 // Set of access to check after all writes have been processed.
346 PtrAccessSet DeferredAccesses;
348 // Iterate over each alias set twice, once to process read/write pointers,
349 // and then to process read-only pointers.
350 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
351 bool UseDeferred = SetIteration > 0;
352 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
355 Value *Ptr = AV.getValue();
357 // For a single memory access in AliasSetTracker, Accesses may contain
358 // both read and write, and they both need to be handled for CheckDeps.
360 if (AC.getPointer() != Ptr)
363 bool IsWrite = AC.getInt();
365 // If we're using the deferred access set, then it contains only
367 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
368 if (UseDeferred && !IsReadOnlyPtr)
370 // Otherwise, the pointer must be in the PtrAccessSet, either as a
372 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
373 S.count(MemAccessInfo(Ptr, false))) &&
374 "Alias-set pointer not in the access set?");
376 MemAccessInfo Access(Ptr, IsWrite);
377 DepCands.insert(Access);
379 // Memorize read-only pointers for later processing and skip them in
380 // the first round (they need to be checked after we have seen all
381 // write pointers). Note: we also mark pointer that are not
382 // consecutive as "read-only" pointers (so that we check
383 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
384 if (!UseDeferred && IsReadOnlyPtr) {
385 DeferredAccesses.insert(Access);
389 // If this is a write - check other reads and writes for conflicts. If
390 // this is a read only check other writes for conflicts (but only if
391 // there is no other write to the ptr - this is an optimization to
392 // catch "a[i] = a[i] + " without having to do a dependence check).
393 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
394 CheckDeps.insert(Access);
395 IsRTCheckNeeded = true;
401 // Create sets of pointers connected by a shared alias set and
402 // underlying object.
403 typedef SmallVector<Value *, 16> ValueVector;
404 ValueVector TempObjects;
405 GetUnderlyingObjects(Ptr, TempObjects, DL);
406 for (Value *UnderlyingObj : TempObjects) {
407 UnderlyingObjToAccessMap::iterator Prev =
408 ObjToLastAccess.find(UnderlyingObj);
409 if (Prev != ObjToLastAccess.end())
410 DepCands.unionSets(Access, Prev->second);
412 ObjToLastAccess[UnderlyingObj] = Access;
421 /// \brief Checks memory dependences among accesses to the same underlying
422 /// object to determine whether there vectorization is legal or not (and at
423 /// which vectorization factor).
425 /// This class works under the assumption that we already checked that memory
426 /// locations with different underlying pointers are "must-not alias".
427 /// We use the ScalarEvolution framework to symbolically evalutate access
428 /// functions pairs. Since we currently don't restructure the loop we can rely
429 /// on the program order of memory accesses to determine their safety.
430 /// At the moment we will only deem accesses as safe for:
431 /// * A negative constant distance assuming program order.
433 /// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
434 /// a[i] = tmp; y = a[i];
436 /// The latter case is safe because later checks guarantuee that there can't
437 /// be a cycle through a phi node (that is, we check that "x" and "y" is not
438 /// the same variable: a header phi can only be an induction or a reduction, a
439 /// reduction can't have a memory sink, an induction can't have a memory
440 /// source). This is important and must not be violated (or we have to
441 /// resort to checking for cycles through memory).
443 /// * A positive constant distance assuming program order that is bigger
444 /// than the biggest memory access.
446 /// tmp = a[i] OR b[i] = x
447 /// a[i+2] = tmp y = b[i+2];
449 /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
451 /// * Zero distances and all accesses have the same size.
453 class MemoryDepChecker {
455 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
456 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
458 MemoryDepChecker(ScalarEvolution *Se, const DataLayout *Dl, const Loop *L)
459 : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0),
460 ShouldRetryWithRuntimeCheck(false) {}
462 /// \brief Register the location (instructions are given increasing numbers)
463 /// of a write access.
464 void addAccess(StoreInst *SI) {
465 Value *Ptr = SI->getPointerOperand();
466 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
467 InstMap.push_back(SI);
471 /// \brief Register the location (instructions are given increasing numbers)
472 /// of a write access.
473 void addAccess(LoadInst *LI) {
474 Value *Ptr = LI->getPointerOperand();
475 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
476 InstMap.push_back(LI);
480 /// \brief Check whether the dependencies between the accesses are safe.
482 /// Only checks sets with elements in \p CheckDeps.
483 bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
484 MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides);
486 /// \brief The maximum number of bytes of a vector register we can vectorize
487 /// the accesses safely with.
488 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
490 /// \brief In same cases when the dependency check fails we can still
491 /// vectorize the loop with a dynamic array access check.
492 bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
496 const DataLayout *DL;
497 const Loop *InnermostLoop;
499 /// \brief Maps access locations (ptr, read/write) to program order.
500 DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
502 /// \brief Memory access instructions in program order.
503 SmallVector<Instruction *, 16> InstMap;
505 /// \brief The program order index to be used for the next instruction.
508 // We can access this many bytes in parallel safely.
509 unsigned MaxSafeDepDistBytes;
511 /// \brief If we see a non-constant dependence distance we can still try to
512 /// vectorize this loop with runtime checks.
513 bool ShouldRetryWithRuntimeCheck;
515 /// \brief Check whether there is a plausible dependence between the two
518 /// Access \p A must happen before \p B in program order. The two indices
519 /// identify the index into the program order map.
521 /// This function checks whether there is a plausible dependence (or the
522 /// absence of such can't be proved) between the two accesses. If there is a
523 /// plausible dependence but the dependence distance is bigger than one
524 /// element access it records this distance in \p MaxSafeDepDistBytes (if this
525 /// distance is smaller than any other distance encountered so far).
526 /// Otherwise, this function returns true signaling a possible dependence.
527 bool isDependent(const MemAccessInfo &A, unsigned AIdx,
528 const MemAccessInfo &B, unsigned BIdx,
529 ValueToValueMap &Strides);
531 /// \brief Check whether the data dependence could prevent store-load
533 bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
536 } // end anonymous namespace
538 static bool isInBoundsGep(Value *Ptr) {
539 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
540 return GEP->isInBounds();
544 /// \brief Check whether the access through \p Ptr has a constant stride.
545 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
546 const Loop *Lp, ValueToValueMap &StridesMap) {
547 const Type *Ty = Ptr->getType();
548 assert(Ty->isPointerTy() && "Unexpected non-ptr");
550 // Make sure that the pointer does not point to aggregate types.
551 const PointerType *PtrTy = cast<PointerType>(Ty);
552 if (PtrTy->getElementType()->isAggregateType()) {
553 DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
558 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
560 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
562 DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
563 << *Ptr << " SCEV: " << *PtrScev << "\n");
567 // The accesss function must stride over the innermost loop.
568 if (Lp != AR->getLoop()) {
569 DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
570 *Ptr << " SCEV: " << *PtrScev << "\n");
573 // The address calculation must not wrap. Otherwise, a dependence could be
575 // An inbounds getelementptr that is a AddRec with a unit stride
576 // cannot wrap per definition. The unit stride requirement is checked later.
577 // An getelementptr without an inbounds attribute and unit stride would have
578 // to access the pointer value "0" which is undefined behavior in address
579 // space 0, therefore we can also vectorize this case.
580 bool IsInBoundsGEP = isInBoundsGep(Ptr);
581 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
582 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
583 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
584 DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
585 << *Ptr << " SCEV: " << *PtrScev << "\n");
589 // Check the step is constant.
590 const SCEV *Step = AR->getStepRecurrence(*SE);
592 // Calculate the pointer stride and check if it is consecutive.
593 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
595 DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
596 " SCEV: " << *PtrScev << "\n");
600 int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
601 const APInt &APStepVal = C->getValue()->getValue();
603 // Huge step value - give up.
604 if (APStepVal.getBitWidth() > 64)
607 int64_t StepVal = APStepVal.getSExtValue();
610 int64_t Stride = StepVal / Size;
611 int64_t Rem = StepVal % Size;
615 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
616 // know we can't "wrap around the address space". In case of address space
617 // zero we know that this won't happen without triggering undefined behavior.
618 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
619 Stride != 1 && Stride != -1)
625 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
626 unsigned TypeByteSize) {
627 // If loads occur at a distance that is not a multiple of a feasible vector
628 // factor store-load forwarding does not take place.
629 // Positive dependences might cause troubles because vectorizing them might
630 // prevent store-load forwarding making vectorized code run a lot slower.
631 // a[i] = a[i-3] ^ a[i-8];
632 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
633 // hence on your typical architecture store-load forwarding does not take
634 // place. Vectorizing in such cases does not make sense.
635 // Store-load forwarding distance.
636 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
637 // Maximum vector factor.
638 unsigned MaxVFWithoutSLForwardIssues =
639 VectorizerParams::MaxVectorWidth * TypeByteSize;
640 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
641 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
643 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
645 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
646 MaxVFWithoutSLForwardIssues = (vf >>=1);
651 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
652 DEBUG(dbgs() << "LAA: Distance " << Distance <<
653 " that could cause a store-load forwarding conflict\n");
657 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
658 MaxVFWithoutSLForwardIssues !=
659 VectorizerParams::MaxVectorWidth * TypeByteSize)
660 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
664 bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
665 const MemAccessInfo &B, unsigned BIdx,
666 ValueToValueMap &Strides) {
667 assert (AIdx < BIdx && "Must pass arguments in program order");
669 Value *APtr = A.getPointer();
670 Value *BPtr = B.getPointer();
671 bool AIsWrite = A.getInt();
672 bool BIsWrite = B.getInt();
674 // Two reads are independent.
675 if (!AIsWrite && !BIsWrite)
678 // We cannot check pointers in different address spaces.
679 if (APtr->getType()->getPointerAddressSpace() !=
680 BPtr->getType()->getPointerAddressSpace())
683 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
684 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
686 int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides);
687 int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides);
689 const SCEV *Src = AScev;
690 const SCEV *Sink = BScev;
692 // If the induction step is negative we have to invert source and sink of the
694 if (StrideAPtr < 0) {
697 std::swap(APtr, BPtr);
698 std::swap(Src, Sink);
699 std::swap(AIsWrite, BIsWrite);
700 std::swap(AIdx, BIdx);
701 std::swap(StrideAPtr, StrideBPtr);
704 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
706 DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
707 << "(Induction step: " << StrideAPtr << ")\n");
708 DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
709 << *InstMap[BIdx] << ": " << *Dist << "\n");
711 // Need consecutive accesses. We don't want to vectorize
712 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
713 // the address space.
714 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
715 DEBUG(dbgs() << "Non-consecutive pointer access\n");
719 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
721 DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
722 ShouldRetryWithRuntimeCheck = true;
726 Type *ATy = APtr->getType()->getPointerElementType();
727 Type *BTy = BPtr->getType()->getPointerElementType();
728 unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
730 // Negative distances are not plausible dependencies.
731 const APInt &Val = C->getValue()->getValue();
732 if (Val.isNegative()) {
733 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
734 if (IsTrueDataDependence &&
735 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
739 DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
743 // Write to the same location with the same size.
744 // Could be improved to assert type sizes are the same (i32 == float, etc).
748 DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
752 assert(Val.isStrictlyPositive() && "Expect a positive value");
754 // Positive distance bigger than max vectorization factor.
757 "LAA: ReadWrite-Write positive dependency with different types\n");
761 unsigned Distance = (unsigned) Val.getZExtValue();
763 // Bail out early if passed-in parameters make vectorization not feasible.
764 unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
765 VectorizerParams::VectorizationFactor : 1);
766 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
767 VectorizerParams::VectorizationInterleave : 1);
769 // The distance must be bigger than the size needed for a vectorized version
770 // of the operation and the size of the vectorized operation must not be
771 // bigger than the currrent maximum size.
772 if (Distance < 2*TypeByteSize ||
773 2*TypeByteSize > MaxSafeDepDistBytes ||
774 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
775 DEBUG(dbgs() << "LAA: Failure because of Positive distance "
776 << Val.getSExtValue() << '\n');
780 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
781 Distance : MaxSafeDepDistBytes;
783 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
784 if (IsTrueDataDependence &&
785 couldPreventStoreLoadForward(Distance, TypeByteSize))
788 DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue() <<
789 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
794 bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
795 MemAccessInfoSet &CheckDeps,
796 ValueToValueMap &Strides) {
798 MaxSafeDepDistBytes = -1U;
799 while (!CheckDeps.empty()) {
800 MemAccessInfo CurAccess = *CheckDeps.begin();
802 // Get the relevant memory access set.
803 EquivalenceClasses<MemAccessInfo>::iterator I =
804 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
806 // Check accesses within this set.
807 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
808 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
810 // Check every access pair.
812 CheckDeps.erase(*AI);
813 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
815 // Check every accessing instruction pair in program order.
816 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
817 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
818 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
819 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
820 if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
822 if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
833 void LoopAccessInfo::analyzeLoop(ValueToValueMap &Strides) {
835 typedef SmallVector<Value*, 16> ValueVector;
836 typedef SmallPtrSet<Value*, 16> ValueSet;
838 // Holds the Load and Store *instructions*.
842 // Holds all the different accesses in the loop.
843 unsigned NumReads = 0;
844 unsigned NumReadWrites = 0;
846 PtrRtCheck.Pointers.clear();
847 PtrRtCheck.Need = false;
849 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
850 MemoryDepChecker DepChecker(SE, DL, TheLoop);
853 for (Loop::block_iterator bb = TheLoop->block_begin(),
854 be = TheLoop->block_end(); bb != be; ++bb) {
856 // Scan the BB and collect legal loads and stores.
857 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
860 // If this is a load, save it. If this instruction can read from memory
861 // but is not a load, then we quit. Notice that we don't handle function
862 // calls that read or write.
863 if (it->mayReadFromMemory()) {
864 // Many math library functions read the rounding mode. We will only
865 // vectorize a loop if it contains known function calls that don't set
866 // the flag. Therefore, it is safe to ignore this read from memory.
867 CallInst *Call = dyn_cast<CallInst>(it);
868 if (Call && getIntrinsicIDForCall(Call, TLI))
871 LoadInst *Ld = dyn_cast<LoadInst>(it);
872 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
873 emitAnalysis(VectorizationReport(Ld)
874 << "read with atomic ordering or volatile read");
875 DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
881 DepChecker.addAccess(Ld);
885 // Save 'store' instructions. Abort if other instructions write to memory.
886 if (it->mayWriteToMemory()) {
887 StoreInst *St = dyn_cast<StoreInst>(it);
889 emitAnalysis(VectorizationReport(it) <<
890 "instruction cannot be vectorized");
894 if (!St->isSimple() && !IsAnnotatedParallel) {
895 emitAnalysis(VectorizationReport(St)
896 << "write with atomic ordering or volatile write");
897 DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
902 Stores.push_back(St);
903 DepChecker.addAccess(St);
908 // Now we have two lists that hold the loads and the stores.
909 // Next, we find the pointers that they use.
911 // Check if we see any stores. If there are no stores, then we don't
912 // care if the pointers are *restrict*.
913 if (!Stores.size()) {
914 DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
919 AccessAnalysis::DepCandidates DependentAccesses;
920 AccessAnalysis Accesses(DL, AA, DependentAccesses);
922 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
923 // multiple times on the same object. If the ptr is accessed twice, once
924 // for read and once for write, it will only appear once (on the write
925 // list). This is okay, since we are going to check for conflicts between
926 // writes and between reads and writes, but not between reads and reads.
929 ValueVector::iterator I, IE;
930 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
931 StoreInst *ST = cast<StoreInst>(*I);
932 Value* Ptr = ST->getPointerOperand();
934 if (isUniform(Ptr)) {
936 VectorizationReport(ST)
937 << "write to a loop invariant address could not be vectorized");
938 DEBUG(dbgs() << "LAA: We don't allow storing to uniform addresses\n");
943 // If we did *not* see this pointer before, insert it to the read-write
944 // list. At this phase it is only a 'write' list.
945 if (Seen.insert(Ptr).second) {
948 AliasAnalysis::Location Loc = AA->getLocation(ST);
949 // The TBAA metadata could have a control dependency on the predication
950 // condition, so we cannot rely on it when determining whether or not we
951 // need runtime pointer checks.
952 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
953 Loc.AATags.TBAA = nullptr;
955 Accesses.addStore(Loc);
959 if (IsAnnotatedParallel) {
961 << "LAA: A loop annotated parallel, ignore memory dependency "
967 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
968 LoadInst *LD = cast<LoadInst>(*I);
969 Value* Ptr = LD->getPointerOperand();
970 // If we did *not* see this pointer before, insert it to the
971 // read list. If we *did* see it before, then it is already in
972 // the read-write list. This allows us to vectorize expressions
973 // such as A[i] += x; Because the address of A[i] is a read-write
974 // pointer. This only works if the index of A[i] is consecutive.
975 // If the address of i is unknown (for example A[B[i]]) then we may
976 // read a few words, modify, and write a few words, and some of the
977 // words may be written to the same address.
978 bool IsReadOnlyPtr = false;
979 if (Seen.insert(Ptr).second ||
980 !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) {
982 IsReadOnlyPtr = true;
985 AliasAnalysis::Location Loc = AA->getLocation(LD);
986 // The TBAA metadata could have a control dependency on the predication
987 // condition, so we cannot rely on it when determining whether or not we
988 // need runtime pointer checks.
989 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
990 Loc.AATags.TBAA = nullptr;
992 Accesses.addLoad(Loc, IsReadOnlyPtr);
995 // If we write (or read-write) to a single destination and there are no
996 // other reads in this loop then is it safe to vectorize.
997 if (NumReadWrites == 1 && NumReads == 0) {
998 DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
1003 // Build dependence sets and check whether we need a runtime pointer bounds
1005 Accesses.buildDependenceSets();
1006 bool NeedRTCheck = Accesses.isRTCheckNeeded();
1008 // Find pointers with computable bounds. We are going to use this information
1009 // to place a runtime bound check.
1010 unsigned NumComparisons = 0;
1011 bool CanDoRT = false;
1013 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
1016 DEBUG(dbgs() << "LAA: We need to do " << NumComparisons <<
1017 " pointer comparisons.\n");
1019 // If we only have one set of dependences to check pointers among we don't
1020 // need a runtime check.
1021 if (NumComparisons == 0 && NeedRTCheck)
1022 NeedRTCheck = false;
1024 // Check that we did not collect too many pointers or found an unsizeable
1027 NumComparisons > VectorizerParams::RuntimeMemoryCheckThreshold) {
1033 DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
1036 if (NeedRTCheck && !CanDoRT) {
1037 emitAnalysis(VectorizationReport() << "cannot identify array bounds");
1038 DEBUG(dbgs() << "LAA: We can't vectorize because we can't find " <<
1039 "the array bounds.\n");
1045 PtrRtCheck.Need = NeedRTCheck;
1048 if (Accesses.isDependencyCheckNeeded()) {
1049 DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
1050 CanVecMem = DepChecker.areDepsSafe(
1051 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1052 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1054 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
1055 DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
1058 // Clear the dependency checks. We assume they are not needed.
1059 Accesses.resetDepChecks();
1062 PtrRtCheck.Need = true;
1064 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
1065 TheLoop, Strides, true);
1066 // Check that we did not collect too many pointers or found an unsizeable
1069 NumComparisons > VectorizerParams::RuntimeMemoryCheckThreshold) {
1070 if (!CanDoRT && NumComparisons > 0)
1071 emitAnalysis(VectorizationReport()
1072 << "cannot check memory dependencies at runtime");
1074 emitAnalysis(VectorizationReport()
1075 << NumComparisons << " exceeds limit of "
1076 << VectorizerParams::RuntimeMemoryCheckThreshold
1077 << " dependent memory operations checked at runtime");
1078 DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
1089 emitAnalysis(VectorizationReport() <<
1090 "unsafe dependent memory operations in loop");
1092 DEBUG(dbgs() << "LAA: We" << (NeedRTCheck ? "" : " don't") <<
1093 " need a runtime memory check.\n");
1096 bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1097 DominatorTree *DT) {
1098 assert(TheLoop->contains(BB) && "Unknown block used");
1100 // Blocks that do not dominate the latch need predication.
1101 BasicBlock* Latch = TheLoop->getLoopLatch();
1102 return !DT->dominates(BB, Latch);
1105 void LoopAccessInfo::emitAnalysis(VectorizationReport &Message) {
1106 assert(!Report && "Multiple report generated");
1110 bool LoopAccessInfo::isUniform(Value *V) {
1111 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1114 // FIXME: this function is currently a duplicate of the one in
1115 // LoopVectorize.cpp.
1116 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1120 if (Instruction *I = dyn_cast<Instruction>(V))
1121 return I->getParent() == Loc->getParent() ? I : nullptr;
1125 std::pair<Instruction *, Instruction *>
1126 LoopAccessInfo::addRuntimeCheck(Instruction *Loc) {
1127 Instruction *tnullptr = nullptr;
1128 if (!PtrRtCheck.Need)
1129 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1131 unsigned NumPointers = PtrRtCheck.Pointers.size();
1132 SmallVector<TrackingVH<Value> , 2> Starts;
1133 SmallVector<TrackingVH<Value> , 2> Ends;
1135 LLVMContext &Ctx = Loc->getContext();
1136 SCEVExpander Exp(*SE, "induction");
1137 Instruction *FirstInst = nullptr;
1139 for (unsigned i = 0; i < NumPointers; ++i) {
1140 Value *Ptr = PtrRtCheck.Pointers[i];
1141 const SCEV *Sc = SE->getSCEV(Ptr);
1143 if (SE->isLoopInvariant(Sc, TheLoop)) {
1144 DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" <<
1146 Starts.push_back(Ptr);
1147 Ends.push_back(Ptr);
1149 DEBUG(dbgs() << "LAA: Adding RT check for range:" << *Ptr << '\n');
1150 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1152 // Use this type for pointer arithmetic.
1153 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1155 Value *Start = Exp.expandCodeFor(PtrRtCheck.Starts[i], PtrArithTy, Loc);
1156 Value *End = Exp.expandCodeFor(PtrRtCheck.Ends[i], PtrArithTy, Loc);
1157 Starts.push_back(Start);
1158 Ends.push_back(End);
1162 IRBuilder<> ChkBuilder(Loc);
1163 // Our instructions might fold to a constant.
1164 Value *MemoryRuntimeCheck = nullptr;
1165 for (unsigned i = 0; i < NumPointers; ++i) {
1166 for (unsigned j = i+1; j < NumPointers; ++j) {
1167 if (!PtrRtCheck.needsChecking(i, j))
1170 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1171 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1173 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1174 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1175 "Trying to bounds check pointers with different address spaces");
1177 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1178 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1180 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1181 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1182 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
1183 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
1185 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1186 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1187 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1188 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1189 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1190 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1191 if (MemoryRuntimeCheck) {
1192 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1194 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1196 MemoryRuntimeCheck = IsConflict;
1200 // We have to do this trickery because the IRBuilder might fold the check to a
1201 // constant expression in which case there is no Instruction anchored in a
1203 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1204 ConstantInt::getTrue(Ctx));
1205 ChkBuilder.Insert(Check, "memcheck.conflict");
1206 FirstInst = getFirstInst(FirstInst, Check, Loc);
1207 return std::make_pair(FirstInst, Check);
1210 LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
1211 const DataLayout *DL,
1212 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
1213 DominatorTree *DT, ValueToValueMap &Strides)
1214 : TheLoop(L), SE(SE), DL(DL), TLI(TLI), AA(AA), DT(DT), NumLoads(0),
1215 NumStores(0), MaxSafeDepDistBytes(-1U), CanVecMem(false) {
1216 analyzeLoop(Strides);
1219 LoopAccessInfo &LoopAccessAnalysis::getInfo(Loop *L, ValueToValueMap &Strides) {
1220 auto &LAI = LoopAccessInfoMap[L];
1223 assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
1224 "Symbolic strides changed for loop");
1228 LAI = make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, Strides);
1230 LAI->NumSymbolicStrides = Strides.size();
1236 bool LoopAccessAnalysis::runOnFunction(Function &F) {
1237 SE = &getAnalysis<ScalarEvolution>();
1238 DL = F.getParent()->getDataLayout();
1239 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1240 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1241 AA = &getAnalysis<AliasAnalysis>();
1242 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1247 void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
1248 AU.addRequired<ScalarEvolution>();
1249 AU.addRequired<AliasAnalysis>();
1250 AU.addRequired<DominatorTreeWrapperPass>();
1252 AU.setPreservesAll();
1255 char LoopAccessAnalysis::ID = 0;
1256 static const char laa_name[] = "Loop Access Analysis";
1257 #define LAA_NAME "loop-accesses"
1259 INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1260 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1261 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1262 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1263 INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1266 Pass *createLAAPass() {
1267 return new LoopAccessAnalysis();