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 static cl::opt<unsigned, true>
29 VectorizationFactor("force-vector-width", cl::Hidden,
30 cl::desc("Sets the SIMD width. Zero is autoselect."),
31 cl::location(VectorizerParams::VectorizationFactor));
32 unsigned VectorizerParams::VectorizationFactor = 0;
34 static cl::opt<unsigned, true>
35 VectorizationInterleave("force-vector-interleave", cl::Hidden,
36 cl::desc("Sets the vectorization interleave count. "
37 "Zero is autoselect."),
39 VectorizerParams::VectorizationInterleave));
40 unsigned VectorizerParams::VectorizationInterleave = 0;
42 /// When performing memory disambiguation checks at runtime do not make more
43 /// than this number of comparisons.
44 const unsigned VectorizerParams::RuntimeMemoryCheckThreshold = 8;
46 /// Maximum SIMD width.
47 const unsigned VectorizerParams::MaxVectorWidth = 64;
49 bool VectorizerParams::isInterleaveForced() {
50 return ::VectorizationInterleave.getNumOccurrences() > 0;
53 void LoopAccessReport::emitAnalysis(const LoopAccessReport &Message,
54 const Function *TheFunction,
56 const char *PassName) {
57 DebugLoc DL = TheLoop->getStartLoc();
58 if (const Instruction *I = Message.getInstr())
59 DL = I->getDebugLoc();
60 emitOptimizationRemarkAnalysis(TheFunction->getContext(), PassName,
61 *TheFunction, DL, Message.str());
64 Value *llvm::stripIntegerCast(Value *V) {
65 if (CastInst *CI = dyn_cast<CastInst>(V))
66 if (CI->getOperand(0)->getType()->isIntegerTy())
67 return CI->getOperand(0);
71 const SCEV *llvm::replaceSymbolicStrideSCEV(ScalarEvolution *SE,
72 ValueToValueMap &PtrToStride,
73 Value *Ptr, Value *OrigPtr) {
75 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
77 // If there is an entry in the map return the SCEV of the pointer with the
78 // symbolic stride replaced by one.
79 ValueToValueMap::iterator SI = PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
80 if (SI != PtrToStride.end()) {
81 Value *StrideVal = SI->second;
84 StrideVal = stripIntegerCast(StrideVal);
86 // Replace symbolic stride by one.
87 Value *One = ConstantInt::get(StrideVal->getType(), 1);
88 ValueToValueMap RewriteMap;
89 RewriteMap[StrideVal] = One;
92 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
93 DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
98 // Otherwise, just return the SCEV of the original pointer.
99 return SE->getSCEV(Ptr);
102 void LoopAccessInfo::RuntimePointerCheck::insert(ScalarEvolution *SE, Loop *Lp,
103 Value *Ptr, bool WritePtr,
106 ValueToValueMap &Strides) {
107 // Get the stride replaced scev.
108 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
109 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
110 assert(AR && "Invalid addrec expression");
111 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
112 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
113 Pointers.push_back(Ptr);
114 Starts.push_back(AR->getStart());
115 Ends.push_back(ScEnd);
116 IsWritePtr.push_back(WritePtr);
117 DependencySetId.push_back(DepSetId);
118 AliasSetId.push_back(ASId);
121 bool LoopAccessInfo::RuntimePointerCheck::needsChecking(unsigned I,
123 // No need to check if two readonly pointers intersect.
124 if (!IsWritePtr[I] && !IsWritePtr[J])
127 // Only need to check pointers between two different dependency sets.
128 if (DependencySetId[I] == DependencySetId[J])
131 // Only need to check pointers in the same alias set.
132 if (AliasSetId[I] != AliasSetId[J])
138 void LoopAccessInfo::RuntimePointerCheck::print(raw_ostream &OS,
139 unsigned Depth) const {
140 unsigned NumPointers = Pointers.size();
141 if (NumPointers == 0)
144 OS.indent(Depth) << "Run-time memory checks:\n";
146 for (unsigned I = 0; I < NumPointers; ++I)
147 for (unsigned J = I + 1; J < NumPointers; ++J)
148 if (needsChecking(I, J)) {
149 OS.indent(Depth) << N++ << ":\n";
150 OS.indent(Depth + 2) << *Pointers[I] << "\n";
151 OS.indent(Depth + 2) << *Pointers[J] << "\n";
156 /// \brief Analyses memory accesses in a loop.
158 /// Checks whether run time pointer checks are needed and builds sets for data
159 /// dependence checking.
160 class AccessAnalysis {
162 /// \brief Read or write access location.
163 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
164 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
166 /// \brief Set of potential dependent memory accesses.
167 typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
169 AccessAnalysis(const DataLayout *Dl, AliasAnalysis *AA, DepCandidates &DA) :
170 DL(Dl), AST(*AA), DepCands(DA), IsRTCheckNeeded(false) {}
172 /// \brief Register a load and whether it is only read from.
173 void addLoad(AliasAnalysis::Location &Loc, bool IsReadOnly) {
174 Value *Ptr = const_cast<Value*>(Loc.Ptr);
175 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
176 Accesses.insert(MemAccessInfo(Ptr, false));
178 ReadOnlyPtr.insert(Ptr);
181 /// \brief Register a store.
182 void addStore(AliasAnalysis::Location &Loc) {
183 Value *Ptr = const_cast<Value*>(Loc.Ptr);
184 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
185 Accesses.insert(MemAccessInfo(Ptr, true));
188 /// \brief Check whether we can check the pointers at runtime for
189 /// non-intersection.
190 bool canCheckPtrAtRT(LoopAccessInfo::RuntimePointerCheck &RtCheck,
191 unsigned &NumComparisons,
192 ScalarEvolution *SE, Loop *TheLoop,
193 ValueToValueMap &Strides,
194 bool ShouldCheckStride = false);
196 /// \brief Goes over all memory accesses, checks whether a RT check is needed
197 /// and builds sets of dependent accesses.
198 void buildDependenceSets() {
199 processMemAccesses();
202 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
204 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
205 void resetDepChecks() { CheckDeps.clear(); }
207 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
210 typedef SetVector<MemAccessInfo> PtrAccessSet;
212 /// \brief Go over all memory access and check whether runtime pointer checks
213 /// are needed /// and build sets of dependency check candidates.
214 void processMemAccesses();
216 /// Set of all accesses.
217 PtrAccessSet Accesses;
219 /// Set of accesses that need a further dependence check.
220 MemAccessInfoSet CheckDeps;
222 /// Set of pointers that are read only.
223 SmallPtrSet<Value*, 16> ReadOnlyPtr;
225 const DataLayout *DL;
227 /// An alias set tracker to partition the access set by underlying object and
228 //intrinsic property (such as TBAA metadata).
231 /// Sets of potentially dependent accesses - members of one set share an
232 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
233 /// dependence check.
234 DepCandidates &DepCands;
236 bool IsRTCheckNeeded;
239 } // end anonymous namespace
241 /// \brief Check whether a pointer can participate in a runtime bounds check.
242 static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides,
244 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
245 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
249 return AR->isAffine();
252 /// \brief Check the stride of the pointer and ensure that it does not wrap in
253 /// the address space.
254 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
255 const Loop *Lp, ValueToValueMap &StridesMap);
257 bool AccessAnalysis::canCheckPtrAtRT(
258 LoopAccessInfo::RuntimePointerCheck &RtCheck,
259 unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop,
260 ValueToValueMap &StridesMap, bool ShouldCheckStride) {
261 // Find pointers with computable bounds. We are going to use this information
262 // to place a runtime bound check.
265 bool IsDepCheckNeeded = isDependencyCheckNeeded();
268 // We assign a consecutive id to access from different alias sets.
269 // Accesses between different groups doesn't need to be checked.
271 for (auto &AS : AST) {
272 unsigned NumReadPtrChecks = 0;
273 unsigned NumWritePtrChecks = 0;
275 // We assign consecutive id to access from different dependence sets.
276 // Accesses within the same set don't need a runtime check.
277 unsigned RunningDepId = 1;
278 DenseMap<Value *, unsigned> DepSetId;
281 Value *Ptr = A.getValue();
282 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
283 MemAccessInfo Access(Ptr, IsWrite);
290 if (hasComputableBounds(SE, StridesMap, Ptr) &&
291 // When we run after a failing dependency check we have to make sure we
292 // don't have wrapping pointers.
293 (!ShouldCheckStride ||
294 isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) {
295 // The id of the dependence set.
298 if (IsDepCheckNeeded) {
299 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
300 unsigned &LeaderId = DepSetId[Leader];
302 LeaderId = RunningDepId++;
305 // Each access has its own dependence set.
306 DepId = RunningDepId++;
308 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
310 DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
316 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
317 NumComparisons += 0; // Only one dependence set.
319 NumComparisons += (NumWritePtrChecks * (NumReadPtrChecks +
320 NumWritePtrChecks - 1));
326 // If the pointers that we would use for the bounds comparison have different
327 // address spaces, assume the values aren't directly comparable, so we can't
328 // use them for the runtime check. We also have to assume they could
329 // overlap. In the future there should be metadata for whether address spaces
331 unsigned NumPointers = RtCheck.Pointers.size();
332 for (unsigned i = 0; i < NumPointers; ++i) {
333 for (unsigned j = i + 1; j < NumPointers; ++j) {
334 // Only need to check pointers between two different dependency sets.
335 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
337 // Only need to check pointers in the same alias set.
338 if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j])
341 Value *PtrI = RtCheck.Pointers[i];
342 Value *PtrJ = RtCheck.Pointers[j];
344 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
345 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
347 DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
348 " different address spaces\n");
357 void AccessAnalysis::processMemAccesses() {
358 // We process the set twice: first we process read-write pointers, last we
359 // process read-only pointers. This allows us to skip dependence tests for
360 // read-only pointers.
362 DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
363 DEBUG(dbgs() << " AST: "; AST.dump());
364 DEBUG(dbgs() << "LAA: Accesses:\n");
366 for (auto A : Accesses)
367 dbgs() << "\t" << *A.getPointer() << " (" <<
368 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
369 "read-only" : "read")) << ")\n";
372 // The AliasSetTracker has nicely partitioned our pointers by metadata
373 // compatibility and potential for underlying-object overlap. As a result, we
374 // only need to check for potential pointer dependencies within each alias
376 for (auto &AS : AST) {
377 // Note that both the alias-set tracker and the alias sets themselves used
378 // linked lists internally and so the iteration order here is deterministic
379 // (matching the original instruction order within each set).
381 bool SetHasWrite = false;
383 // Map of pointers to last access encountered.
384 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
385 UnderlyingObjToAccessMap ObjToLastAccess;
387 // Set of access to check after all writes have been processed.
388 PtrAccessSet DeferredAccesses;
390 // Iterate over each alias set twice, once to process read/write pointers,
391 // and then to process read-only pointers.
392 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
393 bool UseDeferred = SetIteration > 0;
394 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
397 Value *Ptr = AV.getValue();
399 // For a single memory access in AliasSetTracker, Accesses may contain
400 // both read and write, and they both need to be handled for CheckDeps.
402 if (AC.getPointer() != Ptr)
405 bool IsWrite = AC.getInt();
407 // If we're using the deferred access set, then it contains only
409 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
410 if (UseDeferred && !IsReadOnlyPtr)
412 // Otherwise, the pointer must be in the PtrAccessSet, either as a
414 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
415 S.count(MemAccessInfo(Ptr, false))) &&
416 "Alias-set pointer not in the access set?");
418 MemAccessInfo Access(Ptr, IsWrite);
419 DepCands.insert(Access);
421 // Memorize read-only pointers for later processing and skip them in
422 // the first round (they need to be checked after we have seen all
423 // write pointers). Note: we also mark pointer that are not
424 // consecutive as "read-only" pointers (so that we check
425 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
426 if (!UseDeferred && IsReadOnlyPtr) {
427 DeferredAccesses.insert(Access);
431 // If this is a write - check other reads and writes for conflicts. If
432 // this is a read only check other writes for conflicts (but only if
433 // there is no other write to the ptr - this is an optimization to
434 // catch "a[i] = a[i] + " without having to do a dependence check).
435 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
436 CheckDeps.insert(Access);
437 IsRTCheckNeeded = true;
443 // Create sets of pointers connected by a shared alias set and
444 // underlying object.
445 typedef SmallVector<Value *, 16> ValueVector;
446 ValueVector TempObjects;
447 GetUnderlyingObjects(Ptr, TempObjects, DL);
448 for (Value *UnderlyingObj : TempObjects) {
449 UnderlyingObjToAccessMap::iterator Prev =
450 ObjToLastAccess.find(UnderlyingObj);
451 if (Prev != ObjToLastAccess.end())
452 DepCands.unionSets(Access, Prev->second);
454 ObjToLastAccess[UnderlyingObj] = Access;
463 /// \brief Checks memory dependences among accesses to the same underlying
464 /// object to determine whether there vectorization is legal or not (and at
465 /// which vectorization factor).
467 /// This class works under the assumption that we already checked that memory
468 /// locations with different underlying pointers are "must-not alias".
469 /// We use the ScalarEvolution framework to symbolically evalutate access
470 /// functions pairs. Since we currently don't restructure the loop we can rely
471 /// on the program order of memory accesses to determine their safety.
472 /// At the moment we will only deem accesses as safe for:
473 /// * A negative constant distance assuming program order.
475 /// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
476 /// a[i] = tmp; y = a[i];
478 /// The latter case is safe because later checks guarantuee that there can't
479 /// be a cycle through a phi node (that is, we check that "x" and "y" is not
480 /// the same variable: a header phi can only be an induction or a reduction, a
481 /// reduction can't have a memory sink, an induction can't have a memory
482 /// source). This is important and must not be violated (or we have to
483 /// resort to checking for cycles through memory).
485 /// * A positive constant distance assuming program order that is bigger
486 /// than the biggest memory access.
488 /// tmp = a[i] OR b[i] = x
489 /// a[i+2] = tmp y = b[i+2];
491 /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
493 /// * Zero distances and all accesses have the same size.
495 class MemoryDepChecker {
497 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
498 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
500 MemoryDepChecker(ScalarEvolution *Se, const DataLayout *Dl, const Loop *L)
501 : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0),
502 ShouldRetryWithRuntimeCheck(false) {}
504 /// \brief Register the location (instructions are given increasing numbers)
505 /// of a write access.
506 void addAccess(StoreInst *SI) {
507 Value *Ptr = SI->getPointerOperand();
508 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
509 InstMap.push_back(SI);
513 /// \brief Register the location (instructions are given increasing numbers)
514 /// of a write access.
515 void addAccess(LoadInst *LI) {
516 Value *Ptr = LI->getPointerOperand();
517 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
518 InstMap.push_back(LI);
522 /// \brief Check whether the dependencies between the accesses are safe.
524 /// Only checks sets with elements in \p CheckDeps.
525 bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
526 MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides);
528 /// \brief The maximum number of bytes of a vector register we can vectorize
529 /// the accesses safely with.
530 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
532 /// \brief In same cases when the dependency check fails we can still
533 /// vectorize the loop with a dynamic array access check.
534 bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
538 const DataLayout *DL;
539 const Loop *InnermostLoop;
541 /// \brief Maps access locations (ptr, read/write) to program order.
542 DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
544 /// \brief Memory access instructions in program order.
545 SmallVector<Instruction *, 16> InstMap;
547 /// \brief The program order index to be used for the next instruction.
550 // We can access this many bytes in parallel safely.
551 unsigned MaxSafeDepDistBytes;
553 /// \brief If we see a non-constant dependence distance we can still try to
554 /// vectorize this loop with runtime checks.
555 bool ShouldRetryWithRuntimeCheck;
557 /// \brief Check whether there is a plausible dependence between the two
560 /// Access \p A must happen before \p B in program order. The two indices
561 /// identify the index into the program order map.
563 /// This function checks whether there is a plausible dependence (or the
564 /// absence of such can't be proved) between the two accesses. If there is a
565 /// plausible dependence but the dependence distance is bigger than one
566 /// element access it records this distance in \p MaxSafeDepDistBytes (if this
567 /// distance is smaller than any other distance encountered so far).
568 /// Otherwise, this function returns true signaling a possible dependence.
569 bool isDependent(const MemAccessInfo &A, unsigned AIdx,
570 const MemAccessInfo &B, unsigned BIdx,
571 ValueToValueMap &Strides);
573 /// \brief Check whether the data dependence could prevent store-load
575 bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
578 } // end anonymous namespace
580 static bool isInBoundsGep(Value *Ptr) {
581 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
582 return GEP->isInBounds();
586 /// \brief Check whether the access through \p Ptr has a constant stride.
587 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
588 const Loop *Lp, ValueToValueMap &StridesMap) {
589 const Type *Ty = Ptr->getType();
590 assert(Ty->isPointerTy() && "Unexpected non-ptr");
592 // Make sure that the pointer does not point to aggregate types.
593 const PointerType *PtrTy = cast<PointerType>(Ty);
594 if (PtrTy->getElementType()->isAggregateType()) {
595 DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
600 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
602 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
604 DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
605 << *Ptr << " SCEV: " << *PtrScev << "\n");
609 // The accesss function must stride over the innermost loop.
610 if (Lp != AR->getLoop()) {
611 DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
612 *Ptr << " SCEV: " << *PtrScev << "\n");
615 // The address calculation must not wrap. Otherwise, a dependence could be
617 // An inbounds getelementptr that is a AddRec with a unit stride
618 // cannot wrap per definition. The unit stride requirement is checked later.
619 // An getelementptr without an inbounds attribute and unit stride would have
620 // to access the pointer value "0" which is undefined behavior in address
621 // space 0, therefore we can also vectorize this case.
622 bool IsInBoundsGEP = isInBoundsGep(Ptr);
623 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
624 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
625 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
626 DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
627 << *Ptr << " SCEV: " << *PtrScev << "\n");
631 // Check the step is constant.
632 const SCEV *Step = AR->getStepRecurrence(*SE);
634 // Calculate the pointer stride and check if it is consecutive.
635 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
637 DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
638 " SCEV: " << *PtrScev << "\n");
642 int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
643 const APInt &APStepVal = C->getValue()->getValue();
645 // Huge step value - give up.
646 if (APStepVal.getBitWidth() > 64)
649 int64_t StepVal = APStepVal.getSExtValue();
652 int64_t Stride = StepVal / Size;
653 int64_t Rem = StepVal % Size;
657 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
658 // know we can't "wrap around the address space". In case of address space
659 // zero we know that this won't happen without triggering undefined behavior.
660 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
661 Stride != 1 && Stride != -1)
667 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
668 unsigned TypeByteSize) {
669 // If loads occur at a distance that is not a multiple of a feasible vector
670 // factor store-load forwarding does not take place.
671 // Positive dependences might cause troubles because vectorizing them might
672 // prevent store-load forwarding making vectorized code run a lot slower.
673 // a[i] = a[i-3] ^ a[i-8];
674 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
675 // hence on your typical architecture store-load forwarding does not take
676 // place. Vectorizing in such cases does not make sense.
677 // Store-load forwarding distance.
678 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
679 // Maximum vector factor.
680 unsigned MaxVFWithoutSLForwardIssues =
681 VectorizerParams::MaxVectorWidth * TypeByteSize;
682 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
683 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
685 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
687 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
688 MaxVFWithoutSLForwardIssues = (vf >>=1);
693 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
694 DEBUG(dbgs() << "LAA: Distance " << Distance <<
695 " that could cause a store-load forwarding conflict\n");
699 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
700 MaxVFWithoutSLForwardIssues !=
701 VectorizerParams::MaxVectorWidth * TypeByteSize)
702 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
706 bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
707 const MemAccessInfo &B, unsigned BIdx,
708 ValueToValueMap &Strides) {
709 assert (AIdx < BIdx && "Must pass arguments in program order");
711 Value *APtr = A.getPointer();
712 Value *BPtr = B.getPointer();
713 bool AIsWrite = A.getInt();
714 bool BIsWrite = B.getInt();
716 // Two reads are independent.
717 if (!AIsWrite && !BIsWrite)
720 // We cannot check pointers in different address spaces.
721 if (APtr->getType()->getPointerAddressSpace() !=
722 BPtr->getType()->getPointerAddressSpace())
725 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
726 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
728 int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides);
729 int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides);
731 const SCEV *Src = AScev;
732 const SCEV *Sink = BScev;
734 // If the induction step is negative we have to invert source and sink of the
736 if (StrideAPtr < 0) {
739 std::swap(APtr, BPtr);
740 std::swap(Src, Sink);
741 std::swap(AIsWrite, BIsWrite);
742 std::swap(AIdx, BIdx);
743 std::swap(StrideAPtr, StrideBPtr);
746 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
748 DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
749 << "(Induction step: " << StrideAPtr << ")\n");
750 DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
751 << *InstMap[BIdx] << ": " << *Dist << "\n");
753 // Need consecutive accesses. We don't want to vectorize
754 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
755 // the address space.
756 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
757 DEBUG(dbgs() << "Non-consecutive pointer access\n");
761 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
763 DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
764 ShouldRetryWithRuntimeCheck = true;
768 Type *ATy = APtr->getType()->getPointerElementType();
769 Type *BTy = BPtr->getType()->getPointerElementType();
770 unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
772 // Negative distances are not plausible dependencies.
773 const APInt &Val = C->getValue()->getValue();
774 if (Val.isNegative()) {
775 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
776 if (IsTrueDataDependence &&
777 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
781 DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
785 // Write to the same location with the same size.
786 // Could be improved to assert type sizes are the same (i32 == float, etc).
790 DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
794 assert(Val.isStrictlyPositive() && "Expect a positive value");
796 // Positive distance bigger than max vectorization factor.
799 "LAA: ReadWrite-Write positive dependency with different types\n");
803 unsigned Distance = (unsigned) Val.getZExtValue();
805 // Bail out early if passed-in parameters make vectorization not feasible.
806 unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
807 VectorizerParams::VectorizationFactor : 1);
808 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
809 VectorizerParams::VectorizationInterleave : 1);
811 // The distance must be bigger than the size needed for a vectorized version
812 // of the operation and the size of the vectorized operation must not be
813 // bigger than the currrent maximum size.
814 if (Distance < 2*TypeByteSize ||
815 2*TypeByteSize > MaxSafeDepDistBytes ||
816 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
817 DEBUG(dbgs() << "LAA: Failure because of Positive distance "
818 << Val.getSExtValue() << '\n');
822 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
823 Distance : MaxSafeDepDistBytes;
825 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
826 if (IsTrueDataDependence &&
827 couldPreventStoreLoadForward(Distance, TypeByteSize))
830 DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue() <<
831 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
836 bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
837 MemAccessInfoSet &CheckDeps,
838 ValueToValueMap &Strides) {
840 MaxSafeDepDistBytes = -1U;
841 while (!CheckDeps.empty()) {
842 MemAccessInfo CurAccess = *CheckDeps.begin();
844 // Get the relevant memory access set.
845 EquivalenceClasses<MemAccessInfo>::iterator I =
846 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
848 // Check accesses within this set.
849 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
850 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
852 // Check every access pair.
854 CheckDeps.erase(*AI);
855 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
857 // Check every accessing instruction pair in program order.
858 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
859 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
860 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
861 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
862 if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
864 if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
875 bool LoopAccessInfo::canAnalyzeLoop() {
876 // We can only analyze innermost loops.
877 if (!TheLoop->empty()) {
878 emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
882 // We must have a single backedge.
883 if (TheLoop->getNumBackEdges() != 1) {
885 LoopAccessReport() <<
886 "loop control flow is not understood by analyzer");
890 // We must have a single exiting block.
891 if (!TheLoop->getExitingBlock()) {
893 LoopAccessReport() <<
894 "loop control flow is not understood by analyzer");
898 // We only handle bottom-tested loops, i.e. loop in which the condition is
899 // checked at the end of each iteration. With that we can assume that all
900 // instructions in the loop are executed the same number of times.
901 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
903 LoopAccessReport() <<
904 "loop control flow is not understood by analyzer");
908 // We need to have a loop header.
909 DEBUG(dbgs() << "LAA: Found a loop: " <<
910 TheLoop->getHeader()->getName() << '\n');
912 // ScalarEvolution needs to be able to find the exit count.
913 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
914 if (ExitCount == SE->getCouldNotCompute()) {
915 emitAnalysis(LoopAccessReport() <<
916 "could not determine number of loop iterations");
917 DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
924 void LoopAccessInfo::analyzeLoop(ValueToValueMap &Strides) {
926 typedef SmallVector<Value*, 16> ValueVector;
927 typedef SmallPtrSet<Value*, 16> ValueSet;
929 // Holds the Load and Store *instructions*.
933 // Holds all the different accesses in the loop.
934 unsigned NumReads = 0;
935 unsigned NumReadWrites = 0;
937 PtrRtCheck.Pointers.clear();
938 PtrRtCheck.Need = false;
940 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
941 MemoryDepChecker DepChecker(SE, DL, TheLoop);
944 for (Loop::block_iterator bb = TheLoop->block_begin(),
945 be = TheLoop->block_end(); bb != be; ++bb) {
947 // Scan the BB and collect legal loads and stores.
948 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
951 // If this is a load, save it. If this instruction can read from memory
952 // but is not a load, then we quit. Notice that we don't handle function
953 // calls that read or write.
954 if (it->mayReadFromMemory()) {
955 // Many math library functions read the rounding mode. We will only
956 // vectorize a loop if it contains known function calls that don't set
957 // the flag. Therefore, it is safe to ignore this read from memory.
958 CallInst *Call = dyn_cast<CallInst>(it);
959 if (Call && getIntrinsicIDForCall(Call, TLI))
962 LoadInst *Ld = dyn_cast<LoadInst>(it);
963 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
964 emitAnalysis(LoopAccessReport(Ld)
965 << "read with atomic ordering or volatile read");
966 DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
972 DepChecker.addAccess(Ld);
976 // Save 'store' instructions. Abort if other instructions write to memory.
977 if (it->mayWriteToMemory()) {
978 StoreInst *St = dyn_cast<StoreInst>(it);
980 emitAnalysis(LoopAccessReport(it) <<
981 "instruction cannot be vectorized");
985 if (!St->isSimple() && !IsAnnotatedParallel) {
986 emitAnalysis(LoopAccessReport(St)
987 << "write with atomic ordering or volatile write");
988 DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
993 Stores.push_back(St);
994 DepChecker.addAccess(St);
999 // Now we have two lists that hold the loads and the stores.
1000 // Next, we find the pointers that they use.
1002 // Check if we see any stores. If there are no stores, then we don't
1003 // care if the pointers are *restrict*.
1004 if (!Stores.size()) {
1005 DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
1010 AccessAnalysis::DepCandidates DependentAccesses;
1011 AccessAnalysis Accesses(DL, AA, DependentAccesses);
1013 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1014 // multiple times on the same object. If the ptr is accessed twice, once
1015 // for read and once for write, it will only appear once (on the write
1016 // list). This is okay, since we are going to check for conflicts between
1017 // writes and between reads and writes, but not between reads and reads.
1020 ValueVector::iterator I, IE;
1021 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1022 StoreInst *ST = cast<StoreInst>(*I);
1023 Value* Ptr = ST->getPointerOperand();
1025 if (isUniform(Ptr)) {
1027 LoopAccessReport(ST)
1028 << "write to a loop invariant address could not be vectorized");
1029 DEBUG(dbgs() << "LAA: We don't allow storing to uniform addresses\n");
1034 // If we did *not* see this pointer before, insert it to the read-write
1035 // list. At this phase it is only a 'write' list.
1036 if (Seen.insert(Ptr).second) {
1039 AliasAnalysis::Location Loc = AA->getLocation(ST);
1040 // The TBAA metadata could have a control dependency on the predication
1041 // condition, so we cannot rely on it when determining whether or not we
1042 // need runtime pointer checks.
1043 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
1044 Loc.AATags.TBAA = nullptr;
1046 Accesses.addStore(Loc);
1050 if (IsAnnotatedParallel) {
1052 << "LAA: A loop annotated parallel, ignore memory dependency "
1058 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1059 LoadInst *LD = cast<LoadInst>(*I);
1060 Value* Ptr = LD->getPointerOperand();
1061 // If we did *not* see this pointer before, insert it to the
1062 // read list. If we *did* see it before, then it is already in
1063 // the read-write list. This allows us to vectorize expressions
1064 // such as A[i] += x; Because the address of A[i] is a read-write
1065 // pointer. This only works if the index of A[i] is consecutive.
1066 // If the address of i is unknown (for example A[B[i]]) then we may
1067 // read a few words, modify, and write a few words, and some of the
1068 // words may be written to the same address.
1069 bool IsReadOnlyPtr = false;
1070 if (Seen.insert(Ptr).second ||
1071 !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) {
1073 IsReadOnlyPtr = true;
1076 AliasAnalysis::Location Loc = AA->getLocation(LD);
1077 // The TBAA metadata could have a control dependency on the predication
1078 // condition, so we cannot rely on it when determining whether or not we
1079 // need runtime pointer checks.
1080 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
1081 Loc.AATags.TBAA = nullptr;
1083 Accesses.addLoad(Loc, IsReadOnlyPtr);
1086 // If we write (or read-write) to a single destination and there are no
1087 // other reads in this loop then is it safe to vectorize.
1088 if (NumReadWrites == 1 && NumReads == 0) {
1089 DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
1094 // Build dependence sets and check whether we need a runtime pointer bounds
1096 Accesses.buildDependenceSets();
1097 bool NeedRTCheck = Accesses.isRTCheckNeeded();
1099 // Find pointers with computable bounds. We are going to use this information
1100 // to place a runtime bound check.
1101 unsigned NumComparisons = 0;
1102 bool CanDoRT = false;
1104 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
1107 DEBUG(dbgs() << "LAA: We need to do " << NumComparisons <<
1108 " pointer comparisons.\n");
1110 // If we only have one set of dependences to check pointers among we don't
1111 // need a runtime check.
1112 if (NumComparisons == 0 && NeedRTCheck)
1113 NeedRTCheck = false;
1115 // Check that we did not collect too many pointers or found an unsizeable
1118 NumComparisons > VectorizerParams::RuntimeMemoryCheckThreshold) {
1124 DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
1127 if (NeedRTCheck && !CanDoRT) {
1128 emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
1129 DEBUG(dbgs() << "LAA: We can't vectorize because we can't find " <<
1130 "the array bounds.\n");
1136 PtrRtCheck.Need = NeedRTCheck;
1139 if (Accesses.isDependencyCheckNeeded()) {
1140 DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
1141 CanVecMem = DepChecker.areDepsSafe(
1142 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1143 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1145 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
1146 DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
1149 // Clear the dependency checks. We assume they are not needed.
1150 Accesses.resetDepChecks();
1153 PtrRtCheck.Need = true;
1155 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
1156 TheLoop, Strides, true);
1157 // Check that we did not collect too many pointers or found an unsizeable
1160 NumComparisons > VectorizerParams::RuntimeMemoryCheckThreshold) {
1161 if (!CanDoRT && NumComparisons > 0)
1162 emitAnalysis(LoopAccessReport()
1163 << "cannot check memory dependencies at runtime");
1165 emitAnalysis(LoopAccessReport()
1166 << NumComparisons << " exceeds limit of "
1167 << VectorizerParams::RuntimeMemoryCheckThreshold
1168 << " dependent memory operations checked at runtime");
1169 DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
1180 emitAnalysis(LoopAccessReport() <<
1181 "unsafe dependent memory operations in loop");
1183 DEBUG(dbgs() << "LAA: We" << (NeedRTCheck ? "" : " don't") <<
1184 " need a runtime memory check.\n");
1187 bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1188 DominatorTree *DT) {
1189 assert(TheLoop->contains(BB) && "Unknown block used");
1191 // Blocks that do not dominate the latch need predication.
1192 BasicBlock* Latch = TheLoop->getLoopLatch();
1193 return !DT->dominates(BB, Latch);
1196 void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
1197 assert(!Report && "Multiple reports generated");
1201 bool LoopAccessInfo::isUniform(Value *V) const {
1202 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1205 // FIXME: this function is currently a duplicate of the one in
1206 // LoopVectorize.cpp.
1207 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1211 if (Instruction *I = dyn_cast<Instruction>(V))
1212 return I->getParent() == Loc->getParent() ? I : nullptr;
1216 std::pair<Instruction *, Instruction *>
1217 LoopAccessInfo::addRuntimeCheck(Instruction *Loc) const {
1218 Instruction *tnullptr = nullptr;
1219 if (!PtrRtCheck.Need)
1220 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1222 unsigned NumPointers = PtrRtCheck.Pointers.size();
1223 SmallVector<TrackingVH<Value> , 2> Starts;
1224 SmallVector<TrackingVH<Value> , 2> Ends;
1226 LLVMContext &Ctx = Loc->getContext();
1227 SCEVExpander Exp(*SE, "induction");
1228 Instruction *FirstInst = nullptr;
1230 for (unsigned i = 0; i < NumPointers; ++i) {
1231 Value *Ptr = PtrRtCheck.Pointers[i];
1232 const SCEV *Sc = SE->getSCEV(Ptr);
1234 if (SE->isLoopInvariant(Sc, TheLoop)) {
1235 DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" <<
1237 Starts.push_back(Ptr);
1238 Ends.push_back(Ptr);
1240 DEBUG(dbgs() << "LAA: Adding RT check for range:" << *Ptr << '\n');
1241 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1243 // Use this type for pointer arithmetic.
1244 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1246 Value *Start = Exp.expandCodeFor(PtrRtCheck.Starts[i], PtrArithTy, Loc);
1247 Value *End = Exp.expandCodeFor(PtrRtCheck.Ends[i], PtrArithTy, Loc);
1248 Starts.push_back(Start);
1249 Ends.push_back(End);
1253 IRBuilder<> ChkBuilder(Loc);
1254 // Our instructions might fold to a constant.
1255 Value *MemoryRuntimeCheck = nullptr;
1256 for (unsigned i = 0; i < NumPointers; ++i) {
1257 for (unsigned j = i+1; j < NumPointers; ++j) {
1258 if (!PtrRtCheck.needsChecking(i, j))
1261 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1262 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1264 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1265 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1266 "Trying to bounds check pointers with different address spaces");
1268 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1269 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1271 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1272 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1273 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
1274 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
1276 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1277 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1278 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1279 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1280 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1281 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1282 if (MemoryRuntimeCheck) {
1283 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1285 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1287 MemoryRuntimeCheck = IsConflict;
1291 // We have to do this trickery because the IRBuilder might fold the check to a
1292 // constant expression in which case there is no Instruction anchored in a
1294 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1295 ConstantInt::getTrue(Ctx));
1296 ChkBuilder.Insert(Check, "memcheck.conflict");
1297 FirstInst = getFirstInst(FirstInst, Check, Loc);
1298 return std::make_pair(FirstInst, Check);
1301 LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
1302 const DataLayout *DL,
1303 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
1304 DominatorTree *DT, ValueToValueMap &Strides)
1305 : TheLoop(L), SE(SE), DL(DL), TLI(TLI), AA(AA), DT(DT), NumLoads(0),
1306 NumStores(0), MaxSafeDepDistBytes(-1U), CanVecMem(false) {
1307 if (canAnalyzeLoop())
1308 analyzeLoop(Strides);
1311 void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1313 if (PtrRtCheck.empty())
1314 OS.indent(Depth) << "Memory dependences are safe\n";
1316 OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
1320 OS.indent(Depth) << "Report: " << Report->str() << "\n";
1322 // FIXME: Print unsafe dependences
1324 // List the pair of accesses need run-time checks to prove independence.
1325 PtrRtCheck.print(OS, Depth);
1329 const LoopAccessInfo &LoopAccessAnalysis::getInfo(Loop *L,
1330 ValueToValueMap &Strides) {
1331 auto &LAI = LoopAccessInfoMap[L];
1334 assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
1335 "Symbolic strides changed for loop");
1339 LAI = llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, Strides);
1341 LAI->NumSymbolicStrides = Strides.size();
1347 void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
1348 LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
1350 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1351 ValueToValueMap NoSymbolicStrides;
1353 for (Loop *TopLevelLoop : *LI)
1354 for (Loop *L : depth_first(TopLevelLoop)) {
1355 OS.indent(2) << L->getHeader()->getName() << ":\n";
1356 auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
1361 bool LoopAccessAnalysis::runOnFunction(Function &F) {
1362 SE = &getAnalysis<ScalarEvolution>();
1363 DL = F.getParent()->getDataLayout();
1364 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1365 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1366 AA = &getAnalysis<AliasAnalysis>();
1367 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1372 void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
1373 AU.addRequired<ScalarEvolution>();
1374 AU.addRequired<AliasAnalysis>();
1375 AU.addRequired<DominatorTreeWrapperPass>();
1376 AU.addRequired<LoopInfoWrapperPass>();
1378 AU.setPreservesAll();
1381 char LoopAccessAnalysis::ID = 0;
1382 static const char laa_name[] = "Loop Access Analysis";
1383 #define LAA_NAME "loop-accesses"
1385 INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1386 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1387 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1388 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1389 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
1390 INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1393 Pass *createLAAPass() {
1394 return new LoopAccessAnalysis();