OSDN Git Service

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