Eric Fiselier | 1e1f8ec | 2018-07-26 00:34:50 +0000 | [diff] [blame] | 1 | /*===-- int128_builtins.cpp - Implement __muloti4 --------------------------=== |
| 2 | * |
| 3 | * The LLVM Compiler Infrastructure |
| 4 | * |
| 5 | * This file is dual licensed under the MIT and the University of Illinois Open |
| 6 | * Source Licenses. See LICENSE.TXT for details. |
| 7 | * |
| 8 | * ===----------------------------------------------------------------------=== |
| 9 | * |
| 10 | * This file implements __muloti4, and is stolen from the compiler_rt library. |
| 11 | * |
| 12 | * FIXME: we steal and re-compile it into filesystem, which uses __int128_t, |
| 13 | * and requires this builtin when sanitized. See llvm.org/PR30643 |
| 14 | * |
| 15 | * ===----------------------------------------------------------------------=== |
| 16 | */ |
| 17 | #include "__config" |
| 18 | #include "climits" |
| 19 | |
Eric Fiselier | 998a5c8 | 2018-07-27 03:07:09 +0000 | [diff] [blame] | 20 | #if !defined(_LIBCPP_HAS_NO_INT128) |
Eric Fiselier | 1e1f8ec | 2018-07-26 00:34:50 +0000 | [diff] [blame] | 21 | |
Eric Fiselier | f74c546 | 2018-07-26 03:36:37 +0000 | [diff] [blame] | 22 | extern "C" __attribute__((no_sanitize("undefined"))) |
| 23 | __int128_t __muloti4(__int128_t a, __int128_t b, int* overflow) { |
Eric Fiselier | 1e1f8ec | 2018-07-26 00:34:50 +0000 | [diff] [blame] | 24 | const int N = (int)(sizeof(__int128_t) * CHAR_BIT); |
| 25 | const __int128_t MIN = (__int128_t)1 << (N - 1); |
| 26 | const __int128_t MAX = ~MIN; |
| 27 | *overflow = 0; |
| 28 | __int128_t result = a * b; |
| 29 | if (a == MIN) { |
| 30 | if (b != 0 && b != 1) |
| 31 | *overflow = 1; |
| 32 | return result; |
| 33 | } |
| 34 | if (b == MIN) { |
| 35 | if (a != 0 && a != 1) |
| 36 | *overflow = 1; |
| 37 | return result; |
| 38 | } |
| 39 | __int128_t sa = a >> (N - 1); |
| 40 | __int128_t abs_a = (a ^ sa) - sa; |
| 41 | __int128_t sb = b >> (N - 1); |
| 42 | __int128_t abs_b = (b ^ sb) - sb; |
| 43 | if (abs_a < 2 || abs_b < 2) |
| 44 | return result; |
| 45 | if (sa == sb) { |
| 46 | if (abs_a > MAX / abs_b) |
| 47 | *overflow = 1; |
| 48 | } else { |
| 49 | if (abs_a > MIN / -abs_b) |
| 50 | *overflow = 1; |
| 51 | } |
| 52 | return result; |
| 53 | } |
| 54 | |
| 55 | #endif |