xref: /openbmc/qemu/libdecnumber/dpd/decimal32.c (revision 1721fe75df1cbabf2665a2b76a6e7b5bc0fc036b)
1 /* Decimal 32-bit format module for the decNumber C Library.
2    Copyright (C) 2005, 2007 Free Software Foundation, Inc.
3    Contributed by IBM Corporation.  Author Mike Cowlishaw.
4 
5    This file is part of GCC.
6 
7    GCC is free software; you can redistribute it and/or modify it under
8    the terms of the GNU General Public License as published by the Free
9    Software Foundation; either version 2, or (at your option) any later
10    version.
11 
12    In addition to the permissions in the GNU General Public License,
13    the Free Software Foundation gives you unlimited permission to link
14    the compiled version of this file into combinations with other
15    programs, and to distribute those combinations without any
16    restriction coming from the use of this file.  (The General Public
17    License restrictions do apply in other respects; for example, they
18    cover modification of the file, and distribution when not linked
19    into a combine executable.)
20 
21    GCC is distributed in the hope that it will be useful, but WITHOUT ANY
22    WARRANTY; without even the implied warranty of MERCHANTABILITY or
23    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
24    for more details.
25 
26    You should have received a copy of the GNU General Public License
27    along with GCC; see the file COPYING.  If not, see
28    <https://www.gnu.org/licenses/>.  */
29 
30 /* ------------------------------------------------------------------ */
31 /* Decimal 32-bit format module					      */
32 /* ------------------------------------------------------------------ */
33 /* This module comprises the routines for decimal32 format numbers.   */
34 /* Conversions are supplied to and from decNumber and String.	      */
35 /*								      */
36 /* This is used when decNumber provides operations, either for all    */
37 /* operations or as a proxy between decNumber and decSingle.	      */
38 /*								      */
39 /* Error handling is the same as decNumber (qv.).		      */
40 /* ------------------------------------------------------------------ */
41 #include "qemu/osdep.h"
42 
43 #include "libdecnumber/dconfig.h"
44 #define	 DECNUMDIGITS  7      /* make decNumbers with space for 7 */
45 #include "libdecnumber/decNumber.h"
46 #include "libdecnumber/decNumberLocal.h"
47 #include "libdecnumber/dpd/decimal32.h"
48 
49 /* Utility tables and routines [in decimal64.c] */
50 extern const uInt   COMBEXP[32], COMBMSD[32];
51 extern const uByte  BIN2CHAR[4001];
52 
53 extern void decDigitsToDPD(const decNumber *, uInt *, Int);
54 extern void decDigitsFromDPD(decNumber *, const uInt *, Int);
55 
56 #if DECTRACE || DECCHECK
57 void decimal32Show(const decimal32 *);		  /* for debug */
58 extern void decNumberShow(const decNumber *);	  /* .. */
59 #endif
60 
61 /* Useful macro */
62 /* Clear a structure (e.g., a decNumber) */
63 #define DEC_clear(d) memset(d, 0, sizeof(*d))
64 
65 /* ------------------------------------------------------------------ */
66 /* decimal32FromNumber -- convert decNumber to decimal32	      */
67 /*								      */
68 /*   ds is the target decimal32					      */
69 /*   dn is the source number (assumed valid)			      */
70 /*   set is the context, used only for reporting errors		      */
71 /*								      */
72 /* The set argument is used only for status reporting and for the     */
73 /* rounding mode (used if the coefficient is more than DECIMAL32_Pmax */
74 /* digits or an overflow is detected).	If the exponent is out of the */
75 /* valid range then Overflow or Underflow will be raised.	      */
76 /* After Underflow a subnormal result is possible.		      */
77 /*								      */
78 /* DEC_Clamped is set if the number has to be 'folded down' to fit,   */
79 /* by reducing its exponent and multiplying the coefficient by a      */
80 /* power of ten, or if the exponent on a zero had to be clamped.      */
81 /* ------------------------------------------------------------------ */
decimal32FromNumber(decimal32 * d32,const decNumber * dn,decContext * set)82 decimal32 * decimal32FromNumber(decimal32 *d32, const decNumber *dn,
83 			      decContext *set) {
84   uInt status=0;		   /* status accumulator */
85   Int ae;			   /* adjusted exponent */
86   decNumber  dw;		   /* work */
87   decContext dc;		   /* .. */
88   uInt *pu;			   /* .. */
89   uInt comb, exp;		   /* .. */
90   uInt targ=0;			   /* target 32-bit */
91 
92   /* If the number has too many digits, or the exponent could be */
93   /* out of range then reduce the number under the appropriate */
94   /* constraints.  This could push the number to Infinity or zero, */
95   /* so this check and rounding must be done before generating the */
96   /* decimal32] */
97   ae=dn->exponent+dn->digits-1;		     /* [0 if special] */
98   if (dn->digits>DECIMAL32_Pmax		     /* too many digits */
99    || ae>DECIMAL32_Emax			     /* likely overflow */
100    || ae<DECIMAL32_Emin) {		     /* likely underflow */
101     decContextDefault(&dc, DEC_INIT_DECIMAL32); /* [no traps] */
102     dc.round=set->round;		     /* use supplied rounding */
103     decNumberPlus(&dw, dn, &dc);	     /* (round and check) */
104     /* [this changes -0 to 0, so enforce the sign...] */
105     dw.bits|=dn->bits&DECNEG;
106     status=dc.status;			     /* save status */
107     dn=&dw;				     /* use the work number */
108     } /* maybe out of range */
109 
110   if (dn->bits&DECSPECIAL) {			  /* a special value */
111     if (dn->bits&DECINF) targ=DECIMAL_Inf<<24;
112      else {					  /* sNaN or qNaN */
113       if ((*dn->lsu!=0 || dn->digits>1)		  /* non-zero coefficient */
114        && (dn->digits<DECIMAL32_Pmax)) {	  /* coefficient fits */
115 	decDigitsToDPD(dn, &targ, 0);
116 	}
117       if (dn->bits&DECNAN) targ|=DECIMAL_NaN<<24;
118        else targ|=DECIMAL_sNaN<<24;
119       } /* a NaN */
120     } /* special */
121 
122    else { /* is finite */
123     if (decNumberIsZero(dn)) {		     /* is a zero */
124       /* set and clamp exponent */
125       if (dn->exponent<-DECIMAL32_Bias) {
126 	exp=0;				     /* low clamp */
127 	status|=DEC_Clamped;
128 	}
129        else {
130 	exp=dn->exponent+DECIMAL32_Bias;     /* bias exponent */
131 	if (exp>DECIMAL32_Ehigh) {	     /* top clamp */
132 	  exp=DECIMAL32_Ehigh;
133 	  status|=DEC_Clamped;
134 	  }
135 	}
136       comb=(exp>>3) & 0x18;		/* msd=0, exp top 2 bits .. */
137       }
138      else {				/* non-zero finite number */
139       uInt msd;				/* work */
140       Int pad=0;			/* coefficient pad digits */
141 
142       /* the dn is known to fit, but it may need to be padded */
143       exp=(uInt)(dn->exponent+DECIMAL32_Bias);	  /* bias exponent */
144       if (exp>DECIMAL32_Ehigh) {		  /* fold-down case */
145 	pad=exp-DECIMAL32_Ehigh;
146 	exp=DECIMAL32_Ehigh;			  /* [to maximum] */
147 	status|=DEC_Clamped;
148 	}
149 
150       /* fastpath common case */
151       if (DECDPUN==3 && pad==0) {
152 	targ=BIN2DPD[dn->lsu[0]];
153 	if (dn->digits>3) targ|=(uInt)(BIN2DPD[dn->lsu[1]])<<10;
154 	msd=(dn->digits==7 ? dn->lsu[2] : 0);
155 	}
156        else { /* general case */
157 	decDigitsToDPD(dn, &targ, pad);
158 	/* save and clear the top digit */
159 	msd=targ>>20;
160 	targ&=0x000fffff;
161 	}
162 
163       /* create the combination field */
164       if (msd>=8) comb=0x18 | ((exp>>5) & 0x06) | (msd & 0x01);
165 	     else comb=((exp>>3) & 0x18) | msd;
166       }
167     targ|=comb<<26;		   /* add combination field .. */
168     targ|=(exp&0x3f)<<20;	   /* .. and exponent continuation */
169     } /* finite */
170 
171   if (dn->bits&DECNEG) targ|=0x80000000;  /* add sign bit */
172 
173   /* now write to storage; this is endian */
174   pu=(uInt *)d32->bytes;	   /* overlay */
175   *pu=targ;			   /* directly store the int */
176 
177   if (status!=0) decContextSetStatus(set, status); /* pass on status */
178   /* decimal32Show(d32); */
179   return d32;
180   } /* decimal32FromNumber */
181 
182 /* ------------------------------------------------------------------ */
183 /* decimal32ToNumber -- convert decimal32 to decNumber		      */
184 /*   d32 is the source decimal32				      */
185 /*   dn is the target number, with appropriate space		      */
186 /* No error is possible.					      */
187 /* ------------------------------------------------------------------ */
decimal32ToNumber(const decimal32 * d32,decNumber * dn)188 decNumber * decimal32ToNumber(const decimal32 *d32, decNumber *dn) {
189   uInt msd;			   /* coefficient MSD */
190   uInt exp;			   /* exponent top two bits */
191   uInt comb;			   /* combination field */
192   uInt sour;			   /* source 32-bit */
193   const uInt *pu;		   /* work */
194 
195   /* load source from storage; this is endian */
196   pu=(const uInt *)d32->bytes;	   /* overlay */
197   sour=*pu;			   /* directly load the int */
198 
199   comb=(sour>>26)&0x1f;		   /* combination field */
200 
201   decNumberZero(dn);		   /* clean number */
202   if (sour&0x80000000) dn->bits=DECNEG; /* set sign if negative */
203 
204   msd=COMBMSD[comb];		   /* decode the combination field */
205   exp=COMBEXP[comb];		   /* .. */
206 
207   if (exp==3) {			   /* is a special */
208     if (msd==0) {
209       dn->bits|=DECINF;
210       return dn;		   /* no coefficient needed */
211       }
212     else if (sour&0x02000000) dn->bits|=DECSNAN;
213     else dn->bits|=DECNAN;
214     msd=0;			   /* no top digit */
215     }
216    else {			   /* is a finite number */
217     dn->exponent=(exp<<6)+((sour>>20)&0x3f)-DECIMAL32_Bias; /* unbiased */
218     }
219 
220   /* get the coefficient */
221   sour&=0x000fffff;		   /* clean coefficient continuation */
222   if (msd) {			   /* non-zero msd */
223     sour|=msd<<20;		   /* prefix to coefficient */
224     decDigitsFromDPD(dn, &sour, 3); /* process 3 declets */
225     return dn;
226     }
227   /* msd=0 */
228   if (!sour) return dn;		   /* easy: coefficient is 0 */
229   if (sour&0x000ffc00)		   /* need 2 declets? */
230     decDigitsFromDPD(dn, &sour, 2); /* process 2 declets */
231    else
232     decDigitsFromDPD(dn, &sour, 1); /* process 1 declet */
233   return dn;
234   } /* decimal32ToNumber */
235 
236 /* ------------------------------------------------------------------ */
237 /* to-scientific-string -- conversion to numeric string		      */
238 /* to-engineering-string -- conversion to numeric string	      */
239 /*								      */
240 /*   decimal32ToString(d32, string);				      */
241 /*   decimal32ToEngString(d32, string);				      */
242 /*								      */
243 /*  d32 is the decimal32 format number to convert		      */
244 /*  string is the string where the result will be laid out	      */
245 /*								      */
246 /*  string must be at least 24 characters			      */
247 /*								      */
248 /*  No error is possible, and no status can be set.		      */
249 /* ------------------------------------------------------------------ */
decimal32ToEngString(const decimal32 * d32,char * string)250 char * decimal32ToEngString(const decimal32 *d32, char *string){
251   decNumber dn;				/* work */
252   decimal32ToNumber(d32, &dn);
253   decNumberToEngString(&dn, string);
254   return string;
255   } /* decimal32ToEngString */
256 
decimal32ToString(const decimal32 * d32,char * string)257 char * decimal32ToString(const decimal32 *d32, char *string){
258   uInt msd;			   /* coefficient MSD */
259   Int  exp;			   /* exponent top two bits or full */
260   uInt comb;			   /* combination field */
261   char *cstart;			   /* coefficient start */
262   char *c;			   /* output pointer in string */
263   const uInt *pu;		   /* work */
264   const uByte *u;		   /* .. */
265   char *s, *t;			   /* .. (source, target) */
266   Int  dpd;			   /* .. */
267   Int  pre, e;			   /* .. */
268   uInt sour;			   /* source 32-bit */
269 
270   /* load source from storage; this is endian */
271   pu=(const uInt *)d32->bytes;	   /* overlay */
272   sour=*pu;			   /* directly load the int */
273 
274   c=string;			   /* where result will go */
275   if (((Int)sour)<0) *c++='-';	   /* handle sign */
276 
277   comb=(sour>>26)&0x1f;		   /* combination field */
278   msd=COMBMSD[comb];		   /* decode the combination field */
279   exp=COMBEXP[comb];		   /* .. */
280 
281   if (exp==3) {
282     if (msd==0) {		   /* infinity */
283       strcpy(c,	  "Inf");
284       strcpy(c+3, "inity");
285       return string;		   /* easy */
286       }
287     if (sour&0x02000000) *c++='s'; /* sNaN */
288     strcpy(c, "NaN");		   /* complete word */
289     c+=3;			   /* step past */
290     if ((sour&0x000fffff)==0) return string; /* zero payload */
291     /* otherwise drop through to add integer; set correct exp */
292     exp=0; msd=0;		   /* setup for following code */
293     }
294    else exp=(exp<<6)+((sour>>20)&0x3f)-DECIMAL32_Bias; /* unbiased */
295 
296   /* convert 7 digits of significand to characters */
297   cstart=c;			   /* save start of coefficient */
298   if (msd) *c++='0'+(char)msd;	   /* non-zero most significant digit */
299 
300   /* Now decode the declets.  After extracting each one, it is */
301   /* decoded to binary and then to a 4-char sequence by table lookup; */
302   /* the 4-chars are a 1-char length (significant digits, except 000 */
303   /* has length 0).  This allows us to left-align the first declet */
304   /* with non-zero content, then remaining ones are full 3-char */
305   /* length.  We use fixed-length memcpys because variable-length */
306   /* causes a subroutine call in GCC.  (These are length 4 for speed */
307   /* and are safe because the array has an extra terminator byte.) */
308   #define dpd2char u=&BIN2CHAR[DPD2BIN[dpd]*4];			  \
309 		   if (c!=cstart) {memcpy(c, u+1, 4); c+=3;}	  \
310 		    else if (*u)  {memcpy(c, u+4-*u, 4); c+=*u;}
311 
312   dpd=(sour>>10)&0x3ff;		   /* declet 1 */
313   dpd2char;
314   dpd=(sour)&0x3ff;		   /* declet 2 */
315   dpd2char;
316 
317   if (c==cstart) *c++='0';	   /* all zeros -- make 0 */
318 
319   if (exp==0) {			   /* integer or NaN case -- easy */
320     *c='\0';			   /* terminate */
321     return string;
322     }
323 
324   /* non-0 exponent */
325   e=0;				   /* assume no E */
326   pre=c-cstart+exp;
327   /* [here, pre-exp is the digits count (==1 for zero)] */
328   if (exp>0 || pre<-5) {	   /* need exponential form */
329     e=pre-1;			   /* calculate E value */
330     pre=1;			   /* assume one digit before '.' */
331     } /* exponential form */
332 
333   /* modify the coefficient, adding 0s, '.', and E+nn as needed */
334   s=c-1;			   /* source (LSD) */
335   if (pre>0) {			   /* ddd.ddd (plain), perhaps with E */
336     char *dotat=cstart+pre;
337     if (dotat<c) {		   /* if embedded dot needed... */
338       t=c;				/* target */
339       for (; s>=dotat; s--, t--) *t=*s; /* open the gap; leave t at gap */
340       *t='.';				/* insert the dot */
341       c++;				/* length increased by one */
342       }
343 
344     /* finally add the E-part, if needed; it will never be 0, and has */
345     /* a maximum length of 3 digits (E-101 case) */
346     if (e!=0) {
347       *c++='E';			   /* starts with E */
348       *c++='+';			   /* assume positive */
349       if (e<0) {
350 	*(c-1)='-';		   /* oops, need '-' */
351 	e=-e;			   /* uInt, please */
352 	}
353       u=&BIN2CHAR[e*4];		   /* -> length byte */
354       memcpy(c, u+4-*u, 4);	   /* copy fixed 4 characters [is safe] */
355       c+=*u;			   /* bump pointer appropriately */
356       }
357     *c='\0';			   /* add terminator */
358     /*printf("res %s\n", string); */
359     return string;
360     } /* pre>0 */
361 
362   /* -5<=pre<=0: here for plain 0.ddd or 0.000ddd forms (can never have E) */
363   t=c+1-pre;
364   *(t+1)='\0';				/* can add terminator now */
365   for (; s>=cstart; s--, t--) *t=*s;	/* shift whole coefficient right */
366   c=cstart;
367   *c++='0';				/* always starts with 0. */
368   *c++='.';
369   for (; pre<0; pre++) *c++='0';	/* add any 0's after '.' */
370   /*printf("res %s\n", string); */
371   return string;
372   } /* decimal32ToString */
373 
374 /* ------------------------------------------------------------------ */
375 /* to-number -- conversion from numeric string			      */
376 /*								      */
377 /*   decimal32FromString(result, string, set);			      */
378 /*								      */
379 /*  result  is the decimal32 format number which gets the result of   */
380 /*	    the conversion					      */
381 /*  *string is the character string which should contain a valid      */
382 /*	    number (which may be a special value)		      */
383 /*  set	    is the context					      */
384 /*								      */
385 /* The context is supplied to this routine is used for error handling */
386 /* (setting of status and traps) and for the rounding mode, only.     */
387 /* If an error occurs, the result will be a valid decimal32 NaN.      */
388 /* ------------------------------------------------------------------ */
decimal32FromString(decimal32 * result,const char * string,decContext * set)389 decimal32 * decimal32FromString(decimal32 *result, const char *string,
390 				decContext *set) {
391   decContext dc;			     /* work */
392   decNumber dn;				     /* .. */
393 
394   decContextDefault(&dc, DEC_INIT_DECIMAL32); /* no traps, please */
395   dc.round=set->round;			      /* use supplied rounding */
396 
397   decNumberFromString(&dn, string, &dc);     /* will round if needed */
398   decimal32FromNumber(result, &dn, &dc);
399   if (dc.status!=0) {			     /* something happened */
400     decContextSetStatus(set, dc.status);     /* .. pass it on */
401     }
402   return result;
403   } /* decimal32FromString */
404 
405 /* ------------------------------------------------------------------ */
406 /* decimal32IsCanonical -- test whether encoding is canonical	      */
407 /*   d32 is the source decimal32				      */
408 /*   returns 1 if the encoding of d32 is canonical, 0 otherwise	      */
409 /* No error is possible.					      */
410 /* ------------------------------------------------------------------ */
decimal32IsCanonical(const decimal32 * d32)411 uint32_t decimal32IsCanonical(const decimal32 *d32) {
412   decNumber dn;				/* work */
413   decimal32 canon;			/* .. */
414   decContext dc;			/* .. */
415   decContextDefault(&dc, DEC_INIT_DECIMAL32);
416   decimal32ToNumber(d32, &dn);
417   decimal32FromNumber(&canon, &dn, &dc);/* canon will now be canonical */
418   return memcmp(d32, &canon, DECIMAL32_Bytes)==0;
419   } /* decimal32IsCanonical */
420 
421 /* ------------------------------------------------------------------ */
422 /* decimal32Canonical -- copy an encoding, ensuring it is canonical   */
423 /*   d32 is the source decimal32				      */
424 /*   result is the target (may be the same decimal32)		      */
425 /*   returns result						      */
426 /* No error is possible.					      */
427 /* ------------------------------------------------------------------ */
decimal32Canonical(decimal32 * result,const decimal32 * d32)428 decimal32 * decimal32Canonical(decimal32 *result, const decimal32 *d32) {
429   decNumber dn;				/* work */
430   decContext dc;			/* .. */
431   decContextDefault(&dc, DEC_INIT_DECIMAL32);
432   decimal32ToNumber(d32, &dn);
433   decimal32FromNumber(result, &dn, &dc);/* result will now be canonical */
434   return result;
435   } /* decimal32Canonical */
436 
437 #if DECTRACE || DECCHECK
438 /* Macros for accessing decimal32 fields.  These assume the argument
439    is a reference (pointer) to the decimal32 structure, and the
440    decimal32 is in network byte order (big-endian) */
441 /* Get sign */
442 #define decimal32Sign(d)       ((unsigned)(d)->bytes[0]>>7)
443 
444 /* Get combination field */
445 #define decimal32Comb(d)       (((d)->bytes[0] & 0x7c)>>2)
446 
447 /* Get exponent continuation [does not remove bias] */
448 #define decimal32ExpCon(d)     ((((d)->bytes[0] & 0x03)<<4)	      \
449 			     | ((unsigned)(d)->bytes[1]>>4))
450 
451 /* Set sign [this assumes sign previously 0] */
452 #define decimal32SetSign(d, b) {				      \
453   (d)->bytes[0]|=((unsigned)(b)<<7);}
454 
455 /* Set exponent continuation [does not apply bias] */
456 /* This assumes range has been checked and exponent previously 0; */
457 /* type of exponent must be unsigned */
458 #define decimal32SetExpCon(d, e) {				      \
459   (d)->bytes[0]|=(uint8_t)((e)>>4);				      \
460   (d)->bytes[1]|=(uint8_t)(((e)&0x0F)<<4);}
461 
462 /* ------------------------------------------------------------------ */
463 /* decimal32Show -- display a decimal32 in hexadecimal [debug aid]    */
464 /*   d32 -- the number to show					      */
465 /* ------------------------------------------------------------------ */
466 /* Also shows sign/cob/expconfields extracted - valid bigendian only */
decimal32Show(const decimal32 * d32)467 void decimal32Show(const decimal32 *d32) {
468   char buf[DECIMAL32_Bytes*2+1];
469   Int i, j=0;
470 
471   if (DECLITEND) {
472     for (i=0; i<DECIMAL32_Bytes; i++, j+=2) {
473       sprintf(&buf[j], "%02x", d32->bytes[3-i]);
474       }
475     printf(" D32> %s [S:%d Cb:%02x Ec:%02x] LittleEndian\n", buf,
476 	   d32->bytes[3]>>7, (d32->bytes[3]>>2)&0x1f,
477 	   ((d32->bytes[3]&0x3)<<4)| (d32->bytes[2]>>4));
478     }
479    else {
480     for (i=0; i<DECIMAL32_Bytes; i++, j+=2) {
481       sprintf(&buf[j], "%02x", d32->bytes[i]);
482       }
483     printf(" D32> %s [S:%d Cb:%02x Ec:%02x] BigEndian\n", buf,
484 	   decimal32Sign(d32), decimal32Comb(d32), decimal32ExpCon(d32));
485     }
486   } /* decimal32Show */
487 #endif
488