[clang] [clang][bytecode] Handle multiple base paths in dynamic_cast (PR #213592)

via cfe-commits cfe-commits at lists.llvm.org
Sun Aug 2 21:57:14 PDT 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)

<details>
<summary>Changes</summary>

This can happen via virtual bases.

Fixes https://github.com/llvm/llvm-project/issues/213569

---
Full diff: https://github.com/llvm/llvm-project/pull/213592.diff


2 Files Affected:

- (modified) clang/lib/AST/ByteCode/Interp.cpp (+6-2) 
- (modified) clang/test/AST/ByteCode/dynamic-cast.cpp (+14) 


``````````diff
diff --git a/clang/lib/AST/ByteCode/Interp.cpp b/clang/lib/AST/ByteCode/Interp.cpp
index 475d206356de8..2da4e4e764971 100644
--- a/clang/lib/AST/ByteCode/Interp.cpp
+++ b/clang/lib/AST/ByteCode/Interp.cpp
@@ -2166,9 +2166,13 @@ bool DynamicCast(InterpState &S, CodePtr OpPC, const Type *DestTypePtr,
 
     CXXBasePaths Paths;
     getRecord(P.getBase())->isDerivedFrom(getRecord(P), Paths);
-    assert(std::distance(Paths.begin(), Paths.end()) == 1);
 
-    return Paths.front().Access == AS_private;
+    // Through virtual bases, they might be more than one "direct" base. They
+    // can have different access specifiers. They must all be private for the
+    // base to be private.
+    return llvm::all_of(Paths, [](const CXXBasePath &P) -> bool {
+      return P.Access == AS_private;
+    });
   };
 
   enum {
diff --git a/clang/test/AST/ByteCode/dynamic-cast.cpp b/clang/test/AST/ByteCode/dynamic-cast.cpp
index a81bab400a50a..83a745e271a28 100644
--- a/clang/test/AST/ByteCode/dynamic-cast.cpp
+++ b/clang/test/AST/ByteCode/dynamic-cast.cpp
@@ -338,3 +338,17 @@ namespace UnrelatedInitializingPtr {
   constexpr auto p = dynamic_cast<C &>(a); // both-error {{must be initialized by a constant expression}} \
                                            // both-note {{reference dynamic_cast failed: dynamic type 'UnrelatedInitializingPtr::D' of operand does not have a base class of type 'C'}}
 }
+
+namespace VirtualBase {
+  struct A { virtual constexpr ~A() = default; };
+  struct B : public virtual A {};
+  struct C : private virtual A {};
+  struct D : B, C {};
+
+  constexpr bool test() {
+    D d;
+    A *a = static_cast<B *>(&d);
+    return dynamic_cast<C *>(a) == static_cast<C *>(&d);
+  }
+  static_assert(test());
+}

``````````

</details>


https://github.com/llvm/llvm-project/pull/213592


More information about the cfe-commits mailing list