PR 15657
[platform/upstream/binutils.git] / gdb / doublest.c
1 /* Floating point routines for GDB, the GNU debugger.
2
3    Copyright (C) 1986-2013 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 /* Support for converting target fp numbers into host DOUBLEST format.  */
21
22 /* XXX - This code should really be in libiberty/floatformat.c,
23    however configuration issues with libiberty made this very
24    difficult to do in the available time.  */
25
26 #include "defs.h"
27 #include "doublest.h"
28 #include "floatformat.h"
29 #include "gdb_assert.h"
30 #include "gdb_string.h"
31 #include "gdbtypes.h"
32 #include <math.h>               /* ldexp */
33
34 /* The odds that CHAR_BIT will be anything but 8 are low enough that I'm not
35    going to bother with trying to muck around with whether it is defined in
36    a system header, what we do if not, etc.  */
37 #define FLOATFORMAT_CHAR_BIT 8
38
39 /* The number of bytes that the largest floating-point type that we
40    can convert to doublest will need.  */
41 #define FLOATFORMAT_LARGEST_BYTES 16
42
43 /* Extract a field which starts at START and is LEN bytes long.  DATA and
44    TOTAL_LEN are the thing we are extracting it from, in byteorder ORDER.  */
45 static unsigned long
46 get_field (const bfd_byte *data, enum floatformat_byteorders order,
47            unsigned int total_len, unsigned int start, unsigned int len)
48 {
49   unsigned long result;
50   unsigned int cur_byte;
51   int cur_bitshift;
52
53   /* Caller must byte-swap words before calling this routine.  */
54   gdb_assert (order == floatformat_little || order == floatformat_big);
55
56   /* Start at the least significant part of the field.  */
57   if (order == floatformat_little)
58     {
59       /* We start counting from the other end (i.e, from the high bytes
60          rather than the low bytes).  As such, we need to be concerned
61          with what happens if bit 0 doesn't start on a byte boundary.
62          I.e, we need to properly handle the case where total_len is
63          not evenly divisible by 8.  So we compute ``excess'' which
64          represents the number of bits from the end of our starting
65          byte needed to get to bit 0.  */
66       int excess = FLOATFORMAT_CHAR_BIT - (total_len % FLOATFORMAT_CHAR_BIT);
67
68       cur_byte = (total_len / FLOATFORMAT_CHAR_BIT) 
69                  - ((start + len + excess) / FLOATFORMAT_CHAR_BIT);
70       cur_bitshift = ((start + len + excess) % FLOATFORMAT_CHAR_BIT) 
71                      - FLOATFORMAT_CHAR_BIT;
72     }
73   else
74     {
75       cur_byte = (start + len) / FLOATFORMAT_CHAR_BIT;
76       cur_bitshift =
77         ((start + len) % FLOATFORMAT_CHAR_BIT) - FLOATFORMAT_CHAR_BIT;
78     }
79   if (cur_bitshift > -FLOATFORMAT_CHAR_BIT)
80     result = *(data + cur_byte) >> (-cur_bitshift);
81   else
82     result = 0;
83   cur_bitshift += FLOATFORMAT_CHAR_BIT;
84   if (order == floatformat_little)
85     ++cur_byte;
86   else
87     --cur_byte;
88
89   /* Move towards the most significant part of the field.  */
90   while (cur_bitshift < len)
91     {
92       result |= (unsigned long)*(data + cur_byte) << cur_bitshift;
93       cur_bitshift += FLOATFORMAT_CHAR_BIT;
94       switch (order)
95         {
96         case floatformat_little:
97           ++cur_byte;
98           break;
99         case floatformat_big:
100           --cur_byte;
101           break;
102         }
103     }
104   if (len < sizeof(result) * FLOATFORMAT_CHAR_BIT)
105     /* Mask out bits which are not part of the field.  */
106     result &= ((1UL << len) - 1);
107   return result;
108 }
109
110 /* Normalize the byte order of FROM into TO.  If no normalization is
111    needed then FMT->byteorder is returned and TO is not changed;
112    otherwise the format of the normalized form in TO is returned.  */
113
114 static enum floatformat_byteorders
115 floatformat_normalize_byteorder (const struct floatformat *fmt,
116                                  const void *from, void *to)
117 {
118   const unsigned char *swapin;
119   unsigned char *swapout;
120   int words;
121   
122   if (fmt->byteorder == floatformat_little
123       || fmt->byteorder == floatformat_big)
124     return fmt->byteorder;
125
126   words = fmt->totalsize / FLOATFORMAT_CHAR_BIT;
127   words >>= 2;
128
129   swapout = (unsigned char *)to;
130   swapin = (const unsigned char *)from;
131
132   if (fmt->byteorder == floatformat_vax)
133     {
134       while (words-- > 0)
135         {
136           *swapout++ = swapin[1];
137           *swapout++ = swapin[0];
138           *swapout++ = swapin[3];
139           *swapout++ = swapin[2];
140           swapin += 4;
141         }
142       /* This may look weird, since VAX is little-endian, but it is
143          easier to translate to big-endian than to little-endian.  */
144       return floatformat_big;
145     }
146   else
147     {
148       gdb_assert (fmt->byteorder == floatformat_littlebyte_bigword);
149
150       while (words-- > 0)
151         {
152           *swapout++ = swapin[3];
153           *swapout++ = swapin[2];
154           *swapout++ = swapin[1];
155           *swapout++ = swapin[0];
156           swapin += 4;
157         }
158       return floatformat_big;
159     }
160 }
161   
162 /* Convert from FMT to a DOUBLEST.
163    FROM is the address of the extended float.
164    Store the DOUBLEST in *TO.  */
165
166 static void
167 convert_floatformat_to_doublest (const struct floatformat *fmt,
168                                  const void *from,
169                                  DOUBLEST *to)
170 {
171   unsigned char *ufrom = (unsigned char *) from;
172   DOUBLEST dto;
173   long exponent;
174   unsigned long mant;
175   unsigned int mant_bits, mant_off;
176   int mant_bits_left;
177   int special_exponent;         /* It's a NaN, denorm or zero.  */
178   enum floatformat_byteorders order;
179   unsigned char newfrom[FLOATFORMAT_LARGEST_BYTES];
180   enum float_kind kind;
181   
182   gdb_assert (fmt->totalsize
183               <= FLOATFORMAT_LARGEST_BYTES * FLOATFORMAT_CHAR_BIT);
184
185   /* For non-numbers, reuse libiberty's logic to find the correct
186      format.  We do not lose any precision in this case by passing
187      through a double.  */
188   kind = floatformat_classify (fmt, from);
189   if (kind == float_infinite || kind == float_nan)
190     {
191       double dto;
192
193       floatformat_to_double (fmt, from, &dto);
194       *to = (DOUBLEST) dto;
195       return;
196     }
197
198   order = floatformat_normalize_byteorder (fmt, ufrom, newfrom);
199
200   if (order != fmt->byteorder)
201     ufrom = newfrom;
202
203   if (fmt->split_half)
204     {
205       DOUBLEST dtop, dbot;
206
207       floatformat_to_doublest (fmt->split_half, ufrom, &dtop);
208       /* Preserve the sign of 0, which is the sign of the top
209          half.  */
210       if (dtop == 0.0)
211         {
212           *to = dtop;
213           return;
214         }
215       floatformat_to_doublest (fmt->split_half,
216                              ufrom + fmt->totalsize / FLOATFORMAT_CHAR_BIT / 2,
217                              &dbot);
218       *to = dtop + dbot;
219       return;
220     }
221
222   exponent = get_field (ufrom, order, fmt->totalsize, fmt->exp_start,
223                         fmt->exp_len);
224   /* Note that if exponent indicates a NaN, we can't really do anything useful
225      (not knowing if the host has NaN's, or how to build one).  So it will
226      end up as an infinity or something close; that is OK.  */
227
228   mant_bits_left = fmt->man_len;
229   mant_off = fmt->man_start;
230   dto = 0.0;
231
232   special_exponent = exponent == 0 || exponent == fmt->exp_nan;
233
234   /* Don't bias NaNs.  Use minimum exponent for denorms.  For
235      simplicity, we don't check for zero as the exponent doesn't matter.
236      Note the cast to int; exp_bias is unsigned, so it's important to
237      make sure the operation is done in signed arithmetic.  */
238   if (!special_exponent)
239     exponent -= fmt->exp_bias;
240   else if (exponent == 0)
241     exponent = 1 - fmt->exp_bias;
242
243   /* Build the result algebraically.  Might go infinite, underflow, etc;
244      who cares.  */
245
246 /* If this format uses a hidden bit, explicitly add it in now.  Otherwise,
247    increment the exponent by one to account for the integer bit.  */
248
249   if (!special_exponent)
250     {
251       if (fmt->intbit == floatformat_intbit_no)
252         dto = ldexp (1.0, exponent);
253       else
254         exponent++;
255     }
256
257   while (mant_bits_left > 0)
258     {
259       mant_bits = min (mant_bits_left, 32);
260
261       mant = get_field (ufrom, order, fmt->totalsize, mant_off, mant_bits);
262
263       dto += ldexp ((double) mant, exponent - mant_bits);
264       exponent -= mant_bits;
265       mant_off += mant_bits;
266       mant_bits_left -= mant_bits;
267     }
268
269   /* Negate it if negative.  */
270   if (get_field (ufrom, order, fmt->totalsize, fmt->sign_start, 1))
271     dto = -dto;
272   *to = dto;
273 }
274 \f
275 /* Set a field which starts at START and is LEN bytes long.  DATA and
276    TOTAL_LEN are the thing we are extracting it from, in byteorder ORDER.  */
277 static void
278 put_field (unsigned char *data, enum floatformat_byteorders order,
279            unsigned int total_len, unsigned int start, unsigned int len,
280            unsigned long stuff_to_put)
281 {
282   unsigned int cur_byte;
283   int cur_bitshift;
284
285   /* Caller must byte-swap words before calling this routine.  */
286   gdb_assert (order == floatformat_little || order == floatformat_big);
287
288   /* Start at the least significant part of the field.  */
289   if (order == floatformat_little)
290     {
291       int excess = FLOATFORMAT_CHAR_BIT - (total_len % FLOATFORMAT_CHAR_BIT);
292
293       cur_byte = (total_len / FLOATFORMAT_CHAR_BIT) 
294                  - ((start + len + excess) / FLOATFORMAT_CHAR_BIT);
295       cur_bitshift = ((start + len + excess) % FLOATFORMAT_CHAR_BIT) 
296                      - FLOATFORMAT_CHAR_BIT;
297     }
298   else
299     {
300       cur_byte = (start + len) / FLOATFORMAT_CHAR_BIT;
301       cur_bitshift =
302         ((start + len) % FLOATFORMAT_CHAR_BIT) - FLOATFORMAT_CHAR_BIT;
303     }
304   if (cur_bitshift > -FLOATFORMAT_CHAR_BIT)
305     {
306       *(data + cur_byte) &=
307         ~(((1 << ((start + len) % FLOATFORMAT_CHAR_BIT)) - 1)
308           << (-cur_bitshift));
309       *(data + cur_byte) |=
310         (stuff_to_put & ((1 << FLOATFORMAT_CHAR_BIT) - 1)) << (-cur_bitshift);
311     }
312   cur_bitshift += FLOATFORMAT_CHAR_BIT;
313   if (order == floatformat_little)
314     ++cur_byte;
315   else
316     --cur_byte;
317
318   /* Move towards the most significant part of the field.  */
319   while (cur_bitshift < len)
320     {
321       if (len - cur_bitshift < FLOATFORMAT_CHAR_BIT)
322         {
323           /* This is the last byte.  */
324           *(data + cur_byte) &=
325             ~((1 << (len - cur_bitshift)) - 1);
326           *(data + cur_byte) |= (stuff_to_put >> cur_bitshift);
327         }
328       else
329         *(data + cur_byte) = ((stuff_to_put >> cur_bitshift)
330                               & ((1 << FLOATFORMAT_CHAR_BIT) - 1));
331       cur_bitshift += FLOATFORMAT_CHAR_BIT;
332       if (order == floatformat_little)
333         ++cur_byte;
334       else
335         --cur_byte;
336     }
337 }
338
339 /* The converse: convert the DOUBLEST *FROM to an extended float and
340    store where TO points.  Neither FROM nor TO have any alignment
341    restrictions.  */
342
343 static void
344 convert_doublest_to_floatformat (CONST struct floatformat *fmt,
345                                  const DOUBLEST *from, void *to)
346 {
347   DOUBLEST dfrom;
348   int exponent;
349   DOUBLEST mant;
350   unsigned int mant_bits, mant_off;
351   int mant_bits_left;
352   unsigned char *uto = (unsigned char *) to;
353   enum floatformat_byteorders order = fmt->byteorder;
354   unsigned char newto[FLOATFORMAT_LARGEST_BYTES];
355
356   if (order != floatformat_little)
357     order = floatformat_big;
358
359   if (order != fmt->byteorder)
360     uto = newto;
361
362   memcpy (&dfrom, from, sizeof (dfrom));
363   memset (uto, 0, (fmt->totalsize + FLOATFORMAT_CHAR_BIT - 1) 
364                     / FLOATFORMAT_CHAR_BIT);
365
366   if (fmt->split_half)
367     {
368       /* Use static volatile to ensure that any excess precision is
369          removed via storing in memory, and so the top half really is
370          the result of converting to double.  */
371       static volatile double dtop, dbot;
372       DOUBLEST dtopnv, dbotnv;
373
374       dtop = (double) dfrom;
375       /* If the rounded top half is Inf, the bottom must be 0 not NaN
376          or Inf.  */
377       if (dtop + dtop == dtop && dtop != 0.0)
378         dbot = 0.0;
379       else
380         dbot = (double) (dfrom - (DOUBLEST) dtop);
381       dtopnv = dtop;
382       dbotnv = dbot;
383       floatformat_from_doublest (fmt->split_half, &dtopnv, uto);
384       floatformat_from_doublest (fmt->split_half, &dbotnv,
385                                (uto
386                                 + fmt->totalsize / FLOATFORMAT_CHAR_BIT / 2));
387       return;
388     }
389
390   if (dfrom == 0)
391     return;                     /* Result is zero */
392   if (dfrom != dfrom)           /* Result is NaN */
393     {
394       /* From is NaN */
395       put_field (uto, order, fmt->totalsize, fmt->exp_start,
396                  fmt->exp_len, fmt->exp_nan);
397       /* Be sure it's not infinity, but NaN value is irrel.  */
398       put_field (uto, order, fmt->totalsize, fmt->man_start,
399                  fmt->man_len, 1);
400       goto finalize_byteorder;
401     }
402
403   /* If negative, set the sign bit.  */
404   if (dfrom < 0)
405     {
406       put_field (uto, order, fmt->totalsize, fmt->sign_start, 1, 1);
407       dfrom = -dfrom;
408     }
409
410   if (dfrom + dfrom == dfrom && dfrom != 0.0)   /* Result is Infinity.  */
411     {
412       /* Infinity exponent is same as NaN's.  */
413       put_field (uto, order, fmt->totalsize, fmt->exp_start,
414                  fmt->exp_len, fmt->exp_nan);
415       /* Infinity mantissa is all zeroes.  */
416       put_field (uto, order, fmt->totalsize, fmt->man_start,
417                  fmt->man_len, 0);
418       goto finalize_byteorder;
419     }
420
421 #ifdef HAVE_LONG_DOUBLE
422   mant = frexpl (dfrom, &exponent);
423 #else
424   mant = frexp (dfrom, &exponent);
425 #endif
426
427   if (exponent + fmt->exp_bias <= 0)
428     {
429       /* The value is too small to be expressed in the destination
430          type (not enough bits in the exponent.  Treat as 0.  */
431       put_field (uto, order, fmt->totalsize, fmt->exp_start,
432                  fmt->exp_len, 0);
433       put_field (uto, order, fmt->totalsize, fmt->man_start,
434                  fmt->man_len, 0);
435       goto finalize_byteorder;
436     }
437
438   if (exponent + fmt->exp_bias >= (1 << fmt->exp_len))
439     {
440       /* The value is too large to fit into the destination.
441          Treat as infinity.  */
442       put_field (uto, order, fmt->totalsize, fmt->exp_start,
443                  fmt->exp_len, fmt->exp_nan);
444       put_field (uto, order, fmt->totalsize, fmt->man_start,
445                  fmt->man_len, 0);
446       goto finalize_byteorder;
447     }
448
449   put_field (uto, order, fmt->totalsize, fmt->exp_start, fmt->exp_len,
450              exponent + fmt->exp_bias - 1);
451
452   mant_bits_left = fmt->man_len;
453   mant_off = fmt->man_start;
454   while (mant_bits_left > 0)
455     {
456       unsigned long mant_long;
457
458       mant_bits = mant_bits_left < 32 ? mant_bits_left : 32;
459
460       mant *= 4294967296.0;
461       mant_long = ((unsigned long) mant) & 0xffffffffL;
462       mant -= mant_long;
463
464       /* If the integer bit is implicit, then we need to discard it.
465          If we are discarding a zero, we should be (but are not) creating
466          a denormalized number which means adjusting the exponent
467          (I think).  */
468       if (mant_bits_left == fmt->man_len
469           && fmt->intbit == floatformat_intbit_no)
470         {
471           mant_long <<= 1;
472           mant_long &= 0xffffffffL;
473           /* If we are processing the top 32 mantissa bits of a doublest
474              so as to convert to a float value with implied integer bit,
475              we will only be putting 31 of those 32 bits into the
476              final value due to the discarding of the top bit.  In the 
477              case of a small float value where the number of mantissa 
478              bits is less than 32, discarding the top bit does not alter
479              the number of bits we will be adding to the result.  */
480           if (mant_bits == 32)
481             mant_bits -= 1;
482         }
483
484       if (mant_bits < 32)
485         {
486           /* The bits we want are in the most significant MANT_BITS bits of
487              mant_long.  Move them to the least significant.  */
488           mant_long >>= 32 - mant_bits;
489         }
490
491       put_field (uto, order, fmt->totalsize,
492                  mant_off, mant_bits, mant_long);
493       mant_off += mant_bits;
494       mant_bits_left -= mant_bits;
495     }
496
497  finalize_byteorder:
498   /* Do we need to byte-swap the words in the result?  */
499   if (order != fmt->byteorder)
500     floatformat_normalize_byteorder (fmt, newto, to);
501 }
502
503 /* Check if VAL (which is assumed to be a floating point number whose
504    format is described by FMT) is negative.  */
505
506 int
507 floatformat_is_negative (const struct floatformat *fmt,
508                          const bfd_byte *uval)
509 {
510   enum floatformat_byteorders order;
511   unsigned char newfrom[FLOATFORMAT_LARGEST_BYTES];
512   
513   gdb_assert (fmt != NULL);
514   gdb_assert (fmt->totalsize
515               <= FLOATFORMAT_LARGEST_BYTES * FLOATFORMAT_CHAR_BIT);
516
517   order = floatformat_normalize_byteorder (fmt, uval, newfrom);
518
519   if (order != fmt->byteorder)
520     uval = newfrom;
521
522   return get_field (uval, order, fmt->totalsize, fmt->sign_start, 1);
523 }
524
525 /* Check if VAL is "not a number" (NaN) for FMT.  */
526
527 enum float_kind
528 floatformat_classify (const struct floatformat *fmt,
529                       const bfd_byte *uval)
530 {
531   long exponent;
532   unsigned long mant;
533   unsigned int mant_bits, mant_off;
534   int mant_bits_left;
535   enum floatformat_byteorders order;
536   unsigned char newfrom[FLOATFORMAT_LARGEST_BYTES];
537   int mant_zero;
538   
539   gdb_assert (fmt != NULL);
540   gdb_assert (fmt->totalsize
541               <= FLOATFORMAT_LARGEST_BYTES * FLOATFORMAT_CHAR_BIT);
542
543   order = floatformat_normalize_byteorder (fmt, uval, newfrom);
544
545   if (order != fmt->byteorder)
546     uval = newfrom;
547
548   exponent = get_field (uval, order, fmt->totalsize, fmt->exp_start,
549                         fmt->exp_len);
550
551   mant_bits_left = fmt->man_len;
552   mant_off = fmt->man_start;
553
554   mant_zero = 1;
555   while (mant_bits_left > 0)
556     {
557       mant_bits = min (mant_bits_left, 32);
558
559       mant = get_field (uval, order, fmt->totalsize, mant_off, mant_bits);
560
561       /* If there is an explicit integer bit, mask it off.  */
562       if (mant_off == fmt->man_start
563           && fmt->intbit == floatformat_intbit_yes)
564         mant &= ~(1 << (mant_bits - 1));
565
566       if (mant)
567         {
568           mant_zero = 0;
569           break;
570         }
571
572       mant_off += mant_bits;
573       mant_bits_left -= mant_bits;
574     }
575
576   /* If exp_nan is not set, assume that inf, NaN, and subnormals are not
577      supported.  */
578   if (! fmt->exp_nan)
579     {
580       if (mant_zero)
581         return float_zero;
582       else
583         return float_normal;
584     }
585
586   if (exponent == 0 && !mant_zero)
587     return float_subnormal;
588
589   if (exponent == fmt->exp_nan)
590     {
591       if (mant_zero)
592         return float_infinite;
593       else
594         return float_nan;
595     }
596
597   if (mant_zero)
598     return float_zero;
599
600   return float_normal;
601 }
602
603 /* Convert the mantissa of VAL (which is assumed to be a floating
604    point number whose format is described by FMT) into a hexadecimal
605    and store it in a static string.  Return a pointer to that string.  */
606
607 const char *
608 floatformat_mantissa (const struct floatformat *fmt,
609                       const bfd_byte *val)
610 {
611   unsigned char *uval = (unsigned char *) val;
612   unsigned long mant;
613   unsigned int mant_bits, mant_off;
614   int mant_bits_left;
615   static char res[50];
616   char buf[9];
617   int len;
618   enum floatformat_byteorders order;
619   unsigned char newfrom[FLOATFORMAT_LARGEST_BYTES];
620   
621   gdb_assert (fmt != NULL);
622   gdb_assert (fmt->totalsize
623               <= FLOATFORMAT_LARGEST_BYTES * FLOATFORMAT_CHAR_BIT);
624
625   order = floatformat_normalize_byteorder (fmt, uval, newfrom);
626
627   if (order != fmt->byteorder)
628     uval = newfrom;
629
630   if (! fmt->exp_nan)
631     return 0;
632
633   /* Make sure we have enough room to store the mantissa.  */
634   gdb_assert (sizeof res > ((fmt->man_len + 7) / 8) * 2);
635
636   mant_off = fmt->man_start;
637   mant_bits_left = fmt->man_len;
638   mant_bits = (mant_bits_left % 32) > 0 ? mant_bits_left % 32 : 32;
639
640   mant = get_field (uval, order, fmt->totalsize, mant_off, mant_bits);
641
642   len = xsnprintf (res, sizeof res, "%lx", mant);
643
644   mant_off += mant_bits;
645   mant_bits_left -= mant_bits;
646
647   while (mant_bits_left > 0)
648     {
649       mant = get_field (uval, order, fmt->totalsize, mant_off, 32);
650
651       xsnprintf (buf, sizeof buf, "%08lx", mant);
652       gdb_assert (len + strlen (buf) <= sizeof res);
653       strcat (res, buf);
654
655       mant_off += 32;
656       mant_bits_left -= 32;
657     }
658
659   return res;
660 }
661
662 \f
663 /* Convert TO/FROM target to the hosts DOUBLEST floating-point format.
664
665    If the host and target formats agree, we just copy the raw data
666    into the appropriate type of variable and return, letting the host
667    increase precision as necessary.  Otherwise, we call the conversion
668    routine and let it do the dirty work.  */
669
670 static const struct floatformat *host_float_format = GDB_HOST_FLOAT_FORMAT;
671 static const struct floatformat *host_double_format = GDB_HOST_DOUBLE_FORMAT;
672 static const struct floatformat *host_long_double_format
673   = GDB_HOST_LONG_DOUBLE_FORMAT;
674
675 void
676 floatformat_to_doublest (const struct floatformat *fmt,
677                          const void *in, DOUBLEST *out)
678 {
679   gdb_assert (fmt != NULL);
680   if (fmt == host_float_format)
681     {
682       float val;
683
684       memcpy (&val, in, sizeof (val));
685       *out = val;
686     }
687   else if (fmt == host_double_format)
688     {
689       double val;
690
691       memcpy (&val, in, sizeof (val));
692       *out = val;
693     }
694   else if (fmt == host_long_double_format)
695     {
696       long double val;
697
698       memcpy (&val, in, sizeof (val));
699       *out = val;
700     }
701   else
702     convert_floatformat_to_doublest (fmt, in, out);
703 }
704
705 void
706 floatformat_from_doublest (const struct floatformat *fmt,
707                            const DOUBLEST *in, void *out)
708 {
709   gdb_assert (fmt != NULL);
710   if (fmt == host_float_format)
711     {
712       float val = *in;
713
714       memcpy (out, &val, sizeof (val));
715     }
716   else if (fmt == host_double_format)
717     {
718       double val = *in;
719
720       memcpy (out, &val, sizeof (val));
721     }
722   else if (fmt == host_long_double_format)
723     {
724       long double val = *in;
725
726       memcpy (out, &val, sizeof (val));
727     }
728   else
729     convert_doublest_to_floatformat (fmt, in, out);
730 }
731
732 \f
733 /* Return a floating-point format for a floating-point variable of
734    length LEN.  If no suitable floating-point format is found, an
735    error is thrown.
736
737    We need this functionality since information about the
738    floating-point format of a type is not always available to GDB; the
739    debug information typically only tells us the size of a
740    floating-point type.
741
742    FIXME: kettenis/2001-10-28: In many places, particularly in
743    target-dependent code, the format of floating-point types is known,
744    but not passed on by GDB.  This should be fixed.  */
745
746 static const struct floatformat *
747 floatformat_from_length (struct gdbarch *gdbarch, int len)
748 {
749   const struct floatformat *format;
750
751   if (len * TARGET_CHAR_BIT == gdbarch_half_bit (gdbarch))
752     format = gdbarch_half_format (gdbarch)
753                [gdbarch_byte_order (gdbarch)];
754   else if (len * TARGET_CHAR_BIT == gdbarch_float_bit (gdbarch))
755     format = gdbarch_float_format (gdbarch)
756                [gdbarch_byte_order (gdbarch)];
757   else if (len * TARGET_CHAR_BIT == gdbarch_double_bit (gdbarch))
758     format = gdbarch_double_format (gdbarch)
759                [gdbarch_byte_order (gdbarch)];
760   else if (len * TARGET_CHAR_BIT == gdbarch_long_double_bit (gdbarch))
761     format = gdbarch_long_double_format (gdbarch)
762                [gdbarch_byte_order (gdbarch)];
763   /* On i386 the 'long double' type takes 96 bits,
764      while the real number of used bits is only 80,
765      both in processor and in memory.
766      The code below accepts the real bit size.  */ 
767   else if ((gdbarch_long_double_format (gdbarch) != NULL)
768            && (len * TARGET_CHAR_BIT
769                == gdbarch_long_double_format (gdbarch)[0]->totalsize))
770     format = gdbarch_long_double_format (gdbarch)
771                [gdbarch_byte_order (gdbarch)];
772   else
773     format = NULL;
774   if (format == NULL)
775     error (_("Unrecognized %d-bit floating-point type."),
776            len * TARGET_CHAR_BIT);
777   return format;
778 }
779
780 const struct floatformat *
781 floatformat_from_type (const struct type *type)
782 {
783   struct gdbarch *gdbarch = get_type_arch (type);
784
785   gdb_assert (TYPE_CODE (type) == TYPE_CODE_FLT);
786   if (TYPE_FLOATFORMAT (type) != NULL)
787     return TYPE_FLOATFORMAT (type)[gdbarch_byte_order (gdbarch)];
788   else
789     return floatformat_from_length (gdbarch, TYPE_LENGTH (type));
790 }
791
792 /* Extract a floating-point number of type TYPE from a target-order
793    byte-stream at ADDR.  Returns the value as type DOUBLEST.  */
794
795 DOUBLEST
796 extract_typed_floating (const void *addr, const struct type *type)
797 {
798   const struct floatformat *fmt = floatformat_from_type (type);
799   DOUBLEST retval;
800
801   floatformat_to_doublest (fmt, addr, &retval);
802   return retval;
803 }
804
805 /* Store VAL as a floating-point number of type TYPE to a target-order
806    byte-stream at ADDR.  */
807
808 void
809 store_typed_floating (void *addr, const struct type *type, DOUBLEST val)
810 {
811   const struct floatformat *fmt = floatformat_from_type (type);
812
813   /* FIXME: kettenis/2001-10-28: It is debatable whether we should
814      zero out any remaining bytes in the target buffer when TYPE is
815      longer than the actual underlying floating-point format.  Perhaps
816      we should store a fixed bitpattern in those remaining bytes,
817      instead of zero, or perhaps we shouldn't touch those remaining
818      bytes at all.
819
820      NOTE: cagney/2001-10-28: With the way things currently work, it
821      isn't a good idea to leave the end bits undefined.  This is
822      because GDB writes out the entire sizeof(<floating>) bits of the
823      floating-point type even though the value might only be stored
824      in, and the target processor may only refer to, the first N <
825      TYPE_LENGTH (type) bits.  If the end of the buffer wasn't
826      initialized, GDB would write undefined data to the target.  An
827      errant program, refering to that undefined data, would then
828      become non-deterministic.
829
830      See also the function convert_typed_floating below.  */
831   memset (addr, 0, TYPE_LENGTH (type));
832
833   floatformat_from_doublest (fmt, &val, addr);
834 }
835
836 /* Convert a floating-point number of type FROM_TYPE from a
837    target-order byte-stream at FROM to a floating-point number of type
838    TO_TYPE, and store it to a target-order byte-stream at TO.  */
839
840 void
841 convert_typed_floating (const void *from, const struct type *from_type,
842                         void *to, const struct type *to_type)
843 {
844   const struct floatformat *from_fmt = floatformat_from_type (from_type);
845   const struct floatformat *to_fmt = floatformat_from_type (to_type);
846
847   if (from_fmt == NULL || to_fmt == NULL)
848     {
849       /* If we don't know the floating-point format of FROM_TYPE or
850          TO_TYPE, there's not much we can do.  We might make the
851          assumption that if the length of FROM_TYPE and TO_TYPE match,
852          their floating-point format would match too, but that
853          assumption might be wrong on targets that support
854          floating-point types that only differ in endianness for
855          example.  So we warn instead, and zero out the target buffer.  */
856       warning (_("Can't convert floating-point number to desired type."));
857       memset (to, 0, TYPE_LENGTH (to_type));
858     }
859   else if (from_fmt == to_fmt)
860     {
861       /* We're in business.  The floating-point format of FROM_TYPE
862          and TO_TYPE match.  However, even though the floating-point
863          format matches, the length of the type might still be
864          different.  Make sure we don't overrun any buffers.  See
865          comment in store_typed_floating for a discussion about
866          zeroing out remaining bytes in the target buffer.  */
867       memset (to, 0, TYPE_LENGTH (to_type));
868       memcpy (to, from, min (TYPE_LENGTH (from_type), TYPE_LENGTH (to_type)));
869     }
870   else
871     {
872       /* The floating-point types don't match.  The best we can do
873          (apart from simulating the target FPU) is converting to the
874          widest floating-point type supported by the host, and then
875          again to the desired type.  */
876       DOUBLEST d;
877
878       floatformat_to_doublest (from_fmt, from, &d);
879       floatformat_from_doublest (to_fmt, &d, to);
880     }
881 }
882
883 const struct floatformat *floatformat_ieee_single[BFD_ENDIAN_UNKNOWN];
884 const struct floatformat *floatformat_ieee_double[BFD_ENDIAN_UNKNOWN];
885 const struct floatformat *floatformat_ieee_quad[BFD_ENDIAN_UNKNOWN];
886 const struct floatformat *floatformat_arm_ext[BFD_ENDIAN_UNKNOWN];
887 const struct floatformat *floatformat_ia64_spill[BFD_ENDIAN_UNKNOWN];
888
889 extern void _initialize_doublest (void);
890
891 extern void
892 _initialize_doublest (void)
893 {
894   floatformat_ieee_single[BFD_ENDIAN_LITTLE] = &floatformat_ieee_single_little;
895   floatformat_ieee_single[BFD_ENDIAN_BIG] = &floatformat_ieee_single_big;
896   floatformat_ieee_double[BFD_ENDIAN_LITTLE] = &floatformat_ieee_double_little;
897   floatformat_ieee_double[BFD_ENDIAN_BIG] = &floatformat_ieee_double_big;
898   floatformat_arm_ext[BFD_ENDIAN_LITTLE]
899     = &floatformat_arm_ext_littlebyte_bigword;
900   floatformat_arm_ext[BFD_ENDIAN_BIG] = &floatformat_arm_ext_big;
901   floatformat_ia64_spill[BFD_ENDIAN_LITTLE] = &floatformat_ia64_spill_little;
902   floatformat_ia64_spill[BFD_ENDIAN_BIG] = &floatformat_ia64_spill_big;
903   floatformat_ieee_quad[BFD_ENDIAN_LITTLE] = &floatformat_ia64_quad_little;
904   floatformat_ieee_quad[BFD_ENDIAN_BIG] = &floatformat_ia64_quad_big;
905 }