blob: bf1ab04691ce00405d57f77f9fa2148297210966 [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
15#if __x86_64
16
17#include "int_lib.h"
18#include <stdlib.h>
19
20/* Returns: a * b */
21
22/* Effects: sets *overflow to 1 if a * b overflows */
23
24ti_int
25__muloti4(ti_int a, ti_int b, int* overflow)
26{
27 const int N = (int)(sizeof(ti_int) * CHAR_BIT);
28 const ti_int MIN = (ti_int)1 << (N-1);
29 const ti_int MAX = ~MIN;
30 *overflow = 0;
31 ti_int result = a * b;
32 if (a == MIN)
33 {
34 if (b != 0 && b != 1)
35 *overflow = 1;
36 return result;
37 }
38 if (b == MIN)
39 {
40 if (a != 0 && a != 1)
41 *overflow = 1;
42 return result;
43 }
44 ti_int sa = a >> (N - 1);
45 ti_int abs_a = (a ^ sa) - sa;
46 ti_int sb = b >> (N - 1);
47 ti_int abs_b = (b ^ sb) - sb;
48 if (abs_a < 2 || abs_b < 2)
49 return result;
50 if (sa == sb)
51 {
52 if (abs_a > MAX / abs_b)
53 *overflow = 1;
54 }
55 else
56 {
57 if (abs_a > MIN / -abs_b)
58 *overflow = 1;
59 }
60 return result;
61}
62
63#endif