[llvm] [CodeGenPrepare][NFC] Reland: Update the dominator tree instead of rebuilding it (PR #179040)

Mingjie Xu via llvm-commits llvm-commits at lists.llvm.org
Thu Feb 12 03:53:35 PST 2026


https://github.com/Enna1 updated https://github.com/llvm/llvm-project/pull/179040

>From cd32e5b36c524cc0f713927a5f10090b971aea60 Mon Sep 17 00:00:00 2001
From: Enna1 <xumingjie.enna1 at bytedance.com>
Date: Fri, 30 Jan 2026 21:38:20 +0800
Subject: [PATCH 01/14] [BasicBlockUtils] Fix dominator tree update for entry
 block in splitBlockBefore()

Domoninator update for entry block in `SplitBlockPredecessors()` was fixed by
06dfbb50d70eea4ae38d655842626a0b9b224d5c , this patch fixes dominator
tree update for entry block in `splitBlockBefore()` with
`UpdateAnalysisInformation()`.
---
 llvm/lib/Transforms/Utils/BasicBlockUtils.cpp | 66 ++++++-------------
 1 file changed, 21 insertions(+), 45 deletions(-)

diff --git a/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp b/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp
index b0c04086f5e84..12206e14ca8fd 100644
--- a/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp
+++ b/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp
@@ -1064,51 +1064,6 @@ BasicBlock *llvm::SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt,
                         Before);
 }
 
-BasicBlock *llvm::splitBlockBefore(BasicBlock *Old, BasicBlock::iterator SplitPt,
-                                   DomTreeUpdater *DTU, LoopInfo *LI,
-                                   MemorySSAUpdater *MSSAU,
-                                   const Twine &BBName) {
-
-  BasicBlock::iterator SplitIt = SplitPt;
-  while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
-    ++SplitIt;
-  std::string Name = BBName.str();
-  BasicBlock *New = Old->splitBasicBlock(
-      SplitIt, Name.empty() ? Old->getName() + ".split" : Name,
-      /* Before=*/true);
-
-  // The new block lives in whichever loop the old one did. This preserves
-  // LCSSA as well, because we force the split point to be after any PHI nodes.
-  if (LI)
-    if (Loop *L = LI->getLoopFor(Old))
-      L->addBasicBlockToLoop(New, *LI);
-
-  if (DTU) {
-    SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
-    // New dominates Old. The predecessor nodes of the Old node dominate
-    // New node.
-    SmallPtrSet<BasicBlock *, 8> UniquePredecessorsOfOld;
-    DTUpdates.push_back({DominatorTree::Insert, New, Old});
-    DTUpdates.reserve(DTUpdates.size() + 2 * pred_size(New));
-    for (BasicBlock *PredecessorOfOld : predecessors(New))
-      if (UniquePredecessorsOfOld.insert(PredecessorOfOld).second) {
-        DTUpdates.push_back({DominatorTree::Insert, PredecessorOfOld, New});
-        DTUpdates.push_back({DominatorTree::Delete, PredecessorOfOld, Old});
-      }
-
-    DTU->applyUpdates(DTUpdates);
-
-    // Move MemoryAccesses still tracked in Old, but part of New now.
-    // Update accesses in successor blocks accordingly.
-    if (MSSAU) {
-      MSSAU->applyUpdates(DTUpdates, DTU->getDomTree());
-      if (VerifyMemorySSA)
-        MSSAU->getMemorySSA()->verifyMemorySSA();
-    }
-  }
-  return New;
-}
-
 /// Update DominatorTree, LoopInfo, and LCCSA analysis information.
 /// Invalidates DFS Numbering when DTU or DT is provided.
 static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
@@ -1223,6 +1178,27 @@ static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
   }
 }
 
+BasicBlock *llvm::splitBlockBefore(BasicBlock *Old,
+                                   BasicBlock::iterator SplitPt,
+                                   DomTreeUpdater *DTU, LoopInfo *LI,
+                                   MemorySSAUpdater *MSSAU,
+                                   const Twine &BBName) {
+  BasicBlock::iterator SplitIt = SplitPt;
+  while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
+    ++SplitIt;
+  SmallVector<BasicBlock *, 4> Preds(predecessors(Old));
+  std::string Name = BBName.str();
+  BasicBlock *New = Old->splitBasicBlock(
+      SplitIt, Name.empty() ? Old->getName() + ".split" : Name,
+      /* Before=*/true);
+
+  bool HasLoopExit = false;
+  UpdateAnalysisInformation(Old, New, Preds, DTU, nullptr, LI, MSSAU, false,
+                            HasLoopExit);
+
+  return New;
+}
+
 /// Update the PHI nodes in OrigBB to include the values coming from NewBB.
 /// This also updates AliasAnalysis, if available.
 static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,

>From 0cf9493bf6611ebecbbd4a6a895fd5c4d1413b85 Mon Sep 17 00:00:00 2001
From: Enna1 <xumingjie.enna1 at bytedance.com>
Date: Fri, 30 Jan 2026 21:38:28 +0800
Subject: [PATCH 02/14] add test

---
 .../Transforms/Utils/BasicBlockUtilsTest.cpp  | 25 +++++++++++++++++++
 1 file changed, 25 insertions(+)

diff --git a/llvm/unittests/Transforms/Utils/BasicBlockUtilsTest.cpp b/llvm/unittests/Transforms/Utils/BasicBlockUtilsTest.cpp
index 00d9e9ff81e05..d5b4f6b6d6593 100644
--- a/llvm/unittests/Transforms/Utils/BasicBlockUtilsTest.cpp
+++ b/llvm/unittests/Transforms/Utils/BasicBlockUtilsTest.cpp
@@ -378,6 +378,31 @@ define i32 @no_unreachable(i1 %cond) {
   EXPECT_TRUE(DT.verify());
 }
 
