]> CyberLeo.Net >> Repos - FreeBSD/releng/9.2.git/blob - contrib/compiler-rt/lib/udivsi3.c
- Copy stable/9 to releng/9.2 as part of the 9.2-RELEASE cycle.
[FreeBSD/releng/9.2.git] / contrib / compiler-rt / lib / udivsi3.c
1 /* ===-- udivsi3.c - Implement __udivsi3 -----------------------------------===
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 __udivsi3 for the compiler_rt library.
11  *
12  * ===----------------------------------------------------------------------===
13  */
14
15 #include "int_lib.h"
16
17 /* Returns: a / b */
18
19 /* Translated from Figure 3-40 of The PowerPC Compiler Writer's Guide */
20
21 ARM_EABI_FNALIAS(uidiv, udivsi3);
22
23 COMPILER_RT_ABI su_int
24 __udivsi3(su_int n, su_int d)
25 {
26     const unsigned n_uword_bits = sizeof(su_int) * CHAR_BIT;
27     su_int q;
28     su_int r;
29     unsigned sr;
30     /* special cases */
31     if (d == 0)
32         return 0; /* ?! */
33     if (n == 0)
34         return 0;
35     sr = __builtin_clz(d) - __builtin_clz(n);
36     /* 0 <= sr <= n_uword_bits - 1 or sr large */
37     if (sr > n_uword_bits - 1)  /* d > r */
38         return 0;
39     if (sr == n_uword_bits - 1)  /* d == 1 */
40         return n;
41     ++sr;
42     /* 1 <= sr <= n_uword_bits - 1 */
43     /* Not a special case */
44     q = n << (n_uword_bits - sr);
45     r = n >> sr;
46     su_int carry = 0;
47     for (; sr > 0; --sr)
48     {
49         /* r:q = ((r:q)  << 1) | carry */
50         r = (r << 1) | (q >> (n_uword_bits - 1));
51         q = (q << 1) | carry;
52         /* carry = 0;
53          * if (r.all >= d.all)
54          * {
55          *      r.all -= d.all;
56          *      carry = 1;
57          * }
58          */
59         const si_int s = (si_int)(d - r - 1) >> (n_uword_bits - 1);
60         carry = s & 1;
61         r -= d & s;
62     }
63     q = (q << 1) | carry;
64     return q;
65 }