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

Bruno Cardoso Lopes via cfe-commits cfe-commits at lists.llvm.org
Wed Nov 4 11:50:28 PST 2026


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

>From 43515a3aba3efb7b84ddb74bb40d358e9986145b Mon Sep 17 00:00:00 2001
From: Bruno Cardoso Lopes <bruno.cardoso at gmail.com>
Date: Tue, 3 Nov 2026 12:08:10 -0800
Subject: [PATCH 1/7] [CIR] Keep CIR global types visible across lowering
 replacements

A lookup after a global is lowered finds the LLVM global, whose type
may have been adjusted during lowering. Stash the CIR type in a
transient cir.preconversion_sym_type attribute on every global
replacement and prefer it in readers; strip it on exit. Build
region-initialized globals beside the root op, swap them in after the
initializer visit, and maintain the cached symbol table explicitly at
every replacement. Read call musttail/inline attributes before the
replace erases the root op.

Fixes order-dependent GEP rejections for self-referential globals and
later globals referencing adjusted globals. No other test changes.
Func/alias upkeep and readers ride with the one-shot flip itself.

Assisted-by: Muse Code (Muse)
---
 clang/include/clang/CIR/Dialect/IR/CIROps.td  |   2 +-
 clang/include/clang/CIR/LoweringHelpers.h     |  14 +++
 .../CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp | 104 ++++++++++++++----
 clang/lib/CIR/Lowering/LoweringHelpers.cpp    |   8 +-
 .../test/CIR/CodeGen/global-self-reference.c  |  36 ++++++
 .../global-view-bulk-after-adjusted.cir       |  26 +++++
 6 files changed, 169 insertions(+), 21 deletions(-)
 create mode 100644 clang/test/CIR/CodeGen/global-self-reference.c
 create mode 100644 clang/test/CIR/Lowering/global-view-bulk-after-adjusted.cir

diff --git a/clang/include/clang/CIR/Dialect/IR/CIROps.td b/clang/include/clang/CIR/Dialect/IR/CIROps.td
index bd762aae3e1d7e..439b2308f538a1 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIROps.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIROps.td
@@ -3599,7 +3599,7 @@ def CIR_GlobalOp : CIR_RegionBranchOpBase<"global", [
       cir::GlobalOp op, mlir::Attribute init,
       mlir::ConversionPatternRewriter &rewriter) const;
 
