OSDN Git Service

* decl.c: Miscellaneous whitespace fixes.
[pf3gnuchains/gcc-fork.git] / gcc / fortran / trans-types.c
1 /* Backend support for Fortran 95 basic types and derived types.
2    Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 Free Software
3    Foundation, Inc.
4    Contributed by Paul Brook <paul@nowt.org>
5    and Steven Bosscher <s.bosscher@student.tudelft.nl>
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 2, or (at your option) any later
12 version.
13
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
17 for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING.  If not, write to the Free
21 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
22 02110-1301, USA.  */
23
24 /* trans-types.c -- gfortran backend types */
25
26 #include "config.h"
27 #include "system.h"
28 #include "coretypes.h"
29 #include "tree.h"
30 #include "tm.h"
31 #include "target.h"
32 #include "ggc.h"
33 #include "toplev.h"
34 #include "gfortran.h"
35 #include "trans.h"
36 #include "trans-types.h"
37 #include "trans-const.h"
38 #include "real.h"
39 \f
40
41 #if (GFC_MAX_DIMENSIONS < 10)
42 #define GFC_RANK_DIGITS 1
43 #define GFC_RANK_PRINTF_FORMAT "%01d"
44 #elif (GFC_MAX_DIMENSIONS < 100)
45 #define GFC_RANK_DIGITS 2
46 #define GFC_RANK_PRINTF_FORMAT "%02d"
47 #else
48 #error If you really need >99 dimensions, continue the sequence above...
49 #endif
50
51 static tree gfc_get_derived_type (gfc_symbol * derived);
52
53 tree gfc_array_index_type;
54 tree gfc_array_range_type;
55 tree gfc_character1_type_node;
56 tree pvoid_type_node;
57 tree ppvoid_type_node;
58 tree pchar_type_node;
59
60 tree gfc_charlen_type_node;
61
62 static GTY(()) tree gfc_desc_dim_type;
63 static GTY(()) tree gfc_max_array_element_size;
64 static GTY(()) tree gfc_array_descriptor_base[GFC_MAX_DIMENSIONS];
65
66 /* Arrays for all integral and real kinds.  We'll fill this in at runtime
67    after the target has a chance to process command-line options.  */
68
69 #define MAX_INT_KINDS 5
70 gfc_integer_info gfc_integer_kinds[MAX_INT_KINDS + 1];
71 gfc_logical_info gfc_logical_kinds[MAX_INT_KINDS + 1];
72 static GTY(()) tree gfc_integer_types[MAX_INT_KINDS + 1];
73 static GTY(()) tree gfc_logical_types[MAX_INT_KINDS + 1];
74
75 #define MAX_REAL_KINDS 5
76 gfc_real_info gfc_real_kinds[MAX_REAL_KINDS + 1];
77 static GTY(()) tree gfc_real_types[MAX_REAL_KINDS + 1];
78 static GTY(()) tree gfc_complex_types[MAX_REAL_KINDS + 1];
79
80
81 /* The integer kind to use for array indices.  This will be set to the
82    proper value based on target information from the backend.  */
83
84 int gfc_index_integer_kind;
85
86 /* The default kinds of the various types.  */
87
88 int gfc_default_integer_kind;
89 int gfc_max_integer_kind;
90 int gfc_default_real_kind;
91 int gfc_default_double_kind;
92 int gfc_default_character_kind;
93 int gfc_default_logical_kind;
94 int gfc_default_complex_kind;
95 int gfc_c_int_kind;
96
97 /* The kind size used for record offsets. If the target system supports
98    kind=8, this will be set to 8, otherwise it is set to 4.  */
99 int gfc_intio_kind; 
100
101 /* The integer kind used to store character lengths.  */
102 int gfc_charlen_int_kind;
103
104 /* The size of the numeric storage unit and character storage unit.  */
105 int gfc_numeric_storage_size;
106 int gfc_character_storage_size;
107
108 /* Query the target to determine which machine modes are available for
109    computation.  Choose KIND numbers for them.  */
110
111 void
112 gfc_init_kinds (void)
113 {
114   enum machine_mode mode;
115   int i_index, r_index;
116   bool saw_i4 = false, saw_i8 = false;
117   bool saw_r4 = false, saw_r8 = false, saw_r16 = false;
118
119   for (i_index = 0, mode = MIN_MODE_INT; mode <= MAX_MODE_INT; mode++)
120     {
121       int kind, bitsize;
122
123       if (!targetm.scalar_mode_supported_p (mode))
124         continue;
125
126       /* The middle end doesn't support constants larger than 2*HWI.
127          Perhaps the target hook shouldn't have accepted these either,
128          but just to be safe...  */
129       bitsize = GET_MODE_BITSIZE (mode);
130       if (bitsize > 2*HOST_BITS_PER_WIDE_INT)
131         continue;
132
133       gcc_assert (i_index != MAX_INT_KINDS);
134
135       /* Let the kind equal the bit size divided by 8.  This insulates the
136          programmer from the underlying byte size.  */
137       kind = bitsize / 8;
138
139       if (kind == 4)
140         saw_i4 = true;
141       if (kind == 8)
142         saw_i8 = true;
143
144       gfc_integer_kinds[i_index].kind = kind;
145       gfc_integer_kinds[i_index].radix = 2;
146       gfc_integer_kinds[i_index].digits = bitsize - 1;
147       gfc_integer_kinds[i_index].bit_size = bitsize;
148
149       gfc_logical_kinds[i_index].kind = kind;
150       gfc_logical_kinds[i_index].bit_size = bitsize;
151
152       i_index += 1;
153     }
154
155   /* Set the kind used to match GFC_INT_IO in libgfortran.  This is 
156      used for large file access.  */
157
158   if (saw_i8)
159     gfc_intio_kind = 8;
160   else
161     gfc_intio_kind = 4;
162
163   /* If we do not at least have kind = 4, everything is pointless.  */  
164   gcc_assert(saw_i4);  
165
166   /* Set the maximum integer kind.  Used with at least BOZ constants.  */
167   gfc_max_integer_kind = gfc_integer_kinds[i_index - 1].kind;
168
169   for (r_index = 0, mode = MIN_MODE_FLOAT; mode <= MAX_MODE_FLOAT; mode++)
170     {
171       const struct real_format *fmt = REAL_MODE_FORMAT (mode);
172       int kind;
173
174       if (fmt == NULL)
175         continue;
176       if (!targetm.scalar_mode_supported_p (mode))
177         continue;
178
179       /* Only let float/double/long double go through because the fortran
180          library assumes these are the only floating point types.  */
181
182       if (mode != TYPE_MODE (float_type_node)
183           && (mode != TYPE_MODE (double_type_node))
184           && (mode != TYPE_MODE (long_double_type_node)))
185         continue;
186
187       /* Let the kind equal the precision divided by 8, rounding up.  Again,
188          this insulates the programmer from the underlying byte size.
189
190          Also, it effectively deals with IEEE extended formats.  There, the
191          total size of the type may equal 16, but it's got 6 bytes of padding
192          and the increased size can get in the way of a real IEEE quad format
193          which may also be supported by the target.
194
195          We round up so as to handle IA-64 __floatreg (RFmode), which is an
196          82 bit type.  Not to be confused with __float80 (XFmode), which is
197          an 80 bit type also supported by IA-64.  So XFmode should come out
198          to be kind=10, and RFmode should come out to be kind=11.  Egads.  */
199
200       kind = (GET_MODE_PRECISION (mode) + 7) / 8;
201
202       if (kind == 4)
203         saw_r4 = true;
204       if (kind == 8)
205         saw_r8 = true;
206       if (kind == 16)
207         saw_r16 = true;
208
209       /* Careful we don't stumble a wierd internal mode.  */
210       gcc_assert (r_index <= 0 || gfc_real_kinds[r_index-1].kind != kind);
211       /* Or have too many modes for the allocated space.  */
212       gcc_assert (r_index != MAX_REAL_KINDS);
213
214       gfc_real_kinds[r_index].kind = kind;
215       gfc_real_kinds[r_index].radix = fmt->b;
216       gfc_real_kinds[r_index].digits = fmt->p;
217       gfc_real_kinds[r_index].min_exponent = fmt->emin;
218       gfc_real_kinds[r_index].max_exponent = fmt->emax;
219       if (fmt->pnan < fmt->p)
220         /* This is an IBM extended double format (or the MIPS variant)
221            made up of two IEEE doubles.  The value of the long double is
222            the sum of the values of the two parts.  The most significant
223            part is required to be the value of the long double rounded
224            to the nearest double.  If we use emax of 1024 then we can't
225            represent huge(x) = (1 - b**(-p)) * b**(emax-1) * b, because
226            rounding will make the most significant part overflow.  */
227         gfc_real_kinds[r_index].max_exponent = fmt->emax - 1;
228       gfc_real_kinds[r_index].mode_precision = GET_MODE_PRECISION (mode);
229       r_index += 1;
230     }
231
232   /* Choose the default integer kind.  We choose 4 unless the user
233      directs us otherwise.  */
234   if (gfc_option.flag_default_integer)
235     {
236       if (!saw_i8)
237         fatal_error ("integer kind=8 not available for -fdefault-integer-8 option");
238       gfc_default_integer_kind = 8;
239
240       /* Even if the user specified that the default integer kind be 8,
241          the numerica storage size isn't 64.  In this case, a warning will
242          be issued when NUMERIC_STORAGE_SIZE is used.  */
243       gfc_numeric_storage_size = 4 * 8;
244     }
245   else if (saw_i4)
246     {
247       gfc_default_integer_kind = 4;
248       gfc_numeric_storage_size = 4 * 8;
249     }
250   else
251     {
252       gfc_default_integer_kind = gfc_integer_kinds[i_index - 1].kind;
253       gfc_numeric_storage_size = gfc_integer_kinds[i_index - 1].bit_size;
254     }
255
256   /* Choose the default real kind.  Again, we choose 4 when possible.  */
257   if (gfc_option.flag_default_real)
258     {
259       if (!saw_r8)
260         fatal_error ("real kind=8 not available for -fdefault-real-8 option");
261       gfc_default_real_kind = 8;
262     }
263   else if (saw_r4)
264     gfc_default_real_kind = 4;
265   else
266     gfc_default_real_kind = gfc_real_kinds[0].kind;
267
268   /* Choose the default double kind.  If -fdefault-real and -fdefault-double 
269      are specified, we use kind=8, if it's available.  If -fdefault-real is
270      specified without -fdefault-double, we use kind=16, if it's available.
271      Otherwise we do not change anything.  */
272   if (gfc_option.flag_default_double && !gfc_option.flag_default_real)
273     fatal_error ("Use of -fdefault-double-8 requires -fdefault-real-8");
274
275   if (gfc_option.flag_default_real && gfc_option.flag_default_double && saw_r8)
276     gfc_default_double_kind = 8;
277   else if (gfc_option.flag_default_real && saw_r16)
278     gfc_default_double_kind = 16;
279   else if (saw_r4 && saw_r8)
280     gfc_default_double_kind = 8;
281   else
282     {
283       /* F95 14.6.3.1: A nonpointer scalar object of type double precision
284          real ... occupies two contiguous numeric storage units.
285
286          Therefore we must be supplied a kind twice as large as we chose
287          for single precision.  There are loopholes, in that double
288          precision must *occupy* two storage units, though it doesn't have
289          to *use* two storage units.  Which means that you can make this
290          kind artificially wide by padding it.  But at present there are
291          no GCC targets for which a two-word type does not exist, so we
292          just let gfc_validate_kind abort and tell us if something breaks.  */
293
294       gfc_default_double_kind
295         = gfc_validate_kind (BT_REAL, gfc_default_real_kind * 2, false);
296     }
297
298   /* The default logical kind is constrained to be the same as the
299      default integer kind.  Similarly with complex and real.  */
300   gfc_default_logical_kind = gfc_default_integer_kind;
301   gfc_default_complex_kind = gfc_default_real_kind;
302
303   /* Choose the smallest integer kind for our default character.  */
304   gfc_default_character_kind = gfc_integer_kinds[0].kind;
305   gfc_character_storage_size = gfc_default_character_kind * 8;
306
307   /* Choose the integer kind the same size as "void*" for our index kind.  */
308   gfc_index_integer_kind = POINTER_SIZE / 8;
309   /* Pick a kind the same size as the C "int" type.  */
310   gfc_c_int_kind = INT_TYPE_SIZE / 8;
311 }
312
313 /* Make sure that a valid kind is present.  Returns an index into the
314    associated kinds array, -1 if the kind is not present.  */
315
316 static int
317 validate_integer (int kind)
318 {
319   int i;
320
321   for (i = 0; gfc_integer_kinds[i].kind != 0; i++)
322     if (gfc_integer_kinds[i].kind == kind)
323       return i;
324
325   return -1;
326 }
327
328 static int
329 validate_real (int kind)
330 {
331   int i;
332
333   for (i = 0; gfc_real_kinds[i].kind != 0; i++)
334     if (gfc_real_kinds[i].kind == kind)
335       return i;
336
337   return -1;
338 }
339
340 static int
341 validate_logical (int kind)
342 {
343   int i;
344
345   for (i = 0; gfc_logical_kinds[i].kind; i++)
346     if (gfc_logical_kinds[i].kind == kind)
347       return i;
348
349   return -1;
350 }
351
352 static int
353 validate_character (int kind)
354 {
355   return kind == gfc_default_character_kind ? 0 : -1;
356 }
357
358 /* Validate a kind given a basic type.  The return value is the same
359    for the child functions, with -1 indicating nonexistence of the
360    type.  If MAY_FAIL is false, then -1 is never returned, and we ICE.  */
361
362 int
363 gfc_validate_kind (bt type, int kind, bool may_fail)
364 {
365   int rc;
366
367   switch (type)
368     {
369     case BT_REAL:               /* Fall through */
370     case BT_COMPLEX:
371       rc = validate_real (kind);
372       break;
373     case BT_INTEGER:
374       rc = validate_integer (kind);
375       break;
376     case BT_LOGICAL:
377       rc = validate_logical (kind);
378       break;
379     case BT_CHARACTER:
380       rc = validate_character (kind);
381       break;
382
383     default:
384       gfc_internal_error ("gfc_validate_kind(): Got bad type");
385     }
386
387   if (rc < 0 && !may_fail)
388     gfc_internal_error ("gfc_validate_kind(): Got bad kind");
389
390   return rc;
391 }
392
393
394 /* Four subroutines of gfc_init_types.  Create type nodes for the given kind.
395    Reuse common type nodes where possible.  Recognize if the kind matches up
396    with a C type.  This will be used later in determining which routines may
397    be scarfed from libm.  */
398
399 static tree
400 gfc_build_int_type (gfc_integer_info *info)
401 {
402   int mode_precision = info->bit_size;
403
404   if (mode_precision == CHAR_TYPE_SIZE)
405     info->c_char = 1;
406   if (mode_precision == SHORT_TYPE_SIZE)
407     info->c_short = 1;
408   if (mode_precision == INT_TYPE_SIZE)
409     info->c_int = 1;
410   if (mode_precision == LONG_TYPE_SIZE)
411     info->c_long = 1;
412   if (mode_precision == LONG_LONG_TYPE_SIZE)
413     info->c_long_long = 1;
414
415   if (TYPE_PRECISION (intQI_type_node) == mode_precision)
416     return intQI_type_node;
417   if (TYPE_PRECISION (intHI_type_node) == mode_precision)
418     return intHI_type_node;
419   if (TYPE_PRECISION (intSI_type_node) == mode_precision)
420     return intSI_type_node;
421   if (TYPE_PRECISION (intDI_type_node) == mode_precision)
422     return intDI_type_node;
423   if (TYPE_PRECISION (intTI_type_node) == mode_precision)
424     return intTI_type_node;
425
426   return make_signed_type (mode_precision);
427 }
428
429 static tree
430 gfc_build_real_type (gfc_real_info *info)
431 {
432   int mode_precision = info->mode_precision;
433   tree new_type;
434
435   if (mode_precision == FLOAT_TYPE_SIZE)
436     info->c_float = 1;
437   if (mode_precision == DOUBLE_TYPE_SIZE)
438     info->c_double = 1;
439   if (mode_precision == LONG_DOUBLE_TYPE_SIZE)
440     info->c_long_double = 1;
441
442   if (TYPE_PRECISION (float_type_node) == mode_precision)
443     return float_type_node;
444   if (TYPE_PRECISION (double_type_node) == mode_precision)
445     return double_type_node;
446   if (TYPE_PRECISION (long_double_type_node) == mode_precision)
447     return long_double_type_node;
448
449   new_type = make_node (REAL_TYPE);
450   TYPE_PRECISION (new_type) = mode_precision;
451   layout_type (new_type);
452   return new_type;
453 }
454
455 static tree
456 gfc_build_complex_type (tree scalar_type)
457 {
458   tree new_type;
459
460   if (scalar_type == NULL)
461     return NULL;
462   if (scalar_type == float_type_node)
463     return complex_float_type_node;
464   if (scalar_type == double_type_node)
465     return complex_double_type_node;
466   if (scalar_type == long_double_type_node)
467     return complex_long_double_type_node;
468
469   new_type = make_node (COMPLEX_TYPE);
470   TREE_TYPE (new_type) = scalar_type;
471   layout_type (new_type);
472   return new_type;
473 }
474
475 static tree
476 gfc_build_logical_type (gfc_logical_info *info)
477 {
478   int bit_size = info->bit_size;
479   tree new_type;
480
481   if (bit_size == BOOL_TYPE_SIZE)
482     {
483       info->c_bool = 1;
484       return boolean_type_node;
485     }
486
487   new_type = make_unsigned_type (bit_size);
488   TREE_SET_CODE (new_type, BOOLEAN_TYPE);
489   TYPE_MAX_VALUE (new_type) = build_int_cst (new_type, 1);
490   TYPE_PRECISION (new_type) = 1;
491
492   return new_type;
493 }
494
495 #if 0
496 /* Return the bit size of the C "size_t".  */
497
498 static unsigned int
499 c_size_t_size (void)
500 {
501 #ifdef SIZE_TYPE  
502   if (strcmp (SIZE_TYPE, "unsigned int") == 0)
503     return INT_TYPE_SIZE;
504   if (strcmp (SIZE_TYPE, "long unsigned int") == 0)
505     return LONG_TYPE_SIZE;
506   if (strcmp (SIZE_TYPE, "short unsigned int") == 0)
507     return SHORT_TYPE_SIZE;
508   gcc_unreachable ();
509 #else
510   return LONG_TYPE_SIZE;
511 #endif
512 }
513 #endif
514
515 /* Create the backend type nodes. We map them to their
516    equivalent C type, at least for now.  We also give
517    names to the types here, and we push them in the
518    global binding level context.*/
519
520 void
521 gfc_init_types (void)
522 {
523   char name_buf[16];
524   int index;
525   tree type;
526   unsigned n;
527   unsigned HOST_WIDE_INT hi;
528   unsigned HOST_WIDE_INT lo;
529
530   /* Create and name the types.  */
531 #define PUSH_TYPE(name, node) \
532   pushdecl (build_decl (TYPE_DECL, get_identifier (name), node))
533
534   for (index = 0; gfc_integer_kinds[index].kind != 0; ++index)
535     {
536       type = gfc_build_int_type (&gfc_integer_kinds[index]);
537       gfc_integer_types[index] = type;
538       snprintf (name_buf, sizeof(name_buf), "int%d",
539                 gfc_integer_kinds[index].kind);
540       PUSH_TYPE (name_buf, type);
541     }
542
543   for (index = 0; gfc_logical_kinds[index].kind != 0; ++index)
544     {
545       type = gfc_build_logical_type (&gfc_logical_kinds[index]);
546       gfc_logical_types[index] = type;
547       snprintf (name_buf, sizeof(name_buf), "logical%d",
548                 gfc_logical_kinds[index].kind);
549       PUSH_TYPE (name_buf, type);
550     }
551
552   for (index = 0; gfc_real_kinds[index].kind != 0; index++)
553     {
554       type = gfc_build_real_type (&gfc_real_kinds[index]);
555       gfc_real_types[index] = type;
556       snprintf (name_buf, sizeof(name_buf), "real%d",
557                 gfc_real_kinds[index].kind);
558       PUSH_TYPE (name_buf, type);
559
560       type = gfc_build_complex_type (type);
561       gfc_complex_types[index] = type;
562       snprintf (name_buf, sizeof(name_buf), "complex%d",
563                 gfc_real_kinds[index].kind);
564       PUSH_TYPE (name_buf, type);
565     }
566
567   gfc_character1_type_node = build_type_variant (unsigned_char_type_node, 
568                                                  0, 0);
569   PUSH_TYPE ("char", gfc_character1_type_node);
570
571   PUSH_TYPE ("byte", unsigned_char_type_node);
572   PUSH_TYPE ("void", void_type_node);
573
574   /* DBX debugging output gets upset if these aren't set.  */
575   if (!TYPE_NAME (integer_type_node))
576     PUSH_TYPE ("c_integer", integer_type_node);
577   if (!TYPE_NAME (char_type_node))
578     PUSH_TYPE ("c_char", char_type_node);
579
580 #undef PUSH_TYPE
581
582   pvoid_type_node = build_pointer_type (void_type_node);
583   ppvoid_type_node = build_pointer_type (pvoid_type_node);
584   pchar_type_node = build_pointer_type (gfc_character1_type_node);
585
586   gfc_array_index_type = gfc_get_int_type (gfc_index_integer_kind);
587   /* We cannot use gfc_index_zero_node in definition of gfc_array_range_type,
588      since this function is called before gfc_init_constants.  */
589   gfc_array_range_type
590           = build_range_type (gfc_array_index_type,
591                               build_int_cst (gfc_array_index_type, 0),
592                               NULL_TREE);
593
594   /* The maximum array element size that can be handled is determined
595      by the number of bits available to store this field in the array
596      descriptor.  */
597
598   n = TYPE_PRECISION (gfc_array_index_type) - GFC_DTYPE_SIZE_SHIFT;
599   lo = ~ (unsigned HOST_WIDE_INT) 0;
600   if (n > HOST_BITS_PER_WIDE_INT)
601     hi = lo >> (2*HOST_BITS_PER_WIDE_INT - n);
602   else
603     hi = 0, lo >>= HOST_BITS_PER_WIDE_INT - n;
604   gfc_max_array_element_size
605     = build_int_cst_wide (long_unsigned_type_node, lo, hi);
606
607   size_type_node = gfc_array_index_type;
608
609   boolean_type_node = gfc_get_logical_type (gfc_default_logical_kind);
610   boolean_true_node = build_int_cst (boolean_type_node, 1);
611   boolean_false_node = build_int_cst (boolean_type_node, 0);
612
613   /* ??? Shouldn't this be based on gfc_index_integer_kind or so?  */
614   gfc_charlen_int_kind = 4;
615   gfc_charlen_type_node = gfc_get_int_type (gfc_charlen_int_kind);
616 }
617
618 /* Get the type node for the given type and kind.  */
619
620 tree
621 gfc_get_int_type (int kind)
622 {
623   int index = gfc_validate_kind (BT_INTEGER, kind, true);
624   return index < 0 ? 0 : gfc_integer_types[index];
625 }
626
627 tree
628 gfc_get_real_type (int kind)
629 {
630   int index = gfc_validate_kind (BT_REAL, kind, true);
631   return index < 0 ? 0 : gfc_real_types[index];
632 }
633
634 tree
635 gfc_get_complex_type (int kind)
636 {
637   int index = gfc_validate_kind (BT_COMPLEX, kind, true);
638   return index < 0 ? 0 : gfc_complex_types[index];
639 }
640
641 tree
642 gfc_get_logical_type (int kind)
643 {
644   int index = gfc_validate_kind (BT_LOGICAL, kind, true);
645   return index < 0 ? 0 : gfc_logical_types[index];
646 }
647 \f
648 /* Create a character type with the given kind and length.  */
649
650 tree
651 gfc_get_character_type_len (int kind, tree len)
652 {
653   tree bounds, type;
654
655   gfc_validate_kind (BT_CHARACTER, kind, false);
656
657   bounds = build_range_type (gfc_charlen_type_node, gfc_index_one_node, len);
658   type = build_array_type (gfc_character1_type_node, bounds);
659   TYPE_STRING_FLAG (type) = 1;
660
661   return type;
662 }
663
664
665 /* Get a type node for a character kind.  */
666
667 tree
668 gfc_get_character_type (int kind, gfc_charlen * cl)
669 {
670   tree len;
671
672   len = (cl == NULL) ? NULL_TREE : cl->backend_decl;
673
674   return gfc_get_character_type_len (kind, len);
675 }
676 \f
677 /* Covert a basic type.  This will be an array for character types.  */
678
679 tree
680 gfc_typenode_for_spec (gfc_typespec * spec)
681 {
682   tree basetype;
683
684   switch (spec->type)
685     {
686     case BT_UNKNOWN:
687       gcc_unreachable ();
688
689     case BT_INTEGER:
690       basetype = gfc_get_int_type (spec->kind);
691       break;
692
693     case BT_REAL:
694       basetype = gfc_get_real_type (spec->kind);
695       break;
696
697     case BT_COMPLEX:
698       basetype = gfc_get_complex_type (spec->kind);
699       break;
700
701     case BT_LOGICAL:
702       basetype = gfc_get_logical_type (spec->kind);
703       break;
704
705     case BT_CHARACTER:
706       basetype = gfc_get_character_type (spec->kind, spec->cl);
707       break;
708
709     case BT_DERIVED:
710       basetype = gfc_get_derived_type (spec->derived);
711       break;
712
713     default:
714       gcc_unreachable ();
715     }
716   return basetype;
717 }
718 \f
719 /* Build an INT_CST for constant expressions, otherwise return NULL_TREE.  */
720
721 static tree
722 gfc_conv_array_bound (gfc_expr * expr)
723 {
724   /* If expr is an integer constant, return that.  */
725   if (expr != NULL && expr->expr_type == EXPR_CONSTANT)
726     return gfc_conv_mpz_to_tree (expr->value.integer, gfc_index_integer_kind);
727
728   /* Otherwise return NULL.  */
729   return NULL_TREE;
730 }
731 \f
732 tree
733 gfc_get_element_type (tree type)
734 {
735   tree element;
736
737   if (GFC_ARRAY_TYPE_P (type))
738     {
739       if (TREE_CODE (type) == POINTER_TYPE)
740         type = TREE_TYPE (type);
741       gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
742       element = TREE_TYPE (type);
743     }
744   else
745     {
746       gcc_assert (GFC_DESCRIPTOR_TYPE_P (type));
747       element = GFC_TYPE_ARRAY_DATAPTR_TYPE (type);
748
749       gcc_assert (TREE_CODE (element) == POINTER_TYPE);
750       element = TREE_TYPE (element);
751
752       gcc_assert (TREE_CODE (element) == ARRAY_TYPE);
753       element = TREE_TYPE (element);
754     }
755
756   return element;
757 }
758 \f
759 /* Build an array.  This function is called from gfc_sym_type().
760    Actually returns array descriptor type.
761
762    Format of array descriptors is as follows:
763
764     struct gfc_array_descriptor
765     {
766       array *data
767       index offset;
768       index dtype;
769       struct descriptor_dimension dimension[N_DIM];
770     }
771
772     struct descriptor_dimension
773     {
774       index stride;
775       index lbound;
776       index ubound;
777     }
778
779    Translation code should use gfc_conv_descriptor_* rather than
780    accessing the descriptor directly.  Any changes to the array
781    descriptor type will require changes in gfc_conv_descriptor_* and
782    gfc_build_array_initializer.
783
784    This is represented internally as a RECORD_TYPE. The index nodes
785    are gfc_array_index_type and the data node is a pointer to the
786    data.  See below for the handling of character types.
787
788    The dtype member is formatted as follows:
789     rank = dtype & GFC_DTYPE_RANK_MASK // 3 bits
790     type = (dtype & GFC_DTYPE_TYPE_MASK) >> GFC_DTYPE_TYPE_SHIFT // 3 bits
791     size = dtype >> GFC_DTYPE_SIZE_SHIFT
792
793    I originally used nested ARRAY_TYPE nodes to represent arrays, but
794    this generated poor code for assumed/deferred size arrays.  These
795    require use of PLACEHOLDER_EXPR/WITH_RECORD_EXPR, which isn't part
796    of the GENERIC grammar.  Also, there is no way to explicitly set
797    the array stride, so all data must be packed(1).  I've tried to
798    mark all the functions which would require modification with a GCC
799    ARRAYS comment.
800
801    The data component points to the first element in the array.  The
802    offset field is the position of the origin of the array (ie element
803    (0, 0 ...)).  This may be outsite the bounds of the array.
804
805    An element is accessed by
806     data[offset + index0*stride0 + index1*stride1 + index2*stride2]
807    This gives good performance as the computation does not involve the
808    bounds of the array.  For packed arrays, this is optimized further
809    by substituting the known strides.
810
811    This system has one problem: all array bounds must be within 2^31
812    elements of the origin (2^63 on 64-bit machines).  For example
813     integer, dimension (80000:90000, 80000:90000, 2) :: array
814    may not work properly on 32-bit machines because 80000*80000 >
815    2^31, so the calculation for stride02 would overflow.  This may
816    still work, but I haven't checked, and it relies on the overflow
817    doing the right thing.
818
819    The way to fix this problem is to access elements as follows:
820     data[(index0-lbound0)*stride0 + (index1-lbound1)*stride1]
821    Obviously this is much slower.  I will make this a compile time
822    option, something like -fsmall-array-offsets.  Mixing code compiled
823    with and without this switch will work.
824
825    (1) This can be worked around by modifying the upper bound of the
826    previous dimension.  This requires extra fields in the descriptor
827    (both real_ubound and fake_ubound).  */
828
829
830 /* Returns true if the array sym does not require a descriptor.  */
831
832 int
833 gfc_is_nodesc_array (gfc_symbol * sym)
834 {
835   gcc_assert (sym->attr.dimension);
836
837   /* We only want local arrays.  */
838   if (sym->attr.pointer || sym->attr.allocatable)
839     return 0;
840
841   if (sym->attr.dummy)
842     {
843       if (sym->as->type != AS_ASSUMED_SHAPE)
844         return 1;
845       else
846         return 0;
847     }
848
849   if (sym->attr.result || sym->attr.function)
850     return 0;
851
852   gcc_assert (sym->as->type == AS_EXPLICIT);
853
854   return 1;
855 }
856
857
858 /* Create an array descriptor type.  */
859
860 static tree
861 gfc_build_array_type (tree type, gfc_array_spec * as)
862 {
863   tree lbound[GFC_MAX_DIMENSIONS];
864   tree ubound[GFC_MAX_DIMENSIONS];
865   int n;
866
867   for (n = 0; n < as->rank; n++)
868     {
869       /* Create expressions for the known bounds of the array.  */
870       if (as->type == AS_ASSUMED_SHAPE && as->lower[n] == NULL)
871         lbound[n] = gfc_index_one_node;
872       else
873         lbound[n] = gfc_conv_array_bound (as->lower[n]);
874       ubound[n] = gfc_conv_array_bound (as->upper[n]);
875     }
876
877   return gfc_get_array_type_bounds (type, as->rank, lbound, ubound, 0);
878 }
879 \f
880 /* Returns the struct descriptor_dimension type.  */
881
882 static tree
883 gfc_get_desc_dim_type (void)
884 {
885   tree type;
886   tree decl;
887   tree fieldlist;
888
889   if (gfc_desc_dim_type)
890     return gfc_desc_dim_type;
891
892   /* Build the type node.  */
893   type = make_node (RECORD_TYPE);
894
895   TYPE_NAME (type) = get_identifier ("descriptor_dimension");
896   TYPE_PACKED (type) = 1;
897
898   /* Consists of the stride, lbound and ubound members.  */
899   decl = build_decl (FIELD_DECL,
900                      get_identifier ("stride"), gfc_array_index_type);
901   DECL_CONTEXT (decl) = type;
902   fieldlist = decl;
903
904   decl = build_decl (FIELD_DECL,
905                      get_identifier ("lbound"), gfc_array_index_type);
906   DECL_CONTEXT (decl) = type;
907   fieldlist = chainon (fieldlist, decl);
908
909   decl = build_decl (FIELD_DECL,
910                      get_identifier ("ubound"), gfc_array_index_type);
911   DECL_CONTEXT (decl) = type;
912   fieldlist = chainon (fieldlist, decl);
913
914   /* Finish off the type.  */
915   TYPE_FIELDS (type) = fieldlist;
916
917   gfc_finish_type (type);
918
919   gfc_desc_dim_type = type;
920   return type;
921 }
922
923
924 /* Return the DTYPE for an array.  This describes the type and type parameters
925    of the array.  */
926 /* TODO: Only call this when the value is actually used, and make all the
927    unknown cases abort.  */
928
929 tree
930 gfc_get_dtype (tree type)
931 {
932   tree size;
933   int n;
934   HOST_WIDE_INT i;
935   tree tmp;
936   tree dtype;
937   tree etype;
938   int rank;
939
940   gcc_assert (GFC_DESCRIPTOR_TYPE_P (type) || GFC_ARRAY_TYPE_P (type));
941
942   if (GFC_TYPE_ARRAY_DTYPE (type))
943     return GFC_TYPE_ARRAY_DTYPE (type);
944
945   rank = GFC_TYPE_ARRAY_RANK (type);
946   etype = gfc_get_element_type (type);
947
948   switch (TREE_CODE (etype))
949     {
950     case INTEGER_TYPE:
951       n = GFC_DTYPE_INTEGER;
952       break;
953
954     case BOOLEAN_TYPE:
955       n = GFC_DTYPE_LOGICAL;
956       break;
957
958     case REAL_TYPE:
959       n = GFC_DTYPE_REAL;
960       break;
961
962     case COMPLEX_TYPE:
963       n = GFC_DTYPE_COMPLEX;
964       break;
965
966     /* We will never have arrays of arrays.  */
967     case RECORD_TYPE:
968       n = GFC_DTYPE_DERIVED;
969       break;
970
971     case ARRAY_TYPE:
972       n = GFC_DTYPE_CHARACTER;
973       break;
974
975     default:
976       /* TODO: Don't do dtype for temporary descriptorless arrays.  */
977       /* We can strange array types for temporary arrays.  */
978       return gfc_index_zero_node;
979     }
980
981   gcc_assert (rank <= GFC_DTYPE_RANK_MASK);
982   size = TYPE_SIZE_UNIT (etype);
983
984   i = rank | (n << GFC_DTYPE_TYPE_SHIFT);
985   if (size && INTEGER_CST_P (size))
986     {
987       if (tree_int_cst_lt (gfc_max_array_element_size, size))
988         internal_error ("Array element size too big");
989
990       i += TREE_INT_CST_LOW (size) << GFC_DTYPE_SIZE_SHIFT;
991     }
992   dtype = build_int_cst (gfc_array_index_type, i);
993
994   if (size && !INTEGER_CST_P (size))
995     {
996       tmp = build_int_cst (gfc_array_index_type, GFC_DTYPE_SIZE_SHIFT);
997       tmp  = fold_build2 (LSHIFT_EXPR, gfc_array_index_type,
998                           fold_convert (gfc_array_index_type, size), tmp);
999       dtype = fold_build2 (PLUS_EXPR, gfc_array_index_type, tmp, dtype);
1000     }
1001   /* If we don't know the size we leave it as zero.  This should never happen
1002      for anything that is actually used.  */
1003   /* TODO: Check this is actually true, particularly when repacking
1004      assumed size parameters.  */
1005
1006   GFC_TYPE_ARRAY_DTYPE (type) = dtype;
1007   return dtype;
1008 }
1009
1010
1011 /* Build an array type for use without a descriptor, packed according
1012    to the value of PACKED.  */
1013
1014 tree
1015 gfc_get_nodesc_array_type (tree etype, gfc_array_spec * as, gfc_packed packed)
1016 {
1017   tree range;
1018   tree type;
1019   tree tmp;
1020   int n;
1021   int known_stride;
1022   int known_offset;
1023   mpz_t offset;
1024   mpz_t stride;
1025   mpz_t delta;
1026   gfc_expr *expr;
1027
1028   mpz_init_set_ui (offset, 0);
1029   mpz_init_set_ui (stride, 1);
1030   mpz_init (delta);
1031
1032   /* We don't use build_array_type because this does not include include
1033      lang-specific information (i.e. the bounds of the array) when checking
1034      for duplicates.  */
1035   type = make_node (ARRAY_TYPE);
1036
1037   GFC_ARRAY_TYPE_P (type) = 1;
1038   TYPE_LANG_SPECIFIC (type) = (struct lang_type *)
1039     ggc_alloc_cleared (sizeof (struct lang_type));
1040
1041   known_stride = (packed != PACKED_NO);
1042   known_offset = 1;
1043   for (n = 0; n < as->rank; n++)
1044     {
1045       /* Fill in the stride and bound components of the type.  */
1046       if (known_stride)
1047         tmp =  gfc_conv_mpz_to_tree (stride, gfc_index_integer_kind);
1048       else
1049         tmp = NULL_TREE;
1050       GFC_TYPE_ARRAY_STRIDE (type, n) = tmp;
1051
1052       expr = as->lower[n];
1053       if (expr->expr_type == EXPR_CONSTANT)
1054         {
1055           tmp = gfc_conv_mpz_to_tree (expr->value.integer,
1056                                   gfc_index_integer_kind);
1057         }
1058       else
1059         {
1060           known_stride = 0;
1061           tmp = NULL_TREE;
1062         }
1063       GFC_TYPE_ARRAY_LBOUND (type, n) = tmp;
1064
1065       if (known_stride)
1066         {
1067           /* Calculate the offset.  */
1068           mpz_mul (delta, stride, as->lower[n]->value.integer);
1069           mpz_sub (offset, offset, delta);
1070         }
1071       else
1072         known_offset = 0;
1073
1074       expr = as->upper[n];
1075       if (expr && expr->expr_type == EXPR_CONSTANT)
1076         {
1077           tmp = gfc_conv_mpz_to_tree (expr->value.integer,
1078                                   gfc_index_integer_kind);
1079         }
1080       else
1081         {
1082           tmp = NULL_TREE;
1083           known_stride = 0;
1084         }
1085       GFC_TYPE_ARRAY_UBOUND (type, n) = tmp;
1086
1087       if (known_stride)
1088         {
1089           /* Calculate the stride.  */
1090           mpz_sub (delta, as->upper[n]->value.integer,
1091                    as->lower[n]->value.integer);
1092           mpz_add_ui (delta, delta, 1);
1093           mpz_mul (stride, stride, delta);
1094         }
1095
1096       /* Only the first stride is known for partial packed arrays.  */
1097       if (packed == PACKED_NO || packed == PACKED_PARTIAL)
1098         known_stride = 0;
1099     }
1100
1101   if (known_offset)
1102     {
1103       GFC_TYPE_ARRAY_OFFSET (type) =
1104         gfc_conv_mpz_to_tree (offset, gfc_index_integer_kind);
1105     }
1106   else
1107     GFC_TYPE_ARRAY_OFFSET (type) = NULL_TREE;
1108
1109   if (known_stride)
1110     {
1111       GFC_TYPE_ARRAY_SIZE (type) =
1112         gfc_conv_mpz_to_tree (stride, gfc_index_integer_kind);
1113     }
1114   else
1115     GFC_TYPE_ARRAY_SIZE (type) = NULL_TREE;
1116
1117   GFC_TYPE_ARRAY_RANK (type) = as->rank;
1118   GFC_TYPE_ARRAY_DTYPE (type) = NULL_TREE;
1119   range = build_range_type (gfc_array_index_type, gfc_index_zero_node,
1120                             NULL_TREE);
1121   /* TODO: use main type if it is unbounded.  */
1122   GFC_TYPE_ARRAY_DATAPTR_TYPE (type) =
1123     build_pointer_type (build_array_type (etype, range));
1124
1125   if (known_stride)
1126     {
1127       mpz_sub_ui (stride, stride, 1);
1128       range = gfc_conv_mpz_to_tree (stride, gfc_index_integer_kind);
1129     }
1130   else
1131     range = NULL_TREE;
1132
1133   range = build_range_type (gfc_array_index_type, gfc_index_zero_node, range);
1134   TYPE_DOMAIN (type) = range;
1135
1136   build_pointer_type (etype);
1137   TREE_TYPE (type) = etype;
1138
1139   layout_type (type);
1140
1141   mpz_clear (offset);
1142   mpz_clear (stride);
1143   mpz_clear (delta);
1144
1145   if (packed != PACKED_STATIC || !known_stride)
1146     {
1147       /* For dummy arrays and automatic (heap allocated) arrays we
1148          want a pointer to the array.  */
1149       type = build_pointer_type (type);
1150       GFC_ARRAY_TYPE_P (type) = 1;
1151       TYPE_LANG_SPECIFIC (type) = TYPE_LANG_SPECIFIC (TREE_TYPE (type));
1152     }
1153   return type;
1154 }
1155
1156 /* Return or create the base type for an array descriptor.  */
1157
1158 static tree
1159 gfc_get_array_descriptor_base (int dimen)
1160 {
1161   tree fat_type, fieldlist, decl, arraytype;
1162   char name[16 + GFC_RANK_DIGITS + 1];
1163
1164   gcc_assert (dimen >= 1 && dimen <= GFC_MAX_DIMENSIONS);
1165   if (gfc_array_descriptor_base[dimen - 1])
1166     return gfc_array_descriptor_base[dimen - 1];
1167
1168   /* Build the type node.  */
1169   fat_type = make_node (RECORD_TYPE);
1170
1171   sprintf (name, "array_descriptor" GFC_RANK_PRINTF_FORMAT, dimen);
1172   TYPE_NAME (fat_type) = get_identifier (name);
1173
1174   /* Add the data member as the first element of the descriptor.  */
1175   decl = build_decl (FIELD_DECL, get_identifier ("data"), ptr_type_node);
1176
1177   DECL_CONTEXT (decl) = fat_type;
1178   fieldlist = decl;
1179
1180   /* Add the base component.  */
1181   decl = build_decl (FIELD_DECL, get_identifier ("offset"),
1182                      gfc_array_index_type);
1183   DECL_CONTEXT (decl) = fat_type;
1184   fieldlist = chainon (fieldlist, decl);
1185
1186   /* Add the dtype component.  */
1187   decl = build_decl (FIELD_DECL, get_identifier ("dtype"),
1188                      gfc_array_index_type);
1189   DECL_CONTEXT (decl) = fat_type;
1190   fieldlist = chainon (fieldlist, decl);
1191
1192   /* Build the array type for the stride and bound components.  */
1193   arraytype =
1194     build_array_type (gfc_get_desc_dim_type (),
1195                       build_range_type (gfc_array_index_type,
1196                                         gfc_index_zero_node,
1197                                         gfc_rank_cst[dimen - 1]));
1198
1199   decl = build_decl (FIELD_DECL, get_identifier ("dim"), arraytype);
1200   DECL_CONTEXT (decl) = fat_type;
1201   fieldlist = chainon (fieldlist, decl);
1202
1203   /* Finish off the type.  */
1204   TYPE_FIELDS (fat_type) = fieldlist;
1205
1206   gfc_finish_type (fat_type);
1207
1208   gfc_array_descriptor_base[dimen - 1] = fat_type;
1209   return fat_type;
1210 }
1211
1212 /* Build an array (descriptor) type with given bounds.  */
1213
1214 tree
1215 gfc_get_array_type_bounds (tree etype, int dimen, tree * lbound,
1216                            tree * ubound, int packed)
1217 {
1218   char name[8 + GFC_RANK_DIGITS + GFC_MAX_SYMBOL_LEN];
1219   tree fat_type, base_type, arraytype, lower, upper, stride, tmp;
1220   const char *typename;
1221   int n;
1222
1223   base_type = gfc_get_array_descriptor_base (dimen);
1224   fat_type = build_variant_type_copy (base_type);
1225
1226   tmp = TYPE_NAME (etype);
1227   if (tmp && TREE_CODE (tmp) == TYPE_DECL)
1228     tmp = DECL_NAME (tmp);
1229   if (tmp)
1230     typename = IDENTIFIER_POINTER (tmp);
1231   else
1232     typename = "unknown";
1233   sprintf (name, "array" GFC_RANK_PRINTF_FORMAT "_%.*s", dimen,
1234            GFC_MAX_SYMBOL_LEN, typename);
1235   TYPE_NAME (fat_type) = get_identifier (name);
1236
1237   GFC_DESCRIPTOR_TYPE_P (fat_type) = 1;
1238   TYPE_LANG_SPECIFIC (fat_type) = (struct lang_type *)
1239     ggc_alloc_cleared (sizeof (struct lang_type));
1240
1241   GFC_TYPE_ARRAY_RANK (fat_type) = dimen;
1242   GFC_TYPE_ARRAY_DTYPE (fat_type) = NULL_TREE;
1243
1244   /* Build an array descriptor record type.  */
1245   if (packed != 0)
1246     stride = gfc_index_one_node;
1247   else
1248     stride = NULL_TREE;
1249   for (n = 0; n < dimen; n++)
1250     {
1251       GFC_TYPE_ARRAY_STRIDE (fat_type, n) = stride;
1252
1253       if (lbound)
1254         lower = lbound[n];
1255       else
1256         lower = NULL_TREE;
1257
1258       if (lower != NULL_TREE)
1259         {
1260           if (INTEGER_CST_P (lower))
1261             GFC_TYPE_ARRAY_LBOUND (fat_type, n) = lower;
1262           else
1263             lower = NULL_TREE;
1264         }
1265
1266       upper = ubound[n];
1267       if (upper != NULL_TREE)
1268         {
1269           if (INTEGER_CST_P (upper))
1270             GFC_TYPE_ARRAY_UBOUND (fat_type, n) = upper;
1271           else
1272             upper = NULL_TREE;
1273         }
1274
1275       if (upper != NULL_TREE && lower != NULL_TREE && stride != NULL_TREE)
1276         {
1277           tmp = fold_build2 (MINUS_EXPR, gfc_array_index_type, upper, lower);
1278           tmp = fold_build2 (PLUS_EXPR, gfc_array_index_type, tmp,
1279                              gfc_index_one_node);
1280           stride =
1281             fold_build2 (MULT_EXPR, gfc_array_index_type, tmp, stride);
1282           /* Check the folding worked.  */
1283           gcc_assert (INTEGER_CST_P (stride));
1284         }
1285       else
1286         stride = NULL_TREE;
1287     }
1288   GFC_TYPE_ARRAY_SIZE (fat_type) = stride;
1289
1290   /* TODO: known offsets for descriptors.  */
1291   GFC_TYPE_ARRAY_OFFSET (fat_type) = NULL_TREE;
1292
1293   /* We define data as an unknown size array. Much better than doing
1294      pointer arithmetic.  */
1295   arraytype =
1296     build_array_type (etype, gfc_array_range_type);
1297   arraytype = build_pointer_type (arraytype);
1298   GFC_TYPE_ARRAY_DATAPTR_TYPE (fat_type) = arraytype;
1299
1300   return fat_type;
1301 }
1302 \f
1303 /* Build a pointer type. This function is called from gfc_sym_type().  */
1304
1305 static tree
1306 gfc_build_pointer_type (gfc_symbol * sym, tree type)
1307 {
1308   /* Array pointer types aren't actually pointers.  */
1309   if (sym->attr.dimension)
1310     return type;
1311   else
1312     return build_pointer_type (type);
1313 }
1314 \f
1315 /* Return the type for a symbol.  Special handling is required for character
1316    types to get the correct level of indirection.
1317    For functions return the return type.
1318    For subroutines return void_type_node.
1319    Calling this multiple times for the same symbol should be avoided,
1320    especially for character and array types.  */
1321
1322 tree
1323 gfc_sym_type (gfc_symbol * sym)
1324 {
1325   tree type;
1326   int byref;
1327
1328   if (sym->attr.flavor == FL_PROCEDURE && !sym->attr.function)
1329     return void_type_node;
1330
1331   /* In the case of a function the fake result variable may have a
1332      type different from the function type, so don't return early in
1333      that case.  */
1334   if (sym->backend_decl && !sym->attr.function)
1335     return TREE_TYPE (sym->backend_decl);
1336
1337   type = gfc_typenode_for_spec (&sym->ts);
1338
1339   if (sym->attr.dummy && !sym->attr.function && !sym->attr.value)
1340     byref = 1;
1341   else
1342     byref = 0;
1343
1344   if (sym->attr.dimension)
1345     {
1346       if (gfc_is_nodesc_array (sym))
1347         {
1348           /* If this is a character argument of unknown length, just use the
1349              base type.  */
1350           if (sym->ts.type != BT_CHARACTER
1351               || !(sym->attr.dummy || sym->attr.function)
1352               || sym->ts.cl->backend_decl)
1353             {
1354               type = gfc_get_nodesc_array_type (type, sym->as,
1355                                                 byref ? PACKED_FULL
1356                                                       : PACKED_STATIC);
1357               byref = 0;
1358             }
1359         }
1360       else
1361         type = gfc_build_array_type (type, sym->as);
1362     }
1363   else
1364     {
1365       if (sym->attr.allocatable || sym->attr.pointer)
1366         type = gfc_build_pointer_type (sym, type);
1367     }
1368
1369   /* We currently pass all parameters by reference.
1370      See f95_get_function_decl.  For dummy function parameters return the
1371      function type.  */
1372   if (byref)
1373     {
1374       /* We must use pointer types for potentially absent variables.  The
1375          optimizers assume a reference type argument is never NULL.  */
1376       if (sym->attr.optional || sym->ns->proc_name->attr.entry_master)
1377         type = build_pointer_type (type);
1378       else
1379         type = build_reference_type (type);
1380     }
1381
1382   return (type);
1383 }
1384 \f
1385 /* Layout and output debug info for a record type.  */
1386
1387 void
1388 gfc_finish_type (tree type)
1389 {
1390   tree decl;
1391
1392   decl = build_decl (TYPE_DECL, NULL_TREE, type);
1393   TYPE_STUB_DECL (type) = decl;
1394   layout_type (type);
1395   rest_of_type_compilation (type, 1);
1396   rest_of_decl_compilation (decl, 1, 0);
1397 }
1398 \f
1399 /* Add a field of given NAME and TYPE to the context of a UNION_TYPE
1400    or RECORD_TYPE pointed to by STYPE.  The new field is chained
1401    to the fieldlist pointed to by FIELDLIST.
1402
1403    Returns a pointer to the new field.  */
1404
1405 tree
1406 gfc_add_field_to_struct (tree *fieldlist, tree context,
1407                          tree name, tree type)
1408 {
1409   tree decl;
1410
1411   decl = build_decl (FIELD_DECL, name, type);
1412
1413   DECL_CONTEXT (decl) = context;
1414   DECL_INITIAL (decl) = 0;
1415   DECL_ALIGN (decl) = 0;
1416   DECL_USER_ALIGN (decl) = 0;
1417   TREE_CHAIN (decl) = NULL_TREE;
1418   *fieldlist = chainon (*fieldlist, decl);
1419
1420   return decl;
1421 }
1422
1423
1424 /* Copy the backend_decl and component backend_decls if
1425    the two derived type symbols are "equal", as described
1426    in 4.4.2 and resolved by gfc_compare_derived_types.  */
1427
1428 static int
1429 copy_dt_decls_ifequal (gfc_symbol *from, gfc_symbol *to)
1430 {
1431   gfc_component *to_cm;
1432   gfc_component *from_cm;
1433
1434   if (from->backend_decl == NULL
1435         || !gfc_compare_derived_types (from, to))
1436     return 0;
1437
1438   to->backend_decl = from->backend_decl;
1439
1440   to_cm = to->components;
1441   from_cm = from->components;
1442
1443   /* Copy the component declarations.  If a component is itself
1444      a derived type, we need a copy of its component declarations.
1445      This is done by recursing into gfc_get_derived_type and
1446      ensures that the component's component declarations have
1447      been built.  If it is a character, we need the character 
1448      length, as well.  */
1449   for (; to_cm; to_cm = to_cm->next, from_cm = from_cm->next)
1450     {
1451       to_cm->backend_decl = from_cm->backend_decl;
1452       if (!from_cm->pointer && from_cm->ts.type == BT_DERIVED)
1453         gfc_get_derived_type (to_cm->ts.derived);
1454
1455       else if (from_cm->ts.type == BT_CHARACTER)
1456         to_cm->ts.cl->backend_decl = from_cm->ts.cl->backend_decl;
1457     }
1458
1459   return 1;
1460 }
1461
1462
1463 /* Build a tree node for a derived type.  If there are equal
1464    derived types, with different local names, these are built
1465    at the same time.  If an equal derived type has been built
1466    in a parent namespace, this is used.  */
1467
1468 static tree
1469 gfc_get_derived_type (gfc_symbol * derived)
1470 {
1471   tree typenode, field, field_type, fieldlist;
1472   gfc_component *c;
1473   gfc_dt_list *dt;
1474
1475   gcc_assert (derived && derived->attr.flavor == FL_DERIVED);
1476
1477   /* derived->backend_decl != 0 means we saw it before, but its
1478      components' backend_decl may have not been built.  */
1479   if (derived->backend_decl)
1480     {
1481       /* Its components' backend_decl have been built.  */
1482       if (TYPE_FIELDS (derived->backend_decl))
1483         return derived->backend_decl;
1484       else
1485         typenode = derived->backend_decl;
1486     }
1487   else
1488     {
1489
1490       /* We see this derived type first time, so build the type node.  */
1491       typenode = make_node (RECORD_TYPE);
1492       TYPE_NAME (typenode) = get_identifier (derived->name);
1493       TYPE_PACKED (typenode) = gfc_option.flag_pack_derived;
1494       derived->backend_decl = typenode;
1495     }
1496
1497   /* Go through the derived type components, building them as
1498      necessary. The reason for doing this now is that it is
1499      possible to recurse back to this derived type through a
1500      pointer component (PR24092). If this happens, the fields
1501      will be built and so we can return the type.  */
1502   for (c = derived->components; c; c = c->next)
1503     {
1504       if (c->ts.type != BT_DERIVED)
1505         continue;
1506
1507       if (!c->pointer || c->ts.derived->backend_decl == NULL)
1508         c->ts.derived->backend_decl = gfc_get_derived_type (c->ts.derived);
1509     }
1510
1511   if (TYPE_FIELDS (derived->backend_decl))
1512     return derived->backend_decl;
1513
1514   /* Build the type member list. Install the newly created RECORD_TYPE
1515      node as DECL_CONTEXT of each FIELD_DECL.  */
1516   fieldlist = NULL_TREE;
1517   for (c = derived->components; c; c = c->next)
1518     {
1519       if (c->ts.type == BT_DERIVED)
1520         field_type = c->ts.derived->backend_decl;
1521       else
1522         {
1523           if (c->ts.type == BT_CHARACTER)
1524             {
1525               /* Evaluate the string length.  */
1526               gfc_conv_const_charlen (c->ts.cl);
1527               gcc_assert (c->ts.cl->backend_decl);
1528             }
1529
1530           field_type = gfc_typenode_for_spec (&c->ts);
1531         }
1532
1533       /* This returns an array descriptor type.  Initialization may be
1534          required.  */
1535       if (c->dimension)
1536         {
1537           if (c->pointer || c->allocatable)
1538             {
1539               /* Pointers to arrays aren't actually pointer types.  The
1540                  descriptors are separate, but the data is common.  */
1541               field_type = gfc_build_array_type (field_type, c->as);
1542             }
1543           else
1544             field_type = gfc_get_nodesc_array_type (field_type, c->as,
1545                                                     PACKED_STATIC);
1546         }
1547       else if (c->pointer)
1548         field_type = build_pointer_type (field_type);
1549
1550       field = gfc_add_field_to_struct (&fieldlist, typenode,
1551                                        get_identifier (c->name),
1552                                        field_type);
1553
1554       DECL_PACKED (field) |= TYPE_PACKED (typenode);
1555
1556       gcc_assert (field);
1557       if (!c->backend_decl)
1558         c->backend_decl = field;
1559     }
1560
1561   /* Now we have the final fieldlist.  Record it, then lay out the
1562      derived type, including the fields.  */
1563   TYPE_FIELDS (typenode) = fieldlist;
1564
1565   gfc_finish_type (typenode);
1566
1567   derived->backend_decl = typenode;
1568
1569     /* Add this backend_decl to all the other, equal derived types.  */
1570     for (dt = gfc_derived_types; dt; dt = dt->next)
1571       copy_dt_decls_ifequal (derived, dt->derived);
1572
1573   return derived->backend_decl;
1574 }
1575
1576
1577 int
1578 gfc_return_by_reference (gfc_symbol * sym)
1579 {
1580   if (!sym->attr.function)
1581     return 0;
1582
1583   if (sym->attr.dimension)
1584     return 1;
1585
1586   if (sym->ts.type == BT_CHARACTER)
1587     return 1;
1588
1589   /* Possibly return complex numbers by reference for g77 compatibility.
1590      We don't do this for calls to intrinsics (as the library uses the
1591      -fno-f2c calling convention), nor for calls to functions which always
1592      require an explicit interface, as no compatibility problems can
1593      arise there.  */
1594   if (gfc_option.flag_f2c
1595       && sym->ts.type == BT_COMPLEX
1596       && !sym->attr.intrinsic && !sym->attr.always_explicit)
1597     return 1;
1598
1599   return 0;
1600 }
1601 \f
1602 static tree
1603 gfc_get_mixed_entry_union (gfc_namespace *ns)
1604 {
1605   tree type;
1606   tree decl;
1607   tree fieldlist;
1608   char name[GFC_MAX_SYMBOL_LEN + 1];
1609   gfc_entry_list *el, *el2;
1610
1611   gcc_assert (ns->proc_name->attr.mixed_entry_master);
1612   gcc_assert (memcmp (ns->proc_name->name, "master.", 7) == 0);
1613
1614   snprintf (name, GFC_MAX_SYMBOL_LEN, "munion.%s", ns->proc_name->name + 7);
1615
1616   /* Build the type node.  */
1617   type = make_node (UNION_TYPE);
1618
1619   TYPE_NAME (type) = get_identifier (name);
1620   fieldlist = NULL;
1621
1622   for (el = ns->entries; el; el = el->next)
1623     {
1624       /* Search for duplicates.  */
1625       for (el2 = ns->entries; el2 != el; el2 = el2->next)
1626         if (el2->sym->result == el->sym->result)
1627           break;
1628
1629       if (el == el2)
1630         {
1631           decl = build_decl (FIELD_DECL,
1632                              get_identifier (el->sym->result->name),
1633                              gfc_sym_type (el->sym->result));
1634           DECL_CONTEXT (decl) = type;
1635           fieldlist = chainon (fieldlist, decl);
1636         }
1637     }
1638
1639   /* Finish off the type.  */
1640   TYPE_FIELDS (type) = fieldlist;
1641
1642   gfc_finish_type (type);
1643   return type;
1644 }
1645 \f
1646 tree
1647 gfc_get_function_type (gfc_symbol * sym)
1648 {
1649   tree type;
1650   tree typelist;
1651   gfc_formal_arglist *f;
1652   gfc_symbol *arg;
1653   int nstr;
1654   int alternate_return;
1655
1656   /* Make sure this symbol is a function or a subroutine.  */
1657   gcc_assert (sym->attr.flavor == FL_PROCEDURE);
1658
1659   if (sym->backend_decl)
1660     return TREE_TYPE (sym->backend_decl);
1661
1662   nstr = 0;
1663   alternate_return = 0;
1664   typelist = NULL_TREE;
1665
1666   if (sym->attr.entry_master)
1667     {
1668       /* Additional parameter for selecting an entry point.  */
1669       typelist = gfc_chainon_list (typelist, gfc_array_index_type);
1670     }
1671
1672   /* Some functions we use an extra parameter for the return value.  */
1673   if (gfc_return_by_reference (sym))
1674     {
1675       if (sym->result)
1676         arg = sym->result;
1677       else
1678         arg = sym;
1679
1680       if (arg->ts.type == BT_CHARACTER)
1681         gfc_conv_const_charlen (arg->ts.cl);
1682
1683       type = gfc_sym_type (arg);
1684       if (arg->ts.type == BT_COMPLEX
1685           || arg->attr.dimension
1686           || arg->ts.type == BT_CHARACTER)
1687         type = build_reference_type (type);
1688
1689       typelist = gfc_chainon_list (typelist, type);
1690       if (arg->ts.type == BT_CHARACTER)
1691         typelist = gfc_chainon_list (typelist, gfc_charlen_type_node);
1692     }
1693
1694   /* Build the argument types for the function.  */
1695   for (f = sym->formal; f; f = f->next)
1696     {
1697       arg = f->sym;
1698       if (arg)
1699         {
1700           /* Evaluate constant character lengths here so that they can be
1701              included in the type.  */
1702           if (arg->ts.type == BT_CHARACTER)
1703             gfc_conv_const_charlen (arg->ts.cl);
1704
1705           if (arg->attr.flavor == FL_PROCEDURE)
1706             {
1707               type = gfc_get_function_type (arg);
1708               type = build_pointer_type (type);
1709             }
1710           else
1711             type = gfc_sym_type (arg);
1712
1713           /* Parameter Passing Convention
1714
1715              We currently pass all parameters by reference.
1716              Parameters with INTENT(IN) could be passed by value.
1717              The problem arises if a function is called via an implicit
1718              prototype. In this situation the INTENT is not known.
1719              For this reason all parameters to global functions must be
1720              passed by reference.  Passing by value would potentially
1721              generate bad code.  Worse there would be no way of telling that
1722              this code was bad, except that it would give incorrect results.
1723
1724              Contained procedures could pass by value as these are never
1725              used without an explicit interface, and cannot be passed as
1726              actual parameters for a dummy procedure.  */
1727           if (arg->ts.type == BT_CHARACTER)
1728             nstr++;
1729           typelist = gfc_chainon_list (typelist, type);
1730         }
1731       else
1732         {
1733           if (sym->attr.subroutine)
1734             alternate_return = 1;
1735         }
1736     }
1737
1738   /* Add hidden string length parameters.  */
1739   while (nstr--)
1740     typelist = gfc_chainon_list (typelist, gfc_charlen_type_node);
1741
1742   if (typelist)
1743     typelist = gfc_chainon_list (typelist, void_type_node);
1744
1745   if (alternate_return)
1746     type = integer_type_node;
1747   else if (!sym->attr.function || gfc_return_by_reference (sym))
1748     type = void_type_node;
1749   else if (sym->attr.mixed_entry_master)
1750     type = gfc_get_mixed_entry_union (sym->ns);
1751   else if (gfc_option.flag_f2c
1752            && sym->ts.type == BT_REAL
1753            && sym->ts.kind == gfc_default_real_kind
1754            && !sym->attr.always_explicit)
1755     {
1756       /* Special case: f2c calling conventions require that (scalar) 
1757          default REAL functions return the C type double instead.  f2c
1758          compatibility is only an issue with functions that don't
1759          require an explicit interface, as only these could be
1760          implemented in Fortran 77.  */
1761       sym->ts.kind = gfc_default_double_kind;
1762       type = gfc_typenode_for_spec (&sym->ts);
1763       sym->ts.kind = gfc_default_real_kind;
1764     }
1765   else
1766     type = gfc_sym_type (sym);
1767
1768   type = build_function_type (type, typelist);
1769
1770   return type;
1771 }
1772 \f
1773 /* Language hooks for middle-end access to type nodes.  */
1774
1775 /* Return an integer type with BITS bits of precision,
1776    that is unsigned if UNSIGNEDP is nonzero, otherwise signed.  */
1777
1778 tree
1779 gfc_type_for_size (unsigned bits, int unsignedp)
1780 {
1781   if (!unsignedp)
1782     {
1783       int i;
1784       for (i = 0; i <= MAX_INT_KINDS; ++i)
1785         {
1786           tree type = gfc_integer_types[i];
1787           if (type && bits == TYPE_PRECISION (type))
1788             return type;
1789         }
1790
1791       /* Handle TImode as a special case because it is used by some backends
1792          (eg. ARM) even though it is not available for normal use.  */
1793 #if HOST_BITS_PER_WIDE_INT >= 64
1794       if (bits == TYPE_PRECISION (intTI_type_node))
1795         return intTI_type_node;
1796 #endif
1797     }
1798   else
1799     {
1800       if (bits == TYPE_PRECISION (unsigned_intQI_type_node))
1801         return unsigned_intQI_type_node;
1802       if (bits == TYPE_PRECISION (unsigned_intHI_type_node))
1803         return unsigned_intHI_type_node;
1804       if (bits == TYPE_PRECISION (unsigned_intSI_type_node))
1805         return unsigned_intSI_type_node;
1806       if (bits == TYPE_PRECISION (unsigned_intDI_type_node))
1807         return unsigned_intDI_type_node;
1808       if (bits == TYPE_PRECISION (unsigned_intTI_type_node))
1809         return unsigned_intTI_type_node;
1810     }
1811
1812   return NULL_TREE;
1813 }
1814
1815 /* Return a data type that has machine mode MODE.  If the mode is an
1816    integer, then UNSIGNEDP selects between signed and unsigned types.  */
1817
1818 tree
1819 gfc_type_for_mode (enum machine_mode mode, int unsignedp)
1820 {
1821   int i;
1822   tree *base;
1823
1824   if (GET_MODE_CLASS (mode) == MODE_FLOAT)
1825     base = gfc_real_types;
1826   else if (GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT)
1827     base = gfc_complex_types;
1828   else if (SCALAR_INT_MODE_P (mode))
1829     return gfc_type_for_size (GET_MODE_PRECISION (mode), unsignedp);
1830   else if (VECTOR_MODE_P (mode))
1831     {
1832       enum machine_mode inner_mode = GET_MODE_INNER (mode);
1833       tree inner_type = gfc_type_for_mode (inner_mode, unsignedp);
1834       if (inner_type != NULL_TREE)
1835         return build_vector_type_for_mode (inner_type, mode);
1836       return NULL_TREE;
1837     }
1838   else
1839     return NULL_TREE;
1840
1841   for (i = 0; i <= MAX_REAL_KINDS; ++i)
1842     {
1843       tree type = base[i];
1844       if (type && mode == TYPE_MODE (type))
1845         return type;
1846     }
1847
1848   return NULL_TREE;
1849 }
1850
1851 /* Return a signed type the same as TYPE in other respects.  */
1852
1853 tree
1854 gfc_signed_type (tree type)
1855 {
1856   return get_signed_or_unsigned_type (0, type);
1857 }
1858
1859 #include "gt-fortran-trans-types.h"