xref: /openbsd-src/gnu/llvm/libcxx/src/filesystem/int128_builtins.cpp (revision 4bdff4bed0e3d54e55670334c7d0077db4170f86)
146035553Spatrick /*===-- int128_builtins.cpp - Implement __muloti4 --------------------------===
246035553Spatrick  *
346035553Spatrick  * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
446035553Spatrick  * See https://llvm.org/LICENSE.txt for license information.
546035553Spatrick  * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
646035553Spatrick  *
746035553Spatrick  * ===----------------------------------------------------------------------===
846035553Spatrick  *
946035553Spatrick  * This file implements __muloti4, and is stolen from the compiler_rt library.
1046035553Spatrick  *
1146035553Spatrick  * FIXME: we steal and re-compile it into filesystem, which uses __int128_t,
1246035553Spatrick  * and requires this builtin when sanitized. See llvm.org/PR30643
1346035553Spatrick  *
1446035553Spatrick  * ===----------------------------------------------------------------------===
1546035553Spatrick  */
16*4bdff4beSrobert #include <__config>
17*4bdff4beSrobert #include <climits>
1846035553Spatrick 
1946035553Spatrick #if !defined(_LIBCPP_HAS_NO_INT128)
2046035553Spatrick 
2146035553Spatrick extern "C" __attribute__((no_sanitize("undefined"))) _LIBCPP_FUNC_VIS
__muloti4(__int128_t a,__int128_t b,int * overflow)2246035553Spatrick __int128_t __muloti4(__int128_t a, __int128_t b, int* overflow) {
2346035553Spatrick   const int N = (int)(sizeof(__int128_t) * CHAR_BIT);
2446035553Spatrick   const __int128_t MIN = (__int128_t)1 << (N - 1);
2546035553Spatrick   const __int128_t MAX = ~MIN;
2646035553Spatrick   *overflow = 0;
2746035553Spatrick   __int128_t result = a * b;
2846035553Spatrick   if (a == MIN) {
2946035553Spatrick     if (b != 0 && b != 1)
3046035553Spatrick       *overflow = 1;
3146035553Spatrick     return result;
3246035553Spatrick   }
3346035553Spatrick   if (b == MIN) {
3446035553Spatrick     if (a != 0 && a != 1)
3546035553Spatrick       *overflow = 1;
3646035553Spatrick     return result;
3746035553Spatrick   }
3846035553Spatrick   __int128_t sa = a >> (N - 1);
3946035553Spatrick   __int128_t abs_a = (a ^ sa) - sa;
4046035553Spatrick   __int128_t sb = b >> (N - 1);
4146035553Spatrick   __int128_t abs_b = (b ^ sb) - sb;
4246035553Spatrick   if (abs_a < 2 || abs_b < 2)
4346035553Spatrick     return result;
4446035553Spatrick   if (sa == sb) {
4546035553Spatrick     if (abs_a > MAX / abs_b)
4646035553Spatrick       *overflow = 1;
4746035553Spatrick   } else {
4846035553Spatrick     if (abs_a > MIN / -abs_b)
4946035553Spatrick       *overflow = 1;
5046035553Spatrick   }
5146035553Spatrick   return result;
5246035553Spatrick }
5346035553Spatrick 
5446035553Spatrick #endif
55