[llvm] [WinEH] Preserve asynchronous SEH regions through optimization and code generation (PR #224157)

Yassine Missoum via llvm-commits llvm-commits at lists.llvm.org
Wed Sep 16 15:49:57 PDT 2026


https://github.com/yasster created https://github.com/llvm/llvm-project/pull/224157

## Summary

Preserve asynchronous SEH region membership through LLVM optimization and machine-code generation, and keep the emitted scope tables consistent with the final instruction layout.

This is a backend and optimizer change using the existing `eh-asynch` module flag, table-based SEH personality, and `llvm.seh.try.begin/end` markers. It includes the catchpad-state correction and the related region-preservation work, without changing Clang's SEH emission.

## Motivation

Table-based SEH selects handlers using instruction addresses in scope records. An instruction's unwind destination in IR is therefore only part of the contract: the final address ranges must describe the code that actually belongs to each protected region.

Several transformations can break that correspondence:

- A range ending before a trailing branch leaves a guarded loop backedge uncovered.
- Block placement can put unguarded code between two guarded runs, making a single combined range cover too much.
- Sinking, hoisting, tail merging, and register-allocation insertions can place instructions on the wrong side of a region boundary.
- Recording a catchpad at the state it handles can make its own instructions dispatch back to the same handler instead of an enclosing handler.

## Changes

- Record the enclosing asynchronous SEH state on catchpad entry, propagate it through multi-block handlers, and avoid advancing it again at a later `catchret`.
- Add `SEHTryRegionInfo` and use it in InstCombine and CodeGenPrepare sinking decisions. Recompute the query for the relevant operation rather than keeping a snapshot across CFG changes; treat ambiguous nesting conservatively.
- Represent machine region boundaries with EH labels and a zero-code `SEH_REGION_BARRIER` pseudo that participates in machine dependencies.
- Make machine sinking, MachineLICM, and branch folding respect region membership. Preserve each block's branch debug location when tail merging is declined.
- Keep PHI copies, spills, and fast-register-allocator reloads inside the appropriate ranges. Carry region information and create range labels when splitting critical edges.
- Finalize scope ranges in machine layout order: include eligible trailing branches, exclude returns and frame teardown, separate known unguarded gaps, clamp overshooting end labels, and omit empty ranges.
- Add IR/MIR and assembly regressions, and document the representation and consumer requirements in LLVM's exception-handling guide.

## Scope

The region-specific behavior is gated on the existing asynchronous table-SEH contract. This PR does not introduce new frontend emission, IR intrinsics, function attributes, local-unwind APIs, runtime entry points, or compiler flags. It does not redefine undefined behavior, `volatile`, or `nounwind` semantics.

Keeping Clang unchanged does not make the backend changes inactive: existing IR producers already exercise these paths. This PR is not presented as complete SEH support.

>From a7f701112a0d77146f51f55234bf163e748a8919 Mon Sep 17 00:00:00 2001
From: Yassine Missoum <mmissoum at microsoft.com>
Date: Tue, 15 Sep 2026 15:32:01 -0700
Subject: [PATCH 1/3] [WinEH] Keep SEH catchpad bodies in the enclosing scope

Assign the enclosing asynchronous SEH state on entry to a catchpad, before recording the block state. Propagate that state through multi-block handlers and avoid advancing it a second time at catchret.

Add X86 and AArch64 scope-table regressions for catch-all, named-filter, branching and nested handlers at default codegen optimization and -O0.
---
 llvm/lib/CodeGen/WinEHPrepare.cpp             |   9 +-
 llvm/test/CodeGen/WinEH/seh-catchpad-state.ll | 269 ++++++++++++++++++
 2 files changed, 274 insertions(+), 4 deletions(-)
 create mode 100644 llvm/test/CodeGen/WinEH/seh-catchpad-state.ll

diff --git a/llvm/lib/CodeGen/WinEHPrepare.cpp b/llvm/lib/CodeGen/WinEHPrepare.cpp
index 40cb11cbeb0de..7aebb1b91d6a3 100644
--- a/llvm/lib/CodeGen/WinEHPrepare.cpp
+++ b/llvm/lib/CodeGen/WinEHPrepare.cpp
@@ -321,16 +321,17 @@ void llvm::calculateSEHStateForAsynchEH(const BasicBlock *BB, int State,
     const llvm::Instruction *TI = BB->getTerminator();
     if (It->isEHPad())
       State = EHInfo.EHPadStateMap[&*It];
-    EHInfo.BlockToStateMap[BB] = State; // Record state
 
-    if (isa<CatchPadInst>(It) && isa<CatchReturnInst>(TI)) {
+    if (isa<CatchPadInst>(It)) {
       const Constant *FilterOrNull = cast<Constant>(
           cast<CatchPadInst>(It)->getArgOperand(0)->stripPointerCasts());
       const Function *Filter = dyn_cast<Function>(FilterOrNull);
       if (!Filter || !Filter->getName().starts_with("__IsLocalUnwind"))
         State = EHInfo.SEHUnwindMap[State].ToState; // Retrive next State
-    } else if ((isa<CleanupReturnInst>(TI) || isa<CatchReturnInst>(TI)) &&
-               State > 0) {
+    }
+    EHInfo.BlockToStateMap[BB] = State; // Record state
+
+    if (isa<CleanupReturnInst>(TI) && State > 0) {
       // Retrive the new State.
       State = EHInfo.SEHUnwindMap[State].ToState; // Retrive next State
     } else if (isa<InvokeInst>(TI)) {
diff --git a/llvm/test/CodeGen/WinEH/seh-catchpad-state.ll b/llvm/test/CodeGen/WinEH/seh-catchpad-state.ll
new file mode 100644
index 0000000000000..38c8f2e2916f5
--- /dev/null
+++ b/llvm/test/CodeGen/WinEH/seh-catchpad-state.ll
@@ -0,0 +1,269 @@
+; REQUIRES: x86-registered-target || aarch64-registered-target
+; RUN: %if x86-registered-target %{ llc -mtriple=x86_64-pc-windows-msvc -x86-asm-syntax=intel -verify-machineinstrs < %s | FileCheck %s --check-prefixes=CHECK,X86 %}
+; RUN: %if x86-registered-target %{ llc -O0 -mtriple=x86_64-pc-windows-msvc -x86-asm-syntax=intel -verify-machineinstrs < %s | FileCheck %s --check-prefixes=CHECK,X86 %}
+; RUN: %if aarch64-registered-target %{ llc -mtriple=aarch64-pc-windows-msvc -verify-machineinstrs < %s | FileCheck %s --check-prefixes=CHECK,AARCH64 %}
+; RUN: %if aarch64-registered-target %{ llc -O0 -mtriple=aarch64-pc-windows-msvc -verify-machineinstrs < %s | FileCheck %s --check-prefixes=CHECK,AARCH64 %}
+
+declare void @may_fault(ptr)
+declare i32 @filter(ptr, ptr)
+declare void @llvm.seh.try.begin()
+declare void @llvm.seh.try.end()
+declare i32 @__C_specific_handler(...)
+
+define void @leading_store(ptr %address) personality ptr @__C_specific_handler {
+entry:
+  store volatile i32 11, ptr %address
+  invoke void @llvm.seh.try.begin()
+          to label %guarded unwind label %dispatch
+
+guarded:
+  store volatile i32 22, ptr %address
+  invoke void @may_fault(ptr %address)
+          to label %guarded.end unwind label %dispatch
+
+guarded.end:
+  invoke void @llvm.seh.try.end()
+          to label %exit unwind label %dispatch
+
+dispatch:
+  %switch = catchswitch within none [label %handler] unwind to caller
+
+handler:
+  %pad = catchpad within %switch [ptr null]
+  store volatile i32 44, ptr %address
+  catchret from %pad to label %exit
+
+exit:
+  store volatile i32 33, ptr %address
+  ret void
+}
+
+; CHECK-LABEL: leading_store:
+; X86: mov dword ptr [{{[^]]+}}], 11
+; AARCH64: mov [[BEFORE:w[0-9]+]], #11
+; AARCH64-NEXT: str [[BEFORE]], [{{[^]]+}}]
+; CHECK: %guarded{{$}}
+; CHECK-NEXT: [[BEGIN:\.Ltmp[0-9]+]]:
+; X86: mov dword ptr [{{[^]]+}}], 22
+; AARCH64: mov [[GUARDED:w[0-9]+]], #22
+; AARCH64-NEXT: str [[GUARDED]], [{{[^]]+}}]
+; CHECK: {{(call|bl)}} may_fault
+; CHECK: [[END:\.Ltmp[0-9]+]]:
+; CHECK: [[HANDLER:\.LBB[0-9]+_[0-9]+]]: {{.*}}%handler{{$}}
+; X86: mov dword ptr [{{[^]]+}}], 44
+; AARCH64: mov [[CAUGHT:w[0-9]+]], #44
+; AARCH64-NEXT: str [[CAUGHT]], [{{[^]]+}}]
+; X86: mov dword ptr [{{[^]]+}}], 33
+; AARCH64: mov [[AFTER:w[0-9]+]], #33
+; AARCH64-NEXT: str [[AFTER]], [{{[^]]+}}]
+; CHECK: .Llsda_begin{{[0-9]+}}:
+; CHECK-NEXT: {{\.(long|word)}} [[BEGIN]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} [[END]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} 1
+; CHECK-NEXT: {{\.(long|word)}} [[HANDLER]]@IMGREL
+; CHECK-NEXT: .Llsda_end{{[0-9]+}}:
+
+define void @branching_handler(ptr %address, i1 %condition) personality ptr @__C_specific_handler {
+entry:
+  invoke void @llvm.seh.try.begin()
+          to label %guarded unwind label %dispatch
+
+guarded:
+  invoke void @may_fault(ptr %address)
+          to label %guarded.end unwind label %dispatch
+
+guarded.end:
+  invoke void @llvm.seh.try.end()
+          to label %exit unwind label %dispatch
+
+dispatch:
+  %switch = catchswitch within none [label %handler] unwind to caller
+
+handler:
+  %pad = catchpad within %switch [ptr @filter]
+  store volatile i32 44, ptr %address
+  br i1 %condition, label %handler.left, label %handler.right
+
+handler.left:
+  store volatile i32 55, ptr %address
+  catchret from %pad to label %exit
+
+handler.right:
+  store volatile i32 66, ptr %address
+  catchret from %pad to label %exit
+
+exit:
+  store volatile i32 33, ptr %address
+  ret void
+}
+
+; CHECK-LABEL: branching_handler:
+; CHECK: %guarded{{$}}
+; CHECK-NEXT: [[BRANCH_BEGIN:\.Ltmp[0-9]+]]:
+; CHECK: {{(call|bl)}} may_fault
+; CHECK: [[BRANCH_END:\.Ltmp[0-9]+]]:
+; CHECK: [[BRANCH_HANDLER:\.LBB[0-9]+_[0-9]+]]: {{.*}}%handler{{$}}
+; X86: mov dword ptr [{{[^]]+}}], 44
+; AARCH64: mov [[BRANCH_CAUGHT:w[0-9]+]], #44
+; AARCH64-NEXT: str [[BRANCH_CAUGHT]], [{{[^]]+}}]
+; X86: mov dword ptr [{{[^]]+}}], 55
+; AARCH64: mov [[LEFT:w[0-9]+]], #55
+; AARCH64-NEXT: str [[LEFT]], [{{[^]]+}}]
+; X86: mov dword ptr [{{[^]]+}}], 66
+; AARCH64: mov [[RIGHT:w[0-9]+]], #66
+; AARCH64-NEXT: str [[RIGHT]], [{{[^]]+}}]
+; CHECK: .Llsda_begin{{[0-9]+}}:
+; CHECK-NEXT: {{\.(long|word)}} [[BRANCH_BEGIN]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} [[BRANCH_END]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} filter at IMGREL
+; CHECK-NEXT: {{\.(long|word)}} [[BRANCH_HANDLER]]@IMGREL
+; CHECK-NEXT: .Llsda_end{{[0-9]+}}:
+
+define void @nested_handler(ptr %address, i1 %condition) personality ptr @__C_specific_handler {
+entry:
+  invoke void @llvm.seh.try.begin()
+          to label %outer unwind label %outer.dispatch
+
+outer:
+  invoke void @llvm.seh.try.begin()
+          to label %middle unwind label %middle.dispatch
+
+middle:
+  invoke void @llvm.seh.try.begin()
+          to label %inner unwind label %inner.dispatch
+
+inner:
+  invoke void @may_fault(ptr %address)
+          to label %inner.end unwind label %inner.dispatch
+
+inner.end:
+  invoke void @llvm.seh.try.end()
+          to label %middle.end unwind label %inner.dispatch
+
+middle.end:
+  store volatile i32 77, ptr %address
+  invoke void @llvm.seh.try.end()
+          to label %outer.end unwind label %middle.dispatch
+
+outer.end:
+  store volatile i32 88, ptr %address
+  invoke void @llvm.seh.try.end()
+          to label %exit unwind label %outer.dispatch
+
+inner.dispatch:
+  %inner.switch = catchswitch within none [label %inner.handler] unwind label %middle.dispatch
+
+inner.handler:
+  %inner.pad = catchpad within %inner.switch [ptr null]
+  store volatile i32 44, ptr %address
+  br i1 %condition, label %inner.left, label %inner.right
+
+inner.left:
+  store volatile i32 55, ptr %address
+  catchret from %inner.pad to label %middle.end
+
+inner.right:
+  store volatile i32 66, ptr %address
+  catchret from %inner.pad to label %middle.end
+
+middle.dispatch:
+  %middle.switch = catchswitch within none [label %middle.handler] unwind label %outer.dispatch
+
+middle.handler:
+  %middle.pad = catchpad within %middle.switch [ptr null]
+  store volatile i32 99, ptr %address
+  catchret from %middle.pad to label %outer.end
+
+outer.dispatch:
+  %outer.switch = catchswitch within none [label %outer.handler] unwind to caller
+
+outer.handler:
+  %outer.pad = catchpad within %outer.switch [ptr null]
+  store volatile i32 111, ptr %address
+  catchret from %outer.pad to label %exit
+
+exit:
+  store volatile i32 33, ptr %address
+  ret void
+}
+
+; CHECK-LABEL: nested_handler:
+; CHECK: %inner{{$}}
+; CHECK-NEXT: [[INNER_BEGIN:\.Ltmp[0-9]+]]:
+; CHECK: {{(call|bl)}} may_fault
+; CHECK: [[INNER_END:\.Ltmp[0-9]+]]:
+; CHECK: %middle.end{{$}}
+; CHECK-NEXT: [[MIDDLE_BEGIN:\.Ltmp[0-9]+]]:
+; X86: mov dword ptr [{{[^]]+}}], 77
+; AARCH64: mov [[MIDDLE_VALUE:w[0-9]+]], #77
+; AARCH64-NEXT: str [[MIDDLE_VALUE]], [{{[^]]+}}]
+; CHECK-NEXT: [[MIDDLE_END:\.Ltmp[0-9]+]]:
+; CHECK: %outer.end{{$}}
+; CHECK-NEXT: [[OUTER_BEGIN:\.Ltmp[0-9]+]]:
+; X86: mov dword ptr [{{[^]]+}}], 88
+; AARCH64: mov [[OUTER_VALUE:w[0-9]+]], #88
+; AARCH64-NEXT: str [[OUTER_VALUE]], [{{[^]]+}}]
+; CHECK-NEXT: [[OUTER_END:\.Ltmp[0-9]+]]:
+; CHECK: [[INNER_HANDLER:\.LBB[0-9]+_[0-9]+]]: {{.*}}%inner.handler{{$}}
+; CHECK: [[INNER_HANDLER_BEGIN:\.Ltmp[0-9]+]]:
+; X86: mov dword ptr [{{[^]]+}}], 44
+; AARCH64: mov [[INNER_CAUGHT:w[0-9]+]], #44
+; AARCH64-NEXT: str [[INNER_CAUGHT]], [{{[^]]+}}]
+; X86: mov dword ptr [{{[^]]+}}], 55
+; AARCH64: mov [[INNER_LEFT:w[0-9]+]], #55
+; AARCH64-NEXT: str [[INNER_LEFT]], [{{[^]]+}}]
+; X86: mov dword ptr [{{[^]]+}}], 66
+; AARCH64: mov [[INNER_RIGHT:w[0-9]+]], #66
+; AARCH64-NEXT: str [[INNER_RIGHT]], [{{[^]]+}}]
+; CHECK-NEXT: [[INNER_HANDLER_END:\.Ltmp[0-9]+]]:
+; CHECK: [[MIDDLE_HANDLER:\.LBB[0-9]+_[0-9]+]]: {{.*}}%middle.handler{{$}}
+; CHECK: [[MIDDLE_HANDLER_BEGIN:\.Ltmp[0-9]+]]:
+; X86: mov dword ptr [{{[^]]+}}], 99
+; AARCH64: mov [[MIDDLE_CAUGHT:w[0-9]+]], #99
+; AARCH64-NEXT: str [[MIDDLE_CAUGHT]], [{{[^]]+}}]
+; CHECK-NEXT: [[MIDDLE_HANDLER_END:\.Ltmp[0-9]+]]:
+; CHECK: [[OUTER_HANDLER:\.LBB[0-9]+_[0-9]+]]: {{.*}}%outer.handler{{$}}
+; X86: mov dword ptr [{{[^]]+}}], 111
+; AARCH64: mov [[OUTER_CAUGHT:w[0-9]+]], #111
+; AARCH64-NEXT: str [[OUTER_CAUGHT]], [{{[^]]+}}]
+; CHECK: .Llsda_begin{{[0-9]+}}:
+; CHECK-NEXT: {{\.(long|word)}} [[INNER_BEGIN]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} [[INNER_END]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} 1
+; CHECK-NEXT: {{\.(long|word)}} [[INNER_HANDLER]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} [[INNER_BEGIN]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} [[INNER_END]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} 1
+; CHECK-NEXT: {{\.(long|word)}} [[MIDDLE_HANDLER]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} [[INNER_BEGIN]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} [[INNER_END]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} 1
+; CHECK-NEXT: {{\.(long|word)}} [[OUTER_HANDLER]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} [[MIDDLE_BEGIN]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} [[MIDDLE_END]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} 1
+; CHECK-NEXT: {{\.(long|word)}} [[MIDDLE_HANDLER]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} [[MIDDLE_BEGIN]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} [[MIDDLE_END]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} 1
+; CHECK-NEXT: {{\.(long|word)}} [[OUTER_HANDLER]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} [[OUTER_BEGIN]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} [[OUTER_END]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} 1
+; CHECK-NEXT: {{\.(long|word)}} [[OUTER_HANDLER]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} [[INNER_HANDLER_BEGIN]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} [[INNER_HANDLER_END]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} 1
+; CHECK-NEXT: {{\.(long|word)}} [[MIDDLE_HANDLER]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} [[INNER_HANDLER_BEGIN]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} [[INNER_HANDLER_END]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} 1
+; CHECK-NEXT: {{\.(long|word)}} [[OUTER_HANDLER]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} [[MIDDLE_HANDLER_BEGIN]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} [[MIDDLE_HANDLER_END]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} 1
+; CHECK-NEXT: {{\.(long|word)}} [[OUTER_HANDLER]]@IMGREL
+; CHECK-NEXT: .Llsda_end{{[0-9]+}}:
+
+!llvm.module.flags = !{!0}
+!0 = !{i32 1, !"eh-asynch", i32 1}
\ No newline at end of file

