[clang] [CIR] Implement 'weak-ref' lowering (PR #238538)

Erich Keane via cfe-commits cfe-commits at lists.llvm.org
Wed Nov 4 13:00:17 PST 2026


https://github.com/erichkeane updated https://github.com/llvm/llvm-project/pull/238538

>From 5a9397f341a5873a372fdd835adba75746704515 Mon Sep 17 00:00:00 2001
From: erichkeane <ekeane at nvidia.com>
Date: Tue, 3 Nov 2026 13:39:49 -0800
Subject: [PATCH 1/5] [CIR] Implement 'weak-ref' lowering

This patch implements the weakref attribute, replacing 2 missing
features and quite a few 'NYI' diagnostics.

This is handled for both functions and variables, so it needs to be
threaded in a few places.  For the most part, this is a copy of the
classic-codegen changes, though a few places cause us to have to do
things in slightly different orders, such as the CIRGenExprConstant
changes, where the CIR differentiation between a global view to variable
and function are different.

AI disclosure: Claude wrote up the test and got more cases than I came up
with in my attempt.
---
 clang/include/clang/CIR/MissingFeatures.h    |   2 -
 clang/lib/CIR/CodeGen/CIRGenExpr.cpp         |  17 ++-
 clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp |  16 +--
 clang/lib/CIR/CodeGen/CIRGenModule.cpp       |  46 +++++++-
 clang/lib/CIR/CodeGen/CIRGenModule.h         |  10 ++
 clang/test/CIR/CodeGen/attr-weakref.c        | 115 ++++++++++++++++++-
 6 files changed, 187 insertions(+), 19 deletions(-)

diff --git a/clang/include/clang/CIR/MissingFeatures.h b/clang/include/clang/CIR/MissingFeatures.h
index 323cf2423c354c..8986da21542da7 100644
--- a/clang/include/clang/CIR/MissingFeatures.h
+++ b/clang/include/clang/CIR/MissingFeatures.h
@@ -30,7 +30,6 @@ struct MissingFeatures {
 
   // Unhandled global/linkage information.
   static bool opGlobalThreadLocal() { return false; }
-  static bool opGlobalWeakRef() { return false; }
   static bool opGlobalUnnamedAddr() { return false; }
   static bool opGlobalVisibility() { return false; }
   static bool opGlobalDLLImportExport() { return false; }
@@ -305,7 +304,6 @@ struct MissingFeatures {
   static bool vlas() { return false; }
   static bool vtableEmitMetadata() { return false; }
   static bool vtableRelativeLayout() { return false; }
-  static bool weakRefReference() { return false; }
   static bool writebacks() { return false; }
   static bool msvcCXXPersonality() { return false; }
   static bool functionUsesSEHTry() { return false; }
diff --git a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
index 68a06cf7e04ab5..e64cc6e7201118 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
@@ -974,7 +974,9 @@ Address CIRGenFunction::emitExtVectorElementLValue(LValue lv,
 }
 
 static cir::FuncOp emitFunctionDeclPointer(CIRGenModule &cgm, GlobalDecl gd) {
-  assert(!cir::MissingFeatures::weakRefReference());
+  const auto *fd = cast<FunctionDecl>(gd.getDecl());
+  if (fd->hasAttr<WeakRefAttr>())
+    return cast<cir::FuncOp>(cgm.getWeakRefReference(fd));
   return cgm.getAddrOfFunction(gd);
 }
 
@@ -1194,8 +1196,17 @@ LValue CIRGenFunction::emitDeclRefLValue(const DeclRefExpr *e) {
           !e->getLocation().isValid()) &&
          "Should not use decl without marking it used!");
 
-  if (nd->hasAttr<WeakRefAttr>())
-    cgm.errorNYI(nd->getSourceRange(), "emitGlobal: WeakRefAttr");
+  // A weakref variable refers to its alias target. Weakref functions are
+  // handled by emitFunctionDeclPointer.
+  if (const auto *vd = dyn_cast<VarDecl>(nd);
+      vd && vd->hasAttr<WeakRefAttr>()) {
+    auto aliasee = mlir::cast<cir::GlobalOp>(cgm.getWeakRefReference(vd));
+    mlir::Value v =
+        builder.createGetGlobal(getLoc(e->getSourceRange()), aliasee);
+    Address addr(v, convertTypeForMem(vd->getType()),
+                 getContext().getDeclAlign(vd));
+    return makeAddrLValue(addr, ty, AlignmentSource::Decl);
+  }
 
   if (const auto *vd = dyn_cast<VarDecl>(nd)) {
     // Checks for omitted feature handling
diff --git a/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp b/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp
index ad8034bfbae4e3..89d80b647a81ae 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp
@@ -946,14 +946,11 @@ ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) {
     // at properties of the most recent declaration at the point of emission.
     d = cast<ValueDecl>(d->getMostRecentDecl());
 
-    if (d->hasAttr<WeakRefAttr>()) {
-      cgm.errorNYI(d->getSourceRange(),
-                   "ConstantLValueEmitter: emit pointer base for weakref");
-      return {};
-    }
-
     if (auto *fd = dyn_cast<FunctionDecl>(d)) {
-      cir::FuncOp fop = cgm.getAddrOfFunction(fd);
+      cir::FuncOp fop =
+          fd->hasAttr<WeakRefAttr>()
+              ? mlir::cast<cir::FuncOp>(cgm.getWeakRefReference(fd))
+              : cgm.getAddrOfFunction(fd);
       CIRGenBuilderTy &builder = cgm.getBuilder();
       mlir::MLIRContext *mlirContext = builder.getContext();
       // Use the destination pointer type (e.g. struct field type), not
@@ -978,6 +975,11 @@ ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) {
           ptrTy, mlir::FlatSymbolRefAttr::get(mlirContext, symName));
     }
 
+    // A weakref refers to its alias target. Handle non-function versions here.
+    if (d->hasAttr<WeakRefAttr>())
+      return cgm.getBuilder().getGlobalViewAttr(
+          cast<cir::GlobalOp>(cgm.getWeakRefReference(d)));
+
     if (auto *vd = dyn_cast<VarDecl>(d)) {
       // We can never refer to a variable with local storage.
       if (!vd->hasLocalStorage()) {
diff --git a/clang/lib/CIR/CodeGen/CIRGenModule.cpp b/clang/lib/CIR/CodeGen/CIRGenModule.cpp
index 7047df9d1a0cc1..c61bbfbf0d4335 100644
--- a/clang/lib/CIR/CodeGen/CIRGenModule.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenModule.cpp
@@ -1293,7 +1293,10 @@ CIRGenModule::getOrCreateCIRGlobal(StringRef mangledName, mlir::Type ty,
 
   if (entry) {
     mlir::ptr::MemorySpaceAttrInterface entryCIRAS = entry.getAddrSpaceAttr();
-    assert(!cir::MissingFeatures::opGlobalWeakRef());
+
+    // A weakref's target is only weak until something else names it.
+    if (weakRefReferences.erase(entry) && d && !d->hasAttr<WeakAttr>())
+      entry.setLinkage(cir::GlobalLinkageKind::ExternalLinkage);
 
     assert(!cir::MissingFeatures::setDLLStorageClass());
     assert(!cir::MissingFeatures::openMP());
@@ -1323,7 +1326,7 @@ CIRGenModule::getOrCreateCIRGlobal(StringRef mangledName, mlir::Type ty,
       return entry;
   }
 
-  mlir::Location loc = getLoc(d->getSourceRange());
+  mlir::Location loc = d ? getLoc(d->getSourceRange()) : theModule->getLoc();
 
   // Calculate constant storage flag before creating the global. This was moved
   // from after the global creation to ensure the constant flag is set correctly
@@ -1427,6 +1430,33 @@ CIRGenModule::getOrCreateCIRGlobal(StringRef mangledName, mlir::Type ty,
   return gv;
 }
 
+mlir::Operation *CIRGenModule::getWeakRefReference(const ValueDecl *vd) {
+  const auto *aa = vd->getAttr<AliasAttr>();
+  assert(aa && "No alias?");
+
+  // See if there is already something with the target's name in the module.
+  if (mlir::Operation *entry = getGlobalValue(aa->getAliasee()))
+    return entry;
+
+  mlir::Operation *aliasee;
+  if (const auto *fd = dyn_cast<FunctionDecl>(vd)) {
+    cir::FuncOp fn =
+        getOrCreateCIRFunction(aa->getAliasee(), convertType(fd->getType()),
+                               GlobalDecl(fd), /*forVTable=*/false);
+    fn.setLinkage(cir::GlobalLinkageKind::ExternalWeakLinkage);
+    aliasee = fn;
+  } else {
+    cir::GlobalOp gv = getOrCreateCIRGlobal(
+        aa->getAliasee(), getTypes().convertTypeForMem(vd->getType()),
+        LangAS::Default, /*d=*/nullptr, NotForDefinition);
+    gv.setLinkage(cir::GlobalLinkageKind::ExternalWeakLinkage);
+    aliasee = gv;
+  }
+
+  weakRefReferences.insert(aliasee);
+  return aliasee;
+}
+
 cir::GlobalOp
 CIRGenModule::getOrCreateCIRGlobal(const VarDecl *d, mlir::Type ty,
                                    ForDefinition_t isForDefinition) {
@@ -1725,6 +1755,10 @@ void CIRGenModule::emitGlobalVarDefinition(const clang::VarDecl *vd,
       gv.setConstant(true);
   }
 
+  // The global may have been created without a declaration, e.g. as the target
+  // of a weakref, so make sure the alignment comes from the definition.
+  gv.setAlignmentAttr(getSize(astContext.getDeclAlign(vd)));
+
   // Set CIR linkage and DLL storage class.
   gv.setLinkage(linkage);
   // FIXME(cir): setLinkage should likely set MLIR's visibility automatically.
@@ -3701,7 +3735,13 @@ cir::FuncOp CIRGenModule::getOrCreateCIRFunction(
   if (entry) {
     assert(mlir::isa<cir::FuncOp>(entry));
 
-    assert(!cir::MissingFeatures::weakRefReference());
+    // A weakref's target is only weak until something else names it.
+    if (weakRefReferences.erase(entry)) {
+      const auto *fd = cast_or_null<FunctionDecl>(d);
+      if (fd && !fd->hasAttr<WeakAttr>())
+        cast<cir::FuncOp>(entry).setLinkage(
+            cir::GlobalLinkageKind::ExternalLinkage);
+    }
 
     // Handle dropped DLL attributes.
     if (d && !d->hasAttr<DLLImportAttr>() && !d->hasAttr<DLLExportAttr>()) {
diff --git a/clang/lib/CIR/CodeGen/CIRGenModule.h b/clang/lib/CIR/CodeGen/CIRGenModule.h
index 074ca5818ae2ee..718b5fc3ade7b0 100644
--- a/clang/lib/CIR/CodeGen/CIRGenModule.h
+++ b/clang/lib/CIR/CodeGen/CIRGenModule.h
@@ -141,6 +141,11 @@ class CIRGenModule : public CIRGenTypeCache {
 
   llvm::DenseSet<clang::GlobalDecl> diagnosedConflictingDefinitions;
 
+  /// Symbols created as the target of a weakref. They are extern_weak until
+  /// something names them in a way that is not itself weak, such as an
+  /// ordinary declaration or definition of the target.
+  llvm::SmallPtrSet<mlir::Operation *, 4> weakRefReferences;
+
   /// -------
   /// Annotations
   /// -------
@@ -295,6 +300,11 @@ class CIRGenModule : public CIRGenTypeCache {
   cir::GlobalOp getOrCreateCIRGlobal(const VarDecl *d, mlir::Type ty,
                                      ForDefinition_t isForDefinition);
 
+  /// Return the symbol that a weakref declaration refers to: the cir.func or
+  /// cir.global named by its alias target, declared extern_weak if it did not
+  /// already exist.
+  mlir::Operation *getWeakRefReference(const clang::ValueDecl *vd);
+
   cir::GlobalOp
   createGlobalOp(mlir::Location loc, llvm::StringRef name, mlir::Type t,
                  bool isConstant = false,
diff --git a/clang/test/CIR/CodeGen/attr-weakref.c b/clang/test/CIR/CodeGen/attr-weakref.c
index 621a277d79e790..a71dc71159513d 100644
--- a/clang/test/CIR/CodeGen/attr-weakref.c
+++ b/clang/test/CIR/CodeGen/attr-weakref.c
@@ -3,7 +3,22 @@
 // RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fclangir -emit-llvm %s -o %t-cir.ll
 // RUN: FileCheck --check-prefix=LLVM --input-file=%t-cir.ll %s
 // RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm %s -o %t.ll
-// RUN: FileCheck --check-prefix=OGCG --input-file=%t.ll %s
+// RUN: FileCheck --check-prefix=LLVM --input-file=%t.ll %s
+
+// Globals. A weakref's target is extern_weak unless the target is also declared
+// or defined, without being weak, elsewhere in the translation unit.
+// CIR-DAG: cir.global "private" extern_weak @var_target : !s32i
+// LLVM-DAG: @var_target = extern_weak global i32
+// CIR-DAG: cir.global external @var_init = #cir.global_view<@var_target> : !cir.ptr<!s32i> align(8)
+// LLVM-DAG: @var_init = global ptr @var_target, align 8
+// CIR-DAG: cir.global external @fn_init = #cir.global_view<@fn_target> : !cir.ptr<!cir.func<(!s32i)>> align(8)
+// LLVM-DAG: @fn_init = global ptr @fn_target, align 8
+// CIR-DAG: cir.global external @later_def = #cir.int<5> : !s32i align(4)
+// LLVM-DAG: @later_def = global i32 5, align 4
+// CIR-DAG: cir.global "private" external @decl_target : !s32i
+// LLVM-DAG: @decl_target = external global i32
+// CIR-DAG: cir.global "private" extern_weak @weak_target : !s32i
+// LLVM-DAG: @weak_target = extern_weak global i32
 
 // A weakref declaration that is never referenced should produce no output for
 // either the alias or its target. Only the unrelated definition below should
@@ -18,9 +33,101 @@ void unrelated(void) {}
 // CIR-NOT: @weakref_target
 // LLVM-NOT: @weakref_alias
 // LLVM-NOT: @weakref_target
-// OGCG-NOT: @weakref_alias
-// OGCG-NOT: @weakref_target
 
 // CIR: cir.func{{.*}}@unrelated
 // LLVM: define{{.*}}@unrelated
-// OGCG: define{{.*}}@unrelated
+
+// A reference to a weakref is a reference to its target, which is declared
+// extern_weak.
+static int var_ref __attribute__((weakref("var_target")));
+static void fn_ref(int) __attribute__((weakref("fn_target")));
+
+int read_var(void) { return var_ref; }
+// CIR: cir.func {{.*}}@read_var()
+// CIR:   %[[VAR:.*]] = cir.get_global @var_target : !cir.ptr<!s32i>
+// CIR:   cir.load align(4) %[[VAR]]
+// LLVM: define {{.*}}@read_var()
+// LLVM:   load i32, ptr @var_target, align 4
+
+int *addr_var(void) { return &var_ref; }
+// CIR: cir.func {{.*}}@addr_var()
+// CIR:   cir.get_global @var_target : !cir.ptr<!s32i>
+// LLVM: define {{.*}}@addr_var()
+// LLVM:   ptr @var_target
+
+void call_fn(void) { fn_ref(1); }
+// CIR: cir.func {{.*}}@call_fn()
+// CIR:   cir.call @fn_target(%{{.*}}) : (!s32i {llvm.noundef}) -> ()
+// CIR: cir.func extern_weak private @fn_target(!s32i {llvm.noundef})
+// LLVM: define {{.*}}@call_fn()
+// LLVM:   call void @fn_target(i32 noundef 1)
+// LLVM: declare extern_weak void @fn_target(i32 noundef)
+
+int fn_not_null(void) { return fn_ref != 0; }
+// CIR: cir.func {{.*}}@fn_not_null()
+// CIR:   %[[FN:.*]] = cir.get_global @fn_target : !cir.ptr<!cir.func<(!s32i)>>
+// CIR:   cir.cmp ne %[[FN]], %{{.*}} : !cir.ptr<!cir.func<(!s32i)>>
+// LLVM: define {{.*}}@fn_not_null()
+// LLVM:   icmp ne ptr @fn_target, null
+
+void call_fn_through_pointer(void) {
+  void (*p)(int) = fn_ref;
+  p(2);
+}
+// CIR: cir.func {{.*}}@call_fn_through_pointer()
+// CIR:   cir.get_global @fn_target
+// LLVM: define {{.*}}@call_fn_through_pointer()
+// LLVM:   store ptr @fn_target, ptr %{{.*}}
+// LLVM:   call void %{{.*}}(i32 noundef 2)
+
+// A weakref in a constant initializer is the address of its target.
+int *var_init = &var_ref;
+void (*fn_init)(int) = fn_ref;
+
+// The target of a weakref is no longer weak once it is defined, or declared
+// without 'weak', anywhere in the translation unit, even after the weakref is
+// used.
+static int later_ref __attribute__((weakref("later_def")));
+int *addr_later(void) { return &later_ref; }
+int later_def = 5;
+// CIR: cir.func {{.*}}@addr_later()
+// CIR:   cir.get_global @later_def : !cir.ptr<!s32i>
+// LLVM: define {{.*}}@addr_later()
+// LLVM:   ptr @later_def
+
+static void later_fn_ref(void) __attribute__((weakref("later_fn")));
+void call_later_fn(void) { later_fn_ref(); }
+void later_fn(void) {}
+// CIR: cir.func {{.*}}@call_later_fn()
+// CIR:   cir.call @later_fn() : () -> ()
+// CIR: cir.func no_inline dso_local @later_fn()
+// LLVM: define {{.*}}@call_later_fn()
+// LLVM:   call void @later_fn()
+// LLVM: define dso_local void @later_fn()
+
+static int decl_ref __attribute__((weakref("decl_target")));
+int read_decl(void) { return decl_ref; }
+extern int decl_target;
+int read_decl_target(void) { return decl_target; }
+// CIR: cir.func {{.*}}@read_decl()
+// CIR:   cir.get_global @decl_target : !cir.ptr<!s32i>
+// CIR: cir.func {{.*}}@read_decl_target()
+// CIR:   cir.get_global @decl_target : !cir.ptr<!s32i>
+// LLVM: define {{.*}}@read_decl()
+// LLVM:   load i32, ptr @decl_target
+// LLVM: define {{.*}}@read_decl_target()
+// LLVM:   load i32, ptr @decl_target
+
+// If the target is itself declared weak, it stays weak.
+static int weak_ref __attribute__((weakref("weak_target")));
+int read_weak(void) { return weak_ref; }
+extern int weak_target __attribute__((weak));
+int read_weak_target(void) { return weak_target; }
+// CIR: cir.func {{.*}}@read_weak()
+// CIR:   cir.get_global @weak_target : !cir.ptr<!s32i>
+// CIR: cir.func {{.*}}@read_weak_target()
+// CIR:   cir.get_global @weak_target : !cir.ptr<!s32i>
+// LLVM: define {{.*}}@read_weak()
+// LLVM:   load i32, ptr @weak_target
+// LLVM: define {{.*}}@read_weak_target()
+// LLVM:   load i32, ptr @weak_target

>From e85a6b7c5ec4292f5de7e53caa51dccf396e26e9 Mon Sep 17 00:00:00 2001
From: erichkeane <ekeane at nvidia.com>
Date: Wed, 4 Nov 2026 06:54:13 -0800
Subject: [PATCH 2/5] Add loc arg to the getOrCreateCIRGlobal overload

---
 clang/lib/CIR/CodeGen/CIRGenModule.cpp | 18 ++++++++----------
 clang/lib/CIR/CodeGen/CIRGenModule.h   |  3 ++-
 2 files changed, 10 insertions(+), 11 deletions(-)

diff --git a/clang/lib/CIR/CodeGen/CIRGenModule.cpp b/clang/lib/CIR/CodeGen/CIRGenModule.cpp
index c61bbfbf0d4335..95ffab17c56ce3 100644
--- a/clang/lib/CIR/CodeGen/CIRGenModule.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenModule.cpp
@@ -1279,15 +1279,15 @@ void CIRGenModule::replaceGlobal(cir::GlobalOp oldGV, cir::GlobalOp newGV) {
 /// mangled name but some other type.
 cir::GlobalOp
 CIRGenModule::getOrCreateCIRGlobal(StringRef mangledName, mlir::Type ty,
-                                   LangAS langAS, const VarDecl *d,
+                                   LangAS langAS, mlir::Location loc,
+                                   const VarDecl *d,
                                    ForDefinition_t isForDefinition) {
 
   // Lookup the entry, lazily creating it if necessary.
   cir::GlobalOp entry;
   if (mlir::Operation *v = getGlobalValue(mangledName)) {
     if (!isa<cir::GlobalOp>(v))
-      errorNYI(d->getSourceRange(),
-               "getOrCreateCIRGlobal: global with non-GlobalOp type");
+      errorNYI(loc, "getOrCreateCIRGlobal: global with non-GlobalOp type");
     entry = cast<cir::GlobalOp>(v);
   }
 
@@ -1313,8 +1313,7 @@ CIRGenModule::getOrCreateCIRGlobal(StringRef mangledName, mlir::Type ty,
     // recognizing the global as a declaration, for now only check if
     // initializer is present.
     if (isForDefinition && !entry.isDeclaration()) {
-      errorNYI(d->getSourceRange(),
-               "getOrCreateCIRGlobal: global with conflicting type");
+      errorNYI(loc, "getOrCreateCIRGlobal: global with conflicting type");
     }
 
     // Address space check removed because it is unnecessary because CIR records
@@ -1326,8 +1325,6 @@ CIRGenModule::getOrCreateCIRGlobal(StringRef mangledName, mlir::Type ty,
       return entry;
   }
 
-  mlir::Location loc = d ? getLoc(d->getSourceRange()) : theModule->getLoc();
-
   // Calculate constant storage flag before creating the global. This was moved
   // from after the global creation to ensure the constant flag is set correctly
   // at creation time, matching the logic used in emitCXXGlobalVarDeclInit.
@@ -1448,7 +1445,8 @@ mlir::Operation *CIRGenModule::getWeakRefReference(const ValueDecl *vd) {
   } else {
     cir::GlobalOp gv = getOrCreateCIRGlobal(
         aa->getAliasee(), getTypes().convertTypeForMem(vd->getType()),
-        LangAS::Default, /*d=*/nullptr, NotForDefinition);
+        LangAS::Default, getLoc(vd->getSourceRange()), /*d=*/nullptr,
+        NotForDefinition);
     gv.setLinkage(cir::GlobalLinkageKind::ExternalWeakLinkage);
     aliasee = gv;
   }
@@ -1466,8 +1464,8 @@ CIRGenModule::getOrCreateCIRGlobal(const VarDecl *d, mlir::Type ty,
     ty = getTypes().convertTypeForMem(astTy);
 
   StringRef mangledName = getMangledName(d);
-  return getOrCreateCIRGlobal(mangledName, ty, getGlobalVarAddressSpace(d), d,
-                              isForDefinition);
+  return getOrCreateCIRGlobal(mangledName, ty, getGlobalVarAddressSpace(d),
+                              getLoc(d->getSourceRange()), d, isForDefinition);
 }
 
 /// Return the mlir::Value for the address of the given global variable. If
diff --git a/clang/lib/CIR/CodeGen/CIRGenModule.h b/clang/lib/CIR/CodeGen/CIRGenModule.h
index 718b5fc3ade7b0..633b4070c52166 100644
--- a/clang/lib/CIR/CodeGen/CIRGenModule.h
+++ b/clang/lib/CIR/CodeGen/CIRGenModule.h
@@ -294,7 +294,8 @@ class CIRGenModule : public CIRGenTypeCache {
   /// If the specified mangled name is not in the module, create and return an
   /// mlir::GlobalOp value
   cir::GlobalOp getOrCreateCIRGlobal(llvm::StringRef mangledName, mlir::Type ty,
-                                     LangAS langAS, const VarDecl *d,
+                                     LangAS langAS, mlir::Location loc,
+                                     const VarDecl *d,
                                      ForDefinition_t isForDefinition);
 
   cir::GlobalOp getOrCreateCIRGlobal(const VarDecl *d, mlir::Type ty,

>From cca09b58268efc6d05f8ea373b13a1cb3fa71c53 Mon Sep 17 00:00:00 2001
From: erichkeane <ekeane at nvidia.com>
Date: Wed, 4 Nov 2026 07:19:28 -0800
Subject: [PATCH 3/5] Move the CIRGenExpr use on FuncOp to use the
 getRawPointer function

---
 clang/lib/CIR/CodeGen/CIRGenExpr.cpp         | 12 ++++++------
 clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp |  5 +----
 clang/lib/CIR/CodeGen/CIRGenModule.h         | 10 ++++++++++
 clang/lib/CIR/CodeGen/CIRGenPointerAuth.cpp  |  8 ++++++++
 4 files changed, 25 insertions(+), 10 deletions(-)

diff --git a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
index e64cc6e7201118..0c42cfdc24c951 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
@@ -973,11 +973,11 @@ Address CIRGenFunction::emitExtVectorElementLValue(LValue lv,
   return Address(elementValue, vectorElementTy, alignment);
 }
 
-static cir::FuncOp emitFunctionDeclPointer(CIRGenModule &cgm, GlobalDecl gd) {
+cir::FuncOp CIRGenModule::getRawFunctionPointer(GlobalDecl gd) {
   const auto *fd = cast<FunctionDecl>(gd.getDecl());
   if (fd->hasAttr<WeakRefAttr>())
-    return cast<cir::FuncOp>(cgm.getWeakRefReference(fd));
-  return cgm.getAddrOfFunction(gd);
+    return cast<cir::FuncOp>(getWeakRefReference(fd));
+  return getAddrOfFunction(gd);
 }
 
 static LValue emitCapturedFieldLValue(CIRGenFunction &cgf, const FieldDecl *fd,
@@ -1039,7 +1039,7 @@ LValue CIRGenFunction::emitLValueForLambdaField(const FieldDecl *field) {
 static LValue emitFunctionDeclLValue(CIRGenFunction &cgf, const Expr *e,
                                      GlobalDecl gd) {
   const FunctionDecl *fd = cast<FunctionDecl>(gd.getDecl());
-  cir::FuncOp funcOp = emitFunctionDeclPointer(cgf.cgm, gd);
+  cir::FuncOp funcOp = cgf.cgm.getFunctionPointer(gd);
   mlir::Location loc = cgf.getLoc(e->getSourceRange());
   CharUnits align = cgf.getContext().getDeclAlign(fd);
 
@@ -2440,7 +2440,7 @@ CIRGenCallee CIRGenFunction::emitDirectCallee(const GlobalDecl &gd) {
       if (!clone) {
         // Create a forward declaration - the body will be generated in
         // generateCode when the function definition is processed
-        cir::FuncOp calleeFunc = emitFunctionDeclPointer(cgm, gd);
+        cir::FuncOp calleeFunc = cgm.getRawFunctionPointer(gd);
         mlir::OpBuilder::InsertionGuard guard(builder);
         builder.setInsertionPointToStart(cgm.getModule().getBody());
 
@@ -2465,7 +2465,7 @@ CIRGenCallee CIRGenFunction::emitDirectCallee(const GlobalDecl &gd) {
       return CIRGenCallee::forBuiltin(builtinID, fd);
   }
 
-  cir::FuncOp callee = emitFunctionDeclPointer(cgm, gd);
+  cir::FuncOp callee = cgm.getRawFunctionPointer(gd);
 
   if ((cgm.getLangOpts().CUDA || cgm.getLangOpts().HIP) &&
       !cgm.getLangOpts().CUDAIsDevice && fd->hasAttr<CUDAGlobalAttr>()) {
diff --git a/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp b/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp
index 89d80b647a81ae..cde4d666622689 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp
@@ -947,10 +947,7 @@ ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) {
     d = cast<ValueDecl>(d->getMostRecentDecl());
 
     if (auto *fd = dyn_cast<FunctionDecl>(d)) {
-      cir::FuncOp fop =
-          fd->hasAttr<WeakRefAttr>()
-              ? mlir::cast<cir::FuncOp>(cgm.getWeakRefReference(fd))
-              : cgm.getAddrOfFunction(fd);
+      cir::FuncOp fop = cgm.getRawFunctionPointer(GlobalDecl{fd});
       CIRGenBuilderTy &builder = cgm.getBuilder();
       mlir::MLIRContext *mlirContext = builder.getContext();
       // Use the destination pointer type (e.g. struct field type), not
diff --git a/clang/lib/CIR/CodeGen/CIRGenModule.h b/clang/lib/CIR/CodeGen/CIRGenModule.h
index 633b4070c52166..cbc120adbac573 100644
--- a/clang/lib/CIR/CodeGen/CIRGenModule.h
+++ b/clang/lib/CIR/CodeGen/CIRGenModule.h
@@ -655,6 +655,16 @@ class CIRGenModule : public CIRGenTypeCache {
   getAddrOfGlobal(clang::GlobalDecl gd,
                   ForDefinition_t isForDefinition = NotForDefinition);
 
+  /// Return a function pointer for a reference to the given function.
+  /// This correctly handles weak references, but does not apply a
+  /// pointer signature.
+  cir::FuncOp getRawFunctionPointer(GlobalDecl GD);
+
+  /// Return the ABI-correct function pointer value for a reference
+  /// to the given function.  This will apply a pointer signature if
+  /// necessary, caching the result for the given function.
+  cir::FuncOp getFunctionPointer(GlobalDecl GD);
+
   // Return whether RTTI information should be emitted for this target.
   bool shouldEmitRTTI(bool forEH = false) {
     return (forEH || getLangOpts().RTTI) && !getLangOpts().CUDAIsDevice &&
diff --git a/clang/lib/CIR/CodeGen/CIRGenPointerAuth.cpp b/clang/lib/CIR/CodeGen/CIRGenPointerAuth.cpp
index 20b0646fdab444..c3f5dc027c835c 100644
--- a/clang/lib/CIR/CodeGen/CIRGenPointerAuth.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenPointerAuth.cpp
@@ -21,3 +21,11 @@ Address CIRGenFunction::getAsNaturalAddressOf(Address addr,
   assert(!cir::MissingFeatures::pointerAuthentication());
   return addr;
 }
+cir::FuncOp CIRGenModule::getFunctionPointer(GlobalDecl gd) {
+  // This should eventually get the function pointer with authentication
+  // information added.  Since this is not yet implemented, this just gets the
+  // 'base' pointer right now.
+  assert(!cir::MissingFeatures::pointerAuthentication());
+
+  return getRawFunctionPointer(gd);
+}

>From 9a50374aae7ff7704c16261be937663e191871a6 Mon Sep 17 00:00:00 2001
From: erichkeane <ekeane at nvidia.com>
Date: Wed, 4 Nov 2026 07:19:42 -0800
Subject: [PATCH 4/5] Clang-format

---
 clang/lib/CIR/CodeGen/CIRGenModule.cpp | 8 +++-----
 1 file changed, 3 insertions(+), 5 deletions(-)

diff --git a/clang/lib/CIR/CodeGen/CIRGenModule.cpp b/clang/lib/CIR/CodeGen/CIRGenModule.cpp
index 95ffab17c56ce3..22e20ff74bfa60 100644
--- a/clang/lib/CIR/CodeGen/CIRGenModule.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenModule.cpp
@@ -1277,11 +1277,9 @@ void CIRGenModule::replaceGlobal(cir::GlobalOp oldGV, cir::GlobalOp newGV) {
 /// 3. If \p isForDefinition is true, it is guaranteed that an actual global
 /// with type \p ty will be returned, not conversion of a variable with the same
 /// mangled name but some other type.
-cir::GlobalOp
-CIRGenModule::getOrCreateCIRGlobal(StringRef mangledName, mlir::Type ty,
-                                   LangAS langAS, mlir::Location loc,
-                                   const VarDecl *d,
-                                   ForDefinition_t isForDefinition) {
+cir::GlobalOp CIRGenModule::getOrCreateCIRGlobal(
+    StringRef mangledName, mlir::Type ty, LangAS langAS, mlir::Location loc,
+    const VarDecl *d, ForDefinition_t isForDefinition) {
 
   // Lookup the entry, lazily creating it if necessary.
   cir::GlobalOp entry;

>From e01802f2f76ad3f19d032b0fd6ad7bdac02945a2 Mon Sep 17 00:00:00 2001
From: erichkeane <ekeane at nvidia.com>
Date: Wed, 4 Nov 2026 12:59:50 -0800
Subject: [PATCH 5/5] fixup based on Bruno's comment

---
 clang/lib/CIR/CodeGen/CIRGenCall.h            |  2 ++
 clang/lib/CIR/CodeGen/CIRGenExpr.cpp          | 15 ++++++--
 clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp  | 11 ++++--
 clang/lib/CIR/CodeGen/CIRGenModule.cpp        | 36 ++++++++++++++++---
 .../CIR/CodeGen/attr-weakref-type-mismatch.c  | 30 ++++++++++++++++
 5 files changed, 83 insertions(+), 11 deletions(-)
 create mode 100644 clang/test/CIR/CodeGen/attr-weakref-type-mismatch.c

diff --git a/clang/lib/CIR/CodeGen/CIRGenCall.h b/clang/lib/CIR/CodeGen/CIRGenCall.h
index b30b4969ca45eb..82578524523ad1 100644
--- a/clang/lib/CIR/CodeGen/CIRGenCall.h
+++ b/clang/lib/CIR/CodeGen/CIRGenCall.h
@@ -94,6 +94,8 @@ class CIRGenCallee {
     return CIRGenCallee(abstractInfo, funcPtr);
   }
 
+  bool isInvalid() const { return kindOrFunctionPtr == SpecialKind::Invalid; }
+
   bool isBuiltin() const { return kindOrFunctionPtr == SpecialKind::Builtin; }
 
   const clang::FunctionDecl *getBuiltinDecl() const {
diff --git a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
index 0c42cfdc24c951..0720508203563d 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
@@ -976,7 +976,7 @@ Address CIRGenFunction::emitExtVectorElementLValue(LValue lv,
 cir::FuncOp CIRGenModule::getRawFunctionPointer(GlobalDecl gd) {
   const auto *fd = cast<FunctionDecl>(gd.getDecl());
   if (fd->hasAttr<WeakRefAttr>())
-    return cast<cir::FuncOp>(getWeakRefReference(fd));
+    return cast_or_null<cir::FuncOp>(getWeakRefReference(fd));
   return getAddrOfFunction(gd);
 }
 
@@ -1197,10 +1197,13 @@ LValue CIRGenFunction::emitDeclRefLValue(const DeclRefExpr *e) {
          "Should not use decl without marking it used!");
 
   // A weakref variable refers to its alias target. Weakref functions are
-  // handled by emitFunctionDeclPointer.
+  // handled by getRawFunctionPointer.
   if (const auto *vd = dyn_cast<VarDecl>(nd);
       vd && vd->hasAttr<WeakRefAttr>()) {
-    auto aliasee = mlir::cast<cir::GlobalOp>(cgm.getWeakRefReference(vd));
+    auto aliasee =
+        mlir::cast_or_null<cir::GlobalOp>(cgm.getWeakRefReference(vd));
+    if (!aliasee)
+      return LValue();
     mlir::Value v =
         builder.createGetGlobal(getLoc(e->getSourceRange()), aliasee);
     Address addr(v, convertTypeForMem(vd->getType()),
@@ -2466,6 +2469,8 @@ CIRGenCallee CIRGenFunction::emitDirectCallee(const GlobalDecl &gd) {
   }
 
   cir::FuncOp callee = cgm.getRawFunctionPointer(gd);
+  if (!callee)
+    return CIRGenCallee();
 
   if ((cgm.getLangOpts().CUDA || cgm.getLangOpts().HIP) &&
       !cgm.getLangOpts().CUDAIsDevice && fd->hasAttr<CUDAGlobalAttr>()) {
@@ -2698,6 +2703,10 @@ RValue CIRGenFunction::emitCallExpr(const clang::CallExpr *e,
 
   CIRGenCallee callee = emitCallee(e->getCallee());
 
+  // emitCallee has already diagnosed (errorNYI) why there is no callee.
+  if (callee.isInvalid())
+    return getUndefRValue(e->getType());
+
   if (callee.isBuiltin())
     return emitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(), e,
                            returnValue);
diff --git a/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp b/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp
index cde4d666622689..9dc948dc7e7808 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp
@@ -948,6 +948,8 @@ ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) {
 
     if (auto *fd = dyn_cast<FunctionDecl>(d)) {
       cir::FuncOp fop = cgm.getRawFunctionPointer(GlobalDecl{fd});
+      if (!fop)
+        return {};
       CIRGenBuilderTy &builder = cgm.getBuilder();
       mlir::MLIRContext *mlirContext = builder.getContext();
       // Use the destination pointer type (e.g. struct field type), not
@@ -973,9 +975,12 @@ ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) {
     }
 
     // A weakref refers to its alias target. Handle non-function versions here.
-    if (d->hasAttr<WeakRefAttr>())
-      return cgm.getBuilder().getGlobalViewAttr(
-          cast<cir::GlobalOp>(cgm.getWeakRefReference(d)));
+    if (d->hasAttr<WeakRefAttr>()) {
+      auto aliasee = cast_or_null<cir::GlobalOp>(cgm.getWeakRefReference(d));
+      if (!aliasee)
+        return {};
+      return cgm.getBuilder().getGlobalViewAttr(aliasee);
+    }
 
     if (auto *vd = dyn_cast<VarDecl>(d)) {
       // We can never refer to a variable with local storage.
diff --git a/clang/lib/CIR/CodeGen/CIRGenModule.cpp b/clang/lib/CIR/CodeGen/CIRGenModule.cpp
index 22e20ff74bfa60..6383228fb98e87 100644
--- a/clang/lib/CIR/CodeGen/CIRGenModule.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenModule.cpp
@@ -1284,8 +1284,10 @@ cir::GlobalOp CIRGenModule::getOrCreateCIRGlobal(
   // Lookup the entry, lazily creating it if necessary.
   cir::GlobalOp entry;
   if (mlir::Operation *v = getGlobalValue(mangledName)) {
-    if (!isa<cir::GlobalOp>(v))
+    if (!isa<cir::GlobalOp>(v)) {
       errorNYI(loc, "getOrCreateCIRGlobal: global with non-GlobalOp type");
+      return nullptr;
+    }
     entry = cast<cir::GlobalOp>(v);
   }
 
@@ -1430,8 +1432,24 @@ mlir::Operation *CIRGenModule::getWeakRefReference(const ValueDecl *vd) {
   assert(aa && "No alias?");
 
   // See if there is already something with the target's name in the module.
-  if (mlir::Operation *entry = getGlobalValue(aa->getAliasee()))
-    return entry;
+  if (mlir::Operation *entry = getGlobalValue(aa->getAliasee())) {
+    // Classic codegen is able to just treat whatever value it gets as the
+    // 'right' type.  This needs to introduce SOME sort of conversion it seems.
+    // For now, reject any cases that don't match.
+    if (const auto *fd = dyn_cast<FunctionDecl>(vd)) {
+      auto fn = dyn_cast<cir::FuncOp>(entry);
+
+      if (fn && fn.getFunctionType() == convertType(fd->getType()))
+        return fn;
+    } else if (auto gv = dyn_cast<cir::GlobalOp>(entry)) {
+      if (gv.getSymType() == getTypes().convertTypeForMem(vd->getType()))
+        return gv;
+    }
+
+    errorNYI(vd->getSourceRange(),
+             "weakref target already declared with a different type");
+    return nullptr;
+  }
 
   mlir::Operation *aliasee;
   if (const auto *fd = dyn_cast<FunctionDecl>(vd)) {
@@ -3016,8 +3034,16 @@ void CIRGenModule::emitTentativeDefinition(const VarDecl *d) {
   // If we already have a definition, not declaration, with the same mangled
   // name, emitting of declaration is not required (and would actually overwrite
   // the emitted definition).
-  if (gv && !mlir::cast<cir::GlobalOp>(gv).isDeclaration())
-    return;
+  if (gv) {
+    auto gvOp = dyn_cast<cir::GlobalOp>(gv);
+    if (!gvOp) {
+      errorNYI(d->getSourceRange(),
+               "emitTentativeDefinition: name already used by a non-global");
+      return;
+    }
+    if (!gvOp.isDeclaration())
+      return;
+  }
 
   // If we have not seen a reference to this variable yet, place it into the
   // deferred declarations table to be emitted if needed later.
diff --git a/clang/test/CIR/CodeGen/attr-weakref-type-mismatch.c b/clang/test/CIR/CodeGen/attr-weakref-type-mismatch.c
new file mode 100644
index 00000000000000..a08a9162b20e9b
--- /dev/null
+++ b/clang/test/CIR/CodeGen/attr-weakref-type-mismatch.c
@@ -0,0 +1,30 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fclangir -emit-cir -verify -DVAR %s -o %t.cir
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fclangir -emit-cir -verify -DFN %s -o %t.cir
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fclangir -emit-cir -verify -DTENTATIVE %s -o %t.cir
+
+// A weakref whose target name was already declared with a different type (or
+// kind) can't be reused as-is, since CIR symbols are typed.
+
+#ifdef VAR
+extern long tgt_var;
+long use_var(void) { return tgt_var; }
+// expected-error at +1 {{ClangIR code gen Not Yet Implemented: weakref target already declared with a different type}}
+static int r_var __attribute__((weakref("tgt_var")));
+int *get_r_var(void) { return &r_var; }
+#endif
+
+#ifdef FN
+int tgt_fn(void);
+int use_fn(void) { return tgt_fn(); }
+// expected-error at +1 {{ClangIR code gen Not Yet Implemented: weakref target already declared with a different type}}
+static void r_fn(void) __attribute__((weakref("tgt_fn")));
+void call_r_fn(void) { r_fn(); }
+#endif
+
+// A function weakref whose target is later defined as a variable.
+#ifdef TENTATIVE
+static void r_fn2(void) __attribute__((weakref("gv")));
+// expected-error at +1 {{ClangIR code gen Not Yet Implemented: emitTentativeDefinition: name already used by a non-global}}
+int gv;
+void call_r_fn2(void) { r_fn2(); }
+#endif



More information about the cfe-commits mailing list