blob: 16af2285806e0bc56090238fc30643a3ff7524f9 [file] [log] [blame]
Daniel Dunbarb3a69012009-06-26 16:47:03 +00001//===-- udivsi3.c - Implement __udivsi3 -----------------------------------===//
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 __udivsi3 for the compiler_rt library.
11//
12//===----------------------------------------------------------------------===//
13
14#include "int_lib.h"
15
16// Returns: a / b
17
18// Translated from Figure 3-40 of The PowerPC Compiler Writer's Guide
19
20su_int
21__udivsi3(su_int n, su_int d)
22{
23 const unsigned n_uword_bits = sizeof(su_int) * CHAR_BIT;
24 su_int q;
25 su_int r;
26 unsigned sr;
27 // special cases
28 if (d == 0)
29 return 0; // ?!
30 if (n == 0)
31 return 0;
32 sr = __builtin_clz(d) - __builtin_clz(n);
33 // 0 <= sr <= n_uword_bits - 1 or sr large
34 if (sr > n_uword_bits - 1) // d > r
35 return 0;
36 if (sr == n_uword_bits - 1) // d == 1
37 return n;
38 ++sr;
39 // 1 <= sr <= n_uword_bits - 1
40 // Not a special case
41 q = n << (n_uword_bits - sr);
42 r = n >> sr;
43 su_int carry = 0;
44 for (; sr > 0; --sr)
45 {
46 // r:q = ((r:q) << 1) | carry
47 r = (r << 1) | (q >> (n_uword_bits - 1));
48 q = (q << 1) | carry;
49 // carry = 0;
50 // if (r.all >= d.all)
51 // {
52 // r.all -= d.all;
53 // carry = 1;
54 // }
55 const si_int s = (si_int)(d - r - 1) >> (n_uword_bits - 1);
56 carry = s & 1;
57 r -= d & s;
58 }
59 q = (q << 1) | carry;
60 return q;
61}