Skip to content

Commit 91387ed

Browse files
committed
LAA: generalize strides over unequal type sizes
getDepdenceDistanceStrideAndSize currently returns a non-zero TypeByteSize only if the type-sizes of the source and sink are equal. The non-zero TypeByteSize is then used by isDependent to scale the strides, the distance between the accesses, and the VF. This restriction is very artificial, as the stride sizes can be scaled by the respective type-sizes in advance, freeing isDependent of this responsibility, and removing the ugly special-case of zero-TypeByteSize. The patch also has the side-effect of fixing the long-standing TODO of requesting runtime-checks when the strides are unequal. The test impact of this patch is that several false depdendencies are eliminated, and several unknown depdendencies now come with runtime-checks instead.
1 parent 4e8eabd commit 91387ed

File tree

6 files changed

+135
-115
lines changed

6 files changed

+135
-115
lines changed

llvm/include/llvm/Analysis/LoopAccessAnalysis.h

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -366,16 +366,20 @@ class MemoryDepChecker {
366366

367367
struct DepDistanceStrideAndSizeInfo {
368368
const SCEV *Dist;
369-
uint64_t StrideA;
370-
uint64_t StrideB;
369+
uint64_t MaxStride;
370+
std::optional<uint64_t> CommonStride;
371+
bool ShouldRetryWithRuntimeCheck;
371372
uint64_t TypeByteSize;
372373
bool AIsWrite;
373374
bool BIsWrite;
374375

375-
DepDistanceStrideAndSizeInfo(const SCEV *Dist, uint64_t StrideA,
376-
uint64_t StrideB, uint64_t TypeByteSize,
377-
bool AIsWrite, bool BIsWrite)
378-
: Dist(Dist), StrideA(StrideA), StrideB(StrideB),
376+
DepDistanceStrideAndSizeInfo(const SCEV *Dist, uint64_t MaxStride,
377+
std::optional<uint64_t> CommonStride,
378+
bool ShouldRetryWithRuntimeCheck,
379+
uint64_t TypeByteSize, bool AIsWrite,
380+
bool BIsWrite)
381+
: Dist(Dist), MaxStride(MaxStride), CommonStride(CommonStride),
382+
ShouldRetryWithRuntimeCheck(ShouldRetryWithRuntimeCheck),
379383
TypeByteSize(TypeByteSize), AIsWrite(AIsWrite), BIsWrite(BIsWrite) {}
380384
};
381385

llvm/lib/Analysis/LoopAccessAnalysis.cpp

Lines changed: 80 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -1799,8 +1799,7 @@ void MemoryDepChecker::mergeInStatus(VectorizationSafetyStatus S) {
17991799
/// }
18001800
static bool isSafeDependenceDistance(const DataLayout &DL, ScalarEvolution &SE,
18011801
const SCEV &MaxBTC, const SCEV &Dist,
1802-
uint64_t MaxStride,
1803-
uint64_t TypeByteSize) {
1802+
uint64_t MaxStride) {
18041803

18051804
// If we can prove that
18061805
// (**) |Dist| > MaxBTC * Step
@@ -1819,8 +1818,7 @@ static bool isSafeDependenceDistance(const DataLayout &DL, ScalarEvolution &SE,
18191818
// will be executed only if LoopCount >= VF, proving distance >= LoopCount
18201819
// also guarantees that distance >= VF.
18211820
//
1822-
const uint64_t ByteStride = MaxStride * TypeByteSize;
1823-
const SCEV *Step = SE.getConstant(MaxBTC.getType(), ByteStride);
1821+
const SCEV *Step = SE.getConstant(MaxBTC.getType(), MaxStride);
18241822
const SCEV *Product = SE.getMulExpr(&MaxBTC, Step);
18251823

18261824
const SCEV *CastedDist = &Dist;
@@ -1864,9 +1862,7 @@ static bool areStridedAccessesIndependent(uint64_t Distance, uint64_t Stride,
18641862
if (Distance % TypeByteSize)
18651863
return false;
18661864

1867-
uint64_t ScaledDist = Distance / TypeByteSize;
1868-
1869-
// No dependence if the scaled distance is not multiple of the stride.
1865+
// No dependence if the distance is not multiple of the stride.
18701866
// E.g.
18711867
// for (i = 0; i < 1024 ; i += 4)
18721868
// A[i+2] = A[i] + 1;
@@ -1882,7 +1878,7 @@ static bool areStridedAccessesIndependent(uint64_t Distance, uint64_t Stride,
18821878
// Two accesses in memory (scaled distance is 4, stride is 3):
18831879
// | A[0] | | | A[3] | | | A[6] | | |
18841880
// | | | | | A[4] | | | A[7] | |
1885-
return ScaledDist % Stride;
1881+
return Distance % Stride;
18861882
}
18871883

18881884
std::variant<MemoryDepChecker::Dependence::DepType,
@@ -1921,6 +1917,7 @@ MemoryDepChecker::getDependenceDistanceStrideAndSize(
19211917
if (StrideAPtr && *StrideAPtr < 0) {
19221918
std::swap(Src, Sink);
19231919
std::swap(AInst, BInst);
1920+
std::swap(ATy, BTy);
19241921
std::swap(StrideAPtr, StrideBPtr);
19251922
}
19261923

@@ -1972,30 +1969,68 @@ MemoryDepChecker::getDependenceDistanceStrideAndSize(
19721969
return MemoryDepChecker::Dependence::IndirectUnsafe;
19731970
}
19741971

1975-
int64_t StrideAPtrInt = *StrideAPtr;
1976-
int64_t StrideBPtrInt = *StrideBPtr;
1977-
LLVM_DEBUG(dbgs() << "LAA: Src induction step: " << StrideAPtrInt
1978-
<< " Sink induction step: " << StrideBPtrInt << "\n");
1972+
LLVM_DEBUG(dbgs() << "LAA: Src induction step: " << *StrideAPtr
1973+
<< " Sink induction step: " << *StrideBPtr << "\n");
1974+
1975+
// Note that store size is different from alloc size, which is dependent on
1976+
// store size. We use the former for checking illegal cases, and the latter
1977+
// for scaling strides.
1978+
TypeSize AStoreSz = DL.getTypeStoreSize(ATy),
1979+
BStoreSz = DL.getTypeStoreSize(BTy);
1980+
1981+
// When the distance is zero, we're reading/writing the same memory location:
1982+
// check that the store sizes are equal. Otherwise, fail with an unknown
1983+
// dependence for which we should not generate runtime checks.
1984+
if (Dist->isZero() && AStoreSz != BStoreSz)
1985+
return MemoryDepChecker::Dependence::Unknown;
1986+
1987+
// We can't get get a uint64_t for the AllocSize if either of the store sizes
1988+
// are scalable.
1989+
if (AStoreSz.isScalable() || BStoreSz.isScalable())
1990+
return MemoryDepChecker::Dependence::Unknown;
1991+
1992+
// The TypeByteSize is used to scale Distance and VF. In these contexts, the
1993+
// only size that matters is the size of the Sink.
1994+
uint64_t ASz = alignTo(AStoreSz, DL.getABITypeAlign(ATy).value()),
1995+
TypeByteSize = alignTo(BStoreSz, DL.getABITypeAlign(BTy).value());
1996+
1997+
// We scale the strides by the alloc-type-sizes, so we can check that the
1998+
// common distance is equal when ASz != BSz.
1999+
int64_t StrideAScaled = *StrideAPtr * ASz;
2000+
int64_t StrideBScaled = *StrideBPtr * TypeByteSize;
2001+
19792002
// At least Src or Sink are loop invariant and the other is strided or
19802003
// invariant. We can generate a runtime check to disambiguate the accesses.
1981-
if (!StrideAPtrInt || !StrideBPtrInt)
2004+
if (!StrideAScaled || !StrideBScaled)
19822005
return MemoryDepChecker::Dependence::Unknown;
19832006

19842007
// Both Src and Sink have a constant stride, check if they are in the same
19852008
// direction.
1986-
if ((StrideAPtrInt > 0) != (StrideBPtrInt > 0)) {
2009+
if ((StrideAScaled > 0) != (StrideBScaled > 0)) {
19872010
LLVM_DEBUG(
19882011
dbgs() << "Pointer access with strides in different directions\n");
19892012
return MemoryDepChecker::Dependence::Unknown;
19902013
}
19912014

1992-
uint64_t TypeByteSize = DL.getTypeAllocSize(ATy);
1993-
bool HasSameSize =
1994-
DL.getTypeStoreSizeInBits(ATy) == DL.getTypeStoreSizeInBits(BTy);
1995-
if (!HasSameSize)
1996-
TypeByteSize = 0;
1997-
return DepDistanceStrideAndSizeInfo(Dist, std::abs(StrideAPtrInt),
1998-
std::abs(StrideBPtrInt), TypeByteSize,
2015+
StrideAScaled = std::abs(StrideAScaled);
2016+
StrideBScaled = std::abs(StrideBScaled);
2017+
2018+
// MaxStride is the max of the scaled strides, as expected.
2019+
uint64_t MaxStride = std::max(StrideAScaled, StrideBScaled);
2020+
2021+
// CommonStride is set if both scaled strides are equal.
2022+
std::optional<uint64_t> CommonStride;
2023+
if (StrideAScaled == StrideBScaled)
2024+
CommonStride = StrideAScaled;
2025+
2026+
// TODO: Historically, we don't retry with runtime checks unless the unscaled
2027+
// strides are the same, but this doesn't make sense. Fix this once the
2028+
// condition for runtime checks in isDependent is fixed.
2029+
bool ShouldRetryWithRuntimeCheck =
2030+
std::abs(*StrideAPtr) == std::abs(*StrideBPtr);
2031+
2032+
return DepDistanceStrideAndSizeInfo(Dist, MaxStride, CommonStride,
2033+
ShouldRetryWithRuntimeCheck, TypeByteSize,
19992034
AIsWrite, BIsWrite);
20002035
}
20012036

@@ -2011,32 +2046,28 @@ MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
20112046
if (std::holds_alternative<Dependence::DepType>(Res))
20122047
return std::get<Dependence::DepType>(Res);
20132048

2014-
auto &[Dist, StrideA, StrideB, TypeByteSize, AIsWrite, BIsWrite] =
2049+
auto &[Dist, MaxStride, CommonStride, ShouldRetryWithRuntimeCheck,
2050+
TypeByteSize, AIsWrite, BIsWrite] =
20152051
std::get<DepDistanceStrideAndSizeInfo>(Res);
2016-
bool HasSameSize = TypeByteSize > 0;
20172052

2018-
std::optional<uint64_t> CommonStride =
2019-
StrideA == StrideB ? std::make_optional(StrideA) : std::nullopt;
20202053
if (isa<SCEVCouldNotCompute>(Dist)) {
2021-
// TODO: Relax requirement that there is a common stride to retry with
2022-
// non-constant distance dependencies.
2023-
FoundNonConstantDistanceDependence |= CommonStride.has_value();
2054+
// TODO: Relax requirement that there is a common unscaled stride to retry
2055+
// with non-constant distance dependencies.
2056+
FoundNonConstantDistanceDependence |= ShouldRetryWithRuntimeCheck;
20242057
LLVM_DEBUG(dbgs() << "LAA: Dependence because of uncomputable distance.\n");
20252058
return Dependence::Unknown;
20262059
}
20272060

20282061
ScalarEvolution &SE = *PSE.getSE();
20292062
auto &DL = InnermostLoop->getHeader()->getDataLayout();
2030-
uint64_t MaxStride = std::max(StrideA, StrideB);
20312063

20322064
// If the distance between the acecsses is larger than their maximum absolute
20332065
// stride multiplied by the symbolic maximum backedge taken count (which is an
20342066
// upper bound of the number of iterations), the accesses are independet, i.e.
20352067
// they are far enough appart that accesses won't access the same location
20362068
// across all loop ierations.
2037-
if (HasSameSize && isSafeDependenceDistance(
2038-
DL, SE, *(PSE.getSymbolicMaxBackedgeTakenCount()),
2039-
*Dist, MaxStride, TypeByteSize))
2069+
if (isSafeDependenceDistance(
2070+
DL, SE, *(PSE.getSymbolicMaxBackedgeTakenCount()), *Dist, MaxStride))
20402071
return Dependence::NoDep;
20412072

20422073
const SCEVConstant *ConstDist = dyn_cast<SCEVConstant>(Dist);
@@ -2047,7 +2078,7 @@ MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
20472078

20482079
// If the distance between accesses and their strides are known constants,
20492080
// check whether the accesses interlace each other.
2050-
if (Distance > 0 && CommonStride && CommonStride > 1 && HasSameSize &&
2081+
if (Distance > 0 && CommonStride && CommonStride > 1 &&
20512082
areStridedAccessesIndependent(Distance, *CommonStride, TypeByteSize)) {
20522083
LLVM_DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
20532084
return Dependence::NoDep;
@@ -2061,15 +2092,9 @@ MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
20612092

20622093
// Negative distances are not plausible dependencies.
20632094
if (SE.isKnownNonPositive(Dist)) {
2064-
if (SE.isKnownNonNegative(Dist)) {
2065-
if (HasSameSize) {
2066-
// Write to the same location with the same size.
2067-
return Dependence::Forward;
2068-
}
2069-
LLVM_DEBUG(dbgs() << "LAA: possibly zero dependence difference but "
2070-
"different type sizes\n");
2071-
return Dependence::Unknown;
2072-
}
2095+
if (SE.isKnownNonNegative(Dist))
2096+
// Write to the same location.
2097+
return Dependence::Forward;
20732098

20742099
bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
20752100
// Check if the first access writes to a location that is read in a later
@@ -2084,13 +2109,12 @@ MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
20842109
if (!ConstDist) {
20852110
// TODO: FoundNonConstantDistanceDependence is used as a necessary
20862111
// condition to consider retrying with runtime checks. Historically, we
2087-
// did not set it when strides were different but there is no inherent
2088-
// reason to.
2089-
FoundNonConstantDistanceDependence |= CommonStride.has_value();
2112+
// did not set it when unscaled strides were different but there is no
2113+
// inherent reason to.
2114+
FoundNonConstantDistanceDependence |= ShouldRetryWithRuntimeCheck;
20902115
return Dependence::Unknown;
20912116
}
2092-
if (!HasSameSize ||
2093-
couldPreventStoreLoadForward(
2117+
if (couldPreventStoreLoadForward(
20942118
ConstDist->getAPInt().abs().getZExtValue(), TypeByteSize)) {
20952119
LLVM_DEBUG(
20962120
dbgs() << "LAA: Forward but may prevent st->ld forwarding\n");
@@ -2105,27 +2129,20 @@ MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
21052129
int64_t MinDistance = SE.getSignedRangeMin(Dist).getSExtValue();
21062130
// Below we only handle strictly positive distances.
21072131
if (MinDistance <= 0) {
2108-
FoundNonConstantDistanceDependence |= CommonStride.has_value();
2132+
FoundNonConstantDistanceDependence |= ShouldRetryWithRuntimeCheck;
21092133
return Dependence::Unknown;
21102134
}
21112135

2112-
if (!ConstDist) {
2136+
if (!ConstDist)
21132137
// Previously this case would be treated as Unknown, possibly setting
21142138
// FoundNonConstantDistanceDependence to force re-trying with runtime
21152139
// checks. Until the TODO below is addressed, set it here to preserve
21162140
// original behavior w.r.t. re-trying with runtime checks.
21172141
// TODO: FoundNonConstantDistanceDependence is used as a necessary
21182142
// condition to consider retrying with runtime checks. Historically, we
2119-
// did not set it when strides were different but there is no inherent
2120-
// reason to.
2121-
FoundNonConstantDistanceDependence |= CommonStride.has_value();
2122-
}
2123-
2124-
if (!HasSameSize) {
2125-
LLVM_DEBUG(dbgs() << "LAA: ReadWrite-Write positive dependency with "
2126-
"different type sizes\n");
2127-
return Dependence::Unknown;
2128-
}
2143+
// did not set it when unscaled strides were different but there is no
2144+
// inherent reason to.
2145+
FoundNonConstantDistanceDependence |= ShouldRetryWithRuntimeCheck;
21292146

21302147
if (!CommonStride)
21312148
return Dependence::Unknown;
@@ -2140,8 +2157,8 @@ MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
21402157

21412158
// It's not vectorizable if the distance is smaller than the minimum distance
21422159
// needed for a vectroized/unrolled version. Vectorizing one iteration in
2143-
// front needs TypeByteSize * Stride. Vectorizing the last iteration needs
2144-
// TypeByteSize (No need to plus the last gap distance).
2160+
// front needs CommonStride. Vectorizing the last iteration needs TypeByteSize
2161+
// (No need to plus the last gap distance).
21452162
//
21462163
// E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
21472164
// foo(int *A) {
@@ -2168,8 +2185,7 @@ MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
21682185
// We know that Dist is positive, but it may not be constant. Use the signed
21692186
// minimum for computations below, as this ensures we compute the closest
21702187
// possible dependence distance.
2171-
uint64_t MinDistanceNeeded =
2172-
TypeByteSize * *CommonStride * (MinNumIter - 1) + TypeByteSize;
2188+
uint64_t MinDistanceNeeded = *CommonStride * (MinNumIter - 1) + TypeByteSize;
21732189
if (MinDistanceNeeded > static_cast<uint64_t>(MinDistance)) {
21742190
if (!ConstDist) {
21752191
// For non-constant distances, we checked the lower bound of the
@@ -2225,7 +2241,7 @@ MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
22252241

22262242
// An update to MinDepDistBytes requires an update to MaxSafeVectorWidthInBits
22272243
// since there is a backwards dependency.
2228-
uint64_t MaxVF = MinDepDistBytes / (TypeByteSize * *CommonStride);
2244+
uint64_t MaxVF = MinDepDistBytes / *CommonStride;
22292245
LLVM_DEBUG(dbgs() << "LAA: Positive min distance " << MinDistance
22302246
<< " with max VF = " << MaxVF << '\n');
22312247

llvm/test/Analysis/LoopAccessAnalysis/depend_diff_types.ll

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -129,16 +129,8 @@ define void @neg_dist_dep_type_size_equivalence(ptr nocapture %vec, i64 %n) {
129129
; CHECK-LABEL: 'neg_dist_dep_type_size_equivalence'
130130
; CHECK-NEXT: loop:
131131
; CHECK-NEXT: Report: unsafe dependent memory operations in loop. Use #pragma clang loop distribute(enable) to allow loop distribution to attempt to isolate the offending operations into a separate loop
132-
; CHECK-NEXT: Unknown data dependence.
132+
; CHECK-NEXT: Backward loop carried data dependence that prevents store-to-load forwarding.
133133
; CHECK-NEXT: Dependences:
134-
; CHECK-NEXT: Unknown:
135-
; CHECK-NEXT: %ld.f64 = load double, ptr %gep.iv, align 8 ->
136-
; CHECK-NEXT: store i32 %ld.i64.i32, ptr %gep.iv.n.i64, align 8
137-
; CHECK-EMPTY:
138-
; CHECK-NEXT: Unknown:
139-
; CHECK-NEXT: %ld.i64 = load i64, ptr %gep.iv, align 8 ->
140-
; CHECK-NEXT: store i32 %ld.i64.i32, ptr %gep.iv.n.i64, align 8
141-
; CHECK-EMPTY:
142134
; CHECK-NEXT: BackwardVectorizableButPreventsForwarding:
143135
; CHECK-NEXT: %ld.f64 = load double, ptr %gep.iv, align 8 ->
144136
; CHECK-NEXT: store double %val, ptr %gep.iv.101.i64, align 8

llvm/test/Analysis/LoopAccessAnalysis/forward-loop-carried.ll

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -70,10 +70,6 @@ define void @forward_different_access_sizes(ptr readnone %end, ptr %start) {
7070
; CHECK-NEXT: store i32 0, ptr %gep.2, align 4 ->
7171
; CHECK-NEXT: %l = load i24, ptr %gep.1, align 1
7272
; CHECK-EMPTY:
73-
; CHECK-NEXT: Forward:
74-
; CHECK-NEXT: store i32 0, ptr %gep.2, align 4 ->
75-
; CHECK-NEXT: store i24 %l, ptr %ptr.iv, align 1
76-
; CHECK-EMPTY:
7773
; CHECK-NEXT: Run-time memory checks:
7874
; CHECK-NEXT: Grouped accesses:
7975
; CHECK-EMPTY:

0 commit comments

Comments
 (0)