https://github.com/xlauko created 
https://github.com/llvm/llvm-project/pull/246635

Stack description follows.

>From 5ade720d267894797732578cf97cf58435784f16 Mon Sep 17 00:00:00 2001
From: Henrich Lauko <[email protected]>
Date: Fri, 27 Nov 2026 08:37:46 +0000
Subject: [PATCH] [CIR] Replace same-region gotos with branches

CIRGen emits C/C++ gotos as symbolic cir.goto ops that name a cir.label.
They are not CFG edges, so the core rewrite driver, eraseUnreachableBlocks
and dataflow analyses treat the label's block as dead until GotoSolver runs
after FlattenCFG.

Add cir-goto-elimination, a cir.func pass that runs first in the
CIR-to-CIR pipeline and again at the start of the pre-lowering pipeline for
input that skips it. A goto whose label is in the same region becomes a
cir.br to the label's block. Gotos that cross region boundaries are left
for GotoSolver.

Add cir-erase-unused-labels, a module pass that runs right after it and
erases the labels that no goto names and whose address is not taken. It is
a module pass because global initializers can take a label's address; the
function pass reads and writes nothing outside its function. The scan for
labels whose address is taken through global and constant attributes moves
from GotoSolver into CIRTransformUtils so both passes share it.

Assisted-by: Claude Code (Opus 5.5).
---
 clang/include/clang/CIR/Dialect/Passes.h      |   2 +
 clang/include/clang/CIR/Dialect/Passes.td     |  34 ++++++
 .../Dialect/Transforms/CIRTransformUtils.h    |  12 ++
 .../Dialect/Transforms/CIRTransformUtils.cpp  |  23 ++++
 .../lib/CIR/Dialect/Transforms/CMakeLists.txt |   1 +
 .../Dialect/Transforms/GotoElimination.cpp    | 107 ++++++++++++++++++
 .../lib/CIR/Dialect/Transforms/GotoSolver.cpp |  27 +----
 clang/lib/CIR/Lowering/CIRPasses.cpp          |   6 +
 .../cleanup-scope-label-attr-block.cpp        |   1 -
 clang/test/CIR/CodeGen/goto.cpp               |  58 ++++------
 clang/test/CIR/CodeGen/label.c                |  47 ++------
 .../CIR/CodeGen/switch-pre-case-stmts.cpp     |  29 +----
 clang/test/CIR/CodeGen/unreachable-cycle.c    |   7 +-
 .../CodeGenCoroutines/coro-fallthrough.cpp    |  20 +++-
 .../test/CIR/Transforms/goto-elimination.cir  |  82 ++++++++++++++
 clang/tools/cir-opt/cir-opt.cpp               |   6 +
 16 files changed, 339 insertions(+), 123 deletions(-)
 create mode 100644 clang/lib/CIR/Dialect/Transforms/GotoElimination.cpp
 create mode 100644 clang/test/CIR/Transforms/goto-elimination.cir

diff --git a/clang/include/clang/CIR/Dialect/Passes.h 
b/clang/include/clang/CIR/Dialect/Passes.h
index 2618f0b990c694..7e7a056cbb7d75 100644
--- a/clang/include/clang/CIR/Dialect/Passes.h
+++ b/clang/include/clang/CIR/Dialect/Passes.h
@@ -40,6 +40,8 @@ createCallConvLoweringPass(cir::CallConvTarget target,
                            const llvm::abi::X86ABICompatInfo &x86AbiCompat);
 std::unique_ptr<Pass> createHoistAllocasPass();
 std::unique_ptr<Pass> createLoweringPreparePass();
+std::unique_ptr<Pass> createGotoEliminationPass();
+std::unique_ptr<Pass> createEraseUnusedLabelsPass();
 std::unique_ptr<Pass> createGotoSolverPass();
 std::unique_ptr<Pass> createIdiomRecognizerPass();
 std::unique_ptr<Pass> createLibOptPass();
diff --git a/clang/include/clang/CIR/Dialect/Passes.td 
b/clang/include/clang/CIR/Dialect/Passes.td
index faa7986257418e..3b7143dc2d5811 100644
--- a/clang/include/clang/CIR/Dialect/Passes.td
+++ b/clang/include/clang/CIR/Dialect/Passes.td
@@ -88,6 +88,40 @@ def CIRFlattenCFG : Pass<"cir-flatten-cfg"> {
   let dependentDialects = ["cir::CIRDialect"];
 }
 
