Skip to content

[Utils] Fix incorrect LCSSA PHI nodes when splitting critical edges with MergeIdenticalEdges #131744

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 5 commits into from
Apr 3, 2025

Conversation

Camsyn
Copy link
Contributor

@Camsyn Camsyn commented Mar 18, 2025

Description

This PR fixes incorrect LCSSA PHI node generation when splitting critical edges with both
PreserveLCSSA and MergeIdenticalEdges enabled. The bug caused PHI nodes in the split block
to miss predecessors when multiple identical edges were merged.


Issue Details

When splitting edges from blocks with >1 identical edges to a loop exit block (e.g., via switch
instructions), the interaction between these options leads to invalid PHI nodes:

  1. MergeIdenticalEdges merges identical edges into a single edge to the new split block.
  2. PreserveLCSSA would only insert one PHI entry for the merged edge, ignoring the original
    number of identical edges.

Example (simplified from function Parse in lemon.c from SQLite3 in FuzzBench):

; Original IR  
exiting:  
  switch i8 %cond, label %while.body [  
      i8 0, label %exit  
      i8 10, label %exit  
  ]  
exit:  
  %phi = phi i32 [%val, %exiting], [%val, %exiting]  ; Requires two predecessors  

After splitting with PreserveLCSSA and MergeIdenticalEdges, the PHI node in the split block
incorrectly became:

split:  
  %lcssa = phi i32 [%val, %exiting]   ; Missing one predecessor!  
  br label %exit  

instead of the correct:

split:  
  %lcssa = phi i32 [%val, %exiting], [%val, %exiting]  ; Both edges preserved  
  br label %exit  

Fix

Modify createPHIsForSplitLoopExit to accept all predecessor entries corresponding to the number
of merged edges. Instead of passing a single predecessor block, we now pass NumSplittedIdenticalEdges
copies of the original block, ensuring PHI nodes have correct incoming entries.


Impact

Fixes miscompilations in edge cases where critical edge splitting interacts with LCSSA and
edge merging. No known regressions introduced.


References

  • Original bug context: BreakCriticalEdges.cpp (lines 291)
  • Example derived from FuzzBench/SQLite3’s Parse function in lemon.c.

…ith MergeIdenticalEdges


When splitting a critical edge from a block with multiple identical 
edges to an exit block while both `PreserveLCSSA` and 
`MergeIdenticalEdges` are enabled, the generated LCSSA PHI 
nodes in the split block would miss incoming values from merged edges.

This occurs because:
1. `MergeIdenticalEdges` merges multiple identical edges into a single 
    edge to the new split block.
2. `PreserveLCSSA` (in `createPHIsForSplitLoopExit`) previously assumed
    only one incoming edge from the original block, creating PHI nodes 
    with incomplete predecessors.

The fix modifies `createPHIsForSplitLoopExit` to account for merged 
edges by passing all original predecessor entries (matching the number 
of merged edges) when creating PHI nodes. 

This ensures all incoming values are properly reflected in the split 
block's PHI nodes.

Add unittest case in `BasicBlockUtilsTest.cpp` to verify the correction 
of PHI node generation in this scenario.
Copy link

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@llvmbot
Copy link
Member

llvmbot commented Mar 18, 2025

@llvm/pr-subscribers-llvm-transforms

Author: None (Camsyn)

Changes

Description

This PR fixes incorrect LCSSA PHI node generation when splitting critical edges with both
PreserveLCSSA and MergeIdenticalEdges enabled. The bug caused PHI nodes in the split block
to miss predecessors when multiple identical edges were merged.


Issue Details

When splitting edges from blocks with >1 identical edges to a loop exit block (e.g., via switch
instructions), the interaction between these options leads to invalid PHI nodes:

  1. MergeIdenticalEdges merges identical edges into a single edge to the new split block.
  2. PreserveLCSSA would only insert one PHI entry for the merged edge, ignoring the original
    number of identical edges.

Example (simplified from function Parse in lemon.c from SQLite3 in FuzzBench):

