[llvm-branch-commits] [llvm] [LoopInterchange] Drop loop metadata and branch weights of interchanged loops (PR #235892)

Madhur Amilkanthwar via llvm-branch-commits llvm-branch-commits at lists.llvm.org
Tue Nov 3 23:03:10 PST 2026


================
@@ -2168,6 +2170,26 @@ void LoopInterchangeTransform::restructureLoops(
   SE->forgetLoop(NewOuter);
 }
 
+/// Update the metadata attached to the latch branches of the two loops. The
+/// loop metadata and the branch weights are dropped. Some attributes of the
+/// loop metadata may not hold after interchange (e.g.,
+/// llvm.loop.parallel_accesses of the inner loop doesn't imply that the loop is
+/// parallel when it becomes the outer loop), and no followup attributes are
+/// defined for interchange.
+/// TODO: Preserve the branch weights by swapping them.
+void LoopInterchangeTransform::updateLatchMetadata() {
+  auto *OuterLoopLatchBI =
+      cast<CondBrInst>(OuterLoop->getLoopLatch()->getTerminator());
+  auto *InnerLoopLatchBI =
+      cast<CondBrInst>(InnerLoop->getLoopLatch()->getTerminator());
+
+  for (CondBrInst *BI : {OuterLoopLatchBI, InnerLoopLatchBI}) {
+    BI->setMetadata(LLVMContext::MD_loop, nullptr);
+    BI->setMetadata(LLVMContext::MD_prof, nullptr);
----------------
madhur13490 wrote:

Do we need to drop the branch weights at all? Since each weight stays with its own loop's latch, the ratio still describes that loop after interchange. Triangular nests are rejected, so the inner trip count doesn't depend on the outer induction variable. In @branch_weights, the output before this patch kept 1:63 on the j branch and 127:1 on the i branch. That still gives trip counts of 64 and 128, which matches the code after interchange. Is there a case where the old weights become wrong? If not, I'd keep them, because marking them unknown throws away PGO data for every interchanged nest.

Minor: if we keep this code, the setMetadata(MD_prof, nullptr) call only matters when the function has no profile, because setExplicitlyUnknownBranchWeightsIfProfiled overwrites it otherwise. An if/else or a short comment would make that clearer.

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


More information about the llvm-branch-commits mailing list