+def GotoElimination : Pass<"cir-goto-elimination", "cir::FuncOp"> {
+  let summary = "Replace symbolic gotos with control-flow edges";
+  let description = [{
+    Rewrites `cir.goto` into control flow that the CFG and region-branch
+    interfaces describe. A goto whose `cir.label` is in the same region becomes
+    a `cir.br` to the label's block.
+
+    Gotos this cannot route yet are left for `cir-goto-solver`. Labels stay;
+    `cir-erase-unused-labels` erases those nothing names any more.
+  }];
+  let constructor = "mlir::createGotoEliminationPass()";
+  let dependentDialects = ["cir::CIRDialect"];
+  let statistics = [
+    Statistic<"numSameRegionGotos", "same-region-gotos",
+              "Gotos replaced with a branch in the same region">,
+  ];
+}
+
+def EraseUnusedLabels : Pass<"cir-erase-unused-labels", "mlir::ModuleOp"> {
+  let summary = "Erase labels that nothing names";
+  let description = [{
+    Erases each `cir.label` that no `cir.goto` names and whose address no
+    `cir.block_address` op and no attribute, such as a global's initializer,
+    takes. It is a module pass because those attributes can live outside the
+    label's function.
+  }];
+  let constructor = "mlir::createEraseUnusedLabelsPass()";
+  let dependentDialects = ["cir::CIRDialect"];
+  let statistics = [
+    Statistic<"numErasedLabels", "erased-labels",
+              "Labels erased because nothing refers to them">,
+  ];
+}
+
 def GotoSolver : Pass<"cir-goto-solver", "mlir::ModuleOp"> {
   let summary = "Replaces goto operations with branches";
   let description = [{
diff --git a/clang/include/clang/CIR/Dialect/Transforms/CIRTransformUtils.h 
b/clang/include/clang/CIR/Dialect/Transforms/CIRTransformUtils.h
index c30d61e0b3eeef..ac2e545b50c0a4 100644
--- a/clang/include/clang/CIR/Dialect/Transforms/CIRTransformUtils.h
+++ b/clang/include/clang/CIR/Dialect/Transforms/CIRTransformUtils.h
@@ -13,7 +13,9 @@
 #include "mlir/IR/PatternMatch.h"
 #include "clang/CIR/Dialect/IR/CIRDialect.h"
 
+#include "llvm/ADT/SetVector.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringMap.h"
 
 namespace cir {
 /// Helper type for lowering global ctor/dtors, that contain all the values
@@ -63,6 +65,16 @@ mlir::Block *replaceThrowWithTryThrow(cir::ThrowOp throwOp,
 void collectUnreachable(mlir::Operation *parent,
                         llvm::SmallVectorImpl<mlir::Operation *> &ops);
 
+/// Labels whose address is taken through attributes of `cir.global` and
+/// `cir.const` ops (`#cir.block_addr_info` and `#cir.block_addr_diff`), keyed
+/// by the name of the function they belong to. Each set keeps the walk order 
of
+/// the first reference to each label. Address-taken labels found through
+/// `cir.block_address` ops are not included: they are visible to a walk of the
+/// function itself.
+using AddressTakenLabels =
+    llvm::StringMap<llvm::SmallSetVector<llvm::StringRef, 4>>;
+AddressTakenLabels collectAddressTakenLabelsInAttributes(mlir::ModuleOp 
module);
+
 } // namespace cir
 
 #endif // LLVM_CLANG_CIR_DIALECT_TRANSFORMS_CIRTRANSFORMUTILS_H
diff --git a/clang/lib/CIR/Dialect/Transforms/CIRTransformUtils.cpp 
b/clang/lib/CIR/Dialect/Transforms/CIRTransformUtils.cpp
index 3d173cf56e6c26..2811bf7bc543c1 100644
--- a/clang/lib/CIR/Dialect/Transforms/CIRTransformUtils.cpp
+++ b/clang/lib/CIR/Dialect/Transforms/CIRTransformUtils.cpp
@@ -137,3 +137,26 @@ mlir::Block *cir::replaceThrowWithTryThrow(cir::ThrowOp 
throwOp,
 
   return normalDest;
 }
+
+cir::AddressTakenLabels
+cir::collectAddressTakenLabelsInAttributes(mlir::ModuleOp module) {
+  AddressTakenLabels labels;
+  module.walk([&](mlir::Operation *op) {
+    if (!mlir::isa<cir::GlobalOp, cir::ConstantOp>(op))
+      return;
+    op->getName().walkInherentAttrs(
+        op, [&](llvm::StringRef, mlir::Attribute &attr) {
+          attr.walk(
+              [&](cir::BlockAddrInfoAttr info) {
+                labels[info.getFunc().getValue()].insert(info.getLabel());
+              },
+              [&](cir::BlockAddrDiffAttr diff) {
+                // A difference references two labels of the same function.
+                auto &funcLabels = labels[diff.getFunc().getValue()];
+                funcLabels.insert(diff.getLhsLabel().getValue());
+                funcLabels.insert(diff.getRhsLabel().getValue());
+              });
+        });
+  });
+  return labels;
+}
diff --git a/clang/lib/CIR/Dialect/Transforms/CMakeLists.txt 
b/clang/lib/CIR/Dialect/Transforms/CMakeLists.txt
index 83bd84b72af048..0c5f39f7eadbcb 100644
--- a/clang/lib/CIR/Dialect/Transforms/CMakeLists.txt
+++ b/clang/lib/CIR/Dialect/Transforms/CMakeLists.txt
@@ -12,6 +12,7 @@ add_clang_library(MLIRCIRTransforms
   FlattenCFG.cpp
   HoistAllocas.cpp
   LoweringPrepare.cpp
+  GotoElimination.cpp
   GotoSolver.cpp
   IdiomRecognizer.cpp
   LibOpt.cpp
diff --git a/clang/lib/CIR/Dialect/Transforms/GotoElimination.cpp 
b/clang/lib/CIR/Dialect/Transforms/GotoElimination.cpp
new file mode 100644
index 00000000000000..cffb3e2e0b55cb
--- /dev/null
+++ b/clang/lib/CIR/Dialect/Transforms/GotoElimination.cpp
@@ -0,0 +1,107 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements a pass that replaces symbolic `cir.goto` operations
+// with control-flow edges, so that the CFG and the region-branch interfaces
+// describe every way into a block.
+//
+// A goto whose label is in the same region becomes a `cir.br`.
+//
+//===----------------------------------------------------------------------===//
+
+#include "PassDetail.h"
+#include "mlir/IR/PatternMatch.h"
+#include "clang/CIR/Dialect/IR/CIRDialect.h"
+#include "clang/CIR/Dialect/Passes.h"
+#include "clang/CIR/Dialect/Transforms/CIRTransformUtils.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/DenseSet.h"
+
+using namespace mlir;
+
+namespace mlir {
+#define GEN_PASS_DEF_GOTOELIMINATION
+#define GEN_PASS_DEF_ERASEUNUSEDLABELS
+#include "clang/CIR/Dialect/Passes.h.inc"
+} // namespace mlir
+
+namespace {
+
+struct GotoEliminationPass
+    : public impl::GotoEliminationBase<GotoEliminationPass> {
+  using GotoEliminationBase::GotoEliminationBase;
+
+  void runOnOperation() override;
+};
+
+struct EraseUnusedLabelsPass
+    : public impl::EraseUnusedLabelsBase<EraseUnusedLabelsPass> {
+  using EraseUnusedLabelsBase::EraseUnusedLabelsBase;
+
+  void runOnOperation() override;
+};
+
+} // namespace
+
+void GotoEliminationPass::runOnOperation() {
+  cir::FuncOp func = getOperation();
+  IRRewriter rewriter(func.getContext());
+
+  llvm::DenseMap<StringAttr, cir::LabelOp> labels;
+  SmallVector<cir::GotoOp> gotos;
+  func.getBody().walk([&](Operation *op) {
+    if (auto label = dyn_cast<cir::LabelOp>(op))
+      labels.try_emplace(label.getLabelAttr(), label);
+    else if (auto gotoOp = dyn_cast<cir::GotoOp>(op))
+      gotos.push_back(gotoOp);
+  });
+
+  for (cir::GotoOp gotoOp : gotos) {
+    Block *dest = labels.lookup(gotoOp.getLabelAttr())->getBlock();
+    // A goto this cannot route yet is left for GotoSolver.
+    if (dest->getParent() != gotoOp->getParentRegion())
+      continue;
+    rewriter.setInsertionPoint(gotoOp);
+    rewriter.replaceOpWithNewOp<cir::BrOp>(gotoOp, dest);
+    ++numSameRegionGotos;
+  }
+}
+
+void EraseUnusedLabelsPass::runOnOperation() {
+  ModuleOp module = getOperation();
+  cir::AddressTakenLabels attrLabels =
+      cir::collectAddressTakenLabelsInAttributes(module);
+  for (cir::FuncOp func : module.getOps<cir::FuncOp>()) {
+    llvm::DenseSet<StringRef> named;
+    if (auto it = attrLabels.find(func.getSymName()); it != attrLabels.end())
+      named.insert_range(it->second);
+    SmallVector<cir::LabelOp> labels;
+    func.getBody().walk([&](Operation *op) {
+      if (auto label = dyn_cast<cir::LabelOp>(op))
+        labels.push_back(label);
+      else if (auto gotoOp = dyn_cast<cir::GotoOp>(op))
+        named.insert(gotoOp.getLabel());
+      else if (auto blockAddr = dyn_cast<cir::BlockAddressOp>(op))
+        named.insert(blockAddr.getBlockAddrInfo().getLabel());
+    });
+    for (cir::LabelOp label : labels) {
+      if (named.contains(label.getLabel()))
+        continue;
+      label.erase();
+      ++numErasedLabels;
+    }
+  }
+}
+
+std::unique_ptr<Pass> mlir::createGotoEliminationPass() {
+  return std::make_unique<GotoEliminationPass>();
+}
+
+std::unique_ptr<Pass> mlir::createEraseUnusedLabelsPass() {
+  return std::make_unique<EraseUnusedLabelsPass>();
+}
diff --git a/clang/lib/CIR/Dialect/Transforms/GotoSolver.cpp 
b/clang/lib/CIR/Dialect/Transforms/GotoSolver.cpp
index 6d1b451e1a1e3f..b9dc2304b33884 100644
--- a/clang/lib/CIR/Dialect/Transforms/GotoSolver.cpp
+++ b/clang/lib/CIR/Dialect/Transforms/GotoSolver.cpp
@@ -8,6 +8,7 @@
 #include "PassDetail.h"
 #include "clang/CIR/Dialect/IR/CIRDialect.h"
 #include "clang/CIR/Dialect/Passes.h"
+#include "clang/CIR/Dialect/Transforms/CIRTransformUtils.h"
 #include "llvm/ADT/SetVector.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/Support/TimeProfiler.h"
@@ -125,31 +126,9 @@ void GotoSolverPass::runOnOperation() {
   // only attribute-carried addresses (globals, constants) that no
   // function-body walk sees. BlockAddressOp stays out so op labels keep
   // their IR-order phase instead of sorting with the attributes.
-  llvm::StringMap<llvm::SmallSetVector<StringRef, 4>> globalBlockAddrLabels;
   mlir::ModuleOp module = mlir::cast<mlir::ModuleOp>(getOperation());
-  module.walk([&](mlir::Operation *op) {
-    if (!mlir::isa<cir::GlobalOp, cir::ConstantOp>(op))
-      return;
-    auto collectBlockAddresses = [&](mlir::Attribute attr) {
-      attr.walk(
-          [&](cir::BlockAddrInfoAttr info) {
-            globalBlockAddrLabels[info.getFunc().getValue()].insert(
-                info.getLabel());
-          },
-          [&](cir::BlockAddrDiffAttr diff) {
-            // A block-address difference attribute references two labels in
-            // the same function; keep both alive.
-            llvm::SmallSetVector<StringRef, 4> &labels =
-                globalBlockAddrLabels[diff.getFunc().getValue()];
-            labels.insert(diff.getLhsLabel().getValue());
-            labels.insert(diff.getRhsLabel().getValue());
-          });
-    };
-    op->getName().walkInherentAttrs(
-        op, [&](llvm::StringRef, mlir::Attribute &attr) {
-          collectBlockAddresses(attr);
-        });
-  });
+  cir::AddressTakenLabels globalBlockAddrLabels =
+      cir::collectAddressTakenLabelsInAttributes(module);
 
   static const llvm::SmallVector<StringRef> empty;
   for (cir::FuncOp func : module.getOps<cir::FuncOp>()) {
diff --git a/clang/lib/CIR/Lowering/CIRPasses.cpp 
b/clang/lib/CIR/Lowering/CIRPasses.cpp
index 2752be5eb3fefe..65ad97fa7bc3bc 100644
--- a/clang/lib/CIR/Lowering/CIRPasses.cpp
+++ b/clang/lib/CIR/Lowering/CIRPasses.cpp
@@ -114,6 +114,8 @@ runCIRToCIRPasses(mlir::ModuleOp theModule, 
mlir::MLIRContext &mlirContext,
            << "' attribute";
 
   mlir::PassManager pm(&mlirContext);
+  pm.addNestedPass<cir::FuncOp>(mlir::createGotoEliminationPass());
+  pm.addPass(mlir::createEraseUnusedLabelsPass());
   pm.addPass(mlir::createCIRCanonicalizePass());
 
   if (enableCIRSimplify)
@@ -177,6 +179,10 @@ runCIRToCIRPasses(mlir::ModuleOp theModule, 
mlir::MLIRContext &mlirContext,
 namespace mlir {
 
 void populateCIRPreLoweringPasses(OpPassManager &pm) {
+  // Also here for input that did not go through runCIRToCIRPasses, such as
+  // -clangir-disable-passes or cir-translate. It is a no-op on its own output.
+  pm.addNestedPass<cir::FuncOp>(createGotoEliminationPass());
+  pm.addPass(createEraseUnusedLabelsPass());
   pm.addPass(createHoistAllocasPass());
   pm.addPass(createCIRFlattenCFGPass());
   pm.addPass(createCIREHABILoweringPass());
diff --git a/clang/test/CIR/CodeGen/cleanup-scope-label-attr-block.cpp 
b/clang/test/CIR/CodeGen/cleanup-scope-label-attr-block.cpp
index 51e76201c6885c..2691dbe8cb3b65 100644
--- a/clang/test/CIR/CodeGen/cleanup-scope-label-attr-block.cpp
+++ b/clang/test/CIR/CodeGen/cleanup-scope-label-attr-block.cpp
@@ -19,7 +19,6 @@ lbl: {
 }
 
 // CIR-LABEL: cir.func {{.*}} @_Z18test_labeled_blockv(
-// CIR:         cir.label "lbl"
 // CIR-NEXT:    cir.scope {
 // CIR-NEXT:      %[[A_ADDR:.*]] = cir.alloca "a" {{.*}} : 
!cir.ptr<!rec_StructWithDestructor>
 // CIR-NEXT:      cir.cleanup.scope {
diff --git a/clang/test/CIR/CodeGen/goto.cpp b/clang/test/CIR/CodeGen/goto.cpp
index 911c068dcf8d93..0fe087cf403e73 100644
--- a/clang/test/CIR/CodeGen/goto.cpp
+++ b/clang/test/CIR/CodeGen/goto.cpp
@@ -91,22 +91,18 @@ void severalLabelsInARow(int a) {
   b = b + 2;
 }
 // CIR:  cir.func {{.*}} @_Z19severalLabelsInARowi
-// CIR:    cir.goto "end1"
-// CIR:  ^bb[[#BLK1:]]
-// CIR:    cir.goto "end2"
-// CIR:  ^bb[[#BLK2:]]:
-// CIR:    cir.label "end1"
-// CIR:    cir.br ^bb[[#BLK3:]]
-// CIR:  ^bb[[#BLK3]]:
-// CIR:    cir.label "end2"
+// CIR:    cir.br ^[[END:bb[0-9]+]]
+// CIR:  ^bb{{[0-9]+}}:  // no predecessors
+// CIR:    cir.br ^[[END]]
+// CIR:  ^[[END]]:
+// CIR-NOT:  cir.label
+// CIR:    cir.add nsw
 
 // LLVM: define dso_local void @_Z19severalLabelsInARowi
-// LLVM:   br label %[[END1:.*]]
+// LLVM:   br label %[[END:.*]]
 // LLVM: [[UNRE:.*]]:                                                ; No 
predecessors!
-// LLVM:   br label %[[END2:.*]]
-// LLVM: [[END1]]:
-// LLVM:   br label %[[END2]]
-// LLVM: [[END2]]:
+// LLVM:   br label %[[END]]
+// LLVM: [[END]]:
 // LLVM:   ret
 
 // OGCG: define dso_local void @_Z19severalLabelsInARowi
@@ -124,11 +120,11 @@ void severalGotosInARow(int a) {
   b = b + 2;
 }
 // CIR:  cir.func {{.*}} @_Z18severalGotosInARowi
-// CIR:    cir.goto "end"
-// CIR:  ^bb[[#BLK1:]]:
-// CIR:    cir.goto "end"
-// CIR:  ^bb[[#BLK2:]]:
-// CIR:    cir.label "end"
+// CIR:    cir.br ^[[END:bb[0-9]+]]
+// CIR:  ^bb{{[0-9]+}}:  // no predecessors
+// CIR-NEXT:    cir.br ^[[END]]
+// CIR:  ^[[END]]:
+// CIR-NEXT:    cir.load
 
 // LLVM: define dso_local void @_Z18severalGotosInARowi
 // LLVM:   br label %[[END:.*]]
@@ -158,19 +154,14 @@ extern "C" void multiple_non_case(int v) {
 // CIR: cir.switch
 // CIR: cir.case(default, []) {
 // CIR: cir.call @action1()
-// CIR: cir.br ^[[BB1:[a-zA-Z0-9]+]]
-// CIR: ^[[BB1]]:
-// CIR: cir.label
-// CIR: cir.call @action2()
-// CIR: cir.break
+// CIR-NEXT: cir.call @action2()
+// CIR-NEXT: cir.break
 
 // LLVM: define dso_local void @multiple_non_case
 // LLVM: [[SWDEFAULT:.*]]:
 // LLVM:   call void @action1()
-// LLVM:   br label %[[L2:.*]]
-// LLVM: [[L2]]:
-// LLVM:   call void @action2()
-// LLVM:   br label %[[BREAK:.*]]
+// LLVM-NEXT:   call void @action2()
+// LLVM-NEXT:   br label %[[BREAK:.*]]
 
 // OGCG: define dso_local void @multiple_non_case
 // OGCG: sw.default:
@@ -258,10 +249,12 @@ extern "C" void default_follow_label(int v) {
 // CIR: cir.case(equal, [#cir.int<2> : !s32i]) {
 // CIR:   cir.call @action1()
 // CIR:   cir.break
-// CIR:   cir.label "label"
+// CIR: ^[[LABEL:bb[0-9]+]]:
 // CIR: cir.case(default, []) {
 // CIR:   cir.call @action2()
-// CIR:   cir.goto "label"
+// CIR:   cir.yield
+// CIR: }
+// CIR: cir.br ^[[LABEL]]
 
 // LLVM: define dso_local void @default_follow_label
 // LLVM:  switch i32 {{.*}}, label %[[SWDEFAULT:.*]] [
@@ -299,10 +292,9 @@ void g3() {
 }
 
 // CIR:  cir.func {{.*}} @_Z2g3v
-// CIR:    cir.br ^bb1
-// CIR:  ^bb1:
-// CIR:    cir.label "label"
-// CIR:    cir.goto "label"
+// CIR:    cir.br ^[[LABEL:bb[0-9]+]]
+// CIR:  ^[[LABEL]]:
+// CIR-NEXT:    cir.br ^[[LABEL]]
 
 // LLVM: define dso_local void @_Z2g3v()
 // LLVM:   br label %1
diff --git a/clang/test/CIR/CodeGen/label.c b/clang/test/CIR/CodeGen/label.c
index b281697f77e0e0..ceef28e009aea2 100644
--- a/clang/test/CIR/CodeGen/label.c
+++ b/clang/test/CIR/CodeGen/label.c
@@ -11,15 +11,10 @@ void label() {
 }
 
 // CIR:  cir.func {{.*}} @label
-// CIR:     cir.br ^bb1
-// CIR:  ^bb1:
-// CIR:    cir.label "labelA"
-// CIR:    cir.return
+// CIR-NEXT:    cir.return
 
 // LLVM:define dso_local void @label
-// LLVM:   br label %1
-// LLVM: 1:
-// LLVM:  ret void
+// LLVM-NEXT:  ret void
 
 // OGCG: define dso_local void @label
 // OGCG:   br label %labelA
@@ -33,18 +28,10 @@ void multiple_labels() {
 }
 
 // CIR:  cir.func {{.*}} @multiple_labels
-// CIR:    cir.br ^bb1
-// CIR:  ^bb1:
-// CIR:    cir.label "labelB"
-// CIR:    cir.br ^bb2
-// CIR:  ^bb2:
-// CIR:    cir.label "labelC"
-// CIR:    cir.return
+// CIR-NEXT:    cir.return
 
 // LLVM: define dso_local void @multiple_labels(){{.*}}
-// LLVM:   br label %1
-// LLVM: 1:
-// LLVM:   ret void
+// LLVM-NEXT:   ret void
 
 // OGCG: define dso_local void @multiple_labels
 // OGCG:   br label %labelB
@@ -62,9 +49,7 @@ void label_in_if(int cond) {
 
 // CIR:  cir.func {{.*}} @label_in_if
 // CIR:      cir.if {{.*}} {
-// CIR:        cir.br ^bb1
-// CIR:      ^bb1:
-// CIR:        cir.label "labelD"
+// CIR-NOT:    cir.label
 // CIR:        [[LOAD:%.*]] = cir.load align(4) [[COND:%.*]] : 
!cir.ptr<!s32i>, !s32i
 // CIR:        [[INC:%.*]] = cir.inc nsw %3 : !s32i
 // CIR:        cir.store align(4) [[INC]], [[COND]] : !s32i, !cir.ptr<!s32i>
@@ -104,8 +89,7 @@ void after_return() {
 // CIR:  cir.func {{.*}} @after_return
 // CIR:    cir.return
 // CIR:  ^bb1:  // no predecessors
-// CIR:    cir.label "label"
-// CIR:    cir.return
+// CIR-NEXT:    cir.return
 
 // LLVM: define dso_local void @after_return{{.*}}
 // LLVM:   ret void
@@ -126,8 +110,7 @@ void after_unreachable() {
 // CIR:  cir.func {{.*}} @after_unreachable
 // CIR:    cir.unreachable
 // CIR:  ^bb1:
-// CIR:    cir.label "label"
-// CIR:    cir.return
+// CIR-NEXT:    cir.return
 
 // LLVM: define dso_local void @after_unreachable{{.*}}
 // LLVM:   unreachable
@@ -144,16 +127,11 @@ void labelWithoutMatch() {
   return;
 }
 // CIR:  cir.func {{.*}} @labelWithoutMatch
-// CIR:    cir.br ^bb1
-// CIR:  ^bb1:
-// CIR:    cir.label "end"
-// CIR:    cir.return
-// CIR:  }
+// CIR-NEXT:    cir.return
+// CIR-NEXT:  }
 
 // LLVM: define dso_local void @labelWithoutMatch
-// LLVM:   br label %1
-// LLVM: 1:
-// LLVM:   ret void
+// LLVM-NEXT:   ret void
 
 // OGCG: define dso_local void @labelWithoutMatch
 // OGCG:   br label %end
@@ -174,9 +152,8 @@ void foo() {
 // CIR: cir.func {{.*}} @foo
 // CIR:   cir.scope {
 // CIR:     %0 = cir.alloca "agg.tmp0" {{.*}} : !cir.ptr<!rec_S>
-// CIR:      cir.br ^bb1
-// CIR:    ^bb1:
-// CIR:     cir.label "label"
+// CIR-NOT:  cir.label
+// CIR:      cir.call @bar()
 
 // LLVM: define dso_local void @foo(){{.*}} {
 // LLVM:  %{{.*}} = alloca %struct.S, align 1
diff --git a/clang/test/CIR/CodeGen/switch-pre-case-stmts.cpp 
b/clang/test/CIR/CodeGen/switch-pre-case-stmts.cpp
index 20e61a50f77762..6f3d70376af6b9 100644
--- a/clang/test/CIR/CodeGen/switch-pre-case-stmts.cpp
+++ b/clang/test/CIR/CodeGen/switch-pre-case-stmts.cpp
@@ -14,11 +14,8 @@ void pre_case_label() {
 
 // CIR-LABEL: cir.func{{.*}} @_Z14pre_case_labelv
 // CIR: cir.switch({{.*}} : !s32i) {
-// CIR:    cir.br ^bb1
-// CIR:  ^bb1:
-// CIR:    cir.label "LABEL1"
-// CIR:    cir.case(equal, [#cir.int<1> : !s32i]) {
-// CIR:      cir.yield loc(#loc7)
+// CIR-NEXT:    cir.case(equal, [#cir.int<1> : !s32i]) {
+// CIR:      cir.yield loc(#loc{{[0-9]+}})
 // CIR:    }
 // CIR:    cir.yield
 // CIR:  }
@@ -56,13 +53,7 @@ void multiple_pre_case_labels() {
 
 // CIR-LABEL: cir.func{{.*}} @_Z24multiple_pre_case_labelsv
 // CIR:  cir.switch({{.*}} : !s32i) {
-// CIR:    cir.br ^bb1
-// CIR:  ^bb1:
-// CIR:    cir.label "LABEL1"
-// CIR:    cir.br ^bb2
-// CIR:  ^bb2:
-// CIR:    cir.label "LABEL2"
-// CIR:    cir.case(equal, [#cir.int<1> : !s32i]) {
+// CIR-NEXT:    cir.case(equal, [#cir.int<1> : !s32i]) {
 // CIR:      cir.yield
 // CIR:    }
 // CIR:    cir.yield
@@ -234,19 +225,11 @@ void label_only_switch() {
 }
 
 // CIR-LABEL: cir.func{{.*}} @_Z17label_only_switchv
-// CIR:  cir.switch({{.*}} : !s32i) {
-// CIR:    cir.br ^bb1
-// CIR:  ^bb1:
-// CIR:    cir.label "LABEL"
-// CIR:    cir.yield
-// CIR:  }
-// CIR:}
+// CIR-NEXT:    cir.return
+// CIR-NEXT:  }
 
 // LLVM-LABEL: define{{.*}} @_Z17label_only_switchv
-// LLVM:   switch i32 1, label %[[END:.*]] [
-// LLVM:   ]
-// LLVM: [[LABEL:.*]]:{{.*}}; No predecessors!
-// LLVM:   br label %[[END]]
+// LLVM-NEXT:   ret void
 
 // OGCG-LABEL: define{{.*}} @_Z17label_only_switchv
 // OGCG:   switch i32 1, label %[[END:.*]] [
diff --git a/clang/test/CIR/CodeGen/unreachable-cycle.c 
b/clang/test/CIR/CodeGen/unreachable-cycle.c
index 069780254dd284..ef75e2579260d9 100644
--- a/clang/test/CIR/CodeGen/unreachable-cycle.c
+++ b/clang/test/CIR/CodeGen/unreachable-cycle.c
@@ -21,9 +21,12 @@ end:;
 
 // CIR-DAG: cir.global "private" external{{.*}} @x
 // CIR:     cir.func{{.*}} @f
-// CIR:       cir.goto "end"
-// CIR:       cir.label "lab"
+// CIR:       cir.br ^[[END:bb[0-9]+]]
+// CIR:     ^bb{{[0-9]+}}:  // no predecessors
 // CIR:       cir.get_global @x
+// CIR:       cir.br ^[[END]]
+// CIR:     ^[[END]]:
+// CIR-NEXT:  cir.return
 
 // LLVM:     @x = external {{(dso_local )?}}global i32
 // LLVM:     define dso_local void @f
diff --git a/clang/test/CIR/CodeGenCoroutines/coro-fallthrough.cpp 
b/clang/test/CIR/CodeGenCoroutines/coro-fallthrough.cpp
index 63dea681114549..b9bfcdf88286ef 100644
--- a/clang/test/CIR/CodeGenCoroutines/coro-fallthrough.cpp
+++ b/clang/test/CIR/CodeGenCoroutines/coro-fallthrough.cpp
@@ -682,15 +682,20 @@ IntTask goto_at_end() {
 
 // CIR-LABEL: cir.func coroutine {{.*}} @_Z11goto_at_endv(
 // CIR:         }, body : {
-// CIR:             cir.label "l"
-// CIR:             cir.goto "l"
+// CIR:             cir.br ^[[L:bb[0-9]+]]
+// CIR-NEXT:      ^[[L]]:
+// CIR:             cir.br ^[[L]]
 // CIR-NEXT:      ^bb{{[0-9]+}}:  // no predecessors
 // CIR-NEXT:        cir.yield
 // CIR-NOEH-NEXT: }, finalSuspend : {
 // CIR-EH-NEXT:   } catch all
 
 // CIR-FLAT-LABEL: cir.func {{.*}} @_Z11goto_at_endv(
-// CIR-FLAT:         cir.goto "l"
+// CIR-FLAT:         cir.switch.flat
+// CIR-FLAT:       ^bb{{[0-9]+}}:  // 2 preds
+// CIR-FLAT:       ^[[L:bb[0-9]+]]:  // 2 preds: ^bb{{[0-9]+}}, 
^[[BACK:bb[0-9]+]]
+// CIR-FLAT:       ^[[BACK]]:
+// CIR-FLAT-NEXT:    cir.br ^[[L]]
 // CIR-FLAT-NEXT:  ^bb{{[0-9]+}}:  // no predecessors
 // CIR-FLAT-NEXT:    cir.br ^[[FALLTHROUGH:bb[0-9]+]]
 // CIR-FLAT-NEXT:  ^[[FALLTHROUGH]]:
@@ -714,20 +719,25 @@ Task goto_after_co_return() {
 
 // CIR-LABEL: cir.func coroutine {{.*}} @_Z20goto_after_co_returnv(
 // CIR:         }, body : {
+// CIR:             cir.br ^[[L:bb[0-9]+]]
+// CIR-NEXT:      ^[[L]]:
 // CIR:             cir.call @_ZN4Task12promise_type11return_voidEv(
 // CIR-NEXT:        cir.co_return
 // CIR-NEXT:      ^bb{{[0-9]+}}:  // no predecessors
-// CIR-NEXT:        cir.goto "l"
+// CIR-NEXT:        cir.br ^[[L]]
 // CIR-NEXT:      ^bb{{[0-9]+}}:  // no predecessors
 // CIR-NEXT:        cir.yield
 // CIR-NOEH-NEXT: }, finalSuspend : {
 // CIR-EH-NEXT:   } catch all
 
 // CIR-FLAT-LABEL: cir.func {{.*}} @_Z20goto_after_co_returnv(
+// CIR-FLAT:         cir.switch.flat
+// CIR-FLAT:       ^bb{{[0-9]+}}:  // 2 preds
+// CIR-FLAT:       ^[[L:bb[0-9]+]]:  // 2 preds
 // CIR-FLAT:         cir.call @_ZN4Task12promise_type11return_voidEv(
 // CIR-FLAT-NEXT:    cir.br ^[[FINAL:bb[0-9]+]]
 // CIR-FLAT-NEXT:  ^bb{{[0-9]+}}:  // no predecessors
-// CIR-FLAT-NEXT:    cir.goto "l"
+// CIR-FLAT-NEXT:    cir.br ^[[L]]
 // CIR-FLAT-NEXT:  ^bb{{[0-9]+}}:  // no predecessors
 // CIR-FLAT-NEXT:    cir.br ^[[FINAL]]
 // CIR-FLAT-NEXT:  ^[[FINAL]]:
diff --git a/clang/test/CIR/Transforms/goto-elimination.cir 
b/clang/test/CIR/Transforms/goto-elimination.cir
new file mode 100644
index 00000000000000..4000c3c7ff725f
--- /dev/null
+++ b/clang/test/CIR/Transforms/goto-elimination.cir
@@ -0,0 +1,82 @@
+// RUN: cir-opt %s -cir-goto-elimination -cir-erase-unused-labels -o - \
+// RUN:   | FileCheck %s
+// RUN: cir-opt %s -cir-goto-elimination -cir-erase-unused-labels \
+// RUN:   -cir-goto-elimination -cir-erase-unused-labels -o - | FileCheck %s
+
+!s32i = !cir.int<s, 32>
+!void = !cir.void
+
+cir.func private @g()
+
+// A goto to a label in the same region becomes a branch, and the label goes.
+// CHECK-LABEL: cir.func @same_region(
+// CHECK:         cir.br ^[[L:bb[0-9]+]]
+// CHECK:       ^[[L]]:
+// CHECK-NOT:     cir.label
+// CHECK:         cir.return
+cir.func @same_region() {
+  cir.goto "out"
+^bb1:
+  cir.call @g() : () -> ()
+  cir.br ^bb2
+^bb2:
+  cir.label "out"
+  cir.return
+}
+
+// A backward goto in the same region becomes a back edge.
+// CHECK-LABEL: cir.func @backward(
+// CHECK:       ^[[LOOP:bb[0-9]+]]:
+// CHECK-NOT:     cir.label
+// CHECK:         cir.call @g()
+// CHECK-NEXT:    cir.br ^[[LOOP]]
+cir.func @backward() {
+  cir.br ^bb1
+^bb1:
+  cir.label "again"
+  cir.call @g() : () -> ()
+  cir.goto "again"
+}
+
+// A goto nested in a region keeps its label; the label's other same-region
+// goto still becomes a branch.
+// CHECK-LABEL: cir.func @cross_region(
+// CHECK:         cir.scope {
+// CHECK:           cir.goto "out"
+// CHECK:         cir.br ^[[L:bb[0-9]+]]
+// CHECK:       ^[[L]]:
+// CHECK-NEXT:    cir.label "out"
+cir.func @cross_region(%arg0: !cir.bool) {
+  cir.scope {
+    cir.if %arg0 {
+      cir.goto "out"
+    }
+    cir.yield
+  }
+  cir.goto "out"
+^bb1:
+  cir.label "out"
+  cir.return
+}
+
+// A label whose address is taken stays, even with no goto.
+// CHECK-LABEL: cir.func @address_taken(
+// CHECK:         cir.label "taken"
+cir.func @address_taken() -> !cir.ptr<!void> {
+  %0 = cir.block_address <@address_taken, "taken"> : !cir.ptr<!void>
+  cir.br ^bb1
+^bb1:
+  cir.label "taken"
+  cir.return %0 : !cir.ptr<!void>
+}
+
+// A label whose address is taken only in a global initializer stays.
+cir.global external @table = 
#cir.const_array<[#cir.block_addr_info<@from_global, "entry"> : 
!cir.ptr<!void>]> : !cir.array<!cir.ptr<!void> x 1>
+// CHECK-LABEL: cir.func @from_global(
+// CHECK:         cir.label "entry"
+cir.func @from_global() {
+  cir.br ^bb1
+^bb1:
+  cir.label "entry"
+  cir.return
+}
diff --git a/clang/tools/cir-opt/cir-opt.cpp b/clang/tools/cir-opt/cir-opt.cpp
index 79ade03564968a..e9b09ce3a3b005 100644
--- a/clang/tools/cir-opt/cir-opt.cpp
+++ b/clang/tools/cir-opt/cir-opt.cpp
@@ -82,6 +82,12 @@ int main(int argc, char **argv) {
   ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> {
     return mlir::createGotoSolverPass();
   });
+  ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> {
+    return mlir::createGotoEliminationPass();
+  });
+  ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> {
+    return mlir::createEraseUnusedLabelsPass();
+  });
 
   ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> {
     return mlir::createCXXABILoweringPass();

_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to