-    mlir::LogicalResult setupRegionInitializedLLVMGlobalOp(
+    mlir::LLVM::GlobalOp setupRegionInitializedLLVMGlobalOp(
         cir::GlobalOp op, mlir::ConversionPatternRewriter &rewriter) const;
 
     llvm::SmallVector<mlir::NamedAttribute> lowerGlobalAttributes(
diff --git a/clang/include/clang/CIR/LoweringHelpers.h b/clang/include/clang/CIR/LoweringHelpers.h
index 18e4c5cd31a62e..1090318e1906bd 100644
--- a/clang/include/clang/CIR/LoweringHelpers.h
+++ b/clang/include/clang/CIR/LoweringHelpers.h
@@ -100,4 +100,18 @@ mlir::Type convertTypeForLoadStore(const mlir::TypeConverter &converter,
 mlir::Attribute getBitIntStorageAttr(mlir::ConversionPatternRewriter &rewriter,
                                      cir::IntAttr attr,
                                      const mlir::DataLayout &dataLayout);
+
+// Transient attribute holding a symbol's CIR type before lowering. Lookups
+// mid-conversion can find the already-lowered LLVM symbol instead of the
+// CIR op. Its type may have been adjusted during lowering (split rows,
+// flexible array), so readers that need the unadjusted CIR view use this
+// stash. The pass strips it at the end, so it never reaches the output.
+inline constexpr const char *kPreConversionSymType =
+    "cir.preconversion_sym_type";
+
+inline mlir::Type getPreConversionSymType(mlir::Operation *op) {
+  if (auto typeAttr = op->getAttrOfType<mlir::TypeAttr>(kPreConversionSymType))
+    return typeAttr.getValue();
+  return {};
+}
 #endif
diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
index a48dbd04de84ac..61eb83180e7db8 100644
--- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
+++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
@@ -51,6 +51,7 @@
 #include "clang/CIR/MissingFeatures.h"
 #include "clang/CIR/Passes.h"
 #include "llvm/ADT/MapVector.h"
+#include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/TypeSwitch.h"
 #include "llvm/IR/Module.h"
@@ -1079,7 +1080,14 @@ CIRAttrToValue::getAddressOfSymbol(mlir::FlatSymbolRefAttr symbol) {
   mlir::Operation *sourceSymbol =
       symbolTables.lookupSymbolIn(parentModule, symbol);
   if (auto llvmSymbol = dyn_cast<mlir::LLVM::GlobalOp>(sourceSymbol)) {
-    sourceType = llvmSymbol.getType();
+    // Prefer the stashed pre-conversion type: the LLVM global's type may
+    // have been adjusted (split rows, flexible array).
+    if (mlir::Type preType = getPreConversionSymType(llvmSymbol)) {
+      originalType = preType;
+      sourceType = convertTypeForMemory(*converter, dataLayout, originalType);
+    } else {
+      sourceType = llvmSymbol.getType();
+    }
     symName = llvmSymbol.getSymName();
     addrSpace = llvmSymbol.getAddrSpace();
   } else if (auto cirSymbol = dyn_cast<cir::GlobalOp>(sourceSymbol)) {
@@ -2623,6 +2631,10 @@ static mlir::LogicalResult rewriteCallOrInvoke(
 
   mlir::LLVM::CConv cconv = convertCallingConv(call.getCallingConv());
 
+  // The replace below erases the root op, so read what the CallOp branch
+  // needs first.
+  const bool mustTail = op->hasAttr(CIRDialect::getMustTailAttrName());
+  const std::optional<cir::InlineKind> inlineKind = call.getInlineKind();
   if (landingPadBlock) {
     assert(!cir::MissingFeatures::opCallInvokeAttrs());
     auto newOp = rewriter.replaceOpWithNewOp<mlir::LLVM::InvokeOp>(
@@ -2640,10 +2652,10 @@ static mlir::LogicalResult rewriteCallOrInvoke(
     newOp.setNoUnwind(noUnwind);
     newOp.setWillReturn(willReturn);
     newOp.setNoreturn(noReturn);
-    if (op->hasAttr(CIRDialect::getMustTailAttrName()))
+    if (mustTail)
       newOp.setTailCallKind(mlir::LLVM::TailCallKind::MustTail);
 
-    if (std::optional<cir::InlineKind> inlineKind = call.getInlineKind()) {
+    if (inlineKind) {
       newOp.setNoInline(*inlineKind == cir::InlineKind::NoInline);
       newOp.setInlineHint(*inlineKind == cir::InlineKind::InlineHint);
       newOp.setAlwaysInline(*inlineKind == cir::InlineKind::AlwaysInline);
@@ -3359,9 +3371,12 @@ convertTlsModelAttrToLLVM(TLSModelAttr attr) {
   return static_cast<mlir::LLVM::ThreadLocalMode>(attr.getValue());
 }
 
-/// Replace CIR global with a region initialized LLVM global and update
-/// insertion point to the end of the initializer block.
-mlir::LogicalResult
+/// Create the region-initialized LLVM global beside the CIR op and update
+/// insertion point to the end of the initializer block. Returns the new op,
+/// or null on failure. The caller owns the replacement: it runs the
+/// initializer visit with the old op still in the table, then swaps the
+/// table and erases the old op on success.
+mlir::LLVM::GlobalOp
 CIRToLLVMGlobalOpLowering::setupRegionInitializedLLVMGlobalOp(
     cir::GlobalOp op, mlir::ConversionPatternRewriter &rewriter) const {
   mlir::Type llvmType =
@@ -3373,7 +3388,7 @@ CIRToLLVMGlobalOpLowering::setupRegionInitializedLLVMGlobalOp(
     llvmType = adjustGlobalTypeForInit(llvmType, *init, *getTypeConverter(),
                                        dataLayout);
   if (!llvmType)
-    return mlir::failure();
+    return {};
 
   // FIXME: These default values are placeholders until the the equivalent
   //        attributes are available on cir.global ops. This duplicates code
@@ -3390,18 +3405,20 @@ CIRToLLVMGlobalOpLowering::setupRegionInitializedLLVMGlobalOp(
   const uint64_t alignment = op.getAlignment().value_or(0);
   const mlir::LLVM::Linkage linkage = convertLinkage(op.getLinkage());
   const StringRef symbol = op.getSymName();
-  mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter);
 
   SmallVector<mlir::NamedAttribute> attributes =
       lowerGlobalAttributes(op, rewriter);
 
-  mlir::LLVM::GlobalOp newGlobalOp =
-      rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
-          op, llvmType, isConst, linkage, symbol, nullptr, alignment, addrSpace,
-          isDsoLocal, threadLocalMode, comdatAttr, attributes);
+  mlir::Type preConversionType = op.getSymType();
+  mlir::LLVM::GlobalOp newGlobalOp = mlir::LLVM::GlobalOp::create(
+      rewriter, op.getLoc(), llvmType, isConst, linkage, symbol, nullptr,
+      alignment, addrSpace, isDsoLocal, threadLocalMode, mlir::SymbolRefAttr{},
+      attributes);
+  newGlobalOp->setAttr(kPreConversionSymType,
+                       mlir::TypeAttr::get(preConversionType));
   rewriter.createBlock(&newGlobalOp.getRegion());
   rewriter.setInsertionPointToEnd(newGlobalOp.getInitializerBlock());
-  return mlir::success();
+  return newGlobalOp;
 }
 
 mlir::LogicalResult
@@ -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);
     return mlir::failure();
+  }
   mlir::LLVM::ReturnOp::create(rewriter, loc, value);
+  // Attach comdat only after the visit succeeds: creating it earlier would
+  // leave module-level ops behind on a failing compile.
+  if (mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter))
+    newGlobalOp.setComdatAttr(comdatAttr);
+  symbolTable.remove(op);
+  symbolTable.insert(newGlobalOp);
+  rewriter.eraseOp(op);
   return mlir::success();
 }
 
@@ -3531,10 +3568,17 @@ mlir::LogicalResult CIRToLLVMGlobalOpLowering::matchAndRewrite(
         if (std::optional<mlir::Attribute> bulkInit = lowerConstArrayAttr(
                 constArr, symbolTables, typeConverter, modOp)) {
           mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter);
-          rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
+          // The driver does not invalidate the cached symbol table, so
+          // maintain it explicitly: drop the old entry before replacement
+          // and register the new op after.
+          symbolTables.getSymbolTable(modOp).remove(op);
+          auto newGlobalOp = rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
               op, llvmType, isConst, linkage, symbol, bulkInit.value(),
               alignment, addrSpace, isDsoLocal, threadLocalMode, comdatAttr,
               attributes);
+          newGlobalOp->setAttr(kPreConversionSymType,
+                               mlir::TypeAttr::get(cirSymType));
+          symbolTables.getSymbolTable(modOp).insert(newGlobalOp);
           return mlir::success();
         }
       }
@@ -3550,9 +3594,16 @@ mlir::LogicalResult CIRToLLVMGlobalOpLowering::matchAndRewrite(
       if (std::optional<mlir::Attribute> bulkInit = lowerConstRecordAttr(
               constRecord, symbolTables, typeConverter, modOp)) {
         mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter);
-        rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
+        // The driver does not invalidate the cached symbol table, so
+        // maintain it explicitly: drop the old entry before replacement
+        // and register the new op after.
+        symbolTables.getSymbolTable(modOp).remove(op);
+        auto newGlobalOp = rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
             op, llvmType, isConst, linkage, symbol, bulkInit.value(), alignment,
             addrSpace, isDsoLocal, threadLocalMode, comdatAttr, attributes);
+        newGlobalOp->setAttr(kPreConversionSymType,
+                             mlir::TypeAttr::get(cirSymType));
+        symbolTables.getSymbolTable(modOp).insert(newGlobalOp);
         return mlir::success();
       }
       return matchAndRewriteRegionInitializedGlobal(op, init.value(), rewriter);
@@ -3575,10 +3626,17 @@ mlir::LogicalResult CIRToLLVMGlobalOpLowering::matchAndRewrite(
   }
 
   mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter);
-  rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
+  // The driver does not invalidate the cached symbol table, so
+  // maintain it explicitly: drop the old entry before replacement
+  // and register the new op after.
+  mlir::ModuleOp modOp = op->getParentOfType<mlir::ModuleOp>();
+  symbolTables.getSymbolTable(modOp).remove(op);
+  auto newGlobalOp = rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
       op, llvmType, isConst, linkage, symbol, init.value_or(mlir::Attribute()),
       alignment, addrSpace, isDsoLocal, threadLocalMode, comdatAttr,
       attributes);
+  newGlobalOp->setAttr(kPreConversionSymType, mlir::TypeAttr::get(cirSymType));
+  symbolTables.getSymbolTable(modOp).insert(newGlobalOp);
 
   return mlir::success();
 }
@@ -4879,6 +4937,14 @@ void ConvertCIRToLLVMPass::runOnOperation() {
   llvm::TimeTraceScope scope("Convert CIR to LLVM Pass");
 
   mlir::ModuleOp module = getOperation();
+  // The pre-conversion type snapshots never reach the output, however the
+  // pass exits. Snapshots only ever sit on module-level symbols.
+  mlir::StringAttr stashName =
+      mlir::StringAttr::get(&getContext(), kPreConversionSymType);
+  llvm::scope_exit stripPreConversionTypes([&] {
+    for (mlir::Operation &op : module.getBody()->getOperations())
+      op.removeAttr(stashName);
+  });
   mlir::DataLayout dl(module);
   mlir::LLVMTypeConverter converter(&getContext());
   prepareTypeConverter(converter, dl);
diff --git a/clang/lib/CIR/Lowering/LoweringHelpers.cpp b/clang/lib/CIR/Lowering/LoweringHelpers.cpp
index 1ab147c0f96396..693e73a70ec537 100644
--- a/clang/lib/CIR/Lowering/LoweringHelpers.cpp
+++ b/clang/lib/CIR/Lowering/LoweringHelpers.cpp
@@ -290,7 +290,13 @@ globalViewMatchesPointerLeaf(cir::GlobalViewAttr gv, mlir::ModuleOp moduleOp,
   mlir::Type sourceType;
   auto sourceSymbol = symbolTables.lookupSymbolIn(moduleOp, gv.getSymbol());
   if (auto llvmSymbol = mlir::dyn_cast<mlir::LLVM::GlobalOp>(sourceSymbol)) {
-    sourceType = llvmSymbol.getType();
+    // Prefer the stashed pre-conversion type: the lowered type may have been
+    // adjusted, which would answer differently depending on lowering order.
+    // Globals that were never CIR (no stash) keep the converted-type view.
+    if (mlir::Type preType = getPreConversionSymType(llvmSymbol))
+      sourceType = converter->convertType(preType);
+    else
+      sourceType = llvmSymbol.getType();
     sourceAddrSpace = llvmSymbol.getAddrSpace();
   } else if (auto cirSymbol = mlir::dyn_cast<cir::GlobalOp>(sourceSymbol)) {
     sourceType = converter->convertType(cirSymbol.getSymType());
diff --git a/clang/test/CIR/CodeGen/global-self-reference.c b/clang/test/CIR/CodeGen/global-self-reference.c
new file mode 100644
index 00000000000000..1848f3c50b950a
--- /dev/null
+++ b/clang/test/CIR/CodeGen/global-self-reference.c
@@ -0,0 +1,36 @@
+// RUN: split-file %s %t
+
+// A global whose initializer refers to itself must resolve the
+// self-reference to the CIR type. Warm and cold table cases are
+// separate TUs below, with different symbol names.
+
+//--- warm.c
+
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fclangir -emit-llvm %t/warm.c -o %t/warm-cir.ll
+// RUN: FileCheck --input-file=%t/warm-cir.ll %t/warm.c -check-prefix=LLVM
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm %t/warm.c -o %t/warm.ll
+// RUN: FileCheck --input-file=%t/warm.ll %t/warm.c -check-prefix=LLVM
+
+// LLVM: @arr = {{.*}}global <{ ptr, ptr, [98 x ptr] }> <{ ptr getelementptr {{.*}} i64 40), ptr getelementptr {{.*}} i64 56),
+// LLVM: @later = {{.*}}global ptr getelementptr {{.*}} @arr, i64 56)
+
+// Preceding globals so the module symbol table is cached.
+int x;
+int *px = &x;
+void *arr[100] = {&arr[5], &arr[7], 0};
+void **later = &arr[7];
+
+//--- cold.c
+
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fclangir -emit-llvm %t/cold.c -o %t/cold-cir.ll
+// RUN: FileCheck --input-file=%t/cold-cir.ll %t/cold.c -check-prefix=LLVM
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm %t/cold.c -o %t/cold.ll
+// RUN: FileCheck --input-file=%t/cold.ll %t/cold.c -check-prefix=LLVM
+
+// LLVM: @solo = {{.*}}global <{ ptr, ptr, [98 x ptr] }> <{ ptr getelementptr {{.*}} i64 40), ptr getelementptr {{.*}} i64 56),
+// LLVM: @follower = {{.*}}global ptr getelementptr {{.*}} @solo, i64 56)
+
+// The self-referential global is the first symbol: in the old code the
+// table was still cold here and the lowering failed.
+void *solo[100] = {&solo[5], &solo[7], 0};
+void **follower = &solo[7];
diff --git a/clang/test/CIR/Lowering/global-view-bulk-after-adjusted.cir b/clang/test/CIR/Lowering/global-view-bulk-after-adjusted.cir
new file mode 100644
index 00000000000000..4a64a3d1cfb798
--- /dev/null
+++ b/clang/test/CIR/Lowering/global-view-bulk-after-adjusted.cir
@@ -0,0 +1,26 @@
+// RUN: cir-opt %s --cir-to-llvm -o - | FileCheck %s
+
+!void = !cir.void
+!arr_ty = !cir.array<!cir.ptr<!void> x 100>
+!bulk_ty = !cir.array<!cir.ptr<!cir.array<!cir.ptr<!void> x 100>> x 2>
+
+module attributes {cir.triple = "x86_64-unknown-linux-gnu"} {
+  // Region-initialized, so its LLVM type is adjusted (grouped struct).
+  cir.global external dso_local @arr = #cir.const_array<[
+      #cir.global_view<@arr, [5 : i32]> : !cir.ptr<!void>,
+      #cir.global_view<@arr, [7 : i32]> : !cir.ptr<!void>
+  ], trailing_zeros> : !arr_ty
+
+  // Unindexed views of @arr: bulk lowering must see the CIR array type
+  // via the stash, not the adjusted LLVM struct type.
+  cir.global external dso_local @bulk = #cir.const_array<[
+      #cir.global_view<@arr> : !cir.ptr<!cir.array<!cir.ptr<!void> x 100>>,
+      #cir.global_view<@arr> : !cir.ptr<!cir.array<!cir.ptr<!void> x 100>>
+  ]> : !bulk_ty
+}
+
+// CHECK: llvm.mlir.global external @arr
+// CHECK: llvm.insertvalue
+// CHECK: llvm.mlir.global external @bulk([@arr, @arr])
+// CHECK-NOT: llvm.insertvalue
+// CHECK-NOT: llvm.return

>From 5b428660eb63f8aa6c68846040b48ca80533df31 Mon Sep 17 00:00:00 2001
From: Bruno Cardoso Lopes <bruno.cardoso at gmail.com>
Date: Wed, 4 Nov 2026 10:49:22 -0800
Subject: [PATCH 2/7] Address review: stash and upkeep for aliases, vtable
 reader

Function and variable alias replacements now maintain the cached
symbol table and stash the pre-conversion type, like the global
replacements. getAddressOfSymbol reads the stash on alias lookups.
getValueForVTableSymbol prefers the stashed type over the possibly
adjusted LLVM global type.
---
 .../CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp | 44 +++++++++++++++++--
 1 file changed, 40 insertions(+), 4 deletions(-)

diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
index 61eb83180e7db8..285640c77429b3 100644
--- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
+++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
@@ -1107,8 +1107,17 @@ CIRAttrToValue::getAddressOfSymbol(mlir::FlatSymbolRefAttr symbol) {
     symName = fun.getSymName();
     addrSpace = cirDataLayout.getProgramAddressSpace();
   } else if (auto alias = dyn_cast<mlir::LLVM::AliasOp>(sourceSymbol)) {
-    sourceType = alias.getType();
+    if (mlir::Type preType = getPreConversionSymType(alias)) {
+      originalType = preType;
+      if (mlir::isa<cir::FuncType>(preType))
+        sourceType = converter->convertType(originalType);
+      else
+        sourceType = convertTypeForMemory(*converter, dataLayout, originalType);
+    } else {
+      sourceType = alias.getType();
+    }
     symName = alias.getSymName();
+    addrSpace = alias.getAddrSpace();
   } else {
     llvm_unreachable("Unexpected GlobalOp type");
   }
@@ -3149,11 +3158,18 @@ mlir::LogicalResult CIRToLLVMFuncOpLowering::matchAndRewriteAlias(
 
   mlir::Location loc = op.getLoc();
   // Create the alias before replacing: without pattern rollback the
-  // replace erases the root op immediately.
+  // replace erases the root op immediately. The driver does not
+  // invalidate the cached symbol table either, so build it before the
+  // replacement exists and maintain it explicitly below.
+  mlir::ModuleOp modOp = op->getParentOfType<mlir::ModuleOp>();
+  mlir::Type preConversionType = op.getFunctionType();
+  symbolTables.getSymbolTable(modOp);
   auto aliasOp = mlir::LLVM::AliasOp::create(
       rewriter, loc, ty, convertLinkage(op.getLinkage()), op.getName(),
       op.getDsoLocal(), mlir::LLVM::ThreadLocalMode::NotThreadLocal,
       attributes);
+  aliasOp->setAttr(kPreConversionSymType,
+                   mlir::TypeAttr::get(preConversionType));
   aliasOp.setVisibility_(
       lowerCIRVisibilityToLLVMVisibility(op.getGlobalVisibility()));
   {
@@ -3167,7 +3183,9 @@ mlir::LogicalResult CIRToLLVMFuncOpLowering::matchAndRewriteAlias(
         mlir::LLVM::AddressOfOp::create(rewriter, loc, ptrTy, aliasee);
     mlir::LLVM::ReturnOp::create(rewriter, loc, addrOp);
   }
+  symbolTables.getSymbolTable(modOp).remove(op);
   rewriter.replaceOp(op, aliasOp);
+  symbolTables.getSymbolTable(modOp).insert(aliasOp);
 
   return mlir::success();
 }
@@ -3526,10 +3544,15 @@ mlir::LogicalResult CIRToLLVMGlobalOpLowering::matchAndRewrite(
   if (std::optional<llvm::StringRef> aliasee = op.getAliasee()) {
     mlir::Location loc = op.getLoc();
     // Create the alias before replacing: without pattern rollback the
-    // replace erases the root op immediately.
+    // replace erases the root op immediately. The driver does not
+    // invalidate the cached symbol table either, so build it before the
+    // replacement exists and maintain it explicitly below.
+    mlir::ModuleOp modOp = op->getParentOfType<mlir::ModuleOp>();
+    symbolTables.getSymbolTable(modOp);
     auto aliasOp =
         mlir::LLVM::AliasOp::create(rewriter, loc, llvmType, linkage, symbol,
                                     isDsoLocal, threadLocalMode, attributes);
+    aliasOp->setAttr(kPreConversionSymType, mlir::TypeAttr::get(cirSymType));
     {
       mlir::OpBuilder::InsertionGuard guard(rewriter);
       rewriter.createBlock(&aliasOp.getInitializerRegion());
@@ -3539,7 +3562,9 @@ mlir::LogicalResult CIRToLLVMGlobalOpLowering::matchAndRewrite(
           mlir::LLVM::AddressOfOp::create(rewriter, loc, ptrTy, *aliasee);
       mlir::LLVM::ReturnOp::create(rewriter, loc, addrOp);
     }
+    symbolTables.getSymbolTable(modOp).remove(op);
     rewriter.replaceOp(op, aliasOp);
+    symbolTables.getSymbolTable(modOp).insert(aliasOp);
     return mlir::success();
   }
 
@@ -5386,7 +5411,18 @@ getValueForVTableSymbol(mlir::Operation *op,
   auto module = op->getParentOfType<mlir::ModuleOp>();
   mlir::Operation *symbol = symbolTables.lookupSymbolIn(module, nameAttr);
   if (auto llvmSymbol = mlir::dyn_cast<mlir::LLVM::GlobalOp>(symbol)) {
-    eltType = llvmSymbol.getType();
+    // Prefer the stashed pre-conversion type: the LLVM global's type may
+    // have been adjusted (split rows, flexible array).
+    if (mlir::Type preType = getPreConversionSymType(llvmSymbol)) {
+      eltType = converter->convertType(preType);
+      if (!eltType) {
+        emitTypeConversionError(op, preType)
+            << " for vtable symbol " << nameAttr;
+        return {};
+      }
+    } else {
+      eltType = llvmSymbol.getType();
+    }
   } else if (auto cirSymbol = mlir::dyn_cast<cir::GlobalOp>(symbol)) {
     eltType = converter->convertType(cirSymbol.getSymType());
     if (!eltType) {

>From a6f12aa1c4df1bec4e375553b6c9205790316805 Mon Sep 17 00:00:00 2001
From: Bruno Cardoso Lopes <bruno.cardoso at gmail.com>
Date: Wed, 4 Nov 2026 10:52:27 -0800
Subject: [PATCH 3/7] Address review: replaceCirGlobal helper for global
 replacements

The remove/replace/stash/insert sequence was repeated at three sites.
One helper enforces the ordering (table entry dropped before creation
so the replacement reuses the name). No behavior change.
---
 .../CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp | 65 ++++++++++---------
 1 file changed, 33 insertions(+), 32 deletions(-)

diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
index 285640c77429b3..5c6a4225e6f917 100644
--- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
+++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
@@ -3490,6 +3490,29 @@ CIRToLLVMGlobalOpLowering::matchAndRewriteRegionInitializedGlobal(
   return mlir::success();
 }
 
+// Replace a CIR global with an LLVM global, maintaining the cached symbol
+// table and stashing the CIR type for later lookups. The table entry is
+// dropped before creation so the replacement reuses the name.
+static mlir::LLVM::GlobalOp
+replaceCirGlobal(mlir::SymbolTableCollection &symbolTables, cir::GlobalOp op,
+                 mlir::Type llvmType, bool isConst, mlir::LLVM::Linkage linkage,
+                 llvm::StringRef symbol, mlir::Attribute init,
+                 uint64_t alignment, unsigned addrSpace, bool isDsoLocal,
+                 mlir::LLVM::ThreadLocalMode threadLocalMode,
+                 mlir::SymbolRefAttr comdatAttr,
+                 llvm::ArrayRef<mlir::NamedAttribute> attributes,
+                 mlir::ConversionPatternRewriter &rewriter) {
+  mlir::ModuleOp modOp = op->getParentOfType<mlir::ModuleOp>();
+  symbolTables.getSymbolTable(modOp).remove(op);
+  auto newGlobalOp = rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
+      op, llvmType, isConst, linkage, symbol, init, alignment, addrSpace,
+      isDsoLocal, threadLocalMode, comdatAttr, attributes);
+  newGlobalOp->setAttr(kPreConversionSymType,
+                       mlir::TypeAttr::get(op.getSymType()));
+  symbolTables.getSymbolTable(modOp).insert(newGlobalOp);
+  return newGlobalOp;
+}
+
 mlir::LogicalResult CIRToLLVMGlobalOpLowering::matchAndRewrite(
     cir::GlobalOp op, OpAdaptor adaptor,
     mlir::ConversionPatternRewriter &rewriter) const {
@@ -3593,17 +3616,9 @@ mlir::LogicalResult CIRToLLVMGlobalOpLowering::matchAndRewrite(
         if (std::optional<mlir::Attribute> bulkInit = lowerConstArrayAttr(
                 constArr, symbolTables, typeConverter, modOp)) {
           mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter);
-          // The driver does not invalidate the cached symbol table, so
-          // maintain it explicitly: drop the old entry before replacement
-          // and register the new op after.
-          symbolTables.getSymbolTable(modOp).remove(op);
-          auto newGlobalOp = rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
-              op, llvmType, isConst, linkage, symbol, bulkInit.value(),
-              alignment, addrSpace, isDsoLocal, threadLocalMode, comdatAttr,
-              attributes);
-          newGlobalOp->setAttr(kPreConversionSymType,
-                               mlir::TypeAttr::get(cirSymType));
-          symbolTables.getSymbolTable(modOp).insert(newGlobalOp);
+          replaceCirGlobal(symbolTables, op, llvmType, isConst, linkage, symbol,
+                           bulkInit.value(), alignment, addrSpace, isDsoLocal,
+                           threadLocalMode, comdatAttr, attributes, rewriter);
           return mlir::success();
         }
       }
@@ -3619,16 +3634,9 @@ mlir::LogicalResult CIRToLLVMGlobalOpLowering::matchAndRewrite(
       if (std::optional<mlir::Attribute> bulkInit = lowerConstRecordAttr(
               constRecord, symbolTables, typeConverter, modOp)) {
         mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter);
-        // The driver does not invalidate the cached symbol table, so
-        // maintain it explicitly: drop the old entry before replacement
-        // and register the new op after.
-        symbolTables.getSymbolTable(modOp).remove(op);
-        auto newGlobalOp = rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
-            op, llvmType, isConst, linkage, symbol, bulkInit.value(), alignment,
-            addrSpace, isDsoLocal, threadLocalMode, comdatAttr, attributes);
-        newGlobalOp->setAttr(kPreConversionSymType,
-                             mlir::TypeAttr::get(cirSymType));
-        symbolTables.getSymbolTable(modOp).insert(newGlobalOp);
+        replaceCirGlobal(symbolTables, op, llvmType, isConst, linkage, symbol,
+                         bulkInit.value(), alignment, addrSpace, isDsoLocal,
+                         threadLocalMode, comdatAttr, attributes, rewriter);
         return mlir::success();
       }
       return matchAndRewriteRegionInitializedGlobal(op, init.value(), rewriter);
@@ -3651,17 +3659,10 @@ mlir::LogicalResult CIRToLLVMGlobalOpLowering::matchAndRewrite(
   }
 
   mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter);
-  // The driver does not invalidate the cached symbol table, so
-  // maintain it explicitly: drop the old entry before replacement
-  // and register the new op after.
-  mlir::ModuleOp modOp = op->getParentOfType<mlir::ModuleOp>();
-  symbolTables.getSymbolTable(modOp).remove(op);
-  auto newGlobalOp = rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
-      op, llvmType, isConst, linkage, symbol, init.value_or(mlir::Attribute()),
-      alignment, addrSpace, isDsoLocal, threadLocalMode, comdatAttr,
-      attributes);
-  newGlobalOp->setAttr(kPreConversionSymType, mlir::TypeAttr::get(cirSymType));
-  symbolTables.getSymbolTable(modOp).insert(newGlobalOp);
+  replaceCirGlobal(symbolTables, op, llvmType, isConst, linkage, symbol,
+                   init.value_or(mlir::Attribute()), alignment, addrSpace,
+                   isDsoLocal, threadLocalMode, comdatAttr, attributes,
+                   rewriter);
 
   return mlir::success();
 }

>From f0236f1a719410f43d982ea0afb7508602f4119b Mon Sep 17 00:00:00 2001
From: Bruno Cardoso Lopes <bruno.cardoso at gmail.com>
Date: Wed, 4 Nov 2026 10:53:43 -0800
Subject: [PATCH 4/7] Address review: test nits and comdat comment

Describe the cold-table case directly instead of via old-code
behavior, drop the redundant CHECK-NOT, and scope the comdat comment
to what deferring it delivers.
---
 clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp         | 4 ++--
 clang/test/CIR/CodeGen/global-self-reference.c              | 3 +--
 clang/test/CIR/Lowering/global-view-bulk-after-adjusted.cir | 1 -
 3 files changed, 3 insertions(+), 5 deletions(-)

diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
index 5c6a4225e6f917..b2dc3c313c99a2 100644
--- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
+++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
@@ -3480,8 +3480,8 @@ CIRToLLVMGlobalOpLowering::matchAndRewriteRegionInitializedGlobal(
     return mlir::failure();
   }
   mlir::LLVM::ReturnOp::create(rewriter, loc, value);
-  // Attach comdat only after the visit succeeds: creating it earlier would
-  // leave module-level ops behind on a failing compile.
+  // Attach comdat only after the visit succeeds, so the failure path
+  // above only has the new global itself to drop.
   if (mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter))
     newGlobalOp.setComdatAttr(comdatAttr);
   symbolTable.remove(op);
diff --git a/clang/test/CIR/CodeGen/global-self-reference.c b/clang/test/CIR/CodeGen/global-self-reference.c
index 1848f3c50b950a..cccbbfa5c1ed3e 100644
--- a/clang/test/CIR/CodeGen/global-self-reference.c
+++ b/clang/test/CIR/CodeGen/global-self-reference.c
@@ -30,7 +30,6 @@ void **later = &arr[7];
 // LLVM: @solo = {{.*}}global <{ ptr, ptr, [98 x ptr] }> <{ ptr getelementptr {{.*}} i64 40), ptr getelementptr {{.*}} i64 56),
 // LLVM: @follower = {{.*}}global ptr getelementptr {{.*}} @solo, i64 56)
 
-// The self-referential global is the first symbol: in the old code the
-// table was still cold here and the lowering failed.
+// Cold table: the self-referential global is the first symbol in the TU.
 void *solo[100] = {&solo[5], &solo[7], 0};
 void **follower = &solo[7];
diff --git a/clang/test/CIR/Lowering/global-view-bulk-after-adjusted.cir b/clang/test/CIR/Lowering/global-view-bulk-after-adjusted.cir
index 4a64a3d1cfb798..59403ca54f5aae 100644
--- a/clang/test/CIR/Lowering/global-view-bulk-after-adjusted.cir
+++ b/clang/test/CIR/Lowering/global-view-bulk-after-adjusted.cir
@@ -23,4 +23,3 @@ module attributes {cir.triple = "x86_64-unknown-linux-gnu"} {
 // CHECK: llvm.insertvalue
 // CHECK: llvm.mlir.global external @bulk([@arr, @arr])
 // CHECK-NOT: llvm.insertvalue
-// CHECK-NOT: llvm.return

>From ae9a7fc8db8137799a63d8d1c03ea6a88691f2c3 Mon Sep 17 00:00:00 2001
From: Bruno Cardoso Lopes <bruno.cardoso at gmail.com>
Date: Wed, 4 Nov 2026 10:59:49 -0800
Subject: [PATCH 5/7] Address review: read the CIR type before replacing in
 replaceCirGlobal

The helper read op.getSymType() after replaceOpWithNewOp, which erases
the root op without rollback. Harmless today, UAF under one-shot.
Capture it first, like the sites it replaced.
---
 clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
index b2dc3c313c99a2..db8673f476a69f 100644
--- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
+++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
@@ -3503,12 +3503,13 @@ replaceCirGlobal(mlir::SymbolTableCollection &symbolTables, cir::GlobalOp op,
                  llvm::ArrayRef<mlir::NamedAttribute> attributes,
                  mlir::ConversionPatternRewriter &rewriter) {
   mlir::ModuleOp modOp = op->getParentOfType<mlir::ModuleOp>();
+  // Read before the replace erases the root op.
+  mlir::Type cirSymType = op.getSymType();
   symbolTables.getSymbolTable(modOp).remove(op);
   auto newGlobalOp = rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
       op, llvmType, isConst, linkage, symbol, init, alignment, addrSpace,
       isDsoLocal, threadLocalMode, comdatAttr, attributes);
-  newGlobalOp->setAttr(kPreConversionSymType,
-                       mlir::TypeAttr::get(op.getSymType()));
+  newGlobalOp->setAttr(kPreConversionSymType, mlir::TypeAttr::get(cirSymType));
   symbolTables.getSymbolTable(modOp).insert(newGlobalOp);
   return newGlobalOp;
 }

>From ac525d322bc3a879810747b53107517bd5aba930 Mon Sep 17 00:00:00 2001
From: Bruno Cardoso Lopes <bruno.cardoso at gmail.com>
Date: Wed, 4 Nov 2026 11:23:11 -0800
Subject: [PATCH 6/7] Address review: replace pre-conversion type stash with a
 symbol type map

Build the CIR type of every global and function once before
conversion, keyed by symbol name, and pass it to the patterns that
read replaced symbols. Lookups that find an already-lowered LLVM
symbol use the map instead of the LLVM type, which may have been
adjusted. No per-op attribute, no strip step. The map covers globals,
functions, and both alias forms; symbols absent from it were never
CIR and keep the converted-type view. The function branch of
getAddressOfSymbol now also consults the map, making function
lookups independent of lowering order.

Pattern constructors gain the map alongside symbolTables: the shared
custom constructor for GlobalOp and ConstantOp, plus new custom
constructors for the intrinsic-call and vtable patterns that read
replaced symbols.
---
 clang/include/clang/CIR/Dialect/IR/CIROps.td  |  19 ++-
 clang/include/clang/CIR/LoweringHelpers.h     |  39 ++---
 .../CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp | 151 ++++++++++--------
 .../CIR/Lowering/DirectToLLVM/LowerToLLVM.h   |  16 +-
 clang/lib/CIR/Lowering/LoweringHelpers.cpp    |  92 ++++++-----
 5 files changed, 183 insertions(+), 134 deletions(-)

diff --git a/clang/include/clang/CIR/Dialect/IR/CIROps.td b/clang/include/clang/CIR/Dialect/IR/CIROps.td
index 439b2308f538a1..d1ee7c0fec9da0 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIROps.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIROps.td
@@ -688,8 +688,9 @@ def CIR_ConstantOp : CIR_Op<"const", [
 
   let hasCXXABILowering = true;
   let isLLVMLoweringRecursive = true;
-  let customLLVMLoweringConstructorDecl =
-    LoweringBuilders<(ins "LLVMBlockAddressInfo &":$blockInfoAddr)>;
+  let customLLVMLoweringConstructorDecl = LoweringBuilders<(
+      ins "LLVMBlockAddressInfo &":$blockInfoAddr,
+      "const CIRPreConversionTypeMap &":$preConversionTypes)>;
 }
 
 //===----------------------------------------------------------------------===//
@@ -3611,8 +3612,9 @@ def CIR_GlobalOp : CIR_RegionBranchOpBase<"global", [
                                       mlir::OpBuilder &builder) const;
   }];
 
