1/* Decimal 128-bit format module from the decNumber C Library.
2   Copyright (C) 2005 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, write to the Free
28   Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
29   02110-1301, USA.  */
30
31/* ------------------------------------------------------------------ */
32/* This module comprises the routines for decimal128 format numbers.  */
33/* Conversions are supplied to and from decNumber and String.         */
34/*                                                                    */
35/* No arithmetic routines are included; decNumber provides these.     */
36/*                                                                    */
37/* Error handling is the same as decNumber (qv.).                     */
38/* ------------------------------------------------------------------ */
39#include <string.h>		/* [for memset/memcpy] */
40#include <stdio.h>		/* [for printf] */
41
42#define  DECNUMDIGITS 34	/* we need decNumbers with space for 34 */
43#include "config.h"
44#include "decNumber.h"		/* base number library */
45#include "decNumberLocal.h"	/* decNumber local types, etc. */
46#include "decimal128.h"		/* our primary include */
47#include "decUtility.h"		/* utility routines */
48
49#if DECTRACE || DECCHECK
50void decimal128Show (const decimal128 *);	/* for debug */
51void decNumberShow (const decNumber *);	/* .. */
52#endif
53
54/* Useful macro */
55/* Clear a structure (e.g., a decNumber) */
56#define DEC_clear(d) memset(d, 0, sizeof(*d))
57
58/* ------------------------------------------------------------------ */
59/* decimal128FromNumber -- convert decNumber to decimal128            */
60/*                                                                    */
61/*   ds is the target decimal128                                      */
62/*   dn is the source number (assumed valid)                          */
63/*   set is the context, used only for reporting errors               */
64/*                                                                    */
65/* The set argument is used only for status reporting and for the     */
66/* rounding mode (used if the coefficient is more than DECIMAL128_Pmax*/
67/* digits or an overflow is detected).  If the exponent is out of the */
68/* valid range then Overflow or Underflow will be raised.             */
69/* After Underflow a subnormal result is possible.                    */
70/*                                                                    */
71/* DEC_Clamped is set if the number has to be 'folded down' to fit,   */
72/* by reducing its exponent and multiplying the coefficient by a      */
73/* power of ten, or if the exponent on a zero had to be clamped.      */
74/* ------------------------------------------------------------------ */
75decimal128 *
76decimal128FromNumber (decimal128 * d128, const decNumber * dn, decContext * set)
77{
78  uInt status = 0;		/* status accumulator */
79  Int pad = 0;			/* coefficient pad digits */
80  decNumber dw;			/* work */
81  decContext dc;		/* .. */
82  uByte isneg = dn->bits & DECNEG;	/* non-0 if original sign set */
83  uInt comb, exp;		/* work */
84
85  /* If the number is finite, and has too many digits, or the exponent */
86  /* could be out of range then we reduce the number under the */
87  /* appropriate constraints */
88  if (!(dn->bits & DECSPECIAL))
89    {				/* not a special value */
90      Int ae = dn->exponent + dn->digits - 1;	/* adjusted exponent */
91      if (dn->digits > DECIMAL128_Pmax	/* too many digits */
92	  || ae > DECIMAL128_Emax	/* likely overflow */
93	  || ae < DECIMAL128_Emin)
94	{			/* likely underflow */
95	  decContextDefault (&dc, DEC_INIT_DECIMAL128);	/* [no traps] */
96	  dc.round = set->round;	/* use supplied rounding */
97	  decNumberPlus (&dw, dn, &dc);	/* (round and check) */
98	  /* [this changes -0 to 0, but it will be restored below] */
99	  status |= dc.status;	/* save status */
100	  dn = &dw;		/* use the work number */
101	}
102      /* [this could have pushed number to Infinity or zero, so this */
103      /* rounding must be done before we generate the decimal128] */
104    }
105
106  DEC_clear (d128);		/* clean the target */
107  if (dn->bits & DECSPECIAL)
108    {				/* a special value */
109      uByte top;		/* work */
110      if (dn->bits & DECINF)
111	top = DECIMAL_Inf;
112      else
113	{			/* sNaN or qNaN */
114	  if ((*dn->lsu != 0 || dn->digits > 1)	/* non-zero coefficient */
115	      && (dn->digits < DECIMAL128_Pmax))
116	    {			/* coefficient fits */
117	      decDensePackCoeff (dn, d128->bytes, sizeof (d128->bytes), 0);
118	    }
119	  if (dn->bits & DECNAN)
120	    top = DECIMAL_NaN;
121	  else
122	    top = DECIMAL_sNaN;
123	}
124      d128->bytes[0] = top;
125    }
126  else if (decNumberIsZero (dn))
127    {				/* a zero */
128      /* set and clamp exponent */
129      if (dn->exponent < -DECIMAL128_Bias)
130	{
131	  exp = 0;
132	  status |= DEC_Clamped;
133	}
134      else
135	{
136	  exp = dn->exponent + DECIMAL128_Bias;	/* bias exponent */
137	  if (exp > DECIMAL128_Ehigh)
138	    {			/* top clamp */
139	      exp = DECIMAL128_Ehigh;
140	      status |= DEC_Clamped;
141	    }
142	}
143      comb = (exp >> 9) & 0x18;	/* combination field */
144      d128->bytes[0] = (uByte) (comb << 2);
145      exp &= 0xfff;		/* remaining exponent bits */
146      decimal128SetExpCon (d128, exp);
147    }
148  else
149    {				/* non-zero finite number */
150      uInt msd;			/* work */
151
152      /* we have a dn that fits, but it may need to be padded */
153      exp = (uInt) (dn->exponent + DECIMAL128_Bias);	/* bias exponent */
154
155      if (exp > DECIMAL128_Ehigh)
156	{			/* fold-down case */
157	  pad = exp - DECIMAL128_Ehigh;
158	  exp = DECIMAL128_Ehigh;	/* [to maximum] */
159	  status |= DEC_Clamped;
160	}
161
162      decDensePackCoeff (dn, d128->bytes, sizeof (d128->bytes), pad);
163
164      /* save and clear the top digit */
165      msd = ((unsigned) d128->bytes[1] << 2) & 0x0c;	/* top 2 bits */
166      msd |= ((unsigned) d128->bytes[2] >> 6);	/* low 2 bits */
167      d128->bytes[1] &= 0xfc;
168      d128->bytes[2] &= 0x3f;
169
170      /* create the combination field */
171      if (msd >= 8)
172	comb = 0x18 | (msd & 0x01) | ((exp >> 11) & 0x06);
173      else
174	comb = (msd & 0x07) | ((exp >> 9) & 0x18);
175      d128->bytes[0] = (uByte) (comb << 2);
176      exp &= 0xfff;		/* remaining exponent bits */
177      decimal128SetExpCon (d128, exp);
178    }
179
180  if (isneg)
181    decimal128SetSign (d128, 1);
182  if (status != 0)
183    decContextSetStatus (set, status);	/* pass on status */
184
185  /* decimal128Show(d128); */
186  return d128;
187}
188
189/* ------------------------------------------------------------------ */
190/* decimal128ToNumber -- convert decimal128 to decNumber              */
191/*   d128 is the source decimal128                                    */
192/*   dn is the target number, with appropriate space                  */
193/* No error is possible.                                              */
194/* ------------------------------------------------------------------ */
195decNumber *
196decimal128ToNumber (const decimal128 * d128, decNumber * dn)
197{
198  uInt msd;			/* coefficient MSD */
199  decimal128 wk;		/* working copy, if needed */
200  uInt top = d128->bytes[0] & 0x7f;	/* top byte, less sign bit */
201  decNumberZero (dn);		/* clean target */
202  /* set the sign if negative */
203  if (decimal128Sign (d128))
204    dn->bits = DECNEG;
205
206  if (top >= 0x78)
207    {				/* is a special */
208      if ((top & 0x7c) == (DECIMAL_Inf & 0x7c))
209	dn->bits |= DECINF;
210      else if ((top & 0x7e) == (DECIMAL_NaN & 0x7e))
211	dn->bits |= DECNAN;
212      else
213	dn->bits |= DECSNAN;
214      msd = 0;			/* no top digit */
215    }
216  else
217    {				/* have a finite number */
218      uInt comb = top >> 2;	/* combination field */
219      uInt exp;			/* exponent */
220
221      if (comb >= 0x18)
222	{
223	  msd = 8 + (comb & 0x01);
224	  exp = (comb & 0x06) << 11;	/* MSBs */
225	}
226      else
227	{
228	  msd = comb & 0x07;
229	  exp = (comb & 0x18) << 9;
230	}
231      dn->exponent = exp + decimal128ExpCon (d128) - DECIMAL128_Bias;	/* remove bias */
232    }
233
234  /* get the coefficient, unless infinite */
235  if (!(dn->bits & DECINF))
236    {
237      Int bunches = DECIMAL128_Pmax / 3;	/* coefficient full bunches to convert */
238      Int odd = 0;		/* assume MSD is 0 (no odd bunch) */
239      if (msd != 0)
240	{			/* coefficient has leading non-0 digit */
241	  /* make a copy of the decimal128, with an extra bunch which has */
242	  /* the top digit ready for conversion */
243	  wk = *d128;		/* take a copy */
244	  wk.bytes[0] = 0;	/* clear all but coecon */
245	  wk.bytes[1] = 0;	/* .. */
246	  wk.bytes[2] &= 0x3f;	/* .. */
247	  wk.bytes[1] |= (msd >> 2);	/* and prefix MSD */
248	  wk.bytes[2] |= (msd << 6);	/* .. */
249	  odd++;		/* indicate the extra */
250	  d128 = &wk;		/* use the work copy */
251	}
252      decDenseUnpackCoeff (d128->bytes, sizeof (d128->bytes), dn, bunches,
253			   odd);
254    }
255
256  /* decNumberShow(dn); */
257  return dn;
258}
259
260/* ------------------------------------------------------------------ */
261/* to-scientific-string -- conversion to numeric string               */
262/* to-engineering-string -- conversion to numeric string              */
263/*                                                                    */
264/*   decimal128ToString(d128, string);                                */
265/*   decimal128ToEngString(d128, string);                             */
266/*                                                                    */
267/*  d128 is the decimal128 format number to convert                   */
268/*  string is the string where the result will be laid out            */
269/*                                                                    */
270/*  string must be at least 24 characters                             */
271/*                                                                    */
272/*  No error is possible, and no status can be set.                   */
273/* ------------------------------------------------------------------ */
274char *
275decimal128ToString (const decimal128 * d128, char *string)
276{
277  decNumber dn;			/* work */
278  decimal128ToNumber (d128, &dn);
279  decNumberToString (&dn, string);
280  return string;
281}
282
283char *
284decimal128ToEngString (const decimal128 * d128, char *string)
285{
286  decNumber dn;			/* work */
287  decimal128ToNumber (d128, &dn);
288  decNumberToEngString (&dn, string);
289  return string;
290}
291
292/* ------------------------------------------------------------------ */
293/* to-number -- conversion from numeric string                        */
294/*                                                                    */
295/*   decimal128FromString(result, string, set);                       */
296/*                                                                    */
297/*  result  is the decimal128 format number which gets the result of  */
298/*          the conversion                                            */
299/*  *string is the character string which should contain a valid      */
300/*          number (which may be a special value)                     */
301/*  set     is the context                                            */
302/*                                                                    */
303/* The context is supplied to this routine is used for error handling */
304/* (setting of status and traps) and for the rounding mode, only.     */
305/* If an error occurs, the result will be a valid decimal128 NaN.     */
306/* ------------------------------------------------------------------ */
307decimal128 *
308decimal128FromString (decimal128 * result, const char *string, decContext * set)
309{
310  decContext dc;		/* work */
311  decNumber dn;			/* .. */
312
313  decContextDefault (&dc, DEC_INIT_DECIMAL128);	/* no traps, please */
314  dc.round = set->round;	/* use supplied rounding */
315
316  decNumberFromString (&dn, string, &dc);	/* will round if needed */
317  decimal128FromNumber (result, &dn, &dc);
318  if (dc.status != 0)
319    {				/* something happened */
320      decContextSetStatus (set, dc.status);	/* .. pass it on */
321    }
322  return result;
323}
324
325
326#if DECTRACE || DECCHECK
327/* ------------------------------------------------------------------ */
328/* decimal128Show -- display a single in hexadecimal [debug aid]      */
329/*   d128 -- the number to show                                       */
330/* ------------------------------------------------------------------ */
331/* Also shows sign/cob/expconfields extracted */
332void
333decimal128Show (const decimal128 * d128)
334{
335  char buf[DECIMAL128_Bytes * 2 + 1];
336  Int i, j;
337  j = 0;
338  for (i = 0; i < DECIMAL128_Bytes; i++)
339    {
340      sprintf (&buf[j], "%02x", d128->bytes[i]);
341      j = j + 2;
342    }
343  printf (" D128> %s [S:%d Cb:%02x E:%d]\n", buf,
344	  decimal128Sign (d128), decimal128Comb (d128),
345	  decimal128ExpCon (d128));
346}
347#endif
348