2 * 128-bit division and remainder for compilers not supporting __int128
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "qemu/osdep.h"
26 #include "qemu/host-utils.h"
27 #include "qemu/int128.h"
32 * Division and remainder algorithms for 128-bit due to Stefan Kanthak,
33 * https://skanthak.homepage.t-online.de/integer.html#udivmodti4
35 * - function should never be called with v equals to 0, it has to
36 * be dealt with beforehand
37 * - quotien pointer must be valid
39 static Int128 divrem128(Int128 u, Int128 v, Int128 *q)
46 /* we have uu÷0v => let's use divu128 */
49 tmp = divu128(&lo, &hi, v.lo);
50 *q = int128_make128(lo, hi);
51 return int128_make128(tmp, 0);
53 hi = int128_gethi(int128_lshift(v, s));
58 divu128(&lo, &tmp, hi);
59 lo = int128_gethi(int128_lshift(int128_make128(lo, 0), s));
60 } else { /* prevent overflow */
63 divu128(&lo, &tmp, hi);
64 lo = int128_gethi(int128_lshift(int128_make128(lo, 1), s));
67 qq = int128_make64(lo);
70 mulu64(&lo, &hi, lo, v.lo);
73 if (hi < tmp /* quotient * divisor >= 2**128 > dividend */
74 || hi > u.hi /* quotient * divisor > dividend */
75 || (hi == u.hi && lo > u.lo)) {
77 mulu64(&lo, &hi, qq.lo, v.lo);
82 u.hi -= hi + (u.lo < lo);
88 Int128 int128_divu(Int128 a, Int128 b)
95 Int128 int128_remu(Int128 a, Int128 b)
98 return divrem128(a, b, &q);
101 Int128 int128_divs(Int128 a, Int128 b)
104 bool sgna = !int128_nonneg(a);
105 bool sgnb = !int128_nonneg(b);
124 Int128 int128_rems(Int128 a, Int128 b)
127 bool sgna = !int128_nonneg(a);
128 bool sgnb = !int128_nonneg(b);
138 r = divrem128(a, b, &q);