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;
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;
42 static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
43 "runtime-memory-check-threshold", cl::Hidden,
44 cl::desc("When performing memory disambiguation checks at runtime do not "
45 "generate more than this number of comparisons (default = 8)."),
46 cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
47 unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
49 /// Maximum SIMD width.
50 const unsigned VectorizerParams::MaxVectorWidth = 64;
52 /// \brief We collect interesting dependences up to this threshold.
53 static cl::opt<unsigned> MaxInterestingDependence(
54 "max-interesting-dependences", cl::Hidden,
55 cl::desc("Maximum number of interesting dependences collected by "
56 "loop-access analysis (default = 100)"),
59 bool VectorizerParams::isInterleaveForced() {
60 return ::VectorizationInterleave.getNumOccurrences() > 0;
63 void LoopAccessReport::emitAnalysis(const LoopAccessReport &Message,
64 const Function *TheFunction,
66 const char *PassName) {
67 DebugLoc DL = TheLoop->getStartLoc();
68 if (const Instruction *I = Message.getInstr())
69 DL = I->getDebugLoc();
70 emitOptimizationRemarkAnalysis(TheFunction->getContext(), PassName,
71 *TheFunction, DL, Message.str());
74 Value *llvm::stripIntegerCast(Value *V) {
75 if (CastInst *CI = dyn_cast<CastInst>(V))
76 if (CI->getOperand(0)->getType()->isIntegerTy())
77 return CI->getOperand(0);
81 const SCEV *llvm::replaceSymbolicStrideSCEV(ScalarEvolution *SE,
82 const ValueToValueMap &PtrToStride,
83 Value *Ptr, Value *OrigPtr) {
85 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
87 // If there is an entry in the map return the SCEV of the pointer with the
88 // symbolic stride replaced by one.
89 ValueToValueMap::const_iterator SI =
90 PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
91 if (SI != PtrToStride.end()) {
92 Value *StrideVal = SI->second;
95 StrideVal = stripIntegerCast(StrideVal);
97 // Replace symbolic stride by one.
98 Value *One = ConstantInt::get(StrideVal->getType(), 1);
99 ValueToValueMap RewriteMap;
100 RewriteMap[StrideVal] = One;
103 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
104 DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
109 // Otherwise, just return the SCEV of the original pointer.
110 return SE->getSCEV(Ptr);
113 void LoopAccessInfo::RuntimePointerCheck::insert(
114 ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
115 unsigned ASId, const ValueToValueMap &Strides) {
116 // Get the stride replaced scev.
117 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
118 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
119 assert(AR && "Invalid addrec expression");
120 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
121 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
122 Pointers.push_back(Ptr);
123 Starts.push_back(AR->getStart());
124 Ends.push_back(ScEnd);
125 IsWritePtr.push_back(WritePtr);
126 DependencySetId.push_back(DepSetId);
127 AliasSetId.push_back(ASId);
130 bool LoopAccessInfo::RuntimePointerCheck::needsChecking(unsigned I,
132 // No need to check if two readonly pointers intersect.
133 if (!IsWritePtr[I] && !IsWritePtr[J])
136 // Only need to check pointers between two different dependency sets.
137 if (DependencySetId[I] == DependencySetId[J])
140 // Only need to check pointers in the same alias set.
141 if (AliasSetId[I] != AliasSetId[J])
147 void LoopAccessInfo::RuntimePointerCheck::print(raw_ostream &OS,
148 unsigned Depth) const {
149 unsigned NumPointers = Pointers.size();
150 if (NumPointers == 0)
153 OS.indent(Depth) << "Run-time memory checks:\n";
155 for (unsigned I = 0; I < NumPointers; ++I)
156 for (unsigned J = I + 1; J < NumPointers; ++J)
157 if (needsChecking(I, J)) {
158 OS.indent(Depth) << N++ << ":\n";
159 OS.indent(Depth + 2) << *Pointers[I] << "\n";
160 OS.indent(Depth + 2) << *Pointers[J] << "\n";
165 /// \brief Analyses memory accesses in a loop.
167 /// Checks whether run time pointer checks are needed and builds sets for data
168 /// dependence checking.
169 class AccessAnalysis {
171 /// \brief Read or write access location.
172 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
173 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
175 AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA,
176 MemoryDepChecker::DepCandidates &DA)
177 : DL(Dl), AST(*AA), DepCands(DA), IsRTCheckNeeded(false) {}
179 /// \brief Register a load and whether it is only read from.
180 void addLoad(AliasAnalysis::Location &Loc, bool IsReadOnly) {
181 Value *Ptr = const_cast<Value*>(Loc.Ptr);
182 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
183 Accesses.insert(MemAccessInfo(Ptr, false));
185 ReadOnlyPtr.insert(Ptr);
188 /// \brief Register a store.
189 void addStore(AliasAnalysis::Location &Loc) {
190 Value *Ptr = const_cast<Value*>(Loc.Ptr);
191 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
192 Accesses.insert(MemAccessInfo(Ptr, true));
195 /// \brief Check whether we can check the pointers at runtime for
196 /// non-intersection.
197 bool canCheckPtrAtRT(LoopAccessInfo::RuntimePointerCheck &RtCheck,
198 unsigned &NumComparisons, ScalarEvolution *SE,
199 Loop *TheLoop, const ValueToValueMap &Strides,
200 bool ShouldCheckStride = false);
202 /// \brief Goes over all memory accesses, checks whether a RT check is needed
203 /// and builds sets of dependent accesses.
204 void buildDependenceSets() {
205 processMemAccesses();
208 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
210 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
211 void resetDepChecks() { CheckDeps.clear(); }
213 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
216 typedef SetVector<MemAccessInfo> PtrAccessSet;
218 /// \brief Go over all memory access and check whether runtime pointer checks
219 /// are needed /// and build sets of dependency check candidates.
220 void processMemAccesses();
222 /// Set of all accesses.
223 PtrAccessSet Accesses;
225 const DataLayout &DL;
227 /// Set of accesses that need a further dependence check.
228 MemAccessInfoSet CheckDeps;
230 /// Set of pointers that are read only.
231 SmallPtrSet<Value*, 16> ReadOnlyPtr;
233 /// An alias set tracker to partition the access set by underlying object and
234 //intrinsic property (such as TBAA metadata).
237 /// Sets of potentially dependent accesses - members of one set share an
238 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
239 /// dependence check.
240 MemoryDepChecker::DepCandidates &DepCands;
242 bool IsRTCheckNeeded;
245 } // end anonymous namespace
247 /// \brief Check whether a pointer can participate in a runtime bounds check.
248 static bool hasComputableBounds(ScalarEvolution *SE,
249 const ValueToValueMap &Strides, Value *Ptr) {
250 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
251 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
255 return AR->isAffine();
258 /// \brief Check the stride of the pointer and ensure that it does not wrap in
259 /// the address space.
260 static int isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
261 const ValueToValueMap &StridesMap);
263 bool AccessAnalysis::canCheckPtrAtRT(
264 LoopAccessInfo::RuntimePointerCheck &RtCheck, unsigned &NumComparisons,
265 ScalarEvolution *SE, Loop *TheLoop, const ValueToValueMap &StridesMap,
266 bool ShouldCheckStride) {
267 // Find pointers with computable bounds. We are going to use this information
268 // to place a runtime bound check.
271 bool IsDepCheckNeeded = isDependencyCheckNeeded();
274 // We assign a consecutive id to access from different alias sets.
275 // Accesses between different groups doesn't need to be checked.
277 for (auto &AS : AST) {
278 unsigned NumReadPtrChecks = 0;
279 unsigned NumWritePtrChecks = 0;
281 // We assign consecutive id to access from different dependence sets.
282 // Accesses within the same set don't need a runtime check.
283 unsigned RunningDepId = 1;
284 DenseMap<Value *, unsigned> DepSetId;
287 Value *Ptr = A.getValue();
288 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
289 MemAccessInfo Access(Ptr, IsWrite);
296 if (hasComputableBounds(SE, StridesMap, Ptr) &&
297 // When we run after a failing dependency check we have to make sure
298 // we don't have wrapping pointers.
299 (!ShouldCheckStride ||
300 isStridedPtr(SE, Ptr, TheLoop, StridesMap) == 1)) {
301 // The id of the dependence set.
304 if (IsDepCheckNeeded) {
305 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
306 unsigned &LeaderId = DepSetId[Leader];
308 LeaderId = RunningDepId++;
311 // Each access has its own dependence set.
312 DepId = RunningDepId++;
314 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
316 DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
322 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
323 NumComparisons += 0; // Only one dependence set.
325 NumComparisons += (NumWritePtrChecks * (NumReadPtrChecks +
326 NumWritePtrChecks - 1));
332 // If the pointers that we would use for the bounds comparison have different
333 // address spaces, assume the values aren't directly comparable, so we can't
334 // use them for the runtime check. We also have to assume they could
335 // overlap. In the future there should be metadata for whether address spaces
337 unsigned NumPointers = RtCheck.Pointers.size();
338 for (unsigned i = 0; i < NumPointers; ++i) {
339 for (unsigned j = i + 1; j < NumPointers; ++j) {
340 // Only need to check pointers between two different dependency sets.
341 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
343 // Only need to check pointers in the same alias set.
344 if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j])
347 Value *PtrI = RtCheck.Pointers[i];
348 Value *PtrJ = RtCheck.Pointers[j];
350 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
351 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
353 DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
354 " different address spaces\n");
363 void AccessAnalysis::processMemAccesses() {
364 // We process the set twice: first we process read-write pointers, last we
365 // process read-only pointers. This allows us to skip dependence tests for
366 // read-only pointers.
368 DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
369 DEBUG(dbgs() << " AST: "; AST.dump());
370 DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n");
372 for (auto A : Accesses)
373 dbgs() << "\t" << *A.getPointer() << " (" <<
374 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
375 "read-only" : "read")) << ")\n";
378 // The AliasSetTracker has nicely partitioned our pointers by metadata
379 // compatibility and potential for underlying-object overlap. As a result, we
380 // only need to check for potential pointer dependencies within each alias
382 for (auto &AS : AST) {
383 // Note that both the alias-set tracker and the alias sets themselves used
384 // linked lists internally and so the iteration order here is deterministic
385 // (matching the original instruction order within each set).
387 bool SetHasWrite = false;
389 // Map of pointers to last access encountered.
390 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
391 UnderlyingObjToAccessMap ObjToLastAccess;
393 // Set of access to check after all writes have been processed.
394 PtrAccessSet DeferredAccesses;
396 // Iterate over each alias set twice, once to process read/write pointers,
397 // and then to process read-only pointers.
398 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
399 bool UseDeferred = SetIteration > 0;
400 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
403 Value *Ptr = AV.getValue();
405 // For a single memory access in AliasSetTracker, Accesses may contain
406 // both read and write, and they both need to be handled for CheckDeps.
408 if (AC.getPointer() != Ptr)
411 bool IsWrite = AC.getInt();
413 // If we're using the deferred access set, then it contains only
415 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
416 if (UseDeferred && !IsReadOnlyPtr)
418 // Otherwise, the pointer must be in the PtrAccessSet, either as a
420 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
421 S.count(MemAccessInfo(Ptr, false))) &&
422 "Alias-set pointer not in the access set?");
424 MemAccessInfo Access(Ptr, IsWrite);
425 DepCands.insert(Access);
427 // Memorize read-only pointers for later processing and skip them in
428 // the first round (they need to be checked after we have seen all
429 // write pointers). Note: we also mark pointer that are not
430 // consecutive as "read-only" pointers (so that we check
431 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
432 if (!UseDeferred && IsReadOnlyPtr) {
433 DeferredAccesses.insert(Access);
437 // If this is a write - check other reads and writes for conflicts. If
438 // this is a read only check other writes for conflicts (but only if
439 // there is no other write to the ptr - this is an optimization to
440 // catch "a[i] = a[i] + " without having to do a dependence check).
441 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
442 CheckDeps.insert(Access);
443 IsRTCheckNeeded = true;
449 // Create sets of pointers connected by a shared alias set and
450 // underlying object.
451 typedef SmallVector<Value *, 16> ValueVector;
452 ValueVector TempObjects;
453 GetUnderlyingObjects(Ptr, TempObjects, DL);
454 for (Value *UnderlyingObj : TempObjects) {
455 UnderlyingObjToAccessMap::iterator Prev =
456 ObjToLastAccess.find(UnderlyingObj);
457 if (Prev != ObjToLastAccess.end())
458 DepCands.unionSets(Access, Prev->second);
460 ObjToLastAccess[UnderlyingObj] = Access;
468 static bool isInBoundsGep(Value *Ptr) {
469 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
470 return GEP->isInBounds();
474 /// \brief Check whether the access through \p Ptr has a constant stride.
475 static int isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
476 const ValueToValueMap &StridesMap) {
477 const Type *Ty = Ptr->getType();
478 assert(Ty->isPointerTy() && "Unexpected non-ptr");
480 // Make sure that the pointer does not point to aggregate types.
481 const PointerType *PtrTy = cast<PointerType>(Ty);
482 if (PtrTy->getElementType()->isAggregateType()) {
483 DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
488 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
490 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
492 DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
493 << *Ptr << " SCEV: " << *PtrScev << "\n");
497 // The accesss function must stride over the innermost loop.
498 if (Lp != AR->getLoop()) {
499 DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
500 *Ptr << " SCEV: " << *PtrScev << "\n");
503 // The address calculation must not wrap. Otherwise, a dependence could be
505 // An inbounds getelementptr that is a AddRec with a unit stride
506 // cannot wrap per definition. The unit stride requirement is checked later.
507 // An getelementptr without an inbounds attribute and unit stride would have
508 // to access the pointer value "0" which is undefined behavior in address
509 // space 0, therefore we can also vectorize this case.
510 bool IsInBoundsGEP = isInBoundsGep(Ptr);
511 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
512 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
513 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
514 DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
515 << *Ptr << " SCEV: " << *PtrScev << "\n");
519 // Check the step is constant.
520 const SCEV *Step = AR->getStepRecurrence(*SE);
522 // Calculate the pointer stride and check if it is consecutive.
523 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
525 DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
526 " SCEV: " << *PtrScev << "\n");
530 auto &DL = Lp->getHeader()->getModule()->getDataLayout();
531 int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
532 const APInt &APStepVal = C->getValue()->getValue();
534 // Huge step value - give up.
535 if (APStepVal.getBitWidth() > 64)
538 int64_t StepVal = APStepVal.getSExtValue();
541 int64_t Stride = StepVal / Size;
542 int64_t Rem = StepVal % Size;
546 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
547 // know we can't "wrap around the address space". In case of address space
548 // zero we know that this won't happen without triggering undefined behavior.
549 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
550 Stride != 1 && Stride != -1)
556 bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
560 case BackwardVectorizable:
564 case ForwardButPreventsForwarding:
566 case BackwardVectorizableButPreventsForwarding:
571 bool MemoryDepChecker::Dependence::isInterestingDependence(DepType Type) {
577 case BackwardVectorizable:
579 case ForwardButPreventsForwarding:
581 case BackwardVectorizableButPreventsForwarding:
586 bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
590 case ForwardButPreventsForwarding:
594 case BackwardVectorizable:
596 case BackwardVectorizableButPreventsForwarding:
601 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
602 unsigned TypeByteSize) {
603 // If loads occur at a distance that is not a multiple of a feasible vector
604 // factor store-load forwarding does not take place.
605 // Positive dependences might cause troubles because vectorizing them might
606 // prevent store-load forwarding making vectorized code run a lot slower.
607 // a[i] = a[i-3] ^ a[i-8];
608 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
609 // hence on your typical architecture store-load forwarding does not take
610 // place. Vectorizing in such cases does not make sense.
611 // Store-load forwarding distance.
612 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
613 // Maximum vector factor.
614 unsigned MaxVFWithoutSLForwardIssues =
615 VectorizerParams::MaxVectorWidth * TypeByteSize;
616 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
617 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
619 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
621 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
622 MaxVFWithoutSLForwardIssues = (vf >>=1);
627 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
628 DEBUG(dbgs() << "LAA: Distance " << Distance <<
629 " that could cause a store-load forwarding conflict\n");
633 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
634 MaxVFWithoutSLForwardIssues !=
635 VectorizerParams::MaxVectorWidth * TypeByteSize)
636 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
640 MemoryDepChecker::Dependence::DepType
641 MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
642 const MemAccessInfo &B, unsigned BIdx,
643 const ValueToValueMap &Strides) {
644 assert (AIdx < BIdx && "Must pass arguments in program order");
646 Value *APtr = A.getPointer();
647 Value *BPtr = B.getPointer();
648 bool AIsWrite = A.getInt();
649 bool BIsWrite = B.getInt();
651 // Two reads are independent.
652 if (!AIsWrite && !BIsWrite)
653 return Dependence::NoDep;
655 // We cannot check pointers in different address spaces.
656 if (APtr->getType()->getPointerAddressSpace() !=
657 BPtr->getType()->getPointerAddressSpace())
658 return Dependence::Unknown;
660 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
661 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
663 int StrideAPtr = isStridedPtr(SE, APtr, InnermostLoop, Strides);
664 int StrideBPtr = isStridedPtr(SE, BPtr, InnermostLoop, Strides);
666 const SCEV *Src = AScev;
667 const SCEV *Sink = BScev;
669 // If the induction step is negative we have to invert source and sink of the
671 if (StrideAPtr < 0) {
674 std::swap(APtr, BPtr);
675 std::swap(Src, Sink);
676 std::swap(AIsWrite, BIsWrite);
677 std::swap(AIdx, BIdx);
678 std::swap(StrideAPtr, StrideBPtr);
681 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
683 DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
684 << "(Induction step: " << StrideAPtr << ")\n");
685 DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
686 << *InstMap[BIdx] << ": " << *Dist << "\n");
688 // Need consecutive accesses. We don't want to vectorize
689 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
690 // the address space.
691 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
692 DEBUG(dbgs() << "Non-consecutive pointer access\n");
693 return Dependence::Unknown;
696 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
698 DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
699 ShouldRetryWithRuntimeCheck = true;
700 return Dependence::Unknown;
703 Type *ATy = APtr->getType()->getPointerElementType();
704 Type *BTy = BPtr->getType()->getPointerElementType();
705 auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
706 unsigned TypeByteSize = DL.getTypeAllocSize(ATy);
708 // Negative distances are not plausible dependencies.
709 const APInt &Val = C->getValue()->getValue();
710 if (Val.isNegative()) {
711 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
712 if (IsTrueDataDependence &&
713 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
715 return Dependence::ForwardButPreventsForwarding;
717 DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
718 return Dependence::Forward;
721 // Write to the same location with the same size.
722 // Could be improved to assert type sizes are the same (i32 == float, etc).
725 return Dependence::NoDep;
726 DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
727 return Dependence::Unknown;
730 assert(Val.isStrictlyPositive() && "Expect a positive value");
734 "LAA: ReadWrite-Write positive dependency with different types\n");
735 return Dependence::Unknown;
738 unsigned Distance = (unsigned) Val.getZExtValue();
740 // Bail out early if passed-in parameters make vectorization not feasible.
741 unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
742 VectorizerParams::VectorizationFactor : 1);
743 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
744 VectorizerParams::VectorizationInterleave : 1);
746 // The distance must be bigger than the size needed for a vectorized version
747 // of the operation and the size of the vectorized operation must not be
748 // bigger than the currrent maximum size.
749 if (Distance < 2*TypeByteSize ||
750 2*TypeByteSize > MaxSafeDepDistBytes ||
751 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
752 DEBUG(dbgs() << "LAA: Failure because of Positive distance "
753 << Val.getSExtValue() << '\n');
754 return Dependence::Backward;
757 // Positive distance bigger than max vectorization factor.
758 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
759 Distance : MaxSafeDepDistBytes;
761 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
762 if (IsTrueDataDependence &&
763 couldPreventStoreLoadForward(Distance, TypeByteSize))
764 return Dependence::BackwardVectorizableButPreventsForwarding;
766 DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue() <<
767 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
769 return Dependence::BackwardVectorizable;
772 bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
773 MemAccessInfoSet &CheckDeps,
774 const ValueToValueMap &Strides) {
776 MaxSafeDepDistBytes = -1U;
777 while (!CheckDeps.empty()) {
778 MemAccessInfo CurAccess = *CheckDeps.begin();
780 // Get the relevant memory access set.
781 EquivalenceClasses<MemAccessInfo>::iterator I =
782 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
784 // Check accesses within this set.
785 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
786 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
788 // Check every access pair.
790 CheckDeps.erase(*AI);
791 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
793 // Check every accessing instruction pair in program order.
794 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
795 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
796 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
797 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
798 auto A = std::make_pair(&*AI, *I1);
799 auto B = std::make_pair(&*OI, *I2);
805 Dependence::DepType Type =
806 isDependent(*A.first, A.second, *B.first, B.second, Strides);
807 SafeForVectorization &= Dependence::isSafeForVectorization(Type);
809 // Gather dependences unless we accumulated MaxInterestingDependence
810 // dependences. In that case return as soon as we find the first
811 // unsafe dependence. This puts a limit on this quadratic
813 if (RecordInterestingDependences) {
814 if (Dependence::isInterestingDependence(Type))
815 InterestingDependences.push_back(
816 Dependence(A.second, B.second, Type));
818 if (InterestingDependences.size() >= MaxInterestingDependence) {
819 RecordInterestingDependences = false;
820 InterestingDependences.clear();
821 DEBUG(dbgs() << "Too many dependences, stopped recording\n");
824 if (!RecordInterestingDependences && !SafeForVectorization)
833 DEBUG(dbgs() << "Total Interesting Dependences: "
834 << InterestingDependences.size() << "\n");
835 return SafeForVectorization;
838 const char *MemoryDepChecker::Dependence::DepName[] = {
839 "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
840 "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
842 void MemoryDepChecker::Dependence::print(
843 raw_ostream &OS, unsigned Depth,
844 const SmallVectorImpl<Instruction *> &Instrs) const {
845 OS.indent(Depth) << DepName[Type] << ":\n";
846 OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
847 OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
850 bool LoopAccessInfo::canAnalyzeLoop() {
851 // We can only analyze innermost loops.
852 if (!TheLoop->empty()) {
853 emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
857 // We must have a single backedge.
858 if (TheLoop->getNumBackEdges() != 1) {
860 LoopAccessReport() <<
861 "loop control flow is not understood by analyzer");
865 // We must have a single exiting block.
866 if (!TheLoop->getExitingBlock()) {
868 LoopAccessReport() <<
869 "loop control flow is not understood by analyzer");
873 // We only handle bottom-tested loops, i.e. loop in which the condition is
874 // checked at the end of each iteration. With that we can assume that all
875 // instructions in the loop are executed the same number of times.
876 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
878 LoopAccessReport() <<
879 "loop control flow is not understood by analyzer");
883 // We need to have a loop header.
884 DEBUG(dbgs() << "LAA: Found a loop: " <<
885 TheLoop->getHeader()->getName() << '\n');
887 // ScalarEvolution needs to be able to find the exit count.
888 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
889 if (ExitCount == SE->getCouldNotCompute()) {
890 emitAnalysis(LoopAccessReport() <<
891 "could not determine number of loop iterations");
892 DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
899 void LoopAccessInfo::analyzeLoop(const ValueToValueMap &Strides) {
901 typedef SmallVector<Value*, 16> ValueVector;
902 typedef SmallPtrSet<Value*, 16> ValueSet;
904 // Holds the Load and Store *instructions*.
908 // Holds all the different accesses in the loop.
909 unsigned NumReads = 0;
910 unsigned NumReadWrites = 0;
912 PtrRtCheck.Pointers.clear();
913 PtrRtCheck.Need = false;
915 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
918 for (Loop::block_iterator bb = TheLoop->block_begin(),
919 be = TheLoop->block_end(); bb != be; ++bb) {
921 // Scan the BB and collect legal loads and stores.
922 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
925 // If this is a load, save it. If this instruction can read from memory
926 // but is not a load, then we quit. Notice that we don't handle function
927 // calls that read or write.
928 if (it->mayReadFromMemory()) {
929 // Many math library functions read the rounding mode. We will only
930 // vectorize a loop if it contains known function calls that don't set
931 // the flag. Therefore, it is safe to ignore this read from memory.
932 CallInst *Call = dyn_cast<CallInst>(it);
933 if (Call && getIntrinsicIDForCall(Call, TLI))
936 LoadInst *Ld = dyn_cast<LoadInst>(it);
937 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
938 emitAnalysis(LoopAccessReport(Ld)
939 << "read with atomic ordering or volatile read");
940 DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
946 DepChecker.addAccess(Ld);
950 // Save 'store' instructions. Abort if other instructions write to memory.
951 if (it->mayWriteToMemory()) {
952 StoreInst *St = dyn_cast<StoreInst>(it);
954 emitAnalysis(LoopAccessReport(it) <<
955 "instruction cannot be vectorized");
959 if (!St->isSimple() && !IsAnnotatedParallel) {
960 emitAnalysis(LoopAccessReport(St)
961 << "write with atomic ordering or volatile write");
962 DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
967 Stores.push_back(St);
968 DepChecker.addAccess(St);
973 // Now we have two lists that hold the loads and the stores.
974 // Next, we find the pointers that they use.
976 // Check if we see any stores. If there are no stores, then we don't
977 // care if the pointers are *restrict*.
978 if (!Stores.size()) {
979 DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
984 MemoryDepChecker::DepCandidates DependentAccesses;
985 AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
986 AA, DependentAccesses);
988 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
989 // multiple times on the same object. If the ptr is accessed twice, once
990 // for read and once for write, it will only appear once (on the write
991 // list). This is okay, since we are going to check for conflicts between
992 // writes and between reads and writes, but not between reads and reads.
995 ValueVector::iterator I, IE;
996 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
997 StoreInst *ST = cast<StoreInst>(*I);
998 Value* Ptr = ST->getPointerOperand();
1000 if (isUniform(Ptr)) {
1002 LoopAccessReport(ST)
1003 << "write to a loop invariant address could not be vectorized");
1004 DEBUG(dbgs() << "LAA: We don't allow storing to uniform addresses\n");
1009 // If we did *not* see this pointer before, insert it to the read-write
1010 // list. At this phase it is only a 'write' list.
1011 if (Seen.insert(Ptr).second) {
1014 AliasAnalysis::Location Loc = AA->getLocation(ST);
1015 // The TBAA metadata could have a control dependency on the predication
1016 // condition, so we cannot rely on it when determining whether or not we
1017 // need runtime pointer checks.
1018 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
1019 Loc.AATags.TBAA = nullptr;
1021 Accesses.addStore(Loc);
1025 if (IsAnnotatedParallel) {
1027 << "LAA: A loop annotated parallel, ignore memory dependency "
1033 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1034 LoadInst *LD = cast<LoadInst>(*I);
1035 Value* Ptr = LD->getPointerOperand();
1036 // If we did *not* see this pointer before, insert it to the
1037 // read list. If we *did* see it before, then it is already in
1038 // the read-write list. This allows us to vectorize expressions
1039 // such as A[i] += x; Because the address of A[i] is a read-write
1040 // pointer. This only works if the index of A[i] is consecutive.
1041 // If the address of i is unknown (for example A[B[i]]) then we may
1042 // read a few words, modify, and write a few words, and some of the
1043 // words may be written to the same address.
1044 bool IsReadOnlyPtr = false;
1045 if (Seen.insert(Ptr).second || !isStridedPtr(SE, Ptr, TheLoop, Strides)) {
1047 IsReadOnlyPtr = true;
1050 AliasAnalysis::Location Loc = AA->getLocation(LD);
1051 // The TBAA metadata could have a control dependency on the predication
1052 // condition, so we cannot rely on it when determining whether or not we
1053 // need runtime pointer checks.
1054 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
1055 Loc.AATags.TBAA = nullptr;
1057 Accesses.addLoad(Loc, IsReadOnlyPtr);
1060 // If we write (or read-write) to a single destination and there are no
1061 // other reads in this loop then is it safe to vectorize.
1062 if (NumReadWrites == 1 && NumReads == 0) {
1063 DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
1068 // Build dependence sets and check whether we need a runtime pointer bounds
1070 Accesses.buildDependenceSets();
1071 bool NeedRTCheck = Accesses.isRTCheckNeeded();
1073 // Find pointers with computable bounds. We are going to use this information
1074 // to place a runtime bound check.
1075 unsigned NumComparisons = 0;
1076 bool CanDoRT = false;
1078 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
1081 DEBUG(dbgs() << "LAA: We need to do " << NumComparisons <<
1082 " pointer comparisons.\n");
1084 // If we only have one set of dependences to check pointers among we don't
1085 // need a runtime check.
1086 if (NumComparisons == 0 && NeedRTCheck)
1087 NeedRTCheck = false;
1089 // Check that we did not collect too many pointers or found an unsizeable
1091 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
1097 DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
1100 if (NeedRTCheck && !CanDoRT) {
1101 emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
1102 DEBUG(dbgs() << "LAA: We can't vectorize because we can't find " <<
1103 "the array bounds.\n");
1109 PtrRtCheck.Need = NeedRTCheck;
1112 if (Accesses.isDependencyCheckNeeded()) {
1113 DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
1114 CanVecMem = DepChecker.areDepsSafe(
1115 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1116 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1118 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
1119 DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
1122 // Clear the dependency checks. We assume they are not needed.
1123 Accesses.resetDepChecks();
1126 PtrRtCheck.Need = true;
1128 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
1129 TheLoop, Strides, true);
1130 // Check that we did not collect too many pointers or found an unsizeable
1132 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
1133 if (!CanDoRT && NumComparisons > 0)
1134 emitAnalysis(LoopAccessReport()
1135 << "cannot check memory dependencies at runtime");
1137 emitAnalysis(LoopAccessReport()
1138 << NumComparisons << " exceeds limit of "
1139 << RuntimeMemoryCheckThreshold
1140 << " dependent memory operations checked at runtime");
1141 DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
1152 emitAnalysis(LoopAccessReport() <<
1153 "unsafe dependent memory operations in loop");
1155 DEBUG(dbgs() << "LAA: We" << (NeedRTCheck ? "" : " don't") <<
1156 " need a runtime memory check.\n");
1159 bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1160 DominatorTree *DT) {
1161 assert(TheLoop->contains(BB) && "Unknown block used");
1163 // Blocks that do not dominate the latch need predication.
1164 BasicBlock* Latch = TheLoop->getLoopLatch();
1165 return !DT->dominates(BB, Latch);
1168 void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
1169 assert(!Report && "Multiple reports generated");
1173 bool LoopAccessInfo::isUniform(Value *V) const {
1174 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1177 // FIXME: this function is currently a duplicate of the one in
1178 // LoopVectorize.cpp.
1179 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1183 if (Instruction *I = dyn_cast<Instruction>(V))
1184 return I->getParent() == Loc->getParent() ? I : nullptr;
1188 std::pair<Instruction *, Instruction *>
1189 LoopAccessInfo::addRuntimeCheck(Instruction *Loc) const {
1190 Instruction *tnullptr = nullptr;
1191 if (!PtrRtCheck.Need)
1192 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1194 unsigned NumPointers = PtrRtCheck.Pointers.size();
1195 SmallVector<TrackingVH<Value> , 2> Starts;
1196 SmallVector<TrackingVH<Value> , 2> Ends;
1198 LLVMContext &Ctx = Loc->getContext();
1199 SCEVExpander Exp(*SE, DL, "induction");
1200 Instruction *FirstInst = nullptr;
1202 for (unsigned i = 0; i < NumPointers; ++i) {
1203 Value *Ptr = PtrRtCheck.Pointers[i];
1204 const SCEV *Sc = SE->getSCEV(Ptr);
1206 if (SE->isLoopInvariant(Sc, TheLoop)) {
1207 DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" <<
1209 Starts.push_back(Ptr);
1210 Ends.push_back(Ptr);
1212 DEBUG(dbgs() << "LAA: Adding RT check for range:" << *Ptr << '\n');
1213 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1215 // Use this type for pointer arithmetic.
1216 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1218 Value *Start = Exp.expandCodeFor(PtrRtCheck.Starts[i], PtrArithTy, Loc);
1219 Value *End = Exp.expandCodeFor(PtrRtCheck.Ends[i], PtrArithTy, Loc);
1220 Starts.push_back(Start);
1221 Ends.push_back(End);
1225 IRBuilder<> ChkBuilder(Loc);
1226 // Our instructions might fold to a constant.
1227 Value *MemoryRuntimeCheck = nullptr;
1228 for (unsigned i = 0; i < NumPointers; ++i) {
1229 for (unsigned j = i+1; j < NumPointers; ++j) {
1230 if (!PtrRtCheck.needsChecking(i, j))
1233 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1234 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1236 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1237 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1238 "Trying to bounds check pointers with different address spaces");
1240 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1241 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1243 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1244 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1245 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
1246 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
1248 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1249 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1250 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1251 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1252 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1253 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1254 if (MemoryRuntimeCheck) {
1255 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1257 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1259 MemoryRuntimeCheck = IsConflict;
1263 // We have to do this trickery because the IRBuilder might fold the check to a
1264 // constant expression in which case there is no Instruction anchored in a
1266 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1267 ConstantInt::getTrue(Ctx));
1268 ChkBuilder.Insert(Check, "memcheck.conflict");
1269 FirstInst = getFirstInst(FirstInst, Check, Loc);
1270 return std::make_pair(FirstInst, Check);
1273 LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
1274 const DataLayout &DL,
1275 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
1277 const ValueToValueMap &Strides)
1278 : DepChecker(SE, L), TheLoop(L), SE(SE), DL(DL), TLI(TLI), AA(AA),
1279 DT(DT), NumLoads(0), NumStores(0), MaxSafeDepDistBytes(-1U),
1281 if (canAnalyzeLoop())
1282 analyzeLoop(Strides);
1285 void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1287 if (PtrRtCheck.empty())
1288 OS.indent(Depth) << "Memory dependences are safe\n";
1290 OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
1294 OS.indent(Depth) << "Report: " << Report->str() << "\n";
1296 if (auto *InterestingDependences = DepChecker.getInterestingDependences()) {
1297 OS.indent(Depth) << "Interesting Dependences:\n";
1298 for (auto &Dep : *InterestingDependences) {
1299 Dep.print(OS, Depth + 2, DepChecker.getMemoryInstructions());
1303 OS.indent(Depth) << "Too many interesting dependences, not recorded\n";
1305 // List the pair of accesses need run-time checks to prove independence.
1306 PtrRtCheck.print(OS, Depth);
1310 const LoopAccessInfo &
1311 LoopAccessAnalysis::getInfo(Loop *L, const ValueToValueMap &Strides) {
1312 auto &LAI = LoopAccessInfoMap[L];
1315 assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
1316 "Symbolic strides changed for loop");
1320 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
1321 LAI = llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, Strides);
1323 LAI->NumSymbolicStrides = Strides.size();
1329 void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
1330 LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
1332 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1333 ValueToValueMap NoSymbolicStrides;
1335 for (Loop *TopLevelLoop : *LI)
1336 for (Loop *L : depth_first(TopLevelLoop)) {
1337 OS.indent(2) << L->getHeader()->getName() << ":\n";
1338 auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
1343 bool LoopAccessAnalysis::runOnFunction(Function &F) {
1344 SE = &getAnalysis<ScalarEvolution>();
1345 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1346 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1347 AA = &getAnalysis<AliasAnalysis>();
1348 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1353 void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
1354 AU.addRequired<ScalarEvolution>();
1355 AU.addRequired<AliasAnalysis>();
1356 AU.addRequired<DominatorTreeWrapperPass>();
1357 AU.addRequired<LoopInfoWrapperPass>();
1359 AU.setPreservesAll();
1362 char LoopAccessAnalysis::ID = 0;
1363 static const char laa_name[] = "Loop Access Analysis";
1364 #define LAA_NAME "loop-accesses"
1366 INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1367 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1368 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1369 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1370 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
1371 INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1374 Pass *createLAAPass() {
1375 return new LoopAccessAnalysis();