[clang] [AST] Avoid casting tagged DeclGroup pointer to Decl* in DeclGroupRef (PR #238331)

Romaric Jodin via cfe-commits cfe-commits at lists.llvm.org
Tue Dec 1 00:31:25 PST 2026


https://github.com/rjodinchr updated https://github.com/llvm/llvm-project/pull/238331

>From e84ead27e59e38649f1ea8c1cfd13b42dc7764a6 Mon Sep 17 00:00:00 2001
From: Romaric Jodin <rjodin at google.com>
Date: Tue, 3 Nov 2026 11:51:54 +0100
Subject: [PATCH 1/2] [AST] Avoid casting tagged DeclGroup pointer to Decl* in
 DeclGroupRef

DeclGroupRef::getFromOpaquePtr(void *Ptr) previously converted the
opaque pointer directly via static_cast<Decl *>(Ptr) before storing it
in D, even when the low tag bit of Ptr is DeclGroupKind (0x1) and Ptr
actually points to a tagged DeclGroup allocation rather than a Decl.

Because Decl is a polymorphic class, building with Control Flow
Integrity (-fsanitize=cfi-derived-cast / -fsanitize=cfi-unrelated-cast)
instruments static_cast<Decl *>(Ptr) to verify the vtable pointer at
*Ptr. When Ptr is a tagged DeclGroup * (whose alignment is 8 bytes and
whose low bit is 1), dereferencing the unaligned tagged address as a
Decl * fails the CFI vtable check at runtime.

Inspect the tag bit in getFromOpaquePtr(void *Ptr) first and construct
the DeclGroupRef via DeclGroupRef(reinterpret_cast<DeclGroup *>(...))
when the kind is DeclGroupKind, only casting to Decl * when the pointer
actually represents a single Decl. Add a unit test in DeclTest covering
DeclGroupRef::getFromOpaquePtr round-trips for both single-decl and
multi-decl groups.
---
 clang/include/clang/AST/DeclGroup.h |  7 ++++---
 clang/unittests/AST/DeclTest.cpp    | 27 +++++++++++++++++++++++++++
 2 files changed, 31 insertions(+), 3 deletions(-)

diff --git a/clang/include/clang/AST/DeclGroup.h b/clang/include/clang/AST/DeclGroup.h
index 6637599f0cd0c8..f6ba6aeedc8310 100644
--- a/clang/include/clang/AST/DeclGroup.h
+++ b/clang/include/clang/AST/DeclGroup.h
@@ -120,9 +120,10 @@ class DeclGroupRef {
 
   void *getAsOpaquePtr() const { return D; }
   static DeclGroupRef getFromOpaquePtr(void *Ptr) {
-    DeclGroupRef X;
-    X.D = static_cast<Decl*>(Ptr);
-    return X;
+    if ((reinterpret_cast<uintptr_t>(Ptr) & Mask) == SingleDeclKind)
+      return DeclGroupRef(static_cast<Decl *>(Ptr));
+    return DeclGroupRef(reinterpret_cast<DeclGroup *>(
+        reinterpret_cast<uintptr_t>(Ptr) & ~Mask));
   }
 };
 
diff --git a/clang/unittests/AST/DeclTest.cpp b/clang/unittests/AST/DeclTest.cpp
index 195b8ab4c4e661..ad3cdeb91a1d14 100644
--- a/clang/unittests/AST/DeclTest.cpp
+++ b/clang/unittests/AST/DeclTest.cpp
@@ -1029,3 +1029,30 @@ TEST(Decl, ObjCPropertyDeclNameForDiagnostic) {
                              /*Qualified=*/true);
   EXPECT_EQ(ExtPQualifiedOS.str(), "-[MyClass extensionProp]");
 }
