[llvm] [SLP] Add store-to-load forwarding conflict cost for widened store chains (PR #199606)
Alexey Bataev via llvm-commits
llvm-commits at lists.llvm.org
Sun Oct 11 09:13:28 PDT 2026
================
@@ -29454,6 +29701,307 @@ bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
return Changed;
}
+/// Returns the constant loop-carried byte stride of \p Ptr in \p L, i.e. the
+/// step of its affine SCEV recurrence, 0 when \p Ptr is loop-invariant (it
+/// never moves, so its "stride" is trivially constant), or std::nullopt when
+/// \p Ptr is neither a simple affine recurrence in \p L with a constant step
+/// nor loop-invariant. This is the same notion as LoopAccessAnalysis's
+/// CommonStride; it is computed here directly from ScalarEvolution rather
+/// than via getPtrStride, whose no-wrap versioning and
+/// PredicatedScalarEvolution machinery is meant for legality, not costing.
+static std::optional<int64_t>
+getConstantLoopStrideInBytes(Value *Ptr, ScalarEvolution &SE, const Loop *L) {
+ const SCEV *PtrSCEV = SE.getSCEV(Ptr);
+ const auto *AR = dyn_cast<SCEVAddRecExpr>(PtrSCEV);
+ if (!AR || AR->getLoop() != L)
+ return SE.isLoopInvariant(PtrSCEV, L) ? std::make_optional<int64_t>(0)
+ : std::nullopt;
+ const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE));
+ if (!Step)
+ return std::nullopt;
+ const APInt &StepVal = Step->getAPInt();
+ if (StepVal.getSignificantBits() > 64)
+ return std::nullopt;
+ return StepVal.getSExtValue();
+}
+
+bool BoUpSLP::findStoreLoadForwardingConflict(
+ StoreInst *BaseStore, unsigned VF, LoadInst *OnlyLoad,
+ std::optional<uint64_t> LoadSizeOverride,
+ SmallVectorImpl<LoadInst *> *ConflictingLoads,
+ std::optional<uint64_t> StoreSizeOverride) {
+ assert(BaseStore && "Expected a valid base store");
+
+ Type *StoreTy = getValueType(BaseStore, SLPReVec);
+ // A scalable stored type has no fixed byte window. Bail out before
+ // getNumElements, which rejects scalable vectors.
+ if (isa<ScalableVectorType>(StoreTy))
+ return false;
+ Type *ValueTy = StoreTy->getScalarType();
+ TypeSize StoreSize = DL->getTypeStoreSize(ValueTy);
+ if (StoreSize.isScalable())
+ return false;
+ uint64_t ElementSize = StoreSize.getFixedValue();
+ if (ElementSize == 0)
+ return false;
+
+ // Store-to-load forwarding hazards are a loop-carried concern.
+ const Loop *StoreL = LI->getLoopFor(BaseStore->getParent());
+ if (!StoreL)
+ return false;
+
+ uint64_t VectorStoreBytes = StoreSizeOverride
+ ? *StoreSizeOverride
+ : VF * getNumElements(StoreTy) * ElementSize;
+ LLVM_DEBUG(dbgs() << "SLP: STLF check: VF=" << VF
+ << " ElementSize=" << ElementSize
+ << " VectorStoreBytes=" << VectorStoreBytes << "\n");
+
+ // Loop-carried byte stride of the store. A conflict is only a real hazard if
+ // a future iteration's load re-reads the bytes this store wrote, which is a
+ // property of the stride (see the per-load check below).
+ std::optional<int64_t> StoreStride =
+ getConstantLoopStrideInBytes(BaseStore->getPointerOperand(), *SE, StoreL);
+
+ // A store-to-load forwarding hazard can involve any load in the loop that
+ // reads the widened store's base, not only loads that became SLP tree nodes:
+ // a conflicting load may feed a scalar store, sit below a gather/splat leaf,
+ // or be vectorized in a different tree. Enumerate every simple load in the
+ // store's loop that shares the store base. The widened width below is only
+ // visible for loads in the current tree; loads vectorized by other trees are
+ // modeled at scalar width.
+ Value *StoreBase = getUnderlyingObject(BaseStore->getPointerOperand());
+ const auto CandidateLoads = [&] {
+ SmallVector<LoadInst *> Loads;
+ if (OnlyLoad) {
+ if (OnlyLoad->isSimple() &&
+ getUnderlyingObject(OnlyLoad->getPointerOperand()) == StoreBase)
+ Loads.push_back(OnlyLoad);
+ return Loads;
+ }
+ for (BasicBlock *BB : StoreL->blocks())
+ for (Instruction &I : *BB)
+ if (auto *LoadI = dyn_cast<LoadInst>(&I))
+ if (LoadI->isSimple() &&
+ getUnderlyingObject(LoadI->getPointerOperand()) == StoreBase)
+ Loads.push_back(LoadI);
+ return Loads;
+ }();
+
+ if (CandidateLoads.empty())
+ return false;
+
+ // For each candidate load, the widened chain becomes one wide store at the
+ // base; check whether the load straddles two such wide stores.
+ for (LoadInst *LoadI : CandidateLoads) {
+ // Only loads in the store's loop share its loop-carried dependence.
+ if (LI->getLoopFor(LoadI->getParent()) != StoreL)
+ continue;
+ const TreeEntry *WidenedLoadEntry = nullptr;
+ for (const TreeEntry *LTE : getTreeEntries(LoadI)) {
+ if (LTE->isGather() || DeletedNodes.contains(LTE) ||
+ TransformedToGatherNodes.contains(LTE))
+ continue;
+ if (LTE->hasState() &&
+ (LTE->State == TreeEntry::Vectorize ||
+ LTE->State == TreeEntry::CompressVectorize) &&
+ LTE->getOpcode() == Instruction::Load) {
+ WidenedLoadEntry = LTE;
+ break;
+ }
+ }
+ // Interior lanes are not independent wide loads; the base lane's
+ // evaluation covers the whole widened load.
+ bool IsWidenedBaseLane = WidenedLoadEntry != nullptr;
+ if (WidenedLoadEntry) {
+ for (Value *V : WidenedLoadEntry->Scalars) {
+ auto *OtherLd = dyn_cast<LoadInst>(V);
+ if (!OtherLd || OtherLd == LoadI)
+ continue;
+ std::optional<int64_t> LaneDiff = getPointersDiff(
+ LoadI->getType(), LoadI->getPointerOperand(), OtherLd->getType(),
+ OtherLd->getPointerOperand(), *DL, *SE, /*StrictCheck=*/false,
+ /*CheckType=*/false);
+ // Another lane sits at a lower address, so LoadI is not the base.
+ if (LaneDiff && *LaneDiff < 0) {
+ IsWidenedBaseLane = false;
+ break;
+ }
+ }
+ if (!IsWidenedBaseLane)
+ continue;
+ }
+ std::optional<int64_t> Diff =
+ getPointersDiff(ValueTy, BaseStore->getPointerOperand(),
+ LoadI->getType(), LoadI->getPointerOperand(), *DL, *SE,
+ /*StrictCheck=*/true, /*CheckType=*/false);
+ if (!Diff || *Diff >= 0)
+ continue;
+ // Negating the minimum signed value is undefined.
+ if (*Diff == std::numeric_limits<int64_t>::min())
+ continue;
+
+ uint64_t Distance = static_cast<uint64_t>(-*Diff) * ElementSize;
+ LLVM_DEBUG(dbgs() << "SLP: STLF: load=" << *LoadI << " distance="
+ << Distance << " bytes from chain base\n");
+
+ // A widened (regularly vectorized) load accesses the whole vector at once,
+ // so its effective width is the number of emitted lanes * element size, not
+ // one element. Such a wide load can straddle two wide stores even when
+ // perfectly aligned, which the misalignment-only test would miss. Use the
+ // count of distinct scalars actually loaded from memory (not the reuse-
+ // inflated vector factor) for the emitted load width; for an interleaved
+ // entry Scalars already lists every lane across all streams, so it is not
+ // rescaled by the interleave factor again here.
+ TypeSize LoadTypeSize = DL->getTypeStoreSize(LoadI->getType());
+ uint64_t LoadElementSize =
+ LoadTypeSize.isScalable() ? 0 : LoadTypeSize.getFixedValue();
+ if (LoadSizeOverride) {
+ LoadElementSize = *LoadSizeOverride;
+ } else if (WidenedLoadEntry &&
+ WidenedLoadEntry->State == TreeEntry::CompressVectorize) {
+ // A compressed (masked-load + shuffle) entry's real footprint is the
+ // full underlying vector load span, not just the (possibly sparser)
+ // set of scalars actually kept by the compress mask.
+ auto CompressIt = CompressEntryToData.find(WidenedLoadEntry);
+ if (CompressIt != CompressEntryToData.end()) {
+ auto *CompressVecTy =
+ cast<FixedVectorType>(std::get<1>(CompressIt->second));
+ LoadElementSize *= CompressVecTy->getNumElements();
+ } else {
+ LoadElementSize *= WidenedLoadEntry->Scalars.size();
+ }
+ } else if (WidenedLoadEntry) {
+ LoadElementSize *= WidenedLoadEntry->Scalars.size();
+ }
+ // A conflict is only a real hazard if a future iteration's load actually
+ // re-reads the bytes this store wrote. With a common positive loop-carried
+ // stride S, equal for the load and the store, the store's bytes are re-read
+ // iff there is an integer k >= 1 with
+ // Distance - LoadElementSize < k * S < Distance + VectorStoreBytes.
+ // If no such k exists the accesses are strided-independent, so there is no
+ // forwarding hazard. When the stride is unknown, non-positive, or differs
+ // between load and store, fall back to the conservative check below.
+ std::optional<int64_t> LoadStride =
+ getConstantLoopStrideInBytes(LoadI->getPointerOperand(), *SE, StoreL);
+ // The strided-independence test below only rules out re-reads by *future*
+ // iterations (k >= 1); it says nothing about the current iteration (k == 0,
+ // i.e. Distance < LoadElementSize), where a load wide enough to reach
+ // forward into the store's own bytes already overlaps it and must go
+ // through the conflict predicate. After skipping interior lanes above,
+ // LoadI is the widened load's base (or a scalar load).
+ // A k == 0 overlap is a store-to-load *forwarding* hazard only when the
+ // store executes before the load in program order, so the load reads bytes
+ // the store just wrote (RAW). If the load precedes the store (a WAR
+ // overlap, e.g. a read-then-write sweep), nothing is forwarded. Dominance
+ // lets a store in an earlier block count; when the store does not
+ // dominate the load, the order is not established and it is not treated
+ // as a current-iteration hazard.
+ bool OverlapsCurrentStore = (!WidenedLoadEntry || IsWidenedBaseLane) &&
+ Distance < LoadElementSize &&
+ DT->dominates(BaseStore, LoadI);
+ // Both pointers are loop-invariant, so their byte distance never changes
+ // across iterations: if they do not overlap now, they never will.
+ if (!OverlapsCurrentStore && StoreStride && LoadStride &&
+ *StoreStride == 0 && *LoadStride == 0 && Distance >= LoadElementSize) {
+ LLVM_DEBUG(dbgs() << "SLP: STLF: both pointers loop-invariant, "
+ << "distance never changes -> no conflict\n");
+ continue;
+ }
+ if (!OverlapsCurrentStore && StoreStride && LoadStride &&
+ *StoreStride == *LoadStride && *StoreStride > 0) {
+ int64_t Stride = *StoreStride;
+ int64_t Lo = static_cast<int64_t>(Distance) -
+ static_cast<int64_t>(LoadElementSize);
+ int64_t Hi = static_cast<int64_t>(Distance) +
+ static_cast<int64_t>(VectorStoreBytes);
+ int64_t K = Lo < Stride ? 1 : (Lo / Stride) + 1;
+ if (Stride * K >= Hi) {
+ LLVM_DEBUG(dbgs() << "SLP: STLF: strided-independent (stride " << Stride
+ << "), no future re-read -> no conflict\n");
+ continue;
+ }
+ }
+ // With a negative common stride a later iteration's load sits |S| bytes
+ // further below the store base per iteration, so it reaches the store's
+ // bytes only while Distance + k * |S| < LoadElementSize.
+ if (!OverlapsCurrentStore && StoreStride && *StoreStride < 0 &&
+ Distance + (0 - static_cast<uint64_t>(*StoreStride)) >=
+ LoadElementSize) {
+ LLVM_DEBUG(dbgs() << "SLP: STLF: negative common stride (" << *StoreStride
+ << "), distance invariant -> no conflict\n");
+ continue;
+ }
+ // Conflict if the load overlaps two wide stores within the recency window,
+ // either because it is misaligned or because the load itself is wider than
+ // the wide store and overruns its window.
+ if (MemoryDepChecker::isStoreLoadForwardingConflict(
+ Distance, VectorStoreBytes, ElementSize, LoadElementSize)) {
+ LLVM_DEBUG(dbgs() << "SLP: Store-load forwarding conflict: "
+ << (isVectorized(LoadI) ? "widened" : "scalar")
+ << " load, distance " << Distance
+ << " bytes, vector store width " << VectorStoreBytes
+ << " bytes, load width " << LoadElementSize
+ << " bytes, misalignment "
+ << (Distance % VectorStoreBytes) << "\n");
+ if (!ConflictingLoads)
+ return true;
+ ConflictingLoads->push_back(LoadI);
+ }
+ }
+
+ return ConflictingLoads && !ConflictingLoads->empty();
+}
+
+bool BoUpSLP::isStoreSideSTLFHandled(const TreeEntry *StoreE) const {
+ return StoreE->hasState() && StoreE->getOpcode() == Instruction::Store &&
+ (StoreE->State == TreeEntry::Vectorize ||
+ StoreE->State == TreeEntry::StridedVectorize);
+}
+
+bool BoUpSLP::findStoreLoadForwardingHazardForLoad(LoadInst *BaseLoad,
+ unsigned VF) {
+ TypeSize ScalarLoadSize = DL->getTypeStoreSize(BaseLoad->getType());
+ if (ScalarLoadSize.isScalable() || ScalarLoadSize.getFixedValue() == 0)
+ return false;
+ uint64_t VectorLoadBytes = VF * ScalarLoadSize.getFixedValue();
+ const Loop *LoadL = LI->getLoopFor(BaseLoad->getParent());
+ if (!LoadL)
+ return false;
+
+ Value *LoadBase = getUnderlyingObject(BaseLoad->getPointerOperand());
+ for (BasicBlock *BB : LoadL->blocks()) {
+ for (Instruction &I : *BB) {
+ auto *StoreI = dyn_cast<StoreInst>(&I);
+ if (!StoreI || !StoreI->isSimple() ||
+ getUnderlyingObject(StoreI->getPointerOperand()) != LoadBase)
+ continue;
+
+ bool HandledByStoreCost = false;
+ for (const TreeEntry *StoreE : getTreeEntries(StoreI)) {
+ if (DeletedNodes.contains(StoreE) ||
+ TransformedToGatherNodes.contains(StoreE) ||
+ !isStoreSideSTLFHandled(StoreE))
+ continue;
+ HandledByStoreCost = true;
+ break;
+ }
+ if (HandledByStoreCost)
+ continue;
+ // Expanded stores remain load-side: they represent masked, non-
+ // contiguous narrow writes, not one store containing the load, so the
+ // store side never has a single window to charge; StridedVectorize
+ // stores are now charged directly by the store-side check above (which
+ // has the real, possibly non-contiguous span), so they are excluded
+ // here to avoid double-charging the same conflict from both sides.
+ if (findStoreLoadForwardingConflict(StoreI, /*VF=*/1, BaseLoad,
----------------
alexey-bataev wrote:
Widened load of one tree against a widened store of another is charged only while that store is still scalar in IR. Record store committed to STLFChargedLoads windows at commit and check later load trees against them
https://github.com/llvm/llvm-project/pull/199606
More information about the llvm-commits
mailing list