[llvm] [LoopInterchange] Do not interchange guarded imperfect loop nests (PR #201504)

Madhur Amilkanthwar via llvm-commits llvm-commits at lists.llvm.org
Thu Jun 4 08:08:51 PDT 2026


================
@@ -832,6 +832,34 @@ bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) {
         Succ != OuterLoopLatch)
       return false;
 
+  // Reject nests where the outer-loop header conditionally branches to the
+  // outer latch. Such a branch guards the inner loop, so it runs only on a
+  // subset of the outer iterations. If interchanged, the inner loop would move
+  // outside the guard and run on every outer iteration, including the
+  // guarded-off ones. That is illegal when the inner loop relies on the guard
+  // to terminate.
+  //
+  // TODO: This is conservative approach and under some circumstances, we can
+  // still allow the interchange. e.g.
+  // for (j = 0; j < 3; j++) {
+  //  for (i = 0; i < 2; i++) {
+  //   if (j != 0)                     // guard: invariant across (i,k)
+  //     for (k = 0; ; k++) {          // inner; eq-exit needs j>=1
+  //       y[i][j][k] = x[j][k][i] + w[j][k][i];
+  //       if (k + 1 == j) break;
+  //     }
+  //  }
+  // }
+  // Here the guard (j != 0) uses only the enclosing loop's IV j, not the
+  // interchanged IVs (i and k), so it is invariant across both interchanged
+  // loops and could be hoisted to gate the whole nest; the interchange would
+  // still be legal.
----------------
madhur13490 wrote:

I think I have added a simple example. Otherwise, I don't mind, dropping the example.

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


More information about the llvm-commits mailing list