Merge -r 127928:132243 from trunk
[official-gcc.git] / libdecnumber / dpd / decimal128.c
blob0e32ceb181c68b654eee6ba47fdfcb16bd0d168a
1 /* Decimal 128-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.
5 This file is part of GCC.
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.
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.)
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.
26 You should have received a copy of the GNU General Public License
27 along with GCC; see the file COPYING. If not, write to the Free
28 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
29 02110-1301, USA. */
31 /* ------------------------------------------------------------------ */
32 /* Decimal 128-bit format module */
33 /* ------------------------------------------------------------------ */
34 /* This module comprises the routines for decimal128 format numbers. */
35 /* Conversions are supplied to and from decNumber and String. */
36 /* */
37 /* This is used when decNumber provides operations, either for all */
38 /* operations or as a proxy between decNumber and decSingle. */
39 /* */
40 /* Error handling is the same as decNumber (qv.). */
41 /* ------------------------------------------------------------------ */
42 #include <string.h> /* [for memset/memcpy] */
43 #include <stdio.h> /* [for printf] */
45 #include "config.h" /* GCC definitions */
46 #define DECNUMDIGITS 34 /* make decNumbers with space for 34 */
47 #include "decNumber.h" /* base number library */
48 #include "decNumberLocal.h" /* decNumber local types, etc. */
49 #include "decimal128.h" /* our primary include */
51 /* Utility routines and tables [in decimal64.c] */
52 extern const uInt COMBEXP[32], COMBMSD[32];
53 extern const uShort DPD2BIN[1024];
54 extern const uShort BIN2DPD[1000]; /* [not used] */
55 extern const uByte BIN2CHAR[4001];
57 extern void decDigitsFromDPD(decNumber *, const uInt *, Int);
58 extern void decDigitsToDPD(const decNumber *, uInt *, Int);
60 #if DECTRACE || DECCHECK
61 void decimal128Show(const decimal128 *); /* for debug */
62 extern void decNumberShow(const decNumber *); /* .. */
63 #endif
65 /* Useful macro */
66 /* Clear a structure (e.g., a decNumber) */
67 #define DEC_clear(d) memset(d, 0, sizeof(*d))
69 /* ------------------------------------------------------------------ */
70 /* decimal128FromNumber -- convert decNumber to decimal128 */
71 /* */
72 /* ds is the target decimal128 */
73 /* dn is the source number (assumed valid) */
74 /* set is the context, used only for reporting errors */
75 /* */
76 /* The set argument is used only for status reporting and for the */
77 /* rounding mode (used if the coefficient is more than DECIMAL128_Pmax*/
78 /* digits or an overflow is detected). If the exponent is out of the */
79 /* valid range then Overflow or Underflow will be raised. */
80 /* After Underflow a subnormal result is possible. */
81 /* */
82 /* DEC_Clamped is set if the number has to be 'folded down' to fit, */
83 /* by reducing its exponent and multiplying the coefficient by a */
84 /* power of ten, or if the exponent on a zero had to be clamped. */
85 /* ------------------------------------------------------------------ */
86 decimal128 * decimal128FromNumber(decimal128 *d128, const decNumber *dn,
87 decContext *set) {
88 uInt status=0; /* status accumulator */
89 Int ae; /* adjusted exponent */
90 decNumber dw; /* work */
91 decContext dc; /* .. */
92 uInt *pu; /* .. */
93 uInt comb, exp; /* .. */
94 uInt targar[4]={0,0,0,0}; /* target 128-bit */
95 #define targhi targar[3] /* name the word with the sign */
96 #define targmh targar[2] /* name the words */
97 #define targml targar[1] /* .. */
98 #define targlo targar[0] /* .. */
100 /* If the number has too many digits, or the exponent could be */
101 /* out of range then reduce the number under the appropriate */
102 /* constraints. This could push the number to Infinity or zero, */
103 /* so this check and rounding must be done before generating the */
104 /* decimal128] */
105 ae=dn->exponent+dn->digits-1; /* [0 if special] */
106 if (dn->digits>DECIMAL128_Pmax /* too many digits */
107 || ae>DECIMAL128_Emax /* likely overflow */
108 || ae<DECIMAL128_Emin) { /* likely underflow */
109 decContextDefault(&dc, DEC_INIT_DECIMAL128); /* [no traps] */
110 dc.round=set->round; /* use supplied rounding */
111 decNumberPlus(&dw, dn, &dc); /* (round and check) */
112 /* [this changes -0 to 0, so enforce the sign...] */
113 dw.bits|=dn->bits&DECNEG;
114 status=dc.status; /* save status */
115 dn=&dw; /* use the work number */
116 } /* maybe out of range */
118 if (dn->bits&DECSPECIAL) { /* a special value */
119 if (dn->bits&DECINF) targhi=DECIMAL_Inf<<24;
120 else { /* sNaN or qNaN */
121 if ((*dn->lsu!=0 || dn->digits>1) /* non-zero coefficient */
122 && (dn->digits<DECIMAL128_Pmax)) { /* coefficient fits */
123 decDigitsToDPD(dn, targar, 0);
125 if (dn->bits&DECNAN) targhi|=DECIMAL_NaN<<24;
126 else targhi|=DECIMAL_sNaN<<24;
127 } /* a NaN */
128 } /* special */
130 else { /* is finite */
131 if (decNumberIsZero(dn)) { /* is a zero */
132 /* set and clamp exponent */
133 if (dn->exponent<-DECIMAL128_Bias) {
134 exp=0; /* low clamp */
135 status|=DEC_Clamped;
137 else {
138 exp=dn->exponent+DECIMAL128_Bias; /* bias exponent */
139 if (exp>DECIMAL128_Ehigh) { /* top clamp */
140 exp=DECIMAL128_Ehigh;
141 status|=DEC_Clamped;
144 comb=(exp>>9) & 0x18; /* msd=0, exp top 2 bits .. */
146 else { /* non-zero finite number */
147 uInt msd; /* work */
148 Int pad=0; /* coefficient pad digits */
150 /* the dn is known to fit, but it may need to be padded */
151 exp=(uInt)(dn->exponent+DECIMAL128_Bias); /* bias exponent */
152 if (exp>DECIMAL128_Ehigh) { /* fold-down case */
153 pad=exp-DECIMAL128_Ehigh;
154 exp=DECIMAL128_Ehigh; /* [to maximum] */
155 status|=DEC_Clamped;
158 /* [fastpath for common case is not a win, here] */
159 decDigitsToDPD(dn, targar, pad);
160 /* save and clear the top digit */
161 msd=targhi>>14;
162 targhi&=0x00003fff;
164 /* create the combination field */
165 if (msd>=8) comb=0x18 | ((exp>>11) & 0x06) | (msd & 0x01);
166 else comb=((exp>>9) & 0x18) | msd;
168 targhi|=comb<<26; /* add combination field .. */
169 targhi|=(exp&0xfff)<<14; /* .. and exponent continuation */
170 } /* finite */
172 if (dn->bits&DECNEG) targhi|=0x80000000; /* add sign bit */
174 /* now write to storage; this is endian */
175 pu=(uInt *)d128->bytes; /* overlay */
176 if (DECLITEND) {
177 pu[0]=targlo; /* directly store the low int */
178 pu[1]=targml; /* then the mid-low */
179 pu[2]=targmh; /* then the mid-high */
180 pu[3]=targhi; /* then the high int */
182 else {
183 pu[0]=targhi; /* directly store the high int */
184 pu[1]=targmh; /* then the mid-high */
185 pu[2]=targml; /* then the mid-low */
186 pu[3]=targlo; /* then the low int */
189 if (status!=0) decContextSetStatus(set, status); /* pass on status */
190 /* decimal128Show(d128); */
191 return d128;
192 } /* decimal128FromNumber */
194 /* ------------------------------------------------------------------ */
195 /* decimal128ToNumber -- convert decimal128 to decNumber */
196 /* d128 is the source decimal128 */
197 /* dn is the target number, with appropriate space */
198 /* No error is possible. */
199 /* ------------------------------------------------------------------ */
200 decNumber * decimal128ToNumber(const decimal128 *d128, decNumber *dn) {
201 uInt msd; /* coefficient MSD */
202 uInt exp; /* exponent top two bits */
203 uInt comb; /* combination field */
204 const uInt *pu; /* work */
205 Int need; /* .. */
206 uInt sourar[4]; /* source 128-bit */
207 #define sourhi sourar[3] /* name the word with the sign */
208 #define sourmh sourar[2] /* and the mid-high word */
209 #define sourml sourar[1] /* and the mod-low word */
210 #define sourlo sourar[0] /* and the lowest word */
212 /* load source from storage; this is endian */
213 pu=(const uInt *)d128->bytes; /* overlay */
214 if (DECLITEND) {
215 sourlo=pu[0]; /* directly load the low int */
216 sourml=pu[1]; /* then the mid-low */
217 sourmh=pu[2]; /* then the mid-high */
218 sourhi=pu[3]; /* then the high int */
220 else {
221 sourhi=pu[0]; /* directly load the high int */
222 sourmh=pu[1]; /* then the mid-high */
223 sourml=pu[2]; /* then the mid-low */
224 sourlo=pu[3]; /* then the low int */
227 comb=(sourhi>>26)&0x1f; /* combination field */
229 decNumberZero(dn); /* clean number */
230 if (sourhi&0x80000000) dn->bits=DECNEG; /* set sign if negative */
232 msd=COMBMSD[comb]; /* decode the combination field */
233 exp=COMBEXP[comb]; /* .. */
235 if (exp==3) { /* is a special */
236 if (msd==0) {
237 dn->bits|=DECINF;
238 return dn; /* no coefficient needed */
240 else if (sourhi&0x02000000) dn->bits|=DECSNAN;
241 else dn->bits|=DECNAN;
242 msd=0; /* no top digit */
244 else { /* is a finite number */
245 dn->exponent=(exp<<12)+((sourhi>>14)&0xfff)-DECIMAL128_Bias; /* unbiased */
248 /* get the coefficient */
249 sourhi&=0x00003fff; /* clean coefficient continuation */
250 if (msd) { /* non-zero msd */
251 sourhi|=msd<<14; /* prefix to coefficient */
252 need=12; /* process 12 declets */
254 else { /* msd=0 */
255 if (sourhi) need=11; /* declets to process */
256 else if (sourmh) need=10;
257 else if (sourml) need=7;
258 else if (sourlo) need=4;
259 else return dn; /* easy: coefficient is 0 */
260 } /*msd=0 */
262 decDigitsFromDPD(dn, sourar, need); /* process declets */
263 /* decNumberShow(dn); */
264 return dn;
265 } /* decimal128ToNumber */
267 /* ------------------------------------------------------------------ */
268 /* to-scientific-string -- conversion to numeric string */
269 /* to-engineering-string -- conversion to numeric string */
270 /* */
271 /* decimal128ToString(d128, string); */
272 /* decimal128ToEngString(d128, string); */
273 /* */
274 /* d128 is the decimal128 format number to convert */
275 /* string is the string where the result will be laid out */
276 /* */
277 /* string must be at least 24 characters */
278 /* */
279 /* No error is possible, and no status can be set. */
280 /* ------------------------------------------------------------------ */
281 char * decimal128ToEngString(const decimal128 *d128, char *string){
282 decNumber dn; /* work */
283 decimal128ToNumber(d128, &dn);
284 decNumberToEngString(&dn, string);
285 return string;
286 } /* decimal128ToEngString */
288 char * decimal128ToString(const decimal128 *d128, char *string){
289 uInt msd; /* coefficient MSD */
290 Int exp; /* exponent top two bits or full */
291 uInt comb; /* combination field */
292 char *cstart; /* coefficient start */
293 char *c; /* output pointer in string */
294 const uInt *pu; /* work */
295 char *s, *t; /* .. (source, target) */
296 Int dpd; /* .. */
297 Int pre, e; /* .. */
298 const uByte *u; /* .. */
300 uInt sourar[4]; /* source 128-bit */
301 #define sourhi sourar[3] /* name the word with the sign */
302 #define sourmh sourar[2] /* and the mid-high word */
303 #define sourml sourar[1] /* and the mod-low word */
304 #define sourlo sourar[0] /* and the lowest word */
306 /* load source from storage; this is endian */
307 pu=(const uInt *)d128->bytes; /* overlay */
308 if (DECLITEND) {
309 sourlo=pu[0]; /* directly load the low int */
310 sourml=pu[1]; /* then the mid-low */
311 sourmh=pu[2]; /* then the mid-high */
312 sourhi=pu[3]; /* then the high int */
314 else {
315 sourhi=pu[0]; /* directly load the high int */
316 sourmh=pu[1]; /* then the mid-high */
317 sourml=pu[2]; /* then the mid-low */
318 sourlo=pu[3]; /* then the low int */
321 c=string; /* where result will go */
322 if (((Int)sourhi)<0) *c++='-'; /* handle sign */
324 comb=(sourhi>>26)&0x1f; /* combination field */
325 msd=COMBMSD[comb]; /* decode the combination field */
326 exp=COMBEXP[comb]; /* .. */
328 if (exp==3) {
329 if (msd==0) { /* infinity */
330 strcpy(c, "Inf");
331 strcpy(c+3, "inity");
332 return string; /* easy */
334 if (sourhi&0x02000000) *c++='s'; /* sNaN */
335 strcpy(c, "NaN"); /* complete word */
336 c+=3; /* step past */
337 if (sourlo==0 && sourml==0 && sourmh==0
338 && (sourhi&0x0003ffff)==0) return string; /* zero payload */
339 /* otherwise drop through to add integer; set correct exp */
340 exp=0; msd=0; /* setup for following code */
342 else exp=(exp<<12)+((sourhi>>14)&0xfff)-DECIMAL128_Bias; /* unbiased */
344 /* convert 34 digits of significand to characters */
345 cstart=c; /* save start of coefficient */
346 if (msd) *c++='0'+(char)msd; /* non-zero most significant digit */
348 /* Now decode the declets. After extracting each one, it is */
349 /* decoded to binary and then to a 4-char sequence by table lookup; */
350 /* the 4-chars are a 1-char length (significant digits, except 000 */
351 /* has length 0). This allows us to left-align the first declet */
352 /* with non-zero content, then remaining ones are full 3-char */
353 /* length. We use fixed-length memcpys because variable-length */
354 /* causes a subroutine call in GCC. (These are length 4 for speed */
355 /* and are safe because the array has an extra terminator byte.) */
356 #define dpd2char u=&BIN2CHAR[DPD2BIN[dpd]*4]; \
357 if (c!=cstart) {memcpy(c, u+1, 4); c+=3;} \
358 else if (*u) {memcpy(c, u+4-*u, 4); c+=*u;}
359 dpd=(sourhi>>4)&0x3ff; /* declet 1 */
360 dpd2char;
361 dpd=((sourhi&0xf)<<6) | (sourmh>>26); /* declet 2 */
362 dpd2char;
363 dpd=(sourmh>>16)&0x3ff; /* declet 3 */
364 dpd2char;
365 dpd=(sourmh>>6)&0x3ff; /* declet 4 */
366 dpd2char;
367 dpd=((sourmh&0x3f)<<4) | (sourml>>28); /* declet 5 */
368 dpd2char;
369 dpd=(sourml>>18)&0x3ff; /* declet 6 */
370 dpd2char;
371 dpd=(sourml>>8)&0x3ff; /* declet 7 */
372 dpd2char;
373 dpd=((sourml&0xff)<<2) | (sourlo>>30); /* declet 8 */
374 dpd2char;
375 dpd=(sourlo>>20)&0x3ff; /* declet 9 */
376 dpd2char;
377 dpd=(sourlo>>10)&0x3ff; /* declet 10 */
378 dpd2char;
379 dpd=(sourlo)&0x3ff; /* declet 11 */
380 dpd2char;
382 if (c==cstart) *c++='0'; /* all zeros -- make 0 */
384 if (exp==0) { /* integer or NaN case -- easy */
385 *c='\0'; /* terminate */
386 return string;
389 /* non-0 exponent */
390 e=0; /* assume no E */
391 pre=c-cstart+exp;
392 /* [here, pre-exp is the digits count (==1 for zero)] */
393 if (exp>0 || pre<-5) { /* need exponential form */
394 e=pre-1; /* calculate E value */
395 pre=1; /* assume one digit before '.' */
396 } /* exponential form */
398 /* modify the coefficient, adding 0s, '.', and E+nn as needed */
399 s=c-1; /* source (LSD) */
400 if (pre>0) { /* ddd.ddd (plain), perhaps with E */
401 char *dotat=cstart+pre;
402 if (dotat<c) { /* if embedded dot needed... */
403 t=c; /* target */
404 for (; s>=dotat; s--, t--) *t=*s; /* open the gap; leave t at gap */
405 *t='.'; /* insert the dot */
406 c++; /* length increased by one */
409 /* finally add the E-part, if needed; it will never be 0, and has */
410 /* a maximum length of 4 digits */
411 if (e!=0) {
412 *c++='E'; /* starts with E */
413 *c++='+'; /* assume positive */
414 if (e<0) {
415 *(c-1)='-'; /* oops, need '-' */
416 e=-e; /* uInt, please */
418 if (e<1000) { /* 3 (or fewer) digits case */
419 u=&BIN2CHAR[e*4]; /* -> length byte */
420 memcpy(c, u+4-*u, 4); /* copy fixed 4 characters [is safe] */
421 c+=*u; /* bump pointer appropriately */
423 else { /* 4-digits */
424 Int thou=((e>>3)*1049)>>17; /* e/1000 */
425 Int rem=e-(1000*thou); /* e%1000 */
426 *c++='0'+(char)thou;
427 u=&BIN2CHAR[rem*4]; /* -> length byte */
428 memcpy(c, u+1, 4); /* copy fixed 3+1 characters [is safe] */
429 c+=3; /* bump pointer, always 3 digits */
432 *c='\0'; /* add terminator */
433 /*printf("res %s\n", string); */
434 return string;
435 } /* pre>0 */
437 /* -5<=pre<=0: here for plain 0.ddd or 0.000ddd forms (can never have E) */
438 t=c+1-pre;
439 *(t+1)='\0'; /* can add terminator now */
440 for (; s>=cstart; s--, t--) *t=*s; /* shift whole coefficient right */
441 c=cstart;
442 *c++='0'; /* always starts with 0. */
443 *c++='.';
444 for (; pre<0; pre++) *c++='0'; /* add any 0's after '.' */
445 /*printf("res %s\n", string); */
446 return string;
447 } /* decimal128ToString */
449 /* ------------------------------------------------------------------ */
450 /* to-number -- conversion from numeric string */
451 /* */
452 /* decimal128FromString(result, string, set); */
453 /* */
454 /* result is the decimal128 format number which gets the result of */
455 /* the conversion */
456 /* *string is the character string which should contain a valid */
457 /* number (which may be a special value) */
458 /* set is the context */
459 /* */
460 /* The context is supplied to this routine is used for error handling */
461 /* (setting of status and traps) and for the rounding mode, only. */
462 /* If an error occurs, the result will be a valid decimal128 NaN. */
463 /* ------------------------------------------------------------------ */
464 decimal128 * decimal128FromString(decimal128 *result, const char *string,
465 decContext *set) {
466 decContext dc; /* work */
467 decNumber dn; /* .. */
469 decContextDefault(&dc, DEC_INIT_DECIMAL128); /* no traps, please */
470 dc.round=set->round; /* use supplied rounding */
472 decNumberFromString(&dn, string, &dc); /* will round if needed */
473 decimal128FromNumber(result, &dn, &dc);
474 if (dc.status!=0) { /* something happened */
475 decContextSetStatus(set, dc.status); /* .. pass it on */
477 return result;
478 } /* decimal128FromString */
480 /* ------------------------------------------------------------------ */
481 /* decimal128IsCanonical -- test whether encoding is canonical */
482 /* d128 is the source decimal128 */
483 /* returns 1 if the encoding of d128 is canonical, 0 otherwise */
484 /* No error is possible. */
485 /* ------------------------------------------------------------------ */
486 uint32_t decimal128IsCanonical(const decimal128 *d128) {
487 decNumber dn; /* work */
488 decimal128 canon; /* .. */
489 decContext dc; /* .. */
490 decContextDefault(&dc, DEC_INIT_DECIMAL128);
491 decimal128ToNumber(d128, &dn);
492 decimal128FromNumber(&canon, &dn, &dc);/* canon will now be canonical */
493 return memcmp(d128, &canon, DECIMAL128_Bytes)==0;
494 } /* decimal128IsCanonical */
496 /* ------------------------------------------------------------------ */
497 /* decimal128Canonical -- copy an encoding, ensuring it is canonical */
498 /* d128 is the source decimal128 */
499 /* result is the target (may be the same decimal128) */
500 /* returns result */
501 /* No error is possible. */
502 /* ------------------------------------------------------------------ */
503 decimal128 * decimal128Canonical(decimal128 *result, const decimal128 *d128) {
504 decNumber dn; /* work */
505 decContext dc; /* .. */
506 decContextDefault(&dc, DEC_INIT_DECIMAL128);
507 decimal128ToNumber(d128, &dn);
508 decimal128FromNumber(result, &dn, &dc);/* result will now be canonical */
509 return result;
510 } /* decimal128Canonical */
512 #if DECTRACE || DECCHECK
513 /* Macros for accessing decimal128 fields. These assume the argument
514 is a reference (pointer) to the decimal128 structure, and the
515 decimal128 is in network byte order (big-endian) */
516 /* Get sign */
517 #define decimal128Sign(d) ((unsigned)(d)->bytes[0]>>7)
519 /* Get combination field */
520 #define decimal128Comb(d) (((d)->bytes[0] & 0x7c)>>2)
522 /* Get exponent continuation [does not remove bias] */
523 #define decimal128ExpCon(d) ((((d)->bytes[0] & 0x03)<<10) \
524 | ((unsigned)(d)->bytes[1]<<2) \
525 | ((unsigned)(d)->bytes[2]>>6))
527 /* Set sign [this assumes sign previously 0] */
528 #define decimal128SetSign(d, b) { \
529 (d)->bytes[0]|=((unsigned)(b)<<7);}
531 /* Set exponent continuation [does not apply bias] */
532 /* This assumes range has been checked and exponent previously 0; */
533 /* type of exponent must be unsigned */
534 #define decimal128SetExpCon(d, e) { \
535 (d)->bytes[0]|=(uint8_t)((e)>>10); \
536 (d)->bytes[1] =(uint8_t)(((e)&0x3fc)>>2); \
537 (d)->bytes[2]|=(uint8_t)(((e)&0x03)<<6);}
539 /* ------------------------------------------------------------------ */
540 /* decimal128Show -- display a decimal128 in hexadecimal [debug aid] */
541 /* d128 -- the number to show */
542 /* ------------------------------------------------------------------ */
543 /* Also shows sign/cob/expconfields extracted */
544 void decimal128Show(const decimal128 *d128) {
545 char buf[DECIMAL128_Bytes*2+1];
546 Int i, j=0;
548 if (DECLITEND) {
549 for (i=0; i<DECIMAL128_Bytes; i++, j+=2) {
550 sprintf(&buf[j], "%02x", d128->bytes[15-i]);
552 printf(" D128> %s [S:%d Cb:%02x Ec:%02x] LittleEndian\n", buf,
553 d128->bytes[15]>>7, (d128->bytes[15]>>2)&0x1f,
554 ((d128->bytes[15]&0x3)<<10)|(d128->bytes[14]<<2)|
555 (d128->bytes[13]>>6));
557 else {
558 for (i=0; i<DECIMAL128_Bytes; i++, j+=2) {
559 sprintf(&buf[j], "%02x", d128->bytes[i]);
561 printf(" D128> %s [S:%d Cb:%02x Ec:%02x] BigEndian\n", buf,
562 decimal128Sign(d128), decimal128Comb(d128),
563 decimal128ExpCon(d128));
565 } /* decimal128Show */
566 #endif