+TEST(BasicBlockUtils, splitBlockBefore) {
+  LLVMContext C;
+  std::unique_ptr<Module> M = parseIR(C, R"IR(
+define i32 @basic_func(i1 %cond) {
+entry:
+  br i1 %cond, label %bb0, label %bb1
+bb0:
+  br label %bb1
+bb1:
+  %phi = phi i32 [ 0, %entry ], [ 1, %bb0 ]
+  ret i32 %phi
+}
+)IR");
+  Function *F = M->getFunction("basic_func");
+  DominatorTree DT(*F);
+  DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
+  BasicBlock *EntryBB = &F->getEntryBlock();
+  Instruction *TI = EntryBB->getTerminator();
+
+  // Make sure the dominator tree is properly updated if calling this on the
+  // entry block.
+  splitBlockBefore(EntryBB, TI, &DTU, nullptr, nullptr);
+  EXPECT_TRUE(DTU.getDomTree().verify());
+}
+
 TEST(BasicBlockUtils, SplitBlockPredecessors) {
   LLVMContext C;
   std::unique_ptr<Module> M = parseIR(C, R"IR(

>From f7e50fe0d1d02a8f161c0bc48e50087bf5dbed99 Mon Sep 17 00:00:00 2001
From: Enna1 <xumingjie.enna1 at bytedance.com>
Date: Fri, 30 Jan 2026 23:28:30 +0800
Subject: [PATCH 03/14] address review comment

---
 llvm/lib/Transforms/Utils/BasicBlockUtils.cpp | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp b/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp
index 12206e14ca8fd..3fb407d7218d7 100644
--- a/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp
+++ b/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp
@@ -1187,9 +1187,8 @@ BasicBlock *llvm::splitBlockBefore(BasicBlock *Old,
   while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
     ++SplitIt;
   SmallVector<BasicBlock *, 4> Preds(predecessors(Old));
-  std::string Name = BBName.str();
   BasicBlock *New = Old->splitBasicBlock(
-      SplitIt, Name.empty() ? Old->getName() + ".split" : Name,
+      SplitIt, BBName.isTriviallyEmpty() ? Old->getName() + ".split" : BBName,
       /* Before=*/true);
 
   bool HasLoopExit = false;

>From 3c6bfa73a3ad8bd958ec6a2692f8430c61cc710e Mon Sep 17 00:00:00 2001
From: "xumingjie.enna1" <xumingjie.enna1 at bytedance.com>
Date: Sun, 14 Dec 2025 22:22:49 +0800
Subject: [PATCH 04/14] [CodeGenPrepare][NFC] Reland: Update the dominator tree
 instead of rebuilding it

The original differential revision is https://reviews.llvm.org/D153638

Reverted in https://github.com/llvm/llvm-project/commit/f5b5a30858f32e237636acd296b6d0f87c1dfe97 because of causing a clang crash.

This patch relands it with the crash fixed, in the `while (MadeChange)`
loop, `optimizeBlock()` and `eliminateFallThrough()` can delete blocks,
we need to flush awaiting deletion in each iteration.
---
 .../Transforms/Utils/BypassSlowDivision.h     |   7 +-
 llvm/lib/CodeGen/CodeGenPrepare.cpp           | 209 ++++++++++--------
 .../Transforms/Utils/BypassSlowDivision.cpp   |  46 +++-
 ...bypass-slow-div-debug-info-inseltpoison.ll |  66 +++---
 .../AMDGPU/bypass-slow-div-debug-info.ll      |  66 +++---
 5 files changed, 233 insertions(+), 161 deletions(-)

diff --git a/llvm/include/llvm/Transforms/Utils/BypassSlowDivision.h b/llvm/include/llvm/Transforms/Utils/BypassSlowDivision.h
index bd98c902d1ab4..eceb131d8c60c 100644
--- a/llvm/include/llvm/Transforms/Utils/BypassSlowDivision.h
+++ b/llvm/include/llvm/Transforms/Utils/BypassSlowDivision.h
@@ -25,6 +25,8 @@
 namespace llvm {
 
 class BasicBlock;
+class DomTreeUpdater;
+class LoopInfo;
 class Value;
 
 struct DivRemMapKey {
@@ -66,8 +68,9 @@ template <> struct DenseMapInfo<DivRemMapKey> {
 ///
 /// This optimization may add basic blocks immediately after BB; for obvious
 /// reasons, you shouldn't pass those blocks to bypassSlowDivision.
-bool bypassSlowDivision(
-    BasicBlock *BB, const DenseMap<unsigned int, unsigned int> &BypassWidth);
+bool bypassSlowDivision(BasicBlock *BB,
+                        const DenseMap<unsigned int, unsigned int> &BypassWidth,
+                        DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr);
 
 } // end namespace llvm
 
diff --git a/llvm/lib/CodeGen/CodeGenPrepare.cpp b/llvm/lib/CodeGen/CodeGenPrepare.cpp
index b9cf73a48ee22..96ab1add651bc 100644
--- a/llvm/lib/CodeGen/CodeGenPrepare.cpp
+++ b/llvm/lib/CodeGen/CodeGenPrepare.cpp
@@ -24,6 +24,7 @@
 #include "llvm/ADT/Statistic.h"
 #include "llvm/Analysis/BlockFrequencyInfo.h"
 #include "llvm/Analysis/BranchProbabilityInfo.h"
+#include "llvm/Analysis/DomTreeUpdater.h"
 #include "llvm/Analysis/FloatingPointPredicateUtils.h"
 #include "llvm/Analysis/InstructionSimplify.h"
 #include "llvm/Analysis/LoopInfo.h"
@@ -253,6 +254,15 @@ static cl::opt<bool> EnableICMP_EQToICMP_ST(
     "cgp-icmp-eq2icmp-st", cl::Hidden, cl::init(false),
     cl::desc("Enable ICMP_EQ to ICMP_S(L|G)T conversion."));
 
+#ifdef EXPENSIVE_CHECKS
+static bool VerifyDT = true;
+#else
+static bool VerifyDT = false;
+#endif
+static cl::opt<bool, true> VerifyDTUpdates(
+    "cgp-verify-dt-updates", cl::location(VerifyDT), cl::Hidden,
+    cl::desc("Verify dominator tree updates in CodeGenPrepare"));
+
 static cl::opt<bool>
     VerifyBFIUpdates("cgp-verify-bfi-updates", cl::Hidden, cl::init(false),
                      cl::desc("Enable BFI update verification for "
@@ -312,6 +322,8 @@ class CodeGenPrepare {
   const TargetTransformInfo *TTI = nullptr;
   const BasicBlockSectionsProfileReader *BBSectionsProfileReader = nullptr;
   const TargetLibraryInfo *TLInfo = nullptr;
+  DominatorTree *DT = nullptr;
+  DomTreeUpdater *DTU = nullptr;
   LoopInfo *LI = nullptr;
   std::unique_ptr<BlockFrequencyInfo> BFI;
   std::unique_ptr<BranchProbabilityInfo> BPI;
@@ -363,10 +375,6 @@ class CodeGenPrepare {
   /// DataLayout for the Function being processed.
   const DataLayout *DL = nullptr;
 
-  /// Building the dominator tree can be expensive, so we only build it
-  /// lazily and update it when required.
-  std::unique_ptr<DominatorTree> DT;
-
 public:
   CodeGenPrepare() = default;
   CodeGenPrepare(const TargetMachine *TM) : TM(TM){};
@@ -409,20 +417,16 @@ class CodeGenPrepare {
     }
   }
 
-  // Get the DominatorTree, building if necessary.
-  DominatorTree &getDT(Function &F) {
-    if (!DT)
-      DT = std::make_unique<DominatorTree>(F);
-    return *DT;
-  }
+  // Get the DominatorTree, updating it if necessary.
+  DominatorTree &getDT() { return DTU->getDomTree(); }
 
   void removeAllAssertingVHReferences(Value *V);
   bool eliminateAssumptions(Function &F);
-  bool eliminateFallThrough(Function &F, DominatorTree *DT = nullptr);
-  bool eliminateMostlyEmptyBlocks(Function &F);
+  bool eliminateFallThrough(Function &F);
+  bool eliminateMostlyEmptyBlocks(Function &F, ModifyDT &ModifiedDT);
   BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
   bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
-  void eliminateMostlyEmptyBlock(BasicBlock *BB);
+  void eliminateMostlyEmptyBlock(BasicBlock *BB, ModifyDT &ModifiedDT);
   bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
                                      bool isPreheader);
   bool makeBitReverse(Instruction &I);
@@ -466,7 +470,7 @@ class CodeGenPrepare {
       Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
       bool HasPromoted, TypePromotionTransaction &TPT,
       SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
-  bool splitBranchCondition(Function &F, ModifyDT &ModifiedDT);
+  bool splitBranchCondition(Function &F);
   bool simplifyOffsetableRelocate(GCStatepointInst &I);
 
   bool tryToSinkFreeOperands(Instruction *I);
@@ -497,6 +501,7 @@ class CodeGenPrepareLegacyPass : public FunctionPass {
     AU.addRequired<TargetLibraryInfoWrapperPass>();
     AU.addRequired<TargetPassConfig>();
     AU.addRequired<TargetTransformInfoWrapperPass>();
+    AU.addRequired<DominatorTreeWrapperPass>();
     AU.addRequired<LoopInfoWrapperPass>();
     AU.addUsedIfAvailable<BasicBlockSectionsProfileReaderWrapperPass>();
   }
@@ -517,6 +522,7 @@ bool CodeGenPrepareLegacyPass::runOnFunction(Function &F) {
   CGP.TRI = CGP.SubtargetInfo->getRegisterInfo();
   CGP.TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
   CGP.TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
+  CGP.DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
   CGP.LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
   CGP.BPI.reset(new BranchProbabilityInfo(F, *CGP.LI));
   CGP.BFI.reset(new BlockFrequencyInfo(F, *CGP.BPI, *CGP.LI));
@@ -531,6 +537,7 @@ bool CodeGenPrepareLegacyPass::runOnFunction(Function &F) {
 INITIALIZE_PASS_BEGIN(CodeGenPrepareLegacyPass, DEBUG_TYPE,
                       "Optimize for code generation", false, false)
 INITIALIZE_PASS_DEPENDENCY(BasicBlockSectionsProfileReaderWrapperPass)
+INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
@@ -564,6 +571,7 @@ bool CodeGenPrepare::run(Function &F, FunctionAnalysisManager &AM) {
   TRI = SubtargetInfo->getRegisterInfo();
   TLInfo = &AM.getResult<TargetLibraryAnalysis>(F);
   TTI = &AM.getResult<TargetIRAnalysis>(F);
+  DT = &AM.getResult<DominatorTreeAnalysis>(F);
   LI = &AM.getResult<LoopAnalysis>(F);
   BPI.reset(new BranchProbabilityInfo(F, *LI));
   BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
@@ -601,6 +609,14 @@ bool CodeGenPrepare::_run(Function &F) {
       (void)F.setSectionPrefix("unknown");
   }
 
+  DomTreeUpdater DTUpdater(DT, DomTreeUpdater::UpdateStrategy::Lazy);
+  DTU = &DTUpdater;
+  auto resetDTAndLI = [&]() {
+    DTU->recalculate(F);
+    LI->releaseMemory();
+    LI->analyze(DTU->getDomTree());
+  };
+
   /// This optimization identifies DIV instructions that can be
   /// profitably bypassed and carried out with a shorter, faster divide.
   if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI->isSlowDivBypassed()) {
@@ -612,7 +628,7 @@ bool CodeGenPrepare::_run(Function &F) {
       // optimization to those blocks.
       BasicBlock *Next = BB->getNextNode();
       if (!llvm::shouldOptimizeForSize(BB, PSI, BFI.get()))
-        EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
+        EverMadeChange |= bypassSlowDivision(BB, BypassWidths, DTU, LI);
       BB = Next;
     }
   }
@@ -624,31 +640,45 @@ bool CodeGenPrepare::_run(Function &F) {
 
   // Eliminate blocks that contain only PHI nodes and an
   // unconditional branch.
-  EverMadeChange |= eliminateMostlyEmptyBlocks(F);
-
   ModifyDT ModifiedDT = ModifyDT::NotModifyDT;
+  EverMadeChange |= eliminateMostlyEmptyBlocks(F, ModifiedDT);
+  if (ModifiedDT != ModifyDT::NotModifyDT) {
+    // Rebuild the dom tree if the transformation above did change the CFG, but
+    // did not update the DT.
+    resetDTAndLI();
+  }
+
   if (!DisableBranchOpts)
-    EverMadeChange |= splitBranchCondition(F, ModifiedDT);
+    EverMadeChange |= splitBranchCondition(F);
 
   // Split some critical edges where one of the sources is an indirect branch,
   // to help generate sane code for PHIs involving such edges.
-  EverMadeChange |=
-      SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/true);
+  if (SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/true)) {
+    EverMadeChange = true;
+    resetDTAndLI();
+  }
+
+#ifndef NDEBUG
+  if (VerifyDT)
+    assert(getDT().verify(DominatorTree::VerificationLevel::Fast) &&
+           "Incorrect DominatorTree updates in CGP");
+
+  if (VerifyLoopInfo)
+    LI->verify(getDT());
+#endif
 
   // If we are optimzing huge function, we need to consider the build time.
   // Because the basic algorithm's complex is near O(N!).
   IsHugeFunc = F.size() > HugeFuncThresholdInCGPP;
 
-  // Transformations above may invalidate dominator tree and/or loop info.
-  DT.reset();
-  LI->releaseMemory();
-  LI->analyze(getDT(F));
-
   bool MadeChange = true;
   bool FuncIterated = false;
   while (MadeChange) {
     MadeChange = false;
 
+    // Flush pending updates as we may delete BasicBlocks in previous iteration of the current loop.
+    DTU->flush();
+
     for (BasicBlock &BB : llvm::make_early_inc_range(F)) {
       if (FuncIterated && !FreshBBs.contains(&BB))
         continue;
@@ -656,9 +686,6 @@ bool CodeGenPrepare::_run(Function &F) {
       ModifyDT ModifiedDTOnIteration = ModifyDT::NotModifyDT;
       bool Changed = optimizeBlock(BB, ModifiedDTOnIteration);
 
-      if (ModifiedDTOnIteration == ModifyDT::ModifyBBDT)
-        DT.reset();
-
       MadeChange |= Changed;
       if (IsHugeFunc) {
         // If the BB is updated, it may still has chance to be optimized.
@@ -691,11 +718,15 @@ bool CodeGenPrepare::_run(Function &F) {
     MadeChange |= optimizePhiTypes(F);
 
     if (MadeChange)
-      eliminateFallThrough(F, DT.get());
+      eliminateFallThrough(F);
 
 #ifndef NDEBUG
-    if (MadeChange && VerifyLoopInfo)
-      LI->verify(getDT(F));
+    if (VerifyDT)
+      assert(getDT().verify(DominatorTree::VerificationLevel::Fast) &&
+             "Incorrect DominatorTree updates in CGP");
+
+    if (VerifyLoopInfo)
+      LI->verify(getDT());
 #endif
 
     // Really free removed instructions during promotion.
@@ -713,6 +744,9 @@ bool CodeGenPrepare::_run(Function &F) {
   NewGEPBases.clear();
   SunkAddrs.clear();
 
+  // LoopInfo is not needed anymore and ConstantFoldTerminator can break it.
+  LI = nullptr;
+
   if (!DisableBranchOpts) {
     MadeChange = false;
     // Use a set vector to get deterministic iteration order. The order the
@@ -721,7 +755,7 @@ bool CodeGenPrepare::_run(Function &F) {
     SmallSetVector<BasicBlock *, 8> WorkList;
     for (BasicBlock &BB : F) {
       SmallVector<BasicBlock *, 2> Successors(successors(&BB));
-      MadeChange |= ConstantFoldTerminator(&BB, true);
+      MadeChange |= ConstantFoldTerminator(&BB, true, nullptr, DTU);
       if (!MadeChange)
         continue;
 
@@ -736,13 +770,16 @@ bool CodeGenPrepare::_run(Function &F) {
       BasicBlock *BB = WorkList.pop_back_val();
       SmallVector<BasicBlock *, 2> Successors(successors(BB));
 
-      DeleteDeadBlock(BB);
+      DeleteDeadBlock(BB, DTU);
 
       for (BasicBlock *Succ : Successors)
         if (pred_empty(Succ))
           WorkList.insert(Succ);
     }
 
+    // Flush pending DT updates in order to finalise deletion of dead blocks.
+    DTU->flush();
+
     // Merge pairs of basic blocks with unconditional branches, connected by
     // a single edge.
     if (EverMadeChange || MadeChange)
@@ -829,7 +866,7 @@ void CodeGenPrepare::removeAllAssertingVHReferences(Value *V) {
 /// Merge basic blocks which are connected by a single edge, where one of the
 /// basic blocks has a single successor pointing to the other basic block,
 /// which has a single predecessor.
-bool CodeGenPrepare::eliminateFallThrough(Function &F, DominatorTree *DT) {
+bool CodeGenPrepare::eliminateFallThrough(Function &F) {
   bool Changed = false;
   // Scan all of the blocks in the function, except for the entry block.
   // Use a temporary array to avoid iterator being invalidated when
@@ -850,19 +887,13 @@ bool CodeGenPrepare::eliminateFallThrough(Function &F, DominatorTree *DT) {
     if (!SinglePred || SinglePred == BB || BB->hasAddressTaken())
       continue;
 
-    // Make an effort to skip unreachable blocks.
-    if (DT && !DT->isReachableFromEntry(BB))
-      continue;
-
     BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
     if (Term && !Term->isConditional()) {
       Changed = true;
       LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n");
 
       // Merge BB into SinglePred and delete it.
-      MergeBlockIntoPredecessor(BB, /* DTU */ nullptr, LI, /* MSSAU */ nullptr,
-                                /* MemDep */ nullptr,
-                                /* PredecessorWithTwoSuccessors */ false, DT);
+      MergeBlockIntoPredecessor(BB, DTU, LI);
       Preds.insert(SinglePred);
 
       if (IsHugeFunc) {
@@ -913,7 +944,8 @@ BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
 /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
 /// edges in ways that are non-optimal for isel. Start by eliminating these
 /// blocks so we can split them the way we want them.
-bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
+bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F,
+                                                ModifyDT &ModifiedDT) {
   SmallPtrSet<BasicBlock *, 16> Preheaders;
   SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
   while (!LoopList.empty()) {
@@ -944,7 +976,7 @@ bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
         !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
       continue;
 
-    eliminateMostlyEmptyBlock(BB);
+    eliminateMostlyEmptyBlock(BB, ModifiedDT);
     MadeChange = true;
   }
   return MadeChange;
@@ -1120,7 +1152,9 @@ static void replaceAllUsesWith(Value *Old, Value *New,
 
 /// Eliminate a basic block that has only phi's and an unconditional branch in
 /// it.
-void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
+/// Indicate that the DT was modified only if the DT wasn't updated.
+void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB,
+                                               ModifyDT &ModifiedDT) {
   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
   BasicBlock *DestBB = BI->getSuccessor(0);
 
@@ -1134,7 +1168,7 @@ void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
       assert(SinglePred == BB &&
              "Single predecessor not the same as predecessor");
       // Merge DestBB into SinglePred/BB and delete it.
-      MergeBlockIntoPredecessor(DestBB);
+      MergeBlockIntoPredecessor(DestBB, DTU, LI);
       // Note: BB(=SinglePred) will not be deleted on this path.
       // DestBB(=its single successor) is the one that was deleted.
       LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n");
@@ -1187,6 +1221,7 @@ void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
   BB->eraseFromParent();
   ++NumBlocksElim;
 
+  ModifiedDT = ModifyDT::ModifyBBDT;
   LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
 }
 
@@ -1563,7 +1598,7 @@ bool CodeGenPrepare::replaceMathCmpWithIntrinsic(BinaryOperator *BO,
     // Finally, we need to ensure that the insert point will dominate all
     // existing uses of the increment.
 
-    auto &DT = getDT(*BO->getParent()->getParent());
+    auto &DT = getDT();
     if (DT.dominates(Cmp->getParent(), BO->getParent()))
       // If we're moving up the dom tree, all uses are trivially dominated.
       // (This is the common case for code produced by LSR.)
@@ -2552,7 +2587,8 @@ static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
 ///     %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
 ///
 /// If the transform is performed, return true and set ModifiedDT to true.
-static bool despeculateCountZeros(IntrinsicInst *CountZeros, LoopInfo &LI,
+static bool despeculateCountZeros(IntrinsicInst *CountZeros,
+                                  DomTreeUpdater &DTU, LoopInfo &LI,
                                   const TargetLowering *TLI,
                                   const DataLayout *DL, ModifyDT &ModifiedDT,
                                   SmallPtrSet<BasicBlock *, 32> &FreshBBs,
@@ -2580,7 +2616,8 @@ static bool despeculateCountZeros(IntrinsicInst *CountZeros, LoopInfo &LI,
 
   // The intrinsic will be sunk behind a compare against zero and branch.
   BasicBlock *StartBlock = CountZeros->getParent();
-  BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
+  BasicBlock *CallBlock = SplitBlock(StartBlock, CountZeros, &DTU, &LI,
+                                     /* MSSAU */ nullptr, "cond.false");
   if (IsHugeFunc)
     FreshBBs.insert(CallBlock);
 
@@ -2590,17 +2627,11 @@ static bool despeculateCountZeros(IntrinsicInst *CountZeros, LoopInfo &LI,
   BasicBlock::iterator SplitPt = std::next(BasicBlock::iterator(CountZeros));
   // Any debug-info after CountZeros should not be included.
   SplitPt.setHeadBit(true);
-  BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
+  BasicBlock *EndBlock = SplitBlock(CallBlock, &*SplitPt, &DTU, &LI,
+                                    /* MSSAU */ nullptr, "cond.end");
   if (IsHugeFunc)
     FreshBBs.insert(EndBlock);
 
-  // Update the LoopInfo. The new blocks are in the same loop as the start
-  // block.
-  if (Loop *L = LI.getLoopFor(StartBlock)) {
-    L->addBasicBlockToLoop(CallBlock, LI);
-    L->addBasicBlockToLoop(EndBlock, LI);
-  }
-
   // Set up a builder to create a compare, conditional branch, and PHI.
   IRBuilder<> Builder(CountZeros->getContext());
   Builder.SetInsertPoint(StartBlock->getTerminator());
@@ -2615,6 +2646,7 @@ static bool despeculateCountZeros(IntrinsicInst *CountZeros, LoopInfo &LI,
   Value *Cmp = Builder.CreateICmpEQ(Op, Zero, "cmpz");
   Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
   StartBlock->getTerminator()->eraseFromParent();
+  DTU.applyUpdates({{DominatorTree::Insert, StartBlock, EndBlock}});
 
   // Create a PHI in the end block to select either the output of the intrinsic
   // or the bit width of the operand.
@@ -2766,7 +2798,7 @@ bool CodeGenPrepare::optimizeCallInst(CallInst *CI, ModifyDT &ModifiedDT) {
     case Intrinsic::cttz:
     case Intrinsic::ctlz:
       // If counting zeros is expensive, try to avoid it.
-      return despeculateCountZeros(II, *LI, TLI, DL, ModifiedDT, FreshBBs,
+      return despeculateCountZeros(II, *DTU, *LI, TLI, DL, ModifiedDT, FreshBBs,
                                    IsHugeFunc);
     case Intrinsic::fshl:
     case Intrinsic::fshr:
@@ -3092,7 +3124,7 @@ bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB,
       continue;
 
     // Duplicate the return into TailCallBB.
-    (void)FoldReturnIntoUncondBranch(RetI, BB, TailCallBB);
+    (void)FoldReturnIntoUncondBranch(RetI, BB, TailCallBB, DTU);
     assert(!VerifyBFIUpdates ||
            BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB));
     BFI->setBlockFreq(BB,
@@ -3112,7 +3144,7 @@ bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB,
         ClonedInst->insertBefore(CI->getIterator());
       }
     }
-    BB->eraseFromParent();
+    DTU->deleteBB(BB);
   }
 
   return Changed;
@@ -5888,10 +5920,7 @@ bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
     // Defer the query (and possible computation of) the dom tree to point of
     // actual use.  It's expected that most address matches don't actually need
     // the domtree.
-    auto getDTFn = [MemoryInst, this]() -> const DominatorTree & {
-      Function *F = MemoryInst->getParent()->getParent();
-      return this->getDT(*F);
-    };
+    auto getDTFn = [this]() -> const DominatorTree & { return getDT(); };
     ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
         V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *LI, getDTFn,
         *TRI, InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI,
@@ -5953,7 +5982,7 @@ bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
 
   // TODO: Adjust insert point considering (Base|Scaled)Reg if possible.
   if (!SunkAddr) {
-    auto &DT = getDT(*MemoryInst->getFunction());
+    auto &DT = getDT();
     if ((AddrMode.BaseReg && !DT.dominates(AddrMode.BaseReg, &*InsertPos)) ||
         (AddrMode.ScaledReg && !DT.dominates(AddrMode.ScaledReg, &*InsertPos)))
       return Modified;
@@ -6764,7 +6793,7 @@ bool CodeGenPrepare::mergeSExts(Function &F) {
         continue;
       bool inserted = false;
       for (auto &Pt : CurPts) {
-        if (getDT(F).dominates(Inst, Pt)) {
+        if (getDT().dominates(Inst, Pt)) {
           replaceAllUsesWith(Pt, Inst, FreshBBs, IsHugeFunc);
           RemovedInsts.insert(Pt);
           Pt->removeFromParent();
@@ -6773,7 +6802,7 @@ bool CodeGenPrepare::mergeSExts(Function &F) {
           Changed = true;
           break;
         }
-        if (!getDT(F).dominates(Pt, Inst))
+        if (!getDT().dominates(Pt, Inst))
           // Give up if we need to merge in a common dominator as the
           // experiments show it is not profitable.
           continue;
@@ -6869,7 +6898,7 @@ bool CodeGenPrepare::splitLargeGEPOffsets() {
           NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
         else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) {
           NewBaseInsertBB =
-              SplitEdge(NewBaseInsertBB, Invoke->getNormalDest(), DT.get(), LI);
+              SplitEdge(NewBaseInsertBB, Invoke->getNormalDest(), &getDT(), LI);
           NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
         } else
           NewBaseInsertPt = std::next(BaseI->getIterator());
@@ -7739,12 +7768,6 @@ bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
        llvm::shouldOptimizeForSize(SI->getParent(), PSI, BFI.get())))
     return false;
 
-  // The DominatorTree needs to be rebuilt by any consumers after this
-  // transformation. We simply reset here rather than setting the ModifiedDT
-  // flag to avoid restarting the function walk in runOnFunction for each
-  // select optimized.
-  DT.reset();
-
   // Transform a sequence like this:
   //    start:
   //       %cmp = cmp uge i32 %a, %b
@@ -7769,6 +7792,9 @@ bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
   // block and its branch may be optimized away. In that case, one side of the
   // first branch will point directly to select.end, and the corresponding PHI
   // predecessor block will be the start block.
+  // The CFG is altered here and we update the DominatorTree and the LoopInfo,
+  // but we don't set a ModifiedDT flag to avoid restarting the function walk in
+  // runOnFunction for each select optimized.
 
   // Collect values that go on the true side and the values that go on the false
   // side.
@@ -7796,20 +7822,20 @@ bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
   BranchInst *TrueBranch = nullptr;
   BranchInst *FalseBranch = nullptr;
   if (TrueInstrs.size() == 0) {
-    FalseBranch = cast<BranchInst>(SplitBlockAndInsertIfElse(
-        CondFr, SplitPt, false, nullptr, nullptr, LI));
+    FalseBranch = cast<BranchInst>(
+        SplitBlockAndInsertIfElse(CondFr, SplitPt, false, nullptr, DTU, LI));
     FalseBlock = FalseBranch->getParent();
     EndBlock = cast<BasicBlock>(FalseBranch->getOperand(0));
   } else if (FalseInstrs.size() == 0) {
-    TrueBranch = cast<BranchInst>(SplitBlockAndInsertIfThen(
-        CondFr, SplitPt, false, nullptr, nullptr, LI));
+    TrueBranch = cast<BranchInst>(
+        SplitBlockAndInsertIfThen(CondFr, SplitPt, false, nullptr, DTU, LI));
     TrueBlock = TrueBranch->getParent();
     EndBlock = cast<BasicBlock>(TrueBranch->getOperand(0));
   } else {
     Instruction *ThenTerm = nullptr;
     Instruction *ElseTerm = nullptr;
     SplitBlockAndInsertIfThenElse(CondFr, SplitPt, &ThenTerm, &ElseTerm,
-                                  nullptr, nullptr, LI);
+                                  nullptr, DTU, LI);
     TrueBranch = cast<BranchInst>(ThenTerm);
     FalseBranch = cast<BranchInst>(ElseTerm);
     TrueBlock = TrueBranch->getParent();
@@ -9097,13 +9123,9 @@ bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, ModifyDT &ModifiedDT) {
         // For huge function we tend to quickly go though the inner optmization
         // opportunities in the BB. So we go back to the BB head to re-optimize
         // each instruction instead of go back to the function head.
-        if (IsHugeFunc) {
-          DT.reset();
-          getDT(*BB.getParent());
+        if (IsHugeFunc)
           break;
-        } else {
-          return true;
-        }
+        return true;
       }
     }
   } while (ModifiedDT == ModifyDT::ModifyInstDT);
@@ -9173,7 +9195,7 @@ static void DbgInserterHelper(DbgVariableRecord *DVR, BasicBlock::iterator VI) {
 // to re-order dbg.value intrinsics.
 bool CodeGenPrepare::placeDbgValues(Function &F) {
   bool MadeChange = false;
-  DominatorTree DT(F);
+  DominatorTree &DT = getDT();
 
   auto DbgProcessor = [&](auto *DbgItem, Instruction *Position) {
     SmallVector<Instruction *, 4> VIs;
@@ -9287,7 +9309,7 @@ static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
 ///
 /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
 ///
-bool CodeGenPrepare::splitBranchCondition(Function &F, ModifyDT &ModifiedDT) {
+bool CodeGenPrepare::splitBranchCondition(Function &F) {
   if (!TM->Options.EnableFastISel || TLI->isJumpExpensive())
     return false;
 
@@ -9381,6 +9403,20 @@ bool CodeGenPrepare::splitBranchCondition(Function &F, ModifyDT &ModifiedDT) {
       PN.addIncoming(Val, TmpBB);
     }
 
+    if (LI) {
+      if (Loop *L = LI->getLoopFor(&BB))
+        L->addBasicBlockToLoop(TmpBB, *LI);
+    }
+
+    if (DTU) {
+      // The edge we need to delete starts at BB and ends at whatever TBB ends
+      // up pointing to.
+      DTU->applyUpdates({{DominatorTree::Insert, &BB, TmpBB},
+                         {DominatorTree::Insert, TmpBB, TBB},
+                         {DominatorTree::Insert, TmpBB, FBB},
+                         {DominatorTree::Delete, &BB, TBB}});
+    }
+
     // Update the branch weights (from SelectionDAGBuilder::
     // FindMergedConditions).
     if (Opc == Instruction::Or) {
@@ -9457,7 +9493,6 @@ bool CodeGenPrepare::splitBranchCondition(Function &F, ModifyDT &ModifiedDT) {
       }
     }
 
-    ModifiedDT = ModifyDT::ModifyBBDT;
     MadeChange = true;
 
     LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
diff --git a/llvm/lib/Transforms/Utils/BypassSlowDivision.cpp b/llvm/lib/Transforms/Utils/BypassSlowDivision.cpp
index 66d8fea251cbd..5a6cb2e43d104 100644
--- a/llvm/lib/Transforms/Utils/BypassSlowDivision.cpp
+++ b/llvm/lib/Transforms/Utils/BypassSlowDivision.cpp
@@ -18,6 +18,8 @@
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/Analysis/DomTreeUpdater.h"
+#include "llvm/Analysis/LoopInfo.h"
 #include "llvm/Analysis/ValueTracking.h"
 #include "llvm/IR/BasicBlock.h"
 #include "llvm/IR/Constants.h"
@@ -30,6 +32,7 @@
 #include "llvm/IR/Value.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/KnownBits.h"
+#include "llvm/Transforms/Utils/BasicBlockUtils.h"
 #include "llvm/Transforms/Utils/Local.h"
 #include <cassert>
 #include <cstdint>
@@ -76,6 +79,8 @@ class FastDivInsertionTask {
   Instruction *SlowDivOrRem = nullptr;
   IntegerType *BypassType = nullptr;
   BasicBlock *MainBB = nullptr;
+  DomTreeUpdater *DTU = nullptr;
+  LoopInfo *LI = nullptr;
 
   bool isHashLikeValue(Value *V, VisitedSetTy &Visited);
   ValueRange getValueRange(Value *Op, VisitedSetTy &Visited);
@@ -99,7 +104,8 @@ class FastDivInsertionTask {
   Type *getSlowType() { return SlowDivOrRem->getType(); }
 
 public:
-  FastDivInsertionTask(Instruction *I, const BypassWidthsTy &BypassWidths);
+  FastDivInsertionTask(Instruction *I, const BypassWidthsTy &BypassWidths,
+                       DomTreeUpdater *DTU, LoopInfo *LI);
 
   Value *getReplacement(DivCacheTy &Cache);
 };
@@ -107,7 +113,9 @@ class FastDivInsertionTask {
 } // end anonymous namespace
 
 FastDivInsertionTask::FastDivInsertionTask(Instruction *I,
-                                           const BypassWidthsTy &BypassWidths) {
+                                           const BypassWidthsTy &BypassWidths,
+                                           DomTreeUpdater *DTU, LoopInfo *LI)
+    : DTU(DTU), LI(LI) {
   switch (I->getOpcode()) {
   case Instruction::UDiv:
   case Instruction::SDiv:
@@ -412,7 +420,7 @@ std::optional<QuotRemPair> FastDivInsertionTask::insertFastDivAndRem() {
     // lets us entirely avoid a long div.
 
     // Split the basic block before the div/rem.
-    BasicBlock *SuccessorBB = MainBB->splitBasicBlock(SlowDivOrRem);
+    BasicBlock *SuccessorBB = SplitBlock(MainBB, SlowDivOrRem, DTU, LI);
     // Remove the unconditional branch from MainBB to SuccessorBB.
     MainBB->back().eraseFromParent();
     QuotRemWithBB Long;
@@ -423,13 +431,23 @@ std::optional<QuotRemPair> FastDivInsertionTask::insertFastDivAndRem() {
     QuotRemPair Result = createDivRemPhiNodes(Fast, Long, SuccessorBB);
     Value *CmpV = Builder.CreateICmpUGE(Dividend, Divisor);
     Builder.CreateCondBr(CmpV, Fast.BB, SuccessorBB);
+
+    if (DTU)
+      DTU->applyUpdates({{DominatorTree::Insert, MainBB, Fast.BB},
+                         {DominatorTree::Insert, Fast.BB, SuccessorBB}});
+
+    if (LI) {
+      if (Loop *L = LI->getLoopFor(MainBB))
+        L->addBasicBlockToLoop(Fast.BB, *LI);
+    }
+
     return Result;
   } else {
     // General case. Create both slow and fast div/rem pairs and choose one of
     // them at runtime.
 
     // Split the basic block before the div/rem.
-    BasicBlock *SuccessorBB = MainBB->splitBasicBlock(SlowDivOrRem);
+    BasicBlock *SuccessorBB = SplitBlock(MainBB, SlowDivOrRem, DTU, LI);
     // Remove the unconditional branch from MainBB to SuccessorBB.
     MainBB->back().eraseFromParent();
     QuotRemWithBB Fast = createFastBB(SuccessorBB);
@@ -438,6 +456,21 @@ std::optional<QuotRemPair> FastDivInsertionTask::insertFastDivAndRem() {
     Value *CmpV = insertOperandRuntimeCheck(DividendShort ? nullptr : Dividend,
                                             DivisorShort ? nullptr : Divisor);
     Builder.CreateCondBr(CmpV, Fast.BB, Slow.BB);
+
+    if (DTU)
+      DTU->applyUpdates({{DominatorTree::Insert, MainBB, Fast.BB},
+                         {DominatorTree::Insert, MainBB, Slow.BB},
+                         {DominatorTree::Insert, Fast.BB, SuccessorBB},
+                         {DominatorTree::Insert, Slow.BB, SuccessorBB},
+                         {DominatorTree::Delete, MainBB, SuccessorBB}});
+
+    if (LI) {
+      if (Loop *L = LI->getLoopFor(MainBB)) {
+        L->addBasicBlockToLoop(Fast.BB, *LI);
+        L->addBasicBlockToLoop(Slow.BB, *LI);
+      }
+    }
+
     return Result;
   }
 }
@@ -445,7 +478,8 @@ std::optional<QuotRemPair> FastDivInsertionTask::insertFastDivAndRem() {
 /// This optimization identifies DIV/REM instructions in a BB that can be
 /// profitably bypassed and carried out with a shorter, faster divide.
 bool llvm::bypassSlowDivision(BasicBlock *BB,
-                              const BypassWidthsTy &BypassWidths) {
+                              const BypassWidthsTy &BypassWidths,
+                              DomTreeUpdater *DTU, LoopInfo *LI) {
   DivCacheTy PerBBDivCache;
 
   bool MadeChange = false;
@@ -460,7 +494,7 @@ bool llvm::bypassSlowDivision(BasicBlock *BB,
     if (I->use_empty())
       continue;
 
-    FastDivInsertionTask Task(I, BypassWidths);
+    FastDivInsertionTask Task(I, BypassWidths, DTU, LI);
     if (Value *Replacement = Task.getReplacement(PerBBDivCache)) {
       I->replaceAllUsesWith(Replacement);
       I->eraseFromParent();
diff --git a/llvm/test/Transforms/CodeGenPrepare/AMDGPU/bypass-slow-div-debug-info-inseltpoison.ll b/llvm/test/Transforms/CodeGenPrepare/AMDGPU/bypass-slow-div-debug-info-inseltpoison.ll
index 8c198a3c7d607..8a37bd34f6c98 100644
--- a/llvm/test/Transforms/CodeGenPrepare/AMDGPU/bypass-slow-div-debug-info-inseltpoison.ll
+++ b/llvm/test/Transforms/CodeGenPrepare/AMDGPU/bypass-slow-div-debug-info-inseltpoison.ll
@@ -4,22 +4,22 @@
 
 define i64 @sdiv64(i64 %a, i64 %b) {
 ; CHECK-LABEL: @sdiv64(
-; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[A:%.*]], [[B:%.*]], [[DBG6:!dbg !.*]]
-; CHECK-NEXT:    [[TMP2:%.*]] = and i64 [[TMP1]], -4294967296, [[DBG6]]
-; CHECK-NEXT:    [[TMP3:%.*]] = icmp eq i64 [[TMP2]], 0, [[DBG6]]
-; CHECK-NEXT:    br i1 [[TMP3]], label [[TMP4:%.*]], label [[TMP9:%.*]], [[DBG6]]
+; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[A:%.*]], [[B:%.*]], !dbg [[DBG6:![0-9]+]]
+; CHECK-NEXT:    [[TMP2:%.*]] = and i64 [[TMP1]], -4294967296, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP3:%.*]] = icmp eq i64 [[TMP2]], 0, !dbg [[DBG6]]
+; CHECK-NEXT:    br i1 [[TMP3]], label [[TMP4:%.*]], label [[TMP9:%.*]], !dbg [[DBG6]]
 ; CHECK:       4:
-; CHECK-NEXT:    [[TMP5:%.*]] = trunc i64 [[B]] to i32, [[DBG6]]
-; CHECK-NEXT:    [[TMP6:%.*]] = trunc i64 [[A]] to i32, [[DBG6]]
-; CHECK-NEXT:    [[TMP7:%.*]] = udiv i32 [[TMP6]], [[TMP5]], [[DBG6]]
-; CHECK-NEXT:    [[TMP8:%.*]] = zext i32 [[TMP7]] to i64, [[DBG6]]
-; CHECK-NEXT:    br label [[TMP11:%.*]], [[DBG6]]
+; CHECK-NEXT:    [[TMP5:%.*]] = trunc i64 [[B]] to i32, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP6:%.*]] = trunc i64 [[A]] to i32, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP7:%.*]] = udiv i32 [[TMP6]], [[TMP5]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP8:%.*]] = zext i32 [[TMP7]] to i64, !dbg [[DBG6]]
+; CHECK-NEXT:    br label [[DOTSPLIT:%.*]], !dbg [[DBG6]]
 ; CHECK:       9:
-; CHECK-NEXT:    [[TMP10:%.*]] = sdiv i64 [[A]], [[B]], [[DBG6]]
-; CHECK-NEXT:    br label [[TMP11]], [[DBG6]]
-; CHECK:       11:
-; CHECK-NEXT:    [[TMP12:%.*]] = phi i64 [ [[TMP8]], [[TMP4]] ], [ [[TMP10]], [[TMP9]] ], [[DBG6]]
-; CHECK-NEXT:    ret i64 [[TMP12]]
+; CHECK-NEXT:    [[TMP10:%.*]] = sdiv i64 [[A]], [[B]], !dbg [[DBG6]]
+; CHECK-NEXT:    br label [[DOTSPLIT]], !dbg [[DBG6]]
+; CHECK:       .split:
+; CHECK-NEXT:    [[TMP11:%.*]] = phi i64 [ [[TMP8]], [[TMP4]] ], [ [[TMP10]], [[TMP9]] ], !dbg [[DBG6]]
+; CHECK-NEXT:    ret i64 [[TMP11]]
 ;
   %d = sdiv i64 %a, %b, !dbg !6
   ret i64 %d
@@ -29,27 +29,27 @@ define i64 @sdiv64(i64 %a, i64 %b) {
 ; division.
 define <2 x i64> @sdivrem64(i64 %a, i64 %b) {
 ; CHECK-LABEL: @sdivrem64(
-; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[A:%.*]], [[B:%.*]], [[DBG6]]
-; CHECK-NEXT:    [[TMP2:%.*]] = and i64 [[TMP1]], -4294967296, [[DBG6]]
-; CHECK-NEXT:    [[TMP3:%.*]] = icmp eq i64 [[TMP2]], 0, [[DBG6]]
-; CHECK-NEXT:    br i1 [[TMP3]], label [[TMP4:%.*]], label [[TMP11:%.*]], [[DBG6]]
+; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[A:%.*]], [[B:%.*]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP2:%.*]] = and i64 [[TMP1]], -4294967296, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP3:%.*]] = icmp eq i64 [[TMP2]], 0, !dbg [[DBG6]]
+; CHECK-NEXT:    br i1 [[TMP3]], label [[TMP4:%.*]], label [[TMP11:%.*]], !dbg [[DBG6]]
 ; CHECK:       4:
-; CHECK-NEXT:    [[TMP5:%.*]] = trunc i64 [[B]] to i32, [[DBG6]]
-; CHECK-NEXT:    [[TMP6:%.*]] = trunc i64 [[A]] to i32, [[DBG6]]
-; CHECK-NEXT:    [[TMP7:%.*]] = udiv i32 [[TMP6]], [[TMP5]], [[DBG6]]
-; CHECK-NEXT:    [[TMP8:%.*]] = urem i32 [[TMP6]], [[TMP5]], [[DBG6]]
-; CHECK-NEXT:    [[TMP9:%.*]] = zext i32 [[TMP7]] to i64, [[DBG6]]
-; CHECK-NEXT:    [[TMP10:%.*]] = zext i32 [[TMP8]] to i64, [[DBG6]]
-; CHECK-NEXT:    br label [[TMP14:%.*]], [[DBG6]]
+; CHECK-NEXT:    [[TMP5:%.*]] = trunc i64 [[B]] to i32, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP6:%.*]] = trunc i64 [[A]] to i32, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP7:%.*]] = udiv i32 [[TMP6]], [[TMP5]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP8:%.*]] = urem i32 [[TMP6]], [[TMP5]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP9:%.*]] = zext i32 [[TMP7]] to i64, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP10:%.*]] = zext i32 [[TMP8]] to i64, !dbg [[DBG6]]
+; CHECK-NEXT:    br label [[DOTSPLIT:%.*]], !dbg [[DBG6]]
 ; CHECK:       11:
-; CHECK-NEXT:    [[TMP12:%.*]] = sdiv i64 [[A]], [[B]], [[DBG6]]
-; CHECK-NEXT:    [[TMP13:%.*]] = srem i64 [[A]], [[B]], [[DBG6]]
-; CHECK-NEXT:    br label [[TMP14]], [[DBG6]]
-; CHECK:       14:
-; CHECK-NEXT:    [[TMP15:%.*]] = phi i64 [ [[TMP9]], [[TMP4]] ], [ [[TMP12]], [[TMP11]] ], [[DBG6]]
-; CHECK-NEXT:    [[TMP16:%.*]] = phi i64 [ [[TMP10]], [[TMP4]] ], [ [[TMP13]], [[TMP11]] ], [[DBG6]]
-; CHECK-NEXT:    [[INS0:%.*]] = insertelement <2 x i64> poison, i64 [[TMP15]], i32 0
-; CHECK-NEXT:    [[INS1:%.*]] = insertelement <2 x i64> [[INS0]], i64 [[TMP16]], i32 1
+; CHECK-NEXT:    [[TMP12:%.*]] = sdiv i64 [[A]], [[B]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP13:%.*]] = srem i64 [[A]], [[B]], !dbg [[DBG6]]
+; CHECK-NEXT:    br label [[DOTSPLIT]], !dbg [[DBG6]]
+; CHECK:       .split:
+; CHECK-NEXT:    [[TMP14:%.*]] = phi i64 [ [[TMP9]], [[TMP4]] ], [ [[TMP12]], [[TMP11]] ], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP15:%.*]] = phi i64 [ [[TMP10]], [[TMP4]] ], [ [[TMP13]], [[TMP11]] ], !dbg [[DBG6]]
+; CHECK-NEXT:    [[INS0:%.*]] = insertelement <2 x i64> poison, i64 [[TMP14]], i32 0
+; CHECK-NEXT:    [[INS1:%.*]] = insertelement <2 x i64> [[INS0]], i64 [[TMP15]], i32 1
 ; CHECK-NEXT:    ret <2 x i64> [[INS1]]
 ;
   %d = sdiv i64 %a, %b, !dbg !6
diff --git a/llvm/test/Transforms/CodeGenPrepare/AMDGPU/bypass-slow-div-debug-info.ll b/llvm/test/Transforms/CodeGenPrepare/AMDGPU/bypass-slow-div-debug-info.ll
index cf2d96214a54c..0d097202fe80f 100644
--- a/llvm/test/Transforms/CodeGenPrepare/AMDGPU/bypass-slow-div-debug-info.ll
+++ b/llvm/test/Transforms/CodeGenPrepare/AMDGPU/bypass-slow-div-debug-info.ll
@@ -4,22 +4,22 @@
 
 define i64 @sdiv64(i64 %a, i64 %b) {
 ; CHECK-LABEL: @sdiv64(
-; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[A:%.*]], [[B:%.*]], !dbg !6
-; CHECK-NEXT:    [[TMP2:%.*]] = and i64 [[TMP1]], -4294967296, !dbg !6
-; CHECK-NEXT:    [[TMP3:%.*]] = icmp eq i64 [[TMP2]], 0, !dbg !6
-; CHECK-NEXT:    br i1 [[TMP3]], label [[TMP4:%.*]], label [[TMP9:%.*]], !dbg !6
+; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[A:%.*]], [[B:%.*]], !dbg [[DBG6:![0-9]+]]
+; CHECK-NEXT:    [[TMP2:%.*]] = and i64 [[TMP1]], -4294967296, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP3:%.*]] = icmp eq i64 [[TMP2]], 0, !dbg [[DBG6]]
+; CHECK-NEXT:    br i1 [[TMP3]], label [[TMP4:%.*]], label [[TMP9:%.*]], !dbg [[DBG6]]
 ; CHECK:       4:
-; CHECK-NEXT:    [[TMP5:%.*]] = trunc i64 [[B]] to i32, !dbg !6
-; CHECK-NEXT:    [[TMP6:%.*]] = trunc i64 [[A]] to i32, !dbg !6
-; CHECK-NEXT:    [[TMP7:%.*]] = udiv i32 [[TMP6]], [[TMP5]], !dbg !6
-; CHECK-NEXT:    [[TMP8:%.*]] = zext i32 [[TMP7]] to i64, !dbg !6
-; CHECK-NEXT:    br label [[TMP11:%.*]], !dbg !6
+; CHECK-NEXT:    [[TMP5:%.*]] = trunc i64 [[B]] to i32, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP6:%.*]] = trunc i64 [[A]] to i32, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP7:%.*]] = udiv i32 [[TMP6]], [[TMP5]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP8:%.*]] = zext i32 [[TMP7]] to i64, !dbg [[DBG6]]
+; CHECK-NEXT:    br label [[DOTSPLIT:%.*]], !dbg [[DBG6]]
 ; CHECK:       9:
-; CHECK-NEXT:    [[TMP10:%.*]] = sdiv i64 [[A]], [[B]], !dbg !6
-; CHECK-NEXT:    br label [[TMP11]], !dbg !6
-; CHECK:       11:
-; CHECK-NEXT:    [[TMP12:%.*]] = phi i64 [ [[TMP8]], [[TMP4]] ], [ [[TMP10]], [[TMP9]] ], !dbg !6
-; CHECK-NEXT:    ret i64 [[TMP12]]
+; CHECK-NEXT:    [[TMP10:%.*]] = sdiv i64 [[A]], [[B]], !dbg [[DBG6]]
+; CHECK-NEXT:    br label [[DOTSPLIT]], !dbg [[DBG6]]
+; CHECK:       .split:
+; CHECK-NEXT:    [[TMP11:%.*]] = phi i64 [ [[TMP8]], [[TMP4]] ], [ [[TMP10]], [[TMP9]] ], !dbg [[DBG6]]
+; CHECK-NEXT:    ret i64 [[TMP11]]
 ;
   %d = sdiv i64 %a, %b, !dbg !6
   ret i64 %d
@@ -29,27 +29,27 @@ define i64 @sdiv64(i64 %a, i64 %b) {
 ; division.
 define <2 x i64> @sdivrem64(i64 %a, i64 %b) {
 ; CHECK-LABEL: @sdivrem64(
-; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[A:%.*]], [[B:%.*]], !dbg !6
-; CHECK-NEXT:    [[TMP2:%.*]] = and i64 [[TMP1]], -4294967296, !dbg !6
-; CHECK-NEXT:    [[TMP3:%.*]] = icmp eq i64 [[TMP2]], 0, !dbg !6
-; CHECK-NEXT:    br i1 [[TMP3]], label [[TMP4:%.*]], label [[TMP11:%.*]], !dbg !6
+; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[A:%.*]], [[B:%.*]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP2:%.*]] = and i64 [[TMP1]], -4294967296, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP3:%.*]] = icmp eq i64 [[TMP2]], 0, !dbg [[DBG6]]
+; CHECK-NEXT:    br i1 [[TMP3]], label [[TMP4:%.*]], label [[TMP11:%.*]], !dbg [[DBG6]]
 ; CHECK:       4:
-; CHECK-NEXT:    [[TMP5:%.*]] = trunc i64 [[B]] to i32, !dbg !6
-; CHECK-NEXT:    [[TMP6:%.*]] = trunc i64 [[A]] to i32, !dbg !6
-; CHECK-NEXT:    [[TMP7:%.*]] = udiv i32 [[TMP6]], [[TMP5]], !dbg !6
-; CHECK-NEXT:    [[TMP8:%.*]] = urem i32 [[TMP6]], [[TMP5]], !dbg !6
-; CHECK-NEXT:    [[TMP9:%.*]] = zext i32 [[TMP7]] to i64, !dbg !6
-; CHECK-NEXT:    [[TMP10:%.*]] = zext i32 [[TMP8]] to i64, !dbg !6
-; CHECK-NEXT:    br label [[TMP14:%.*]], !dbg !6
+; CHECK-NEXT:    [[TMP5:%.*]] = trunc i64 [[B]] to i32, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP6:%.*]] = trunc i64 [[A]] to i32, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP7:%.*]] = udiv i32 [[TMP6]], [[TMP5]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP8:%.*]] = urem i32 [[TMP6]], [[TMP5]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP9:%.*]] = zext i32 [[TMP7]] to i64, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP10:%.*]] = zext i32 [[TMP8]] to i64, !dbg [[DBG6]]
+; CHECK-NEXT:    br label [[DOTSPLIT:%.*]], !dbg [[DBG6]]
 ; CHECK:       11:
-; CHECK-NEXT:    [[TMP12:%.*]] = sdiv i64 [[A]], [[B]], !dbg !6
-; CHECK-NEXT:    [[TMP13:%.*]] = srem i64 [[A]], [[B]], !dbg !6
-; CHECK-NEXT:    br label [[TMP14]], !dbg !6
-; CHECK:       14:
-; CHECK-NEXT:    [[TMP15:%.*]] = phi i64 [ [[TMP9]], [[TMP4]] ], [ [[TMP12]], [[TMP11]] ], !dbg !6
-; CHECK-NEXT:    [[TMP16:%.*]] = phi i64 [ [[TMP10]], [[TMP4]] ], [ [[TMP13]], [[TMP11]] ], !dbg !6
-; CHECK-NEXT:    [[INS0:%.*]] = insertelement <2 x i64> undef, i64 [[TMP15]], i32 0
-; CHECK-NEXT:    [[INS1:%.*]] = insertelement <2 x i64> [[INS0]], i64 [[TMP16]], i32 1
+; CHECK-NEXT:    [[TMP12:%.*]] = sdiv i64 [[A]], [[B]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP13:%.*]] = srem i64 [[A]], [[B]], !dbg [[DBG6]]
+; CHECK-NEXT:    br label [[DOTSPLIT]], !dbg [[DBG6]]
+; CHECK:       .split:
+; CHECK-NEXT:    [[TMP14:%.*]] = phi i64 [ [[TMP9]], [[TMP4]] ], [ [[TMP12]], [[TMP11]] ], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP15:%.*]] = phi i64 [ [[TMP10]], [[TMP4]] ], [ [[TMP13]], [[TMP11]] ], !dbg [[DBG6]]
+; CHECK-NEXT:    [[INS0:%.*]] = insertelement <2 x i64> undef, i64 [[TMP14]], i32 0
+; CHECK-NEXT:    [[INS1:%.*]] = insertelement <2 x i64> [[INS0]], i64 [[TMP15]], i32 1
 ; CHECK-NEXT:    ret <2 x i64> [[INS1]]
 ;
   %d = sdiv i64 %a, %b, !dbg !6

>From 7d5025110ef7fb10d6a3ee952c0750d7211e83f4 Mon Sep 17 00:00:00 2001
From: Enna1 <xumingjie.enna1 at bytedance.com>
Date: Fri, 30 Jan 2026 21:11:01 +0800
Subject: [PATCH 05/14] update

---
 .../Transforms/Utils/BypassSlowDivision.h     |  3 +-
 llvm/lib/CodeGen/CodeGenPrepare.cpp           | 63 ++++++++----------
 .../Transforms/Utils/BypassSlowDivision.cpp   | 46 ++-----------
 ...bypass-slow-div-debug-info-inseltpoison.ll | 66 +++++++++----------
 .../AMDGPU/bypass-slow-div-debug-info.ll      | 66 +++++++++----------
 5 files changed, 100 insertions(+), 144 deletions(-)

diff --git a/llvm/include/llvm/Transforms/Utils/BypassSlowDivision.h b/llvm/include/llvm/Transforms/Utils/BypassSlowDivision.h
index eceb131d8c60c..d53fb80a80808 100644
--- a/llvm/include/llvm/Transforms/Utils/BypassSlowDivision.h
+++ b/llvm/include/llvm/Transforms/Utils/BypassSlowDivision.h
@@ -69,8 +69,7 @@ template <> struct DenseMapInfo<DivRemMapKey> {
 /// This optimization may add basic blocks immediately after BB; for obvious
 /// reasons, you shouldn't pass those blocks to bypassSlowDivision.
 bool bypassSlowDivision(BasicBlock *BB,
-                        const DenseMap<unsigned int, unsigned int> &BypassWidth,
-                        DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr);
+                        const DenseMap<unsigned int, unsigned int> &BypassWidth);
 
 } // end namespace llvm
 
diff --git a/llvm/lib/CodeGen/CodeGenPrepare.cpp b/llvm/lib/CodeGen/CodeGenPrepare.cpp
index 96ab1add651bc..98fcff975dff7 100644
--- a/llvm/lib/CodeGen/CodeGenPrepare.cpp
+++ b/llvm/lib/CodeGen/CodeGenPrepare.cpp
@@ -423,10 +423,10 @@ class CodeGenPrepare {
   void removeAllAssertingVHReferences(Value *V);
   bool eliminateAssumptions(Function &F);
   bool eliminateFallThrough(Function &F);
-  bool eliminateMostlyEmptyBlocks(Function &F, ModifyDT &ModifiedDT);
+  bool eliminateMostlyEmptyBlocks(Function &F);
   BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
   bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
-  void eliminateMostlyEmptyBlock(BasicBlock *BB, ModifyDT &ModifiedDT);
+  void eliminateMostlyEmptyBlock(BasicBlock *BB);
   bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
                                      bool isPreheader);
   bool makeBitReverse(Instruction &I);
@@ -611,11 +611,6 @@ bool CodeGenPrepare::_run(Function &F) {
 
   DomTreeUpdater DTUpdater(DT, DomTreeUpdater::UpdateStrategy::Lazy);
   DTU = &DTUpdater;
-  auto resetDTAndLI = [&]() {
-    DTU->recalculate(F);
-    LI->releaseMemory();
-    LI->analyze(DTU->getDomTree());
-  };
 
   /// This optimization identifies DIV instructions that can be
   /// profitably bypassed and carried out with a shorter, faster divide.
@@ -628,7 +623,7 @@ bool CodeGenPrepare::_run(Function &F) {
       // optimization to those blocks.
       BasicBlock *Next = BB->getNextNode();
       if (!llvm::shouldOptimizeForSize(BB, PSI, BFI.get()))
-        EverMadeChange |= bypassSlowDivision(BB, BypassWidths, DTU, LI);
+        EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
       BB = Next;
     }
   }
@@ -640,32 +635,22 @@ bool CodeGenPrepare::_run(Function &F) {
 
   // Eliminate blocks that contain only PHI nodes and an
   // unconditional branch.
-  ModifyDT ModifiedDT = ModifyDT::NotModifyDT;
-  EverMadeChange |= eliminateMostlyEmptyBlocks(F, ModifiedDT);
-  if (ModifiedDT != ModifyDT::NotModifyDT) {
-    // Rebuild the dom tree if the transformation above did change the CFG, but
-    // did not update the DT.
-    resetDTAndLI();
-  }
+  EverMadeChange |= eliminateMostlyEmptyBlocks(F);
 
   if (!DisableBranchOpts)
     EverMadeChange |= splitBranchCondition(F);
 
   // Split some critical edges where one of the sources is an indirect branch,
   // to help generate sane code for PHIs involving such edges.
-  if (SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/true)) {
-    EverMadeChange = true;
-    resetDTAndLI();
-  }
-
-#ifndef NDEBUG
-  if (VerifyDT)
-    assert(getDT().verify(DominatorTree::VerificationLevel::Fast) &&
-           "Incorrect DominatorTree updates in CGP");
+  EverMadeChange |=
+      SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/true);
 
