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 LoopAccessReport::emitAnalysis(const LoopAccessReport &Message,
29 const Function *TheFunction,
31 const char *PassName) {
32 DebugLoc DL = TheLoop->getStartLoc();
33 if (const 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])
113 void LoopAccessInfo::RuntimePointerCheck::print(raw_ostream &OS,
114 unsigned Depth) const {
115 unsigned NumPointers = Pointers.size();
116 if (NumPointers == 0)
119 OS.indent(Depth) << "Run-time memory checks:\n";
121 for (unsigned I = 0; I < NumPointers; ++I)
122 for (unsigned J = I + 1; J < NumPointers; ++J)
123 if (needsChecking(I, J)) {
124 OS.indent(Depth) << N++ << ":\n";
125 OS.indent(Depth + 2) << *Pointers[I] << "\n";
126 OS.indent(Depth + 2) << *Pointers[J] << "\n";
131 /// \brief Analyses memory accesses in a loop.
133 /// Checks whether run time pointer checks are needed and builds sets for data
134 /// dependence checking.
135 class AccessAnalysis {
137 /// \brief Read or write access location.
138 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
139 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
141 /// \brief Set of potential dependent memory accesses.
142 typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
144 AccessAnalysis(const DataLayout *Dl, AliasAnalysis *AA, DepCandidates &DA) :
145 DL(Dl), AST(*AA), DepCands(DA), IsRTCheckNeeded(false) {}
147 /// \brief Register a load and whether it is only read from.
148 void addLoad(AliasAnalysis::Location &Loc, bool IsReadOnly) {
149 Value *Ptr = const_cast<Value*>(Loc.Ptr);
150 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
151 Accesses.insert(MemAccessInfo(Ptr, false));
153 ReadOnlyPtr.insert(Ptr);
156 /// \brief Register a store.
157 void addStore(AliasAnalysis::Location &Loc) {
158 Value *Ptr = const_cast<Value*>(Loc.Ptr);
159 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
160 Accesses.insert(MemAccessInfo(Ptr, true));
163 /// \brief Check whether we can check the pointers at runtime for
164 /// non-intersection.
165 bool canCheckPtrAtRT(LoopAccessInfo::RuntimePointerCheck &RtCheck,
166 unsigned &NumComparisons,
167 ScalarEvolution *SE, Loop *TheLoop,
168 ValueToValueMap &Strides,
169 bool ShouldCheckStride = false);
171 /// \brief Goes over all memory accesses, checks whether a RT check is needed
172 /// and builds sets of dependent accesses.
173 void buildDependenceSets() {
174 processMemAccesses();
177 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
179 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
180 void resetDepChecks() { CheckDeps.clear(); }
182 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
185 typedef SetVector<MemAccessInfo> PtrAccessSet;
187 /// \brief Go over all memory access and check whether runtime pointer checks
188 /// are needed /// and build sets of dependency check candidates.
189 void processMemAccesses();
191 /// Set of all accesses.
192 PtrAccessSet Accesses;
194 /// Set of accesses that need a further dependence check.
195 MemAccessInfoSet CheckDeps;
197 /// Set of pointers that are read only.
198 SmallPtrSet<Value*, 16> ReadOnlyPtr;
200 const DataLayout *DL;
202 /// An alias set tracker to partition the access set by underlying object and
203 //intrinsic property (such as TBAA metadata).
206 /// Sets of potentially dependent accesses - members of one set share an
207 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
208 /// dependence check.
209 DepCandidates &DepCands;
211 bool IsRTCheckNeeded;
214 } // end anonymous namespace
216 /// \brief Check whether a pointer can participate in a runtime bounds check.
217 static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides,
219 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
220 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
224 return AR->isAffine();
227 /// \brief Check the stride of the pointer and ensure that it does not wrap in
228 /// the address space.
229 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
230 const Loop *Lp, ValueToValueMap &StridesMap);
232 bool AccessAnalysis::canCheckPtrAtRT(
233 LoopAccessInfo::RuntimePointerCheck &RtCheck,
234 unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop,
235 ValueToValueMap &StridesMap, bool ShouldCheckStride) {
236 // Find pointers with computable bounds. We are going to use this information
237 // to place a runtime bound check.
240 bool IsDepCheckNeeded = isDependencyCheckNeeded();
243 // We assign a consecutive id to access from different alias sets.
244 // Accesses between different groups doesn't need to be checked.
246 for (auto &AS : AST) {
247 unsigned NumReadPtrChecks = 0;
248 unsigned NumWritePtrChecks = 0;
250 // We assign consecutive id to access from different dependence sets.
251 // Accesses within the same set don't need a runtime check.
252 unsigned RunningDepId = 1;
253 DenseMap<Value *, unsigned> DepSetId;
256 Value *Ptr = A.getValue();
257 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
258 MemAccessInfo Access(Ptr, IsWrite);
265 if (hasComputableBounds(SE, StridesMap, Ptr) &&
266 // When we run after a failing dependency check we have to make sure we
267 // don't have wrapping pointers.
268 (!ShouldCheckStride ||
269 isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) {
270 // The id of the dependence set.
273 if (IsDepCheckNeeded) {
274 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
275 unsigned &LeaderId = DepSetId[Leader];
277 LeaderId = RunningDepId++;
280 // Each access has its own dependence set.
281 DepId = RunningDepId++;
283 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
285 DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
291 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
292 NumComparisons += 0; // Only one dependence set.
294 NumComparisons += (NumWritePtrChecks * (NumReadPtrChecks +
295 NumWritePtrChecks - 1));
301 // If the pointers that we would use for the bounds comparison have different
302 // address spaces, assume the values aren't directly comparable, so we can't
303 // use them for the runtime check. We also have to assume they could
304 // overlap. In the future there should be metadata for whether address spaces
306 unsigned NumPointers = RtCheck.Pointers.size();
307 for (unsigned i = 0; i < NumPointers; ++i) {
308 for (unsigned j = i + 1; j < NumPointers; ++j) {
309 // Only need to check pointers between two different dependency sets.
310 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
312 // Only need to check pointers in the same alias set.
313 if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j])
316 Value *PtrI = RtCheck.Pointers[i];
317 Value *PtrJ = RtCheck.Pointers[j];
319 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
320 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
322 DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
323 " different address spaces\n");
332 void AccessAnalysis::processMemAccesses() {
333 // We process the set twice: first we process read-write pointers, last we
334 // process read-only pointers. This allows us to skip dependence tests for
335 // read-only pointers.
337 DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
338 DEBUG(dbgs() << " AST: "; AST.dump());
339 DEBUG(dbgs() << "LAA: Accesses:\n");
341 for (auto A : Accesses)
342 dbgs() << "\t" << *A.getPointer() << " (" <<
343 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
344 "read-only" : "read")) << ")\n";
347 // The AliasSetTracker has nicely partitioned our pointers by metadata
348 // compatibility and potential for underlying-object overlap. As a result, we
349 // only need to check for potential pointer dependencies within each alias
351 for (auto &AS : AST) {
352 // Note that both the alias-set tracker and the alias sets themselves used
353 // linked lists internally and so the iteration order here is deterministic
354 // (matching the original instruction order within each set).
356 bool SetHasWrite = false;
358 // Map of pointers to last access encountered.
359 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
360 UnderlyingObjToAccessMap ObjToLastAccess;
362 // Set of access to check after all writes have been processed.
363 PtrAccessSet DeferredAccesses;
365 // Iterate over each alias set twice, once to process read/write pointers,
366 // and then to process read-only pointers.
367 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
368 bool UseDeferred = SetIteration > 0;
369 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
372 Value *Ptr = AV.getValue();
374 // For a single memory access in AliasSetTracker, Accesses may contain
375 // both read and write, and they both need to be handled for CheckDeps.
377 if (AC.getPointer() != Ptr)
380 bool IsWrite = AC.getInt();
382 // If we're using the deferred access set, then it contains only
384 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
385 if (UseDeferred && !IsReadOnlyPtr)
387 // Otherwise, the pointer must be in the PtrAccessSet, either as a
389 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
390 S.count(MemAccessInfo(Ptr, false))) &&
391 "Alias-set pointer not in the access set?");
393 MemAccessInfo Access(Ptr, IsWrite);
394 DepCands.insert(Access);
396 // Memorize read-only pointers for later processing and skip them in
397 // the first round (they need to be checked after we have seen all
398 // write pointers). Note: we also mark pointer that are not
399 // consecutive as "read-only" pointers (so that we check
400 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
401 if (!UseDeferred && IsReadOnlyPtr) {
402 DeferredAccesses.insert(Access);
406 // If this is a write - check other reads and writes for conflicts. If
407 // this is a read only check other writes for conflicts (but only if
408 // there is no other write to the ptr - this is an optimization to
409 // catch "a[i] = a[i] + " without having to do a dependence check).
410 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
411 CheckDeps.insert(Access);
412 IsRTCheckNeeded = true;
418 // Create sets of pointers connected by a shared alias set and
419 // underlying object.
420 typedef SmallVector<Value *, 16> ValueVector;
421 ValueVector TempObjects;
422 GetUnderlyingObjects(Ptr, TempObjects, DL);
423 for (Value *UnderlyingObj : TempObjects) {
424 UnderlyingObjToAccessMap::iterator Prev =
425 ObjToLastAccess.find(UnderlyingObj);
426 if (Prev != ObjToLastAccess.end())
427 DepCands.unionSets(Access, Prev->second);
429 ObjToLastAccess[UnderlyingObj] = Access;
438 /// \brief Checks memory dependences among accesses to the same underlying
439 /// object to determine whether there vectorization is legal or not (and at
440 /// which vectorization factor).
442 /// This class works under the assumption that we already checked that memory
443 /// locations with different underlying pointers are "must-not alias".
444 /// We use the ScalarEvolution framework to symbolically evalutate access
445 /// functions pairs. Since we currently don't restructure the loop we can rely
446 /// on the program order of memory accesses to determine their safety.
447 /// At the moment we will only deem accesses as safe for:
448 /// * A negative constant distance assuming program order.
450 /// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
451 /// a[i] = tmp; y = a[i];
453 /// The latter case is safe because later checks guarantuee that there can't
454 /// be a cycle through a phi node (that is, we check that "x" and "y" is not
455 /// the same variable: a header phi can only be an induction or a reduction, a
456 /// reduction can't have a memory sink, an induction can't have a memory
457 /// source). This is important and must not be violated (or we have to
458 /// resort to checking for cycles through memory).
460 /// * A positive constant distance assuming program order that is bigger
461 /// than the biggest memory access.
463 /// tmp = a[i] OR b[i] = x
464 /// a[i+2] = tmp y = b[i+2];
466 /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
468 /// * Zero distances and all accesses have the same size.
470 class MemoryDepChecker {
472 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
473 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
475 MemoryDepChecker(ScalarEvolution *Se, const DataLayout *Dl, const Loop *L)
476 : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0),
477 ShouldRetryWithRuntimeCheck(false) {}
479 /// \brief Register the location (instructions are given increasing numbers)
480 /// of a write access.
481 void addAccess(StoreInst *SI) {
482 Value *Ptr = SI->getPointerOperand();
483 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
484 InstMap.push_back(SI);
488 /// \brief Register the location (instructions are given increasing numbers)
489 /// of a write access.
490 void addAccess(LoadInst *LI) {
491 Value *Ptr = LI->getPointerOperand();
492 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
493 InstMap.push_back(LI);
497 /// \brief Check whether the dependencies between the accesses are safe.
499 /// Only checks sets with elements in \p CheckDeps.
500 bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
501 MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides);
503 /// \brief The maximum number of bytes of a vector register we can vectorize
504 /// the accesses safely with.
505 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
507 /// \brief In same cases when the dependency check fails we can still
508 /// vectorize the loop with a dynamic array access check.
509 bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
513 const DataLayout *DL;
514 const Loop *InnermostLoop;
516 /// \brief Maps access locations (ptr, read/write) to program order.
517 DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
519 /// \brief Memory access instructions in program order.
520 SmallVector<Instruction *, 16> InstMap;
522 /// \brief The program order index to be used for the next instruction.
525 // We can access this many bytes in parallel safely.
526 unsigned MaxSafeDepDistBytes;
528 /// \brief If we see a non-constant dependence distance we can still try to
529 /// vectorize this loop with runtime checks.
530 bool ShouldRetryWithRuntimeCheck;
532 /// \brief Check whether there is a plausible dependence between the two
535 /// Access \p A must happen before \p B in program order. The two indices
536 /// identify the index into the program order map.
538 /// This function checks whether there is a plausible dependence (or the
539 /// absence of such can't be proved) between the two accesses. If there is a
540 /// plausible dependence but the dependence distance is bigger than one
541 /// element access it records this distance in \p MaxSafeDepDistBytes (if this
542 /// distance is smaller than any other distance encountered so far).
543 /// Otherwise, this function returns true signaling a possible dependence.
544 bool isDependent(const MemAccessInfo &A, unsigned AIdx,
545 const MemAccessInfo &B, unsigned BIdx,
546 ValueToValueMap &Strides);
548 /// \brief Check whether the data dependence could prevent store-load
550 bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
553 } // end anonymous namespace
555 static bool isInBoundsGep(Value *Ptr) {
556 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
557 return GEP->isInBounds();
561 /// \brief Check whether the access through \p Ptr has a constant stride.
562 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
563 const Loop *Lp, ValueToValueMap &StridesMap) {
564 const Type *Ty = Ptr->getType();
565 assert(Ty->isPointerTy() && "Unexpected non-ptr");
567 // Make sure that the pointer does not point to aggregate types.
568 const PointerType *PtrTy = cast<PointerType>(Ty);
569 if (PtrTy->getElementType()->isAggregateType()) {
570 DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
575 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
577 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
579 DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
580 << *Ptr << " SCEV: " << *PtrScev << "\n");
584 // The accesss function must stride over the innermost loop.
585 if (Lp != AR->getLoop()) {
586 DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
587 *Ptr << " SCEV: " << *PtrScev << "\n");
590 // The address calculation must not wrap. Otherwise, a dependence could be
592 // An inbounds getelementptr that is a AddRec with a unit stride
593 // cannot wrap per definition. The unit stride requirement is checked later.
594 // An getelementptr without an inbounds attribute and unit stride would have
595 // to access the pointer value "0" which is undefined behavior in address
596 // space 0, therefore we can also vectorize this case.
597 bool IsInBoundsGEP = isInBoundsGep(Ptr);
598 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
599 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
600 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
601 DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
602 << *Ptr << " SCEV: " << *PtrScev << "\n");
606 // Check the step is constant.
607 const SCEV *Step = AR->getStepRecurrence(*SE);
609 // Calculate the pointer stride and check if it is consecutive.
610 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
612 DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
613 " SCEV: " << *PtrScev << "\n");
617 int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
618 const APInt &APStepVal = C->getValue()->getValue();
620 // Huge step value - give up.
621 if (APStepVal.getBitWidth() > 64)
624 int64_t StepVal = APStepVal.getSExtValue();
627 int64_t Stride = StepVal / Size;
628 int64_t Rem = StepVal % Size;
632 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
633 // know we can't "wrap around the address space". In case of address space
634 // zero we know that this won't happen without triggering undefined behavior.
635 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
636 Stride != 1 && Stride != -1)
642 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
643 unsigned TypeByteSize) {
644 // If loads occur at a distance that is not a multiple of a feasible vector
645 // factor store-load forwarding does not take place.
646 // Positive dependences might cause troubles because vectorizing them might
647 // prevent store-load forwarding making vectorized code run a lot slower.
648 // a[i] = a[i-3] ^ a[i-8];
649 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
650 // hence on your typical architecture store-load forwarding does not take
651 // place. Vectorizing in such cases does not make sense.
652 // Store-load forwarding distance.
653 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
654 // Maximum vector factor.
655 unsigned MaxVFWithoutSLForwardIssues =
656 VectorizerParams::MaxVectorWidth * TypeByteSize;
657 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
658 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
660 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
662 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
663 MaxVFWithoutSLForwardIssues = (vf >>=1);
668 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
669 DEBUG(dbgs() << "LAA: Distance " << Distance <<
670 " that could cause a store-load forwarding conflict\n");
674 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
675 MaxVFWithoutSLForwardIssues !=
676 VectorizerParams::MaxVectorWidth * TypeByteSize)
677 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
681 bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
682 const MemAccessInfo &B, unsigned BIdx,
683 ValueToValueMap &Strides) {
684 assert (AIdx < BIdx && "Must pass arguments in program order");
686 Value *APtr = A.getPointer();
687 Value *BPtr = B.getPointer();
688 bool AIsWrite = A.getInt();
689 bool BIsWrite = B.getInt();
691 // Two reads are independent.
692 if (!AIsWrite && !BIsWrite)
695 // We cannot check pointers in different address spaces.
696 if (APtr->getType()->getPointerAddressSpace() !=
697 BPtr->getType()->getPointerAddressSpace())
700 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
701 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
703 int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides);
704 int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides);
706 const SCEV *Src = AScev;
707 const SCEV *Sink = BScev;
709 // If the induction step is negative we have to invert source and sink of the
711 if (StrideAPtr < 0) {
714 std::swap(APtr, BPtr);
715 std::swap(Src, Sink);
716 std::swap(AIsWrite, BIsWrite);
717 std::swap(AIdx, BIdx);
718 std::swap(StrideAPtr, StrideBPtr);
721 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
723 DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
724 << "(Induction step: " << StrideAPtr << ")\n");
725 DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
726 << *InstMap[BIdx] << ": " << *Dist << "\n");
728 // Need consecutive accesses. We don't want to vectorize
729 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
730 // the address space.
731 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
732 DEBUG(dbgs() << "Non-consecutive pointer access\n");
736 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
738 DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
739 ShouldRetryWithRuntimeCheck = true;
743 Type *ATy = APtr->getType()->getPointerElementType();
744 Type *BTy = BPtr->getType()->getPointerElementType();
745 unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
747 // Negative distances are not plausible dependencies.
748 const APInt &Val = C->getValue()->getValue();
749 if (Val.isNegative()) {
750 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
751 if (IsTrueDataDependence &&
752 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
756 DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
760 // Write to the same location with the same size.
761 // Could be improved to assert type sizes are the same (i32 == float, etc).
765 DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
769 assert(Val.isStrictlyPositive() && "Expect a positive value");
771 // Positive distance bigger than max vectorization factor.
774 "LAA: ReadWrite-Write positive dependency with different types\n");
778 unsigned Distance = (unsigned) Val.getZExtValue();
780 // Bail out early if passed-in parameters make vectorization not feasible.
781 unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
782 VectorizerParams::VectorizationFactor : 1);
783 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
784 VectorizerParams::VectorizationInterleave : 1);
786 // The distance must be bigger than the size needed for a vectorized version
787 // of the operation and the size of the vectorized operation must not be
788 // bigger than the currrent maximum size.
789 if (Distance < 2*TypeByteSize ||
790 2*TypeByteSize > MaxSafeDepDistBytes ||
791 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
792 DEBUG(dbgs() << "LAA: Failure because of Positive distance "
793 << Val.getSExtValue() << '\n');
797 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
798 Distance : MaxSafeDepDistBytes;
800 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
801 if (IsTrueDataDependence &&
802 couldPreventStoreLoadForward(Distance, TypeByteSize))
805 DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue() <<
806 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
811 bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
812 MemAccessInfoSet &CheckDeps,
813 ValueToValueMap &Strides) {
815 MaxSafeDepDistBytes = -1U;
816 while (!CheckDeps.empty()) {
817 MemAccessInfo CurAccess = *CheckDeps.begin();
819 // Get the relevant memory access set.
820 EquivalenceClasses<MemAccessInfo>::iterator I =
821 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
823 // Check accesses within this set.
824 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
825 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
827 // Check every access pair.
829 CheckDeps.erase(*AI);
830 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
832 // Check every accessing instruction pair in program order.
833 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
834 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
835 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
836 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
837 if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
839 if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
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(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();
916 MemoryDepChecker DepChecker(SE, DL, TheLoop);
919 for (Loop::block_iterator bb = TheLoop->block_begin(),
920 be = TheLoop->block_end(); bb != be; ++bb) {
922 // Scan the BB and collect legal loads and stores.
923 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
926 // If this is a load, save it. If this instruction can read from memory
927 // but is not a load, then we quit. Notice that we don't handle function
928 // calls that read or write.
929 if (it->mayReadFromMemory()) {
930 // Many math library functions read the rounding mode. We will only
931 // vectorize a loop if it contains known function calls that don't set
932 // the flag. Therefore, it is safe to ignore this read from memory.
933 CallInst *Call = dyn_cast<CallInst>(it);
934 if (Call && getIntrinsicIDForCall(Call, TLI))
937 LoadInst *Ld = dyn_cast<LoadInst>(it);
938 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
939 emitAnalysis(LoopAccessReport(Ld)
940 << "read with atomic ordering or volatile read");
941 DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
947 DepChecker.addAccess(Ld);
951 // Save 'store' instructions. Abort if other instructions write to memory.
952 if (it->mayWriteToMemory()) {
953 StoreInst *St = dyn_cast<StoreInst>(it);
955 emitAnalysis(LoopAccessReport(it) <<
956 "instruction cannot be vectorized");
960 if (!St->isSimple() && !IsAnnotatedParallel) {
961 emitAnalysis(LoopAccessReport(St)
962 << "write with atomic ordering or volatile write");
963 DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
968 Stores.push_back(St);
969 DepChecker.addAccess(St);
974 // Now we have two lists that hold the loads and the stores.
975 // Next, we find the pointers that they use.
977 // Check if we see any stores. If there are no stores, then we don't
978 // care if the pointers are *restrict*.
979 if (!Stores.size()) {
980 DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
985 AccessAnalysis::DepCandidates DependentAccesses;
986 AccessAnalysis Accesses(DL, 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 ||
1046 !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) {
1048 IsReadOnlyPtr = true;
1051 AliasAnalysis::Location Loc = AA->getLocation(LD);
1052 // The TBAA metadata could have a control dependency on the predication
1053 // condition, so we cannot rely on it when determining whether or not we
1054 // need runtime pointer checks.
1055 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
1056 Loc.AATags.TBAA = nullptr;
1058 Accesses.addLoad(Loc, IsReadOnlyPtr);
1061 // If we write (or read-write) to a single destination and there are no
1062 // other reads in this loop then is it safe to vectorize.
1063 if (NumReadWrites == 1 && NumReads == 0) {
1064 DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
1069 // Build dependence sets and check whether we need a runtime pointer bounds
1071 Accesses.buildDependenceSets();
1072 bool NeedRTCheck = Accesses.isRTCheckNeeded();
1074 // Find pointers with computable bounds. We are going to use this information
1075 // to place a runtime bound check.
1076 unsigned NumComparisons = 0;
1077 bool CanDoRT = false;
1079 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
1082 DEBUG(dbgs() << "LAA: We need to do " << NumComparisons <<
1083 " pointer comparisons.\n");
1085 // If we only have one set of dependences to check pointers among we don't
1086 // need a runtime check.
1087 if (NumComparisons == 0 && NeedRTCheck)
1088 NeedRTCheck = false;
1090 // Check that we did not collect too many pointers or found an unsizeable
1093 NumComparisons > VectorizerParams::RuntimeMemoryCheckThreshold) {
1099 DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
1102 if (NeedRTCheck && !CanDoRT) {
1103 emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
1104 DEBUG(dbgs() << "LAA: We can't vectorize because we can't find " <<
1105 "the array bounds.\n");
1111 PtrRtCheck.Need = NeedRTCheck;
1114 if (Accesses.isDependencyCheckNeeded()) {
1115 DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
1116 CanVecMem = DepChecker.areDepsSafe(
1117 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1118 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1120 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
1121 DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
1124 // Clear the dependency checks. We assume they are not needed.
1125 Accesses.resetDepChecks();
1128 PtrRtCheck.Need = true;
1130 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
1131 TheLoop, Strides, true);
1132 // Check that we did not collect too many pointers or found an unsizeable
1135 NumComparisons > VectorizerParams::RuntimeMemoryCheckThreshold) {
1136 if (!CanDoRT && NumComparisons > 0)
1137 emitAnalysis(LoopAccessReport()
1138 << "cannot check memory dependencies at runtime");
1140 emitAnalysis(LoopAccessReport()
1141 << NumComparisons << " exceeds limit of "
1142 << VectorizerParams::RuntimeMemoryCheckThreshold
1143 << " dependent memory operations checked at runtime");
1144 DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
1155 emitAnalysis(LoopAccessReport() <<
1156 "unsafe dependent memory operations in loop");
1158 DEBUG(dbgs() << "LAA: We" << (NeedRTCheck ? "" : " don't") <<
1159 " need a runtime memory check.\n");
1162 bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1163 DominatorTree *DT) {
1164 assert(TheLoop->contains(BB) && "Unknown block used");
1166 // Blocks that do not dominate the latch need predication.
1167 BasicBlock* Latch = TheLoop->getLoopLatch();
1168 return !DT->dominates(BB, Latch);
1171 void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
1172 assert(!Report && "Multiple report generated");
1176 bool LoopAccessInfo::isUniform(Value *V) const {
1177 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1180 // FIXME: this function is currently a duplicate of the one in
1181 // LoopVectorize.cpp.
1182 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1186 if (Instruction *I = dyn_cast<Instruction>(V))
1187 return I->getParent() == Loc->getParent() ? I : nullptr;
1191 std::pair<Instruction *, Instruction *>
1192 LoopAccessInfo::addRuntimeCheck(Instruction *Loc) const {
1193 Instruction *tnullptr = nullptr;
1194 if (!PtrRtCheck.Need)
1195 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1197 unsigned NumPointers = PtrRtCheck.Pointers.size();
1198 SmallVector<TrackingVH<Value> , 2> Starts;
1199 SmallVector<TrackingVH<Value> , 2> Ends;
1201 LLVMContext &Ctx = Loc->getContext();
1202 SCEVExpander Exp(*SE, "induction");
1203 Instruction *FirstInst = nullptr;
1205 for (unsigned i = 0; i < NumPointers; ++i) {
1206 Value *Ptr = PtrRtCheck.Pointers[i];
1207 const SCEV *Sc = SE->getSCEV(Ptr);
1209 if (SE->isLoopInvariant(Sc, TheLoop)) {
1210 DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" <<
1212 Starts.push_back(Ptr);
1213 Ends.push_back(Ptr);
1215 DEBUG(dbgs() << "LAA: Adding RT check for range:" << *Ptr << '\n');
1216 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1218 // Use this type for pointer arithmetic.
1219 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1221 Value *Start = Exp.expandCodeFor(PtrRtCheck.Starts[i], PtrArithTy, Loc);
1222 Value *End = Exp.expandCodeFor(PtrRtCheck.Ends[i], PtrArithTy, Loc);
1223 Starts.push_back(Start);
1224 Ends.push_back(End);
1228 IRBuilder<> ChkBuilder(Loc);
1229 // Our instructions might fold to a constant.
1230 Value *MemoryRuntimeCheck = nullptr;
1231 for (unsigned i = 0; i < NumPointers; ++i) {
1232 for (unsigned j = i+1; j < NumPointers; ++j) {
1233 if (!PtrRtCheck.needsChecking(i, j))
1236 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1237 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1239 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1240 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1241 "Trying to bounds check pointers with different address spaces");
1243 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1244 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1246 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1247 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1248 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
1249 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
1251 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1252 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1253 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1254 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1255 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1256 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1257 if (MemoryRuntimeCheck) {
1258 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1260 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1262 MemoryRuntimeCheck = IsConflict;
1266 // We have to do this trickery because the IRBuilder might fold the check to a
1267 // constant expression in which case there is no Instruction anchored in a
1269 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1270 ConstantInt::getTrue(Ctx));
1271 ChkBuilder.Insert(Check, "memcheck.conflict");
1272 FirstInst = getFirstInst(FirstInst, Check, Loc);
1273 return std::make_pair(FirstInst, Check);
1276 LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
1277 const DataLayout *DL,
1278 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
1279 DominatorTree *DT, ValueToValueMap &Strides)
1280 : TheLoop(L), SE(SE), DL(DL), TLI(TLI), AA(AA), DT(DT), NumLoads(0),
1281 NumStores(0), MaxSafeDepDistBytes(-1U), CanVecMem(false) {
1282 if (canAnalyzeLoop())
1283 analyzeLoop(Strides);
1286 void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1288 if (PtrRtCheck.empty())
1289 OS.indent(Depth) << "Memory dependences are safe\n";
1291 OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
1295 OS.indent(Depth) << "Report: " << Report->str() << "\n";
1297 // FIXME: Print unsafe dependences
1299 // List the pair of accesses need run-time checks to prove independence.
1300 PtrRtCheck.print(OS, Depth);
1304 const LoopAccessInfo &LoopAccessAnalysis::getInfo(Loop *L,
1305 ValueToValueMap &Strides) {
1306 auto &LAI = LoopAccessInfoMap[L];
1309 assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
1310 "Symbolic strides changed for loop");
1314 LAI = llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, Strides);
1316 LAI->NumSymbolicStrides = Strides.size();
1322 void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
1323 LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
1325 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1326 ValueToValueMap NoSymbolicStrides;
1328 for (Loop *TopLevelLoop : *LI)
1329 for (Loop *L : depth_first(TopLevelLoop)) {
1330 OS.indent(2) << L->getHeader()->getName() << ":\n";
1331 auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
1336 bool LoopAccessAnalysis::runOnFunction(Function &F) {
1337 SE = &getAnalysis<ScalarEvolution>();
1338 DL = F.getParent()->getDataLayout();
1339 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1340 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1341 AA = &getAnalysis<AliasAnalysis>();
1342 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1347 void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
1348 AU.addRequired<ScalarEvolution>();
1349 AU.addRequired<AliasAnalysis>();
1350 AU.addRequired<DominatorTreeWrapperPass>();
1351 AU.addRequired<LoopInfoWrapperPass>();
1353 AU.setPreservesAll();
1356 char LoopAccessAnalysis::ID = 0;
1357 static const char laa_name[] = "Loop Access Analysis";
1358 #define LAA_NAME "loop-accesses"
1360 INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1361 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1362 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1363 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1364 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
1365 INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1368 Pass *createLAAPass() {
1369 return new LoopAccessAnalysis();