[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:58 PDT 2024
llvmbot wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang
Author: None (c8ef)
<details>
<summary>Changes</summary>
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.
---
Full diff: https://github.com/llvm/llvm-project/pull/112459.diff
3 Files Affected:
- (modified) clang/include/clang/Basic/Builtins.td (+1)
- (modified) clang/lib/AST/ExprConstant.cpp (+11)
- (modified) clang/test/AST/ByteCode/builtin-functions.cpp (+9)
``````````diff
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, "");
}
``````````
</details>
https://github.com/llvm/llvm-project/pull/112459
More information about the cfe-commits
mailing list