-  if (VerifyLoopInfo)
-    LI->verify(getDT());
-#endif
+  // Transformations above may invalidate dominator tree and/or loop info.
+  if (EverMadeChange) {
+    DTU->recalculate(F);
+    LI->releaseMemory();
+    LI->analyze(DTU->getDomTree());
+  }
 
   // If we are optimzing huge function, we need to consider the build time.
   // Because the basic algorithm's complex is near O(N!).
@@ -944,8 +929,7 @@ BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
 /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
 /// edges in ways that are non-optimal for isel. Start by eliminating these
 /// blocks so we can split them the way we want them.
-bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F,
-                                                ModifyDT &ModifiedDT) {
+bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
   SmallPtrSet<BasicBlock *, 16> Preheaders;
   SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
   while (!LoopList.empty()) {
@@ -976,7 +960,7 @@ bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F,
         !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
       continue;
 
-    eliminateMostlyEmptyBlock(BB, ModifiedDT);
+    eliminateMostlyEmptyBlock(BB);
     MadeChange = true;
   }
   return MadeChange;
@@ -1153,8 +1137,7 @@ static void replaceAllUsesWith(Value *Old, Value *New,
 /// Eliminate a basic block that has only phi's and an unconditional branch in
 /// it.
 /// Indicate that the DT was modified only if the DT wasn't updated.
-void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB,
-                                               ModifyDT &ModifiedDT) {
+void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
   BasicBlock *DestBB = BI->getSuccessor(0);
 
@@ -1168,7 +1151,7 @@ void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB,
       assert(SinglePred == BB &&
              "Single predecessor not the same as predecessor");
       // Merge DestBB into SinglePred/BB and delete it.
-      MergeBlockIntoPredecessor(DestBB, DTU, LI);
+      MergeBlockIntoPredecessor(DestBB);
       // Note: BB(=SinglePred) will not be deleted on this path.
       // DestBB(=its single successor) is the one that was deleted.
       LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n");
@@ -1221,7 +1204,6 @@ void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB,
   BB->eraseFromParent();
   ++NumBlocksElim;
 
-  ModifiedDT = ModifyDT::ModifyBBDT;
   LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
 }
 
@@ -6492,9 +6474,10 @@ bool CodeGenPrepare::optimizeMulWithOverflow(Instruction *I, bool IsSigned,
   unsigned VTHalfBitWidth = Ty->getScalarSizeInBits() / 2;
   Type *LegalTy = Ty->getWithNewBitWidth(VTHalfBitWidth);
 
+  SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
+
   // New BBs:
-  BasicBlock *OverflowEntryBB =
-      I->getParent()->splitBasicBlock(I, "", /*Before*/ true);
+  BasicBlock *OverflowEntryBB = SplitBlock(I->getParent(), I, DTU, LI, nullptr, "", /*Before*/ true);
   OverflowEntryBB->takeName(I->getParent());
   // Keep the 'br' instruction that is generated as a result of the split to be
   // erased/replaced later.
@@ -6537,6 +6520,8 @@ bool CodeGenPrepare::optimizeMulWithOverflow(Instruction *I, bool IsSigned,
     IsAnyBitTrue = Builder.CreateOr(CmpLHS, CmpRHS, "or.lhs.rhs");
   }
   Builder.CreateCondBr(IsAnyBitTrue, OverflowBB, NoOverflowBB);
+  DTUpdates.push_back({DominatorTree::Insert, OverflowEntryBB, OverflowBB});
+  DTUpdates.push_back({DominatorTree::Insert, OverflowEntryBB, NoOverflowBB});
 
   // BB overflow.no:
   Builder.SetInsertPoint(NoOverflowBB);
@@ -6561,6 +6546,9 @@ bool CodeGenPrepare::optimizeMulWithOverflow(Instruction *I, bool IsSigned,
   // No we don't need the old terminator in overflow.entry BB, erase it:
   OldTerminator->eraseFromParent();
 
+  DTUpdates.push_back({DominatorTree::Insert, NoOverflowBB, OverflowResBB});
+  DTUpdates.push_back({DominatorTree::Delete, OverflowEntryBB, OverflowResBB});
+
   // BB overflow.res:
   Builder.SetInsertPoint(OverflowResBB, OverflowResBB->getFirstInsertionPt());
   // Create PHI nodes to merge results from no.overflow BB and overflow BB to
@@ -6593,11 +6581,14 @@ bool CodeGenPrepare::optimizeMulWithOverflow(Instruction *I, bool IsSigned,
   Value *MulOverflow = Builder.CreateExtractValue(I, {0}, "mul.overflow");
   Value *OverflowFlag = Builder.CreateExtractValue(I, {1}, "overflow.flag");
   Builder.CreateBr(OverflowResBB);
+  DTUpdates.push_back({DominatorTree::Insert, OverflowBB, OverflowResBB});
 
   // Add The Extracted values to the PHINodes in the overflow.res BB.
   OverflowResPHI->addIncoming(MulOverflow, OverflowBB);
   OverflowFlagPHI->addIncoming(OverflowFlag, OverflowBB);
 
+  DTU->applyUpdates(DTUpdates);
+
   ModifiedDT = ModifyDT::ModifyBBDT;
   return true;
 }
diff --git a/llvm/lib/Transforms/Utils/BypassSlowDivision.cpp b/llvm/lib/Transforms/Utils/BypassSlowDivision.cpp
index 5a6cb2e43d104..66d8fea251cbd 100644
--- a/llvm/lib/Transforms/Utils/BypassSlowDivision.cpp
+++ b/llvm/lib/Transforms/Utils/BypassSlowDivision.cpp
@@ -18,8 +18,6 @@
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallPtrSet.h"
-#include "llvm/Analysis/DomTreeUpdater.h"
-#include "llvm/Analysis/LoopInfo.h"
 #include "llvm/Analysis/ValueTracking.h"
 #include "llvm/IR/BasicBlock.h"
 #include "llvm/IR/Constants.h"
@@ -32,7 +30,6 @@
 #include "llvm/IR/Value.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/KnownBits.h"
-#include "llvm/Transforms/Utils/BasicBlockUtils.h"
 #include "llvm/Transforms/Utils/Local.h"
 #include <cassert>
 #include <cstdint>
@@ -79,8 +76,6 @@ class FastDivInsertionTask {
   Instruction *SlowDivOrRem = nullptr;
   IntegerType *BypassType = nullptr;
   BasicBlock *MainBB = nullptr;
-  DomTreeUpdater *DTU = nullptr;
-  LoopInfo *LI = nullptr;
 
   bool isHashLikeValue(Value *V, VisitedSetTy &Visited);
   ValueRange getValueRange(Value *Op, VisitedSetTy &Visited);
@@ -104,8 +99,7 @@ class FastDivInsertionTask {
   Type *getSlowType() { return SlowDivOrRem->getType(); }
 
 public:
-  FastDivInsertionTask(Instruction *I, const BypassWidthsTy &BypassWidths,
-                       DomTreeUpdater *DTU, LoopInfo *LI);
+  FastDivInsertionTask(Instruction *I, const BypassWidthsTy &BypassWidths);
 
   Value *getReplacement(DivCacheTy &Cache);
 };
@@ -113,9 +107,7 @@ class FastDivInsertionTask {
 } // end anonymous namespace
 
 FastDivInsertionTask::FastDivInsertionTask(Instruction *I,
-                                           const BypassWidthsTy &BypassWidths,
-                                           DomTreeUpdater *DTU, LoopInfo *LI)
-    : DTU(DTU), LI(LI) {
+                                           const BypassWidthsTy &BypassWidths) {
   switch (I->getOpcode()) {
   case Instruction::UDiv:
   case Instruction::SDiv:
@@ -420,7 +412,7 @@ std::optional<QuotRemPair> FastDivInsertionTask::insertFastDivAndRem() {
     // lets us entirely avoid a long div.
 
     // Split the basic block before the div/rem.
-    BasicBlock *SuccessorBB = SplitBlock(MainBB, SlowDivOrRem, DTU, LI);
+    BasicBlock *SuccessorBB = MainBB->splitBasicBlock(SlowDivOrRem);
     // Remove the unconditional branch from MainBB to SuccessorBB.
     MainBB->back().eraseFromParent();
     QuotRemWithBB Long;
@@ -431,23 +423,13 @@ std::optional<QuotRemPair> FastDivInsertionTask::insertFastDivAndRem() {
     QuotRemPair Result = createDivRemPhiNodes(Fast, Long, SuccessorBB);
     Value *CmpV = Builder.CreateICmpUGE(Dividend, Divisor);
     Builder.CreateCondBr(CmpV, Fast.BB, SuccessorBB);
-
-    if (DTU)
-      DTU->applyUpdates({{DominatorTree::Insert, MainBB, Fast.BB},
-                         {DominatorTree::Insert, Fast.BB, SuccessorBB}});
-
-    if (LI) {
-      if (Loop *L = LI->getLoopFor(MainBB))
-        L->addBasicBlockToLoop(Fast.BB, *LI);
-    }
-
     return Result;
   } else {
     // General case. Create both slow and fast div/rem pairs and choose one of
     // them at runtime.
 
     // Split the basic block before the div/rem.
-    BasicBlock *SuccessorBB = SplitBlock(MainBB, SlowDivOrRem, DTU, LI);
+    BasicBlock *SuccessorBB = MainBB->splitBasicBlock(SlowDivOrRem);
     // Remove the unconditional branch from MainBB to SuccessorBB.
     MainBB->back().eraseFromParent();
     QuotRemWithBB Fast = createFastBB(SuccessorBB);
@@ -456,21 +438,6 @@ std::optional<QuotRemPair> FastDivInsertionTask::insertFastDivAndRem() {
     Value *CmpV = insertOperandRuntimeCheck(DividendShort ? nullptr : Dividend,
                                             DivisorShort ? nullptr : Divisor);
     Builder.CreateCondBr(CmpV, Fast.BB, Slow.BB);
-
-    if (DTU)
-      DTU->applyUpdates({{DominatorTree::Insert, MainBB, Fast.BB},
-                         {DominatorTree::Insert, MainBB, Slow.BB},
-                         {DominatorTree::Insert, Fast.BB, SuccessorBB},
-                         {DominatorTree::Insert, Slow.BB, SuccessorBB},
-                         {DominatorTree::Delete, MainBB, SuccessorBB}});
-
-    if (LI) {
-      if (Loop *L = LI->getLoopFor(MainBB)) {
-        L->addBasicBlockToLoop(Fast.BB, *LI);
-        L->addBasicBlockToLoop(Slow.BB, *LI);
-      }
-    }
-
     return Result;
   }
 }
@@ -478,8 +445,7 @@ std::optional<QuotRemPair> FastDivInsertionTask::insertFastDivAndRem() {
 /// This optimization identifies DIV/REM instructions in a BB that can be
 /// profitably bypassed and carried out with a shorter, faster divide.
 bool llvm::bypassSlowDivision(BasicBlock *BB,
-                              const BypassWidthsTy &BypassWidths,
-                              DomTreeUpdater *DTU, LoopInfo *LI) {
+                              const BypassWidthsTy &BypassWidths) {
   DivCacheTy PerBBDivCache;
 
   bool MadeChange = false;
@@ -494,7 +460,7 @@ bool llvm::bypassSlowDivision(BasicBlock *BB,
     if (I->use_empty())
       continue;
 
-    FastDivInsertionTask Task(I, BypassWidths, DTU, LI);
+    FastDivInsertionTask Task(I, BypassWidths);
     if (Value *Replacement = Task.getReplacement(PerBBDivCache)) {
       I->replaceAllUsesWith(Replacement);
       I->eraseFromParent();
diff --git a/llvm/test/Transforms/CodeGenPrepare/AMDGPU/bypass-slow-div-debug-info-inseltpoison.ll b/llvm/test/Transforms/CodeGenPrepare/AMDGPU/bypass-slow-div-debug-info-inseltpoison.ll
index 8a37bd34f6c98..8c198a3c7d607 100644
--- a/llvm/test/Transforms/CodeGenPrepare/AMDGPU/bypass-slow-div-debug-info-inseltpoison.ll
+++ b/llvm/test/Transforms/CodeGenPrepare/AMDGPU/bypass-slow-div-debug-info-inseltpoison.ll
@@ -4,22 +4,22 @@
 
 define i64 @sdiv64(i64 %a, i64 %b) {
 ; CHECK-LABEL: @sdiv64(
-; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[A:%.*]], [[B:%.*]], !dbg [[DBG6:![0-9]+]]
-; CHECK-NEXT:    [[TMP2:%.*]] = and i64 [[TMP1]], -4294967296, !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP3:%.*]] = icmp eq i64 [[TMP2]], 0, !dbg [[DBG6]]
-; CHECK-NEXT:    br i1 [[TMP3]], label [[TMP4:%.*]], label [[TMP9:%.*]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[A:%.*]], [[B:%.*]], [[DBG6:!dbg !.*]]
+; CHECK-NEXT:    [[TMP2:%.*]] = and i64 [[TMP1]], -4294967296, [[DBG6]]
+; CHECK-NEXT:    [[TMP3:%.*]] = icmp eq i64 [[TMP2]], 0, [[DBG6]]
+; CHECK-NEXT:    br i1 [[TMP3]], label [[TMP4:%.*]], label [[TMP9:%.*]], [[DBG6]]
 ; CHECK:       4:
-; CHECK-NEXT:    [[TMP5:%.*]] = trunc i64 [[B]] to i32, !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP6:%.*]] = trunc i64 [[A]] to i32, !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP7:%.*]] = udiv i32 [[TMP6]], [[TMP5]], !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP8:%.*]] = zext i32 [[TMP7]] to i64, !dbg [[DBG6]]
-; CHECK-NEXT:    br label [[DOTSPLIT:%.*]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP5:%.*]] = trunc i64 [[B]] to i32, [[DBG6]]
+; CHECK-NEXT:    [[TMP6:%.*]] = trunc i64 [[A]] to i32, [[DBG6]]
+; CHECK-NEXT:    [[TMP7:%.*]] = udiv i32 [[TMP6]], [[TMP5]], [[DBG6]]
+; CHECK-NEXT:    [[TMP8:%.*]] = zext i32 [[TMP7]] to i64, [[DBG6]]
+; CHECK-NEXT:    br label [[TMP11:%.*]], [[DBG6]]
 ; CHECK:       9:
-; CHECK-NEXT:    [[TMP10:%.*]] = sdiv i64 [[A]], [[B]], !dbg [[DBG6]]
-; CHECK-NEXT:    br label [[DOTSPLIT]], !dbg [[DBG6]]
-; CHECK:       .split:
-; CHECK-NEXT:    [[TMP11:%.*]] = phi i64 [ [[TMP8]], [[TMP4]] ], [ [[TMP10]], [[TMP9]] ], !dbg [[DBG6]]
-; CHECK-NEXT:    ret i64 [[TMP11]]
+; CHECK-NEXT:    [[TMP10:%.*]] = sdiv i64 [[A]], [[B]], [[DBG6]]
+; CHECK-NEXT:    br label [[TMP11]], [[DBG6]]
+; CHECK:       11:
+; CHECK-NEXT:    [[TMP12:%.*]] = phi i64 [ [[TMP8]], [[TMP4]] ], [ [[TMP10]], [[TMP9]] ], [[DBG6]]
+; CHECK-NEXT:    ret i64 [[TMP12]]
 ;
   %d = sdiv i64 %a, %b, !dbg !6
   ret i64 %d
@@ -29,27 +29,27 @@ define i64 @sdiv64(i64 %a, i64 %b) {
 ; division.
 define <2 x i64> @sdivrem64(i64 %a, i64 %b) {
 ; CHECK-LABEL: @sdivrem64(
-; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[A:%.*]], [[B:%.*]], !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP2:%.*]] = and i64 [[TMP1]], -4294967296, !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP3:%.*]] = icmp eq i64 [[TMP2]], 0, !dbg [[DBG6]]
-; CHECK-NEXT:    br i1 [[TMP3]], label [[TMP4:%.*]], label [[TMP11:%.*]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[A:%.*]], [[B:%.*]], [[DBG6]]
+; CHECK-NEXT:    [[TMP2:%.*]] = and i64 [[TMP1]], -4294967296, [[DBG6]]
+; CHECK-NEXT:    [[TMP3:%.*]] = icmp eq i64 [[TMP2]], 0, [[DBG6]]
+; CHECK-NEXT:    br i1 [[TMP3]], label [[TMP4:%.*]], label [[TMP11:%.*]], [[DBG6]]
 ; CHECK:       4:
-; CHECK-NEXT:    [[TMP5:%.*]] = trunc i64 [[B]] to i32, !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP6:%.*]] = trunc i64 [[A]] to i32, !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP7:%.*]] = udiv i32 [[TMP6]], [[TMP5]], !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP8:%.*]] = urem i32 [[TMP6]], [[TMP5]], !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP9:%.*]] = zext i32 [[TMP7]] to i64, !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP10:%.*]] = zext i32 [[TMP8]] to i64, !dbg [[DBG6]]
-; CHECK-NEXT:    br label [[DOTSPLIT:%.*]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP5:%.*]] = trunc i64 [[B]] to i32, [[DBG6]]
+; CHECK-NEXT:    [[TMP6:%.*]] = trunc i64 [[A]] to i32, [[DBG6]]
+; CHECK-NEXT:    [[TMP7:%.*]] = udiv i32 [[TMP6]], [[TMP5]], [[DBG6]]
+; CHECK-NEXT:    [[TMP8:%.*]] = urem i32 [[TMP6]], [[TMP5]], [[DBG6]]
+; CHECK-NEXT:    [[TMP9:%.*]] = zext i32 [[TMP7]] to i64, [[DBG6]]
+; CHECK-NEXT:    [[TMP10:%.*]] = zext i32 [[TMP8]] to i64, [[DBG6]]
+; CHECK-NEXT:    br label [[TMP14:%.*]], [[DBG6]]
 ; CHECK:       11:
