blob: f58dd074eea904eee48486954175b97f6b28572c [file] [log] [blame]
Eric Christopher1ace4052011-06-17 20:17:05 +00001/*===-- muloti4.c - 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 for the compiler_rt library.
11 *
12 * ===----------------------------------------------------------------------===
13 */
14
Eric Christopher1ace4052011-06-17 20:17:05 +000015#include "int_lib.h"
Eric Christopher1ace4052011-06-17 20:17:05 +000016
Chandler Carruth7f2d7c72012-06-22 21:09:22 +000017#if __x86_64
18
Eric Christopher1ace4052011-06-17 20:17:05 +000019/* Returns: a * b */
20
21/* Effects: sets *overflow to 1 if a * b overflows */
22
23ti_int
24__muloti4(ti_int a, ti_int b, int* overflow)
25{
26 const int N = (int)(sizeof(ti_int) * CHAR_BIT);
27 const ti_int MIN = (ti_int)1 << (N-1);
28 const ti_int MAX = ~MIN;
29 *overflow = 0;
30 ti_int result = a * b;
31 if (a == MIN)
32 {
33 if (b != 0 && b != 1)
34 *overflow = 1;
35 return result;
36 }
37 if (b == MIN)
38 {
39 if (a != 0 && a != 1)
40 *overflow = 1;
41 return result;
42 }
43 ti_int sa = a >> (N - 1);
44 ti_int abs_a = (a ^ sa) - sa;
45 ti_int sb = b >> (N - 1);
46 ti_int abs_b = (b ^ sb) - sb;
47 if (abs_a < 2 || abs_b < 2)
48 return result;
49 if (sa == sb)
50 {
51 if (abs_a > MAX / abs_b)
52 *overflow = 1;
53 }
54 else
55 {
56 if (abs_a > MIN / -abs_b)
57 *overflow = 1;
58 }
59 return result;
60}
61
62#endif