-  let customLLVMLoweringConstructorDecl =
-    LoweringBuilders<(ins "LLVMBlockAddressInfo &":$blockInfoAddr)>;
+  let customLLVMLoweringConstructorDecl = LoweringBuilders<(
+      ins "LLVMBlockAddressInfo &":$blockInfoAddr,
+      "const CIRPreConversionTypeMap &":$preConversionTypes)>;
 }
 
 //===----------------------------------------------------------------------===//
@@ -3699,6 +3701,9 @@ def CIR_VTableAddrPointOp : CIR_Op<"vtable.address_point", [
     `)`
     `:` qualified(type($addr)) attr-dict
   }];
+
+  let customLLVMLoweringConstructorDecl =
+    LoweringBuilders<(ins "const CIRPreConversionTypeMap &":$preConversionTypes)>;
 }
 
 //===----------------------------------------------------------------------===//
@@ -3884,6 +3889,9 @@ def CIR_VTTAddrPointOp : CIR_Op<"vtt.address_point", [
   }];
 
   let hasVerifier = 1;
+
+  let customLLVMLoweringConstructorDecl =
+    LoweringBuilders<(ins "const CIRPreConversionTypeMap &":$preConversionTypes)>;
 }
 
 //===----------------------------------------------------------------------===//
@@ -4671,6 +4679,9 @@ def CIR_LLVMIntrinsicCallOp : CIR_Op<"call_llvm_intrinsic"> {
         $_state.addTypes(resType);
     }]>,
   ];