-; CHECK-NEXT:    [[TMP12:%.*]] = sdiv i64 [[A]], [[B]], !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP13:%.*]] = srem i64 [[A]], [[B]], !dbg [[DBG6]]
-; CHECK-NEXT:    br label [[DOTSPLIT]], !dbg [[DBG6]]
-; CHECK:       .split:
-; CHECK-NEXT:    [[TMP14:%.*]] = phi i64 [ [[TMP9]], [[TMP4]] ], [ [[TMP12]], [[TMP11]] ], !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP15:%.*]] = phi i64 [ [[TMP10]], [[TMP4]] ], [ [[TMP13]], [[TMP11]] ], !dbg [[DBG6]]
-; CHECK-NEXT:    [[INS0:%.*]] = insertelement <2 x i64> poison, i64 [[TMP14]], i32 0
-; CHECK-NEXT:    [[INS1:%.*]] = insertelement <2 x i64> [[INS0]], i64 [[TMP15]], i32 1
+; CHECK-NEXT:    [[TMP12:%.*]] = sdiv i64 [[A]], [[B]], [[DBG6]]
+; CHECK-NEXT:    [[TMP13:%.*]] = srem i64 [[A]], [[B]], [[DBG6]]
+; CHECK-NEXT:    br label [[TMP14]], [[DBG6]]
+; CHECK:       14:
+; CHECK-NEXT:    [[TMP15:%.*]] = phi i64 [ [[TMP9]], [[TMP4]] ], [ [[TMP12]], [[TMP11]] ], [[DBG6]]
+; CHECK-NEXT:    [[TMP16:%.*]] = phi i64 [ [[TMP10]], [[TMP4]] ], [ [[TMP13]], [[TMP11]] ], [[DBG6]]
+; CHECK-NEXT:    [[INS0:%.*]] = insertelement <2 x i64> poison, i64 [[TMP15]], i32 0
+; CHECK-NEXT:    [[INS1:%.*]] = insertelement <2 x i64> [[INS0]], i64 [[TMP16]], i32 1
 ; CHECK-NEXT:    ret <2 x i64> [[INS1]]
 ;
   %d = sdiv i64 %a, %b, !dbg !6
