[llvm] [LoopInterchange] Stop performing unprofitable interchange (PR #127473)

Michael Kruse via llvm-commits llvm-commits at lists.llvm.org
Tue Feb 18 05:21:19 PST 2025


================
@@ -1184,11 +1218,27 @@ std::optional<bool> LoopInterchangeProfitability::isProfitableForVectorization(
   return std::optional<bool>(!DepMatrix.empty());
 }
 
-bool LoopInterchangeProfitability::isProfitable(
-    const Loop *InnerLoop, const Loop *OuterLoop, unsigned InnerLoopId,
-    unsigned OuterLoopId, CharMatrix &DepMatrix,
-    const DenseMap<const Loop *, unsigned> &CostMap,
-    std::unique_ptr<CacheCost> &CC) {
+// The bubble-sort fashion algorithm is adopted to sort the loop nest, so the
+// comparison function should ideally induce a strict weak ordering required by
+// some standard C++ libraries. In particular, isProfitable should hold the
+// following properties.
+//
+// Asymmetry: If isProfitable(a, b) is true then isProfitable(b, a) is false.
+// Transitivity: If both isProfitable(a, b) and isProfitable(b, c) is true then
+// isProfitable(a, c) is true.
----------------
Meinersbur wrote:

I don't think transitivity needs to apply. Loop interchange's bubble sort is a greedy algorithm: Make local decision in the hopes that it improves the global result. In particular, it depends on the order of a,b,c in the loop nest. After exchanging a and b, exchanging b and c might not be profitable anymot

```
for c:
  for a:
    for b:
      A[b][a]
      B[c]
```
Interchanging a with b is profitable (making `A[b][a]` consecutive). Interchanging b with c as well (making `B[c]` consecutive)[^1]. But after interchanging a and b, interchanging b and c is not necessarily profitable: it destroys that the entire `A[b][a]` is accessed consecutively.

Of course there are more concerns than conscecutive accesses, such as data reuse. But this is not how `isProfitable`: It consists of multiple single concern decision-making rules, applying the one with the higherst priority. They do not (and cannot) have a global view on what the eventual best loop order would be. If that would be the case, we should compute that order in advance, then apply bubble sort until we reach that order. That wouln't be a greedy algorithm anymore though.

[^1]: You may argue the question is malformed: b and c are not neighbors, they cannot even be interchanged.



https://github.com/llvm/llvm-project/pull/127473


More information about the llvm-commits mailing list