blob: b4a509be2093a54ca160df1df00667efd923566e [file] [log] [blame]
Edward O'Callaghan1fcb40b2009-08-05 19:06:50 +00001/* ===-- mulvsi3.c - Implement __mulvsi3 -----------------------------------===
2 *
3 * The LLVM Compiler Infrastructure
4 *
5 * This file is distributed under the University of Illinois Open Source
6 * License. See LICENSE.TXT for details.
7 *
8 * ===----------------------------------------------------------------------===
9 *
10 * This file implements __mulvsi3 for the compiler_rt library.
11 *
12 * ===----------------------------------------------------------------------===
13 */
Daniel Dunbarb3a69012009-06-26 16:47:03 +000014
15#include "int_lib.h"
16#include <stdlib.h>
17
Edward O'Callaghan1fcb40b2009-08-05 19:06:50 +000018/* Returns: a * b */
Daniel Dunbarb3a69012009-06-26 16:47:03 +000019
Edward O'Callaghan1fcb40b2009-08-05 19:06:50 +000020/* Effects: aborts if a * b overflows */
Daniel Dunbarb3a69012009-06-26 16:47:03 +000021
22si_int
23__mulvsi3(si_int a, si_int b)
24{
25 const int N = (int)(sizeof(si_int) * CHAR_BIT);
26 const si_int MIN = (si_int)1 << (N-1);
27 const si_int MAX = ~MIN;
28 if (a == MIN)
29 {
30 if (b == 0 || b == 1)
31 return a * b;
Daniel Dunbar48f46ac2010-03-31 17:00:45 +000032 compilerrt_abort();
Daniel Dunbarb3a69012009-06-26 16:47:03 +000033 }
34 if (b == MIN)
35 {
36 if (a == 0 || a == 1)
37 return a * b;
Daniel Dunbar48f46ac2010-03-31 17:00:45 +000038 compilerrt_abort();
Daniel Dunbarb3a69012009-06-26 16:47:03 +000039 }
40 si_int sa = a >> (N - 1);
41 si_int abs_a = (a ^ sa) - sa;
42 si_int sb = b >> (N - 1);
43 si_int abs_b = (b ^ sb) - sb;
44 if (abs_a < 2 || abs_b < 2)
45 return a * b;
46 if (sa == sb)
47 {
48 if (abs_a > MAX / abs_b)
Daniel Dunbar48f46ac2010-03-31 17:00:45 +000049 compilerrt_abort();
Daniel Dunbarb3a69012009-06-26 16:47:03 +000050 }
51 else
52 {
53 if (abs_a > MIN / -abs_b)
Daniel Dunbar48f46ac2010-03-31 17:00:45 +000054 compilerrt_abort();
Daniel Dunbarb3a69012009-06-26 16:47:03 +000055 }
56 return a * b;
57}