diff --git a/llvm/test/Transforms/CodeGenPrepare/AMDGPU/bypass-slow-div-debug-info.ll b/llvm/test/Transforms/CodeGenPrepare/AMDGPU/bypass-slow-div-debug-info.ll
index 0d097202fe80f..cf2d96214a54c 100644
--- a/llvm/test/Transforms/CodeGenPrepare/AMDGPU/bypass-slow-div-debug-info.ll
+++ b/llvm/test/Transforms/CodeGenPrepare/AMDGPU/bypass-slow-div-debug-info.ll
@@ -4,22 +4,22 @@
 
 define i64 @sdiv64(i64 %a, i64 %b) {
 ; CHECK-LABEL: @sdiv64(
-; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[A:%.*]], [[B:%.*]], !dbg [[DBG6:![0-9]+]]
-; CHECK-NEXT:    [[TMP2:%.*]] = and i64 [[TMP1]], -4294967296, !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP3:%.*]] = icmp eq i64 [[TMP2]], 0, !dbg [[DBG6]]
-; CHECK-NEXT:    br i1 [[TMP3]], label [[TMP4:%.*]], label [[TMP9:%.*]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[A:%.*]], [[B:%.*]], !dbg !6
+; CHECK-NEXT:    [[TMP2:%.*]] = and i64 [[TMP1]], -4294967296, !dbg !6
+; CHECK-NEXT:    [[TMP3:%.*]] = icmp eq i64 [[TMP2]], 0, !dbg !6
+; CHECK-NEXT:    br i1 [[TMP3]], label [[TMP4:%.*]], label [[TMP9:%.*]], !dbg !6
 ; CHECK:       4:
-; CHECK-NEXT:    [[TMP5:%.*]] = trunc i64 [[B]] to i32, !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP6:%.*]] = trunc i64 [[A]] to i32, !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP7:%.*]] = udiv i32 [[TMP6]], [[TMP5]], !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP8:%.*]] = zext i32 [[TMP7]] to i64, !dbg [[DBG6]]
-; CHECK-NEXT:    br label [[DOTSPLIT:%.*]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP5:%.*]] = trunc i64 [[B]] to i32, !dbg !6
+; CHECK-NEXT:    [[TMP6:%.*]] = trunc i64 [[A]] to i32, !dbg !6
+; CHECK-NEXT:    [[TMP7:%.*]] = udiv i32 [[TMP6]], [[TMP5]], !dbg !6
+; CHECK-NEXT:    [[TMP8:%.*]] = zext i32 [[TMP7]] to i64, !dbg !6
+; CHECK-NEXT:    br label [[TMP11:%.*]], !dbg !6
 ; CHECK:       9:
-; CHECK-NEXT:    [[TMP10:%.*]] = sdiv i64 [[A]], [[B]], !dbg [[DBG6]]
-; CHECK-NEXT:    br label [[DOTSPLIT]], !dbg [[DBG6]]
-; CHECK:       .split:
-; CHECK-NEXT:    [[TMP11:%.*]] = phi i64 [ [[TMP8]], [[TMP4]] ], [ [[TMP10]], [[TMP9]] ], !dbg [[DBG6]]
-; CHECK-NEXT:    ret i64 [[TMP11]]
+; CHECK-NEXT:    [[TMP10:%.*]] = sdiv i64 [[A]], [[B]], !dbg !6
+; CHECK-NEXT:    br label [[TMP11]], !dbg !6
+; CHECK:       11:
+; CHECK-NEXT:    [[TMP12:%.*]] = phi i64 [ [[TMP8]], [[TMP4]] ], [ [[TMP10]], [[TMP9]] ], !dbg !6
+; CHECK-NEXT:    ret i64 [[TMP12]]
 ;
   %d = sdiv i64 %a, %b, !dbg !6
   ret i64 %d
@@ -29,27 +29,27 @@ define i64 @sdiv64(i64 %a, i64 %b) {
 ; division.
 define <2 x i64> @sdivrem64(i64 %a, i64 %b) {
 ; CHECK-LABEL: @sdivrem64(
-; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[A:%.*]], [[B:%.*]], !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP2:%.*]] = and i64 [[TMP1]], -4294967296, !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP3:%.*]] = icmp eq i64 [[TMP2]], 0, !dbg [[DBG6]]
-; CHECK-NEXT:    br i1 [[TMP3]], label [[TMP4:%.*]], label [[TMP11:%.*]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[A:%.*]], [[B:%.*]], !dbg !6
+; CHECK-NEXT:    [[TMP2:%.*]] = and i64 [[TMP1]], -4294967296, !dbg !6
+; CHECK-NEXT:    [[TMP3:%.*]] = icmp eq i64 [[TMP2]], 0, !dbg !6
+; CHECK-NEXT:    br i1 [[TMP3]], label [[TMP4:%.*]], label [[TMP11:%.*]], !dbg !6
 ; CHECK:       4:
