[LoopInterchange] Wrong direction vector analysis in LoopInterchange?
I found a simple missed-optimization in LoopInterchange and tried to fix. However, I'm confused in the current implementation.
Problem
The following loops can be interchanged theoretically because they only have a flow dependence with a direction vector (<, =) from (X) to (Y).
fail1.ll:
target datalayout = "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128"
target triple = "aarch64-unknown-linux-gnu"
define dso_local void @foo(ptr noalias noundef %a, ptr noalias noundef %b, ptr noalias noundef %c) {
entry:
br label %loop1.header
loop1.header:
%i2 = phi i64 [ 1, %entry ], [ %i2.inc, %loop1.latch ]
%i2.st = add i64 %i2, 1
%i2.ld = add i64 %i2, 0
br label %loop2.header
loop2.header:
%i1 = phi i64 [ 1, %loop1.header ], [ %i1.inc, %loop2.header ]
%i1.st = add i64 %i1, 0
%i1.ld = add i64 %i1, 0
%a.st = getelementptr inbounds [64 x i32], ptr %a, i64 %i1.st, i64 %i2.st
%a.ld = getelementptr inbounds [64 x i32], ptr %a, i64 %i1.ld, i64 %i2.ld
%b.ld = getelementptr inbounds [64 x i32], ptr %b, i64 %i1, i64 %i2
%c.st = getelementptr inbounds [64 x i32], ptr %c, i64 %i1, i64 %i2
%b.val = load i32, ptr %b.ld, align 4
store i32 %b.val, ptr %a.st, align 4 ; (X) store to a[i1][i2+1]
%a.val = load i32, ptr %a.ld, align 4 ; (Y) load from a[i1][i2]
store i32 %a.val, ptr %c.st, align 4
%i1.inc = add nuw nsw i64 %i1, 1
%loop2.exitcond.not = icmp eq i64 %i1.inc, 63
br i1 %loop2.exitcond.not, label %loop1.latch, label %loop2.header
loop1.latch:
%i2.inc = add nuw nsw i64 %i2, 1
%loop1.exitcond.not = icmp eq i64 %i2.inc, 63
br i1 %loop1.exitcond.not, label %exit, label %loop1.header
exit:
ret void
}
This IR corresponds to the following C program.
fail1.c:
#define N1 64
#define N2 64
void foo(unsigned a[restrict N1][N2],
unsigned b[restrict N1][N2],
unsigned c[restrict N1][N2]) {
for (unsigned long i2 = 1; i2 < N2-1; i2++) {
for (unsigned long i1 = 1; i1 < N1-1; i1++) {
a[i1][i2+1] = b[i1][i2];
c[i1][i2] = a[i1][i2];
}
}
}
However, they aren't interchanged.
$ opt -S -passes=loop-interchange -cache-line-size=64 -debug-only=loop-interchange -o /dev/null fail1.ll
Processing LoopList of size = 2
Found 4 Loads and Stores to analyze
Found flow dependency between Src and Dst
Src: store i32 %b.val, ptr %a.st, align 4
Dst: %a.val = load i32, ptr %a.ld, align 4
Dependence before interchange
> =
Processing InnerLoopId = 1 and OuterLoopId = 0
Failed interchange InnerLoopId = 1 and OuterLoopId = 0 due to dependence
Not interchanging loops. Cannot prove legality.
On the other hand, the following loops are successfully interchanged. The only difference from fail1.ll is the the order of (X) and (Y).
pass1.ll:
target datalayout = "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128"
target triple = "aarch64-unknown-linux-gnu"
define dso_local void @foo(ptr noalias noundef %a, ptr noalias noundef %b, ptr noalias noundef %c) {
entry:
br label %loop1.header
loop1.header:
%i2 = phi i64 [ 1, %entry ], [ %i2.inc, %loop1.latch ]
%i2.st = add i64 %i2, 1
%i2.ld = add i64 %i2, 0
br label %loop2.header
loop2.header:
%i1 = phi i64 [ 1, %loop1.header ], [ %i1.inc, %loop2.header ]
%i1.st = add i64 %i1, 0
%i1.ld = add i64 %i1, 0
%a.st = getelementptr inbounds [64 x i32], ptr %a, i64 %i1.st, i64 %i2.st
%a.ld = getelementptr inbounds [64 x i32], ptr %a, i64 %i1.ld, i64 %i2.ld
%b.ld = getelementptr inbounds [64 x i32], ptr %b, i64 %i1, i64 %i2
%c.st = getelementptr inbounds [64 x i32], ptr %c, i64 %i1, i64 %i2
%b.val = load i32, ptr %b.ld, align 4
%a.val = load i32, ptr %a.ld, align 4 ; (Y) load from a[i1][i2]
store i32 %b.val, ptr %a.st, align 4 ; (X) store to a[i1][i2+1]
store i32 %a.val, ptr %c.st, align 4
%i1.inc = add nuw nsw i64 %i1, 1
%loop2.exitcond.not = icmp eq i64 %i1.inc, 63
br i1 %loop2.exitcond.not, label %loop1.latch, label %loop2.header
loop1.latch:
%i2.inc = add nuw nsw i64 %i2, 1
%loop1.exitcond.not = icmp eq i64 %i2.inc, 63
br i1 %loop1.exitcond.not, label %exit, label %loop1.header
exit:
ret void
}
$ opt -S -passes=loop-interchange -cache-line-size=64 -debug-only=loop-interchange -o /dev/null pass1.ll
Processing LoopList of size = 2
Found 4 Loads and Stores to analyze
Found anti dependency between Src and Dst
Src: %a.val = load i32, ptr %a.ld, align 4
Dst: store i32 %b.val, ptr %a.st, align 4
Dependence before interchange
< =
Processing InnerLoopId = 1 and OuterLoopId = 0
Checking if loops are tightly nested
Checking instructions in Loop header and Loop latch
Loops are perfectly nested
Loops are legal to interchange
InnerIndex = 0, OuterIndex = 1
Splitting the inner loop latch
splitting InnerLoopHeader done
adjustLoopBranches called
Loops interchanged.
Dependence after interchange
= <
Environment
Latest main branch (commit b941857b40)
(@CongzheUalberta's recent cost model commit is not relevant; the problem occurs both before the commit and after the commit)
Analysis
The debug output for fail1.ll is:
$ opt -S -passes=loop-interchange -cache-line-size=64 -debug-only=loop-interchange -o /dev/null fail1.ll
Processing LoopList of size = 2
Found 4 Loads and Stores to analyze
Found flow dependency between Src and Dst
Src: store i32 %b.val, ptr %a.st, align 4
Dst: %a.val = load i32, ptr %a.ld, align 4
Dependence before interchange
> =
(snip)
It's incorrect. The correct direction vector is (<, =), not (>, =)
The interchange is rejected by the isOuterMostDepPositive function.
I think the cause is in the populateDependencyMatrix function.
for (I = MemInstr.begin(), IE = MemInstr.end(); I != IE; ++I) {
for (J = I, JE = MemInstr.end(); J != JE; ++J) { // (C)
std::vector<char> Dep;
Instruction *Src = cast<Instruction>(*I);
Instruction *Dst = cast<Instruction>(*J);
// Ignore Input dependencies.
if (isa<LoadInst>(Src) && isa<LoadInst>(Dst))
continue;
// Track Output, Flow, and Anti dependencies.
if (auto D = DI->depends(Src, Dst, true)) {
assert(D->isOrdered() && "Expected an output, flow or anti dep.");
LLVM_DEBUG(StringRef DepType =
D->isFlow() ? "flow" : D->isAnti() ? "anti" : "output";
dbgs() << "Found " << DepType
<< " dependency between Src and Dst\n"
<< " Src:" << *Src << "\n Dst:" << *Dst << '\n');
unsigned Levels = D->getLevels();
char Direction;
for (unsigned II = 1; II <= Levels; ++II) {
const SCEV *Distance = D->getDistance(II);
const SCEVConstant *SCEVConst =
dyn_cast_or_null<SCEVConstant>(Distance);
if (SCEVConst) {
const ConstantInt *CI = SCEVConst->getValue();
if (CI->isNegative()) // (A)
Direction = '<';
else if (CI->isZero())
Direction = '=';
else
Direction = '>';
Dep.push_back(Direction);
} else if (D->isScalar(II)) {
Direction = 'S';
Dep.push_back(Direction);
} else {
unsigned Dir = D->getDirection(II);
if (Dir == Dependence::DVEntry::LT || // (B)
Dir == Dependence::DVEntry::LE)
Direction = '<';
else if (Dir == Dependence::DVEntry::GT ||
Dir == Dependence::DVEntry::GE)
Direction = '>';
else if (Dir == Dependence::DVEntry::EQ)
Direction = '=';
else
Direction = '*';
Dep.push_back(Direction);
}
}
// (snip)
}
}
At (A), CI->isNegative() gives a distance, not a direction. So I think the direction should be > for CI->isNegative() and < for CI->isPositive(). Changing so will be consistent with (B) because Dir == Dependence::DVEntry::LT when CI->isPositive().
However, another problem arises. Changing so will prevent interchange of pass1.ll above. Before the change, the debug output for pass.ll is:
$ opt -S -passes=loop-interchange -cache-line-size=64 -debug-only=loop-interchange -o /dev/null pass1.ll
Processing LoopList of size = 2
Found 4 Loads and Stores to analyze
Found anti dependency between Src and Dst
Src: %a.val = load i32, ptr %a.ld, align 4
Dst: store i32 %b.val, ptr %a.st, align 4
Dependence before interchange
< =
(snip)
Loops interchanged.
(snip)
After the change, the debug output for pass.ll is:
$ opt -S -passes=loop-interchange -cache-line-size=64 -debug-only=loop-interchange -o /dev/null pass1.ll
Processing LoopList of size = 2
Found 4 Loads and Stores to analyze
Found anti dependency between Src and Dst
Src: %a.val = load i32, ptr %a.ld, align 4
Dst: store i32 %b.val, ptr %a.st, align 4
Dependence before interchange
> =
(snip)
Not interchanging loops. Cannot prove legality.
The correct dependence is same as fail1.ll (flow dependence form store to load with a direction vector (<, =)). A dependence form store to load is not analyzed because the analysis loop is triangle at (C).
I'm confused by:
- Why DependenceAnalysis returns anti-dependence from
loadtostore? - Why the analysis loop is triangle at (C)?
I suspect DependenceAnalysis also returns a destination-to-source (not only source-to-destination) dependence information with a reverse distance vector (and direction vector). If so, we must address the reverse case.
Question
- My change for
fail1.ll(>forCI->isNegative()and<forCI->isPositive()) is correct? - The current behavior of DependenceAnalysis for
pass1.llis correct?
@CongzheUalberta @bmahjour @TaWeiTu You commited to LoopInterchange and DependenceAnalysis recently. Does anyone have a comment?
Thanks for bringing it up, I will do some investigations on this issue.
My apologies for the delay. After some initial investigations I thought there might be some problems with dependence analysis (DA).
The debug dump from fail1.ll which says the dependence vector is [> =] does not seem to be correct, as @kawashima-fj pointed out, the correct dependence vector should be [< =]. A dependence vector [> =] is not even legal since it is not positive.
Nevertheless it looks to me the problem is within DA, not loop interchange. DA is supposed to produce a correct result for its clients (loop interchange in this case) at the first place, and it is not supposed to output a negative dependence vector. However, if we take a look at the DA lit tests, we could see lots of negative dependence vectors generated everywhere, e.g., in PreliminaryNoValidityCheckFixedSize.ll we check ; CHECK: da analyze - flow [-3 -2]!. IMHO when it produces a negative dependence vector, DA should reverse all signs in the vector and reverse the type of dependence, e.g., from a flow dependence to an anti dependence. I'm not clear yet why DA behaves like this, and I'm doing further investigations on it.
Hope my explanations are clear. Any comments are very much appreciated :) @kawashima-fj @Meinersbur @bmahjour
@CongzheUalberta Thanks for your investigations.
Nevertheless it looks to me the problem is within DA, not loop interchange
I think we have some problems. At least one within loop interchange and at least one within DA.
1. Problem in loop interchange
Passing my fail1.ll to DA shows the following output. This shows the correct dependence flow [1 0].
$ opt -S "-passes=print<da>" -o /dev/null fail1.ll
'Dependence Analysis' for function 'foo':
Src: %b.val = load i32, ptr %b.ld, align 4 --> Dst: %b.val = load i32, ptr %b.ld, align 4
da analyze - none!
Src: %b.val = load i32, ptr %b.ld, align 4 --> Dst: store i32 %b.val, ptr %a.st, align 4
da analyze - none!
Src: %b.val = load i32, ptr %b.ld, align 4 --> Dst: %a.val = load i32, ptr %a.ld, align 4
da analyze - none!
Src: %b.val = load i32, ptr %b.ld, align 4 --> Dst: store i32 %a.val, ptr %c.st, align 4
da analyze - none!
Src: store i32 %b.val, ptr %a.st, align 4 --> Dst: store i32 %b.val, ptr %a.st, align 4
da analyze - none!
Src: store i32 %b.val, ptr %a.st, align 4 --> Dst: %a.val = load i32, ptr %a.ld, align 4
da analyze - consistent flow [1 0]!
Src: store i32 %b.val, ptr %a.st, align 4 --> Dst: store i32 %a.val, ptr %c.st, align 4
da analyze - none!
Src: %a.val = load i32, ptr %a.ld, align 4 --> Dst: %a.val = load i32, ptr %a.ld, align 4
da analyze - none!
Src: %a.val = load i32, ptr %a.ld, align 4 --> Dst: store i32 %a.val, ptr %c.st, align 4
da analyze - none!
Src: store i32 %a.val, ptr %c.st, align 4 --> Dst: store i32 %a.val, ptr %c.st, align 4
da analyze - none!
Debugging the populateDependencyMatrix function in LoopInterchange.cpp also shows the correct distance vector [1 0] and the direction vector [< =] (getDirection return 1 for LT and 2 for EQ).
(gdb) call Src->dump()
store i32 %b.val, ptr %a.st, align 4
(gdb) call Dst->dump()
%a.val = load i32, ptr %a.ld, align 4
(gdb) p Levels
$1 = 2
(gdb) p II
$2 = 1
(gdb) call SCEVConst->dump()
1
(gdb) call CI->isNegative()
$3 = false
(gdb) call CI->isZero()
$4 = false
(gdb) call D->getDirection(II)
$5 = 1
(gdb) p II
$6 = 2
(gdb) call SCEVConst->dump()
0
(gdb) call CI->isNegative()
$7 = false
(gdb) call CI->isZero()
$8 = true
(gdb) call D->getDirection(II)
$9 = 2
For the case of fail1.ll, I think the problem is at (A) in my first post.
2. Problem in dependence analysis
IMHO when it produces a negative dependence vector, DA should reverse all signs in the vector and reverse the type of dependence, e.g., from a flow dependence to an anti dependence.
I agree with you. However, we should also reverse Src and Dst.
Passing my pass1.ll to DA shows the following output.
$ opt -S "-passes=print<da>" -o /dev/null pass1.ll
'Dependence Analysis' for function 'foo':
Src: %b.val = load i32, ptr %b.ld, align 4 --> Dst: %b.val = load i32, ptr %b.ld, align 4
da analyze - none!
Src: %b.val = load i32, ptr %b.ld, align 4 --> Dst: %a.val = load i32, ptr %a.ld, align 4
da analyze - none!
Src: %b.val = load i32, ptr %b.ld, align 4 --> Dst: store i32 %b.val, ptr %a.st, align 4
da analyze - none!
Src: %b.val = load i32, ptr %b.ld, align 4 --> Dst: store i32 %a.val, ptr %c.st, align 4
da analyze - none!
Src: %a.val = load i32, ptr %a.ld, align 4 --> Dst: %a.val = load i32, ptr %a.ld, align 4
da analyze - none!
Src: %a.val = load i32, ptr %a.ld, align 4 --> Dst: store i32 %b.val, ptr %a.st, align 4
da analyze - consistent anti [-1 0]!
Src: %a.val = load i32, ptr %a.ld, align 4 --> Dst: store i32 %a.val, ptr %c.st, align 4
da analyze - none!
Src: store i32 %b.val, ptr %a.st, align 4 --> Dst: store i32 %b.val, ptr %a.st, align 4
da analyze - none!
Src: store i32 %b.val, ptr %a.st, align 4 --> Dst: store i32 %a.val, ptr %c.st, align 4
da analyze - none!
Src: store i32 %a.val, ptr %c.st, align 4 --> Dst: store i32 %a.val, ptr %c.st, align 4
da analyze - none!
It should be flow [1 0], not anti [-1 0]. And, Src: store --> Dst: load, not Src: load --> Dst: store.
I'm not clear yet why DA behaves like this
I am also confused.
llvm/test/Analysis/DependenceAnalysis/Coupled.ll:55 and llvm/test/Analysis/DependenceAnalysis/DADelin.ll:328 also check negative dependences.
The dumpExampleDependence function has a triangle loops of SrcI and DstI.
So, the behavior seems to be intentional. But why?
@kawashima-fj Thank you, I completely agree. It might be that I did not make it clear enough in my previous post, but your last comment is exactly what I've indicate. The problem in loop interchange looks trivial to fix (not the root cause though) -- we just need to switch the signs at (A), i.e., return > when CI->isNegative() and < otherwise.
What is more significant is the root problem in DA. It looks to me that DA lacks a check for legality of distance vectors in the end -- with an attempt to fix it I've locally added a legality check for distance vectors to check if the vectors are non-positive, and I would reverse the signs of each element if the vector is non-positive. With that fix, and together with the fix in loop interchange as described above, both fail1.ll and pass1.ll could work correctly and can be interchanged.
However, with the fix in DA applied, I've seen 13 lit test failures for now. Some are in dependence analysis which is expected. But I do see 4 failures in loop unroll and jam, e.g.,
Transforms/LoopUnrollAndJam/dependencies.ll,
Transforms/LoopUnrollAndJam/dependencies_multidims.ll,
Transforms/LoopUnrollAndJam/disable.ll,
Transforms/LoopUnrollAndJam/unroll-and-jam.ll.
I'm looking further into why those unroll and jam tests fail. Also I need to make sure there is no regression with the DA fix applied. I'm working on those issues now, and I would appreciate any comment at this point.
A negative dependence vector simply indicates that the source and sink of the dependence edge need to be reversed. For instance an anti-dependence of distance -1 from S1 to S2 means there is a flow dependence from S2 to S1 with a distance of 1.
Currently the interface exposed by the analysis requires specifying a source and a sink (via DependenceAnalysis::depends()). When the source and sink is dictated by the interface, the analysis cannot simply reverse the direction vectors because it cannot reverse the input.
One could define an interface where the input does not dictate the order of the end points of an edge, but such an interface would not be usable for loop-independent dependencies.
To keep things simple, I think the client should take care to handle negative direction vectors. For example loop-interchange could "normalize" the dependence matrix by reversing all vectors that are negative during construction.
Thanks Bardia for your comment! Your point that the client should take care to handle negative direction vectors makes sense, nevertheless IMHO the benefit of doing the fix in DA is that we do not need to replicate the same work for "normalization" of the result in different clients of DA. I'm wondering which one of the two approaches is preferred?
As described I had some code that "normalize" the distance vectors and actually reverses the "Src" and "Dst" for the Dependence object that DependenceInfo::depends() returns, if the distance vector is negative. I'm double checking to make sure if does not have negtive effect (e.g., on lit tests). I'd appreciate any comment on it and I'll be glad to make changes to the design.
I'm wondering if you could clarify what you meant by "One could define an interface where the input does not dictate the order of the end points of an edge, but such an interface would not be usable for loop-independent dependencies"? I thought for loop independent dependencies the ordering is trival and straightfoward which is the ordering of instructions in the IR, even if the interface does not dictate it explicitly?
I'm wondering if you could clarify what you meant by "One could define an interface where the input does not dictate the order of the end points of an edge, but such an interface would not be usable for loop-independent dependencies"? I thought for loop independent dependencies the ordering is trival and straightfoward which is the ordering of instructions in the IR, even if the interface does not dictate it explicitly?
The source and sink of loop-independent dependencies need to be based on program order, but if the interface does not indicate which of the two instructions comes first, then DA would have to try to figure it out on its own. Program order is typically known by a client as it walks instructions in a region and queries dependence info, whereas determining it in DA would be redundant and more expensive.
As described I had some code that "normalize" the distance vectors and actually reverses the "Src" and "Dst" for the Dependence object that DependenceInfo::depends() returns, if the distance vector is negative. I'm double checking to make sure if does not have negtive effect (e.g., on lit tests). I'd appreciate any comment on it and I'll be glad to make changes to the design.
I'd be concerned about swapping the order behind the scenes given that the client queried it in a certain order. A conceivable algorithm may actually want to receive a negative direction vector, eg if it tries to examine how dependencies would change if instructions are reordered. This and the concern about replicating the normalization code, could possibly be addressed by introducing a normalize() function on the Dependence class?
@bmahjour Thanks for your explanation. I understand the intent. However, I think it's confusing. When there is an anti dependence S1 → S2 and no dependence S2 → S1, DependenceInfo::depends(S2, S1, true) returns a flow dependence (Dependence::isFlow() is true) with a negative direction vector. It is not intuitive. It is intuitive if DependenceInfo::depends(S2, S1, true) does not return Dependence and only DependenceInfo::depends(S1, S2, true) returns Dependence.
That being said, some code exist that rely on the current behavior. Adding isReverse() function to Dependence and documenting the current behavior may be helpful.
I found someone added this issue to the agenda of the loop optimization group meeting. Though I cannot attend the meeting, I hope in-depth discussion is made.
A isReverse() method may not be as straightforward as it seems it first. Consider the following:
for (int i = 0; i < 32; ++i) {
Src: A[i] = ...;
Dst: use(A[31 - i]);
}
Polly would determine the following dependences:
- RAW (flow):
{ Src[i] -> Dst[31 - i] : i >= 16 } - WAR (anti):
{ Dst[i] -> Src[31 - i] : i < 16 }
DependenceAnalysis is only capable of returning a single Dependence object. That is, either
- DependenceInfo::depends(Src, Dst, true): flow[<>]
or
- DependenceInfo::depends(Dst, Src, true): anti[<>]
Where both return objects represent the RAW and WAR dependencies at the same time (I have not tested what DA actually determines, it might just return confused/*).
That is, if a dependence result contains >, it means that a reversed dependence needs to be considered as well. (ie. flow[>] -> anti[<]. anti[>] -> flow[<], output[>] -> output[<]). Which one you get only depends on whether one calls depends(Src,Dst) or depends(Dst,Src).
Hence what isReversed() returns on <> dependencies is a bit ambiguous. @bmahjour suggested to only return true if it a > (or =>) dependency. That might help to canonicalize the dependency vector, and the understanding of the interface. On the other side, it can already be queried using Dependence::getDirection) == DVEntry::GT it may also make it less obvious that the reverse direction may still need to be considered (if <>, <=>, *).
Edit: Add text to example according to what was discussed in the loop opt meeting.
for (int i = 0; i < 64; ++i) { Src: A[i] = ...; Dst: use(A[63 - i]); }
This is an interesting case where the direction of the dependence changes midway through the loop. These cases should classify as crossing (ie crossing SIV in this example) and result in either <> or * as the direction entry. Reversing such entries will yield the same entry, so “normalize()” should leave them alone, but to be conservative we should probably treat them as negative when deciding if interchange is legal or not.
This is also captured in the meeting minutes for today's call.
Thanks for all the discussions, I've posted https://reviews.llvm.org/D130188 together with https://reviews.llvm.org/D130189 to fix it.
Should be resolved by D130188 and D130189, I'll close the issue for now. Please let me know if there's any remaining issues.