xref: /netbsd-src/external/gpl3/gcc.old/dist/libgcc/config/nios2/lib2-divmod-hi.c (revision 8feb0f0b7eaff0608f8350bbfa3098827b4bb91b)
1 /* Copyright (C) 2012-2020 Free Software Foundation, Inc.
2    Contributed by Altera and Mentor Graphics, Inc.
3 
4 This file is free software; you can redistribute it and/or modify it
5 under the terms of the GNU General Public License as published by the
6 Free Software Foundation; either version 3, or (at your option) any
7 later version.
8 
9 This file is distributed in the hope that it will be useful, but
10 WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 General Public License for more details.
13 
14 Under Section 7 of GPL version 3, you are granted additional
15 permissions described in the GCC Runtime Library Exception, version
16 3.1, as published by the Free Software Foundation.
17 
18 You should have received a copy of the GNU General Public License and
19 a copy of the GCC Runtime Library Exception along with this program;
20 see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
21 <http://www.gnu.org/licenses/>.  */
22 
23 #include "lib2-nios2.h"
24 
25 /* 16-bit HI divide and modulo as used in Nios II.  */
26 
27 static UHItype
udivmodhi4(UHItype num,UHItype den,word_type modwanted)28 udivmodhi4 (UHItype num, UHItype den, word_type modwanted)
29 {
30   UHItype bit = 1;
31   UHItype res = 0;
32 
33   while (den < num && bit && !(den & (1L<<15)))
34     {
35       den <<=1;
36       bit <<=1;
37     }
38   while (bit)
39     {
40       if (num >= den)
41 	{
42 	  num -= den;
43 	  res |= bit;
44 	}
45       bit >>=1;
46       den >>=1;
47     }
48   if (modwanted)
49     return num;
50   return res;
51 }
52 
53 
54 HItype
__divhi3(HItype a,HItype b)55 __divhi3 (HItype a, HItype b)
56 {
57   word_type neg = 0;
58   HItype res;
59 
60   if (a < 0)
61     {
62       a = -a;
63       neg = !neg;
64     }
65 
66   if (b < 0)
67     {
68       b = -b;
69       neg = !neg;
70     }
71 
72   res = udivmodhi4 (a, b, 0);
73 
74   if (neg)
75     res = -res;
76 
77   return res;
78 }
79 
80 
81 HItype
__modhi3(HItype a,HItype b)82 __modhi3 (HItype a, HItype b)
83 {
84   word_type neg = 0;
85   HItype res;
86 
87   if (a < 0)
88     {
89       a = -a;
90       neg = 1;
91     }
92 
93   if (b < 0)
94     b = -b;
95 
96   res = udivmodhi4 (a, b, 1);
97 
98   if (neg)
99     res = -res;
100 
101   return res;
102 }
103 
104 
105 UHItype
__udivhi3(UHItype a,UHItype b)106 __udivhi3 (UHItype a, UHItype b)
107 {
108   return udivmodhi4 (a, b, 0);
109 }
110 
111 
112 UHItype
__umodhi3(UHItype a,UHItype b)113 __umodhi3 (UHItype a, UHItype b)
114 {
115   return udivmodhi4 (a, b, 1);
116 }
117 
118