Skip to content

[clang][bytecode] Remove base casts before doing memcpy #137754

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 29, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions clang/lib/AST/ByteCode/Disasm.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,7 @@ LLVM_DUMP_METHOD void InlineDescriptor::dump(llvm::raw_ostream &OS) const {
OS << "IsActive: " << IsActive << "\n";
OS << "InUnion: " << InUnion << "\n";
OS << "IsFieldMutable: " << IsFieldMutable << "\n";
OS << "IsArrayElement: " << IsArrayElement << "\n";
OS << "Desc: ";
if (Desc)
Desc->dump(OS);
Expand Down
13 changes: 11 additions & 2 deletions clang/lib/AST/ByteCode/InterpBuiltin.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1849,8 +1849,17 @@ static bool interp__builtin_memcpy(InterpState &S, CodePtr OpPC,

// Check for overlapping memory regions.
if (!Move && Pointer::pointToSameBlock(SrcPtr, DestPtr)) {
unsigned SrcIndex = SrcPtr.getIndex() * SrcPtr.elemSize();
unsigned DstIndex = DestPtr.getIndex() * DestPtr.elemSize();
// Remove base casts.
Pointer SrcP = SrcPtr;
while (SrcP.isBaseClass())
SrcP = SrcP.getBase();

Pointer DestP = DestPtr;
while (DestP.isBaseClass())
DestP = DestP.getBase();

unsigned SrcIndex = SrcP.expand().getIndex() * SrcP.elemSize();
unsigned DstIndex = DestP.expand().getIndex() * DestP.elemSize();
unsigned N = Size.getZExtValue();

if ((SrcIndex <= DstIndex && (SrcIndex + N) > DstIndex) ||
Expand Down
14 changes: 13 additions & 1 deletion clang/test/AST/ByteCode/builtin-functions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1383,7 +1383,19 @@ namespace BuiltinMemcpy {
static_assert(type_pun(0x3f800000) == 1.0f); // both-error {{constant}} \
// both-note {{in call}}


struct Base { int a; };
struct Derived : Base { int b; };
constexpr int test_derived_to_base(int n) {
Derived arr[2] = {1, 2, 3, 4};
Base *p = &arr[0];
Base *q = &arr[1];
__builtin_memcpy(p, q, sizeof(Base) * n); // both-note {{source is not a contiguous array of at least 2 elements of type 'BuiltinMemcpy::Base'}}
return arr[0].a * 1000 + arr[0].b * 100 + arr[1].a * 10 + arr[1].b;
}
static_assert(test_derived_to_base(0) == 1234);
static_assert(test_derived_to_base(1) == 3234);
static_assert(test_derived_to_base(2) == 3434); // both-error {{constant}} \
// both-note {{in call}}
}

namespace Memcmp {
Expand Down
Loading