1 //===-- mulvti3.c - Implement __mulvti3 -----------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements __mulvti3 for the compiler_rt library.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "int_lib.h"
14 
15 #ifdef CRT_HAS_128BIT
16 
17 // Returns: a * b
18 
19 // Effects: aborts if a * b overflows
20 
21 COMPILER_RT_ABI ti_int __mulvti3(ti_int a, ti_int b) {
22   const int N = (int)(sizeof(ti_int) * CHAR_BIT);
23   const ti_int MIN = (ti_int)1 << (N - 1);
24   const ti_int MAX = ~MIN;
25   if (a == MIN) {
26     if (b == 0 || b == 1)
27       return a * b;
28     compilerrt_abort();
29   }
30   if (b == MIN) {
31     if (a == 0 || a == 1)
32       return a * b;
33     compilerrt_abort();
34   }
35   ti_int sa = a >> (N - 1);
36   ti_int abs_a = (a ^ sa) - sa;
37   ti_int sb = b >> (N - 1);
38   ti_int abs_b = (b ^ sb) - sb;
39   if (abs_a < 2 || abs_b < 2)
40     return a * b;
41   if (sa == sb) {
42     if (abs_a > MAX / abs_b)
43       compilerrt_abort();
44   } else {
45     if (abs_a > MIN / -abs_b)
46       compilerrt_abort();
47   }
48   return a * b;
49 }
50 
51 #endif // CRT_HAS_128BIT
52