Skip to content

[C++23] [CLANG] Adding C++23 constexpr math functions: fmin, fmax and frexp. #88978

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

Open
wants to merge 23 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
3acc848
Adding C23 constexpr math functions fmin and frexp.
zahiraam Apr 16, 2024
d7050b5
Addressed review comments.
zahiraam Apr 22, 2024
625028a
Responded to review comments.
zahiraam May 1, 2024
319fdd0
Added code to store the exponent in Pointer. Edited LIT tests
zahiraam May 8, 2024
da06dba
Added fmax function and function IsinRange function.
zahiraam May 9, 2024
1793cf0
Addressed review comments.
zahiraam May 10, 2024
42d7d4c
Added a fix for failing LIT test.
zahiraam May 15, 2024
9f4d632
Fixed aix-builtin-mapping.c test.
zahiraam May 17, 2024
efeec9b
Merge remote-tracking branch 'origin/main' into C23ConstExpr
zahiraam May 17, 2024
e384a05
Addressed review comments.
zahiraam Jun 11, 2024
5f67645
Put back CodeGen/aix-builtin-mapping.c how it was originally written.
zahiraam Jun 11, 2024
49186b9
Fix build issue in flang.
zahiraam Jul 26, 2024
cf2814d
Merge remote-tracking branch 'origin/main' into C23ConstExpr
zahiraam Jul 26, 2024
1c2912c
Merge remote-tracking branch 'origin/main' into C23ConstExpr
zahiraam Jul 26, 2024
d32737e
Rewrote isInFrexpResultRange according to review comments and fixed
zahiraam Jul 26, 2024
bd536f5
Fix format.
zahiraam Jul 26, 2024
32b788a
Addressed missed review comments.
zahiraam Jul 29, 2024
501e39a
Addressed review comments. Remove StoreExponent function and fixed LIT
zahiraam Aug 5, 2024
0cc61eb
Replaced ConstexpSince by Constexpr for FrexpF16F128.
zahiraam Aug 13, 2024
c615b22
Removed builtin attribute ConstExprSince and replaced it with a member
zahiraam Aug 22, 2024
5eec2db
Fix format.
zahiraam Aug 22, 2024
299df9a
Fix LIT failures.
zahiraam Aug 23, 2024
1507a33
Merge remote-tracking branch 'origin/main' into C23ConstExpr
zahiraam Aug 23, 2024
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
5 changes: 3 additions & 2 deletions clang/include/clang/Basic/Builtins.td
Original file line number Diff line number Diff line change
Expand Up @@ -3440,9 +3440,10 @@ def Fmod : FPMathTemplate, LibBuiltin<"math.h"> {

def Frexp : FPMathTemplate, LibBuiltin<"math.h"> {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a separate FrexpF16F128 that should probably also be updated.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have added UnprefixedOnlyConstexprSince to the class LIBBUILTIN so it will be unknow if I add it to this def. I will wait to see if the changes I made were correct and update this rule accordingly.

let Spellings = ["frexp"];
let Attributes = [NoThrow];
let Attributes = [NoThrow, Constexpr];
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Constexpr here makes the non-__builtin_-prefixed version of the function constexpr under all language levels.
I checked the code: The OnlyBuiltinPrefixedAliasIsConstexpr flag can add constexpr-ness; it does not restrict it.

For reference:

if (Builtin->getValueAsBit("OnlyBuiltinPrefixedAliasIsConstexpr"))
OS << 'E';

We may need a new builtin attribute that expresses constexpr for the non-prefixed functions only for C++23 and up (but we might end up with C++26-and-up, etc. in the future). However, it seems making the non-prefixed functions actually non-constexpr (as opposed to simply failing to evaluate) is only a QoI concern (see #88978 (comment) for more context).

@philnik777, thoughts?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This also influences __has_constexpr_builtin(fmin), which would return true but then fail to actually evaluate during a constant expression, which doesn't seem that great. IMO we'd probably want to introduce the concept of "constexpr since C++xy".

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO we'd probably want to introduce the concept of "constexpr since C++xy".

@philnik777, are you envisioning something where LangOptions are passed into Builtin::Context::isConstantEvaluated?

bool isConstantEvaluated(unsigned ID) const {

I think the existing Constexpr/"E" attribute can be left alone for use in "always constexpr" cases.

For the selectively-constexpr cases, LibBuiltin in clang/include/clang/Basic/BuiltinsBase.td should have OnlyBuiltinPrefixedAliasIsConstexpr renamed to BuiltinPrefixedAliasIsConstexpr. Then adding a new string property for UnprefixedOnlyConstexprSince makes sense to me. It can be encoded into Builtin::Info (and I think using the LangFeatures enumeration from "clang/Basic/LangStandard.h" is not terribly wrong).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

let Prototype = "T(T, int*)";
let AddBuiltinPrefixedAlias = 1;
let OnlyBuiltinPrefixedAliasIsConstexpr = 1;
}

def Ldexp : FPMathTemplate, LibBuiltin<"math.h"> {
Expand Down Expand Up @@ -3618,7 +3619,7 @@ def Fmax : FPMathTemplate, LibBuiltin<"math.h"> {

def Fmin : FPMathTemplate, LibBuiltin<"math.h"> {
let Spellings = ["fmin"];
let Attributes = [NoThrow, Const];
let Attributes = [NoThrow, Const, Constexpr];
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same comment re: making the non-prefixed versions constexpr only for C++23 and up.

let Prototype = "T(T, T)";
let AddBuiltinPrefixedAlias = 1;
let OnlyBuiltinPrefixedAliasIsConstexpr = 1;
Expand Down
19 changes: 18 additions & 1 deletion clang/lib/AST/ExprConstant.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2922,7 +2922,7 @@ static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
// If during the evaluation of an expression, the result is not
// mathematically defined [...], the behavior is undefined.
// FIXME: C++ rules require us to not conform to IEEE 754 here.
if (LHS.isNaN()) {
if (!Info.getLangOpts().CPlusPlus23 && LHS.isNaN()) {
Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
return Info.noteUndefinedBehavior();
}
Expand Down Expand Up @@ -14547,6 +14547,20 @@ bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
default:
return false;

case Builtin::BI__builtin_frexp:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The non-__builtin_-prefixed cases need to be added in as per @philnik777's comment (#88978 (comment)). Same for the other two function families.

Some more thought is needed on how to handle the non-__builtin_-prefixed cases under non-C++23-or-higher language modes. The specific implications of those functions being non-constexpr under said modes (as required, for C++, by https://wg21.link/constexpr.functions) may determine the solution to apply in this PR.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added the non-`_builtin prefixed cases.

case Builtin::BI__builtin_frexpf:
case Builtin::BI__builtin_frexpl: {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

__builtin_frexpf16 and __builtin_frexp128 should probably be added at the same time as the other __builtin_* cases.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You mean adding :
case Builtin::BI__builtin_frexp16:
case Builtin::BI_builtin_frexp128:
to the cases here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

LValue Pointer;
if (!EvaluateFloat(E->getArg(0), Result, Info) ||
!EvaluatePointer(E->getArg(1), Pointer, Info))
return false;
llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
int FrexpExp;
FrexpExp = ilogb(Result);
FrexpExp = FrexpExp == llvm::detail::IEEEFloat::IEK_Zero ? 0 : FrexpExp + 1;
Result = scalbn(Result, -FrexpExp, RM);
return true;
}
case Builtin::BI__builtin_huge_val:
case Builtin::BI__builtin_huge_valf:
case Builtin::BI__builtin_huge_vall:
Expand Down Expand Up @@ -14638,6 +14652,9 @@ bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
return true;
}

case Builtin::BIfmin:
case Builtin::BIfminf:
Comment on lines +15093 to +15094
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't make these evaluate in constexpr. Not only does this extend C (not a stated intent of the patch), it will cause accidental dependencies that break when -fno-builtin is used.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These have to be made constexpr, at least in C++23. C++ stdlibs can't override them to make them call the __builtin_ versions, so Clang has to handle that.

This comment was marked as resolved.

This comment was marked as resolved.

This comment was marked as resolved.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we'll be missing at least "pedantic" diagnostics if we don't restrict the constexpr-ness to C++23 and up. So we do need that restriction.

The interaction with -fno-builtin[-*] may need more discussion. At least the documentation for that option would need to be updated if the C++23 constexpr math would break with it.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At the Clang C/C++ Language Workgroup call on 2024-05-15, it was agreed that -fno-builtin[-*] should remain capable of disabling built-in treatment even when that treatment would be required for conformance w.r.t. constexpr behaviour of functions shared with C.

For me, the first expectation for this PR (on that subject) is an update to the documentation of -fno-builtin[-*].

@AaronBallman @ldionne, I am no sure how we want to handle this w.r.t. documenting the C++23 implementation status. Does it go in both the Clang documentation (for the functions shared with C) and the libc++ documentation (for the overloads added by C++)?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think anything should happen to the libc++ documentation in this patch. We can update the implementation to behave the same across the different overloads in a follow-up and update our documentation then.

case Builtin::BIfminl:
case Builtin::BI__builtin_fmin:
case Builtin::BI__builtin_fminf:
case Builtin::BI__builtin_fminl:
Expand Down
59 changes: 59 additions & 0 deletions clang/test/CodeGenCXX/constexpr-math.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// RUN: %clang_cc1 -x c++ -triple x86_64-unknown-unknown -std=c++23 \
// RUN: -DWIN -emit-llvm -o - %s | FileCheck %s --check-prefixes=WIN

// RUN: %clang_cc1 -x c++ -triple x86_64-unknown-unknown -std=c++23 \
// RUN: -emit-llvm -o - %s | FileCheck %s --check-prefixes=LNX

#ifdef WIN
#define INFINITY ((float)(1e+300 * 1e+300))
#define NAN (-(float)(INFINITY * 0.0F))
#else
#define NAN (__builtin_nanf(""))
#define INFINITY (__builtin_inff())
#endif

int func()
{
int i;

// fmin
constexpr double f1 = __builtin_fmin(15.24, 1.3);
constexpr double f2 = __builtin_fmin(-0.0, +0.0);
constexpr double f3 = __builtin_fmin(+0.0, -0.0);
constexpr float f4 = __builtin_fminf(NAN, NAN);
constexpr float f5 = __builtin_fminf(NAN, -1);
constexpr float f6 = __builtin_fminf(-INFINITY, 0);
constexpr float f7 = __builtin_fminf(INFINITY, 0);
constexpr long double f8 = __builtin_fminl(123.456L, 789.012L);

// frexp
constexpr double f9 = __builtin_frexp(123.45, &i);
constexpr double f10 = __builtin_frexp(0.0, &i);
constexpr double f11 = __builtin_frexp(-0.0, &i);
constexpr double f12 = __builtin_frexpf(NAN, &i);
constexpr double f13 = __builtin_frexpf(-NAN, &i);
constexpr double f14 = __builtin_frexpf(INFINITY, &i);
constexpr double f15 = __builtin_frexpf(INFINITY, &i);
constexpr long double f16 = __builtin_frexpl(259.328L, &i);

return 0;
}

// CHECK: store double 1.300000e+00, ptr {{.*}}
// CHECK: store double -0.000000e+00, ptr {{.*}}
// CHECK: store double -0.000000e+00, ptr {{.*}}
// WIN: store float 0xFFF8000000000000, ptr {{.*}}
// LNX: store float 0x7FF8000000000000, ptr {{.*}}
// CHECK: store float -1.000000e+00, ptr {{.*}}
// CHECK: store float 0xFFF0000000000000, ptr {{.*}}
// CHECK: store double 1.234560e+02, ptr {{.*}}

// CHECK: store double 0x3FEEDCCCCCCCCCCD, ptr {{.*}}
// CHECK: store double 0.000000e+00, ptr {{.*}}
// CHECK: store double -0.000000e+00, ptr {{.*}}
// CHECK: store double 0xFFF8000000000000, ptr {{.*}}
// WIN: store double 0x7FF8000000000000, ptr {{.*}}
// LNX: store double 0xFFF8000000000000, ptr {{.*}}
// CHECK: store double 0x7FF0000000000000, ptr {{.*}}
// CHECK: store double 0x7FF0000000000000, ptr {{.*}}
// CHECK: store double 5.065000e-01, ptr {{.*}}
38 changes: 38 additions & 0 deletions clang/test/SemaCXX/constexpr-math.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// RUN: %clang_cc1 -DWIN -verify -std=c++23 -fsyntax-only %s
// RUN: %clang_cc1 -verify -std=c++23 -fsyntax-only %s
Copy link
Collaborator

@hubert-reinterpretcast hubert-reinterpretcast May 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Duplicate this run line for -std=c++20.
Modify the test to use the __builtin_* functions only for the -std=c++20 case.
Use only the non-__builtin_* functions for the -std=c++23 case.

For example replace calls using CALL_BUILTIN:

#if __cplusplus <= 202002L
#define CALL_BUILTIN(BASE_NAME, __VA_ARGS__) __builtin_##BASE_NAME(__VA_ARGS__)
#else
#define CALL_BUILTIN(BASE_NAME, __VA_ARGS__) BASE_NAME(__VA_ARGS__)
#endif

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.


// expected-no-diagnostics


#ifdef WIN
#define INFINITY ((float)(1e+300 * 1e+300))
#define NAN (-(float)(INFINITY * 0.0F))
#else
#define NAN (__builtin_nanf(""))
#define INFINITY (__builtin_inff())
#endif

int main() {
int i;

// fmin
static_assert(__builtin_fmin(15.24, 1.3) == 1.3, "");
static_assert(__builtin_fmin(-0.0, +0.0) == -0.0, "");
static_assert(__builtin_fmin(+0.0, -0.0) == -0.0, "");
static_assert(__builtin_fminf(NAN, -1) == -1, "");
static_assert(__builtin_fminf(+INFINITY, 0) == 0, "");
static_assert(__builtin_isinf(__builtin_fminf(-INFINITY, 0)), "");
static_assert(__builtin_isnan(__builtin_fminf(NAN,NAN)), "");

// frexp
static_assert(__builtin_frexp(123.45, &i) == 0.96445312500000002);
static_assert(!__builtin_isnan(__builtin_frexp(123.45, &i)), "");
static_assert(__builtin_iszero(__builtin_frexp(0.0, &i)), "");
static_assert(__builtin_iszero(__builtin_frexp(-0.0, &i)), "");
static_assert(__builtin_isnan(__builtin_frexp(NAN, &i)));
static_assert(__builtin_isnan(__builtin_frexp(-NAN, &i)));
static_assert(!__builtin_isfinite(__builtin_frexp(INFINITY, &i)));
static_assert(!__builtin_isfinite(__builtin_frexp(-INFINITY, &i)));

return 0;
}