1998a5c88SEric Fiselier /*===-- int128_builtins.cpp - Implement __muloti4 --------------------------=== 2998a5c88SEric Fiselier * 357b08b09SChandler Carruth * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 457b08b09SChandler Carruth * See https://llvm.org/LICENSE.txt for license information. 557b08b09SChandler Carruth * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6998a5c88SEric Fiselier * 7998a5c88SEric Fiselier * ===----------------------------------------------------------------------=== 8998a5c88SEric Fiselier * 9998a5c88SEric Fiselier * This file implements __muloti4, and is stolen from the compiler_rt library. 10998a5c88SEric Fiselier * 11998a5c88SEric Fiselier * FIXME: we steal and re-compile it into filesystem, which uses __int128_t, 12998a5c88SEric Fiselier * and requires this builtin when sanitized. See llvm.org/PR30643 13998a5c88SEric Fiselier * 14998a5c88SEric Fiselier * ===----------------------------------------------------------------------=== 15998a5c88SEric Fiselier */ 16bbb0f2c7SArthur O'Dwyer #include <__config> 17bbb0f2c7SArthur O'Dwyer #include <climits> 18998a5c88SEric Fiselier 19*ba87515fSNikolas Klauser #if _LIBCPP_HAS_INT128 20998a5c88SEric Fiselier 219783f28cSLouis Dionne extern "C" __attribute__((no_sanitize("undefined"))) _LIBCPP_EXPORTED_FROM_ABI __int128_t 229783f28cSLouis Dionne __muloti4(__int128_t a, __int128_t b, int* overflow) { 23998a5c88SEric Fiselier const int N = (int)(sizeof(__int128_t) * CHAR_BIT); 24998a5c88SEric Fiselier const __int128_t MIN = (__int128_t)1 << (N - 1); 25998a5c88SEric Fiselier const __int128_t MAX = ~MIN; 26998a5c88SEric Fiselier *overflow = 0; 27998a5c88SEric Fiselier __int128_t result = a * b; 28998a5c88SEric Fiselier if (a == MIN) { 29998a5c88SEric Fiselier if (b != 0 && b != 1) 30998a5c88SEric Fiselier *overflow = 1; 31998a5c88SEric Fiselier return result; 32998a5c88SEric Fiselier } 33998a5c88SEric Fiselier if (b == MIN) { 34998a5c88SEric Fiselier if (a != 0 && a != 1) 35998a5c88SEric Fiselier *overflow = 1; 36998a5c88SEric Fiselier return result; 37998a5c88SEric Fiselier } 38998a5c88SEric Fiselier __int128_t sa = a >> (N - 1); 39998a5c88SEric Fiselier __int128_t abs_a = (a ^ sa) - sa; 40998a5c88SEric Fiselier __int128_t sb = b >> (N - 1); 41998a5c88SEric Fiselier __int128_t abs_b = (b ^ sb) - sb; 42998a5c88SEric Fiselier if (abs_a < 2 || abs_b < 2) 43998a5c88SEric Fiselier return result; 44998a5c88SEric Fiselier if (sa == sb) { 45998a5c88SEric Fiselier if (abs_a > MAX / abs_b) 46998a5c88SEric Fiselier *overflow = 1; 47998a5c88SEric Fiselier } else { 48998a5c88SEric Fiselier if (abs_a > MIN / -abs_b) 49998a5c88SEric Fiselier *overflow = 1; 50998a5c88SEric Fiselier } 51998a5c88SEric Fiselier return result; 52998a5c88SEric Fiselier } 53998a5c88SEric Fiselier 54998a5c88SEric Fiselier #endif 55