>From 9b81b493e641c63ea53b7c0acb328f59a863ef7f Mon Sep 17 00:00:00 2001
From: Yassine Missoum <mmissoum at microsoft.com>
Date: Tue, 15 Sep 2026 16:48:46 -0700
Subject: [PATCH 2/3] [WinEH] Preserve asynchronous SEH regions through
 optimization

Track regions for the existing eh-asynch table-SEH contract through IR sinking and machine-code transformations. Add zero-code region barriers and protected insertion points for PHI copies, register allocation and critical-edge blocks.

Finalize scope ranges in layout order, including trailing branches while excluding unguarded gaps and frame teardown. Preserve branch debug locations when tail merging is declined.

Add cross-target IR and machine regressions plus documentation. Clang emission and new local-unwind APIs are unchanged.

Co-authored-by: Daniel Paoliello <danpao at microsoft.com>
---
 llvm/docs/ExceptionHandling.md                |  33 +++
 llvm/include/llvm/CodeGen/MachineBasicBlock.h |   7 +
 llvm/include/llvm/IR/EHPersonalities.h        |  10 +
 llvm/include/llvm/Support/TargetOpcodes.def   |   2 +
 llvm/include/llvm/Target/Target.td            |  11 +
 llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp    |  11 +-
 llvm/lib/CodeGen/AsmPrinter/WinException.cpp  | 141 ++++++++++--
 llvm/lib/CodeGen/AsmPrinter/WinException.h    |   3 +
 llvm/lib/CodeGen/BranchFolding.cpp            |  24 ++-
 llvm/lib/CodeGen/BranchFolding.h              |   3 +-
 llvm/lib/CodeGen/CodeGenPrepare.cpp           |  13 ++
 llvm/lib/CodeGen/MachineBasicBlock.cpp        |  65 +++++-
 llvm/lib/CodeGen/MachineLICM.cpp              |   9 +-
 llvm/lib/CodeGen/MachineSink.cpp              |  11 +
 llvm/lib/CodeGen/PHIEliminationUtils.cpp      |   2 +-
 llvm/lib/CodeGen/RegAllocFast.cpp             |   8 +
 .../CodeGen/SelectionDAG/SelectionDAGISel.cpp |  46 ++++
 llvm/lib/CodeGen/SplitKit.cpp                 |   6 +-
 llvm/lib/IR/EHPersonalities.cpp               |  80 +++++++
 .../InstCombine/InstructionCombining.cpp      |   4 +
 llvm/test/CodeGen/WinEH/seh-catchpad-state.ll | 100 +++++++--
 .../CodeGen/WinEH/seh-region-preservation.ll  | 203 ++++++++++++++++++
 .../test/CodeGen/X86/seh-region-insertion.mir | 173 +++++++++++++++
 .../InstCombine/seh-region-sinking.ll         | 140 ++++++++++++
 24 files changed, 1057 insertions(+), 48 deletions(-)
 create mode 100644 llvm/test/CodeGen/WinEH/seh-region-preservation.ll
 create mode 100644 llvm/test/CodeGen/X86/seh-region-insertion.mir
 create mode 100644 llvm/test/Transforms/InstCombine/seh-region-sinking.ll

diff --git a/llvm/docs/ExceptionHandling.md b/llvm/docs/ExceptionHandling.md
index 4b6cf835bac7f..3db86620515ce 100644
--- a/llvm/docs/ExceptionHandling.md
+++ b/llvm/docs/ExceptionHandling.md
@@ -500,6 +500,39 @@ to rethrow an exception or continue unwinding.  Therefore, LLVM must use the IR
 constructs described later in this document to implement compatible exception
 handling.
 
+### Preserving asynchronous SEH regions
+
+For table-based SEH with the `eh-asynch` module flag, invokes of
+`llvm.seh.try.begin` and `llvm.seh.try.end` describe protected regions.
+The handler selected for a fault depends on the instruction address in the
+emitted scope table, not just on the unwind destination of the nearest call.
+Consequently, describing only the calls is insufficient for this mode.
+
+`SEHTryRegionInfo` associates IR blocks with their protecting EH pad. Its
+region comparison is conservative for unreachable blocks or ambiguous
+nesting. The result is a snapshot: consumers must recompute it after changing
+the CFG or region markers. InstCombine and CodeGenPrepare use it when deciding
+whether to sink instructions between blocks. The query does not enable new
+behavior for other personalities or for modules without `eh-asynch`.
+
+Instruction selection represents machine region boundaries with EH labels
+and `SEH_REGION_BARRIER`. The barrier participates in memory dependencies and
+cannot be duplicated, but emits no code. Machine instruction motion must
+respect region membership as well as these boundaries. PHI copies, spills,
+and reloads belonging to a block must be inserted inside its protected range;
+critical-edge splitting must carry the region and create corresponding labels.
+
+Scope ranges are finalized in machine layout order. A range may extend over
+the block's trailing branches, but not its return or frame teardown. Separate
+runs must remain separate when an unguarded block lies between them, and an
+end label moved past such a boundary must be clamped. Empty ranges need no
+scope record. A handler executes in its enclosing region rather than the
+region it handles, including when its body spans multiple blocks.
+
+These mechanisms consume existing IR. They do not introduce new local-unwind
+intrinsics, change Clang's marker emission, or change the language rules for
+undefined behavior, volatile accesses, or `nounwind`.
+
 ### SEH filter expressions
 
 The SEH personality functions also use funclets to implement filter expressions,
diff --git a/llvm/include/llvm/CodeGen/MachineBasicBlock.h b/llvm/include/llvm/CodeGen/MachineBasicBlock.h
index d5c31c4b7281b..a29317e4e2930 100644
--- a/llvm/include/llvm/CodeGen/MachineBasicBlock.h
+++ b/llvm/include/llvm/CodeGen/MachineBasicBlock.h
@@ -925,6 +925,13 @@ class MachineBasicBlock
     return const_cast<MachineBasicBlock *>(this)->getFirstTerminator();
   }
 
+  LLVM_ABI iterator getInsertPtBeforeTerminators();
+  LLVM_ABI bool hasSameSEHRegion(const MachineBasicBlock &Other) const;
+  const_iterator getInsertPtBeforeTerminators() const {
+    return const_cast<MachineBasicBlock *>(this)
+        ->getInsertPtBeforeTerminators();
+  }
+
   /// Same getFirstTerminator but it ignores bundles and return an
   /// instr_iterator instead.
   LLVM_ABI instr_iterator getFirstInstrTerminator();
diff --git a/llvm/include/llvm/IR/EHPersonalities.h b/llvm/include/llvm/IR/EHPersonalities.h
index 39f6817b3dc38..95622a3213efe 100644
--- a/llvm/include/llvm/IR/EHPersonalities.h
+++ b/llvm/include/llvm/IR/EHPersonalities.h
@@ -12,6 +12,7 @@
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/TinyPtrVector.h"
 #include "llvm/Support/Compiler.h"