; Original IR  
exiting:  
  switch i8 %cond, label %while.body [  
      i8 0, label %exit  
      i8 10, label %exit  
  ]  
exit:  
  %phi = phi i32 [%val, %exiting], [%val, %exiting]  ; Requires two predecessors  

After splitting with PreserveLCSSA and MergeIdenticalEdges, the PHI node in the split block
incorrectly became:

split:  
  %lcssa = phi i32 [%val, %exiting]   ; Missing one predecessor!  
  br label %exit  

instead of the correct:

split:  
  %lcssa = phi i32 [%val, %exiting], [%val, %exiting]  ; Both edges preserved  
  br label %exit  

Fix

Modify createPHIsForSplitLoopExit to accept all predecessor entries corresponding to the number
of merged edges. Instead of passing a single predecessor block, we now pass NumSplittedIdenticalEdges
copies of the original block, ensuring PHI nodes have correct incoming entries.


Impact

Fixes miscompilations in edge cases where critical edge splitting interacts with LCSSA and
edge merging. No known regressions introduced.


References

  • Original bug context: BreakCriticalEdges.cpp (lines 291)
  • Example derived from FuzzBench/SQLite3’s Parse function in lemon.c.

Full diff: https://github.com/llvm/llvm-project/pull/131744.diff

2 Files Affected:

  • (modified) llvm/lib/Transforms/Utils/BreakCriticalEdges.cpp (+10-1)
  • (modified) llvm/unittests/Transforms/Utils/BasicBlockUtilsTest.cpp (+57)
diff --git a/llvm/lib/Transforms/Utils/BreakCriticalEdges.cpp b/llvm/lib/Transforms/Utils/BreakCriticalEdges.cpp
index 62b4b545f29bb..075a1afb4f6d9 100644
--- a/llvm/lib/Transforms/Utils/BreakCriticalEdges.cpp
+++ b/llvm/lib/Transforms/Utils/BreakCriticalEdges.cpp
@@ -205,6 +205,8 @@ llvm::SplitKnownCriticalEdge(Instruction *TI, unsigned SuccNum,
     }
   }
 
+  unsigned NumSplittedIdenticalEdges = 1; 
+
   // If there are any other edges from TIBB to DestBB, update those to go
   // through the split block, making those edges non-critical as well (and
   // reducing the number of phi entries in the DestBB if relevant).
@@ -217,6 +219,9 @@ llvm::SplitKnownCriticalEdge(Instruction *TI, unsigned SuccNum,
 
       // We found another edge to DestBB, go to NewBB instead.
       TI->setSuccessor(i, NewBB);
+
+      // Record the number of splitted identical edges to DestBB.
+      NumSplittedIdenticalEdges++;
     }
   }
 
