Skip to content

[LoopInterchange] Skip legality check if surrounding loops already guarantee dependency (NFC) #139254

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 13, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 23 additions & 6 deletions llvm/lib/Transforms/Scalar/LoopInterchange.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -231,18 +231,26 @@ static void interChangeDependencies(CharMatrix &DepMatrix, unsigned FromIndx,
std::swap(DepMatrix[I][ToIndx], DepMatrix[I][FromIndx]);
}

// After interchanging, check if the direction vector is valid.
// Check if a direction vector is lexicographically positive. Return true if it
// is positive, nullopt if it is "zero", otherwise false.
// [Theorem] A permutation of the loops in a perfect nest is legal if and only
// if the direction matrix, after the same permutation is applied to its
// columns, has no ">" direction as the leftmost non-"=" direction in any row.
static bool isLexicographicallyPositive(std::vector<char> &DV) {
for (unsigned char Direction : DV) {
static std::optional<bool> isLexicographicallyPositive(std::vector<char> &DV,
unsigned Begin,
unsigned End) {
ArrayRef<char> DVRef(DV);
for (unsigned char Direction : DVRef.slice(Begin, End - Begin)) {
if (Direction == '<')
return true;
if (Direction == '>' || Direction == '*')
return false;
}
return true;
return std::nullopt;
}

static std::optional<bool> isLexicographicallyPositive(std::vector<char> &DV) {
return isLexicographicallyPositive(DV, 0, DV.size());
}

// Checks if it is legal to interchange 2 loops.
Expand All @@ -256,10 +264,19 @@ static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix,
// Create temporary DepVector check its lexicographical order
// before and after swapping OuterLoop vs InnerLoop
Cur = DepMatrix[Row];
if (!isLexicographicallyPositive(Cur))

// If the surrounding loops already ensure that the direction vector is
// lexicographically positive, nothing within the loop will be able to break
// the dependence. In such a case we can skip the subsequent check.
if (isLexicographicallyPositive(Cur, 0, OuterLoopId) == true)
continue;

// Check if the direction vector is lexicographically positive (or zero)
// for both before/after exchanged.
if (isLexicographicallyPositive(Cur) == false)
return false;
std::swap(Cur[InnerLoopId], Cur[OuterLoopId]);
if (!isLexicographicallyPositive(Cur))
if (isLexicographicallyPositive(Cur) == false)
return false;
}
return true;
Expand Down