Skip to content
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
16 changes: 16 additions & 0 deletions clang/lib/AST/Interp/Compiler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4775,6 +4775,22 @@ bool Compiler<Emitter>::visitFunc(const FunctionDecl *F) {
if (!R)
return false;

if (R->isUnion() && Ctor->isCopyOrMoveConstructor()) {
// union copy and move ctors are special.
assert(cast<CompoundStmt>(Ctor->getBody())->body_empty());
if (!this->emitThis(Ctor))
return false;

auto PVD = Ctor->getParamDecl(0);
ParamOffset PO = this->Params[PVD]; // Must exist.

if (!this->emitGetParam(PT_Ptr, PO.Offset, Ctor))
return false;

return this->emitMemcpy(Ctor) && this->emitPopPtr(Ctor) &&
this->emitRetVoid(Ctor);
}

InitLinkScope<Emitter> InitScope(this, InitLink::This());
for (const auto *Init : Ctor->inits()) {
// Scope needed for the initializers.
Expand Down
26 changes: 21 additions & 5 deletions clang/lib/AST/Interp/InterpBuiltin.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1658,18 +1658,34 @@ bool DoMemcpy(InterpState &S, CodePtr OpPC, const Pointer &Src, Pointer &Dest) {
}

if (DestDesc->isRecord()) {
assert(SrcDesc->isRecord());
assert(SrcDesc->ElemRecord == DestDesc->ElemRecord);
const Record *R = DestDesc->ElemRecord;
for (const Record::Field &F : R->fields()) {
auto copyField = [&](const Record::Field &F, bool Activate) -> bool {
Pointer DestField = Dest.atField(F.Offset);
if (std::optional<PrimType> FT = S.Ctx.classify(F.Decl->getType())) {
TYPE_SWITCH(*FT, {
DestField.deref<T>() = Src.atField(F.Offset).deref<T>();
DestField.initialize();
if (Activate)
DestField.activate();
});
return true;
}
return Invalid(S, OpPC);
};

assert(SrcDesc->isRecord());
assert(SrcDesc->ElemRecord == DestDesc->ElemRecord);
const Record *R = DestDesc->ElemRecord;
for (const Record::Field &F : R->fields()) {
if (R->isUnion()) {
// For unions, only copy the active field.
const Pointer &SrcField = Src.atField(F.Offset);
if (SrcField.isActive()) {
if (!copyField(F, /*Activate=*/true))
return false;
}
} else {
return Invalid(S, OpPC);
if (!copyField(F, /*Activate=*/false))
return false;
}
}
return true;
Expand Down
11 changes: 11 additions & 0 deletions clang/test/AST/Interp/unions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -346,5 +346,16 @@ namespace IndirectField {
static_assert(s2.f == 7, "");
}

namespace CopyCtor {
union U {
int a;
int b;
};

constexpr U x = {42};
constexpr U y = x;
static_assert(y.a == 42, "");
static_assert(y.b == 42, ""); // both-error {{constant expression}} \
// both-note {{'b' of union with active member 'a'}}
}
#endif