@@ -288,7 +293,11 @@ llvm::SplitKnownCriticalEdge(Instruction *TI, unsigned SuccNum,
 
         // Update LCSSA form in the newly created exit block.
         if (Options.PreserveLCSSA) {
-          createPHIsForSplitLoopExit(TIBB, NewBB, DestBB);
+          // If > 1 identical edges to be splitted, we need to introduce 
+          // the incoming blocks of the same number for the new PHINode.
+          createPHIsForSplitLoopExit(
+            SmallVector<BasicBlock *, 4>(NumSplittedIdenticalEdges, TIBB),
+            NewBB, DestBB);
         }
 
         if (!LoopPreds.empty()) {
diff --git a/llvm/unittests/Transforms/Utils/BasicBlockUtilsTest.cpp b/llvm/unittests/Transforms/Utils/BasicBlockUtilsTest.cpp
index 56692cf25b797..a2f17ea672833 100644
--- a/llvm/unittests/Transforms/Utils/BasicBlockUtilsTest.cpp
+++ b/llvm/unittests/Transforms/Utils/BasicBlockUtilsTest.cpp
@@ -438,6 +438,63 @@ define void @crit_edge(i1 %cond0, i1 %cond1) {
   EXPECT_TRUE(PDT.verify());
 }
 
+TEST(BasicBlockUtils, SplitLoopCriticalEdge) {
+  LLVMContext C;
+  std::unique_ptr<Module> M = parseIR(C, R"IR(
+declare dso_local i1 @predicate(ptr noundef %p)
+
+define dso_local ptr @Parse(ptr noundef %gp) {
+entry:
+  br label %for.inc
+
+for.inc:
+  %phi = phi ptr [ %gp, %entry ], [ %cp, %while.cond ], [ %cp, %while.cond ]
+  %cond = call i1 @predicate(ptr noundef %phi)
+  %inc= getelementptr inbounds i8, ptr %phi, i64 1
+  br i1 %cond, label %while.cond, label %exit
+
+while.cond:
+  %cp = phi ptr [ %inc, %for.inc ], [ %incdec, %while.body ]
+  %val = load i8, ptr %cp, align 1
+  switch i8 %val, label %while.body [
+    i8 10, label %for.inc
+    i8 0, label %for.inc
+  ]
+
+while.body:
+  %incdec= getelementptr inbounds i8, ptr %cp, i64 1
+  br label %while.cond
+
+exit:
+  ret ptr %phi
+}
+)IR");
+  Function *F = M->getFunction("Parse");
+  DominatorTree DT(*F);
+  LoopInfo LI(DT);
+
+  CriticalEdgeSplittingOptions CESO =
+      CriticalEdgeSplittingOptions(nullptr, &LI, nullptr)
+          .setMergeIdenticalEdges()
+          .setPreserveLCSSA();
+  EXPECT_EQ(2u, SplitAllCriticalEdges(*F, CESO));
+
+  BasicBlock *WhileBB = getBasicBlockByName(*F, "while.cond");
+  BasicBlock *SplitBB = WhileBB->getTerminator()->getSuccessor(1);
+  // The only 1 successor of SplitBB is %for.inc
+  ASSERT_EQ(1u, SplitBB->getTerminator()->getNumSuccessors());
+  // MergeIdenticalEdges: SplitBB has two identical predecessors, %while.cond.
+  ASSERT_EQ(WhileBB, SplitBB->getUniquePredecessor());
+  ASSERT_EQ(true, SplitBB->hasNPredecessors(2));
+
+  PHINode *PN = dyn_cast<PHINode>(&(SplitBB->front()));
+  // PreserveLCSSA: should insert a PHI node in front of SplitBB
+  ASSERT_NE(nullptr, PN);
+  // The PHI node should have 2 identical incoming blocks.
+  ASSERT_EQ(2u, PN->getNumIncomingValues());
+  ASSERT_EQ(PN->getIncomingBlock(0), PN->getIncomingBlock(1));
+}
+
 TEST(BasicBlockUtils, SplitIndirectBrCriticalEdgesIgnorePHIs) {
   LLVMContext C;
   std::unique_ptr<Module> M = parseIR(C, R"IR(

@dtcxzyw dtcxzyw requested a review from nikic March 18, 2025 07:21
Copy link

⚠️ We detected that you are using a GitHub private e-mail address to contribute to the repo.
Please turn off Keep my email addresses private setting in your account.
See LLVM Discourse for more information.

Copy link

github-actions bot commented Mar 18, 2025

✅ With the latest revision this PR passed the C/C++ code formatter.

@nikic
Copy link
Contributor

nikic commented Mar 20, 2025

It looks like the test is failing:


C:\ws\src\llvm\unittests\Transforms\Utils\BasicBlockUtilsTest.cpp:492
Expected equality of these values:
  nullptr
    Which is: NULL
  PN
    Which is: 0000020DEA46FCA8

Co-authored-by: Nikita Popov <github@npopov.com>
@Camsyn
Copy link
Contributor Author

Camsyn commented Apr 3, 2025

Can this PR be merged? Or if there are any deficiencies, I will actively promote it.

@Camsyn Camsyn requested a review from nikic April 3, 2025 08:50
Copy link
Contributor

@nikic nikic left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@nikic nikic merged commit ecc3545 into llvm:main Apr 3, 2025
8 of 11 checks passed
Copy link

github-actions bot commented Apr 3, 2025

@Camsyn Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants