xref: /freebsd/contrib/llvm-project/compiler-rt/lib/builtins/divmodsi4.c (revision 5f757f3ff9144b609b3c433dfd370cc6bdc191ad)
10b57cec5SDimitry Andric //===-- divmodsi4.c - Implement __divmodsi4
20b57cec5SDimitry Andric //--------------------------------===//
30b57cec5SDimitry Andric //
40b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
50b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
60b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
70b57cec5SDimitry Andric //
80b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
90b57cec5SDimitry Andric //
100b57cec5SDimitry Andric // This file implements __divmodsi4 for the compiler_rt library.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "int_lib.h"
150b57cec5SDimitry Andric 
160b57cec5SDimitry Andric // Returns: a / b, *rem = a % b
170b57cec5SDimitry Andric 
180b57cec5SDimitry Andric COMPILER_RT_ABI si_int __divmodsi4(si_int a, si_int b, si_int *rem) {
19e8d8bef9SDimitry Andric   const int bits_in_word_m1 = (int)(sizeof(si_int) * CHAR_BIT) - 1;
20e8d8bef9SDimitry Andric   si_int s_a = a >> bits_in_word_m1;                    // s_a = a < 0 ? -1 : 0
21e8d8bef9SDimitry Andric   si_int s_b = b >> bits_in_word_m1;                    // s_b = b < 0 ? -1 : 0
22*5f757f3fSDimitry Andric   a = (su_int)(a ^ s_a) - s_a;                          // negate if s_a == -1
23*5f757f3fSDimitry Andric   b = (su_int)(b ^ s_b) - s_b;                          // negate if s_b == -1
24e8d8bef9SDimitry Andric   s_b ^= s_a;                                           // sign of quotient
25e8d8bef9SDimitry Andric   su_int r;
26e8d8bef9SDimitry Andric   si_int q = (__udivmodsi4(a, b, &r) ^ s_b) - s_b;      // negate if s_b == -1
27e8d8bef9SDimitry Andric   *rem = (r ^ s_a) - s_a;                               // negate if s_a == -1
28e8d8bef9SDimitry Andric   return q;
290b57cec5SDimitry Andric }
30