Skip to content

[clang][bytecode] Implement placement-new #107033

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
Sep 23, 2024
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
98 changes: 67 additions & 31 deletions clang/lib/AST/ByteCode/Compiler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3097,12 +3097,11 @@ bool Compiler<Emitter>::VisitCXXNewExpr(const CXXNewExpr *E) {
QualType ElementType = E->getAllocatedType();
std::optional<PrimType> ElemT = classify(ElementType);
unsigned PlacementArgs = E->getNumPlacementArgs();
const FunctionDecl *OperatorNew = E->getOperatorNew();
const Expr *PlacementDest = nullptr;
bool IsNoThrow = false;

// FIXME: Better diagnostic. diag::note_constexpr_new_placement
if (PlacementArgs != 0) {
// The only new-placement list we support is of the form (std::nothrow).
//
// FIXME: There is no restriction on this, but it's not clear that any
// other form makes any sense. We get here for cases such as:
//
Expand All @@ -3111,27 +3110,43 @@ bool Compiler<Emitter>::VisitCXXNewExpr(const CXXNewExpr *E) {
// (which should presumably be valid only if N is a multiple of
// alignof(int), and in any case can't be deallocated unless N is
// alignof(X) and X has new-extended alignment).
if (PlacementArgs != 1 || !E->getPlacementArg(0)->getType()->isNothrowT())
return this->emitInvalid(E);
if (PlacementArgs == 1) {
const Expr *Arg1 = E->getPlacementArg(0);
if (Arg1->getType()->isNothrowT()) {
if (!this->discard(Arg1))
return false;
IsNoThrow = true;
} else if (Ctx.getLangOpts().CPlusPlus26 &&
OperatorNew->isReservedGlobalPlacementOperator()) {
// If we have a placement-new destination, we'll later use that instead
// of allocating.
PlacementDest = Arg1;
} else {
return this->emitInvalidNewDeleteExpr(E, E);
}

if (!this->discard(E->getPlacementArg(0)))
return false;
IsNoThrow = true;
} else {
return this->emitInvalid(E);
}
} else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
return this->emitInvalidNewDeleteExpr(E, E);
}

const Descriptor *Desc;
if (ElemT) {
if (E->isArray())
Desc = nullptr; // We're not going to use it in this case.
else
Desc = P.createDescriptor(E, *ElemT, Descriptor::InlineDescMD,
/*IsConst=*/false, /*IsTemporary=*/false,
/*IsMutable=*/false);
} else {
Desc = P.createDescriptor(
E, ElementType.getTypePtr(),
E->isArray() ? std::nullopt : Descriptor::InlineDescMD,
/*IsConst=*/false, /*IsTemporary=*/false, /*IsMutable=*/false, Init);
if (!PlacementDest) {
if (ElemT) {
if (E->isArray())
Desc = nullptr; // We're not going to use it in this case.
else
Desc = P.createDescriptor(E, *ElemT, Descriptor::InlineDescMD,
/*IsConst=*/false, /*IsTemporary=*/false,
/*IsMutable=*/false);
} else {
Desc = P.createDescriptor(
E, ElementType.getTypePtr(),
E->isArray() ? std::nullopt : Descriptor::InlineDescMD,
/*IsConst=*/false, /*IsTemporary=*/false, /*IsMutable=*/false, Init);
}
}

if (E->isArray()) {
Expand All @@ -3148,26 +3163,42 @@ bool Compiler<Emitter>::VisitCXXNewExpr(const CXXNewExpr *E) {

PrimType SizeT = classifyPrim(Stripped->getType());

if (!this->visit(Stripped))
return false;

if (ElemT) {
// N primitive elements.
if (!this->emitAllocN(SizeT, *ElemT, E, IsNoThrow, E))
if (PlacementDest) {
if (!this->visit(PlacementDest))
return false;
if (!this->visit(Stripped))
return false;
if (!this->emitCheckNewTypeMismatchArray(SizeT, E, E))
return false;
} else {
// N Composite elements.
if (!this->emitAllocCN(SizeT, Desc, IsNoThrow, E))
if (!this->visit(Stripped))
return false;

if (ElemT) {
// N primitive elements.
if (!this->emitAllocN(SizeT, *ElemT, E, IsNoThrow, E))
return false;
} else {
// N Composite elements.
if (!this->emitAllocCN(SizeT, Desc, IsNoThrow, E))
return false;
}
}

if (Init && !this->visitInitializer(Init))
return false;

} else {
// Allocate just one element.
if (!this->emitAlloc(Desc, E))
return false;
if (PlacementDest) {
if (!this->visit(PlacementDest))
return false;
if (!this->emitCheckNewTypeMismatch(E, E))
return false;
} else {
// Allocate just one element.
if (!this->emitAlloc(Desc, E))
return false;
}

if (Init) {
if (ElemT) {
Expand All @@ -3194,6 +3225,11 @@ template <class Emitter>
bool Compiler<Emitter>::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
const Expr *Arg = E->getArgument();

const FunctionDecl *OperatorDelete = E->getOperatorDelete();

if (!OperatorDelete->isReplaceableGlobalAllocationFunction())
return this->emitInvalidNewDeleteExpr(E, E);

// Arg must be an lvalue.
if (!this->visit(Arg))
return false;
Expand Down
74 changes: 74 additions & 0 deletions clang/lib/AST/ByteCode/Interp.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1286,6 +1286,80 @@ bool CallPtr(InterpState &S, CodePtr OpPC, uint32_t ArgSize,
return Call(S, OpPC, F, VarArgSize);
}

bool CheckNewTypeMismatch(InterpState &S, CodePtr OpPC, const Expr *E,
std::optional<uint64_t> ArraySize) {
const Pointer &Ptr = S.Stk.peek<Pointer>();

if (!CheckStore(S, OpPC, Ptr))
return false;

const auto *NewExpr = cast<CXXNewExpr>(E);
QualType StorageType = Ptr.getType();

if (isa_and_nonnull<CXXNewExpr>(Ptr.getFieldDesc()->asExpr())) {
// FIXME: Are there other cases where this is a problem?
StorageType = StorageType->getPointeeType();
}

const ASTContext &ASTCtx = S.getASTContext();
QualType AllocType;
if (ArraySize) {
AllocType = ASTCtx.getConstantArrayType(
NewExpr->getAllocatedType(),
APInt(64, static_cast<uint64_t>(*ArraySize), false), nullptr,
ArraySizeModifier::Normal, 0);
} else {
AllocType = NewExpr->getAllocatedType();
}

unsigned StorageSize = 1;
unsigned AllocSize = 1;
if (const auto *CAT = dyn_cast<ConstantArrayType>(AllocType))
AllocSize = CAT->getZExtSize();
if (const auto *CAT = dyn_cast<ConstantArrayType>(StorageType))
StorageSize = CAT->getZExtSize();

if (AllocSize > StorageSize ||
!ASTCtx.hasSimilarType(ASTCtx.getBaseElementType(AllocType),
ASTCtx.getBaseElementType(StorageType))) {
S.FFDiag(S.Current->getLocation(OpPC),
diag::note_constexpr_placement_new_wrong_type)
<< StorageType << AllocType;
return false;
}
return true;
}

bool InvalidNewDeleteExpr(InterpState &S, CodePtr OpPC, const Expr *E) {
assert(E);
const auto &Loc = S.Current->getSource(OpPC);

if (const auto *NewExpr = dyn_cast<CXXNewExpr>(E)) {
const FunctionDecl *OperatorNew = NewExpr->getOperatorNew();

if (!S.getLangOpts().CPlusPlus26 && NewExpr->getNumPlacementArgs() > 0) {
S.FFDiag(Loc, diag::note_constexpr_new_placement)
<< /*C++26 feature*/ 1 << E->getSourceRange();
} else if (NewExpr->getNumPlacementArgs() == 1 &&
!OperatorNew->isReservedGlobalPlacementOperator()) {
S.FFDiag(Loc, diag::note_constexpr_new_placement)
<< /*Unsupported*/ 0 << E->getSourceRange();
} else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
S.FFDiag(Loc, diag::note_constexpr_new_non_replaceable)
<< isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
}
} else {
const auto *DeleteExpr = cast<CXXDeleteExpr>(E);
const FunctionDecl *OperatorDelete = DeleteExpr->getOperatorDelete();
if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
S.FFDiag(Loc, diag::note_constexpr_new_non_replaceable)
<< isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
}
}

return false;
}

bool Interpret(InterpState &S, APValue &Result) {
// The current stack frame when we started Interpret().
// This is being used by the ops to determine wheter
Expand Down
11 changes: 11 additions & 0 deletions clang/lib/AST/ByteCode/Interp.h
Original file line number Diff line number Diff line change
Expand Up @@ -2947,6 +2947,17 @@ static inline bool IsConstantContext(InterpState &S, CodePtr OpPC) {
return true;
}

/// Check if the initializer and storage types of a placement-new expression
/// match.
bool CheckNewTypeMismatch(InterpState &S, CodePtr OpPC, const Expr *E,
std::optional<uint64_t> ArraySize = std::nullopt);

template <PrimType Name, class T = typename PrimConv<Name>::T>
bool CheckNewTypeMismatchArray(InterpState &S, CodePtr OpPC, const Expr *E) {
const auto &Size = S.Stk.pop<T>();
return CheckNewTypeMismatch(S, OpPC, E, static_cast<uint64_t>(Size));
}
bool InvalidNewDeleteExpr(InterpState &S, CodePtr OpPC, const Expr *E);
//===----------------------------------------------------------------------===//
// Read opcode arguments
//===----------------------------------------------------------------------===//
Expand Down
14 changes: 14 additions & 0 deletions clang/lib/AST/ByteCode/Opcodes.td
Original file line number Diff line number Diff line change
Expand Up @@ -787,4 +787,18 @@ def Free : Opcode {
let Args = [ArgBool];
}

def CheckNewTypeMismatch : Opcode {
let Args = [ArgExpr];
}

def InvalidNewDeleteExpr : Opcode {
let Args = [ArgExpr];
}

def CheckNewTypeMismatchArray : Opcode {
let Types = [IntegerTypeClass];
let Args = [ArgExpr];
let HasGroup = 1;
}

def IsConstantContext: Opcode;
36 changes: 21 additions & 15 deletions clang/test/AST/ByteCode/new-delete.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -241,12 +241,10 @@ namespace std {



/// FIXME: The new interpreter produces the wrong diagnostic.
namespace PlacementNew {
constexpr int foo() { // both-error {{never produces a constant expression}}
char c[sizeof(int)];
new (c) int{12}; // ref-note {{this placement new expression is not supported in constant expressions before C++2c}} \
// expected-note {{subexpression not valid in a constant expression}}
new (c) int{12}; // both-note {{this placement new expression is not supported in constant expressions before C++2c}}
return 0;
}
}
Expand Down Expand Up @@ -305,41 +303,38 @@ namespace placement_new_delete {
}
static_assert(ok());

/// FIXME: Diagnosting placement new.
constexpr bool bad(int which) {
switch (which) {
case 0:
delete new (placement_new_arg{}) int; // ref-note {{this placement new expression is not supported in constant expressions}} \
// expected-note {{subexpression not valid in a constant expression}}
delete new (placement_new_arg{}) int; // both-note {{this placement new expression is not supported in constant expressions}}
break;

case 1:
delete new ClassSpecificNew; // ref-note {{call to class-specific 'operator new'}}
delete new ClassSpecificNew; // both-note {{call to class-specific 'operator new'}}
break;

case 2:
delete new ClassSpecificDelete; // ref-note {{call to class-specific 'operator delete'}}
delete new ClassSpecificDelete; // both-note {{call to class-specific 'operator delete'}}
break;

case 3:
delete new DestroyingDelete; // ref-note {{call to class-specific 'operator delete'}}
delete new DestroyingDelete; // both-note {{call to class-specific 'operator delete'}}
break;

case 4:
// FIXME: This technically follows the standard's rules, but it seems
// unreasonable to expect implementations to support this.
delete new (std::align_val_t{64}) Overaligned; // ref-note {{this placement new expression is not supported in constant expressions}} \
// expected-note {{subexpression not valid in a constant expression}}
delete new (std::align_val_t{64}) Overaligned; // both-note {{this placement new expression is not supported in constant expressions}}
break;
}

return true;
}
static_assert(bad(0)); // both-error {{constant expression}} \
// both-note {{in call}}
static_assert(bad(1)); // ref-error {{constant expression}} ref-note {{in call}}
static_assert(bad(2)); // ref-error {{constant expression}} ref-note {{in call}}
static_assert(bad(3)); // ref-error {{constant expression}} ref-note {{in call}}
static_assert(bad(1)); // both-error {{constant expression}} both-note {{in call}}
static_assert(bad(2)); // both-error {{constant expression}} both-note {{in call}}
static_assert(bad(3)); // both-error {{constant expression}} both-note {{in call}}
static_assert(bad(4)); // both-error {{constant expression}} \
// both-note {{in call}}
}
Expand Down Expand Up @@ -586,7 +581,6 @@ constexpr void use_after_free_2() { // both-error {{never produces a constant ex
p->f(); // both-note {{member call on heap allocated object that has been deleted}}
}


/// std::allocator definition
namespace std {
using size_t = decltype(sizeof(0));
Expand Down Expand Up @@ -733,6 +727,18 @@ namespace Limits {
static_assert(dynarray<char>(5, 0) == 'f');
}

/// Just test that we reject placement-new expressions before C++2c.
/// Tests for successful expressions are in placement-new.cpp
namespace Placement {
consteval auto ok1() { // both-error {{never produces a constant expression}}
bool b;
new (&b) bool(true); // both-note 2{{this placement new expression is not supported in constant expressions before C++2c}}
return b;
}
static_assert(ok1()); // both-error {{not an integral constant expression}} \
// both-note {{in call to}}
}

#else
/// Make sure we reject this prior to C++20
constexpr int a() { // both-error {{never produces a constant expression}}
Expand Down
Loading
Loading