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