+
+  let customLLVMLoweringConstructorDecl =
+    LoweringBuilders<(ins "const CIRPreConversionTypeMap &":$preConversionTypes)>;
 }
 
 //===----------------------------------------------------------------------===//
diff --git a/clang/include/clang/CIR/LoweringHelpers.h b/clang/include/clang/CIR/LoweringHelpers.h
index 1090318e1906bd..cb089f3377bb92 100644
--- a/clang/include/clang/CIR/LoweringHelpers.h
+++ b/clang/include/clang/CIR/LoweringHelpers.h
@@ -16,6 +16,14 @@
 #include "mlir/Interfaces/DataLayoutInterfaces.h"
 #include "mlir/Transforms/DialectConversion.h"
 #include "clang/CIR/Dialect/IR/CIRDialect.h"
+#include "llvm/ADT/StringMap.h"
+
+// CIR type of each symbol before lowering, keyed by symbol name. Built once
+// before conversion: lookups after a replacement find the LLVM symbol, whose
+// type may have been adjusted during lowering (split rows, flexible array),
+// and use this instead. Symbols absent from the map were never CIR and keep
+// the converted-type view.
+using CIRPreConversionTypeMap = llvm::StringMap<mlir::Type>;
 
 mlir::DenseElementsAttr
 convertStringAttrToDenseElementsAttr(cir::ConstArrayAttr attr, mlir::Type type);
