From 48e16184a5821b21dd5fd9e01aa507b724e55ece Mon Sep 17 00:00:00 2001 From: BoyBaykiller Date: Sun, 7 Jun 2026 07:58:30 +0200 Subject: [PATCH] * remove candidate block (pred) if possible. This helps downstream phases like optimizeBools --- src/coreclr/jit/fgopt.cpp | 55 ++++++++++++++++++++++++++++++++++----- 1 file changed, 48 insertions(+), 7 deletions(-) diff --git a/src/coreclr/jit/fgopt.cpp b/src/coreclr/jit/fgopt.cpp index 5be7aea1445a53..fe55ef4c5dec31 100644 --- a/src/coreclr/jit/fgopt.cpp +++ b/src/coreclr/jit/fgopt.cpp @@ -5212,6 +5212,23 @@ PhaseStatus Compiler::fgHeadTailMerge(bool early) fgUnlinkStmt(predBlock, stmt); + bool canRemove = + predBlock->isEmpty() && !predBlock->HasFlag(BBF_DONT_REMOVE) && predBlock != fgFirstBB; + if (canRemove) + { + for (BasicBlock* const pred : predBlock->PredBlocksEditing()) + { + fgReplaceJumpTarget(pred, predBlock, commSucc); + } + + fgRemoveBlock(predBlock, true); + + if (commSucc->hasProfileWeight()) + { + commSucc->increaseBBProfileWeight(predBlock->bbWeight); + } + } + // Add one of the matching stmts to block, and // update its flags. // @@ -5344,15 +5361,32 @@ PhaseStatus Compiler::fgHeadTailMerge(bool early) // Fix up the flow. // - if (commSucc != nullptr) + bool canRemove = predBlock->isEmpty() && !predBlock->HasFlag(BBF_DONT_REMOVE) && predBlock != fgFirstBB; + if (canRemove) { - assert(predBlock->KindIs(BBJ_ALWAYS)); - fgRedirectEdge(predBlock->TargetEdgeRef(), crossJumpTarget); + for (BasicBlock* const pred : predBlock->PredBlocksEditing()) + { + fgReplaceJumpTarget(pred, predBlock, crossJumpTarget); + } + fgRemoveBlock(predBlock, true); + + if (commSucc != nullptr && commSucc->hasProfileWeight()) + { + commSucc->increaseBBProfileWeight(predBlock->bbWeight); + } } else { - FlowEdge* const newEdge = fgAddRefPred(crossJumpTarget, predBlock); - predBlock->SetKindAndTargetEdge(BBJ_ALWAYS, newEdge); + if (commSucc != nullptr) + { + assert(predBlock->KindIs(BBJ_ALWAYS)); + fgRedirectEdge(predBlock->TargetEdgeRef(), crossJumpTarget); + } + else + { + FlowEdge* const newEdge = fgAddRefPred(crossJumpTarget, predBlock); + predBlock->SetKindAndTargetEdge(BBJ_ALWAYS, newEdge); + } } // For tail merge we have a common successor of predBlock and @@ -5402,6 +5436,13 @@ PhaseStatus Compiler::fgHeadTailMerge(bool early) continue; } + // If this block was already processed, skip it + // + if (predBlock->isEmpty()) + { + continue; + } + Statement* lastStmt = predBlock->lastStmt(); // Block might be empty. @@ -5498,9 +5539,9 @@ PhaseStatus Compiler::fgHeadTailMerge(bool early) predInfo.Reset(); for (BasicBlock* const block : retOrThrowBlocks.BottomUpOrder()) { - // If this block was already merged, skip it + // If this block was already processed, skip it // - if (!block->KindIs(BBJ_RETURN, BBJ_THROW)) + if (!block->KindIs(BBJ_RETURN, BBJ_THROW) || block->isEmpty()) { continue; }