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/ValueTracking.h"
18 #include "llvm/IR/DiagnosticInfo.h"
19 #include "llvm/IR/Dominators.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Transforms/Utils/VectorUtils.h"
24 #define DEBUG_TYPE "loop-vectorize"
26 void VectorizationReport::emitAnalysis(VectorizationReport &Message,
27 const Function *TheFunction,
28 const Loop *TheLoop) {
29 DebugLoc DL = TheLoop->getStartLoc();
30 if (Instruction *I = Message.getInstr())
31 DL = I->getDebugLoc();
32 emitOptimizationRemarkAnalysis(TheFunction->getContext(), DEBUG_TYPE,
33 *TheFunction, DL, Message.str());
36 Value *llvm::stripIntegerCast(Value *V) {
37 if (CastInst *CI = dyn_cast<CastInst>(V))
38 if (CI->getOperand(0)->getType()->isIntegerTy())
39 return CI->getOperand(0);
43 const SCEV *llvm::replaceSymbolicStrideSCEV(ScalarEvolution *SE,
44 ValueToValueMap &PtrToStride,
45 Value *Ptr, Value *OrigPtr) {
47 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
49 // If there is an entry in the map return the SCEV of the pointer with the
50 // symbolic stride replaced by one.
51 ValueToValueMap::iterator SI = PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
52 if (SI != PtrToStride.end()) {
53 Value *StrideVal = SI->second;
56 StrideVal = stripIntegerCast(StrideVal);
58 // Replace symbolic stride by one.
59 Value *One = ConstantInt::get(StrideVal->getType(), 1);
60 ValueToValueMap RewriteMap;
61 RewriteMap[StrideVal] = One;
64 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
65 DEBUG(dbgs() << "LV: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
70 // Otherwise, just return the SCEV of the original pointer.
71 return SE->getSCEV(Ptr);
74 void LoopAccessAnalysis::RuntimePointerCheck::insert(ScalarEvolution *SE,
79 ValueToValueMap &Strides) {
80 // Get the stride replaced scev.
81 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
82 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
83 assert(AR && "Invalid addrec expression");
84 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
85 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
86 Pointers.push_back(Ptr);
87 Starts.push_back(AR->getStart());
88 Ends.push_back(ScEnd);
89 IsWritePtr.push_back(WritePtr);
90 DependencySetId.push_back(DepSetId);
91 AliasSetId.push_back(ASId);
95 /// \brief Analyses memory accesses in a loop.
97 /// Checks whether run time pointer checks are needed and builds sets for data
98 /// dependence checking.
99 class AccessAnalysis {
101 /// \brief Read or write access location.
102 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
103 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
105 /// \brief Set of potential dependent memory accesses.
106 typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
108 AccessAnalysis(const DataLayout *Dl, AliasAnalysis *AA, DepCandidates &DA) :
109 DL(Dl), AST(*AA), DepCands(DA), IsRTCheckNeeded(false) {}
111 /// \brief Register a load and whether it is only read from.
112 void addLoad(AliasAnalysis::Location &Loc, bool IsReadOnly) {
113 Value *Ptr = const_cast<Value*>(Loc.Ptr);
114 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
115 Accesses.insert(MemAccessInfo(Ptr, false));
117 ReadOnlyPtr.insert(Ptr);
120 /// \brief Register a store.
121 void addStore(AliasAnalysis::Location &Loc) {
122 Value *Ptr = const_cast<Value*>(Loc.Ptr);
123 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
124 Accesses.insert(MemAccessInfo(Ptr, true));
127 /// \brief Check whether we can check the pointers at runtime for
128 /// non-intersection.
129 bool canCheckPtrAtRT(LoopAccessAnalysis::RuntimePointerCheck &RtCheck,
130 unsigned &NumComparisons,
131 ScalarEvolution *SE, Loop *TheLoop,
132 ValueToValueMap &Strides,
133 bool ShouldCheckStride = false);
135 /// \brief Goes over all memory accesses, checks whether a RT check is needed
136 /// and builds sets of dependent accesses.
137 void buildDependenceSets() {
138 processMemAccesses();
141 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
143 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
144 void resetDepChecks() { CheckDeps.clear(); }
146 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
149 typedef SetVector<MemAccessInfo> PtrAccessSet;
151 /// \brief Go over all memory access and check whether runtime pointer checks
152 /// are needed /// and build sets of dependency check candidates.
153 void processMemAccesses();
155 /// Set of all accesses.
156 PtrAccessSet Accesses;
158 /// Set of accesses that need a further dependence check.
159 MemAccessInfoSet CheckDeps;
161 /// Set of pointers that are read only.
162 SmallPtrSet<Value*, 16> ReadOnlyPtr;
164 const DataLayout *DL;
166 /// An alias set tracker to partition the access set by underlying object and
167 //intrinsic property (such as TBAA metadata).
170 /// Sets of potentially dependent accesses - members of one set share an
171 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
172 /// dependence check.
173 DepCandidates &DepCands;
175 bool IsRTCheckNeeded;
178 } // end anonymous namespace
180 /// \brief Check whether a pointer can participate in a runtime bounds check.
181 static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides,
183 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
184 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
188 return AR->isAffine();
191 /// \brief Check the stride of the pointer and ensure that it does not wrap in
192 /// the address space.
193 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
194 const Loop *Lp, ValueToValueMap &StridesMap);
196 bool AccessAnalysis::canCheckPtrAtRT(
197 LoopAccessAnalysis::RuntimePointerCheck &RtCheck,
198 unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop,
199 ValueToValueMap &StridesMap, bool ShouldCheckStride) {
200 // Find pointers with computable bounds. We are going to use this information
201 // to place a runtime bound check.
204 bool IsDepCheckNeeded = isDependencyCheckNeeded();
207 // We assign a consecutive id to access from different alias sets.
208 // Accesses between different groups doesn't need to be checked.
210 for (auto &AS : AST) {
211 unsigned NumReadPtrChecks = 0;
212 unsigned NumWritePtrChecks = 0;
214 // We assign consecutive id to access from different dependence sets.
215 // Accesses within the same set don't need a runtime check.
216 unsigned RunningDepId = 1;
217 DenseMap<Value *, unsigned> DepSetId;
220 Value *Ptr = A.getValue();
221 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
222 MemAccessInfo Access(Ptr, IsWrite);
229 if (hasComputableBounds(SE, StridesMap, Ptr) &&
230 // When we run after a failing dependency check we have to make sure we
231 // don't have wrapping pointers.
232 (!ShouldCheckStride ||
233 isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) {
234 // The id of the dependence set.
237 if (IsDepCheckNeeded) {
238 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
239 unsigned &LeaderId = DepSetId[Leader];
241 LeaderId = RunningDepId++;
244 // Each access has its own dependence set.
245 DepId = RunningDepId++;
247 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
249 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *Ptr << '\n');
255 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
256 NumComparisons += 0; // Only one dependence set.
258 NumComparisons += (NumWritePtrChecks * (NumReadPtrChecks +
259 NumWritePtrChecks - 1));
265 // If the pointers that we would use for the bounds comparison have different
266 // address spaces, assume the values aren't directly comparable, so we can't
267 // use them for the runtime check. We also have to assume they could
268 // overlap. In the future there should be metadata for whether address spaces
270 unsigned NumPointers = RtCheck.Pointers.size();
271 for (unsigned i = 0; i < NumPointers; ++i) {
272 for (unsigned j = i + 1; j < NumPointers; ++j) {
273 // Only need to check pointers between two different dependency sets.
274 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
276 // Only need to check pointers in the same alias set.
277 if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j])
280 Value *PtrI = RtCheck.Pointers[i];
281 Value *PtrJ = RtCheck.Pointers[j];
283 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
284 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
286 DEBUG(dbgs() << "LV: Runtime check would require comparison between"
287 " different address spaces\n");
296 void AccessAnalysis::processMemAccesses() {
297 // We process the set twice: first we process read-write pointers, last we
298 // process read-only pointers. This allows us to skip dependence tests for
299 // read-only pointers.
301 DEBUG(dbgs() << "LV: Processing memory accesses...\n");
302 DEBUG(dbgs() << " AST: "; AST.dump());
303 DEBUG(dbgs() << "LV: Accesses:\n");
305 for (auto A : Accesses)
306 dbgs() << "\t" << *A.getPointer() << " (" <<
307 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
308 "read-only" : "read")) << ")\n";
311 // The AliasSetTracker has nicely partitioned our pointers by metadata
312 // compatibility and potential for underlying-object overlap. As a result, we
313 // only need to check for potential pointer dependencies within each alias
315 for (auto &AS : AST) {
316 // Note that both the alias-set tracker and the alias sets themselves used
317 // linked lists internally and so the iteration order here is deterministic
318 // (matching the original instruction order within each set).
320 bool SetHasWrite = false;
322 // Map of pointers to last access encountered.
323 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
324 UnderlyingObjToAccessMap ObjToLastAccess;
326 // Set of access to check after all writes have been processed.
327 PtrAccessSet DeferredAccesses;
329 // Iterate over each alias set twice, once to process read/write pointers,
330 // and then to process read-only pointers.
331 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
332 bool UseDeferred = SetIteration > 0;
333 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
336 Value *Ptr = AV.getValue();
338 // For a single memory access in AliasSetTracker, Accesses may contain
339 // both read and write, and they both need to be handled for CheckDeps.
341 if (AC.getPointer() != Ptr)
344 bool IsWrite = AC.getInt();
346 // If we're using the deferred access set, then it contains only
348 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
349 if (UseDeferred && !IsReadOnlyPtr)
351 // Otherwise, the pointer must be in the PtrAccessSet, either as a
353 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
354 S.count(MemAccessInfo(Ptr, false))) &&
355 "Alias-set pointer not in the access set?");
357 MemAccessInfo Access(Ptr, IsWrite);
358 DepCands.insert(Access);
360 // Memorize read-only pointers for later processing and skip them in
361 // the first round (they need to be checked after we have seen all
362 // write pointers). Note: we also mark pointer that are not
363 // consecutive as "read-only" pointers (so that we check
364 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
365 if (!UseDeferred && IsReadOnlyPtr) {
366 DeferredAccesses.insert(Access);
370 // If this is a write - check other reads and writes for conflicts. If
371 // this is a read only check other writes for conflicts (but only if
372 // there is no other write to the ptr - this is an optimization to
373 // catch "a[i] = a[i] + " without having to do a dependence check).
374 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
375 CheckDeps.insert(Access);
376 IsRTCheckNeeded = true;
382 // Create sets of pointers connected by a shared alias set and
383 // underlying object.
384 typedef SmallVector<Value *, 16> ValueVector;
385 ValueVector TempObjects;
386 GetUnderlyingObjects(Ptr, TempObjects, DL);
387 for (Value *UnderlyingObj : TempObjects) {
388 UnderlyingObjToAccessMap::iterator Prev =
389 ObjToLastAccess.find(UnderlyingObj);
390 if (Prev != ObjToLastAccess.end())
391 DepCands.unionSets(Access, Prev->second);
393 ObjToLastAccess[UnderlyingObj] = Access;
402 /// \brief Checks memory dependences among accesses to the same underlying
403 /// object to determine whether there vectorization is legal or not (and at
404 /// which vectorization factor).
406 /// This class works under the assumption that we already checked that memory
407 /// locations with different underlying pointers are "must-not alias".
408 /// We use the ScalarEvolution framework to symbolically evalutate access
409 /// functions pairs. Since we currently don't restructure the loop we can rely
410 /// on the program order of memory accesses to determine their safety.
411 /// At the moment we will only deem accesses as safe for:
412 /// * A negative constant distance assuming program order.
414 /// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
415 /// a[i] = tmp; y = a[i];
417 /// The latter case is safe because later checks guarantuee that there can't
418 /// be a cycle through a phi node (that is, we check that "x" and "y" is not
419 /// the same variable: a header phi can only be an induction or a reduction, a
420 /// reduction can't have a memory sink, an induction can't have a memory
421 /// source). This is important and must not be violated (or we have to
422 /// resort to checking for cycles through memory).
424 /// * A positive constant distance assuming program order that is bigger
425 /// than the biggest memory access.
427 /// tmp = a[i] OR b[i] = x
428 /// a[i+2] = tmp y = b[i+2];
430 /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
432 /// * Zero distances and all accesses have the same size.
434 class MemoryDepChecker {
436 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
437 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
439 MemoryDepChecker(ScalarEvolution *Se, const DataLayout *Dl, const Loop *L,
440 const LoopAccessAnalysis::VectorizerParams &VectParams)
441 : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0),
442 ShouldRetryWithRuntimeCheck(false), VectParams(VectParams) {}
444 /// \brief Register the location (instructions are given increasing numbers)
445 /// of a write access.
446 void addAccess(StoreInst *SI) {
447 Value *Ptr = SI->getPointerOperand();
448 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
449 InstMap.push_back(SI);
453 /// \brief Register the location (instructions are given increasing numbers)
454 /// of a write access.
455 void addAccess(LoadInst *LI) {
456 Value *Ptr = LI->getPointerOperand();
457 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
458 InstMap.push_back(LI);
462 /// \brief Check whether the dependencies between the accesses are safe.
464 /// Only checks sets with elements in \p CheckDeps.
465 bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
466 MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides);
468 /// \brief The maximum number of bytes of a vector register we can vectorize
469 /// the accesses safely with.
470 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
472 /// \brief In same cases when the dependency check fails we can still
473 /// vectorize the loop with a dynamic array access check.
474 bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
478 const DataLayout *DL;
479 const Loop *InnermostLoop;
481 /// \brief Maps access locations (ptr, read/write) to program order.
482 DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
484 /// \brief Memory access instructions in program order.
485 SmallVector<Instruction *, 16> InstMap;
487 /// \brief The program order index to be used for the next instruction.
490 // We can access this many bytes in parallel safely.
491 unsigned MaxSafeDepDistBytes;
493 /// \brief If we see a non-constant dependence distance we can still try to
494 /// vectorize this loop with runtime checks.
495 bool ShouldRetryWithRuntimeCheck;
497 /// \brief Vectorizer parameters used by the analysis.
498 LoopAccessAnalysis::VectorizerParams VectParams;
500 /// \brief Check whether there is a plausible dependence between the two
503 /// Access \p A must happen before \p B in program order. The two indices
504 /// identify the index into the program order map.
506 /// This function checks whether there is a plausible dependence (or the
507 /// absence of such can't be proved) between the two accesses. If there is a
508 /// plausible dependence but the dependence distance is bigger than one
509 /// element access it records this distance in \p MaxSafeDepDistBytes (if this
510 /// distance is smaller than any other distance encountered so far).
511 /// Otherwise, this function returns true signaling a possible dependence.
512 bool isDependent(const MemAccessInfo &A, unsigned AIdx,
513 const MemAccessInfo &B, unsigned BIdx,
514 ValueToValueMap &Strides);
516 /// \brief Check whether the data dependence could prevent store-load
518 bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
521 } // end anonymous namespace
523 static bool isInBoundsGep(Value *Ptr) {
524 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
525 return GEP->isInBounds();
529 /// \brief Check whether the access through \p Ptr has a constant stride.
530 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
531 const Loop *Lp, ValueToValueMap &StridesMap) {
532 const Type *Ty = Ptr->getType();
533 assert(Ty->isPointerTy() && "Unexpected non-ptr");
535 // Make sure that the pointer does not point to aggregate types.
536 const PointerType *PtrTy = cast<PointerType>(Ty);
537 if (PtrTy->getElementType()->isAggregateType()) {
538 DEBUG(dbgs() << "LV: Bad stride - Not a pointer to a scalar type" << *Ptr <<
543 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
545 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
547 DEBUG(dbgs() << "LV: Bad stride - Not an AddRecExpr pointer "
548 << *Ptr << " SCEV: " << *PtrScev << "\n");
552 // The accesss function must stride over the innermost loop.
553 if (Lp != AR->getLoop()) {
554 DEBUG(dbgs() << "LV: Bad stride - Not striding over innermost loop " <<
555 *Ptr << " SCEV: " << *PtrScev << "\n");
558 // The address calculation must not wrap. Otherwise, a dependence could be
560 // An inbounds getelementptr that is a AddRec with a unit stride
561 // cannot wrap per definition. The unit stride requirement is checked later.
562 // An getelementptr without an inbounds attribute and unit stride would have
563 // to access the pointer value "0" which is undefined behavior in address
564 // space 0, therefore we can also vectorize this case.
565 bool IsInBoundsGEP = isInBoundsGep(Ptr);
566 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
567 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
568 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
569 DEBUG(dbgs() << "LV: Bad stride - Pointer may wrap in the address space "
570 << *Ptr << " SCEV: " << *PtrScev << "\n");
574 // Check the step is constant.
575 const SCEV *Step = AR->getStepRecurrence(*SE);
577 // Calculate the pointer stride and check if it is consecutive.
578 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
580 DEBUG(dbgs() << "LV: Bad stride - Not a constant strided " << *Ptr <<
581 " SCEV: " << *PtrScev << "\n");
585 int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
586 const APInt &APStepVal = C->getValue()->getValue();
588 // Huge step value - give up.
589 if (APStepVal.getBitWidth() > 64)
592 int64_t StepVal = APStepVal.getSExtValue();
595 int64_t Stride = StepVal / Size;
596 int64_t Rem = StepVal % Size;
600 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
601 // know we can't "wrap around the address space". In case of address space
602 // zero we know that this won't happen without triggering undefined behavior.
603 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
604 Stride != 1 && Stride != -1)
610 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
611 unsigned TypeByteSize) {
612 // If loads occur at a distance that is not a multiple of a feasible vector
613 // factor store-load forwarding does not take place.
614 // Positive dependences might cause troubles because vectorizing them might
615 // prevent store-load forwarding making vectorized code run a lot slower.
616 // a[i] = a[i-3] ^ a[i-8];
617 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
618 // hence on your typical architecture store-load forwarding does not take
619 // place. Vectorizing in such cases does not make sense.
620 // Store-load forwarding distance.
621 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
622 // Maximum vector factor.
623 unsigned MaxVFWithoutSLForwardIssues = VectParams.MaxVectorWidth*TypeByteSize;
624 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
625 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
627 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
629 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
630 MaxVFWithoutSLForwardIssues = (vf >>=1);
635 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
636 DEBUG(dbgs() << "LV: Distance " << Distance <<
637 " that could cause a store-load forwarding conflict\n");
641 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
642 MaxVFWithoutSLForwardIssues != VectParams.MaxVectorWidth*TypeByteSize)
643 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
647 bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
648 const MemAccessInfo &B, unsigned BIdx,
649 ValueToValueMap &Strides) {
650 assert (AIdx < BIdx && "Must pass arguments in program order");
652 Value *APtr = A.getPointer();
653 Value *BPtr = B.getPointer();
654 bool AIsWrite = A.getInt();
655 bool BIsWrite = B.getInt();
657 // Two reads are independent.
658 if (!AIsWrite && !BIsWrite)
661 // We cannot check pointers in different address spaces.
662 if (APtr->getType()->getPointerAddressSpace() !=
663 BPtr->getType()->getPointerAddressSpace())
666 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
667 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
669 int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides);
670 int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides);
672 const SCEV *Src = AScev;
673 const SCEV *Sink = BScev;
675 // If the induction step is negative we have to invert source and sink of the
677 if (StrideAPtr < 0) {
680 std::swap(APtr, BPtr);
681 std::swap(Src, Sink);
682 std::swap(AIsWrite, BIsWrite);
683 std::swap(AIdx, BIdx);
684 std::swap(StrideAPtr, StrideBPtr);
687 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
689 DEBUG(dbgs() << "LV: Src Scev: " << *Src << "Sink Scev: " << *Sink
690 << "(Induction step: " << StrideAPtr << ")\n");
691 DEBUG(dbgs() << "LV: Distance for " << *InstMap[AIdx] << " to "
692 << *InstMap[BIdx] << ": " << *Dist << "\n");
694 // Need consecutive accesses. We don't want to vectorize
695 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
696 // the address space.
697 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
698 DEBUG(dbgs() << "Non-consecutive pointer access\n");
702 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
704 DEBUG(dbgs() << "LV: Dependence because of non-constant distance\n");
705 ShouldRetryWithRuntimeCheck = true;
709 Type *ATy = APtr->getType()->getPointerElementType();
710 Type *BTy = BPtr->getType()->getPointerElementType();
711 unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
713 // Negative distances are not plausible dependencies.
714 const APInt &Val = C->getValue()->getValue();
715 if (Val.isNegative()) {
716 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
717 if (IsTrueDataDependence &&
718 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
722 DEBUG(dbgs() << "LV: Dependence is negative: NoDep\n");
726 // Write to the same location with the same size.
727 // Could be improved to assert type sizes are the same (i32 == float, etc).
731 DEBUG(dbgs() << "LV: Zero dependence difference but different types\n");
735 assert(Val.isStrictlyPositive() && "Expect a positive value");
737 // Positive distance bigger than max vectorization factor.
740 "LV: ReadWrite-Write positive dependency with different types\n");
744 unsigned Distance = (unsigned) Val.getZExtValue();
746 // Bail out early if passed-in parameters make vectorization not feasible.
747 unsigned ForcedFactor = (VectParams.VectorizationFactor ?
748 VectParams.VectorizationFactor : 1);
749 unsigned ForcedUnroll = (VectParams.VectorizationInterleave ?
750 VectParams.VectorizationInterleave : 1);
752 // The distance must be bigger than the size needed for a vectorized version
753 // of the operation and the size of the vectorized operation must not be
754 // bigger than the currrent maximum size.
755 if (Distance < 2*TypeByteSize ||
756 2*TypeByteSize > MaxSafeDepDistBytes ||
757 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
758 DEBUG(dbgs() << "LV: Failure because of Positive distance "
759 << Val.getSExtValue() << '\n');
763 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
764 Distance : MaxSafeDepDistBytes;
766 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
767 if (IsTrueDataDependence &&
768 couldPreventStoreLoadForward(Distance, TypeByteSize))
771 DEBUG(dbgs() << "LV: Positive distance " << Val.getSExtValue() <<
772 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
777 bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
778 MemAccessInfoSet &CheckDeps,
779 ValueToValueMap &Strides) {
781 MaxSafeDepDistBytes = -1U;
782 while (!CheckDeps.empty()) {
783 MemAccessInfo CurAccess = *CheckDeps.begin();
785 // Get the relevant memory access set.
786 EquivalenceClasses<MemAccessInfo>::iterator I =
787 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
789 // Check accesses within this set.
790 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
791 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
793 // Check every access pair.
795 CheckDeps.erase(*AI);
796 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
798 // Check every accessing instruction pair in program order.
799 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
800 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
801 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
802 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
803 if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
805 if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
816 bool LoopAccessAnalysis::canVectorizeMemory(ValueToValueMap &Strides) {
818 typedef SmallVector<Value*, 16> ValueVector;
819 typedef SmallPtrSet<Value*, 16> ValueSet;
821 // Holds the Load and Store *instructions*.
825 // Holds all the different accesses in the loop.
826 unsigned NumReads = 0;
827 unsigned NumReadWrites = 0;
829 PtrRtCheck.Pointers.clear();
830 PtrRtCheck.Need = false;
832 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
833 MemoryDepChecker DepChecker(SE, DL, TheLoop, VectParams);
836 for (Loop::block_iterator bb = TheLoop->block_begin(),
837 be = TheLoop->block_end(); bb != be; ++bb) {
839 // Scan the BB and collect legal loads and stores.
840 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
843 // If this is a load, save it. If this instruction can read from memory
844 // but is not a load, then we quit. Notice that we don't handle function
845 // calls that read or write.
846 if (it->mayReadFromMemory()) {
847 // Many math library functions read the rounding mode. We will only
848 // vectorize a loop if it contains known function calls that don't set
849 // the flag. Therefore, it is safe to ignore this read from memory.
850 CallInst *Call = dyn_cast<CallInst>(it);
851 if (Call && getIntrinsicIDForCall(Call, TLI))
854 LoadInst *Ld = dyn_cast<LoadInst>(it);
855 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
856 emitAnalysis(VectorizationReport(Ld)
857 << "read with atomic ordering or volatile read");
858 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
863 DepChecker.addAccess(Ld);
867 // Save 'store' instructions. Abort if other instructions write to memory.
868 if (it->mayWriteToMemory()) {
869 StoreInst *St = dyn_cast<StoreInst>(it);
871 emitAnalysis(VectorizationReport(it) <<
872 "instruction cannot be vectorized");
875 if (!St->isSimple() && !IsAnnotatedParallel) {
876 emitAnalysis(VectorizationReport(St)
877 << "write with atomic ordering or volatile write");
878 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
882 Stores.push_back(St);
883 DepChecker.addAccess(St);
888 // Now we have two lists that hold the loads and the stores.
889 // Next, we find the pointers that they use.
891 // Check if we see any stores. If there are no stores, then we don't
892 // care if the pointers are *restrict*.
893 if (!Stores.size()) {
894 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
898 AccessAnalysis::DepCandidates DependentAccesses;
899 AccessAnalysis Accesses(DL, AA, DependentAccesses);
901 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
902 // multiple times on the same object. If the ptr is accessed twice, once
903 // for read and once for write, it will only appear once (on the write
904 // list). This is okay, since we are going to check for conflicts between
905 // writes and between reads and writes, but not between reads and reads.
908 ValueVector::iterator I, IE;
909 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
910 StoreInst *ST = cast<StoreInst>(*I);
911 Value* Ptr = ST->getPointerOperand();
913 if (isUniform(Ptr)) {
915 VectorizationReport(ST)
916 << "write to a loop invariant address could not be vectorized");
917 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
921 // If we did *not* see this pointer before, insert it to the read-write
922 // list. At this phase it is only a 'write' list.
923 if (Seen.insert(Ptr).second) {
926 AliasAnalysis::Location Loc = AA->getLocation(ST);
927 // The TBAA metadata could have a control dependency on the predication
928 // condition, so we cannot rely on it when determining whether or not we
929 // need runtime pointer checks.
930 if (blockNeedsPredication(ST->getParent()))
931 Loc.AATags.TBAA = nullptr;
933 Accesses.addStore(Loc);
937 if (IsAnnotatedParallel) {
939 << "LV: A loop annotated parallel, ignore memory dependency "
944 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
945 LoadInst *LD = cast<LoadInst>(*I);
946 Value* Ptr = LD->getPointerOperand();
947 // If we did *not* see this pointer before, insert it to the
948 // read list. If we *did* see it before, then it is already in
949 // the read-write list. This allows us to vectorize expressions
950 // such as A[i] += x; Because the address of A[i] is a read-write
951 // pointer. This only works if the index of A[i] is consecutive.
952 // If the address of i is unknown (for example A[B[i]]) then we may
953 // read a few words, modify, and write a few words, and some of the
954 // words may be written to the same address.
955 bool IsReadOnlyPtr = false;
956 if (Seen.insert(Ptr).second ||
957 !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) {
959 IsReadOnlyPtr = true;
962 AliasAnalysis::Location Loc = AA->getLocation(LD);
963 // The TBAA metadata could have a control dependency on the predication
964 // condition, so we cannot rely on it when determining whether or not we
965 // need runtime pointer checks.
966 if (blockNeedsPredication(LD->getParent()))
967 Loc.AATags.TBAA = nullptr;
969 Accesses.addLoad(Loc, IsReadOnlyPtr);
972 // If we write (or read-write) to a single destination and there are no
973 // other reads in this loop then is it safe to vectorize.
974 if (NumReadWrites == 1 && NumReads == 0) {
975 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
979 // Build dependence sets and check whether we need a runtime pointer bounds
981 Accesses.buildDependenceSets();
982 bool NeedRTCheck = Accesses.isRTCheckNeeded();
984 // Find pointers with computable bounds. We are going to use this information
985 // to place a runtime bound check.
986 unsigned NumComparisons = 0;
987 bool CanDoRT = false;
989 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
992 DEBUG(dbgs() << "LV: We need to do " << NumComparisons <<
993 " pointer comparisons.\n");
995 // If we only have one set of dependences to check pointers among we don't
996 // need a runtime check.
997 if (NumComparisons == 0 && NeedRTCheck)
1000 // Check that we did not collect too many pointers or found an unsizeable
1002 if (!CanDoRT || NumComparisons > VectParams.RuntimeMemoryCheckThreshold) {
1008 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
1011 if (NeedRTCheck && !CanDoRT) {
1012 emitAnalysis(VectorizationReport() << "cannot identify array bounds");
1013 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
1014 "the array bounds.\n");
1019 PtrRtCheck.Need = NeedRTCheck;
1021 bool CanVecMem = true;
1022 if (Accesses.isDependencyCheckNeeded()) {
1023 DEBUG(dbgs() << "LV: Checking memory dependencies\n");
1024 CanVecMem = DepChecker.areDepsSafe(
1025 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1026 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1028 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
1029 DEBUG(dbgs() << "LV: Retrying with memory checks\n");
1032 // Clear the dependency checks. We assume they are not needed.
1033 Accesses.resetDepChecks();
1036 PtrRtCheck.Need = true;
1038 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
1039 TheLoop, Strides, true);
1040 // Check that we did not collect too many pointers or found an unsizeable
1042 if (!CanDoRT || NumComparisons > VectParams.RuntimeMemoryCheckThreshold) {
1043 if (!CanDoRT && NumComparisons > 0)
1044 emitAnalysis(VectorizationReport()
1045 << "cannot check memory dependencies at runtime");
1047 emitAnalysis(VectorizationReport()
1048 << NumComparisons << " exceeds limit of "
1049 << VectParams.RuntimeMemoryCheckThreshold
1050 << " dependent memory operations checked at runtime");
1051 DEBUG(dbgs() << "LV: Can't vectorize with memory checks\n");
1061 emitAnalysis(VectorizationReport() <<
1062 "unsafe dependent memory operations in loop");
1064 DEBUG(dbgs() << "LV: We" << (NeedRTCheck ? "" : " don't") <<
1065 " need a runtime memory check.\n");
1070 bool LoopAccessAnalysis::blockNeedsPredication(BasicBlock *BB) {
1071 assert(TheLoop->contains(BB) && "Unknown block used");
1073 // Blocks that do not dominate the latch need predication.
1074 BasicBlock* Latch = TheLoop->getLoopLatch();
1075 return !DT->dominates(BB, Latch);
1078 void LoopAccessAnalysis::emitAnalysis(VectorizationReport &Message) {
1079 VectorizationReport::emitAnalysis(Message, TheFunction, TheLoop);
1082 bool LoopAccessAnalysis::isUniform(Value *V) {
1083 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));