@@ -34,13 +42,19 @@ convertToDenseElementsAttr(cir::ConstArrayAttr attr,
                            const llvm::SmallVectorImpl<int64_t> &dims,
                            mlir::Type type);
 
-std::optional<mlir::Attribute> lowerConstArrayAttr(
-    cir::ConstArrayAttr constArr, mlir::SymbolTableCollection &symbolTables,
-    const mlir::TypeConverter *converter, mlir::ModuleOp moduleOp = {});
+std::optional<mlir::Attribute>
+lowerConstArrayAttr(cir::ConstArrayAttr constArr,
+                    mlir::SymbolTableCollection &symbolTables,
+                    const mlir::TypeConverter *converter,
+                    const CIRPreConversionTypeMap &preConversionTypes,
+                    mlir::ModuleOp moduleOp = {});
 
-std::optional<mlir::Attribute> lowerConstRecordAttr(
-    cir::ConstRecordAttr constRecord, mlir::SymbolTableCollection &symbolTables,
-    const mlir::TypeConverter *converter, mlir::ModuleOp moduleOp = {});
+std::optional<mlir::Attribute>
+lowerConstRecordAttr(cir::ConstRecordAttr constRecord,
+                     mlir::SymbolTableCollection &symbolTables,
+                     const mlir::TypeConverter *converter,
+                     const CIRPreConversionTypeMap &preConversionTypes,
+                     mlir::ModuleOp moduleOp = {});
 
 /// Return \p attr with the trailing zeros of any array that
 /// adjustGlobalTypeForInit would split off written out as explicit zero
@@ -101,17 +115,4 @@ mlir::Attribute getBitIntStorageAttr(mlir::ConversionPatternRewriter &rewriter,
                                      cir::IntAttr attr,
                                      const mlir::DataLayout &dataLayout);
 
-// Transient attribute holding a symbol's CIR type before lowering. Lookups
-// mid-conversion can find the already-lowered LLVM symbol instead of the
-// CIR op. Its type may have been adjusted during lowering (split rows,
-// flexible array), so readers that need the unadjusted CIR view use this
-// stash. The pass strips it at the end, so it never reaches the output.
-inline constexpr const char *kPreConversionSymType =
-    "cir.preconversion_sym_type";
-
-inline mlir::Type getPreConversionSymType(mlir::Operation *op) {
-  if (auto typeAttr = op->getAttrOfType<mlir::TypeAttr>(kPreConversionSymType))
-    return typeAttr.getValue();
-  return {};
-}
 #endif
diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
index db8673f476a69f..42fcd0d4b36f9f 100644
--- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
+++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
@@ -51,7 +51,6 @@
 #include "clang/CIR/MissingFeatures.h"
 #include "clang/CIR/Passes.h"
 #include "llvm/ADT/MapVector.h"
-#include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/TypeSwitch.h"
 #include "llvm/IR/Module.h"
@@ -498,10 +497,11 @@ class CIRAttrToValue {
                  mlir::ConversionPatternRewriter &rewriter,
                  mlir::SymbolTableCollection &symbolTables,
                  const mlir::TypeConverter *converter,
+                 const CIRPreConversionTypeMap &preConversionTypes,
                  LLVMBlockAddressInfo *blockInfoAddr = nullptr)
       : parentLoc(parentLoc), parentModule(parentModule), rewriter(rewriter),
         symbolTables(symbolTables), converter(converter),
-        blockInfoAddr(blockInfoAddr) {}
+        preConversionTypes(preConversionTypes), blockInfoAddr(blockInfoAddr) {}
 
 #define GET_CIR_ATTR_TO_VALUE_VISITOR_DECLS
 #include "clang/CIR/Dialect/IR/CIRLowering.inc"
@@ -524,21 +524,23 @@ class CIRAttrToValue {
   mlir::ConversionPatternRewriter &rewriter;
   mlir::SymbolTableCollection &symbolTables;
   const mlir::TypeConverter *converter;
+  const CIRPreConversionTypeMap &preConversionTypes;
   // Only available when lowering global initializers that may contain block
   // address attributes. Used to resolve a BlockAddrInfoAttr to its block tag.
   LLVMBlockAddressInfo *blockInfoAddr;
 };
 
 /// Switches on the type of attribute and calls the appropriate conversion.
-mlir::Value lowerCirAttrAsValue(mlir::Location parentLoc,
-                                mlir::ModuleOp parentModule,
-                                const mlir::Attribute attr,
-                                mlir::ConversionPatternRewriter &rewriter,
-                                mlir::SymbolTableCollection &symbolTables,
-                                const mlir::TypeConverter *converter,
-                                LLVMBlockAddressInfo *blockInfoAddr) {
+mlir::Value
+lowerCirAttrAsValue(mlir::Location parentLoc, mlir::ModuleOp parentModule,
+                    const mlir::Attribute attr,
+                    mlir::ConversionPatternRewriter &rewriter,
+                    mlir::SymbolTableCollection &symbolTables,
+                    const mlir::TypeConverter *converter,
+                    const CIRPreConversionTypeMap &preConversionTypes,
+                    LLVMBlockAddressInfo *blockInfoAddr) {
   CIRAttrToValue valueConverter(parentLoc, parentModule, rewriter, symbolTables,
-                                converter, blockInfoAddr);
+                                converter, preConversionTypes, blockInfoAddr);
   return valueConverter.visit(attr);
 }
 
