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 
ARM_EABI_FNALIAS(uidiv,udivsi3)21 ARM_EABI_FNALIAS(uidiv, udivsi3)
22 
23 /* This function should not call __divsi3! */
24 COMPILER_RT_ABI su_int
25 __udivsi3(su_int n, su_int d)
26 {
27     const unsigned n_uword_bits = sizeof(su_int) * CHAR_BIT;
28     su_int q;
29     su_int r;
30     unsigned sr;
31     /* special cases */
32     if (d == 0)
33         return 0; /* ?! */
34     if (n == 0)
35         return 0;
36     sr = __builtin_clz(d) - __builtin_clz(n);
37     /* 0 <= sr <= n_uword_bits - 1 or sr large */
38     if (sr > n_uword_bits - 1)  /* d > r */
39         return 0;
40     if (sr == n_uword_bits - 1)  /* d == 1 */
41         return n;
42     ++sr;
43     /* 1 <= sr <= n_uword_bits - 1 */
44     /* Not a special case */
45     q = n << (n_uword_bits - sr);
46     r = n >> sr;
47     su_int carry = 0;
48     for (; sr > 0; --sr)
49     {
50         /* r:q = ((r:q)  << 1) | carry */
51         r = (r << 1) | (q >> (n_uword_bits - 1));
52         q = (q << 1) | carry;
53         /* carry = 0;
54          * if (r.all >= d.all)
55          * {
56          *      r.all -= d.all;
57          *      carry = 1;
58          * }
59          */
60         const si_int s = (si_int)(d - r - 1) >> (n_uword_bits - 1);
61         carry = s & 1;
62         r -= d & s;
63     }
64     q = (q << 1) | carry;
65     return q;
66 }
67