[clang] [CIR] Keep CIR global types visible across lowering replacements (PR #238698)

Henrich Lauko via cfe-commits cfe-commits at lists.llvm.org
Wed Nov 4 01:07:22 PST 2026


================
@@ -3420,18 +3437,38 @@ CIRToLLVMGlobalOpLowering::matchAndRewriteRegionInitializedGlobal(
   // to the appropriate value.
   const mlir::Location loc = op.getLoc();
   mlir::ModuleOp moduleOp = op->getParentOfType<mlir::ModuleOp>();
-  if (failed(setupRegionInitializedLLVMGlobalOp(op, rewriter)))
+  // Build the cached table before the replacement exists, so the swap below
+  // drops a real entry instead of depending on duplicate tolerance.
+  auto &symbolTable = symbolTables.getSymbolTable(moduleOp);
+  // Create the replacement beside the root op, not via replaceOp: the table
+  // swap below and the visit both need the old op alive.
+  rewriter.setInsertionPoint(op);
+  mlir::LLVM::GlobalOp newGlobalOp =
+      setupRegionInitializedLLVMGlobalOp(op, rewriter);
+  if (!newGlobalOp)
     return mlir::failure();
-
+  // Keep the old op in the table during the visit so self-references
+  // resolve to the CIR type, not the possibly adjusted LLVM type.
   // Pass blockInfoAddr so that block address initializers (either as the whole
   // initializer or nested inside an aggregate) can be resolved by the
   // BlockAddrInfoAttr visitor.
   CIRAttrToValue valueConverter(loc, moduleOp, rewriter, symbolTables,
                                 typeConverter, &blockInfoAddr);
   mlir::Value value = valueConverter.visit(init);
-  if (!value)
+  if (!value) {
+    // Drop the speculative replacement; the table still holds the live
+    // root op for the driver to report on.
+    rewriter.eraseOp(newGlobalOp);
----------------
xlauko wrote:

Without rollback, a pattern shouldn't fail after changing the IR. Erasing `newGlobalOp` still leaves any declarations the visitor created, so the comdat comment below overstates what moving it buys. Can the parts that can fail run before the new global is created?

https://github.com/llvm/llvm-project/pull/238698


More information about the cfe-commits mailing list