-; CHECK-NEXT:    [[TMP5:%.*]] = trunc i64 [[B]] to i32, !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP6:%.*]] = trunc i64 [[A]] to i32, !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP7:%.*]] = udiv i32 [[TMP6]], [[TMP5]], !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP8:%.*]] = urem i32 [[TMP6]], [[TMP5]], !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP9:%.*]] = zext i32 [[TMP7]] to i64, !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP10:%.*]] = zext i32 [[TMP8]] to i64, !dbg [[DBG6]]
-; CHECK-NEXT:    br label [[DOTSPLIT:%.*]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP5:%.*]] = trunc i64 [[B]] to i32, !dbg !6
+; CHECK-NEXT:    [[TMP6:%.*]] = trunc i64 [[A]] to i32, !dbg !6
+; CHECK-NEXT:    [[TMP7:%.*]] = udiv i32 [[TMP6]], [[TMP5]], !dbg !6
+; CHECK-NEXT:    [[TMP8:%.*]] = urem i32 [[TMP6]], [[TMP5]], !dbg !6
+; CHECK-NEXT:    [[TMP9:%.*]] = zext i32 [[TMP7]] to i64, !dbg !6
+; CHECK-NEXT:    [[TMP10:%.*]] = zext i32 [[TMP8]] to i64, !dbg !6
+; CHECK-NEXT:    br label [[TMP14:%.*]], !dbg !6
 ; CHECK:       11:
-; CHECK-NEXT:    [[TMP12:%.*]] = sdiv i64 [[A]], [[B]], !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP13:%.*]] = srem i64 [[A]], [[B]], !dbg [[DBG6]]
-; CHECK-NEXT:    br label [[DOTSPLIT]], !dbg [[DBG6]]
-; CHECK:       .split:
-; CHECK-NEXT:    [[TMP14:%.*]] = phi i64 [ [[TMP9]], [[TMP4]] ], [ [[TMP12]], [[TMP11]] ], !dbg [[DBG6]]
-; CHECK-NEXT:    [[TMP15:%.*]] = phi i64 [ [[TMP10]], [[TMP4]] ], [ [[TMP13]], [[TMP11]] ], !dbg [[DBG6]]
-; CHECK-NEXT:    [[INS0:%.*]] = insertelement <2 x i64> undef, i64 [[TMP14]], i32 0
-; CHECK-NEXT:    [[INS1:%.*]] = insertelement <2 x i64> [[INS0]], i64 [[TMP15]], i32 1
+; CHECK-NEXT:    [[TMP12:%.*]] = sdiv i64 [[A]], [[B]], !dbg !6
+; CHECK-NEXT:    [[TMP13:%.*]] = srem i64 [[A]], [[B]], !dbg !6
+; CHECK-NEXT:    br label [[TMP14]], !dbg !6
+; CHECK:       14:
+; CHECK-NEXT:    [[TMP15:%.*]] = phi i64 [ [[TMP9]], [[TMP4]] ], [ [[TMP12]], [[TMP11]] ], !dbg !6
+; CHECK-NEXT:    [[TMP16:%.*]] = phi i64 [ [[TMP10]], [[TMP4]] ], [ [[TMP13]], [[TMP11]] ], !dbg !6
+; CHECK-NEXT:    [[INS0:%.*]] = insertelement <2 x i64> undef, i64 [[TMP15]], i32 0
+; CHECK-NEXT:    [[INS1:%.*]] = insertelement <2 x i64> [[INS0]], i64 [[TMP16]], i32 1
 ; CHECK-NEXT:    ret <2 x i64> [[INS1]]
 ;
   %d = sdiv i64 %a, %b, !dbg !6

>From 308068ea447ecf4e4a7d9f31f1730da72e6bb03c Mon Sep 17 00:00:00 2001
From: Enna1 <xumingjie.enna1 at bytedance.com>
Date: Sat, 31 Jan 2026 20:58:45 +0800
Subject: [PATCH 06/14] clang-format

---
 llvm/include/llvm/Transforms/Utils/BypassSlowDivision.h | 4 ++--
 llvm/lib/CodeGen/CodeGenPrepare.cpp                     | 6 ++++--
 2 files changed, 6 insertions(+), 4 deletions(-)

diff --git a/llvm/include/llvm/Transforms/Utils/BypassSlowDivision.h b/llvm/include/llvm/Transforms/Utils/BypassSlowDivision.h
index d53fb80a80808..66e53c650f109 100644
--- a/llvm/include/llvm/Transforms/Utils/BypassSlowDivision.h
+++ b/llvm/include/llvm/Transforms/Utils/BypassSlowDivision.h
@@ -68,8 +68,8 @@ template <> struct DenseMapInfo<DivRemMapKey> {
 ///
 /// This optimization may add basic blocks immediately after BB; for obvious
 /// reasons, you shouldn't pass those blocks to bypassSlowDivision.
-bool bypassSlowDivision(BasicBlock *BB,
-                        const DenseMap<unsigned int, unsigned int> &BypassWidth);
+bool bypassSlowDivision(
+    BasicBlock *BB, const DenseMap<unsigned int, unsigned int> &BypassWidth);
 
 } // end namespace llvm
 
