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

Erich Keane via cfe-commits cfe-commits at lists.llvm.org
Tue Nov 3 13:46:20 PST 2026


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

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.

>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] [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



More information about the cfe-commits mailing list