+
+TEST(Decl, DeclGroupRefOpaquePtrRoundTrip) {
+  auto AST = tooling::buildASTFromCode("int a, b;");
+  ASTContext &Ctx = AST->getASTContext();
+
+  auto *A = const_cast<VarDecl *>(
+      selectFirst<VarDecl>("a", match(varDecl(hasName("a")).bind("a"), Ctx)));
+  auto *B = const_cast<VarDecl *>(
+      selectFirst<VarDecl>("b", match(varDecl(hasName("b")).bind("b"), Ctx)));
+  ASSERT_NE(A, nullptr);
+  ASSERT_NE(B, nullptr);
+
+  DeclGroupRef Single(A);
+  DeclGroupRef SingleRoundTrip =
+      DeclGroupRef::getFromOpaquePtr(Single.getAsOpaquePtr());
+  EXPECT_TRUE(SingleRoundTrip.isSingleDecl());
+  EXPECT_EQ(SingleRoundTrip.getSingleDecl(), A);
+
+  Decl *Decls[] = {A, B};
+  DeclGroupRef Group = DeclGroupRef::Create(Ctx, Decls, 2);
+  DeclGroupRef GroupRoundTrip =
+      DeclGroupRef::getFromOpaquePtr(Group.getAsOpaquePtr());
+  ASSERT_TRUE(GroupRoundTrip.isDeclGroup());
+  ASSERT_EQ(std::distance(GroupRoundTrip.begin(), GroupRoundTrip.end()), 2);
+  EXPECT_EQ(GroupRoundTrip.begin()[0], A);
+  EXPECT_EQ(GroupRoundTrip.begin()[1], B);
+}

>From 42fcd6a97cc2ec68ad138ee5776274719eb0557c Mon Sep 17 00:00:00 2001
From: Romaric Jodin <rjodin at google.com>
Date: Tue, 1 Dec 2026 09:28:14 +0100
Subject: [PATCH 2/2] [AST] Use llvm::PointerUnion<Decl *, DeclGroup *> in
 DeclGroupRef

Replace the manual low-bit tagging on a Decl * member in DeclGroupRef
with llvm::PointerUnion<Decl *, DeclGroup *>, using getAddrOfPtr1() for
single-decl iteration and getFromOpaqueValue() / getOpaqueValue() for
opaque pointer conversions.

This avoids ever representing a tagged DeclGroup * as a Decl * (rather
than only avoiding the CK_BitCast CFI check in getFromOpaquePtr while
still converting from uintptr_t in DeclGroupRef(DeclGroup *)). Also
update the DeclGroupRef natvis visualizer and extend the unit test to
cover empty and single-decl iteration.
---
 clang/include/clang/AST/DeclGroup.h       | 56 ++++++++++-------------
 clang/unittests/AST/DeclTest.cpp          | 15 ++++++
 clang/utils/ClangVisualizers/clang.natvis |  6 +--
 3 files changed, 42 insertions(+), 35 deletions(-)

diff --git a/clang/include/clang/AST/DeclGroup.h b/clang/include/clang/AST/DeclGroup.h
index f6ba6aeedc8310..9e27c791482f49 100644
--- a/clang/include/clang/AST/DeclGroup.h
+++ b/clang/include/clang/AST/DeclGroup.h
@@ -13,14 +13,15 @@
 #ifndef LLVM_CLANG_AST_DECLGROUP_H
 #define LLVM_CLANG_AST_DECLGROUP_H
 
+#include "clang/AST/DeclBase.h"
+#include "llvm/ADT/PointerUnion.h"
+#include "llvm/Support/Casting.h"
 #include "llvm/Support/TrailingObjects.h"
 #include <cassert>