diff --git a/llvm/lib/CodeGen/CodeGenPrepare.cpp b/llvm/lib/CodeGen/CodeGenPrepare.cpp
index 98fcff975dff7..9a6051aee0f8a 100644
--- a/llvm/lib/CodeGen/CodeGenPrepare.cpp
+++ b/llvm/lib/CodeGen/CodeGenPrepare.cpp
@@ -661,7 +661,8 @@ bool CodeGenPrepare::_run(Function &F) {
   while (MadeChange) {
     MadeChange = false;
 
-    // Flush pending updates as we may delete BasicBlocks in previous iteration of the current loop.
+    // Flush pending updates as we may delete BasicBlocks in previous iteration
+    // of the current loop.
     DTU->flush();
 
     for (BasicBlock &BB : llvm::make_early_inc_range(F)) {
@@ -6477,7 +6478,8 @@ bool CodeGenPrepare::optimizeMulWithOverflow(Instruction *I, bool IsSigned,
   SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
 
   // New BBs:
-  BasicBlock *OverflowEntryBB = SplitBlock(I->getParent(), I, DTU, LI, nullptr, "", /*Before*/ true);
+  BasicBlock *OverflowEntryBB =
+      SplitBlock(I->getParent(), I, DTU, LI, nullptr, "", /*Before*/ true);
   OverflowEntryBB->takeName(I->getParent());
   // Keep the 'br' instruction that is generated as a result of the split to be
   // erased/replaced later.

>From 84924d7d6a91f1da8fb19abf1ee6aca6bfa3d133 Mon Sep 17 00:00:00 2001
From: Enna1 <xumingjie.enna1 at bytedance.com>
Date: Sun, 1 Feb 2026 12:55:40 +0800
Subject: [PATCH 07/14] clean up

---
 llvm/include/llvm/Transforms/Utils/BypassSlowDivision.h | 2 --
 1 file changed, 2 deletions(-)

diff --git a/llvm/include/llvm/Transforms/Utils/BypassSlowDivision.h b/llvm/include/llvm/Transforms/Utils/BypassSlowDivision.h
index 66e53c650f109..bd98c902d1ab4 100644
--- a/llvm/include/llvm/Transforms/Utils/BypassSlowDivision.h
+++ b/llvm/include/llvm/Transforms/Utils/BypassSlowDivision.h
@@ -25,8 +25,6 @@
 namespace llvm {
 
 class BasicBlock;
-class DomTreeUpdater;
-class LoopInfo;
 class Value;
 
 struct DivRemMapKey {

>From b780ff59a910fdea5247ff69954460283fd9091d Mon Sep 17 00:00:00 2001
From: Enna1 <xumingjie.enna1 at bytedance.com>
Date: Tue, 3 Feb 2026 09:40:42 +0800
Subject: [PATCH 08/14] update

---
 llvm/lib/CodeGen/CodeGenPrepare.cpp | 14 +++++---------
 1 file changed, 5 insertions(+), 9 deletions(-)

diff --git a/llvm/lib/CodeGen/CodeGenPrepare.cpp b/llvm/lib/CodeGen/CodeGenPrepare.cpp
index f58860866e437..038752ccb73c3 100644
--- a/llvm/lib/CodeGen/CodeGenPrepare.cpp
+++ b/llvm/lib/CodeGen/CodeGenPrepare.cpp
@@ -6475,8 +6475,6 @@ bool CodeGenPrepare::optimizeMulWithOverflow(Instruction *I, bool IsSigned,
   unsigned VTHalfBitWidth = Ty->getScalarSizeInBits() / 2;
   Type *LegalTy = Ty->getWithNewBitWidth(VTHalfBitWidth);
 
-  SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
-
   // New BBs:
   BasicBlock *OverflowEntryBB =
       splitBlockBefore(I->getParent(), I, DTU, LI, nullptr, "");
@@ -6522,8 +6520,6 @@ bool CodeGenPrepare::optimizeMulWithOverflow(Instruction *I, bool IsSigned,
     IsAnyBitTrue = Builder.CreateOr(CmpLHS, CmpRHS, "or.lhs.rhs");
   }
   Builder.CreateCondBr(IsAnyBitTrue, OverflowBB, NoOverflowBB);
-  DTUpdates.push_back({DominatorTree::Insert, OverflowEntryBB, OverflowBB});
-  DTUpdates.push_back({DominatorTree::Insert, OverflowEntryBB, NoOverflowBB});
 
   // BB overflow.no:
   Builder.SetInsertPoint(NoOverflowBB);
@@ -6548,9 +6544,6 @@ bool CodeGenPrepare::optimizeMulWithOverflow(Instruction *I, bool IsSigned,
   // No we don't need the old terminator in overflow.entry BB, erase it:
   OldTerminator->eraseFromParent();
 
-  DTUpdates.push_back({DominatorTree::Insert, NoOverflowBB, OverflowResBB});
-  DTUpdates.push_back({DominatorTree::Delete, OverflowEntryBB, OverflowResBB});
-
   // BB overflow.res:
   Builder.SetInsertPoint(OverflowResBB, OverflowResBB->getFirstInsertionPt());
   // Create PHI nodes to merge results from no.overflow BB and overflow BB to
@@ -6583,13 +6576,16 @@ bool CodeGenPrepare::optimizeMulWithOverflow(Instruction *I, bool IsSigned,
   Value *MulOverflow = Builder.CreateExtractValue(I, {0}, "mul.overflow");
   Value *OverflowFlag = Builder.CreateExtractValue(I, {1}, "overflow.flag");
   Builder.CreateBr(OverflowResBB);
-  DTUpdates.push_back({DominatorTree::Insert, OverflowBB, OverflowResBB});
 
   // Add The Extracted values to the PHINodes in the overflow.res BB.
   OverflowResPHI->addIncoming(MulOverflow, OverflowBB);
   OverflowFlagPHI->addIncoming(OverflowFlag, OverflowBB);
 
-  DTU->applyUpdates(DTUpdates);
+  DTU->applyUpdates({{DominatorTree::Insert, OverflowEntryBB, OverflowBB},
+                     {DominatorTree::Insert, OverflowEntryBB, NoOverflowBB},
+                     {DominatorTree::Insert, NoOverflowBB, OverflowResBB},
+                     {DominatorTree::Delete, OverflowEntryBB, OverflowResBB},
+                     {DominatorTree::Insert, OverflowBB, OverflowResBB}});
 
   ModifiedDT = ModifyDT::ModifyBBDT;
   return true;

>From 6f76b278ec82079443fdf841e970d74afa67684b Mon Sep 17 00:00:00 2001
From: Enna1 <xumingjie.enna1 at bytedance.com>
Date: Thu, 5 Feb 2026 21:59:34 +0800
Subject: [PATCH 09/14] remove class member DominatorTree *DT

---
 llvm/lib/CodeGen/CodeGenPrepare.cpp | 13 +++++++------
 1 file changed, 7 insertions(+), 6 deletions(-)

diff --git a/llvm/lib/CodeGen/CodeGenPrepare.cpp b/llvm/lib/CodeGen/CodeGenPrepare.cpp
index 038752ccb73c3..06a899789fdca 100644
--- a/llvm/lib/CodeGen/CodeGenPrepare.cpp
+++ b/llvm/lib/CodeGen/CodeGenPrepare.cpp
@@ -322,7 +322,6 @@ class CodeGenPrepare {
   const TargetTransformInfo *TTI = nullptr;
   const BasicBlockSectionsProfileReader *BBSectionsProfileReader = nullptr;
   const TargetLibraryInfo *TLInfo = nullptr;
-  DominatorTree *DT = nullptr;
   DomTreeUpdater *DTU = nullptr;
   LoopInfo *LI = nullptr;
   std::unique_ptr<BlockFrequencyInfo> BFI;
@@ -522,7 +521,6 @@ bool CodeGenPrepareLegacyPass::runOnFunction(Function &F) {
   CGP.TRI = CGP.SubtargetInfo->getRegisterInfo();
   CGP.TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
   CGP.TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
-  CGP.DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
   CGP.LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
   CGP.BPI.reset(new BranchProbabilityInfo(F, *CGP.LI));
   CGP.BFI.reset(new BlockFrequencyInfo(F, *CGP.BPI, *CGP.LI));
@@ -530,6 +528,10 @@ bool CodeGenPrepareLegacyPass::runOnFunction(Function &F) {
   auto BBSPRWP =
       getAnalysisIfAvailable<BasicBlockSectionsProfileReaderWrapperPass>();
   CGP.BBSectionsProfileReader = BBSPRWP ? &BBSPRWP->getBBSPR() : nullptr;
+  DomTreeUpdater DTUpdater(
+      &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
+      DomTreeUpdater::UpdateStrategy::Lazy);
+  CGP.DTU = &DTUpdater;
 
   return CGP._run(F);
 }
@@ -571,7 +573,6 @@ bool CodeGenPrepare::run(Function &F, FunctionAnalysisManager &AM) {
   TRI = SubtargetInfo->getRegisterInfo();
   TLInfo = &AM.getResult<TargetLibraryAnalysis>(F);
   TTI = &AM.getResult<TargetIRAnalysis>(F);
-  DT = &AM.getResult<DominatorTreeAnalysis>(F);
   LI = &AM.getResult<LoopAnalysis>(F);
   BPI.reset(new BranchProbabilityInfo(F, *LI));
   BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
@@ -579,6 +580,9 @@ bool CodeGenPrepare::run(Function &F, FunctionAnalysisManager &AM) {
   PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
   BBSectionsProfileReader =
       AM.getCachedResult<BasicBlockSectionsProfileReaderAnalysis>(F);
+  DomTreeUpdater DTUpdater(&AM.getResult<DominatorTreeAnalysis>(F),
+                           DomTreeUpdater::UpdateStrategy::Lazy);
+  DTU = &DTUpdater;
   return _run(F);
 }
 
@@ -609,9 +613,6 @@ bool CodeGenPrepare::_run(Function &F) {
       (void)F.setSectionPrefix("unknown");
   }
 
-  DomTreeUpdater DTUpdater(DT, DomTreeUpdater::UpdateStrategy::Lazy);
-  DTU = &DTUpdater;
-
   /// This optimization identifies DIV instructions that can be
   /// profitably bypassed and carried out with a shorter, faster divide.
   if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI->isSlowDivBypassed()) {

>From 2b2e48bf930d25bf1beb1865fcd5a850b7226290 Mon Sep 17 00:00:00 2001
From: Enna1 <xumingjie.enna1 at bytedance.com>
Date: Tue, 10 Feb 2026 19:04:11 +0800
Subject: [PATCH 10/14] Add DomTreeUpdater and LoopInfo support for
 bypassSlowDivision()

Add DomTreeUpdater support for eliminateMostlyEmptyBlocks(),  eliminateMostlyEmptyBlocks() may introduce new loop,
add an argument `ResetLI` for eliminateMostlyEmptyBlocks()  indicated
that LoopInfo should be reanalyzed.
---
 .../Transforms/Utils/BypassSlowDivision.h     |  7 +-
 llvm/lib/CodeGen/CodeGenPrepare.cpp           | 58 +++++++++++-----
 .../Transforms/Utils/BypassSlowDivision.cpp   | 68 +++++++++++++------
 ...bypass-slow-div-debug-info-inseltpoison.ll | 60 ++++++++--------
 .../AMDGPU/bypass-slow-div-debug-info.ll      | 60 ++++++++--------
 5 files changed, 155 insertions(+), 98 deletions(-)

diff --git a/llvm/include/llvm/Transforms/Utils/BypassSlowDivision.h b/llvm/include/llvm/Transforms/Utils/BypassSlowDivision.h
index bd98c902d1ab4..eceb131d8c60c 100644
--- a/llvm/include/llvm/Transforms/Utils/BypassSlowDivision.h
+++ b/llvm/include/llvm/Transforms/Utils/BypassSlowDivision.h
@@ -25,6 +25,8 @@
 namespace llvm {
 
 class BasicBlock;
+class DomTreeUpdater;
+class LoopInfo;
 class Value;
 
 struct DivRemMapKey {
@@ -66,8 +68,9 @@ template <> struct DenseMapInfo<DivRemMapKey> {
 ///
 /// This optimization may add basic blocks immediately after BB; for obvious
 /// reasons, you shouldn't pass those blocks to bypassSlowDivision.
-bool bypassSlowDivision(
-    BasicBlock *BB, const DenseMap<unsigned int, unsigned int> &BypassWidth);
+bool bypassSlowDivision(BasicBlock *BB,
+                        const DenseMap<unsigned int, unsigned int> &BypassWidth,
+                        DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr);
 
 } // end namespace llvm
 
diff --git a/llvm/lib/CodeGen/CodeGenPrepare.cpp b/llvm/lib/CodeGen/CodeGenPrepare.cpp
index 06a899789fdca..a5d799fef7e10 100644
--- a/llvm/lib/CodeGen/CodeGenPrepare.cpp
+++ b/llvm/lib/CodeGen/CodeGenPrepare.cpp
@@ -19,6 +19,7 @@
 #include "llvm/ADT/MapVector.h"
 #include "llvm/ADT/PointerIntPair.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/STLForwardCompat.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/Statistic.h"
@@ -47,6 +48,7 @@
 #include "llvm/IR/Argument.h"
 #include "llvm/IR/Attributes.h"
 #include "llvm/IR/BasicBlock.h"
+#include "llvm/IR/CFG.h"
 #include "llvm/IR/Constant.h"
 #include "llvm/IR/Constants.h"
 #include "llvm/IR/DataLayout.h"
@@ -422,10 +424,10 @@ class CodeGenPrepare {
   void removeAllAssertingVHReferences(Value *V);
   bool eliminateAssumptions(Function &F);
   bool eliminateFallThrough(Function &F);
-  bool eliminateMostlyEmptyBlocks(Function &F);
+  bool eliminateMostlyEmptyBlocks(Function &F, bool &ResetLI);
   BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
   bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
-  void eliminateMostlyEmptyBlock(BasicBlock *BB);
+  bool eliminateMostlyEmptyBlock(BasicBlock *BB);
   bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
                                      bool isPreheader);
   bool makeBitReverse(Instruction &I);
@@ -624,7 +626,7 @@ bool CodeGenPrepare::_run(Function &F) {
       // optimization to those blocks.
       BasicBlock *Next = BB->getNextNode();
       if (!llvm::shouldOptimizeForSize(BB, PSI, BFI.get()))
-        EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
+        EverMadeChange |= bypassSlowDivision(BB, BypassWidths, DTU, LI);
       BB = Next;
     }
   }
@@ -636,18 +638,21 @@ bool CodeGenPrepare::_run(Function &F) {
 
   // Eliminate blocks that contain only PHI nodes and an
   // unconditional branch.
-  EverMadeChange |= eliminateMostlyEmptyBlocks(F);
+  bool ResetLI = false;
+  EverMadeChange |= eliminateMostlyEmptyBlocks(F, ResetLI);
+  if (ResetLI) {
+    LI->releaseMemory();
+    LI->analyze(DTU->getDomTree());
+  }
 
   if (!DisableBranchOpts)
     EverMadeChange |= splitBranchCondition(F);
 
   // Split some critical edges where one of the sources is an indirect branch,
   // to help generate sane code for PHIs involving such edges.
-  EverMadeChange |=
-      SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/true);
-
-  // Transformations above may invalidate dominator tree and/or loop info.
-  if (EverMadeChange) {
+  bool Split = SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/true);
+  EverMadeChange |= Split;
+  if (Split) {
     DTU->recalculate(F);
     LI->releaseMemory();
     LI->analyze(DTU->getDomTree());
@@ -931,7 +936,7 @@ BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
 /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
 /// edges in ways that are non-optimal for isel. Start by eliminating these
 /// blocks so we can split them the way we want them.
-bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
+bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F, bool &ResetLI) {
   SmallPtrSet<BasicBlock *, 16> Preheaders;
   SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
   while (!LoopList.empty()) {
@@ -941,6 +946,7 @@ bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
       Preheaders.insert(Preheader);
   }
 
+  ResetLI = false;
   bool MadeChange = false;
   // Copy blocks into a temporary array to avoid iterator invalidation issues
   // as we remove them.
@@ -955,14 +961,14 @@ bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
 
   for (auto &Block : Blocks) {
     BasicBlock *BB = cast_or_null<BasicBlock>(Block);
-    if (!BB)
+    if (!BB || DTU->isBBPendingDeletion(BB))
       continue;
     BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
     if (!DestBB ||
         !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
       continue;
 
-    eliminateMostlyEmptyBlock(BB);
+    ResetLI |= eliminateMostlyEmptyBlock(BB);
     MadeChange = true;
   }
   return MadeChange;
@@ -1138,8 +1144,8 @@ static void replaceAllUsesWith(Value *Old, Value *New,
 
 /// Eliminate a basic block that has only phi's and an unconditional branch in
 /// it.
-/// Indicate that the DT was modified only if the DT wasn't updated.
-void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
+/// Indicate that the LoopInfo was modified only if it wasn't updated.
+bool CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
   BasicBlock *DestBB = BI->getSuccessor(0);
 
@@ -1153,7 +1159,7 @@ void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
       assert(SinglePred == BB &&
              "Single predecessor not the same as predecessor");
       // Merge DestBB into SinglePred/BB and delete it.
-      MergeBlockIntoPredecessor(DestBB);
+      MergeBlockIntoPredecessor(DestBB, DTU, LI);
       // Note: BB(=SinglePred) will not be deleted on this path.
       // DestBB(=its single successor) is the one that was deleted.
       LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n");
@@ -1163,7 +1169,7 @@ void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
         FreshBBs.insert(SinglePred);
         FreshBBs.erase(DestBB);
       }
-      return;
+      return false;
     }
   }
 
@@ -1202,11 +1208,29 @@ void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
 
   // The PHIs are now updated, change everything that refers to BB to use
   // DestBB and remove BB.
+  SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
+  SmallPtrSet<BasicBlock *, 8> SeenPreds;
+  SmallPtrSet<BasicBlock *, 8> PredOfDestBB(llvm::from_range,
+                                            predecessors(DestBB));
+  for (auto *Pred : predecessors(BB)) {
+    if (!PredOfDestBB.contains(Pred)) {
+      if (SeenPreds.insert(Pred).second)
+        DTUpdates.push_back({DominatorTree::Insert, Pred, DestBB});
+    }
+  }
+  SeenPreds.clear();
+  for (auto *Pred : predecessors(BB)) {
+    if (SeenPreds.insert(Pred).second)
+      DTUpdates.push_back({DominatorTree::Delete, Pred, BB});
+  }
+  DTUpdates.push_back({DominatorTree::Delete, BB, DestBB});
   BB->replaceAllUsesWith(DestBB);
-  BB->eraseFromParent();
+  DTU->applyUpdates(DTUpdates);
+  DTU->deleteBB(BB);
   ++NumBlocksElim;
 
   LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
+  return true;
 }
 
 // Computes a map of base pointer relocation instructions to corresponding
diff --git a/llvm/lib/Transforms/Utils/BypassSlowDivision.cpp b/llvm/lib/Transforms/Utils/BypassSlowDivision.cpp
index 66d8fea251cbd..ff5bf52b560cf 100644
--- a/llvm/lib/Transforms/Utils/BypassSlowDivision.cpp
+++ b/llvm/lib/Transforms/Utils/BypassSlowDivision.cpp
@@ -18,6 +18,8 @@
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/Analysis/DomTreeUpdater.h"
+#include "llvm/Analysis/LoopInfo.h"
 #include "llvm/Analysis/ValueTracking.h"
 #include "llvm/IR/BasicBlock.h"
 #include "llvm/IR/Constants.h"
@@ -30,6 +32,7 @@
 #include "llvm/IR/Value.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/KnownBits.h"
+#include "llvm/Transforms/Utils/BasicBlockUtils.h"
 #include "llvm/Transforms/Utils/Local.h"
 #include <cassert>
 #include <cstdint>
@@ -76,6 +79,8 @@ class FastDivInsertionTask {
   Instruction *SlowDivOrRem = nullptr;
   IntegerType *BypassType = nullptr;
   BasicBlock *MainBB = nullptr;
+  DomTreeUpdater *DTU = nullptr;
+  LoopInfo *LI = nullptr;
 
   bool isHashLikeValue(Value *V, VisitedSetTy &Visited);
   ValueRange getValueRange(Value *Op, VisitedSetTy &Visited);
@@ -99,7 +104,8 @@ class FastDivInsertionTask {
   Type *getSlowType() { return SlowDivOrRem->getType(); }
 
 public:
-  FastDivInsertionTask(Instruction *I, const BypassWidthsTy &BypassWidths);
+  FastDivInsertionTask(Instruction *I, const BypassWidthsTy &BypassWidths,
+                       DomTreeUpdater *DTU, LoopInfo *LI);
 
   Value *getReplacement(DivCacheTy &Cache);
 };
@@ -107,7 +113,9 @@ class FastDivInsertionTask {
 } // end anonymous namespace
 
 FastDivInsertionTask::FastDivInsertionTask(Instruction *I,
-                                           const BypassWidthsTy &BypassWidths) {
+                                           const BypassWidthsTy &BypassWidths,
+                                           DomTreeUpdater *DTU, LoopInfo *LI)
+    : DTU(DTU), LI(LI) {
   switch (I->getOpcode()) {
   case Instruction::UDiv:
   case Instruction::SDiv:
@@ -412,7 +420,7 @@ std::optional<QuotRemPair> FastDivInsertionTask::insertFastDivAndRem() {
     // lets us entirely avoid a long div.
 
     // Split the basic block before the div/rem.
-    BasicBlock *SuccessorBB = MainBB->splitBasicBlock(SlowDivOrRem);
+    BasicBlock *SuccessorBB = SplitBlock(MainBB, SlowDivOrRem, DTU, LI);
     // Remove the unconditional branch from MainBB to SuccessorBB.
     MainBB->back().eraseFromParent();
     QuotRemWithBB Long;
@@ -423,29 +431,51 @@ std::optional<QuotRemPair> FastDivInsertionTask::insertFastDivAndRem() {
     QuotRemPair Result = createDivRemPhiNodes(Fast, Long, SuccessorBB);
     Value *CmpV = Builder.CreateICmpUGE(Dividend, Divisor);
     Builder.CreateCondBr(CmpV, Fast.BB, SuccessorBB);
-    return Result;
-  } else {
-    // General case. Create both slow and fast div/rem pairs and choose one of
-    // them at runtime.
 
-    // Split the basic block before the div/rem.
-    BasicBlock *SuccessorBB = MainBB->splitBasicBlock(SlowDivOrRem);
-    // Remove the unconditional branch from MainBB to SuccessorBB.
-    MainBB->back().eraseFromParent();
-    QuotRemWithBB Fast = createFastBB(SuccessorBB);
-    QuotRemWithBB Slow = createSlowBB(SuccessorBB);
-    QuotRemPair Result = createDivRemPhiNodes(Fast, Slow, SuccessorBB);
-    Value *CmpV = insertOperandRuntimeCheck(DividendShort ? nullptr : Dividend,
-                                            DivisorShort ? nullptr : Divisor);
-    Builder.CreateCondBr(CmpV, Fast.BB, Slow.BB);
+    if (DTU)
+      DTU->applyUpdates({{DominatorTree::Insert, MainBB, Fast.BB},
+                         {DominatorTree::Insert, Fast.BB, SuccessorBB}});
+    if (LI) {
+      if (Loop *L = LI->getLoopFor(MainBB))
+        L->addBasicBlockToLoop(Fast.BB, *LI);
+    }
+
     return Result;
   }
+
+  // General case. Create both slow and fast div/rem pairs and choose one of
+  // them at runtime.
+
+  // Split the basic block before the div/rem.
+  BasicBlock *SuccessorBB = SplitBlock(MainBB, SlowDivOrRem, DTU, LI);
+  // Remove the unconditional branch from MainBB to SuccessorBB.
+  MainBB->back().eraseFromParent();
+  QuotRemWithBB Fast = createFastBB(SuccessorBB);
+  QuotRemWithBB Slow = createSlowBB(SuccessorBB);
+  QuotRemPair Result = createDivRemPhiNodes(Fast, Slow, SuccessorBB);
+  Value *CmpV = insertOperandRuntimeCheck(DividendShort ? nullptr : Dividend,
+                                          DivisorShort ? nullptr : Divisor);
+  Builder.CreateCondBr(CmpV, Fast.BB, Slow.BB);
+  if (DTU)
+    DTU->applyUpdates({{DominatorTree::Insert, MainBB, Fast.BB},
+                       {DominatorTree::Insert, MainBB, Slow.BB},
+                       {DominatorTree::Insert, Fast.BB, SuccessorBB},
+                       {DominatorTree::Insert, Slow.BB, SuccessorBB},
+                       {DominatorTree::Delete, MainBB, SuccessorBB}});
+  if (LI) {
+    if (Loop *L = LI->getLoopFor(MainBB)) {
+      L->addBasicBlockToLoop(Fast.BB, *LI);
+      L->addBasicBlockToLoop(Slow.BB, *LI);
+    }
+  }
+  return Result;
 }
 
 /// This optimization identifies DIV/REM instructions in a BB that can be
 /// profitably bypassed and carried out with a shorter, faster divide.
 bool llvm::bypassSlowDivision(BasicBlock *BB,
-                              const BypassWidthsTy &BypassWidths) {
+                              const BypassWidthsTy &BypassWidths,
+                              DomTreeUpdater *DTU, LoopInfo *LI) {
   DivCacheTy PerBBDivCache;
 
   bool MadeChange = false;
@@ -460,7 +490,7 @@ bool llvm::bypassSlowDivision(BasicBlock *BB,
     if (I->use_empty())
       continue;
 
-    FastDivInsertionTask Task(I, BypassWidths);
+    FastDivInsertionTask Task(I, BypassWidths, DTU, LI);
     if (Value *Replacement = Task.getReplacement(PerBBDivCache)) {
       I->replaceAllUsesWith(Replacement);
       I->eraseFromParent();
diff --git a/llvm/test/Transforms/CodeGenPrepare/AMDGPU/bypass-slow-div-debug-info-inseltpoison.ll b/llvm/test/Transforms/CodeGenPrepare/AMDGPU/bypass-slow-div-debug-info-inseltpoison.ll
index 8c198a3c7d607..20db568d1ff10 100644
--- a/llvm/test/Transforms/CodeGenPrepare/AMDGPU/bypass-slow-div-debug-info-inseltpoison.ll
+++ b/llvm/test/Transforms/CodeGenPrepare/AMDGPU/bypass-slow-div-debug-info-inseltpoison.ll
@@ -4,21 +4,21 @@
 
 define i64 @sdiv64(i64 %a, i64 %b) {
 ; CHECK-LABEL: @sdiv64(
-; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[A:%.*]], [[B:%.*]], [[DBG6:!dbg !.*]]
-; CHECK-NEXT:    [[TMP2:%.*]] = and i64 [[TMP1]], -4294967296, [[DBG6]]
-; CHECK-NEXT:    [[TMP3:%.*]] = icmp eq i64 [[TMP2]], 0, [[DBG6]]
-; CHECK-NEXT:    br i1 [[TMP3]], label [[TMP4:%.*]], label [[TMP9:%.*]], [[DBG6]]
+; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[A:%.*]], [[B:%.*]], !dbg [[DBG6:![0-9]+]]
+; CHECK-NEXT:    [[TMP2:%.*]] = and i64 [[TMP1]], -4294967296, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP3:%.*]] = icmp eq i64 [[TMP2]], 0, !dbg [[DBG6]]
+; CHECK-NEXT:    br i1 [[TMP3]], label [[TMP4:%.*]], label [[TMP9:%.*]], !dbg [[DBG6]]
 ; CHECK:       4:
-; CHECK-NEXT:    [[TMP5:%.*]] = trunc i64 [[B]] to i32, [[DBG6]]
-; CHECK-NEXT:    [[TMP6:%.*]] = trunc i64 [[A]] to i32, [[DBG6]]
-; CHECK-NEXT:    [[TMP7:%.*]] = udiv i32 [[TMP6]], [[TMP5]], [[DBG6]]
-; CHECK-NEXT:    [[TMP8:%.*]] = zext i32 [[TMP7]] to i64, [[DBG6]]
-; CHECK-NEXT:    br label [[TMP11:%.*]], [[DBG6]]
+; CHECK-NEXT:    [[TMP5:%.*]] = trunc i64 [[B]] to i32, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP6:%.*]] = trunc i64 [[A]] to i32, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP7:%.*]] = udiv i32 [[TMP6]], [[TMP5]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP8:%.*]] = zext i32 [[TMP7]] to i64, !dbg [[DBG6]]
+; CHECK-NEXT:    br label [[TMP11:%.*]], !dbg [[DBG6]]
 ; CHECK:       9:
-; CHECK-NEXT:    [[TMP10:%.*]] = sdiv i64 [[A]], [[B]], [[DBG6]]
-; CHECK-NEXT:    br label [[TMP11]], [[DBG6]]
-; CHECK:       11:
-; CHECK-NEXT:    [[TMP12:%.*]] = phi i64 [ [[TMP8]], [[TMP4]] ], [ [[TMP10]], [[TMP9]] ], [[DBG6]]
+; CHECK-NEXT:    [[TMP10:%.*]] = sdiv i64 [[A]], [[B]], !dbg [[DBG6]]
+; CHECK-NEXT:    br label [[TMP11]], !dbg [[DBG6]]
+; CHECK:       .split:
+; CHECK-NEXT:    [[TMP12:%.*]] = phi i64 [ [[TMP8]], [[TMP4]] ], [ [[TMP10]], [[TMP9]] ], !dbg [[DBG6]]
 ; CHECK-NEXT:    ret i64 [[TMP12]]
 ;
   %d = sdiv i64 %a, %b, !dbg !6
@@ -29,25 +29,25 @@ define i64 @sdiv64(i64 %a, i64 %b) {
 ; division.
 define <2 x i64> @sdivrem64(i64 %a, i64 %b) {
 ; CHECK-LABEL: @sdivrem64(
-; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[A:%.*]], [[B:%.*]], [[DBG6]]
-; CHECK-NEXT:    [[TMP2:%.*]] = and i64 [[TMP1]], -4294967296, [[DBG6]]
-; CHECK-NEXT:    [[TMP3:%.*]] = icmp eq i64 [[TMP2]], 0, [[DBG6]]
-; CHECK-NEXT:    br i1 [[TMP3]], label [[TMP4:%.*]], label [[TMP11:%.*]], [[DBG6]]
+; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[A:%.*]], [[B:%.*]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP2:%.*]] = and i64 [[TMP1]], -4294967296, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP3:%.*]] = icmp eq i64 [[TMP2]], 0, !dbg [[DBG6]]
+; CHECK-NEXT:    br i1 [[TMP3]], label [[TMP4:%.*]], label [[TMP11:%.*]], !dbg [[DBG6]]
 ; CHECK:       4:
-; CHECK-NEXT:    [[TMP5:%.*]] = trunc i64 [[B]] to i32, [[DBG6]]
-; CHECK-NEXT:    [[TMP6:%.*]] = trunc i64 [[A]] to i32, [[DBG6]]
-; CHECK-NEXT:    [[TMP7:%.*]] = udiv i32 [[TMP6]], [[TMP5]], [[DBG6]]
-; CHECK-NEXT:    [[TMP8:%.*]] = urem i32 [[TMP6]], [[TMP5]], [[DBG6]]
-; CHECK-NEXT:    [[TMP9:%.*]] = zext i32 [[TMP7]] to i64, [[DBG6]]
-; CHECK-NEXT:    [[TMP10:%.*]] = zext i32 [[TMP8]] to i64, [[DBG6]]
-; CHECK-NEXT:    br label [[TMP14:%.*]], [[DBG6]]
+; CHECK-NEXT:    [[TMP5:%.*]] = trunc i64 [[B]] to i32, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP6:%.*]] = trunc i64 [[A]] to i32, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP7:%.*]] = udiv i32 [[TMP6]], [[TMP5]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP8:%.*]] = urem i32 [[TMP6]], [[TMP5]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP9:%.*]] = zext i32 [[TMP7]] to i64, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP10:%.*]] = zext i32 [[TMP8]] to i64, !dbg [[DBG6]]
+; CHECK-NEXT:    br label [[TMP14:%.*]], !dbg [[DBG6]]
 ; CHECK:       11:
-; CHECK-NEXT:    [[TMP12:%.*]] = sdiv i64 [[A]], [[B]], [[DBG6]]
-; CHECK-NEXT:    [[TMP13:%.*]] = srem i64 [[A]], [[B]], [[DBG6]]
-; CHECK-NEXT:    br label [[TMP14]], [[DBG6]]
-; CHECK:       14:
-; CHECK-NEXT:    [[TMP15:%.*]] = phi i64 [ [[TMP9]], [[TMP4]] ], [ [[TMP12]], [[TMP11]] ], [[DBG6]]
-; CHECK-NEXT:    [[TMP16:%.*]] = phi i64 [ [[TMP10]], [[TMP4]] ], [ [[TMP13]], [[TMP11]] ], [[DBG6]]
+; CHECK-NEXT:    [[TMP12:%.*]] = sdiv i64 [[A]], [[B]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP13:%.*]] = srem i64 [[A]], [[B]], !dbg [[DBG6]]
+; CHECK-NEXT:    br label [[TMP14]], !dbg [[DBG6]]
+; CHECK:       .split:
+; CHECK-NEXT:    [[TMP15:%.*]] = phi i64 [ [[TMP9]], [[TMP4]] ], [ [[TMP12]], [[TMP11]] ], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP16:%.*]] = phi i64 [ [[TMP10]], [[TMP4]] ], [ [[TMP13]], [[TMP11]] ], !dbg [[DBG6]]
 ; CHECK-NEXT:    [[INS0:%.*]] = insertelement <2 x i64> poison, i64 [[TMP15]], i32 0
 ; CHECK-NEXT:    [[INS1:%.*]] = insertelement <2 x i64> [[INS0]], i64 [[TMP16]], i32 1
 ; CHECK-NEXT:    ret <2 x i64> [[INS1]]
