[clang] [clang][bytecode] Fix an assertion failure in dynamic_cast handling (PR #206447)
Timm Baeder via cfe-commits
cfe-commits at lists.llvm.org
Mon Jun 29 03:17:40 PDT 2026
https://github.com/tbaederr created https://github.com/llvm/llvm-project/pull/206447
If `Ptr` is already a root pointer, the `getBase()` call ran into an assertion. Fix this by moving the check to the start of the loop.
>From 0fff7845065fa45a725fbaf5eaa069b4e1be5a06 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= <tbaeder at redhat.com>
Date: Mon, 29 Jun 2026 12:15:11 +0200
Subject: [PATCH] [clang][bytecode] Fix an assertion failure in dynamic_cast
handling
If `Ptr` is already a root pointer, the `getBase()` call ran into an
assertion. Fix this by moving the check to the start of the loop.
---
clang/lib/AST/ByteCode/Interp.cpp | 5 +++--
clang/test/AST/ByteCode/dynamic-cast.cpp | 14 ++++++++++++++
2 files changed, 17 insertions(+), 2 deletions(-)
diff --git a/clang/lib/AST/ByteCode/Interp.cpp b/clang/lib/AST/ByteCode/Interp.cpp
index 2f09c19178f09..80cea48f88c45 100644
--- a/clang/lib/AST/ByteCode/Interp.cpp
+++ b/clang/lib/AST/ByteCode/Interp.cpp
@@ -2139,14 +2139,15 @@ bool DynamicCast(InterpState &S, CodePtr OpPC, const Type *DestTypePtr,
std::optional<PtrView> Result;
// First, check simple downcasts without ambiguities.
for (PtrView Iter = Ptr.view();;) {
+ if (Iter.isRoot() || !Iter.isBaseClass())
+ break;
+
if (typesMatch(TargetType, Iter.getType())) {
Result = Iter;
break;
}
// Moving DOWN the type hierarchy.
Iter = Iter.getBase();
- if (Iter.isRoot() || !Iter.isBaseClass())
- break;
}
// Simply walking down the type hierarchy has produced a valid result, use
diff --git a/clang/test/AST/ByteCode/dynamic-cast.cpp b/clang/test/AST/ByteCode/dynamic-cast.cpp
index a40b455cecabf..bfde7a2a4c0c2 100644
--- a/clang/test/AST/ByteCode/dynamic-cast.cpp
+++ b/clang/test/AST/ByteCode/dynamic-cast.cpp
@@ -295,6 +295,20 @@ namespace UnrelatedAndRootPtr{
static_assert(f());
}
+namespace UnrelatedAndRootReference {
+ struct A {
+ virtual void foo();
+ };
+ struct B1 : A {};
+
+ struct B2 : A {};
+ struct C : B2 {};
+
+ constexpr C c;
+ static_assert(&dynamic_cast<B2 &>((B1 &)c), ""); // both-error {{not an integral constant expression}} \
+ // both-note {{cast that performs the conversions of a reinterpret_cast is not allowed in a constant expression}}
+}
+
namespace Invalid {
struct S { virtual void s(); };
struct A : S {};
More information about the cfe-commits
mailing list