-#include <cstdint>
 
 namespace clang {
 
 class ASTContext;
-class Decl;
 
 class DeclGroup final : private llvm::TrailingObjects<DeclGroup, Decl *> {
   // FIXME: Include a TypeSpecifier object.
@@ -45,21 +46,13 @@ class DeclGroup final : private llvm::TrailingObjects<DeclGroup, Decl *> {
 };
 
 class DeclGroupRef {
-  // Note this is not a PointerIntPair because we need the address of the
-  // non-group case to be valid as a Decl** for iteration.
-  enum Kind { SingleDeclKind=0x0, DeclGroupKind=0x1, Mask=0x1 };
-
-  Decl* D = nullptr;
-
-  Kind getKind() const {
-    return (Kind) (reinterpret_cast<uintptr_t>(D) & Mask);
-  }
+  using UnionTy = llvm::PointerUnion<Decl *, DeclGroup *>;
+  UnionTy D;
 
 public:
   DeclGroupRef() = default;
-  explicit DeclGroupRef(Decl* d) : D(d) {}
-  explicit DeclGroupRef(DeclGroup* dg)
-    : D((Decl*) (reinterpret_cast<uintptr_t>(dg) | DeclGroupKind)) {}
+  explicit DeclGroupRef(Decl *d) : D(d) {}
+  explicit DeclGroupRef(DeclGroup *dg) : D(dg) {}
 
   static DeclGroupRef Create(ASTContext &C, Decl **Decls, unsigned NumDecls) {
     if (NumDecls == 0)
@@ -72,58 +65,57 @@ class DeclGroupRef {
   using iterator = Decl **;
   using const_iterator = Decl * const *;
 
-  bool isNull() const { return D == nullptr; }
-  bool isSingleDecl() const { return getKind() == SingleDeclKind; }
-  bool isDeclGroup() const { return getKind() == DeclGroupKind; }
+  bool isNull() const { return D.isNull(); }
+  bool isSingleDecl() const { return isa<Decl *>(D); }
+  bool isDeclGroup() const { return isa<DeclGroup *>(D); }
 
   Decl *getSingleDecl() {
     assert(isSingleDecl() && "Isn't a single decl");
-    return D;
+    return cast<Decl *>(D);
   }
   const Decl *getSingleDecl() const {
-    return const_cast<DeclGroupRef*>(this)->getSingleDecl();
+    return const_cast<DeclGroupRef *>(this)->getSingleDecl();
   }
 
   DeclGroup &getDeclGroup() {
     assert(isDeclGroup() && "Isn't a declgroup");
-    return *((DeclGroup*)(reinterpret_cast<uintptr_t>(D) & ~Mask));
+    return *cast<DeclGroup *>(D);
   }
   const DeclGroup &getDeclGroup() const {
-    return const_cast<DeclGroupRef*>(this)->getDeclGroup();
+    return const_cast<DeclGroupRef *>(this)->getDeclGroup();
   }
 
   iterator begin() {
     if (isSingleDecl())
-      return D ? &D : nullptr;
+      return D ? D.getAddrOfPtr1() : nullptr;
     return &getDeclGroup()[0];
   }
 
   iterator end() {
     if (isSingleDecl())
-      return D ? &D+1 : nullptr;
+      return D ? D.getAddrOfPtr1() + 1 : nullptr;
     DeclGroup &G = getDeclGroup();
     return &G[0] + G.size();
   }
 
   const_iterator begin() const {
     if (isSingleDecl())
-      return D ? &D : nullptr;
+      return D ? D.getAddrOfPtr1() : nullptr;
     return &getDeclGroup()[0];
   }
 
   const_iterator end() const {
     if (isSingleDecl())
-      return D ? &D+1 : nullptr;
+      return D ? D.getAddrOfPtr1() + 1 : nullptr;
     const DeclGroup &G = getDeclGroup();
     return &G[0] + G.size();
   }
 
-  void *getAsOpaquePtr() const { return D; }
+  void *getAsOpaquePtr() const { return D.getOpaqueValue(); }
   static DeclGroupRef getFromOpaquePtr(void *Ptr) {
-    if ((reinterpret_cast<uintptr_t>(Ptr) & Mask) == SingleDeclKind)
-      return DeclGroupRef(static_cast<Decl *>(Ptr));
-    return DeclGroupRef(reinterpret_cast<DeclGroup *>(
-        reinterpret_cast<uintptr_t>(Ptr) & ~Mask));
+    DeclGroupRef X;
+    X.D = UnionTy::getFromOpaqueValue(Ptr);
+    return X;
   }
 };
 
@@ -144,7 +136,9 @@ namespace llvm {
       return clang::DeclGroupRef::getFromOpaquePtr(P);
     }
 
-    static constexpr int NumLowBitsAvailable = 0;
+    static constexpr int NumLowBitsAvailable =
+        PointerLikeTypeTraits<llvm::PointerUnion<
+            clang::Decl *, clang::DeclGroup *>>::NumLowBitsAvailable;
   };
 
 } // namespace llvm
diff --git a/clang/unittests/AST/DeclTest.cpp b/clang/unittests/AST/DeclTest.cpp
index ad3cdeb91a1d14..a19a4bc67bd9f5 100644
--- a/clang/unittests/AST/DeclTest.cpp
+++ b/clang/unittests/AST/DeclTest.cpp
@@ -1041,16 +1041,31 @@ TEST(Decl, DeclGroupRefOpaquePtrRoundTrip) {
   ASSERT_NE(A, nullptr);
   ASSERT_NE(B, nullptr);
 
+  DeclGroupRef Empty;
+  DeclGroupRef EmptyRoundTrip =
+      DeclGroupRef::getFromOpaquePtr(Empty.getAsOpaquePtr());
+  EXPECT_TRUE(EmptyRoundTrip.isNull());
+  EXPECT_TRUE(EmptyRoundTrip.isSingleDecl());
+  EXPECT_EQ(EmptyRoundTrip.begin(), nullptr);
+  EXPECT_EQ(EmptyRoundTrip.end(), nullptr);
+
   DeclGroupRef Single(A);
   DeclGroupRef SingleRoundTrip =
       DeclGroupRef::getFromOpaquePtr(Single.getAsOpaquePtr());
+  EXPECT_FALSE(SingleRoundTrip.isNull());
   EXPECT_TRUE(SingleRoundTrip.isSingleDecl());
   EXPECT_EQ(SingleRoundTrip.getSingleDecl(), A);
+  ASSERT_EQ(std::distance(SingleRoundTrip.begin(), SingleRoundTrip.end()), 1);
+  EXPECT_EQ(*SingleRoundTrip.begin(), A);
+  const DeclGroupRef &ConstSingle = SingleRoundTrip;
+  ASSERT_EQ(std::distance(ConstSingle.begin(), ConstSingle.end()), 1);
+  EXPECT_EQ(*ConstSingle.begin(), A);
 
   Decl *Decls[] = {A, B};
   DeclGroupRef Group = DeclGroupRef::Create(Ctx, Decls, 2);
   DeclGroupRef GroupRoundTrip =
       DeclGroupRef::getFromOpaquePtr(Group.getAsOpaquePtr());
+  EXPECT_FALSE(GroupRoundTrip.isNull());
   ASSERT_TRUE(GroupRoundTrip.isDeclGroup());
   ASSERT_EQ(std::distance(GroupRoundTrip.begin(), GroupRoundTrip.end()), 2);
   EXPECT_EQ(GroupRoundTrip.begin()[0], A);
diff --git a/clang/utils/ClangVisualizers/clang.natvis b/clang/utils/ClangVisualizers/clang.natvis
index 828557b7279b94..a7053400d24f4d 100644
--- a/clang/utils/ClangVisualizers/clang.natvis
+++ b/clang/utils/ClangVisualizers/clang.natvis
@@ -1037,11 +1037,9 @@ For later versions of Visual Studio, no setup is required-->
     </Expand>
   </Type>
   <Type Name="clang::DeclGroupRef">
-    <DisplayString Condition="(Kind)((uintptr_t)D&1)==SingleDeclKind">{*D}</DisplayString>
-    <DisplayString>{*(DeclGroup *)((uintptr_t)D&~1)}</DisplayString>
+    <DisplayString>{D}</DisplayString>
     <Expand>
-      <ExpandedItem Condition="(Kind)((uintptr_t)D&1)==SingleDeclKind">D</ExpandedItem>
-      <ExpandedItem Condition="(Kind)((uintptr_t)D&1)==DeclGroupKind">(DeclGroup *)((uintptr_t)D&~1)</ExpandedItem>
+      <ExpandedItem>D</ExpandedItem>
     </Expand>
   </Type>
   <Type Name="clang::Declarator">



More information about the cfe-commits mailing list