Skip to content

Commit f602189

Browse files
committed
[Clang] Add __builtin_is_within_lifetime to implement P2641R4's std::is_within_lifetime
Squashed all previous commits (no longer in draft)
1 parent c29aba7 commit f602189

File tree

10 files changed

+693
-7
lines changed

10 files changed

+693
-7
lines changed

clang/include/clang/Basic/Builtins.td

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -934,6 +934,12 @@ def IsConstantEvaluated : LangBuiltin<"CXX_LANG"> {
934934
let Prototype = "bool()";
935935
}
936936

937+
def IsWithinLifetime : LangBuiltin<"CXX_LANG"> {
938+
let Spellings = ["__builtin_is_within_lifetime"];
939+
let Attributes = [NoThrow, CustomTypeChecking, Consteval];
940+
let Prototype = "bool(void*)";
941+
}
942+
937943
// GCC exception builtins
938944
def EHReturn : Builtin {
939945
let Spellings = ["__builtin_eh_return"];

clang/include/clang/Basic/DiagnosticASTKinds.td

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -169,14 +169,14 @@ def note_constexpr_this : Note<
169169
def access_kind : TextSubstitution<
170170
"%select{read of|read of|assignment to|increment of|decrement of|"
171171
"member call on|dynamic_cast of|typeid applied to|construction of|"
172-
"destruction of}0">;
172+
"destruction of|read of}0">;
173173
def access_kind_subobject : TextSubstitution<
174174
"%select{read of|read of|assignment to|increment of|decrement of|"
175175
"member call on|dynamic_cast of|typeid applied to|"
176-
"construction of subobject of|destruction of}0">;
176+
"construction of subobject of|destruction of|read of}0">;
177177
def access_kind_volatile : TextSubstitution<
178178
"%select{read of|read of|assignment to|increment of|decrement of|"
179-
"<ERROR>|<ERROR>|<ERROR>|<ERROR>|<ERROR>}0">;
179+
"<ERROR>|<ERROR>|<ERROR>|<ERROR>|<ERROR>|<ERROR>}0">;
180180
def note_constexpr_lifetime_ended : Note<
181181
"%sub{access_kind}0 %select{temporary|variable}1 whose "
182182
"%plural{8:storage duration|:lifetime}0 has ended">;
@@ -408,6 +408,12 @@ def warn_is_constant_evaluated_always_true_constexpr : Warning<
408408
"'%0' will always evaluate to 'true' in a manifestly constant-evaluated expression">,
409409
InGroup<DiagGroup<"constant-evaluated">>;
410410

411+
def err_invalid_is_within_lifetime : Note<
412+
"'%0' cannot be called with "
413+
"%select{a null pointer|a function pointer|a one-past-the-end pointer|"
414+
"a pointer to an object whose lifetime has not yet begun}1"
415+
>;
416+
411417
// inline asm related.
412418
let CategoryName = "Inline Assembly Issue" in {
413419
def err_asm_invalid_escape : Error<

clang/include/clang/Basic/DiagnosticSemaKinds.td

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12190,6 +12190,9 @@ def err_builtin_launder_invalid_arg : Error<
1219012190
"%select{non-pointer|function pointer|void pointer}0 argument to "
1219112191
"'__builtin_launder' is not allowed">;
1219212192

12193+
def err_builtin_is_within_lifetime_invalid_arg : Error<
12194+
"non-pointer argument to '__builtin_is_within_lifetime' is not allowed">;
12195+
1219312196
def err_builtin_invalid_arg_type: Error <
1219412197
"%ordinal0 argument must be "
1219512198
"%select{a vector, integer or floating point type|a matrix|"

clang/lib/AST/ByteCode/State.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ enum AccessKinds {
3434
AK_TypeId,
3535
AK_Construct,
3636
AK_Destroy,
37+
AK_IsWithinLifetime,
3738
};
3839

3940
/// The order of this enum is important for diagnostics.

clang/lib/AST/ExprConstant.cpp

Lines changed: 105 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1522,7 +1522,8 @@ CallStackFrame::~CallStackFrame() {
15221522
}
15231523

15241524
static bool isRead(AccessKinds AK) {
1525-
return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1525+
return AK == AK_Read || AK == AK_ReadObjectRepresentation ||
1526+
AK == AK_IsWithinLifetime;
15261527
}
15271528

15281529
static bool isModification(AccessKinds AK) {
@@ -1532,6 +1533,7 @@ static bool isModification(AccessKinds AK) {
15321533
case AK_MemberCall:
15331534
case AK_DynamicCast:
15341535
case AK_TypeId:
1536+
case AK_IsWithinLifetime:
15351537
return false;
15361538
case AK_Assign:
15371539
case AK_Increment:
@@ -1549,7 +1551,8 @@ static bool isAnyAccess(AccessKinds AK) {
15491551

15501552
/// Is this an access per the C++ definition?
15511553
static bool isFormalAccess(AccessKinds AK) {
1552-
return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1554+
return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy &&
1555+
AK != AK_IsWithinLifetime;
15531556
}
15541557

15551558
/// Is this kind of axcess valid on an indeterminate object value?
@@ -1561,6 +1564,7 @@ static bool isValidIndeterminateAccess(AccessKinds AK) {
15611564
// These need the object's value.
15621565
return false;
15631566

1567+
case AK_IsWithinLifetime:
15641568
case AK_ReadObjectRepresentation:
15651569
case AK_Assign:
15661570
case AK_Construct:
@@ -3707,7 +3711,8 @@ struct CompleteObject {
37073711
// In C++14 onwards, it is permitted to read a mutable member whose
37083712
// lifetime began within the evaluation.
37093713
// FIXME: Should we also allow this in C++11?
3710-
if (!Info.getLangOpts().CPlusPlus14)
3714+
if (!Info.getLangOpts().CPlusPlus14 &&
3715+
AK != AccessKinds::AK_IsWithinLifetime)
37113716
return false;
37123717
return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
37133718
}
@@ -3760,6 +3765,12 @@ findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
37603765
if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
37613766
(O->isIndeterminate() &&
37623767
!isValidIndeterminateAccess(handler.AccessKind))) {
3768+
// Object has ended lifetime.
3769+
// If I is non-zero, some subobject (member or array element) of a
3770+
// complete object has ended its lifetime, so this is valid for
3771+
// IsWithinLifetime, resulting in false.
3772+
if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
3773+
return false;
37633774
if (!Info.checkingPotentialConstantExpression())
37643775
Info.FFDiag(E, diag::note_constexpr_access_uninit)
37653776
<< handler.AccessKind << O->isIndeterminate()
@@ -3927,6 +3938,9 @@ findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
39273938
// Placement new onto an inactive union member makes it active.
39283939
O->setUnion(Field, APValue());
39293940
} else {
3941+
// Pointer to/into inactive union member: Not within lifetime
3942+
if (handler.AccessKind == AK_IsWithinLifetime)
3943+
return false;
39303944
// FIXME: If O->getUnionValue() is absent, report that there's no
39313945
// active union member rather than reporting the prior active union
39323946
// member. We'll need to fix nullptr_t to not use APValue() as its
@@ -11667,6 +11681,9 @@ class IntExprEvaluator
1166711681

1166811682
bool ZeroInitialization(const Expr *E) { return Success(0, E); }
1166911683

11684+
friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
11685+
const CallExpr *);
11686+
1167011687
//===--------------------------------------------------------------------===//
1167111688
// Visitor Methods
1167211689
//===--------------------------------------------------------------------===//
@@ -12722,6 +12739,11 @@ bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
1272212739
return Success(Info.InConstantContext, E);
1272312740
}
1272412741

12742+
case Builtin::BI__builtin_is_within_lifetime:
12743+
if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
12744+
return Success(*result, E);
12745+
return false;
12746+
1272512747
case Builtin::BI__builtin_ctz:
1272612748
case Builtin::BI__builtin_ctzl:
1272712749
case Builtin::BI__builtin_ctzll:
@@ -17310,3 +17332,83 @@ bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
1731017332
EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
1731117333
return EvaluateBuiltinStrLen(this, Result, Info);
1731217334
}
17335+
17336+
namespace {
17337+
struct IsWithinLifetimeHandler {
17338+
EvalInfo &Info;
17339+
static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
17340+
using result_type = std::optional<bool>;
17341+
std::optional<bool> failed() { return std::nullopt; }
17342+
template <typename T>
17343+
std::optional<bool> found(T &Subobj, QualType SubobjType) {
17344+
return true;
17345+
}
17346+
};
17347+
17348+
std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
17349+
const CallExpr *E) {
17350+
EvalInfo &Info = IEE.Info;
17351+
// Sometimes this is called during some sorts of constant folding / early
17352+
// evaluation. These are meant for non-constant expressions and are not
17353+
// necessary since this consteval builtin will never be evaluated at runtime.
17354+
// Just fail to evaluate when not in a constant context.
17355+
if (!Info.InConstantContext)
17356+
return std::nullopt;
17357+
assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
17358+
const Expr *Arg = E->getArg(0);
17359+
if (Arg->isValueDependent())
17360+
return std::nullopt;
17361+
LValue Val;
17362+
if (!EvaluatePointer(Arg, Val, Info))
17363+
return std::nullopt;
17364+
17365+
auto Error = [&](int Diag) {
17366+
bool CalledFromStd = false;
17367+
const auto *Callee = Info.CurrentCall->getCallee();
17368+
if (Callee && Callee->isInStdNamespace()) {
17369+
const IdentifierInfo *Identifier = Callee->getIdentifier();
17370+
CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
17371+
}
17372+
Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
17373+
: E->getExprLoc(),
17374+
diag::err_invalid_is_within_lifetime)
17375+
<< (CalledFromStd ? "std::is_within_lifetime"
17376+
: "__builtin_is_within_lifetime")
17377+
<< Diag;
17378+
return std::nullopt;
17379+
};
17380+
// C++2c [meta.const.eval]p4:
17381+
// During the evaluation of an expression E as a core constant expression, a
17382+
// call to this function is ill-formed unless p points to an object that is
17383+
// usable in constant expressions or whose complete object's lifetime began
17384+
// within E.
17385+
17386+
// Make sure it points to an object
17387+
// nullptr does not point to an object
17388+
if (Val.isNullPointer() || Val.getLValueBase().isNull())
17389+
return Error(0);
17390+
QualType T = Val.getLValueBase().getType();
17391+
if (T->isFunctionType())
17392+
return Error(1);
17393+
assert(T->isObjectType());
17394+
// Hypothetical array element is not an object
17395+
if (Val.getLValueDesignator().isOnePastTheEnd())
17396+
return Error(2);
17397+
assert(Val.getLValueDesignator().isValidSubobject() &&
17398+
"Unchecked case for valid subobject");
17399+
// All other ill-formed values should have failed EvaluatePointer, so the
17400+
// object should be a pointer to an object that is usable in a constant
17401+
// expression or whose complete lifetime began within the expression
17402+
CompleteObject CO =
17403+
findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
17404+
// The lifetime hasn't begun yet if we are still evaluating the
17405+
// initializer ([basic.life]p(1.2))
17406+
if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
17407+
return Error(3);
17408+
17409+
if (!CO)
17410+
return false;
17411+
IsWithinLifetimeHandler handler{Info};
17412+
return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
17413+
}
17414+
} // namespace

clang/lib/CodeGen/CGBuiltin.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2538,6 +2538,9 @@ static RValue EmitHipStdParUnsupportedBuiltin(CodeGenFunction *CGF,
25382538
RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
25392539
const CallExpr *E,
25402540
ReturnValueSlot ReturnValue) {
2541+
assert(!getContext().BuiltinInfo.isImmediate(BuiltinID) &&
2542+
"Should not codegen for consteval builtins");
2543+
25412544
const FunctionDecl *FD = GD.getDecl()->getAsFunction();
25422545
// See if we can constant fold this builtin. If so, don't emit it at all.
25432546
// TODO: Extend this handling to all builtin calls that we can constant-fold.

clang/lib/Sema/SemaChecking.cpp

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1844,6 +1844,40 @@ static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall) {
18441844
return TheCall;
18451845
}
18461846

1847+
static ExprResult BuiltinIsWithinLifetime(Sema &S, CallExpr *TheCall) {
1848+
if (S.checkArgCount(TheCall, 1))
1849+
return ExprError();
1850+
1851+
ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1852+
if (Arg.isInvalid())
1853+
return ExprError();
1854+
QualType ParamTy = Arg.get()->getType();
1855+
TheCall->setArg(0, Arg.get());
1856+
TheCall->setType(S.Context.BoolTy);
1857+
1858+
// A call to this function is always ill-formed if the type is not a pointer
1859+
// to an object type. There is no Mandates: to that effect, so we can only
1860+
// issue an error if it is actually evaluated as part of a constant evaluation
1861+
// (e.g., `false ? true : std::is_within_lifetime<void()>(nullptr);` is fine)
1862+
// However, `std::is_within_lifetime` will only take pointer types (allow
1863+
// non-const qualified too)
1864+
if (const auto *PT = ParamTy->getAs<PointerType>()) {
1865+
// Disallow VLAs too since those shouldn't be able to
1866+
// be a template parameter for `std::is_within_lifetime`
1867+
if (PT->getPointeeType()->isVariableArrayType()) {
1868+
S.Diag(TheCall->getArg(0)->getExprLoc(), diag::err_vla_unsupported)
1869+
<< 1 << "__builtin_is_within_lifetime";
1870+
return ExprError();
1871+
}
1872+
} else {
1873+
S.Diag(TheCall->getArg(0)->getExprLoc(),
1874+
diag::err_builtin_is_within_lifetime_invalid_arg);
1875+
return ExprError();
1876+
}
1877+
1878+
return TheCall;
1879+
}
1880+
18471881
// Emit an error and return true if the current object format type is in the
18481882
// list of unsupported types.
18491883
static bool CheckBuiltinTargetNotInUnsupported(
@@ -2276,6 +2310,8 @@ Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
22762310
}
22772311
case Builtin::BI__builtin_launder:
22782312
return BuiltinLaunder(*this, TheCall);
2313+
case Builtin::BI__builtin_is_within_lifetime:
2314+
return BuiltinIsWithinLifetime(*this, TheCall);
22792315
case Builtin::BI__sync_fetch_and_add:
22802316
case Builtin::BI__sync_fetch_and_add_1:
22812317
case Builtin::BI__sync_fetch_and_add_2:

clang/lib/Sema/SemaExpr.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17577,7 +17577,8 @@ HandleImmediateInvocations(Sema &SemaRef,
1757717577
(SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
1757817578
SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
1757917579
<< ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
17580-
SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
17580+
if (!FD->getBuiltinID())
17581+
SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
1758117582
if (auto Context =
1758217583
SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
1758317584
SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)

0 commit comments

Comments
 (0)