diff --git a/llvm/test/Transforms/CodeGenPrepare/AMDGPU/bypass-slow-div-debug-info.ll b/llvm/test/Transforms/CodeGenPrepare/AMDGPU/bypass-slow-div-debug-info.ll
index cf2d96214a54c..c0fba863376cf 100644
--- a/llvm/test/Transforms/CodeGenPrepare/AMDGPU/bypass-slow-div-debug-info.ll
+++ b/llvm/test/Transforms/CodeGenPrepare/AMDGPU/bypass-slow-div-debug-info.ll
@@ -4,21 +4,21 @@
 
 define i64 @sdiv64(i64 %a, i64 %b) {
 ; CHECK-LABEL: @sdiv64(
-; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[A:%.*]], [[B:%.*]], !dbg !6
-; CHECK-NEXT:    [[TMP2:%.*]] = and i64 [[TMP1]], -4294967296, !dbg !6
-; CHECK-NEXT:    [[TMP3:%.*]] = icmp eq i64 [[TMP2]], 0, !dbg !6
-; CHECK-NEXT:    br i1 [[TMP3]], label [[TMP4:%.*]], label [[TMP9:%.*]], !dbg !6
+; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[A:%.*]], [[B:%.*]], !dbg [[DBG6:![0-9]+]]
+; CHECK-NEXT:    [[TMP2:%.*]] = and i64 [[TMP1]], -4294967296, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP3:%.*]] = icmp eq i64 [[TMP2]], 0, !dbg [[DBG6]]
+; CHECK-NEXT:    br i1 [[TMP3]], label [[TMP4:%.*]], label [[TMP9:%.*]], !dbg [[DBG6]]
 ; CHECK:       4:
-; CHECK-NEXT:    [[TMP5:%.*]] = trunc i64 [[B]] to i32, !dbg !6
-; CHECK-NEXT:    [[TMP6:%.*]] = trunc i64 [[A]] to i32, !dbg !6
-; CHECK-NEXT:    [[TMP7:%.*]] = udiv i32 [[TMP6]], [[TMP5]], !dbg !6
-; CHECK-NEXT:    [[TMP8:%.*]] = zext i32 [[TMP7]] to i64, !dbg !6
-; CHECK-NEXT:    br label [[TMP11:%.*]], !dbg !6
+; CHECK-NEXT:    [[TMP5:%.*]] = trunc i64 [[B]] to i32, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP6:%.*]] = trunc i64 [[A]] to i32, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP7:%.*]] = udiv i32 [[TMP6]], [[TMP5]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP8:%.*]] = zext i32 [[TMP7]] to i64, !dbg [[DBG6]]
+; CHECK-NEXT:    br label [[DOTSPLIT:%.*]], !dbg [[DBG6]]
 ; CHECK:       9:
-; CHECK-NEXT:    [[TMP10:%.*]] = sdiv i64 [[A]], [[B]], !dbg !6
-; CHECK-NEXT:    br label [[TMP11]], !dbg !6
-; CHECK:       11:
-; CHECK-NEXT:    [[TMP12:%.*]] = phi i64 [ [[TMP8]], [[TMP4]] ], [ [[TMP10]], [[TMP9]] ], !dbg !6
+; CHECK-NEXT:    [[TMP10:%.*]] = sdiv i64 [[A]], [[B]], !dbg [[DBG6]]
+; CHECK-NEXT:    br label [[DOTSPLIT]], !dbg [[DBG6]]
+; CHECK:       .split:
+; CHECK-NEXT:    [[TMP12:%.*]] = phi i64 [ [[TMP8]], [[TMP4]] ], [ [[TMP10]], [[TMP9]] ], !dbg [[DBG6]]
 ; CHECK-NEXT:    ret i64 [[TMP12]]
 ;
   %d = sdiv i64 %a, %b, !dbg !6
@@ -29,25 +29,25 @@ define i64 @sdiv64(i64 %a, i64 %b) {
 ; division.
 define <2 x i64> @sdivrem64(i64 %a, i64 %b) {
 ; CHECK-LABEL: @sdivrem64(
-; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[A:%.*]], [[B:%.*]], !dbg !6
-; CHECK-NEXT:    [[TMP2:%.*]] = and i64 [[TMP1]], -4294967296, !dbg !6
-; CHECK-NEXT:    [[TMP3:%.*]] = icmp eq i64 [[TMP2]], 0, !dbg !6
-; CHECK-NEXT:    br i1 [[TMP3]], label [[TMP4:%.*]], label [[TMP11:%.*]], !dbg !6
+; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[A:%.*]], [[B:%.*]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP2:%.*]] = and i64 [[TMP1]], -4294967296, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP3:%.*]] = icmp eq i64 [[TMP2]], 0, !dbg [[DBG6]]
+; CHECK-NEXT:    br i1 [[TMP3]], label [[TMP4:%.*]], label [[TMP11:%.*]], !dbg [[DBG6]]
 ; CHECK:       4:
-; CHECK-NEXT:    [[TMP5:%.*]] = trunc i64 [[B]] to i32, !dbg !6
-; CHECK-NEXT:    [[TMP6:%.*]] = trunc i64 [[A]] to i32, !dbg !6
-; CHECK-NEXT:    [[TMP7:%.*]] = udiv i32 [[TMP6]], [[TMP5]], !dbg !6
-; CHECK-NEXT:    [[TMP8:%.*]] = urem i32 [[TMP6]], [[TMP5]], !dbg !6
-; CHECK-NEXT:    [[TMP9:%.*]] = zext i32 [[TMP7]] to i64, !dbg !6
-; CHECK-NEXT:    [[TMP10:%.*]] = zext i32 [[TMP8]] to i64, !dbg !6
-; CHECK-NEXT:    br label [[TMP14:%.*]], !dbg !6
+; CHECK-NEXT:    [[TMP5:%.*]] = trunc i64 [[B]] to i32, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP6:%.*]] = trunc i64 [[A]] to i32, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP7:%.*]] = udiv i32 [[TMP6]], [[TMP5]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP8:%.*]] = urem i32 [[TMP6]], [[TMP5]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP9:%.*]] = zext i32 [[TMP7]] to i64, !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP10:%.*]] = zext i32 [[TMP8]] to i64, !dbg [[DBG6]]
+; CHECK-NEXT:    br label [[DOTSPLIT:%.*]], !dbg [[DBG6]]
 ; CHECK:       11:
-; CHECK-NEXT:    [[TMP12:%.*]] = sdiv i64 [[A]], [[B]], !dbg !6
-; CHECK-NEXT:    [[TMP13:%.*]] = srem i64 [[A]], [[B]], !dbg !6
-; CHECK-NEXT:    br label [[TMP14]], !dbg !6
-; CHECK:       14:
-; CHECK-NEXT:    [[TMP15:%.*]] = phi i64 [ [[TMP9]], [[TMP4]] ], [ [[TMP12]], [[TMP11]] ], !dbg !6
-; CHECK-NEXT:    [[TMP16:%.*]] = phi i64 [ [[TMP10]], [[TMP4]] ], [ [[TMP13]], [[TMP11]] ], !dbg !6
+; CHECK-NEXT:    [[TMP12:%.*]] = sdiv i64 [[A]], [[B]], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP13:%.*]] = srem i64 [[A]], [[B]], !dbg [[DBG6]]
+; CHECK-NEXT:    br label [[DOTSPLIT]], !dbg [[DBG6]]
+; CHECK:       .split:
+; CHECK-NEXT:    [[TMP15:%.*]] = phi i64 [ [[TMP9]], [[TMP4]] ], [ [[TMP12]], [[TMP11]] ], !dbg [[DBG6]]
+; CHECK-NEXT:    [[TMP16:%.*]] = phi i64 [ [[TMP10]], [[TMP4]] ], [ [[TMP13]], [[TMP11]] ], !dbg [[DBG6]]
 ; CHECK-NEXT:    [[INS0:%.*]] = insertelement <2 x i64> undef, i64 [[TMP15]], i32 0
 ; CHECK-NEXT:    [[INS1:%.*]] = insertelement <2 x i64> [[INS0]], i64 [[TMP16]], i32 1
 ; CHECK-NEXT:    ret <2 x i64> [[INS1]]

>From 09fce808976da617ce6a6878728a7e6dec5c55b8 Mon Sep 17 00:00:00 2001
From: Enna1 <xumingjie.enna1 at bytedance.com>
Date: Tue, 10 Feb 2026 19:37:18 +0800
Subject: [PATCH 11/14] No need to use a temporary array to avoid iterator
 invalidation

---
 llvm/lib/CodeGen/CodeGenPrepare.cpp | 13 +++----------
 1 file changed, 3 insertions(+), 10 deletions(-)

diff --git a/llvm/lib/CodeGen/CodeGenPrepare.cpp b/llvm/lib/CodeGen/CodeGenPrepare.cpp
index a5d799fef7e10..b0cfb6884bc0c 100644
--- a/llvm/lib/CodeGen/CodeGenPrepare.cpp
+++ b/llvm/lib/CodeGen/CodeGenPrepare.cpp
@@ -948,20 +948,13 @@ bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F, bool &ResetLI) {
 
   ResetLI = false;
   bool MadeChange = false;
-  // Copy blocks into a temporary array to avoid iterator invalidation issues
-  // as we remove them.
-  // Note that this intentionally skips the entry block.
-  SmallVector<WeakTrackingVH, 16> Blocks;
   for (auto &Block : llvm::drop_begin(F)) {
+    BasicBlock *BB = &Block;
     // Delete phi nodes that could block deleting other empty blocks.
     if (!DisableDeletePHIs)
-      MadeChange |= DeleteDeadPHIs(&Block, TLInfo);
-    Blocks.push_back(&Block);
-  }
+      MadeChange |= DeleteDeadPHIs(BB, TLInfo);
 
-  for (auto &Block : Blocks) {
-    BasicBlock *BB = cast_or_null<BasicBlock>(Block);
-    if (!BB || DTU->isBBPendingDeletion(BB))
+    if (DTU->isBBPendingDeletion(BB))
       continue;
     BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
     if (!DestBB ||

>From 08e98c36352ff959b500f6b747a5e8121692eac9 Mon Sep 17 00:00:00 2001
From: Enna1 <xumingjie.enna1 at bytedance.com>
Date: Tue, 10 Feb 2026 19:37:33 +0800
Subject: [PATCH 12/14] Revert as lots tests need to update, leave it for
 future work

---
 llvm/lib/CodeGen/CodeGenPrepare.cpp | 13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)

diff --git a/llvm/lib/CodeGen/CodeGenPrepare.cpp b/llvm/lib/CodeGen/CodeGenPrepare.cpp
index b0cfb6884bc0c..a5d799fef7e10 100644
--- a/llvm/lib/CodeGen/CodeGenPrepare.cpp
+++ b/llvm/lib/CodeGen/CodeGenPrepare.cpp
@@ -948,13 +948,20 @@ bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F, bool &ResetLI) {
 
   ResetLI = false;
   bool MadeChange = false;
+  // Copy blocks into a temporary array to avoid iterator invalidation issues
+  // as we remove them.
+  // Note that this intentionally skips the entry block.
+  SmallVector<WeakTrackingVH, 16> Blocks;
   for (auto &Block : llvm::drop_begin(F)) {
-    BasicBlock *BB = &Block;
     // Delete phi nodes that could block deleting other empty blocks.
     if (!DisableDeletePHIs)
-      MadeChange |= DeleteDeadPHIs(BB, TLInfo);
+      MadeChange |= DeleteDeadPHIs(&Block, TLInfo);
+    Blocks.push_back(&Block);
+  }
 
-    if (DTU->isBBPendingDeletion(BB))
+  for (auto &Block : Blocks) {
+    BasicBlock *BB = cast_or_null<BasicBlock>(Block);
+    if (!BB || DTU->isBBPendingDeletion(BB))
       continue;
     BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
     if (!DestBB ||

>From 525ef691748359964287712b5ff29f1e2259e705 Mon Sep 17 00:00:00 2001
From: Enna1 <xumingjie.enna1 at bytedance.com>
Date: Thu, 12 Feb 2026 11:18:13 +0800
Subject: [PATCH 13/14] debug verify

---
 llvm/lib/CodeGen/CodeGenPrepare.cpp | 9 +++++++++
 1 file changed, 9 insertions(+)

diff --git a/llvm/lib/CodeGen/CodeGenPrepare.cpp b/llvm/lib/CodeGen/CodeGenPrepare.cpp
index a5d799fef7e10..83eccb43e14a9 100644
--- a/llvm/lib/CodeGen/CodeGenPrepare.cpp
+++ b/llvm/lib/CodeGen/CodeGenPrepare.cpp
@@ -658,6 +658,15 @@ bool CodeGenPrepare::_run(Function &F) {
     LI->analyze(DTU->getDomTree());
   }
 
+#ifndef NDEBUG
+  if (VerifyDT)
+    assert(getDT().verify(DominatorTree::VerificationLevel::Fast) &&
+           "Incorrect DominatorTree updates in CGP");
+
+  if (VerifyLoopInfo)
+    LI->verify(getDT());
+#endif
+
   // If we are optimzing huge function, we need to consider the build time.
   // Because the basic algorithm's complex is near O(N!).
   IsHugeFunc = F.size() > HugeFuncThresholdInCGPP;

>From b73d1f7350d6cac92ce2ce3e85c6ef14eaae0707 Mon Sep 17 00:00:00 2001
From: Enna1 <xumingjie.enna1 at bytedance.com>
Date: Thu, 12 Feb 2026 11:35:25 +0800
Subject: [PATCH 14/14] cleanup

---
 llvm/lib/CodeGen/CodeGenPrepare.cpp | 21 ++++++++-------------
 1 file changed, 8 insertions(+), 13 deletions(-)

diff --git a/llvm/lib/CodeGen/CodeGenPrepare.cpp b/llvm/lib/CodeGen/CodeGenPrepare.cpp
index 83eccb43e14a9..a46ab34704a6d 100644
--- a/llvm/lib/CodeGen/CodeGenPrepare.cpp
+++ b/llvm/lib/CodeGen/CodeGenPrepare.cpp
@@ -19,7 +19,6 @@
 #include "llvm/ADT/MapVector.h"
 #include "llvm/ADT/PointerIntPair.h"
 #include "llvm/ADT/STLExtras.h"
-#include "llvm/ADT/STLForwardCompat.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/Statistic.h"
@@ -9426,19 +9425,15 @@ bool CodeGenPrepare::splitBranchCondition(Function &F) {
       PN.addIncoming(Val, TmpBB);
     }
 
-    if (LI) {
-      if (Loop *L = LI->getLoopFor(&BB))
-        L->addBasicBlockToLoop(TmpBB, *LI);
-    }
+    if (Loop *L = LI->getLoopFor(&BB))
+      L->addBasicBlockToLoop(TmpBB, *LI);
 
-    if (DTU) {
-      // The edge we need to delete starts at BB and ends at whatever TBB ends
-      // up pointing to.
-      DTU->applyUpdates({{DominatorTree::Insert, &BB, TmpBB},
-                         {DominatorTree::Insert, TmpBB, TBB},
-                         {DominatorTree::Insert, TmpBB, FBB},
-                         {DominatorTree::Delete, &BB, TBB}});
-    }
+    // The edge we need to delete starts at BB and ends at whatever TBB ends
+    // up pointing to.
+    DTU->applyUpdates({{DominatorTree::Insert, &BB, TmpBB},
+                       {DominatorTree::Insert, TmpBB, TBB},
+                       {DominatorTree::Insert, TmpBB, FBB},
+                       {DominatorTree::Delete, &BB, TBB}});
 
     // Update the branch weights (from SelectionDAGBuilder::
     // FindMergedConditions).



More information about the llvm-commits mailing list