[clang] [clang][bytecode] Implement the constexpr built-in abs function. (PR #112459)
via cfe-commits
cfe-commits at lists.llvm.org
Tue Oct 15 18:24:21 PDT 2024
https://github.com/c8ef created https://github.com/llvm/llvm-project/pull/112459
The current built-in abs function cannot be used in a constexpr environment. This patch fixes the issue.
See also: https://godbolt.org/z/s8x3Yd8ne.
>From dfa1585af3f080987cbd15830c45c34bfecc1fca Mon Sep 17 00:00:00 2001
From: c8ef <c8ef at outlook.com>
Date: Wed, 16 Oct 2024 01:18:13 +0000
Subject: [PATCH] implement constexpr builtin {l}abs
---
clang/include/clang/Basic/Builtins.td | 1 +
clang/lib/AST/ExprConstant.cpp | 11 +++++++++++
clang/test/AST/ByteCode/builtin-functions.cpp | 9 +++++++++
3 files changed, 21 insertions(+)
diff --git a/clang/include/clang/Basic/Builtins.td b/clang/include/clang/Basic/Builtins.td
index bda8a48be92bda..e1b4d5b1fdc0a5 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -2714,6 +2714,7 @@ def Abs : IntMathTemplate, LibBuiltin<"stdlib.h"> {
let Attributes = [NoThrow, Const];
let Prototype = "T(T)";
let AddBuiltinPrefixedAlias = 1;
+ let OnlyBuiltinPrefixedAliasIsConstexpr = 1;
}
def Calloc : LibBuiltin<"stdlib.h"> {
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 52a7f5778ce6d2..69539a7f03feba 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -13055,6 +13055,17 @@ bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
return Success(Val.popcount() % 2, E);
}
+ case Builtin::BI__builtin_abs:
+ case Builtin::BI__builtin_labs:
+ case Builtin::BI__builtin_llabs: {
+ APSInt Val;
+ if (!EvaluateInteger(E->getArg(0), Val, Info))
+ return false;
+ if (Val.isNegative())
+ Val.negate();
+ return Success(Val, E);
+ }
+
case Builtin::BI__builtin_popcount:
case Builtin::BI__builtin_popcountl:
case Builtin::BI__builtin_popcountll:
diff --git a/clang/test/AST/ByteCode/builtin-functions.cpp b/clang/test/AST/ByteCode/builtin-functions.cpp
index 450ff5671314db..46e5b0579bd575 100644
--- a/clang/test/AST/ByteCode/builtin-functions.cpp
+++ b/clang/test/AST/ByteCode/builtin-functions.cpp
@@ -265,6 +265,15 @@ namespace fpclassify {
char classify_subnorm [__builtin_fpclassify(-1, -1, -1, +1, -1, 1.0e-38f)];
}
+namespace abs {
+static_assert(__builtin_abs(14) == 14, "");
+static_assert(__builtin_labs(14L) == 14L, "");
+static_assert(__builtin_llabs(14LL) == 14LL, "");
+static_assert(__builtin_abs(-14) == 14, "");
+static_assert(__builtin_labs(-14L) == 14L, "");
+static_assert(__builtin_llabs(-14LL) == 14LL, "");
+} // namespace abs
+
namespace fabs {
static_assert(__builtin_fabs(-14.0) == 14.0, "");
}
More information about the cfe-commits
mailing list