int128_builtins.cpp revision 336819
1336819Sdim/*===-- int128_builtins.cpp - Implement __muloti4 --------------------------=== 2336819Sdim * 3336819Sdim * The LLVM Compiler Infrastructure 4336819Sdim * 5336819Sdim * This file is dual licensed under the MIT and the University of Illinois Open 6336819Sdim * Source Licenses. See LICENSE.TXT for details. 7336819Sdim * 8336819Sdim * ===----------------------------------------------------------------------=== 9336819Sdim * 10336819Sdim * This file implements __muloti4, and is stolen from the compiler_rt library. 11336819Sdim * 12336819Sdim * FIXME: we steal and re-compile it into filesystem, which uses __int128_t, 13336819Sdim * and requires this builtin when sanitized. See llvm.org/PR30643 14336819Sdim * 15336819Sdim * ===----------------------------------------------------------------------=== 16336819Sdim */ 17336819Sdim#include "__config" 18336819Sdim#include "climits" 19336819Sdim 20336819Sdim#if !defined(_LIBCPP_HAS_NO_INT128) 21336819Sdim 22336819Sdimextern "C" __attribute__((no_sanitize("undefined"))) 23336819Sdim__int128_t __muloti4(__int128_t a, __int128_t b, int* overflow) { 24336819Sdim const int N = (int)(sizeof(__int128_t) * CHAR_BIT); 25336819Sdim const __int128_t MIN = (__int128_t)1 << (N - 1); 26336819Sdim const __int128_t MAX = ~MIN; 27336819Sdim *overflow = 0; 28336819Sdim __int128_t result = a * b; 29336819Sdim if (a == MIN) { 30336819Sdim if (b != 0 && b != 1) 31336819Sdim *overflow = 1; 32336819Sdim return result; 33336819Sdim } 34336819Sdim if (b == MIN) { 35336819Sdim if (a != 0 && a != 1) 36336819Sdim *overflow = 1; 37336819Sdim return result; 38336819Sdim } 39336819Sdim __int128_t sa = a >> (N - 1); 40336819Sdim __int128_t abs_a = (a ^ sa) - sa; 41336819Sdim __int128_t sb = b >> (N - 1); 42336819Sdim __int128_t abs_b = (b ^ sb) - sb; 43336819Sdim if (abs_a < 2 || abs_b < 2) 44336819Sdim return result; 45336819Sdim if (sa == sb) { 46336819Sdim if (abs_a > MAX / abs_b) 47336819Sdim *overflow = 1; 48336819Sdim } else { 49336819Sdim if (abs_a > MIN / -abs_b) 50336819Sdim *overflow = 1; 51336819Sdim } 52336819Sdim return result; 53336819Sdim} 54336819Sdim 55336819Sdim#endif 56