@@ -946,8 +948,8 @@ mlir::Value CIRAttrToValue::visitCirAttr(cir::ConstArrayAttr attr) {
   // for any array type, including an array of split rows, but not for a split
   // array itself: a struct-typed constant needs scalar fields.
   if (mlir::isa<mlir::LLVM::LLVMArrayType>(llvmTy))
-    if (std::optional<mlir::Attribute> constAttr =
-            lowerConstArrayAttr(attr, symbolTables, converter, parentModule))
+    if (std::optional<mlir::Attribute> constAttr = lowerConstArrayAttr(
+            attr, symbolTables, converter, preConversionTypes, parentModule))
       return mlir::LLVM::ConstantOp::create(rewriter, parentLoc, llvmTy,
                                             *constAttr);
 
@@ -1080,9 +1082,10 @@ CIRAttrToValue::getAddressOfSymbol(mlir::FlatSymbolRefAttr symbol) {
   mlir::Operation *sourceSymbol =
       symbolTables.lookupSymbolIn(parentModule, symbol);
   if (auto llvmSymbol = dyn_cast<mlir::LLVM::GlobalOp>(sourceSymbol)) {
-    // Prefer the stashed pre-conversion type: the LLVM global's type may
-    // have been adjusted (split rows, flexible array).
-    if (mlir::Type preType = getPreConversionSymType(llvmSymbol)) {
+    // Prefer the pre-conversion type: the LLVM global's type may have been
+    // adjusted (split rows, flexible array).
+    if (mlir::Type preType =
+            preConversionTypes.lookup(llvmSymbol.getSymName())) {
       originalType = preType;
       sourceType = convertTypeForMemory(*converter, dataLayout, originalType);
     } else {
@@ -1098,7 +1101,12 @@ CIRAttrToValue::getAddressOfSymbol(mlir::FlatSymbolRefAttr symbol) {
             cirSymbol.getAddrSpaceAttr()))
       addrSpace = targetAS.getValue();
   } else if (auto llvmFun = dyn_cast<mlir::LLVM::LLVMFuncOp>(sourceSymbol)) {
-    sourceType = llvmFun.getFunctionType();
+    if (mlir::Type preType = preConversionTypes.lookup(llvmFun.getSymName())) {
+      originalType = preType;
+      sourceType = converter->convertType(originalType);
+    } else {
+      sourceType = llvmFun.getFunctionType();
+    }
     symName = llvmFun.getSymName();
     addrSpace = cirDataLayout.getProgramAddressSpace();
   } else if (auto fun = dyn_cast<cir::FuncOp>(sourceSymbol)) {
@@ -1107,7 +1115,7 @@ CIRAttrToValue::getAddressOfSymbol(mlir::FlatSymbolRefAttr symbol) {
     symName = fun.getSymName();
     addrSpace = cirDataLayout.getProgramAddressSpace();
   } else if (auto alias = dyn_cast<mlir::LLVM::AliasOp>(sourceSymbol)) {
-    if (mlir::Type preType = getPreConversionSymType(alias)) {
+    if (mlir::Type preType = preConversionTypes.lookup(alias.getSymName())) {
       originalType = preType;
       if (mlir::isa<cir::FuncType>(preType))
         sourceType = converter->convertType(originalType);
@@ -2872,9 +2880,9 @@ mlir::LogicalResult CIRToLLVMConstantOpLowering::matchAndRewrite(
     // Lower GlobalViewAttr to llvm.mlir.addressof + llvm.mlir.ptrtoint and
     // BlockAddrDiffAttr to the difference of two llvm.blockaddress.
     if (mlir::isa<cir::GlobalViewAttr, cir::BlockAddrDiffAttr>(op.getValue())) {
-      auto newOp =
-          lowerCirAttrAsValue(op->getLoc(), moduleOp, op.getValue(), rewriter,
-                              symbolTables, getTypeConverter(), &blockInfoAddr);
+      auto newOp = lowerCirAttrAsValue(
+          op->getLoc(), moduleOp, op.getValue(), rewriter, symbolTables,
+          getTypeConverter(), preConversionTypes, &blockInfoAddr);
       rewriter.replaceOp(op, newOp);
       return mlir::success();
     }
@@ -2900,9 +2908,9 @@ mlir::LogicalResult CIRToLLVMConstantOpLowering::matchAndRewrite(
     // llvm.blockaddress.
     if (mlir::isa<cir::GlobalViewAttr, cir::GlobalOffsetAttr, cir::ConstPtrAttr,
                   cir::BlockAddrInfoAttr>(op.getValue())) {
-      auto newOp =
-          lowerCirAttrAsValue(op->getLoc(), moduleOp, op.getValue(), rewriter,
-                              symbolTables, getTypeConverter(), &blockInfoAddr);
+      auto newOp = lowerCirAttrAsValue(
+          op->getLoc(), moduleOp, op.getValue(), rewriter, symbolTables,
+          getTypeConverter(), preConversionTypes, &blockInfoAddr);
       if (!newOp)
         return mlir::failure();
       rewriter.replaceOp(op, newOp);
@@ -2917,12 +2925,14 @@ mlir::LogicalResult CIRToLLVMConstantOpLowering::matchAndRewrite(
       return op.emitError() << "array does not have a constant initializer";
 
     std::optional<mlir::Attribute> denseAttr;
-    if (constArr && (denseAttr = lowerConstArrayAttr(constArr, symbolTables,
-                                                     typeConverter))) {
+    if (constArr &&
+        (denseAttr = lowerConstArrayAttr(constArr, symbolTables, typeConverter,
+                                         preConversionTypes))) {
       attr = denseAttr.value();
     } else {
-      const mlir::Value initVal = lowerCirAttrAsValue(
-          op->getLoc(), moduleOp, value, rewriter, symbolTables, typeConverter);
+      const mlir::Value initVal =
+          lowerCirAttrAsValue(op->getLoc(), moduleOp, value, rewriter,
+                              symbolTables, typeConverter, preConversionTypes);
       if (!initVal)
         return mlir::failure();
       rewriter.replaceOp(op, initVal);
@@ -2930,25 +2940,26 @@ mlir::LogicalResult CIRToLLVMConstantOpLowering::matchAndRewrite(
     }
   } else if (const auto recordAttr =
                  mlir::dyn_cast<cir::ConstRecordAttr>(op.getValue())) {
-    auto initVal = lowerCirAttrAsValue(op->getLoc(), moduleOp,
-                                       spellOutSplitTrailingZeros(recordAttr),
-                                       rewriter, symbolTables, typeConverter);
+    auto initVal = lowerCirAttrAsValue(
+        op->getLoc(), moduleOp, spellOutSplitTrailingZeros(recordAttr),
+        rewriter, symbolTables, typeConverter, preConversionTypes);
     if (!initVal)
       return mlir::failure();
     rewriter.replaceOp(op, initVal);
     return mlir::success();
   } else if (const auto vecTy = mlir::dyn_cast<cir::VectorType>(op.getType())) {
-    mlir::Value initVal =
-        lowerCirAttrAsValue(op->getLoc(), moduleOp, op.getValue(), rewriter,
-                            symbolTables, getTypeConverter());
+    mlir::Value initVal = lowerCirAttrAsValue(
+        op->getLoc(), moduleOp, op.getValue(), rewriter, symbolTables,
+        getTypeConverter(), preConversionTypes);
     if (!initVal)
       return mlir::failure();
     rewriter.replaceOp(op, initVal);
     return mlir::success();
   } else if (mlir::isa<cir::RecordType>(op.getType())) {
     if (mlir::isa<cir::ZeroAttr, cir::UndefAttr>(attr)) {
-      mlir::Value initVal = lowerCirAttrAsValue(
-          op->getLoc(), moduleOp, attr, rewriter, symbolTables, typeConverter);
+      mlir::Value initVal =
+          lowerCirAttrAsValue(op->getLoc(), moduleOp, attr, rewriter,
+                              symbolTables, typeConverter, preConversionTypes);
       if (!initVal)
         return mlir::failure();
       rewriter.replaceOp(op, initVal);
@@ -3162,14 +3173,11 @@ mlir::LogicalResult CIRToLLVMFuncOpLowering::matchAndRewriteAlias(
   // invalidate the cached symbol table either, so build it before the
   // replacement exists and maintain it explicitly below.
   mlir::ModuleOp modOp = op->getParentOfType<mlir::ModuleOp>();
-  mlir::Type preConversionType = op.getFunctionType();
   symbolTables.getSymbolTable(modOp);
   auto aliasOp = mlir::LLVM::AliasOp::create(
       rewriter, loc, ty, convertLinkage(op.getLinkage()), op.getName(),
       op.getDsoLocal(), mlir::LLVM::ThreadLocalMode::NotThreadLocal,
       attributes);
-  aliasOp->setAttr(kPreConversionSymType,
-                   mlir::TypeAttr::get(preConversionType));
   aliasOp.setVisibility_(
       lowerCIRVisibilityToLLVMVisibility(op.getGlobalVisibility()));
   {
@@ -3427,13 +3435,10 @@ CIRToLLVMGlobalOpLowering::setupRegionInitializedLLVMGlobalOp(
   SmallVector<mlir::NamedAttribute> attributes =
       lowerGlobalAttributes(op, rewriter);
 
-  mlir::Type preConversionType = op.getSymType();
   mlir::LLVM::GlobalOp newGlobalOp = mlir::LLVM::GlobalOp::create(
       rewriter, op.getLoc(), llvmType, isConst, linkage, symbol, nullptr,
       alignment, addrSpace, isDsoLocal, threadLocalMode, mlir::SymbolRefAttr{},
       attributes);
-  newGlobalOp->setAttr(kPreConversionSymType,
-                       mlir::TypeAttr::get(preConversionType));
   rewriter.createBlock(&newGlobalOp.getRegion());
   rewriter.setInsertionPointToEnd(newGlobalOp.getInitializerBlock());
   return newGlobalOp;
@@ -3471,7 +3476,8 @@ CIRToLLVMGlobalOpLowering::matchAndRewriteRegionInitializedGlobal(
   // initializer or nested inside an aggregate) can be resolved by the
   // BlockAddrInfoAttr visitor.
   CIRAttrToValue valueConverter(loc, moduleOp, rewriter, symbolTables,
-                                typeConverter, &blockInfoAddr);
+                                typeConverter, preConversionTypes,
+                                &blockInfoAddr);
   mlir::Value value = valueConverter.visit(init);
   if (!value) {
     // Drop the speculative replacement; the table still holds the live
@@ -3491,8 +3497,8 @@ CIRToLLVMGlobalOpLowering::matchAndRewriteRegionInitializedGlobal(
 }
 
 // Replace a CIR global with an LLVM global, maintaining the cached symbol
-// table and stashing the CIR type for later lookups. The table entry is
-// dropped before creation so the replacement reuses the name.
+// table. The table entry is dropped before creation so the replacement
+// reuses the name.
 static mlir::LLVM::GlobalOp
 replaceCirGlobal(mlir::SymbolTableCollection &symbolTables, cir::GlobalOp op,
                  mlir::Type llvmType, bool isConst, mlir::LLVM::Linkage linkage,
@@ -3503,13 +3509,10 @@ replaceCirGlobal(mlir::SymbolTableCollection &symbolTables, cir::GlobalOp op,
                  llvm::ArrayRef<mlir::NamedAttribute> attributes,
                  mlir::ConversionPatternRewriter &rewriter) {
   mlir::ModuleOp modOp = op->getParentOfType<mlir::ModuleOp>();
-  // Read before the replace erases the root op.
-  mlir::Type cirSymType = op.getSymType();
   symbolTables.getSymbolTable(modOp).remove(op);
   auto newGlobalOp = rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
       op, llvmType, isConst, linkage, symbol, init, alignment, addrSpace,
       isDsoLocal, threadLocalMode, comdatAttr, attributes);
-  newGlobalOp->setAttr(kPreConversionSymType, mlir::TypeAttr::get(cirSymType));
   symbolTables.getSymbolTable(modOp).insert(newGlobalOp);
   return newGlobalOp;
 }
@@ -3576,7 +3579,6 @@ mlir::LogicalResult CIRToLLVMGlobalOpLowering::matchAndRewrite(
     auto aliasOp =
         mlir::LLVM::AliasOp::create(rewriter, loc, llvmType, linkage, symbol,
                                     isDsoLocal, threadLocalMode, attributes);
-    aliasOp->setAttr(kPreConversionSymType, mlir::TypeAttr::get(cirSymType));
     {
       mlir::OpBuilder::InsertionGuard guard(rewriter);
       rewriter.createBlock(&aliasOp.getInitializerRegion());
@@ -3614,8 +3616,9 @@ mlir::LogicalResult CIRToLLVMGlobalOpLowering::matchAndRewrite(
       if (isBulkLowerableConstArrayBaseElement(
               getConstArrayBaseElementType(constArr.getType()))) {
         mlir::ModuleOp modOp = op->getParentOfType<mlir::ModuleOp>();
-        if (std::optional<mlir::Attribute> bulkInit = lowerConstArrayAttr(
-                constArr, symbolTables, typeConverter, modOp)) {
+        if (std::optional<mlir::Attribute> bulkInit =
+                lowerConstArrayAttr(constArr, symbolTables, typeConverter,
+                                    preConversionTypes, modOp)) {
           mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter);
           replaceCirGlobal(symbolTables, op, llvmType, isConst, linkage, symbol,
                            bulkInit.value(), alignment, addrSpace, isDsoLocal,
@@ -3632,8 +3635,9 @@ mlir::LogicalResult CIRToLLVMGlobalOpLowering::matchAndRewrite(
       // llvm::ConstantStruct, so the whole initializer becomes a single
       // attribute on the global instead of an insertvalue region.
       mlir::ModuleOp modOp = op->getParentOfType<mlir::ModuleOp>();
-      if (std::optional<mlir::Attribute> bulkInit = lowerConstRecordAttr(
-              constRecord, symbolTables, typeConverter, modOp)) {
+      if (std::optional<mlir::Attribute> bulkInit =
+              lowerConstRecordAttr(constRecord, symbolTables, typeConverter,
+                                   preConversionTypes, modOp)) {
         mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter);
         replaceCirGlobal(symbolTables, op, llvmType, isConst, linkage, symbol,
                          bulkInit.value(), alignment, addrSpace, isDsoLocal,
@@ -4964,14 +4968,15 @@ void ConvertCIRToLLVMPass::runOnOperation() {
   llvm::TimeTraceScope scope("Convert CIR to LLVM Pass");
 
   mlir::ModuleOp module = getOperation();
-  // The pre-conversion type snapshots never reach the output, however the
-  // pass exits. Snapshots only ever sit on module-level symbols.
-  mlir::StringAttr stashName =
-      mlir::StringAttr::get(&getContext(), kPreConversionSymType);
-  llvm::scope_exit stripPreConversionTypes([&] {
-    for (mlir::Operation &op : module.getBody()->getOperations())
-      op.removeAttr(stashName);
-  });
+  // CIR type of each symbol before lowering, for lookups that find the
+  // already-lowered LLVM symbol after replacement.
+  CIRPreConversionTypeMap preConversionTypes;
+  for (mlir::Operation &op : module.getBody()->getOperations()) {
+    if (auto globalOp = mlir::dyn_cast<cir::GlobalOp>(op))
+      preConversionTypes[globalOp.getSymName()] = globalOp.getSymType();
+    else if (auto funcOp = mlir::dyn_cast<cir::FuncOp>(op))
+      preConversionTypes[funcOp.getSymName()] = funcOp.getFunctionType();
+  }
   mlir::DataLayout dl(module);
   mlir::LLVMTypeConverter converter(&getContext());
   prepareTypeConverter(converter, dl);
@@ -4985,15 +4990,23 @@ void ConvertCIRToLLVMPass::runOnOperation() {
   /// repeated O(M) module-wide symbol scans for every call site.
   mlir::SymbolTableCollection symbolTables;
   mlir::RewritePatternSet patterns(&getContext());
-  patterns.add<CIRToLLVMBlockAddressOpLowering, CIRToLLVMConstantOpLowering,
-               CIRToLLVMGlobalOpLowering, CIRToLLVMLabelOpLowering>(
+  patterns.add<CIRToLLVMBlockAddressOpLowering, CIRToLLVMLabelOpLowering>(
       converter, patterns.getContext(), dl, symbolTables, blockInfoAddr);
+  patterns.add<CIRToLLVMGlobalOpLowering, CIRToLLVMConstantOpLowering>(
+      converter, patterns.getContext(), dl, symbolTables, blockInfoAddr,
+      preConversionTypes);
 
   patterns.add<
 #define GET_LLVM_LOWERING_PATTERNS_LIST
 #include "clang/CIR/Dialect/IR/CIRLowering.inc"
 #undef GET_LLVM_LOWERING_PATTERNS_LIST
       >(converter, patterns.getContext(), dl, symbolTables);
+  // Patterns reading replaced symbols take the pre-conversion type map.
+  patterns
+      .add<CIRToLLVMLLVMIntrinsicCallOpLowering,
+           CIRToLLVMVTableAddrPointOpLowering, CIRToLLVMVTTAddrPointOpLowering>(
+          converter, patterns.getContext(), dl, symbolTables,
+          preConversionTypes);
 
   processCIRAttrs(module);
 
@@ -5409,13 +5422,14 @@ getValueForVTableSymbol(mlir::Operation *op,
                         mlir::ConversionPatternRewriter &rewriter,
                         mlir::SymbolTableCollection &symbolTables,
                         const mlir::TypeConverter *converter,
+                        const CIRPreConversionTypeMap &preConversionTypes,
                         mlir::FlatSymbolRefAttr nameAttr, mlir::Type &eltType) {
   auto module = op->getParentOfType<mlir::ModuleOp>();
   mlir::Operation *symbol = symbolTables.lookupSymbolIn(module, nameAttr);
   if (auto llvmSymbol = mlir::dyn_cast<mlir::LLVM::GlobalOp>(symbol)) {
-    // Prefer the stashed pre-conversion type: the LLVM global's type may
-    // have been adjusted (split rows, flexible array).
-    if (mlir::Type preType = getPreConversionSymType(llvmSymbol)) {
+    // Prefer the pre-conversion type: the LLVM global's type may have been
+    // adjusted (split rows, flexible array).
+    if (mlir::Type preType = preConversionTypes.lookup(nameAttr.getValue())) {
       eltType = converter->convertType(preType);
       if (!eltType) {
         emitTypeConversionError(op, preType)
@@ -5449,8 +5463,9 @@ mlir::LogicalResult CIRToLLVMVTableAddrPointOpLowering::matchAndRewrite(
   mlir::Type targetType = converter->convertType(op.getType());
   llvm::SmallVector<mlir::LLVM::GEPArg> offsets;
   mlir::Type eltType;
-  mlir::Value symAddr = getValueForVTableSymbol(
-      op, rewriter, symbolTables, converter, op.getNameAttr(), eltType);
+  mlir::Value symAddr =
+      getValueForVTableSymbol(op, rewriter, symbolTables, converter,
+                              preConversionTypes, op.getNameAttr(), eltType);
   if (!symAddr)
     return mlir::failure();
 
@@ -5513,7 +5528,7 @@ mlir::LogicalResult CIRToLLVMVTTAddrPointOpLowering::matchAndRewrite(
   } else {
     llvmAddr =
         getValueForVTableSymbol(op, rewriter, symbolTables, getTypeConverter(),
-                                op.getNameAttr(), eltType);
+                                preConversionTypes, op.getNameAttr(), eltType);
     if (!llvmAddr)
       return mlir::failure();
     assert(eltType && "Shouldn't ever be missing an eltType here");
diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.h b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.h
index 969c16de651c87..692a424ccce5b4 100644
--- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.h
+++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.h
@@ -17,6 +17,7 @@
 #include "mlir/Transforms/DialectConversion.h"
 #include "clang/CIR/Dialect/IR/CIRDialect.h"
 #include "clang/CIR/Interfaces/CIROpInterfaces.h"
+#include "clang/CIR/LoweringHelpers.h"
 
 namespace cir {
 
@@ -28,13 +29,14 @@ struct LLVMBlockAddressInfo;
 /// May use the datalayout for lowering attributes to-be-stored in memory. When
 /// the attribute may contain block address attributes, `blockInfoAddr` is used
 /// to resolve them.
-mlir::Value lowerCirAttrAsValue(mlir::Location parentLoc,
-                                mlir::ModuleOp parentModule,
-                                mlir::Attribute attr,
-                                mlir::ConversionPatternRewriter &rewriter,
-                                mlir::SymbolTableCollection &symbolTables,
-                                const mlir::TypeConverter *converter,
-                                LLVMBlockAddressInfo *blockInfoAddr = nullptr);
+mlir::Value
+lowerCirAttrAsValue(mlir::Location parentLoc, mlir::ModuleOp parentModule,
+                    mlir::Attribute attr,
+                    mlir::ConversionPatternRewriter &rewriter,
+                    mlir::SymbolTableCollection &symbolTables,
+                    const mlir::TypeConverter *converter,
+                    const CIRPreConversionTypeMap &preConversionTypes,
+                    LLVMBlockAddressInfo *blockInfoAddr = nullptr);
 
 mlir::LLVM::Linkage convertLinkage(cir::GlobalLinkageKind linkage);
 
diff --git a/clang/lib/CIR/Lowering/LoweringHelpers.cpp b/clang/lib/CIR/Lowering/LoweringHelpers.cpp
index 693e73a70ec537..54ddb08028c42b 100644
--- a/clang/lib/CIR/Lowering/LoweringHelpers.cpp
+++ b/clang/lib/CIR/Lowering/LoweringHelpers.cpp
@@ -275,10 +275,11 @@ std::optional<mlir::DenseElementsAttr> convertToDenseElementsAttr(
 
 /// Return true when \p gv can be lowered to a \c FlatSymbolRefAttr leaf without
 /// addrspacecast or bitcast (mirrors \c CIRAttrToValue::visitCirAttr).
-static bool
-globalViewMatchesPointerLeaf(cir::GlobalViewAttr gv, mlir::ModuleOp moduleOp,
-                             mlir::SymbolTableCollection &symbolTables,
-                             const mlir::TypeConverter *converter) {
+static bool globalViewMatchesPointerLeaf(
+    cir::GlobalViewAttr gv, mlir::ModuleOp moduleOp,
+    mlir::SymbolTableCollection &symbolTables,
+    const mlir::TypeConverter *converter,
+    const CIRPreConversionTypeMap &preConversionTypes) {
   if (gv.getIndices() || mlir::isa<cir::IntType, cir::VPtrType>(gv.getType()))
     return false;
 
@@ -290,10 +291,11 @@ globalViewMatchesPointerLeaf(cir::GlobalViewAttr gv, mlir::ModuleOp moduleOp,
   mlir::Type sourceType;
   auto sourceSymbol = symbolTables.lookupSymbolIn(moduleOp, gv.getSymbol());
   if (auto llvmSymbol = mlir::dyn_cast<mlir::LLVM::GlobalOp>(sourceSymbol)) {
-    // Prefer the stashed pre-conversion type: the lowered type may have been
+    // Prefer the pre-conversion type: the lowered type may have been
     // adjusted, which would answer differently depending on lowering order.
-    // Globals that were never CIR (no stash) keep the converted-type view.
-    if (mlir::Type preType = getPreConversionSymType(llvmSymbol))
+    // Globals absent from the map were never CIR and keep the converted-type
+    // view.
+    if (mlir::Type preType = preConversionTypes.lookup(llvmSymbol.getSymName()))
       sourceType = converter->convertType(preType);
     else
       sourceType = llvmSymbol.getType();
@@ -329,10 +331,12 @@ static std::optional<mlir::Attribute>
 lowerPointerElementAttr(mlir::Attribute elt, mlir::MLIRContext *ctx,
                         mlir::ModuleOp moduleOp,
                         mlir::SymbolTableCollection &symbolTables,
-                        const mlir::TypeConverter *converter) {
+                        const mlir::TypeConverter *converter,
+                        const CIRPreConversionTypeMap &preConversionTypes) {
   if (auto gv = mlir::dyn_cast<cir::GlobalViewAttr>(elt)) {
     if (!moduleOp ||
-        !globalViewMatchesPointerLeaf(gv, moduleOp, symbolTables, converter))
+        !globalViewMatchesPointerLeaf(gv, moduleOp, symbolTables, converter,
+                                      preConversionTypes))
       return std::nullopt;
     return gv.getSymbol();
   }
@@ -428,14 +432,18 @@ mlir::Attribute spellOutSplitTrailingZeros(mlir::Attribute attr) {
 
 static std::optional<mlir::Attribute> lowerConstRecordMemberAttr(
     mlir::Attribute attr, mlir::SymbolTableCollection &symbolTables,
-    const mlir::TypeConverter *converter, mlir::ModuleOp moduleOp);
+    const mlir::TypeConverter *converter,
+    const CIRPreConversionTypeMap &preConversionTypes, mlir::ModuleOp moduleOp);
 
 /// Lower \p constArr, which is or contains an array split by
 /// adjustGlobalArrayTypeForInit, element by element into the shape of its
 /// adjusted type. A dense attribute would span the split-off zeros.
-static std::optional<mlir::Attribute> lowerConstArrayAttrByElement(
-    cir::ConstArrayAttr constArr, mlir::SymbolTableCollection &symbolTables,
-    const mlir::TypeConverter *converter, mlir::ModuleOp moduleOp) {
+static std::optional<mlir::Attribute>
+lowerConstArrayAttrByElement(cir::ConstArrayAttr constArr,
+                             mlir::SymbolTableCollection &symbolTables,
+                             const mlir::TypeConverter *converter,
+                             const CIRPreConversionTypeMap &preConversionTypes,
+                             mlir::ModuleOp moduleOp) {
   mlir::MLIRContext *ctx = constArr.getContext();
   auto arrayTy = mlir::cast<cir::ArrayType>(constArr.getType());
   auto elts = mlir::cast<mlir::ArrayAttr>(constArr.getElts());
@@ -449,15 +457,15 @@ static std::optional<mlir::Attribute> lowerConstArrayAttrByElement(
   if (structTy && structTy.getBody().size() < elts.size()) {
     auto prefix = cir::ConstArrayAttr::get(
         cir::ArrayType::get(arrayTy.getElementType(), elts.size()), elts);
-    std::optional<mlir::Attribute> loweredPrefix =
-        lowerConstArrayAttr(prefix, symbolTables, converter, moduleOp);
+    std::optional<mlir::Attribute> loweredPrefix = lowerConstArrayAttr(
+        prefix, symbolTables, converter, preConversionTypes, moduleOp);
     if (!loweredPrefix)
       return std::nullopt;
     lowered.push_back(*loweredPrefix);
   } else {
     for (mlir::Attribute elt : elts) {
-      std::optional<mlir::Attribute> loweredElt =
-          lowerConstRecordMemberAttr(elt, symbolTables, converter, moduleOp);
+      std::optional<mlir::Attribute> loweredElt = lowerConstRecordMemberAttr(
+          elt, symbolTables, converter, preConversionTypes, moduleOp);
       if (!loweredElt)
         return std::nullopt;
       lowered.push_back(*loweredElt);
@@ -472,9 +480,12 @@ static std::optional<mlir::Attribute> lowerConstArrayAttrByElement(
   return mlir::ArrayAttr::get(ctx, lowered);
 }
 
-std::optional<mlir::Attribute> lowerConstArrayAttr(
-    cir::ConstArrayAttr constArr, mlir::SymbolTableCollection &symbolTables,
-    const mlir::TypeConverter *converter, mlir::ModuleOp moduleOp) {
+std::optional<mlir::Attribute>
+lowerConstArrayAttr(cir::ConstArrayAttr constArr,
+                    mlir::SymbolTableCollection &symbolTables,
+                    const mlir::TypeConverter *converter,
+                    const CIRPreConversionTypeMap &preConversionTypes,
+                    mlir::ModuleOp moduleOp) {
   // Ensure ConstArrayAttr has a type.
   const auto typedConstArr = mlir::cast<mlir::TypedAttr>(constArr);
 
@@ -499,7 +510,7 @@ std::optional<mlir::Attribute> lowerConstArrayAttr(
 
   if (containsSplitTrailingZeros(constArr))
     return lowerConstArrayAttrByElement(constArr, symbolTables, converter,
-                                        moduleOp);
+                                        preConversionTypes, moduleOp);
 
   if (mlir::isa<mlir::StringAttr>(constArr.getElts()))
     return convertStringAttrToDenseElementsAttr(constArr,
@@ -534,8 +545,8 @@ std::optional<mlir::Attribute> lowerConstArrayAttr(
     lowered.reserve(eltsArr.size());
     mlir::MLIRContext *ctx = constArr.getContext();
     for (mlir::Attribute elt : eltsArr) {
-      std::optional<mlir::Attribute> llvmElt =
-          lowerPointerElementAttr(elt, ctx, moduleOp, symbolTables, converter);
+      std::optional<mlir::Attribute> llvmElt = lowerPointerElementAttr(
+          elt, ctx, moduleOp, symbolTables, converter, preConversionTypes);
       if (!llvmElt)
         return std::nullopt;
       lowered.push_back(*llvmElt);
@@ -553,8 +564,8 @@ std::optional<mlir::Attribute> lowerConstArrayAttr(
     loweredElts.reserve(cirArrayType.getSize());
 
     for (mlir::Attribute elt : eltsArr) {
-      std::optional<mlir::Attribute> llvmElt =
-          lowerConstRecordMemberAttr(elt, symbolTables, converter, moduleOp);
+      std::optional<mlir::Attribute> llvmElt = lowerConstRecordMemberAttr(
+          elt, symbolTables, converter, preConversionTypes, moduleOp);
       if (!llvmElt)
         return std::nullopt;
       loweredElts.push_back(*llvmElt);
@@ -578,16 +589,21 @@ std::optional<mlir::Attribute> lowerConstArrayAttr(
 /// represented as a single constant attribute (e.g. an indexed
 /// \c GlobalViewAttr), in which case the caller falls back to the region-based
 /// lowering.
-static std::optional<mlir::Attribute> lowerConstRecordMemberAttr(
-    mlir::Attribute attr, mlir::SymbolTableCollection &symbolTables,
-    const mlir::TypeConverter *converter, mlir::ModuleOp moduleOp) {
+static std::optional<mlir::Attribute>
+lowerConstRecordMemberAttr(mlir::Attribute attr,
+                           mlir::SymbolTableCollection &symbolTables,
+                           const mlir::TypeConverter *converter,
+                           const CIRPreConversionTypeMap &preConversionTypes,
+                           mlir::ModuleOp moduleOp) {
   mlir::MLIRContext *ctx = attr.getContext();
 
   if (auto arrayAttr = mlir::dyn_cast<cir::ConstArrayAttr>(attr))
-    return lowerConstArrayAttr(arrayAttr, symbolTables, converter, moduleOp);
+    return lowerConstArrayAttr(arrayAttr, symbolTables, converter,
+                               preConversionTypes, moduleOp);
 
   if (auto recordAttr = mlir::dyn_cast<cir::ConstRecordAttr>(attr))
-    return lowerConstRecordAttr(recordAttr, symbolTables, converter, moduleOp);
+    return lowerConstRecordAttr(recordAttr, symbolTables, converter,
+                                preConversionTypes, moduleOp);
 
   if (mlir::isa<cir::ZeroAttr>(attr))
     return mlir::LLVM::ZeroAttr::get(ctx);
@@ -614,7 +630,8 @@ static std::optional<mlir::Attribute> lowerConstRecordMemberAttr(
 
   // Null pointers and simple address-of-global references can be represented
   // as constant attributes; anything more complex uses the region fallback.
-  return lowerPointerElementAttr(attr, ctx, moduleOp, symbolTables, converter);
+  return lowerPointerElementAttr(attr, ctx, moduleOp, symbolTables, converter,
+                                 preConversionTypes);
 }
 
 // Figure out if we want mark the new struct 'packed' if it isn't already. IF
@@ -920,9 +937,12 @@ mlir::Type adjustGlobalTypeForInit(mlir::Type llvmType, mlir::Attribute init,
                                  ignoredAddedIndexes);
 }
 
-std::optional<mlir::Attribute> lowerConstRecordAttr(
-    cir::ConstRecordAttr constRecord, mlir::SymbolTableCollection &symbolTables,
-    const mlir::TypeConverter *converter, mlir::ModuleOp moduleOp) {
+std::optional<mlir::Attribute>
+lowerConstRecordAttr(cir::ConstRecordAttr constRecord,
+                     mlir::SymbolTableCollection &symbolTables,
+                     const mlir::TypeConverter *converter,
+                     const CIRPreConversionTypeMap &preConversionTypes,
+                     mlir::ModuleOp moduleOp) {
 
   // Build one constant attribute per record member. The LLVM dialect global
   // translation accepts an ArrayAttr (one element per struct field) and emits
@@ -932,8 +952,8 @@ std::optional<mlir::Attribute> lowerConstRecordAttr(
   llvm::SmallVector<mlir::Attribute> loweredMembers;
   loweredMembers.reserve(memberAttrs.size());
   for (mlir::Attribute member : memberAttrs) {
-    std::optional<mlir::Attribute> lowered =
-        lowerConstRecordMemberAttr(member, symbolTables, converter, moduleOp);
+    std::optional<mlir::Attribute> lowered = lowerConstRecordMemberAttr(
+        member, symbolTables, converter, preConversionTypes, moduleOp);
     if (!lowered)
       return std::nullopt;
     loweredMembers.push_back(*lowered);

>From 5bc989040c16a9b1c9c70a643ecc710d607108fb Mon Sep 17 00:00:00 2001
From: Bruno Cardoso Lopes <bruno.cardoso at gmail.com>
Date: Wed, 4 Nov 2026 11:49:32 -0800
Subject: [PATCH 7/7] Fix CI: drop unused preConversionTypes from
 intrinsic-call lowering

The map is only read through CIRAttrToValue in that pattern; the
generated member was never referenced and trips
-Werror,-Wunused-private-field on Clang builds. The pattern returns
to the default constructor and the auto-registered list.
---
 clang/include/clang/CIR/Dialect/IR/CIROps.td        | 3 ---
 clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp | 3 +--
 2 files changed, 1 insertion(+), 5 deletions(-)

diff --git a/clang/include/clang/CIR/Dialect/IR/CIROps.td b/clang/include/clang/CIR/Dialect/IR/CIROps.td
index d1ee7c0fec9da0..3934f0cffc395e 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIROps.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIROps.td
@@ -4679,9 +4679,6 @@ def CIR_LLVMIntrinsicCallOp : CIR_Op<"call_llvm_intrinsic"> {
         $_state.addTypes(resType);
     }]>,
   ];
-
-  let customLLVMLoweringConstructorDecl =
-    LoweringBuilders<(ins "const CIRPreConversionTypeMap &":$preConversionTypes)>;
 }
 
 //===----------------------------------------------------------------------===//
diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
index 42fcd0d4b36f9f..9d918850955ef0 100644
--- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
+++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
@@ -5003,8 +5003,7 @@ void ConvertCIRToLLVMPass::runOnOperation() {
       >(converter, patterns.getContext(), dl, symbolTables);
   // Patterns reading replaced symbols take the pre-conversion type map.
   patterns
-      .add<CIRToLLVMLLVMIntrinsicCallOpLowering,
-           CIRToLLVMVTableAddrPointOpLowering, CIRToLLVMVTTAddrPointOpLowering>(
+      .add<CIRToLLVMVTableAddrPointOpLowering, CIRToLLVMVTTAddrPointOpLowering>(
           converter, patterns.getContext(), dl, symbolTables,
           preConversionTypes);
 



More information about the cfe-commits mailing list