+#include <optional>
 
 namespace llvm {
 class BasicBlock;
@@ -107,6 +108,15 @@ inline bool isNoOpWithoutInvoke(EHPersonality Pers) {
 
 LLVM_ABI bool canSimplifyInvokeNoUnwind(const Function *F);
 
+class LLVM_ABI SEHTryRegionInfo {
+public:
+  explicit SEHTryRegionInfo(const Function &F);
+  bool isSameRegion(const BasicBlock *From, const BasicBlock *To) const;
+
+private:
+  DenseMap<const BasicBlock *, std::optional<const BasicBlock *>> RegionOf;
+};
+
 typedef TinyPtrVector<BasicBlock *> ColorVector;
 
 /// If an EH funclet personality is in use (see isFuncletEHPersonality),
diff --git a/llvm/include/llvm/Support/TargetOpcodes.def b/llvm/include/llvm/Support/TargetOpcodes.def
index 314c2b277a5f8..dbabed8169c47 100644
--- a/llvm/include/llvm/Support/TargetOpcodes.def
+++ b/llvm/include/llvm/Support/TargetOpcodes.def
@@ -235,6 +235,8 @@ HANDLE_TARGET_OPCODE(FAKE_USE)
 // barrier, but does not correspond to any generated instruction.
 HANDLE_TARGET_OPCODE(MEMBARRIER)
 
+HANDLE_TARGET_OPCODE(SEH_REGION_BARRIER)
+
 // Provides information about what jump table the following indirect branch is
 // using.
 HANDLE_TARGET_OPCODE(JUMP_TABLE_DEBUG_INFO)
diff --git a/llvm/include/llvm/Target/Target.td b/llvm/include/llvm/Target/Target.td
index 279de17d00da5..6a405d89ec2b8 100644
--- a/llvm/include/llvm/Target/Target.td
+++ b/llvm/include/llvm/Target/Target.td
@@ -1678,6 +1678,17 @@ def MEMBARRIER : StandardPseudoInstruction {
   let Size = 0;
   let isMeta = true;
 }
+def SEH_REGION_BARRIER : StandardPseudoInstruction {
+  let OutOperandList = (outs);
+  let InOperandList = (ins);
+  let AsmString = "";
+  let hasSideEffects = true;
+  let mayLoad = true;
+  let mayStore = true;
+  let hasCtrlDep = true;
+  let isNotDuplicable = true;
+  let Size = 0;
+}
 def JUMP_TABLE_DEBUG_INFO : StandardPseudoInstruction {
   let OutOperandList = (outs);
   let InOperandList = (ins i64imm:$jti);
diff --git a/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp b/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
index fe034ac8c97c5..859e2023ec535 100644
--- a/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
@@ -2191,6 +2191,7 @@ void AsmPrinter::emitFunctionBody() {
         {
           auto MI2 = std::next(MI.getIterator());
           if (IsEHa && MI2 != MBB.end() &&
+              MI2->getOpcode() != TargetOpcode::SEH_REGION_BARRIER &&
               (MI2->mayLoadOrStore() || MI2->mayRaiseFPException()))
             emitNops(1);
         }
@@ -2238,6 +2239,10 @@ void AsmPrinter::emitFunctionBody() {
         if (isVerbose())
           OutStreamer->emitRawComment("ARITH_FENCE");
         break;
+      case TargetOpcode::SEH_REGION_BARRIER:
+        if (isVerbose())
+          OutStreamer->emitRawComment("SEH_REGION_BARRIER");
+        break;
       case TargetOpcode::MEMBARRIER:
         OutStreamer->emitRawComment("MEMBARRIER");
         break;
@@ -2367,7 +2372,11 @@ void AsmPrinter::emitFunctionBody() {
     // we have BBLabels enabled or if this basic blocks marks the end of a
     // section.
     if (MF->getTarget().Options.BBAddrMap ||
-        (MAI.hasDotTypeDotSizeDirective() && MBB.isEndSection()))
+        (MAI.hasDotTypeDotSizeDirective() && MBB.isEndSection()) ||
+        (MF->getFunction().getParent()->getModuleFlag("eh-asynch") &&
+         MF->getFunction().hasPersonalityFn() &&
+         classifyEHPersonality(MF->getFunction().getPersonalityFn()) ==
+             EHPersonality::MSVC_TableSEH))
       OutStreamer->emitLabel(MBB.getEndSymbol());
 
     if (MBB.isEndSection()) {
diff --git a/llvm/lib/CodeGen/AsmPrinter/WinException.cpp b/llvm/lib/CodeGen/AsmPrinter/WinException.cpp
index 3395e6da6db5a..d510a96fa240d 100644
--- a/llvm/lib/CodeGen/AsmPrinter/WinException.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/WinException.cpp
@@ -63,6 +63,8 @@ void WinException::endModule() {
 
 void WinException::beginFunction(const MachineFunction *MF) {
   shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
+  SEHScopeEndLabels.clear();
+  SEHLabelPositions.clear();
 
   // If any landing pads survive, we need an EH table.
   bool hasLandingPads = !MF->getLandingPads().empty();
@@ -82,6 +84,42 @@ void WinException::beginFunction(const MachineFunction *MF) {
     Per = classifyEHPersonality(PerFn);
   }
 
+  if (Per == EHPersonality::MSVC_TableSEH &&
+      F.getParent()->getModuleFlag("eh-asynch")) {
+    const WinEHFuncInfo *EHInfo = MF->getWinEHFuncInfo();
+    SmallPtrSet<const MCSymbol *, 16> RangeEnds;
+    for (const auto &Range : EHInfo->LabelToStateMap)
+      if (Range.second.first >= 0)
+        RangeEnds.insert(Range.second.second);
+    unsigned Position = 0;
+    for (const MachineBasicBlock &MBB : *MF) {
+      for (const MachineInstr &MI : MBB) {
+        if (MI.isEHLabel())
+          SEHLabelPositions[MI.getOperand(0).getMCSymbol()] = Position;
+        else if (!MI.isMetaInstruction() &&
+                 MI.getOpcode() != TargetOpcode::SEH_REGION_BARRIER)
+          ++Position;
+      }
+      SEHLabelPositions[MBB.getEndSymbol()] = Position;
+      bool HasBranch = false;
+      for (const MachineInstr &MI : reverse(MBB)) {
+        if (MI.isEHLabel()) {
+          const MCSymbol *Label = MI.getOperand(0).getMCSymbol();
+          if (HasBranch && RangeEnds.contains(Label))
+            SEHScopeEndLabels[Label] = MBB.getEndSymbol();
+          break;
+        }
+        if (MI.isMetaInstruction() ||
+            MI.getOpcode() == TargetOpcode::SEH_REGION_BARRIER)
+          continue;
+        if (!MI.isBranch() || MI.isCall() || MI.isReturn() ||
+            MI.getFlag(MachineInstr::FrameDestroy))
+          break;
+        HasBranch = true;
+      }
+    }
+  }
+
   bool forceEmitPersonality = F.hasPersonalityFn() &&
                               !isNoOpWithoutInvoke(Per) &&
                               F.needsUnwindTableEntry();
@@ -395,12 +433,13 @@ struct InvokeStateChange {
 /// reported is the first change to something other than NullState, and a
 /// change back to NullState is always reported at the end of iteration).
 class InvokeStateChangeIterator {
-  InvokeStateChangeIterator(const WinEHFuncInfo &EHInfo,
-                            MachineFunction::const_iterator MFI,
-                            MachineFunction::const_iterator MFE,
-                            MachineBasicBlock::const_iterator MBBI,
-                            int BaseState)
-      : EHInfo(EHInfo), MFI(MFI), MFE(MFE), MBBI(MBBI), BaseState(BaseState) {
+  InvokeStateChangeIterator(
+      const WinEHFuncInfo &EHInfo, MachineFunction::const_iterator MFI,
+      MachineFunction::const_iterator MFE,
+      MachineBasicBlock::const_iterator MBBI, int BaseState,
+      const DenseMap<const MCSymbol *, unsigned> *Positions)
+      : EHInfo(EHInfo), MFI(MFI), MFE(MFE), MBBI(MBBI), BaseState(BaseState),
+        Positions(Positions) {
     LastStateChange.PreviousEndLabel = nullptr;
     LastStateChange.NewStartLabel = nullptr;
     LastStateChange.NewState = BaseState;
@@ -410,15 +449,17 @@ class InvokeStateChangeIterator {
 public:
   static iterator_range<InvokeStateChangeIterator>
   range(const WinEHFuncInfo &EHInfo, MachineFunction::const_iterator Begin,
-        MachineFunction::const_iterator End, int BaseState = NullState) {
+        MachineFunction::const_iterator End, int BaseState = NullState,
+        const DenseMap<const MCSymbol *, unsigned> *Positions = nullptr) {
     // Reject empty ranges to simplify bookkeeping by ensuring that we can get
     // the end of the last block.
     assert(Begin != End);
     auto BlockBegin = Begin->begin();
     auto BlockEnd = std::prev(End)->end();
-    return make_range(
-        InvokeStateChangeIterator(EHInfo, Begin, End, BlockBegin, BaseState),
-        InvokeStateChangeIterator(EHInfo, End, End, BlockEnd, BaseState));
+    return make_range(InvokeStateChangeIterator(EHInfo, Begin, End, BlockBegin,
+                                                BaseState, Positions),
+                      InvokeStateChangeIterator(EHInfo, End, End, BlockEnd,
+                                                BaseState, Positions));
   }
 
   // Iterator methods.
@@ -447,6 +488,35 @@ class InvokeStateChangeIterator {
 private:
   InvokeStateChangeIterator &scan();
 
+  const MCSymbol *clampEnd(const MCSymbol *End,
+                           const MCSymbol *Boundary) const {
+    if (!Positions || !End)
+      return End;
+    auto EndPosition = Positions->find(End);
+    auto BoundaryPosition = Positions->find(Boundary);
+    if (EndPosition != Positions->end() &&
+        BoundaryPosition != Positions->end() &&
+        EndPosition->second > BoundaryPosition->second)
+      return Boundary;
+    return End;
+  }
+
+  bool isUnlabelledSEHGap(const MachineBasicBlock &MBB) const {
+    if (!Positions)
+      return false;
+    auto State = EHInfo.BlockToStateMap.find(MBB.getBasicBlock());
+    if (State == EHInfo.BlockToStateMap.end() || State->second != BaseState)
+      return false;
+    for (const MachineInstr &MI : MBB)
+      if (MI.isEHLabel() &&
+          EHInfo.LabelToStateMap.contains(MI.getOperand(0).getMCSymbol()))
+        return false;
+    return any_of(MBB, [](const MachineInstr &MI) {
+      return !MI.isMetaInstruction() &&
+             MI.getOpcode() != TargetOpcode::SEH_REGION_BARRIER;
+    });
+  }
+
   const WinEHFuncInfo &EHInfo;
   const MCSymbol *CurrentEndLabel = nullptr;
   MachineFunction::const_iterator MFI;
@@ -455,6 +525,9 @@ class InvokeStateChangeIterator {
   InvokeStateChange LastStateChange;
   bool VisitingInvoke = false;
   int BaseState;
+  const DenseMap<const MCSymbol *, unsigned> *Positions;
+  const MachineBasicBlock *StateCheckedBlock = nullptr;
+  bool SawFrameDestroy = false;
 };
 
 } // end anonymous namespace
@@ -464,8 +537,23 @@ InvokeStateChangeIterator &InvokeStateChangeIterator::scan() {
   for (; MFI != MFE; ++MFI, IsNewBlock = true) {
     if (IsNewBlock)
       MBBI = MFI->begin();
+    if (StateCheckedBlock != &*MFI) {
+      StateCheckedBlock = &*MFI;
+      if (LastStateChange.NewState != BaseState && isUnlabelledSEHGap(*MFI)) {
+        LastStateChange.PreviousEndLabel =
+            clampEnd(CurrentEndLabel, std::prev(MFI)->getEndSymbol());
+        LastStateChange.NewStartLabel = nullptr;
+        LastStateChange.NewState = BaseState;
+        CurrentEndLabel = nullptr;
+        VisitingInvoke = false;
+        SawFrameDestroy = false;
+        return *this;
+      }
+    }
     for (auto MBBE = MFI->end(); MBBI != MBBE; ++MBBI) {
       const MachineInstr &MI = *MBBI;
+      if (Positions && MI.getFlag(MachineInstr::FrameDestroy))
+        SawFrameDestroy = true;
       if (!VisitingInvoke && LastStateChange.NewState != BaseState &&
           MI.isCall() && !EHStreamer::callToNoUnwindFunction(&MI)) {
         // Indicate a change of state to the null state.  We don't have
@@ -498,17 +586,28 @@ InvokeStateChangeIterator &InvokeStateChangeIterator::scan() {
       // we know not to treat the inoke we'll see as unwinding to caller.
       VisitingInvoke = true;
       if (NewState == LastStateChange.NewState) {
+        if (SawFrameDestroy && NewState != BaseState) {
+          LastStateChange.PreviousEndLabel = clampEnd(CurrentEndLabel, Label);
+          LastStateChange.NewStartLabel = nullptr;
+          LastStateChange.NewState = BaseState;
+          CurrentEndLabel = nullptr;
+          VisitingInvoke = false;
+          SawFrameDestroy = false;
+          return *this;
+        }
         // The state isn't actually changing here.  Record the new end and
         // keep going.
         CurrentEndLabel = StateAndEnd.second;
+        SawFrameDestroy = false;
         continue;
       }
       // Found a state change to report
-      LastStateChange.PreviousEndLabel = CurrentEndLabel;
+      LastStateChange.PreviousEndLabel = clampEnd(CurrentEndLabel, Label);
       LastStateChange.NewStartLabel = Label;
       LastStateChange.NewState = NewState;
       // Start keeping track of the new current end
       CurrentEndLabel = StateAndEnd.second;
+      SawFrameDestroy = false;
       // Don't re-visit this instr on the next scan
       ++MBBI;
       return *this;
@@ -609,13 +708,17 @@ void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
   MachineFunction::const_iterator Stop = std::next(MF->begin());
   while (Stop != End && !Stop->isEHFuncletEntry())
     ++Stop;
-  for (const auto &StateChange :
-       InvokeStateChangeIterator::range(FuncInfo, MF->begin(), Stop)) {
+  for (const auto &StateChange : InvokeStateChangeIterator::range(
+           FuncInfo, MF->begin(), Stop, NullState,
+           SEHLabelPositions.empty() ? nullptr : &SEHLabelPositions)) {
     // Emit all the actions for the state we just transitioned out of
     // if it was not the null state
-    if (LastEHState != -1)
-      emitSEHActionsForRange(FuncInfo, LastStartLabel,
-                             StateChange.PreviousEndLabel, LastEHState);
+    if (LastEHState != -1) {
+      const MCSymbol *EndLabel = StateChange.PreviousEndLabel;
+      if (MCSymbol *ExtendedEnd = SEHScopeEndLabels.lookup(EndLabel))
+        EndLabel = ExtendedEnd;
+      emitSEHActionsForRange(FuncInfo, LastStartLabel, EndLabel, LastEHState);
+    }
     LastStartLabel = StateChange.NewStartLabel;
     LastEHState = StateChange.NewState;
   }
@@ -635,6 +738,12 @@ void WinException::emitSEHActionsForRange(const WinEHFuncInfo &FuncInfo,
   };
 
   assert(BeginLabel && EndLabel);
+  auto BeginPosition = SEHLabelPositions.find(BeginLabel);
+  auto EndPosition = SEHLabelPositions.find(EndLabel);
+  if (BeginPosition != SEHLabelPositions.end() &&
+      EndPosition != SEHLabelPositions.end() &&
+      BeginPosition->second >= EndPosition->second)
+    return;
   while (State != -1) {
     const SEHUnwindMapEntry &UME = FuncInfo.SEHUnwindMap[State];
     const MCExpr *FilterOrFinally;
diff --git a/llvm/lib/CodeGen/AsmPrinter/WinException.h b/llvm/lib/CodeGen/AsmPrinter/WinException.h
index 47dd30cef133d..fd450a46ab390 100644
--- a/llvm/lib/CodeGen/AsmPrinter/WinException.h
+++ b/llvm/lib/CodeGen/AsmPrinter/WinException.h
@@ -51,6 +51,9 @@ class LLVM_LIBRARY_VISIBILITY WinException : public EHStreamer {
   /// The list of symbols to add to the ehcont section
   std::vector<const MCSymbol *> EHContTargets;
 
+  DenseMap<const MCSymbol *, MCSymbol *> SEHScopeEndLabels;
+  DenseMap<const MCSymbol *, unsigned> SEHLabelPositions;
+
   void emitCSpecificHandlerTable(const MachineFunction *MF);
 
   void emitSEHActionsForRange(const WinEHFuncInfo &FuncInfo,
diff --git a/llvm/lib/CodeGen/BranchFolding.cpp b/llvm/lib/CodeGen/BranchFolding.cpp
index 62920dac7a4d5..81b2ee2dd69f9 100644
--- a/llvm/lib/CodeGen/BranchFolding.cpp
+++ b/llvm/lib/CodeGen/BranchFolding.cpp
@@ -234,6 +234,12 @@ void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
   EHScopeMembership.erase(MBB);
 }
 
+static bool hasSEHRegionBoundary(const MachineBasicBlock &MBB) {
+  return any_of(MBB, [](const MachineInstr &MI) {
+    return MI.getOpcode() == TargetOpcode::SEH_REGION_BARRIER;
+  });
+}
+
 bool BranchFolder::OptimizeFunction(MachineFunction &MF,
                                     const TargetInstrInfo *tii,
                                     const TargetRegisterInfo *tri,
@@ -649,6 +655,10 @@ ProfitableToMerge(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2,
       return false;
   }
 
+  if (hasSEHRegionBoundary(*MBB1) || hasSEHRegionBoundary(*MBB2) ||
+      !MBB1->hasSameSEHRegion(*MBB2))
+    return false;
+
   CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2);
   if (CommonTailLen == 0)
     return false;
@@ -778,8 +788,7 @@ unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
 
 void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
                                         MachineBasicBlock *SuccBB,
-                                        MachineBasicBlock *PredBB,
-                                        const DebugLoc &BranchDL) {
+                                        MachineBasicBlock *PredBB) {
   MPIterator CurMPIter, B;
   for (CurMPIter = std::prev(MergePotentials.end()),
       B = MergePotentials.begin();
@@ -787,7 +796,7 @@ void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
     // Put the unconditional branch back, if we need one.
     MachineBasicBlock *CurMBB = CurMPIter->getBlock();
     if (SuccBB && CurMBB != PredBB)
-      FixTail(CurMBB, SuccBB, TII, BranchDL);
+      FixTail(CurMBB, SuccBB, TII, CurMPIter->getBranchDebugLoc());
     if (CurMPIter == B)
       break;
   }
@@ -1012,7 +1021,6 @@ bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,
   // Walk through equivalence sets looking for actual exact matches.
   while (MergePotentials.size() > 1) {
     unsigned CurHash = MergePotentials.back().getHash();
-    const DebugLoc &BranchDL = MergePotentials.back().getBranchDebugLoc();
 
     // Build SameTails, identifying the set of blocks with this hash code
     // and with the maximum number of instructions in common.
@@ -1023,7 +1031,7 @@ bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,
     // If we didn't find any pair that has at least MinCommonTailLength
     // instructions in common, remove all blocks with this hash code and retry.
     if (SameTails.empty()) {
-      RemoveBlocksWithHash(CurHash, SuccBB, PredBB, BranchDL);
+      RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
       continue;
     }
 
@@ -1070,7 +1078,7 @@ bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,
       // Split a block so that one does.
       if (!CreateCommonTailOnlyBlock(PredBB, SuccBB,
                                      maxCommonTailLength, commonTailIndex)) {
-        RemoveBlocksWithHash(CurHash, SuccBB, PredBB, BranchDL);
+        RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
         continue;
       }
     }
@@ -2056,6 +2064,10 @@ bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock *MBB) {
   if (TBB->pred_size() > 1 || FBB->pred_size() > 1)
     return false;
 
+  if (hasSEHRegionBoundary(*TBB) || hasSEHRegionBoundary(*FBB) ||
+      !MBB->hasSameSEHRegion(*TBB) || !MBB->hasSameSEHRegion(*FBB))
+    return false;
+
   // Find a suitable position to hoist the common instructions to. Also figure
   // out which registers are used or defined by instructions from the insertion
   // point to the end of the block.
diff --git a/llvm/lib/CodeGen/BranchFolding.h b/llvm/lib/CodeGen/BranchFolding.h
index f57211a34b0bc..be8c119442500 100644
--- a/llvm/lib/CodeGen/BranchFolding.h
+++ b/llvm/lib/CodeGen/BranchFolding.h
@@ -174,8 +174,7 @@ class TargetRegisterInfo;
     /// Remove all blocks with hash CurHash from MergePotentials, restoring
     /// branches at ends of blocks as appropriate.
     void RemoveBlocksWithHash(unsigned CurHash, MachineBasicBlock *SuccBB,
-                              MachineBasicBlock *PredBB,
-                              const DebugLoc &BranchDL);
+                              MachineBasicBlock *PredBB);
 
     /// None of the blocks to be tail-merged consist only of the common tail.
     /// Create a block that does by splitting one.
diff --git a/llvm/lib/CodeGen/CodeGenPrepare.cpp b/llvm/lib/CodeGen/CodeGenPrepare.cpp
index 3e0b8a956ca81..4379184785c7d 100644
--- a/llvm/lib/CodeGen/CodeGenPrepare.cpp
+++ b/llvm/lib/CodeGen/CodeGenPrepare.cpp
@@ -55,6 +55,7 @@
 #include "llvm/IR/DebugInfo.h"
 #include "llvm/IR/DerivedTypes.h"
 #include "llvm/IR/Dominators.h"
+#include "llvm/IR/EHPersonalities.h"
 #include "llvm/IR/Function.h"
 #include "llvm/IR/GetElementPtrTypeIterator.h"
 #include "llvm/IR/GlobalValue.h"
@@ -1431,6 +1432,7 @@ bool CodeGenPrepare::simplifyOffsetableRelocate(GCStatepointInst &I) {
 /// Sink the specified cast instruction into its user blocks.
 static bool SinkCast(CastInst *CI) {
   BasicBlock *DefBB = CI->getParent();
+  SEHTryRegionInfo SEHRegions(*CI->getFunction());
 
   /// InsertedCasts - Only insert a cast in each block once.
   DenseMap<BasicBlock *, CastInst *> InsertedCasts;
@@ -1467,6 +1469,9 @@ static bool SinkCast(CastInst *CI) {
       continue;
 
     // If we have already inserted a cast into this block, use it.
+    if (!SEHRegions.isSameRegion(DefBB, UserBB))
+      continue;
+
     CastInst *&InsertedCast = InsertedCasts[UserBB];
 
     if (!InsertedCast) {
@@ -1944,6 +1949,7 @@ static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI,
 
   // Only insert a cmp in each block once.
   DenseMap<BasicBlock *, CmpInst *> InsertedCmps;
+  SEHTryRegionInfo SEHRegions(*Cmp->getFunction());
 
   bool MadeChange = false;
   for (Instruction::user_iterator UI = Cmp->user_begin(), E = Cmp->user_end();
@@ -1967,6 +1973,9 @@ static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI,
       continue;
 
     // If we have already inserted a cmp into this block, use it.
+    if (!SEHRegions.isSameRegion(DefBB, UserBB))
+      continue;
+
     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
 
     if (!InsertedCmp) {
@@ -2358,6 +2367,7 @@ static bool sinkAndCmp0Expression(Instruction *AndI, const TargetLowering &TLI,
       AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
     return false;
 
+  SEHTryRegionInfo SEHRegions(*AndI->getFunction());
   for (auto *U : AndI->users()) {
     Instruction *User = cast<Instruction>(U);
 
@@ -2365,6 +2375,9 @@ static bool sinkAndCmp0Expression(Instruction *AndI, const TargetLowering &TLI,
     if (!isa<ICmpInst>(User))
       return false;
 
+    if (!SEHRegions.isSameRegion(AndI->getParent(), User->getParent()))
+      return false;
+
     auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
     if (!CmpC || !CmpC->isZero())
       return false;
diff --git a/llvm/lib/CodeGen/MachineBasicBlock.cpp b/llvm/lib/CodeGen/MachineBasicBlock.cpp
index fe9f9a52c3d7b..b6d8174023149 100644
--- a/llvm/lib/CodeGen/MachineBasicBlock.cpp
+++ b/llvm/lib/CodeGen/MachineBasicBlock.cpp
@@ -28,9 +28,12 @@
 #include "llvm/CodeGen/TargetLowering.h"
 #include "llvm/CodeGen/TargetRegisterInfo.h"
 #include "llvm/CodeGen/TargetSubtargetInfo.h"
+#include "llvm/CodeGen/WinEHFuncInfo.h"
 #include "llvm/Config/llvm-config.h"
 #include "llvm/IR/BasicBlock.h"
+#include "llvm/IR/EHPersonalities.h"
 #include "llvm/IR/IRPrintingPasses.h"
+#include "llvm/IR/Module.h"
 #include "llvm/IR/ModuleSlotTracker.h"
 #include "llvm/MC/MCAsmInfo.h"
 #include "llvm/MC/MCContext.h"
@@ -251,6 +254,37 @@ MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
   return I;
 }
 
+bool MachineBasicBlock::hasSameSEHRegion(const MachineBasicBlock &Other) const {
+  const Function &Function = getParent()->getFunction();
+  if (!Function.getParent()->getModuleFlag("eh-asynch") ||
+      !Function.hasPersonalityFn() ||
+      classifyEHPersonality(Function.getPersonalityFn()) !=
+          EHPersonality::MSVC_TableSEH)
+    return true;
+  const WinEHFuncInfo *EHInfo = getParent()->getWinEHFuncInfo();
+  if (!EHInfo || EHInfo->BlockToStateMap.empty())
+    return true;
+  auto From = EHInfo->BlockToStateMap.find(getBasicBlock());
+  auto To = EHInfo->BlockToStateMap.find(Other.getBasicBlock());
+  return From != EHInfo->BlockToStateMap.end() &&
+         To != EHInfo->BlockToStateMap.end() && From->second == To->second;
+}
+
+MachineBasicBlock::iterator MachineBasicBlock::getInsertPtBeforeTerminators() {
+  iterator InsertPt = getFirstTerminator();
+  while (InsertPt != begin()) {
+    iterator Marker = std::prev(InsertPt);
+    while (Marker != begin() && Marker->isDebugInstr())
+      --Marker;
+    if (Marker->getOpcode() != TargetOpcode::SEH_REGION_BARRIER)
+      break;
+    InsertPt = Marker;
+    if (InsertPt != begin() && std::prev(InsertPt)->isEHLabel())
+      --InsertPt;
+  }
+  return InsertPt;
+}
+
 MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
   instr_iterator B = instr_begin(), E = instr_end(), I = E;
   while (I != B && ((--I)->isTerminator() || I->isDebugInstr()))
@@ -1201,7 +1235,14 @@ MachineBasicBlock *MachineBasicBlock::SplitCriticalEdge(
   MachineFunction *MF = getParent();
   MachineBasicBlock *PrevFallthrough = getNextNode();
 
-  MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
+  const BasicBlock *EdgeBB = nullptr;
+  const Function &Function = MF->getFunction();
+  if (Function.getParent()->getModuleFlag("eh-asynch") &&
+      Function.hasPersonalityFn() &&
+      classifyEHPersonality(Function.getPersonalityFn()) ==
+          EHPersonality::MSVC_TableSEH)
+    EdgeBB = getBasicBlock();
+  MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock(EdgeBB);
   NMBB->setCallFrameSize(Succ->getCallFrameSize());
 
   // Is there an indirect jump with jump table?
@@ -1289,6 +1330,28 @@ MachineBasicBlock *MachineBasicBlock::SplitCriticalEdge(
     TII->insertBranch(*NMBB, Succ, nullptr, Cond, DL);
   }
 
+  if (EdgeBB) {
+    if (WinEHFuncInfo *EHInfo = MF->getWinEHFuncInfo()) {
+      auto State = EHInfo->BlockToStateMap.find(EdgeBB);
+      if (State != EHInfo->BlockToStateMap.end() && State->second >= 0) {
+        SlotIndexUpdateDelegate SlotUpdater(*MF, Indexes);
+        const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
+        auto InsertPt = NMBB->getFirstTerminator();
+        MCSymbol *BeginLabel = MF->getContext().createTempSymbol();
+        MCSymbol *EndLabel = MF->getContext().createTempSymbol();
+        EHInfo->addIPToStateRange(State->second, BeginLabel, EndLabel);
+        BuildMI(*NMBB, InsertPt, DebugLoc(),
+                TII->get(TargetOpcode::SEH_REGION_BARRIER));
+        BuildMI(*NMBB, InsertPt, DebugLoc(), TII->get(TargetOpcode::EH_LABEL))
+            .addSym(BeginLabel);
+        BuildMI(*NMBB, InsertPt, DebugLoc(), TII->get(TargetOpcode::EH_LABEL))
+            .addSym(EndLabel);
+        BuildMI(*NMBB, InsertPt, DebugLoc(),
+                TII->get(TargetOpcode::SEH_REGION_BARRIER));
+      }
+    }
+  }
+
   // Fix PHI nodes in Succ so they refer to NMBB instead of this.
   Succ->replacePhiUsesWith(this, NMBB);
 
diff --git a/llvm/lib/CodeGen/MachineLICM.cpp b/llvm/lib/CodeGen/MachineLICM.cpp
index 6435bbb9382c1..7b48fa63d8a28 100644
--- a/llvm/lib/CodeGen/MachineLICM.cpp
+++ b/llvm/lib/CodeGen/MachineLICM.cpp
@@ -745,7 +745,9 @@ void MachineLICMImpl::HoistPostRA(MachineInstr *MI, Register Def,
 
   // Splice the instruction to the preheader.
   MachineBasicBlock *MBB = MI->getParent();
-  Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
+  if (!MBB->hasSameSEHRegion(*Preheader))
+    return;
+  Preheader->splice(Preheader->getInsertPtBeforeTerminators(), MBB, MI);
 
   // Since we are moving the instruction out of its basic block, we do not
   // retain its debug location. Doing so would degrade the debugging
@@ -1611,6 +1613,8 @@ bool MachineLICMImpl::MayCSE(MachineInstr *MI) {
 unsigned MachineLICMImpl::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader,
                                 MachineLoop *CurLoop) {
   MachineBasicBlock *SrcBlock = MI->getParent();
+  if (!SrcBlock->hasSameSEHRegion(*Preheader))
+    return 0;
 
   // Disable the instruction hoisting due to block hotness
   if ((DisableHoistingToHotterBlocks == UseBFI::All ||
@@ -1672,7 +1676,8 @@ unsigned MachineLICMImpl::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader,
 
   if (!HasCSEDone) {
     // Otherwise, splice the instruction to the preheader.
-    Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
+    Preheader->splice(Preheader->getInsertPtBeforeTerminators(),
+                      MI->getParent(), MI);
 
     // Since we are moving the instruction out of its basic block, we do not
     // retain its debug location. Doing so would degrade the debugging
diff --git a/llvm/lib/CodeGen/MachineSink.cpp b/llvm/lib/CodeGen/MachineSink.cpp
index cbd2598a47210..00ce3733d88c0 100644
--- a/llvm/lib/CodeGen/MachineSink.cpp
+++ b/llvm/lib/CodeGen/MachineSink.cpp
@@ -1498,6 +1498,9 @@ MachineSinking::FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
   if (SuccToSinkTo && SuccToSinkTo->isEHPad())
     return nullptr;
 
+  if (SuccToSinkTo && !MBB->hasSameSEHRegion(*SuccToSinkTo))
+    return nullptr;
+
   // It ought to be okay to sink instructions into an INLINEASM_BR target, but
   // only if we make sure that MI occurs _before_ an INLINEASM_BR instruction in
   // the source block (which this code does not yet do). So for now, forbid
@@ -1788,6 +1791,8 @@ bool MachineSinking::aggressivelySinkIntoCycle(
     }
 
     MachineBasicBlock *SinkBlock = MI->getParent();
+    if (!I.getParent()->hasSameSEHRegion(*SinkBlock))
+      continue;
     MachineInstr *NewMI = nullptr;
     SinkItem MapEntry(&I, SinkBlock);
 
@@ -2335,6 +2340,12 @@ bool PostRAMachineSinkingImpl::tryToSinkCopy(MachineBasicBlock &CurBB,
     assert((SuccBB->pred_size() == 1 && *SuccBB->pred_begin() == &CurBB) &&
            "Unexpected predecessor");
 
+    if (!CurBB.hasSameSEHRegion(*SuccBB)) {
+      LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
+                                        TRI);
+      continue;
+    }
+
     // Collect DBG_VALUEs that must sink with this copy. We've previously
     // recorded which reg units that DBG_VALUEs read, if this instruction
     // writes any of those units then the corresponding DBG_VALUEs must sink.
diff --git a/llvm/lib/CodeGen/PHIEliminationUtils.cpp b/llvm/lib/CodeGen/PHIEliminationUtils.cpp
index 84aff6f5cbc58..b89566264c2b2 100644
--- a/llvm/lib/CodeGen/PHIEliminationUtils.cpp
+++ b/llvm/lib/CodeGen/PHIEliminationUtils.cpp
@@ -49,7 +49,7 @@ llvm::findPHICopyInsertPoint(MachineBasicBlock* MBB, MachineBasicBlock* SuccMBB,
   // any INLINEASM_BR, we may not need any specialized handling.
   bool EHPadSuccessor = SuccMBB->isEHPad();
   if (!EHPadSuccessor && !hasInlineAsmBrToSuccessor(MBB, SuccMBB))
-    return MBB->getFirstTerminator();
+    return MBB->getInsertPtBeforeTerminators();
 
   // Discover any defs in this basic block.
   SmallPtrSet<MachineInstr *, 8> DefsInMBB;
diff --git a/llvm/lib/CodeGen/RegAllocFast.cpp b/llvm/lib/CodeGen/RegAllocFast.cpp
index 524ed5e069941..a893162421956 100644
--- a/llvm/lib/CodeGen/RegAllocFast.cpp
+++ b/llvm/lib/CodeGen/RegAllocFast.cpp
@@ -685,6 +685,14 @@ MachineBasicBlock::iterator RegAllocFastImpl::getMBBBeginInsertionPoint(
     MachineBasicBlock &MBB, SmallSet<Register, 2> &PrologLiveIns) const {
   MachineBasicBlock::iterator I = MBB.begin();
   while (I != MBB.end()) {
+    if (I->isEHLabel() && std::next(I) != MBB.end() &&
+        std::next(I)->getOpcode() == TargetOpcode::SEH_REGION_BARRIER)
+      break;
+    if (I->getOpcode() == TargetOpcode::SEH_REGION_BARRIER &&
+        std::next(I) != MBB.end() && std::next(I)->isEHLabel()) {
+      ++I;
+      continue;
+    }
     if (I->isLabel()) {
       ++I;
       continue;
diff --git a/llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp b/llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp
index 6233cf8d0d668..2564f913793cd 100644
--- a/llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp
@@ -1499,8 +1499,54 @@ void SelectionDAGISel::reportIPToStateForBlocks(MachineFunction *MF) {
   llvm::WinEHFuncInfo *EHInfo = MF->getWinEHFuncInfo();
   if (!EHInfo)
     return;
+  bool IsTableSEH =
+      MF->getFunction().hasPersonalityFn() &&
+      classifyEHPersonality(MF->getFunction().getPersonalityFn()) ==
+          EHPersonality::MSVC_TableSEH;
   for (MachineBasicBlock &MBB : *MF) {
     const BasicBlock *BB = MBB.getBasicBlock();
+    if (!BB)
+      continue;
+    if (IsTableSEH) {
+      auto StateIt = EHInfo->BlockToStateMap.find(BB);
+      if (StateIt == EHInfo->BlockToStateMap.end())
+        continue;
+      int State = StateIt->second;
+      auto Begin = MBB.getFirstNonPHI();
+      if (Begin == MBB.end())
+        continue;
+      auto End = MBB.getFirstTerminator();
+      if (Begin == End && !MBB.back().isBranch())
+        continue;
+
+      auto FirstEHLabel = llvm::find_if(
+          MBB, [](const MachineInstr &MI) { return MI.isEHLabel(); });
+      if (FirstEHLabel != MBB.end()) {
+        if (State < 0)
+          continue;
+        if (Begin == FirstEHLabel) {
+          BuildMI(MBB, Begin, DebugLoc(),
+                  TII->get(TargetOpcode::SEH_REGION_BARRIER));
+          continue;
+        }
+        End = FirstEHLabel;
+      }
+
+      MCSymbol *BeginLabel = MF->getContext().createTempSymbol();
+      MCSymbol *EndLabel = MF->getContext().createTempSymbol();
+      EHInfo->addIPToStateRange(State, BeginLabel, EndLabel);
+      if (State >= 0)
+        BuildMI(MBB, Begin, DebugLoc(),
+                TII->get(TargetOpcode::SEH_REGION_BARRIER));
+      BuildMI(MBB, Begin, DebugLoc(), TII->get(TargetOpcode::EH_LABEL))
+          .addSym(BeginLabel);
+      BuildMI(MBB, End, DebugLoc(), TII->get(TargetOpcode::EH_LABEL))
+          .addSym(EndLabel);
+      if (State >= 0 && FirstEHLabel == MBB.end())
+        BuildMI(MBB, End, DebugLoc(),
+                TII->get(TargetOpcode::SEH_REGION_BARRIER));
+      continue;
+    }
     int State = EHInfo->BlockToStateMap[BB];
     if (BB->getFirstMayFaultInst()) {
       // Report IP range only for blocks with Faulty inst
diff --git a/llvm/lib/CodeGen/SplitKit.cpp b/llvm/lib/CodeGen/SplitKit.cpp
index 404cfe43289d6..58eb4ccdda509 100644
--- a/llvm/lib/CodeGen/SplitKit.cpp
+++ b/llvm/lib/CodeGen/SplitKit.cpp
@@ -82,7 +82,11 @@ InsertPointAnalysis::computeLastInsertPoint(const LiveInterval &CurLI,
   // Compute insert points on the first call. The pair is independent of the
   // current live interval.
   if (!LIP.first.isValid()) {
-    MachineBasicBlock::const_iterator FirstTerm = MBB.getFirstTerminator();
+    MachineBasicBlock::const_iterator FirstTerm =
+        MBB.getInsertPtBeforeTerminators();
+    while (FirstTerm != MBB.end() &&
+           !LIS.getSlotIndexes()->hasIndex(*FirstTerm))
+      ++FirstTerm;
     if (FirstTerm == MBB.end())
       LIP.first = MBBEnd;
     else
diff --git a/llvm/lib/IR/EHPersonalities.cpp b/llvm/lib/IR/EHPersonalities.cpp
index 12ae4748e1f4a..7a67bdbbc42ce 100644
--- a/llvm/lib/IR/EHPersonalities.cpp
+++ b/llvm/lib/IR/EHPersonalities.cpp
@@ -12,6 +12,7 @@
 #include "llvm/IR/Constants.h"
 #include "llvm/IR/Function.h"
 #include "llvm/IR/Instructions.h"
+#include "llvm/IR/IntrinsicInst.h"
 #include "llvm/IR/Module.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/raw_ostream.h"
@@ -112,6 +113,85 @@ bool llvm::canSimplifyInvokeNoUnwind(const Function *F) {
   return !EHa && !isAsynchronousEHPersonality(Personality);
 }
 
+static const InvokeInst *getSEHTryMarker(const BasicBlock *BB) {
+  const auto *Invoke = dyn_cast<InvokeInst>(BB->getTerminator());
+  if (!Invoke)
+    return nullptr;
+  Intrinsic::ID ID = Invoke->getIntrinsicID();
+  return ID == Intrinsic::seh_try_begin || ID == Intrinsic::seh_try_end
+             ? Invoke
+             : nullptr;
+}
+
+SEHTryRegionInfo::SEHTryRegionInfo(const Function &F) {
+  if (!F.getParent()->getModuleFlag("eh-asynch") || !F.hasPersonalityFn() ||
+      classifyEHPersonality(F.getPersonalityFn()) !=
+          EHPersonality::MSVC_TableSEH)
+    return;
+  if (none_of(F, [](const BasicBlock &BB) {
+        const InvokeInst *Marker = getSEHTryMarker(&BB);
+        return Marker && Marker->getIntrinsicID() == Intrinsic::seh_try_begin;
+      }))
+    return;
+
+  using Region = std::optional<const BasicBlock *>;
+  DenseMap<const BasicBlock *, Region> Parents;
+  SmallVector<const BasicBlock *, 32> Worklist;
+  auto Assign = [&](const BasicBlock *BB, Region NewRegion) {
+    auto [Position, Inserted] = RegionOf.try_emplace(BB, NewRegion);
+    if (Inserted) {
+      Worklist.push_back(BB);
+    } else if (Position->second && Position->second != NewRegion) {
+      Position->second = std::nullopt;
+      Worklist.push_back(BB);
+    }
+  };
+
+  Assign(&F.getEntryBlock(), nullptr);
+  while (!Worklist.empty()) {
+    const BasicBlock *BB = Worklist.pop_back_val();
+    Region Current = RegionOf[BB];
+    Region Normal = Current;
+    if (const InvokeInst *Marker = getSEHTryMarker(BB)) {
+      if (Marker->getIntrinsicID() == Intrinsic::seh_try_begin) {
+        const BasicBlock *Pad = Marker->getUnwindDest();
+        Normal = Pad;
+        auto [Parent, Inserted] = Parents.try_emplace(Pad, Current);
+        if (!Inserted && Parent->second != Current) {
+          for (auto &KnownRegion : RegionOf)
+            KnownRegion.second = std::nullopt;
+          return;
+        }
+        Assign(Pad, Parent->second);
+      } else if (Current && *Current) {
+        auto Parent = Parents.find(*Current);
+        Normal = Parent == Parents.end() ? Region() : Parent->second;
+      }
+    }
+
+    for (const BasicBlock *Successor : successors(BB)) {
+      if (const auto *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
+        if (Successor == Invoke->getUnwindDest())
+          continue;
+      if (const auto *Switch = dyn_cast<CatchSwitchInst>(BB->getTerminator()))
+        if (Successor == Switch->getUnwindDest())
+          continue;
+      Assign(Successor, Normal);
+    }
+  }
+}
+
+bool SEHTryRegionInfo::isSameRegion(const BasicBlock *From,
+                                    const BasicBlock *To) const {
+  if (RegionOf.empty() || From == To)
+    return true;
+  auto Source = RegionOf.find(From);
+  auto Destination = RegionOf.find(To);
+  return Source != RegionOf.end() && Destination != RegionOf.end() &&
+         Source->second && Destination->second &&
+         Source->second == Destination->second;
+}
+
 DenseMap<BasicBlock *, ColorVector> llvm::colorEHFunclets(Function &F) {
   SmallVector<std::pair<BasicBlock *, BasicBlock *>, 16> Worklist;
   BasicBlock *EntryBlock = &F.getEntryBlock();
diff --git a/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp b/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp
index 4b09510933d0c..5d87bceacca40 100644
--- a/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp
@@ -5565,6 +5565,10 @@ bool InstCombinerImpl::tryToSinkInstruction(Instruction *I,
   if (isa<CatchSwitchInst>(DestBlock->getTerminator()))
     return false;
 
+  if (F.getParent()->getModuleFlag("eh-asynch") &&
+      !SEHTryRegionInfo(F).isSameRegion(SrcBlock, DestBlock))
+    return false;
+
   // Do not sink convergent call instructions.
   if (auto *CI = dyn_cast<CallInst>(I)) {
     if (CI->isConvergent())
diff --git a/llvm/test/CodeGen/WinEH/seh-catchpad-state.ll b/llvm/test/CodeGen/WinEH/seh-catchpad-state.ll
index 38c8f2e2916f5..6ebe365de3b35 100644
--- a/llvm/test/CodeGen/WinEH/seh-catchpad-state.ll
+++ b/llvm/test/CodeGen/WinEH/seh-catchpad-state.ll
@@ -1,8 +1,8 @@
 ; REQUIRES: x86-registered-target || aarch64-registered-target
-; RUN: %if x86-registered-target %{ llc -mtriple=x86_64-pc-windows-msvc -x86-asm-syntax=intel -verify-machineinstrs < %s | FileCheck %s --check-prefixes=CHECK,X86 %}
-; RUN: %if x86-registered-target %{ llc -O0 -mtriple=x86_64-pc-windows-msvc -x86-asm-syntax=intel -verify-machineinstrs < %s | FileCheck %s --check-prefixes=CHECK,X86 %}
-; RUN: %if aarch64-registered-target %{ llc -mtriple=aarch64-pc-windows-msvc -verify-machineinstrs < %s | FileCheck %s --check-prefixes=CHECK,AARCH64 %}
-; RUN: %if aarch64-registered-target %{ llc -O0 -mtriple=aarch64-pc-windows-msvc -verify-machineinstrs < %s | FileCheck %s --check-prefixes=CHECK,AARCH64 %}
+; RUN: %if x86-registered-target %{ llc -mtriple=x86_64-pc-windows-msvc -x86-asm-syntax=intel -verify-machineinstrs < %s | FileCheck %s --check-prefixes=CHECK,X86,OPT %}
+; RUN: %if x86-registered-target %{ llc -O0 -mtriple=x86_64-pc-windows-msvc -x86-asm-syntax=intel -verify-machineinstrs < %s | FileCheck %s --check-prefixes=CHECK,X86,O0 %}
+; RUN: %if aarch64-registered-target %{ llc -mtriple=aarch64-pc-windows-msvc -verify-machineinstrs < %s | FileCheck %s --check-prefixes=CHECK,AARCH64,OPT %}
+; RUN: %if aarch64-registered-target %{ llc -O0 -mtriple=aarch64-pc-windows-msvc -verify-machineinstrs < %s | FileCheck %s --check-prefixes=CHECK,AARCH64,O0 %}
 
 declare void @may_fault(ptr)
 declare i32 @filter(ptr, ptr)
@@ -43,19 +43,25 @@ exit:
 ; AARCH64: mov [[BEFORE:w[0-9]+]], #11
 ; AARCH64-NEXT: str [[BEFORE]], [{{[^]]+}}]
 ; CHECK: %guarded{{$}}
+; CHECK-NEXT: {{(#|//)}}SEH_REGION_BARRIER
 ; CHECK-NEXT: [[BEGIN:\.Ltmp[0-9]+]]:
 ; X86: mov dword ptr [{{[^]]+}}], 22
 ; AARCH64: mov [[GUARDED:w[0-9]+]], #22
 ; AARCH64-NEXT: str [[GUARDED]], [{{[^]]+}}]
 ; CHECK: {{(call|bl)}} may_fault
-; CHECK: [[END:\.Ltmp[0-9]+]]:
-; CHECK: [[HANDLER:\.LBB[0-9]+_[0-9]+]]: {{.*}}%handler{{$}}
-; X86: mov dword ptr [{{[^]]+}}], 44
-; AARCH64: mov [[CAUGHT:w[0-9]+]], #44
-; AARCH64-NEXT: str [[CAUGHT]], [{{[^]]+}}]
-; X86: mov dword ptr [{{[^]]+}}], 33
-; AARCH64: mov [[AFTER:w[0-9]+]], #33
-; AARCH64-NEXT: str [[AFTER]], [{{[^]]+}}]
+; CHECK: %guarded.end{{$}}
+; CHECK-NEXT: {{(#|//)}}SEH_REGION_BARRIER
+; CHECK-NEXT: {{\.Ltmp[0-9]+}}:
+; OPT-NEXT: [[END:\.Ltmp[0-9]+]]:
+; O0-NEXT: {{\.Ltmp[0-9]+}}:
+; CHECK-NEXT: {{(#|//)}}SEH_REGION_BARRIER
+; O0-NEXT: {{(jmp|b)}} {{\.LBB[0-9]+_[0-9]+}}
+; O0-NEXT: [[END:\.LBB_END[0-9]+_[0-9]+]]:
+; CHECK-DAG: [[HANDLER:\.LBB[0-9]+_[0-9]+]]: {{.*}}%handler{{$}}
+; X86-DAG: mov dword ptr [{{[^]]+}}], 33
+; X86-DAG: mov dword ptr [{{[^]]+}}], 44
+; AARCH64-DAG: mov {{w[0-9]+}}, #33
+; AARCH64-DAG: mov {{w[0-9]+}}, #44
 ; CHECK: .Llsda_begin{{[0-9]+}}:
 ; CHECK-NEXT: {{\.(long|word)}} [[BEGIN]]@IMGREL
 ; CHECK-NEXT: {{\.(long|word)}} [[END]]@IMGREL
@@ -99,9 +105,17 @@ exit:
 
 ; CHECK-LABEL: branching_handler:
 ; CHECK: %guarded{{$}}
+; CHECK-NEXT: {{(#|//)}}SEH_REGION_BARRIER
 ; CHECK-NEXT: [[BRANCH_BEGIN:\.Ltmp[0-9]+]]:
 ; CHECK: {{(call|bl)}} may_fault
-; CHECK: [[BRANCH_END:\.Ltmp[0-9]+]]:
+; CHECK: %guarded.end{{$}}
+; CHECK-NEXT: {{(#|//)}}SEH_REGION_BARRIER
+; CHECK-NEXT: {{\.Ltmp[0-9]+}}:
+; OPT-NEXT: [[BRANCH_END:\.Ltmp[0-9]+]]:
+; O0-NEXT: {{\.Ltmp[0-9]+}}:
+; CHECK-NEXT: {{(#|//)}}SEH_REGION_BARRIER
+; O0-NEXT: {{(jmp|b)}} {{\.LBB[0-9]+_[0-9]+}}
+; O0-NEXT: [[BRANCH_END:\.LBB_END[0-9]+_[0-9]+]]:
 ; CHECK: [[BRANCH_HANDLER:\.LBB[0-9]+_[0-9]+]]: {{.*}}%handler{{$}}
 ; X86: mov dword ptr [{{[^]]+}}], 44
 ; AARCH64: mov [[BRANCH_CAUGHT:w[0-9]+]], #44
@@ -188,22 +202,54 @@ exit:
 }
 
 ; CHECK-LABEL: nested_handler:
+; O0: %outer{{$}}
+; O0-NEXT: {{(#|//)}}SEH_REGION_BARRIER
+; O0-NEXT: [[OUTER_ENTRY_BEGIN:\.Ltmp[0-9]+]]:
+; O0-NEXT: {{\.Ltmp[0-9]+}}:
+; O0-NEXT: {{(#|//)}}SEH_REGION_BARRIER
+; O0-NEXT: {{(jmp|b)}} {{\.LBB[0-9]+_[0-9]+}}
+; O0-NEXT: [[OUTER_ENTRY_END:\.LBB_END[0-9]+_[0-9]+]]:
+; O0: %middle{{$}}
+; O0-NEXT: {{(#|//)}}SEH_REGION_BARRIER
+; O0-NEXT: [[MIDDLE_ENTRY_BEGIN:\.Ltmp[0-9]+]]:
+; O0-NEXT: {{\.Ltmp[0-9]+}}:
+; O0-NEXT: {{(#|//)}}SEH_REGION_BARRIER
+; O0-NEXT: {{(jmp|b)}} {{\.LBB[0-9]+_[0-9]+}}
+; O0-NEXT: [[MIDDLE_ENTRY_END:\.LBB_END[0-9]+_[0-9]+]]:
 ; CHECK: %inner{{$}}
+; CHECK-NEXT: {{(#|//)}}SEH_REGION_BARRIER
 ; CHECK-NEXT: [[INNER_BEGIN:\.Ltmp[0-9]+]]:
 ; CHECK: {{(call|bl)}} may_fault
-; CHECK: [[INNER_END:\.Ltmp[0-9]+]]:
+; CHECK: %inner.end{{$}}
+; CHECK-NEXT: {{(#|//)}}SEH_REGION_BARRIER
+; CHECK-NEXT: {{\.Ltmp[0-9]+}}:
+; OPT-NEXT: [[INNER_END:\.Ltmp[0-9]+]]:
+; O0-NEXT: {{\.Ltmp[0-9]+}}:
+; CHECK-NEXT: {{(#|//)}}SEH_REGION_BARRIER
+; O0-NEXT: {{(jmp|b)}} {{\.LBB[0-9]+_[0-9]+}}
+; O0-NEXT: [[INNER_END:\.LBB_END[0-9]+_[0-9]+]]:
 ; CHECK: %middle.end{{$}}
+; CHECK-NEXT: {{(#|//)}}SEH_REGION_BARRIER
 ; CHECK-NEXT: [[MIDDLE_BEGIN:\.Ltmp[0-9]+]]:
 ; X86: mov dword ptr [{{[^]]+}}], 77
 ; AARCH64: mov [[MIDDLE_VALUE:w[0-9]+]], #77
 ; AARCH64-NEXT: str [[MIDDLE_VALUE]], [{{[^]]+}}]
-; CHECK-NEXT: [[MIDDLE_END:\.Ltmp[0-9]+]]:
+; OPT-NEXT: [[MIDDLE_END:\.Ltmp[0-9]+]]:
+; O0-NEXT: {{\.Ltmp[0-9]+}}:
+; CHECK-NEXT: {{(#|//)}}SEH_REGION_BARRIER
+; O0-NEXT: {{(jmp|b)}} {{\.LBB[0-9]+_[0-9]+}}
+; O0-NEXT: [[MIDDLE_END:\.LBB_END[0-9]+_[0-9]+]]:
 ; CHECK: %outer.end{{$}}
+; CHECK-NEXT: {{(#|//)}}SEH_REGION_BARRIER
 ; CHECK-NEXT: [[OUTER_BEGIN:\.Ltmp[0-9]+]]:
 ; X86: mov dword ptr [{{[^]]+}}], 88
 ; AARCH64: mov [[OUTER_VALUE:w[0-9]+]], #88
 ; AARCH64-NEXT: str [[OUTER_VALUE]], [{{[^]]+}}]
-; CHECK-NEXT: [[OUTER_END:\.Ltmp[0-9]+]]:
+; OPT-NEXT: [[OUTER_END:\.Ltmp[0-9]+]]:
+; O0-NEXT: {{\.Ltmp[0-9]+}}:
+; CHECK-NEXT: {{(#|//)}}SEH_REGION_BARRIER
+; O0-NEXT: {{(jmp|b)}} {{\.LBB[0-9]+_[0-9]+}}
+; O0-NEXT: [[OUTER_END:\.LBB_END[0-9]+_[0-9]+]]:
 ; CHECK: [[INNER_HANDLER:\.LBB[0-9]+_[0-9]+]]: {{.*}}%inner.handler{{$}}
 ; CHECK: [[INNER_HANDLER_BEGIN:\.Ltmp[0-9]+]]:
 ; X86: mov dword ptr [{{[^]]+}}], 44
@@ -215,18 +261,36 @@ exit:
 ; X86: mov dword ptr [{{[^]]+}}], 66
 ; AARCH64: mov [[INNER_RIGHT:w[0-9]+]], #66
 ; AARCH64-NEXT: str [[INNER_RIGHT]], [{{[^]]+}}]
-; CHECK-NEXT: [[INNER_HANDLER_END:\.Ltmp[0-9]+]]:
+; CHECK-NEXT: {{\.Ltmp[0-9]+}}:
+; CHECK-NEXT: {{(#|//)}}SEH_REGION_BARRIER
+; CHECK-NEXT: {{(jmp|b)}} {{\.LBB[0-9]+_[0-9]+}}
+; CHECK-NEXT: [[INNER_HANDLER_END:\.LBB_END[0-9]+_[0-9]+]]:
 ; CHECK: [[MIDDLE_HANDLER:\.LBB[0-9]+_[0-9]+]]: {{.*}}%middle.handler{{$}}
 ; CHECK: [[MIDDLE_HANDLER_BEGIN:\.Ltmp[0-9]+]]:
 ; X86: mov dword ptr [{{[^]]+}}], 99
 ; AARCH64: mov [[MIDDLE_CAUGHT:w[0-9]+]], #99
 ; AARCH64-NEXT: str [[MIDDLE_CAUGHT]], [{{[^]]+}}]
-; CHECK-NEXT: [[MIDDLE_HANDLER_END:\.Ltmp[0-9]+]]:
+; CHECK-NEXT: {{\.Ltmp[0-9]+}}:
+; CHECK-NEXT: {{(#|//)}}SEH_REGION_BARRIER
+; CHECK-NEXT: {{(jmp|b)}} {{\.LBB[0-9]+_[0-9]+}}
+; CHECK-NEXT: [[MIDDLE_HANDLER_END:\.LBB_END[0-9]+_[0-9]+]]:
 ; CHECK: [[OUTER_HANDLER:\.LBB[0-9]+_[0-9]+]]: {{.*}}%outer.handler{{$}}
 ; X86: mov dword ptr [{{[^]]+}}], 111
 ; AARCH64: mov [[OUTER_CAUGHT:w[0-9]+]], #111
 ; AARCH64-NEXT: str [[OUTER_CAUGHT]], [{{[^]]+}}]
 ; CHECK: .Llsda_begin{{[0-9]+}}:
+; O0-NEXT: {{\.(long|word)}} [[OUTER_ENTRY_BEGIN]]@IMGREL
+; O0-NEXT: {{\.(long|word)}} [[OUTER_ENTRY_END]]@IMGREL
+; O0-NEXT: {{\.(long|word)}} 1
+; O0-NEXT: {{\.(long|word)}} [[OUTER_HANDLER]]@IMGREL
+; O0-NEXT: {{\.(long|word)}} [[MIDDLE_ENTRY_BEGIN]]@IMGREL
+; O0-NEXT: {{\.(long|word)}} [[MIDDLE_ENTRY_END]]@IMGREL
+; O0-NEXT: {{\.(long|word)}} 1
+; O0-NEXT: {{\.(long|word)}} [[MIDDLE_HANDLER]]@IMGREL
+; O0-NEXT: {{\.(long|word)}} [[MIDDLE_ENTRY_BEGIN]]@IMGREL
+; O0-NEXT: {{\.(long|word)}} [[MIDDLE_ENTRY_END]]@IMGREL
+; O0-NEXT: {{\.(long|word)}} 1
+; O0-NEXT: {{\.(long|word)}} [[OUTER_HANDLER]]@IMGREL
 ; CHECK-NEXT: {{\.(long|word)}} [[INNER_BEGIN]]@IMGREL
 ; CHECK-NEXT: {{\.(long|word)}} [[INNER_END]]@IMGREL
 ; CHECK-NEXT: {{\.(long|word)}} 1
diff --git a/llvm/test/CodeGen/WinEH/seh-region-preservation.ll b/llvm/test/CodeGen/WinEH/seh-region-preservation.ll
new file mode 100644
index 0000000000000..3fd107f486aa4
--- /dev/null
+++ b/llvm/test/CodeGen/WinEH/seh-region-preservation.ll
@@ -0,0 +1,203 @@
+; REQUIRES: x86-registered-target || aarch64-registered-target
+; RUN: %if x86-registered-target %{ llc -mtriple=x86_64-pc-windows-msvc -x86-asm-syntax=intel -verify-machineinstrs < %s | FileCheck %s --check-prefixes=CHECK,X86 %}
+; RUN: %if aarch64-registered-target %{ llc -mtriple=aarch64-pc-windows-msvc -verify-machineinstrs < %s | FileCheck %s --check-prefixes=CHECK,AARCH64 %}
+; RUN: %if x86-registered-target %{ llc -mtriple=x86_64-pc-windows-msvc -phi-elim-split-all-critical-edges -stop-after=phi-node-elimination -verify-machineinstrs < %s | FileCheck %s --check-prefix=PHI %}
+
+declare void @llvm.seh.try.begin()
+declare void @llvm.seh.try.end()
+declare i32 @__C_specific_handler(...)
+
+define void @guarded_loop(ptr %address) personality ptr @__C_specific_handler {
+entry:
+  invoke void @llvm.seh.try.begin()
+          to label %loop unwind label %dispatch
+
+loop:
+  store volatile i32 7, ptr %address
+  br label %loop
+
+dispatch:
+  %switch = catchswitch within none [label %handler] unwind to caller
+
+handler:
+  %pad = catchpad within %switch [ptr null]
+  catchret from %pad to label %exit
+
+exit:
+  ret void
+}
+
+; CHECK-LABEL: guarded_loop:
+; CHECK: %loop
+; CHECK: [[BEGIN:\.Ltmp[0-9]+]]:
+; X86: mov dword ptr [{{[^]]+}}], 7
+; AARCH64: str {{w[0-9]+}}, [{{[^]]+}}]
+; CHECK: {{(jmp|b)}} {{\.LBB[0-9]+_[0-9]+}}
+; CHECK-NEXT: [[END:\.LBB_END[0-9]+_[0-9]+]]:
+; CHECK: [[HANDLER:\.LBB[0-9]+_[0-9]+]]: {{.*}}%handler
+; CHECK: .Llsda_begin{{[0-9]+}}:
+; CHECK-NEXT: {{\.(long|word)}} [[BEGIN]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} [[END]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} 1
+; CHECK-NEXT: {{\.(long|word)}} [[HANDLER]]@IMGREL
+; CHECK-NEXT: .Llsda_end{{[0-9]+}}:
+
+declare void @no_return() noreturn
+declare i32 @callee(ptr)
+
+define void @guarded_return(ptr %address) personality ptr @__C_specific_handler {
+entry:
+  invoke void @llvm.seh.try.begin() to label %body unwind label %dispatch
+body:
+  store volatile i32 7, ptr %address
+  ret void
+dispatch:
+  %switch = catchswitch within none [label %handler] unwind to caller
+handler:
+  %pad = catchpad within %switch [ptr null]
+  catchret from %pad to label %fail
+fail:
+  call void @no_return()
+  unreachable
+}
+
+; CHECK-LABEL: guarded_return:
+; CHECK: %body
+; CHECK: [[RETURN_BEGIN:\.Ltmp[0-9]+]]:
+; X86: mov dword ptr [{{[^]]+}}], 7
+; AARCH64: str {{w[0-9]+}}, [{{[^]]+}}]
+; CHECK-NEXT: [[RETURN_END:\.Ltmp[0-9]+]]:
+; CHECK-NEXT: {{(#|//)}}SEH_REGION_BARRIER
+; CHECK-NEXT: .seh_startepilogue
+; CHECK: ret
+; CHECK: [[RETURN_HANDLER:\.LBB[0-9]+_[0-9]+]]: {{.*}}%handler
+; CHECK: .Llsda_begin{{[0-9]+}}:
+; CHECK-NEXT: {{\.(long|word)}} [[RETURN_BEGIN]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} [[RETURN_END]]@IMGREL
+; CHECK-NEXT: {{\.(long|word)}} 1
+; CHECK-NEXT: {{\.(long|word)}} [[RETURN_HANDLER]]@IMGREL
+; CHECK-NEXT: .Llsda_end{{[0-9]+}}:
+
+define i32 @split_region(ptr %address, i1 %condition) personality ptr @__C_specific_handler {
+entry:
+  %isnull = icmp eq ptr %address, null
+  br i1 %isnull, label %exit, label %try.begin
+try.begin:
+  invoke void @llvm.seh.try.begin() to label %try.body unwind label %dispatch
+try.body:
+  %isnull2 = icmp eq ptr %address, null
+  br i1 %isnull2, label %then, label %else
+then:
+  store volatile i32 0, ptr %address
+  br label %join
+else:
+  %called = invoke i32 @callee(ptr %address) to label %cont unwind label %dispatch
+cont:
+  %value = load volatile i64, ptr %address
+  %select = select i1 %condition, i64 %value, i64 0
+  store volatile i64 %select, ptr %address
+  br label %join
+join:
+  invoke void @llvm.seh.try.end() to label %exit unwind label %dispatch
+dispatch:
+  %switch = catchswitch within none [label %handler] unwind to caller
+handler:
+  %pad = catchpad within %switch [ptr null]
+  catchret from %pad to label %exit
+exit:
+  %result = phi i32 [ 0, %join ], [ 1, %entry ], [ -1, %handler ]
+  ret i32 %result
+}
+
+; X86-LABEL: split_region:
+; X86: %try.body
+; X86: [[SPLIT_BEGIN:\.Ltmp[0-9]+]]:
+; X86: call callee
+; X86: %cont
+; X86: mov qword ptr [{{[^]]+}}], {{[a-z0-9]+}}
+; X86: jmp
+; X86-NEXT: [[SPLIT_END:\.LBB_END[0-9]+_[0-9]+]]:
+; X86-NEXT: {{\.LBB[0-9]+_[0-9]+}}: {{.*}}%entry
+; X86-NEXT: mov eax, 1
+; X86: %then
+; X86: [[RESUME:\.Ltmp[0-9]+]]:
+; X86: mov dword ptr [{{[^]]+}}], 0
+; X86: %join
+; X86: xor eax, eax
+; X86-NEXT: [[RESUME_END:\.Ltmp[0-9]+]]:
+; X86: [[SPLIT_HANDLER:\.LBB[0-9]+_[0-9]+]]: {{.*}}%handler
+; X86: .Llsda_begin{{[0-9]+}}:
+; X86-NEXT: .long [[SPLIT_BEGIN]]@IMGREL
+; X86-NEXT: .long [[SPLIT_END]]@IMGREL
+; X86-NEXT: .long 1
+; X86-NEXT: .long [[SPLIT_HANDLER]]@IMGREL
+; X86-NEXT: .long [[RESUME]]@IMGREL
+; X86-NEXT: .long [[RESUME_END]]@IMGREL
+; X86-NEXT: .long 1
+; X86-NEXT: .long [[SPLIT_HANDLER]]@IMGREL
+; X86-NEXT: .Llsda_end{{[0-9]+}}:
+
+define i32 @sunk_load_stays_outside(ptr %address, ptr %source, i1 %condition) personality ptr @__C_specific_handler {
+entry:
+  %value = load i32, ptr %source
+  br i1 %condition, label %try.begin, label %exit
+try.begin:
+  invoke void @llvm.seh.try.begin() to label %body unwind label %dispatch
+body:
+  %sum = add i32 %value, 1
+  store volatile i32 %sum, ptr %address
+  %called = invoke i32 @callee(ptr %address) to label %end unwind label %dispatch
+end:
+  invoke void @llvm.seh.try.end() to label %exit unwind label %dispatch
+dispatch:
+  %switch = catchswitch within none [label %handler] unwind to caller
+handler:
+  %pad = catchpad within %switch [ptr null]
+  catchret from %pad to label %exit
+exit:
+  %result = phi i32 [ 0, %entry ], [ 1, %end ], [ -1, %handler ]
+  ret i32 %result
+}
+
+; CHECK-LABEL: sunk_load_stays_outside:
+; X86: mov {{[a-z0-9]+}}, dword ptr [{{[a-z0-9]+}}]
+; AARCH64: ldr {{w[0-9]+}}, [{{x[0-9]+}}]
+; CHECK: {{(#|//)}}SEH_REGION_BARRIER
+; CHECK-NEXT: [[SINK_BEGIN:\.Ltmp[0-9]+]]:
+; CHECK: {{(call|bl)}} callee
+; CHECK: .Llsda_begin{{[0-9]+}}:
+; CHECK-NEXT: {{\.(long|word)}} [[SINK_BEGIN]]@IMGREL
+
+define i32 @critical_region_edge(ptr %address, i1 %condition) personality ptr @__C_specific_handler {
+entry:
+  invoke void @llvm.seh.try.begin() to label %body unwind label %dispatch
+body:
+  %value = load volatile i32, ptr %address
+  br i1 %condition, label %merge, label %other
+other:
+  %add = add i32 %value, 7
+  br label %merge
+merge:
+  %merged = phi i32 [ %value, %body ], [ %add, %other ]
+  invoke void @llvm.seh.try.end() to label %exit unwind label %dispatch
+dispatch:
+  %switch = catchswitch within none [label %handler] unwind to caller
+handler:
+  %pad = catchpad within %switch [ptr null]
+  catchret from %pad to label %exit
+exit:
+  %result = phi i32 [ %merged, %merge ], [ -1, %handler ]
+  ret i32 %result
+}
+
+; PHI-LABEL: name: critical_region_edge
+; PHI: bb.1.body:
+; PHI: bb.{{[0-9]+}}.body:
+; PHI: SEH_REGION_BARRIER
+; PHI-NEXT: EH_LABEL
+; PHI: COPY
+; PHI-NEXT: EH_LABEL
+; PHI-NEXT: SEH_REGION_BARRIER
+
+!llvm.module.flags = !{!0}
+!0 = !{i32 1, !"eh-asynch", i32 1}
\ No newline at end of file
diff --git a/llvm/test/CodeGen/X86/seh-region-insertion.mir b/llvm/test/CodeGen/X86/seh-region-insertion.mir
new file mode 100644
index 0000000000000..d4e2be7cafd96
--- /dev/null
+++ b/llvm/test/CodeGen/X86/seh-region-insertion.mir
@@ -0,0 +1,173 @@
+# RUN: llc -mtriple=x86_64-pc-windows-msvc -run-pass=early-machinelicm -verify-machineinstrs -o - %s | FileCheck %s
+# RUN: llc -mtriple=x86_64-pc-windows-msvc -run-pass=branch-folder -verify-machineinstrs -o - %s | FileCheck %s --check-prefix=FOLD
+
+--- |
+  define void @nested_markers(ptr %address) {
+  entry:
+    br label %preheader
+  preheader:
+    br label %loop
+  loop:
+    br label %loop
+  }
+
+  define i32 @separate_tails(i32 %condition) !dbg !4 {
+  entry:
+    br label %exit
+  first:
+    br label %exit
+  middle:
+    br label %exit
+  second:
+    br label %exit
+  third:
+    br label %exit
+  exit:
+    ret i32 0
+  }
+
+  define i32 @fold_without_regions(i32 %condition) {
+  entry:
+    br label %exit
+  first:
+    br label %exit
+  second:
+    br label %exit
+  exit:
+    ret i32 0
+  }
+
+  !llvm.module.flags = !{!0}
+  !llvm.dbg.cu = !{!1}
+  !0 = !{i32 2, !"Debug Info Version", i32 3}
+  !1 = distinct !DICompileUnit(language: DW_LANG_C99, file: !2, producer: "clang", emissionKind: FullDebug)
+  !2 = !DIFile(filename: "example.c", directory: "/")
+  !3 = !DISubroutineType(types: !6)
+  !4 = distinct !DISubprogram(name: "separate_tails", scope: !2, file: !2, line: 1, type: !3, unit: !1, spFlags: DISPFlagDefinition)
+  !6 = !{}
+  !7 = !DILocation(line: 11, scope: !4)
+  !8 = !DILocation(line: 22, scope: !4)
+  !9 = !DILocation(line: 33, scope: !4)
+...
+---
+name: nested_markers
+tracksRegLiveness: true
+body: |
+  bb.0.entry:
+    successors: %bb.1
+    liveins: $rcx
+    %0:gr64 = COPY $rcx
+
+  bb.1.preheader:
+    successors: %bb.2
+    SEH_REGION_BARRIER
+    EH_LABEL <mcsymbol .Louter.begin>
+    SEH_REGION_BARRIER
+    EH_LABEL <mcsymbol .Linner.begin>
+    %1:gr64 = MOV64rm %0, 1, $noreg, 0, $noreg :: (load (s64))
+    EH_LABEL <mcsymbol .Linner.end>
+    SEH_REGION_BARRIER
+    EH_LABEL <mcsymbol .Louter.end>
+    SEH_REGION_BARRIER
+    JMP_1 %bb.2
+
+  bb.2.loop:
+    successors: %bb.2
+    %2:gr64 = LEA64r %0, 1, $noreg, 16, $noreg
+    %3:gr64 = ADD64rr %1, %2, implicit-def dead $eflags
+    JMP_1 %bb.2
+...
+
+# CHECK-LABEL: name: nested_markers
+# CHECK: bb.1.preheader:
+# CHECK: EH_LABEL <mcsymbol .Linner.begin>
+# CHECK: {{%[0-9]+}}:gr64 = LEA64r
+# CHECK-NEXT: {{%[0-9]+}}:gr64 = ADD64rr
+# CHECK-NEXT: EH_LABEL <mcsymbol .Linner.end>
+# CHECK-NEXT: SEH_REGION_BARRIER
+# CHECK-NEXT: EH_LABEL <mcsymbol .Louter.end>
+# CHECK-NEXT: SEH_REGION_BARRIER
+# CHECK-NEXT: JMP_1 %bb.2
+
+---
+name: separate_tails
+tracksRegLiveness: true
+body: |
+  bb.0.entry:
+    successors: %bb.1, %bb.2
+    liveins: $ecx, $edx
+    TEST32rr $ecx, $ecx, implicit-def $eflags
+    JCC_1 %bb.2, 5, implicit $eflags
+
+  bb.1.first:
+    successors: %bb.5
+    SEH_REGION_BARRIER
+    $eax = MOV32ri -7
+    JMP_1 %bb.5, debug-location !7
+
+  bb.2.middle:
+    successors: %bb.3, %bb.4
+    liveins: $edx
+    TEST32rr $edx, $edx, implicit-def $eflags
+    JCC_1 %bb.4, 5, implicit $eflags
+
+  bb.3.second:
+    successors: %bb.5
+    SEH_REGION_BARRIER
+    $eax = MOV32ri -7
+    JMP_1 %bb.5, debug-location !8
+
+  bb.4.third:
+    successors: %bb.5
+    SEH_REGION_BARRIER
+    $eax = MOV32ri -7
+    JMP_1 %bb.5, debug-location !9
+
+  bb.5.exit:
+    liveins: $eax
+    RET 0, $eax
+...
+
+# FOLD-LABEL: name: separate_tails
+# FOLD: bb.1.first:
+# FOLD: SEH_REGION_BARRIER
+# FOLD-NEXT: $eax = MOV32ri -7
+# FOLD-NEXT: JMP_1 %bb.5, debug-location !DILocation(line: 11
+# FOLD: bb.3.second:
+# FOLD: SEH_REGION_BARRIER
+# FOLD-NEXT: $eax = MOV32ri -7
+# FOLD-NEXT: JMP_1 %bb.5, debug-location !DILocation(line: 22
+# FOLD: bb.4.third:
+# FOLD: SEH_REGION_BARRIER
+# FOLD-NEXT: $eax = MOV32ri -7
+
+---
+name: fold_without_regions
+tracksRegLiveness: true
+body: |
+  bb.0.entry:
+    successors: %bb.1, %bb.2
+    liveins: $ecx
+    TEST32rr $ecx, $ecx, implicit-def $eflags
+    JCC_1 %bb.2, 5, implicit $eflags
+
+  bb.1.first:
+    successors: %bb.3
+    $ecx = MOV32ri 1
+    $eax = MOV32ri -7
+    JMP_1 %bb.3
+
+  bb.2.second:
+    successors: %bb.3
+    $ecx = MOV32ri 1
+    $eax = MOV32ri -7
+    JMP_1 %bb.3
+
+  bb.3.exit:
+    liveins: $eax
+    RET 0, $eax
+...
+
+# FOLD-LABEL: name: fold_without_regions
+# FOLD: $eax = MOV32ri -7
+# FOLD-NOT: $eax = MOV32ri -7
\ No newline at end of file
diff --git a/llvm/test/Transforms/InstCombine/seh-region-sinking.ll b/llvm/test/Transforms/InstCombine/seh-region-sinking.ll
new file mode 100644
index 0000000000000..c4b10d4feb57b
--- /dev/null
+++ b/llvm/test/Transforms/InstCombine/seh-region-sinking.ll
@@ -0,0 +1,140 @@
+; RUN: opt -passes=instcombine -verify-each -S < %s | FileCheck %s
+; RUN: opt -mtriple=x86_64-pc-windows-msvc -passes='require<profile-summary>,function(codegenprepare)' -verify-each -S < %s | FileCheck %s --check-prefix=CGP
+; RUN: sed '/!llvm.module.flags/d' %s | opt -passes=instcombine -verify-each -S | FileCheck %s --check-prefix=NOASYNC
+
+declare void @llvm.seh.try.begin()
+declare void @llvm.seh.try.end()
+declare i32 @__C_specific_handler(...)
+
+define i32 @no_sink_into_try(ptr %address, i32 %number) personality ptr @__C_specific_handler {
+entry:
+  %multiply = mul i32 %number, 3
+  %add = add i32 %multiply, 7
+  invoke void @llvm.seh.try.begin() to label %body unwind label %dispatch
+body:
+  %value = load volatile i32, ptr %address
+  %sum = add i32 %add, %value
+  invoke void @llvm.seh.try.end() to label %join unwind label %dispatch
+dispatch:
+  %switch = catchswitch within none [label %handler] unwind to caller
+handler:
+  %pad = catchpad within %switch [ptr null]
+  catchret from %pad to label %join
+join:
+  %result = phi i32 [ %sum, %body ], [ -1, %handler ]
+  ret i32 %result
+}
+
+; CHECK-LABEL: define i32 @no_sink_into_try(
+; CHECK: entry:
+; CHECK-NEXT: [[MULTIPLY:%.*]] = mul i32 %number, 3
+; CHECK-NEXT: [[ADD:%.*]] = add i32 [[MULTIPLY]], 7
+; CHECK-NEXT: invoke void @llvm.seh.try.begin()
+
+; NOASYNC-LABEL: define i32 @no_sink_into_try(
+; NOASYNC: entry:
+; NOASYNC-NEXT: invoke void @llvm.seh.try.begin()
+; NOASYNC: body:
+; NOASYNC-NEXT: [[UNGUARDED_MUL:%.*]] = mul i32 %number, 3
+; NOASYNC-NEXT: [[UNGUARDED_ADD:%.*]] = add i32 [[UNGUARDED_MUL]], 7
+
+define i32 @sink_within_try(ptr %address, i32 %number, i1 %condition) personality ptr @__C_specific_handler {
+entry:
+  invoke void @llvm.seh.try.begin() to label %body unwind label %dispatch
+body:
+  %multiply = mul i32 %number, 3
+  br i1 %condition, label %use, label %end
+use:
+  %value = load volatile i32, ptr %address
+  %sum = add i32 %multiply, %value
+  br label %end
+end:
+  %value.end = phi i32 [ %sum, %use ], [ 0, %body ]
+  invoke void @llvm.seh.try.end() to label %join unwind label %dispatch
+dispatch:
+  %switch = catchswitch within none [label %handler] unwind to caller
+handler:
+  %pad = catchpad within %switch [ptr null]
+  catchret from %pad to label %join
+join:
+  %result = phi i32 [ %value.end, %end ], [ -1, %handler ]
+  ret i32 %result
+}
+
+; CHECK-LABEL: define i32 @sink_within_try(
+; CHECK: use:
+; CHECK-NEXT: [[SAME:%.*]] = mul i32 %number, 3
+
+define i32 @no_sink_out_of_try(i32 %number) personality ptr @__C_specific_handler {
+entry:
+  invoke void @llvm.seh.try.begin() to label %body unwind label %dispatch
+body:
+  %multiply = mul i32 %number, 5
+  invoke void @llvm.seh.try.end() to label %join unwind label %dispatch
+dispatch:
+  %switch = catchswitch within none [label %handler] unwind to caller
+handler:
+  %pad = catchpad within %switch [ptr null]
+  catchret from %pad to label %fail
+join:
+  %result = add i32 %multiply, 7
+  ret i32 %result
+fail:
+  ret i32 -1
+}
+
+; CHECK-LABEL: define i32 @no_sink_out_of_try(
+; CHECK: body:
+; CHECK-NEXT: %multiply = mul i32 %number, 5
+; CHECK-NEXT: invoke void @llvm.seh.try.end()
+
+define void @no_sink_cast_or_compare(ptr %address, i64 %wide, i32 %number) personality ptr @__C_specific_handler {
+entry:
+  %truncate = trunc i64 %wide to i32
+  %compare = icmp eq i32 %number, 0
+  invoke void @llvm.seh.try.begin() to label %body unwind label %dispatch
+body:
+  store volatile i32 %truncate, ptr %address
+  %select = select i1 %compare, i32 3, i32 4
+  store volatile i32 %select, ptr %address
+  invoke void @llvm.seh.try.end() to label %exit unwind label %dispatch
+dispatch:
+  %switch = catchswitch within none [label %handler] unwind to caller
+handler:
+  %pad = catchpad within %switch [ptr null]
+  catchret from %pad to label %exit
+exit:
+  ret void
+}
+
+; CGP-LABEL: define void @no_sink_cast_or_compare(
+; CGP: entry:
+; CGP-NEXT: %truncate = trunc i64 %wide to i32
+; CGP-NEXT: %compare = icmp eq i32 %number, 0
+; CGP-NEXT: invoke void @llvm.seh.try.begin()
+
+define void @no_sink_mask(ptr %address, i32 %number) personality ptr @__C_specific_handler {
+entry:
+  %mask = and i32 %number, 7
+  invoke void @llvm.seh.try.begin() to label %body unwind label %dispatch
+body:
+  %compare = icmp eq i32 %mask, 0
+  %select = select i1 %compare, i32 3, i32 4
+  store volatile i32 %select, ptr %address
+  invoke void @llvm.seh.try.end() to label %exit unwind label %dispatch
+dispatch:
+  %switch = catchswitch within none [label %handler] unwind to caller
+handler:
+  %pad = catchpad within %switch [ptr null]
+  catchret from %pad to label %exit
+exit:
+  ret void
+}
+
+; CGP-LABEL: define void @no_sink_mask(
+; CGP: entry:
+; CGP-NEXT: %mask = and i32 %number, 7
+; CGP-NEXT: invoke void @llvm.seh.try.begin()
+
+!llvm.module.flags = !{!0}
+!0 = !{i32 1, !"eh-asynch", i32 1}
\ No newline at end of file

>From 92b77dd2b0063b8d3d979e4847d3f53f2bcd486b Mon Sep 17 00:00:00 2001
From: Yassine Missoum <mmissoum at microsoft.com>
Date: Wed, 16 Sep 2026 14:32:30 -0700
Subject: [PATCH 3/3] [WinEH] Document asynchronous SEH region invariants

Explain region-state tracking, zero-code barriers, scope endpoints, and protected instruction insertion and motion constraints. Comments only; no functional changes.

Assisted-by: GitHub Copilot (via VS Code)
---
 llvm/include/llvm/CodeGen/MachineBasicBlock.h |  9 ++++
 llvm/include/llvm/IR/EHPersonalities.h        | 10 +++++
 llvm/include/llvm/Support/TargetOpcodes.def   |  2 +
 llvm/include/llvm/Target/Target.td            |  3 ++
 llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp    | 11 +++--
 llvm/lib/CodeGen/AsmPrinter/WinException.cpp  | 42 +++++++++++++++----
 llvm/lib/CodeGen/AsmPrinter/WinException.h    |  6 +++
 llvm/lib/CodeGen/BranchFolding.cpp            |  9 +++-
 llvm/lib/CodeGen/CodeGenPrepare.cpp           |  9 +++-
 llvm/lib/CodeGen/MachineBasicBlock.cpp        | 14 +++++++
 llvm/lib/CodeGen/MachineLICM.cpp              |  6 ++-
 llvm/lib/CodeGen/MachineSink.cpp              |  5 +++
 llvm/lib/CodeGen/PHIEliminationUtils.cpp      |  5 ++-
 llvm/lib/CodeGen/RegAllocFast.cpp             |  9 ++--
 .../CodeGen/SelectionDAG/SelectionDAGISel.cpp | 19 ++++++++-
 llvm/lib/CodeGen/SplitKit.cpp                 |  3 ++
 llvm/lib/CodeGen/WinEHPrepare.cpp             |  6 +++
 llvm/lib/IR/EHPersonalities.cpp               | 12 ++++++
 .../InstCombine/InstructionCombining.cpp      |  3 ++
 19 files changed, 161 insertions(+), 22 deletions(-)

diff --git a/llvm/include/llvm/CodeGen/MachineBasicBlock.h b/llvm/include/llvm/CodeGen/MachineBasicBlock.h
index a29317e4e2930..fcbc4edd751b3 100644
--- a/llvm/include/llvm/CodeGen/MachineBasicBlock.h
+++ b/llvm/include/llvm/CodeGen/MachineBasicBlock.h
@@ -925,7 +925,16 @@ class MachineBasicBlock
     return const_cast<MachineBasicBlock *>(this)->getFirstTerminator();
   }
 
+  /// Insert block-local code before terminators and all trailing SEH end
+  /// markers. Using getFirstTerminator() alone can put copies or spills past
+  /// the range's exclusive end, where they no longer have the block's
+  /// protection.
   LLVM_ABI iterator getInsertPtBeforeTerminators();
+
+  /// Compare known SEH states for blocks in the same function. With an active
+  /// table-SEH state map, unknown block identities do not compare equal. Other
+  /// modes impose no restriction here; instruction-level legality still
+  /// applies.
   LLVM_ABI bool hasSameSEHRegion(const MachineBasicBlock &Other) const;
   const_iterator getInsertPtBeforeTerminators() const {
     return const_cast<MachineBasicBlock *>(this)
diff --git a/llvm/include/llvm/IR/EHPersonalities.h b/llvm/include/llvm/IR/EHPersonalities.h
index 95622a3213efe..c42329feb032e 100644
--- a/llvm/include/llvm/IR/EHPersonalities.h
+++ b/llvm/include/llvm/IR/EHPersonalities.h
@@ -108,12 +108,22 @@ inline bool isNoOpWithoutInvoke(EHPersonality Pers) {
 
 LLVM_ABI bool canSimplifyInvokeNoUnwind(const Function *F);
 
+/// Snapshot of the protecting EH pad for blocks in table-based asynchronous
+/// SEH. Scope-table dispatch depends on where an instruction executes, so
+/// moving it between regions can change the handler that observes a fault.
+/// Recompute this information after changing the CFG or the try markers.
 class LLVM_ABI SEHTryRegionInfo {
 public:
   explicit SEHTryRegionInfo(const Function &F);
+
+  /// Whether region membership permits the move, not a complete legality check.
+  /// With active region tracking, different blocks must have known, equal
+  /// regions. Without applicable markers, this query imposes no restriction.
   bool isSameRegion(const BasicBlock *From, const BasicBlock *To) const;
 
 private:
+  // An empty map disables this analysis. Otherwise, an absent key is unvisited,
+  // nullopt is ambiguous, and an engaged null pointer means unwind to caller.
   DenseMap<const BasicBlock *, std::optional<const BasicBlock *>> RegionOf;
 };
 
diff --git a/llvm/include/llvm/Support/TargetOpcodes.def b/llvm/include/llvm/Support/TargetOpcodes.def
index dbabed8169c47..2100edc5eb6c2 100644
--- a/llvm/include/llvm/Support/TargetOpcodes.def
+++ b/llvm/include/llvm/Support/TargetOpcodes.def
@@ -235,6 +235,8 @@ HANDLE_TARGET_OPCODE(FAKE_USE)
 // barrier, but does not correspond to any generated instruction.
 HANDLE_TARGET_OPCODE(MEMBARRIER)
 
+// Pins a table-SEH region boundary for machine passes. It has compiler-visible
+// memory effects but emits no instruction; it is not a runtime memory fence.
 HANDLE_TARGET_OPCODE(SEH_REGION_BARRIER)
 
 // Provides information about what jump table the following indirect branch is
diff --git a/llvm/include/llvm/Target/Target.td b/llvm/include/llvm/Target/Target.td
index 6a405d89ec2b8..b2c2f39741404 100644
--- a/llvm/include/llvm/Target/Target.td
+++ b/llvm/include/llvm/Target/Target.td
@@ -1678,6 +1678,9 @@ def MEMBARRIER : StandardPseudoInstruction {
   let Size = 0;
   let isMeta = true;
 }
+// Unlike MEMBARRIER, this is deliberately not isMeta: dependency analysis must
+// see its memory effects to keep accesses from crossing an SEH range boundary.
+// The effects model compiler ordering only; AsmPrinter emits no instruction.
 def SEH_REGION_BARRIER : StandardPseudoInstruction {
   let OutOperandList = (outs);
   let InOperandList = (ins);
diff --git a/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp b/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
index 859e2023ec535..f442dde2a75dc 100644
--- a/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
@@ -2189,6 +2189,9 @@ void AsmPrinter::emitFunctionBody() {
         //  Div with variable opnds won't be the first instruction in
         //  an EH region as it must be led by at least a Load
         {
+          // The region barrier advertises memory effects to optimizers, but it
+          // cannot fault or emit code. Padding it would add a spurious NOP at a
+          // boundary that may intentionally delimit an empty range.
           auto MI2 = std::next(MI.getIterator());
           if (IsEHa && MI2 != MBB.end() &&
               MI2->getOpcode() != TargetOpcode::SEH_REGION_BARRIER &&
@@ -2240,6 +2243,7 @@ void AsmPrinter::emitFunctionBody() {
           OutStreamer->emitRawComment("ARITH_FENCE");
         break;
       case TargetOpcode::SEH_REGION_BARRIER:
+        // This is compiler ordering, not a hardware fence or a trapping access.
         if (isVerbose())
           OutStreamer->emitRawComment("SEH_REGION_BARRIER");
         break;
@@ -2368,9 +2372,10 @@ void AsmPrinter::emitFunctionBody() {
       ++PrefetchTargetIt;
     }
 
-    // We must emit temporary symbol for the end of this basic block, if either
-    // we have BBLabels enabled or if this basic blocks marks the end of a
-    // section.
+    // Besides address maps and section sizes, asynchronous table SEH needs
+    // final block ends to cover trailing branches or stop a run at a layout
+    // gap. An EH_LABEL before the terminators cannot name that exclusive
+    // endpoint.
     if (MF->getTarget().Options.BBAddrMap ||
         (MAI.hasDotTypeDotSizeDirective() && MBB.isEndSection()) ||
         (MF->getFunction().getParent()->getModuleFlag("eh-asynch") &&
diff --git a/llvm/lib/CodeGen/AsmPrinter/WinException.cpp b/llvm/lib/CodeGen/AsmPrinter/WinException.cpp
index d510a96fa240d..93723c797e45b 100644
--- a/llvm/lib/CodeGen/AsmPrinter/WinException.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/WinException.cpp
@@ -84,6 +84,9 @@ void WinException::beginFunction(const MachineFunction *MF) {
     Per = classifyEHPersonality(PerFn);
   }
 
+  // Range endpoints must describe the final layout, not the block identities
+  // that existed at ISel. Restrict this adjustment to asynchronous table SEH;
+  // C++ EH has a different state model and retains its existing range handling.
   if (Per == EHPersonality::MSVC_TableSEH &&
       F.getParent()->getModuleFlag("eh-asynch")) {
     const WinEHFuncInfo *EHInfo = MF->getWinEHFuncInfo();
@@ -91,6 +94,8 @@ void WinException::beginFunction(const MachineFunction *MF) {
     for (const auto &Range : EHInfo->LabelToStateMap)
       if (Range.second.first >= 0)
         RangeEnds.insert(Range.second.second);
+    // Ordering and equality are sufficient for clamping and empty-range checks;
+    // these positions are not estimates of instruction sizes or byte addresses.
     unsigned Position = 0;
     for (const MachineBasicBlock &MBB : *MF) {
       for (const MachineInstr &MI : MBB) {
@@ -101,6 +106,10 @@ void WinException::beginFunction(const MachineFunction *MF) {
           ++Position;
       }
       SEHLabelPositions[MBB.getEndSymbol()] = Position;
+      // EH_LABEL cannot follow a terminator. Extend only over trailing
+      // branches, stopping at another label or any other real instruction. In
+      // particular, returns, tail calls and frame teardown must not acquire
+      // this protection.
       bool HasBranch = false;
       for (const MachineInstr &MI : reverse(MBB)) {
         if (MI.isEHLabel()) {
@@ -488,6 +497,9 @@ class InvokeStateChangeIterator {
 private:
   InvokeStateChangeIterator &scan();
 
+  // Splitting or placing blocks can move a registered end past the next run.
+  // Shorten such a range at the known boundary; missing position information
+  // must not justify inventing a different endpoint.
   const MCSymbol *clampEnd(const MCSymbol *End,
                            const MCSymbol *Boundary) const {
     if (!Positions || !End)
@@ -504,9 +516,13 @@ class InvokeStateChangeIterator {
   bool isUnlabelledSEHGap(const MachineBasicBlock &MBB) const {
     if (!Positions)
       return false;
+    // A block split after ISel may have a known unguarded state but no range
+    // labels. Continuing a preceding run across its code would over-cover it.
     auto State = EHInfo.BlockToStateMap.find(MBB.getBasicBlock());
     if (State == EHInfo.BlockToStateMap.end() || State->second != BaseState)
       return false;
+    // When registered labels are present, they describe the transitions within
+    // the block more precisely than its entry state. Let the label scan decide.
     for (const MachineInstr &MI : MBB)
       if (MI.isEHLabel() &&
           EHInfo.LabelToStateMap.contains(MI.getOperand(0).getMCSymbol()))
@@ -525,6 +541,8 @@ class InvokeStateChangeIterator {
   InvokeStateChange LastStateChange;
   bool VisitingInvoke = false;
   int BaseState;
+  // Supplied only by asynchronous table-SEH emission. Other users of this
+  // iterator must not apply its region-gap or frame-teardown rules.
   const DenseMap<const MCSymbol *, unsigned> *Positions;
   const MachineBasicBlock *StateCheckedBlock = nullptr;
   bool SawFrameDestroy = false;
@@ -537,6 +555,8 @@ InvokeStateChangeIterator &InvokeStateChangeIterator::scan() {
   for (; MFI != MFE; ++MFI, IsNewBlock = true) {
     if (IsNewBlock)
       MBBI = MFI->begin();
+    // A transition returns without consuming this block. Check it only once so
+    // the next scan can process its labels against the reset base state.
     if (StateCheckedBlock != &*MFI) {
       StateCheckedBlock = &*MFI;
       if (LastStateChange.NewState != BaseState && isUnlabelledSEHGap(*MFI)) {
@@ -568,7 +588,7 @@ InvokeStateChangeIterator &InvokeStateChangeIterator::scan() {
         return *this;
       }
 
-      // All other state changes are at EH labels before/after invokes.
+      // Registered labels describe invoke ranges and asynchronous block ranges.
       if (!MI.isEHLabel())
         continue;
       MCSymbol *Label = MI.getOperand(0).getMCSymbol();
@@ -586,6 +606,10 @@ InvokeStateChangeIterator &InvokeStateChangeIterator::scan() {
       // we know not to treat the inoke we'll see as unwinding to caller.
       VisitingInvoke = true;
       if (NewState == LastStateChange.NewState) {
+        // Equal states do not imply a single contiguous protected run: frame
+        // teardown between them must remain outside the range. Revisit this
+        // label on the next scan so it opens a new run rather than extending
+        // it.
         if (SawFrameDestroy && NewState != BaseState) {
           LastStateChange.PreviousEndLabel = clampEnd(CurrentEndLabel, Label);
           LastStateChange.NewStartLabel = nullptr;
@@ -693,13 +717,10 @@ void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
 
   OS.emitLabel(TableBegin);
 
-  // Iterate over all the invoke try ranges. Unlike MSVC, LLVM currently only
-  // models exceptions from invokes. LLVM also allows arbitrary reordering of
-  // the code, so our tables end up looking a bit different. Rather than
-  // trying to match MSVC's tables exactly, we emit a denormalized table.  For
-  // each range of invokes in the same state, we emit table entries for all
-  // the actions that would be taken in that state. This means our tables are
-  // slightly bigger, which is OK.
+  // Emit a denormalized table for labelled invoke and asynchronous block
+  // ranges: each contiguous run lists all actions for its state. Block
+  // placement can separate same-state runs with unguarded code, so equal states
+  // alone do not justify coalescing their address ranges.
   const MCSymbol *LastStartLabel = nullptr;
   int LastEHState = -1;
   // Break out before we enter into a finally funclet.
@@ -714,6 +735,8 @@ void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
     // Emit all the actions for the state we just transitioned out of
     // if it was not the null state
     if (LastEHState != -1) {
+      // Keep the original labels for the state-change scan; substitute the
+      // extended exclusive end only when writing the scope record.
       const MCSymbol *EndLabel = StateChange.PreviousEndLabel;
       if (MCSymbol *ExtendedEnd = SEHScopeEndLabels.lookup(EndLabel))
         EndLabel = ExtendedEnd;
@@ -738,6 +761,9 @@ void WinException::emitSEHActionsForRange(const WinEHFuncInfo &FuncInfo,
   };
 
   assert(BeginLabel && EndLabel);
+  // A known non-increasing interval cannot protect an instruction address.
+  // Keep ranges with unknown positions rather than guessing that they are
+  // empty.
   auto BeginPosition = SEHLabelPositions.find(BeginLabel);
   auto EndPosition = SEHLabelPositions.find(EndLabel);
   if (BeginPosition != SEHLabelPositions.end() &&
diff --git a/llvm/lib/CodeGen/AsmPrinter/WinException.h b/llvm/lib/CodeGen/AsmPrinter/WinException.h
index fd450a46ab390..f137e2be8527f 100644
--- a/llvm/lib/CodeGen/AsmPrinter/WinException.h
+++ b/llvm/lib/CodeGen/AsmPrinter/WinException.h
@@ -51,7 +51,13 @@ class LLVM_LIBRARY_VISIBILITY WinException : public EHStreamer {
   /// The list of symbols to add to the ehcont section
   std::vector<const MCSymbol *> EHContTargets;
 
+  // Resolve these only after machine passes have finished splitting and merging
+  // blocks. Keep the EH_LABEL in place, but emit the block end as the exclusive
+  // range end when trailing branches also belong to the protected region.
   DenseMap<const MCSymbol *, MCSymbol *> SEHScopeEndLabels;
+
+  // Relative instruction positions, not byte offsets. Meta instructions and
+  // region barriers emit no code and do not separate otherwise adjacent labels.
   DenseMap<const MCSymbol *, unsigned> SEHLabelPositions;
 
   void emitCSpecificHandlerTable(const MachineFunction *MF);
diff --git a/llvm/lib/CodeGen/BranchFolding.cpp b/llvm/lib/CodeGen/BranchFolding.cpp
index 81b2ee2dd69f9..59d7778b57834 100644
--- a/llvm/lib/CodeGen/BranchFolding.cpp
+++ b/llvm/lib/CodeGen/BranchFolding.cpp
@@ -234,6 +234,9 @@ void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
   EHScopeMembership.erase(MBB);
 }
 
+// A boundary ties the block's instructions, including eligible trailing
+// branches, to an address range. A shared tail would need a new range of its
+// own.
 static bool hasSEHRegionBoundary(const MachineBasicBlock &MBB) {
   return any_of(MBB, [](const MachineInstr &MI) {
     return MI.getOpcode() == TargetOpcode::SEH_REGION_BARRIER;
@@ -655,6 +658,9 @@ ProfitableToMerge(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2,
       return false;
   }
 
+  // Equal funclets do not imply equal try regions. Even equal region states do
+  // not justify moving a suffix past its explicit end label, so conservatively
+  // reject boundary-bearing blocks instead of constructing an unlabelled tail.
   if (hasSEHRegionBoundary(*MBB1) || hasSEHRegionBoundary(*MBB2) ||
       !MBB1->hasSameSEHRegion(*MBB2))
     return false;
@@ -793,7 +799,8 @@ void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
   for (CurMPIter = std::prev(MergePotentials.end()),
       B = MergePotentials.begin();
        CurMPIter->getHash() == CurHash; --CurMPIter) {
-    // Put the unconditional branch back, if we need one.
+    // Rejected candidates need their original branch locations restored. A
+    // shared tail hash identifies matching code, not matching source locations.
     MachineBasicBlock *CurMBB = CurMPIter->getBlock();
     if (SuccBB && CurMBB != PredBB)
       FixTail(CurMBB, SuccBB, TII, CurMPIter->getBranchDebugLoc());
diff --git a/llvm/lib/CodeGen/CodeGenPrepare.cpp b/llvm/lib/CodeGen/CodeGenPrepare.cpp
index 4379184785c7d..b200340bc3cb6 100644
--- a/llvm/lib/CodeGen/CodeGenPrepare.cpp
+++ b/llvm/lib/CodeGen/CodeGenPrepare.cpp
@@ -1432,6 +1432,8 @@ bool CodeGenPrepare::simplifyOffsetableRelocate(GCStatepointInst &I) {
 /// Sink the specified cast instruction into its user blocks.
 static bool SinkCast(CastInst *CI) {
   BasicBlock *DefBB = CI->getParent();
+  // This rewrite changes instructions, not edges, so one snapshot suffices for
+  // its uses. Do not cache it across other CodeGenPrepare rewrites of the CFG.
   SEHTryRegionInfo SEHRegions(*CI->getFunction());
 
   /// InsertedCasts - Only insert a cast in each block once.
@@ -1468,10 +1470,12 @@ static bool SinkCast(CastInst *CI) {
     if (UserBB == DefBB)
       continue;
 
-    // If we have already inserted a cast into this block, use it.
+    // Preserve protection at the execution point, including the incoming edge
+    // chosen above for a PHI use, not just at the block containing the user.
     if (!SEHRegions.isSameRegion(DefBB, UserBB))
       continue;
 
+    // If we have already inserted a cast into this block, use it.
     CastInst *&InsertedCast = InsertedCasts[UserBB];
 
     if (!InsertedCast) {
@@ -1972,10 +1976,11 @@ static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI,
     if (UserBB == DefBB)
       continue;
 
-    // If we have already inserted a cmp into this block, use it.
+    // Cloning a comparison into its user's block must not change its region.
     if (!SEHRegions.isSameRegion(DefBB, UserBB))
       continue;
 
+    // If we have already inserted a cmp into this block, use it.
     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
 
     if (!InsertedCmp) {
diff --git a/llvm/lib/CodeGen/MachineBasicBlock.cpp b/llvm/lib/CodeGen/MachineBasicBlock.cpp
index b6d8174023149..55ffaa017c7ae 100644
--- a/llvm/lib/CodeGen/MachineBasicBlock.cpp
+++ b/llvm/lib/CodeGen/MachineBasicBlock.cpp
@@ -264,6 +264,9 @@ bool MachineBasicBlock::hasSameSEHRegion(const MachineBasicBlock &Other) const {
   const WinEHFuncInfo *EHInfo = getParent()->getWinEHFuncInfo();
   if (!EHInfo || EHInfo->BlockToStateMap.empty())
     return true;
+  // Unknown is not the same as the known unguarded state (-1). Treating both
+  // as unguarded would let a block without an IR counterpart accept unsafe
+  // moves.
   auto From = EHInfo->BlockToStateMap.find(getBasicBlock());
   auto To = EHInfo->BlockToStateMap.find(Other.getBasicBlock());
   return From != EHInfo->BlockToStateMap.end() &&
@@ -272,6 +275,9 @@ bool MachineBasicBlock::hasSameSEHRegion(const MachineBasicBlock &Other) const {
 
 MachineBasicBlock::iterator MachineBasicBlock::getInsertPtBeforeTerminators() {
   iterator InsertPt = getFirstTerminator();
+  // A scope's end label is exclusive. Walk above every trailing end-label /
+  // barrier pair, not just one: nested boundaries can otherwise leave inserted
+  // code protected by an outer scope but no longer by the innermost one.
   while (InsertPt != begin()) {
     iterator Marker = std::prev(InsertPt);
     while (Marker != begin() && Marker->isDebugInstr())
@@ -1235,6 +1241,9 @@ MachineBasicBlock *MachineBasicBlock::SplitCriticalEdge(
   MachineFunction *MF = getParent();
   MachineBasicBlock *PrevFallthrough = getNextNode();
 
+  // An edge block has no independent IR identity. Its copies execute on the
+  // predecessor's outgoing edge, so retain that identity for SEH state lookup.
+  // Leave other modes unchanged, including their normal block naming.
   const BasicBlock *EdgeBB = nullptr;
   const Function &Function = MF->getFunction();
   if (Function.getParent()->getModuleFlag("eh-asynch") &&
@@ -1330,10 +1339,15 @@ MachineBasicBlock *MachineBasicBlock::SplitCriticalEdge(
     TII->insertBranch(*NMBB, Succ, nullptr, Cond, DL);
   }
 
+  // This block was created after ISel assigned ranges. Inheriting an IR block
+  // supplies the state, but not labels for its new instructions. Seed a range
+  // now so later PHI copies use the protected insertion point; the normal
+  // successor, liveness and index updates still apply to this split.
   if (EdgeBB) {
     if (WinEHFuncInfo *EHInfo = MF->getWinEHFuncInfo()) {
       auto State = EHInfo->BlockToStateMap.find(EdgeBB);
       if (State != EHInfo->BlockToStateMap.end() && State->second >= 0) {
+        // Barriers are non-meta instructions and need SlotIndexes when present.
         SlotIndexUpdateDelegate SlotUpdater(*MF, Indexes);
         const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
         auto InsertPt = NMBB->getFirstTerminator();
diff --git a/llvm/lib/CodeGen/MachineLICM.cpp b/llvm/lib/CodeGen/MachineLICM.cpp
index 7b48fa63d8a28..f43a8c9a6b168 100644
--- a/llvm/lib/CodeGen/MachineLICM.cpp
+++ b/llvm/lib/CodeGen/MachineLICM.cpp
@@ -743,7 +743,9 @@ void MachineLICMImpl::HoistPostRA(MachineInstr *MI, Register Def,
                     << " from " << printMBBReference(*MI->getParent()) << ": "
                     << *MI);
 
-  // Splice the instruction to the preheader.
+  // A valid insertion point cannot make a cross-region hoist safe: first keep
+  // the same protecting handler, then insert before the preheader's end
+  // markers.
   MachineBasicBlock *MBB = MI->getParent();
   if (!MBB->hasSameSEHRegion(*Preheader))
     return;
@@ -1613,6 +1615,8 @@ bool MachineLICMImpl::MayCSE(MachineInstr *MI) {
 unsigned MachineLICMImpl::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader,
                                 MachineLoop *CurLoop) {
   MachineBasicBlock *SrcBlock = MI->getParent();
+  // Check before either hoisting or CSE can replace the instruction with a
+  // computation outside its protected region.
   if (!SrcBlock->hasSameSEHRegion(*Preheader))
     return 0;
 
diff --git a/llvm/lib/CodeGen/MachineSink.cpp b/llvm/lib/CodeGen/MachineSink.cpp
index 00ce3733d88c0..fd0244e12461a 100644
--- a/llvm/lib/CodeGen/MachineSink.cpp
+++ b/llvm/lib/CodeGen/MachineSink.cpp
@@ -1498,6 +1498,9 @@ MachineSinking::FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
   if (SuccToSinkTo && SuccToSinkTo->isEHPad())
     return nullptr;
 
+  // A legal CFG destination is not enough: the instruction must keep the same
+  // protecting handler. Barriers constrain ordering inside a block, but do not
+  // by themselves make motion between differently guarded blocks legal.
   if (SuccToSinkTo && !MBB->hasSameSEHRegion(*SuccToSinkTo))
     return nullptr;
 
@@ -2341,6 +2344,8 @@ bool PostRAMachineSinkingImpl::tryToSinkCopy(MachineBasicBlock &CurBB,
            "Unexpected predecessor");
 
     if (!CurBB.hasSameSEHRegion(*SuccBB)) {
+      // The copy stays put, so subsequent candidates must still see its
+      // register effects even though we declined to move it.
       LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
                                         TRI);
       continue;
diff --git a/llvm/lib/CodeGen/PHIEliminationUtils.cpp b/llvm/lib/CodeGen/PHIEliminationUtils.cpp
index b89566264c2b2..330d6829f0171 100644
--- a/llvm/lib/CodeGen/PHIEliminationUtils.cpp
+++ b/llvm/lib/CodeGen/PHIEliminationUtils.cpp
@@ -37,8 +37,9 @@ llvm::findPHICopyInsertPoint(MachineBasicBlock* MBB, MachineBasicBlock* SuccMBB,
   if (MBB->empty())
     return MBB->begin();
 
-  // Usually, we just want to insert the copy before the first terminator
-  // instruction. However, for the edge going to a landing pad, we must insert
+  // On a normal edge, insert before both terminators and SEH end markers: the
+  // incoming value's copy belongs to the predecessor's region, including when
+  // it later becomes a stack access. For an edge to a landing pad, insert
   // the copy before the call/invoke instruction. Similarly for an INLINEASM_BR
   // going to an indirect target. This is similar to SplitKit.cpp's
   // computeLastInsertPoint, and similarly assumes that there cannot be multiple
diff --git a/llvm/lib/CodeGen/RegAllocFast.cpp b/llvm/lib/CodeGen/RegAllocFast.cpp
index a893162421956..6288b36027ea8 100644
--- a/llvm/lib/CodeGen/RegAllocFast.cpp
+++ b/llvm/lib/CodeGen/RegAllocFast.cpp
@@ -677,13 +677,14 @@ void RegAllocFastImpl::reload(MachineBasicBlock::iterator Before,
   ++NumLoads;
 }
 
-/// Get basic block begin insertion point.
-/// This is not just MBB.begin() because surprisingly we have EH_LABEL
-/// instructions marking the begin of a basic block. This means we must insert
-/// new instructions after such labels...
+/// Find an entry reload point after labels and prologues, but before SEH end
+/// markers. Reloads serving this block must retain its exception protection.
 MachineBasicBlock::iterator RegAllocFastImpl::getMBBBeginInsertionPoint(
     MachineBasicBlock &MBB, SmallSet<Register, 2> &PrologLiveIns) const {
   MachineBasicBlock::iterator I = MBB.begin();
+  // The pair order matters: skip barrier/begin-label at entry, but stop before
+  // end-label/barrier even if the range has no other instructions yet. A scan
+  // that skips only labels would put a reload outside the protected range.
   while (I != MBB.end()) {
     if (I->isEHLabel() && std::next(I) != MBB.end() &&
         std::next(I)->getOpcode() == TargetOpcode::SEH_REGION_BARRIER)
diff --git a/llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp b/llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp
index 2564f913793cd..a307b9e162d13 100644
--- a/llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp
@@ -1494,7 +1494,9 @@ bool SelectionDAGISel::PrepareEHLandingPad() {
   return true;
 }
 
-// Mark and Report IPToState for each Block under IsEHa
+// Called for eh-asynch modules. Table-SEH ranges must describe protected code,
+// not just calls, and their boundaries must survive later machine passes.
+// Other personalities retain their existing asynchronous state handling below.
 void SelectionDAGISel::reportIPToStateForBlocks(MachineFunction *MF) {
   llvm::WinEHFuncInfo *EHInfo = MF->getWinEHFuncInfo();
   if (!EHInfo)
@@ -1508,6 +1510,7 @@ void SelectionDAGISel::reportIPToStateForBlocks(MachineFunction *MF) {
     if (!BB)
       continue;
     if (IsTableSEH) {
+      // Missing state information is not evidence that the block is unguarded.
       auto StateIt = EHInfo->BlockToStateMap.find(BB);
       if (StateIt == EHInfo->BlockToStateMap.end())
         continue;
@@ -1516,15 +1519,22 @@ void SelectionDAGISel::reportIPToStateForBlocks(MachineFunction *MF) {
       if (Begin == MBB.end())
         continue;
       auto End = MBB.getFirstTerminator();
+      // A branch-only block can still need coverage: scope emission can extend
+      // its end past the branch. Do not create such a range for a bare return.
       if (Begin == End && !MBB.back().isBranch())
         continue;
 
+      // Invoke labels already describe their call. Add only a preceding range
+      // for the block's prefix, rather than nesting a new range around them.
       auto FirstEHLabel = llvm::find_if(
           MBB, [](const MachineInstr &MI) { return MI.isEHLabel(); });
       if (FirstEHLabel != MBB.end()) {
         if (State < 0)
           continue;
         if (Begin == FirstEHLabel) {
+          // Labels alone are skipped by machine insertion-point scans. The
+          // barrier must precede the label so moved-in code cannot silently
+          // become part of its protected range.
           BuildMI(MBB, Begin, DebugLoc(),
                   TII->get(TargetOpcode::SEH_REGION_BARRIER));
           continue;
@@ -1532,6 +1542,10 @@ void SelectionDAGISel::reportIPToStateForBlocks(MachineFunction *MF) {
         End = FirstEHLabel;
       }
 
+      // Even an unguarded (-1) block needs labels when otherwise unlabelled, so
+      // the table scan can stop an earlier protected run before that code.
+      // Empty debug locations avoid attributing these zero-code boundaries to
+      // whichever source instruction happened to be selected last.
       MCSymbol *BeginLabel = MF->getContext().createTempSymbol();
       MCSymbol *EndLabel = MF->getContext().createTempSymbol();
       EHInfo->addIPToStateRange(State, BeginLabel, EndLabel);
@@ -1542,6 +1556,9 @@ void SelectionDAGISel::reportIPToStateForBlocks(MachineFunction *MF) {
           .addSym(BeginLabel);
       BuildMI(MBB, End, DebugLoc(), TII->get(TargetOpcode::EH_LABEL))
           .addSym(EndLabel);
+      // The end-label/barrier pair lets late copies and spills find an
+      // insertion point inside the range. A prefix ending at an invoke uses its
+      // labels.
       if (State >= 0 && FirstEHLabel == MBB.end())
         BuildMI(MBB, End, DebugLoc(),
                 TII->get(TargetOpcode::SEH_REGION_BARRIER));
diff --git a/llvm/lib/CodeGen/SplitKit.cpp b/llvm/lib/CodeGen/SplitKit.cpp
index 58eb4ccdda509..11f35043669a1 100644
--- a/llvm/lib/CodeGen/SplitKit.cpp
+++ b/llvm/lib/CodeGen/SplitKit.cpp
@@ -82,6 +82,9 @@ InsertPointAnalysis::computeLastInsertPoint(const LiveInterval &CurLI,
   // Compute insert points on the first call. The pair is independent of the
   // current live interval.
   if (!LIP.first.isValid()) {
+    // Bound register-allocation insertions by the protected end of the block,
+    // not just its branch. EH_LABEL is meta and has no SlotIndex, so obtain the
+    // index from the next indexed boundary instruction instead of the label.
     MachineBasicBlock::const_iterator FirstTerm =
         MBB.getInsertPtBeforeTerminators();
     while (FirstTerm != MBB.end() &&
diff --git a/llvm/lib/CodeGen/WinEHPrepare.cpp b/llvm/lib/CodeGen/WinEHPrepare.cpp
index 7aebb1b91d6a3..8d5a2bc963311 100644
--- a/llvm/lib/CodeGen/WinEHPrepare.cpp
+++ b/llvm/lib/CodeGen/WinEHPrepare.cpp
@@ -322,6 +322,9 @@ void llvm::calculateSEHStateForAsynchEH(const BasicBlock *BB, int State,
     if (It->isEHPad())
       State = EHInfo.EHPadStateMap[&*It];
 
+    // An ordinary catchpad executes outside the try it handles. Record the
+    // enclosing state before walking the handler body, which may span several
+    // blocks; recording the pad's own state would make it protect itself.
     if (isa<CatchPadInst>(It)) {
       const Constant *FilterOrNull = cast<Constant>(
           cast<CatchPadInst>(It)->getArgOperand(0)->stripPointerCasts());
@@ -331,6 +334,9 @@ void llvm::calculateSEHStateForAsynchEH(const BasicBlock *BB, int State,
     }
     EHInfo.BlockToStateMap[BB] = State; // Record state
 
+    // Catchret does not pop another state: that happened on catchpad entry.
+    // Process other terminators separately so a nested try starting in a
+    // handler can still change the state of its normal successor.
     if (isa<CleanupReturnInst>(TI) && State > 0) {
       // Retrive the new State.
       State = EHInfo.SEHUnwindMap[State].ToState; // Retrive next State
diff --git a/llvm/lib/IR/EHPersonalities.cpp b/llvm/lib/IR/EHPersonalities.cpp
index 7a67bdbbc42ce..a6f2d3a950c6d 100644
--- a/llvm/lib/IR/EHPersonalities.cpp
+++ b/llvm/lib/IR/EHPersonalities.cpp
@@ -124,6 +124,9 @@ static const InvokeInst *getSEHTryMarker(const BasicBlock *BB) {
 }
 
 SEHTryRegionInfo::SEHTryRegionInfo(const Function &F) {
+  // Do not impose SEH region rules on C++ personalities or infer this mode from
+  // markers alone. Its interpretation requires the asynchronous table-SEH
+  // contract as well as explicit try markers.
   if (!F.getParent()->getModuleFlag("eh-asynch") || !F.hasPersonalityFn() ||
       classifyEHPersonality(F.getPersonalityFn()) !=
           EHPersonality::MSVC_TableSEH)
@@ -135,6 +138,7 @@ SEHTryRegionInfo::SEHTryRegionInfo(const Function &F) {
     return;
 
   using Region = std::optional<const BasicBlock *>;
+  // The normal edge of try.end restores the region enclosing its matching try.
   DenseMap<const BasicBlock *, Region> Parents;
   SmallVector<const BasicBlock *, 32> Worklist;
   auto Assign = [&](const BasicBlock *BB, Region NewRegion) {
@@ -142,6 +146,8 @@ SEHTryRegionInfo::SEHTryRegionInfo(const Function &F) {
     if (Inserted) {
       Worklist.push_back(BB);
     } else if (Position->second && Position->second != NewRegion) {
+      // Conflicting paths lose precision permanently; never pick one handler
+      // according to traversal order and authorize a cross-region move.
       Position->second = std::nullopt;
       Worklist.push_back(BB);
     }
@@ -155,9 +161,13 @@ SEHTryRegionInfo::SEHTryRegionInfo(const Function &F) {
     if (const InvokeInst *Marker = getSEHTryMarker(BB)) {
       if (Marker->getIntrinsicID() == Intrinsic::seh_try_begin) {
         const BasicBlock *Pad = Marker->getUnwindDest();
+        // Only the normal successor enters the protected region. The handler
+        // itself runs under the enclosing region, not under its own protection.
         Normal = Pad;
         auto [Parent, Inserted] = Parents.try_emplace(Pad, Current);
         if (!Inserted && Parent->second != Current) {
+          // Earlier try.end results may depend on this parent assignment.
+          // Invalidate all answers rather than retaining traversal-order facts.
           for (auto &KnownRegion : RegionOf)
             KnownRegion.second = std::nullopt;
           return;
@@ -170,6 +180,8 @@ SEHTryRegionInfo::SEHTryRegionInfo(const Function &F) {
     }
 
     for (const BasicBlock *Successor : successors(BB)) {
+      // Handlers are seeded from try.begin above. Propagating the current
+      // region down unwind edges would make a handler protect itself.
       if (const auto *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
         if (Successor == Invoke->getUnwindDest())
           continue;
diff --git a/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp b/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp
index 5d87bceacca40..5aca575e2bb96 100644
--- a/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp
@@ -5565,6 +5565,9 @@ bool InstCombinerImpl::tryToSinkInstruction(Instruction *I,
   if (isa<CatchSwitchInst>(DestBlock->getTerminator()))
     return false;
 
+  // Keep the instruction under the same handler even if ordinary use/dominance
+  // checks allow sinking. InstCombine can edit the CFG and markers between
+  // attempts, so do not reuse a region snapshot from an earlier attempt.
   if (F.getParent()->getModuleFlag("eh-asynch") &&
       !SEHTryRegionInfo(F).isSameRegion(SrcBlock, DestBlock))
     return false;



More information about the llvm-commits mailing list