OSDN Git Service

86575b529d953115250978382e1e7b636f8fdf6c
[pf3gnuchains/gcc-fork.git] / gcc / ada / gcc-interface / utils.c
1 /****************************************************************************
2  *                                                                          *
3  *                         GNAT COMPILER COMPONENTS                         *
4  *                                                                          *
5  *                                U T I L S                                 *
6  *                                                                          *
7  *                          C Implementation File                           *
8  *                                                                          *
9  *          Copyright (C) 1992-2009, Free Software Foundation, Inc.         *
10  *                                                                          *
11  * GNAT is free software;  you can  redistribute it  and/or modify it under *
12  * terms of the  GNU General Public License as published  by the Free Soft- *
13  * ware  Foundation;  either version 3,  or (at your option) any later ver- *
14  * sion.  GNAT is distributed in the hope that it will be useful, but WITH- *
15  * OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY *
16  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License *
17  * for  more details.  You should have received a copy of the GNU General   *
18  * Public License along with GCC; see the file COPYING3.  If not see        *
19  * <http://www.gnu.org/licenses/>.                                          *
20  *                                                                          *
21  * GNAT was originally developed  by the GNAT team at  New York University. *
22  * Extensive contributions were provided by Ada Core Technologies Inc.      *
23  *                                                                          *
24  ****************************************************************************/
25
26 #include "config.h"
27 #include "system.h"
28 #include "coretypes.h"
29 #include "tm.h"
30 #include "tree.h"
31 #include "flags.h"
32 #include "toplev.h"
33 #include "rtl.h"
34 #include "output.h"
35 #include "ggc.h"
36 #include "debug.h"
37 #include "convert.h"
38 #include "target.h"
39 #include "function.h"
40 #include "langhooks.h"
41 #include "pointer-set.h"
42 #include "cgraph.h"
43 #include "tree-dump.h"
44 #include "tree-inline.h"
45 #include "tree-iterator.h"
46 #include "gimple.h"
47
48 #include "ada.h"
49 #include "types.h"
50 #include "atree.h"
51 #include "elists.h"
52 #include "namet.h"
53 #include "nlists.h"
54 #include "stringt.h"
55 #include "uintp.h"
56 #include "fe.h"
57 #include "sinfo.h"
58 #include "einfo.h"
59 #include "ada-tree.h"
60 #include "gigi.h"
61
62 #ifndef MAX_FIXED_MODE_SIZE
63 #define MAX_FIXED_MODE_SIZE GET_MODE_BITSIZE (DImode)
64 #endif
65
66 #ifndef MAX_BITS_PER_WORD
67 #define MAX_BITS_PER_WORD  BITS_PER_WORD
68 #endif
69
70 /* If nonzero, pretend we are allocating at global level.  */
71 int force_global;
72
73 /* The default alignment of "double" floating-point types, i.e. floating
74    point types whose size is equal to 64 bits, or 0 if this alignment is
75    not specifically capped.  */
76 int double_float_alignment;
77
78 /* The default alignment of "double" or larger scalar types, i.e. scalar
79    types whose size is greater or equal to 64 bits, or 0 if this alignment
80    is not specifically capped.  */
81 int double_scalar_alignment;
82
83 /* Tree nodes for the various types and decls we create.  */
84 tree gnat_std_decls[(int) ADT_LAST];
85
86 /* Functions to call for each of the possible raise reasons.  */
87 tree gnat_raise_decls[(int) LAST_REASON_CODE + 1];
88
89 /* Forward declarations for handlers of attributes.  */
90 static tree handle_const_attribute (tree *, tree, tree, int, bool *);
91 static tree handle_nothrow_attribute (tree *, tree, tree, int, bool *);
92 static tree handle_pure_attribute (tree *, tree, tree, int, bool *);
93 static tree handle_novops_attribute (tree *, tree, tree, int, bool *);
94 static tree handle_nonnull_attribute (tree *, tree, tree, int, bool *);
95 static tree handle_sentinel_attribute (tree *, tree, tree, int, bool *);
96 static tree handle_noreturn_attribute (tree *, tree, tree, int, bool *);
97 static tree handle_malloc_attribute (tree *, tree, tree, int, bool *);
98 static tree handle_type_generic_attribute (tree *, tree, tree, int, bool *);
99 static tree handle_vector_size_attribute (tree *, tree, tree, int, bool *);
100 static tree handle_vector_type_attribute (tree *, tree, tree, int, bool *);
101
102 /* Fake handler for attributes we don't properly support, typically because
103    they'd require dragging a lot of the common-c front-end circuitry.  */
104 static tree fake_attribute_handler      (tree *, tree, tree, int, bool *);
105
106 /* Table of machine-independent internal attributes for Ada.  We support
107    this minimal set of attributes to accommodate the needs of builtins.  */
108 const struct attribute_spec gnat_internal_attribute_table[] =
109 {
110   /* { name, min_len, max_len, decl_req, type_req, fn_type_req, handler } */
111   { "const",        0, 0,  true,  false, false, handle_const_attribute   },
112   { "nothrow",      0, 0,  true,  false, false, handle_nothrow_attribute },
113   { "pure",         0, 0,  true,  false, false, handle_pure_attribute },
114   { "no vops",      0, 0,  true,  false, false, handle_novops_attribute },
115   { "nonnull",      0, -1, false, true,  true,  handle_nonnull_attribute },
116   { "sentinel",     0, 1,  false, true,  true,  handle_sentinel_attribute },
117   { "noreturn",     0, 0,  true,  false, false, handle_noreturn_attribute },
118   { "malloc",       0, 0,  true,  false, false, handle_malloc_attribute },
119   { "type generic", 0, 0,  false, true, true, handle_type_generic_attribute },
120
121   { "vector_size",  1, 1,  false, true, false,  handle_vector_size_attribute },
122   { "vector_type",  0, 0,  false, true, false,  handle_vector_type_attribute },
123   { "may_alias",    0, 0, false, true, false, NULL },
124
125   /* ??? format and format_arg are heavy and not supported, which actually
126      prevents support for stdio builtins, which we however declare as part
127      of the common builtins.def contents.  */
128   { "format",     3, 3,  false, true,  true,  fake_attribute_handler },
129   { "format_arg", 1, 1,  false, true,  true,  fake_attribute_handler },
130
131   { NULL,         0, 0, false, false, false, NULL }
132 };
133
134 /* Associates a GNAT tree node to a GCC tree node. It is used in
135    `save_gnu_tree', `get_gnu_tree' and `present_gnu_tree'. See documentation
136    of `save_gnu_tree' for more info.  */
137 static GTY((length ("max_gnat_nodes"))) tree *associate_gnat_to_gnu;
138
139 #define GET_GNU_TREE(GNAT_ENTITY)       \
140   associate_gnat_to_gnu[(GNAT_ENTITY) - First_Node_Id]
141
142 #define SET_GNU_TREE(GNAT_ENTITY,VAL)   \
143   associate_gnat_to_gnu[(GNAT_ENTITY) - First_Node_Id] = (VAL)
144
145 #define PRESENT_GNU_TREE(GNAT_ENTITY)   \
146   (associate_gnat_to_gnu[(GNAT_ENTITY) - First_Node_Id] != NULL_TREE)
147
148 /* Associates a GNAT entity to a GCC tree node used as a dummy, if any.  */
149 static GTY((length ("max_gnat_nodes"))) tree *dummy_node_table;
150
151 #define GET_DUMMY_NODE(GNAT_ENTITY)     \
152   dummy_node_table[(GNAT_ENTITY) - First_Node_Id]
153
154 #define SET_DUMMY_NODE(GNAT_ENTITY,VAL) \
155   dummy_node_table[(GNAT_ENTITY) - First_Node_Id] = (VAL)
156
157 #define PRESENT_DUMMY_NODE(GNAT_ENTITY) \
158   (dummy_node_table[(GNAT_ENTITY) - First_Node_Id] != NULL_TREE)
159
160 /* This variable keeps a table for types for each precision so that we only
161    allocate each of them once. Signed and unsigned types are kept separate.
162
163    Note that these types are only used when fold-const requests something
164    special.  Perhaps we should NOT share these types; we'll see how it
165    goes later.  */
166 static GTY(()) tree signed_and_unsigned_types[2 * MAX_BITS_PER_WORD + 1][2];
167
168 /* Likewise for float types, but record these by mode.  */
169 static GTY(()) tree float_types[NUM_MACHINE_MODES];
170
171 /* For each binding contour we allocate a binding_level structure to indicate
172    the binding depth.  */
173
174 struct GTY((chain_next ("%h.chain"))) gnat_binding_level {
175   /* The binding level containing this one (the enclosing binding level). */
176   struct gnat_binding_level *chain;
177   /* The BLOCK node for this level.  */
178   tree block;
179   /* If nonzero, the setjmp buffer that needs to be updated for any
180      variable-sized definition within this context.  */
181   tree jmpbuf_decl;
182 };
183
184 /* The binding level currently in effect.  */
185 static GTY(()) struct gnat_binding_level *current_binding_level;
186
187 /* A chain of gnat_binding_level structures awaiting reuse.  */
188 static GTY((deletable)) struct gnat_binding_level *free_binding_level;
189
190 /* An array of global declarations.  */
191 static GTY(()) VEC(tree,gc) *global_decls;
192
193 /* An array of builtin function declarations.  */
194 static GTY(()) VEC(tree,gc) *builtin_decls;
195
196 /* An array of global renaming pointers.  */
197 static GTY(()) VEC(tree,gc) *global_renaming_pointers;
198
199 /* A chain of unused BLOCK nodes. */
200 static GTY((deletable)) tree free_block_chain;
201
202 static tree merge_sizes (tree, tree, tree, bool, bool);
203 static tree compute_related_constant (tree, tree);
204 static tree split_plus (tree, tree *);
205 static tree float_type_for_precision (int, enum machine_mode);
206 static tree convert_to_fat_pointer (tree, tree);
207 static tree convert_to_thin_pointer (tree, tree);
208 static tree make_descriptor_field (const char *,tree, tree, tree);
209 static bool potential_alignment_gap (tree, tree, tree);
210 \f
211 /* Initialize the association of GNAT nodes to GCC trees.  */
212
213 void
214 init_gnat_to_gnu (void)
215 {
216   associate_gnat_to_gnu
217     = (tree *) ggc_alloc_cleared (max_gnat_nodes * sizeof (tree));
218 }
219
220 /* GNAT_ENTITY is a GNAT tree node for an entity.   GNU_DECL is the GCC tree
221    which is to be associated with GNAT_ENTITY. Such GCC tree node is always
222    a ..._DECL node.  If NO_CHECK is true, the latter check is suppressed.
223
224    If GNU_DECL is zero, a previous association is to be reset.  */
225
226 void
227 save_gnu_tree (Entity_Id gnat_entity, tree gnu_decl, bool no_check)
228 {
229   /* Check that GNAT_ENTITY is not already defined and that it is being set
230      to something which is a decl.  Raise gigi 401 if not.  Usually, this
231      means GNAT_ENTITY is defined twice, but occasionally is due to some
232      Gigi problem.  */
233   gcc_assert (!(gnu_decl
234                 && (PRESENT_GNU_TREE (gnat_entity)
235                     || (!no_check && !DECL_P (gnu_decl)))));
236
237   SET_GNU_TREE (gnat_entity, gnu_decl);
238 }
239
240 /* GNAT_ENTITY is a GNAT tree node for a defining identifier.
241    Return the ..._DECL node that was associated with it.  If there is no tree
242    node associated with GNAT_ENTITY, abort.
243
244    In some cases, such as delayed elaboration or expressions that need to
245    be elaborated only once, GNAT_ENTITY is really not an entity.  */
246
247 tree
248 get_gnu_tree (Entity_Id gnat_entity)
249 {
250   gcc_assert (PRESENT_GNU_TREE (gnat_entity));
251   return GET_GNU_TREE (gnat_entity);
252 }
253
254 /* Return nonzero if a GCC tree has been associated with GNAT_ENTITY.  */
255
256 bool
257 present_gnu_tree (Entity_Id gnat_entity)
258 {
259   return PRESENT_GNU_TREE (gnat_entity);
260 }
261 \f
262 /* Initialize the association of GNAT nodes to GCC trees as dummies.  */
263
264 void
265 init_dummy_type (void)
266 {
267   dummy_node_table
268     = (tree *) ggc_alloc_cleared (max_gnat_nodes * sizeof (tree));
269 }
270
271 /* Make a dummy type corresponding to GNAT_TYPE.  */
272
273 tree
274 make_dummy_type (Entity_Id gnat_type)
275 {
276   Entity_Id gnat_underlying = Gigi_Equivalent_Type (gnat_type);
277   tree gnu_type;
278
279   /* If there is an equivalent type, get its underlying type.  */
280   if (Present (gnat_underlying))
281     gnat_underlying = Underlying_Type (gnat_underlying);
282
283   /* If there was no equivalent type (can only happen when just annotating
284      types) or underlying type, go back to the original type.  */
285   if (No (gnat_underlying))
286     gnat_underlying = gnat_type;
287
288   /* If it there already a dummy type, use that one.  Else make one.  */
289   if (PRESENT_DUMMY_NODE (gnat_underlying))
290     return GET_DUMMY_NODE (gnat_underlying);
291
292   /* If this is a record, make a RECORD_TYPE or UNION_TYPE; else make
293      an ENUMERAL_TYPE.  */
294   gnu_type = make_node (Is_Record_Type (gnat_underlying)
295                         ? tree_code_for_record_type (gnat_underlying)
296                         : ENUMERAL_TYPE);
297   TYPE_NAME (gnu_type) = get_entity_name (gnat_type);
298   TYPE_DUMMY_P (gnu_type) = 1;
299   TYPE_STUB_DECL (gnu_type)
300     = create_type_stub_decl (TYPE_NAME (gnu_type), gnu_type);
301   if (AGGREGATE_TYPE_P (gnu_type))
302     TYPE_BY_REFERENCE_P (gnu_type) = Is_By_Reference_Type (gnat_type);
303
304   SET_DUMMY_NODE (gnat_underlying, gnu_type);
305
306   return gnu_type;
307 }
308 \f
309 /* Return nonzero if we are currently in the global binding level.  */
310
311 int
312 global_bindings_p (void)
313 {
314   return ((force_global || !current_function_decl) ? -1 : 0);
315 }
316
317 /* Enter a new binding level. */
318
319 void
320 gnat_pushlevel (void)
321 {
322   struct gnat_binding_level *newlevel = NULL;
323
324   /* Reuse a struct for this binding level, if there is one.  */
325   if (free_binding_level)
326     {
327       newlevel = free_binding_level;
328       free_binding_level = free_binding_level->chain;
329     }
330   else
331     newlevel
332       = (struct gnat_binding_level *)
333         ggc_alloc (sizeof (struct gnat_binding_level));
334
335   /* Use a free BLOCK, if any; otherwise, allocate one.  */
336   if (free_block_chain)
337     {
338       newlevel->block = free_block_chain;
339       free_block_chain = BLOCK_CHAIN (free_block_chain);
340       BLOCK_CHAIN (newlevel->block) = NULL_TREE;
341     }
342   else
343     newlevel->block = make_node (BLOCK);
344
345   /* Point the BLOCK we just made to its parent.  */
346   if (current_binding_level)
347     BLOCK_SUPERCONTEXT (newlevel->block) = current_binding_level->block;
348
349   BLOCK_VARS (newlevel->block) = BLOCK_SUBBLOCKS (newlevel->block) = NULL_TREE;
350   TREE_USED (newlevel->block) = 1;
351
352   /* Add this level to the front of the chain (stack) of levels that are
353      active.  */
354   newlevel->chain = current_binding_level;
355   newlevel->jmpbuf_decl = NULL_TREE;
356   current_binding_level = newlevel;
357 }
358
359 /* Set SUPERCONTEXT of the BLOCK for the current binding level to FNDECL
360    and point FNDECL to this BLOCK.  */
361
362 void
363 set_current_block_context (tree fndecl)
364 {
365   BLOCK_SUPERCONTEXT (current_binding_level->block) = fndecl;
366   DECL_INITIAL (fndecl) = current_binding_level->block;
367 }
368
369 /* Set the jmpbuf_decl for the current binding level to DECL.  */
370
371 void
372 set_block_jmpbuf_decl (tree decl)
373 {
374   current_binding_level->jmpbuf_decl = decl;
375 }
376
377 /* Get the jmpbuf_decl, if any, for the current binding level.  */
378
379 tree
380 get_block_jmpbuf_decl (void)
381 {
382   return current_binding_level->jmpbuf_decl;
383 }
384
385 /* Exit a binding level. Set any BLOCK into the current code group.  */
386
387 void
388 gnat_poplevel (void)
389 {
390   struct gnat_binding_level *level = current_binding_level;
391   tree block = level->block;
392
393   BLOCK_VARS (block) = nreverse (BLOCK_VARS (block));
394   BLOCK_SUBBLOCKS (block) = nreverse (BLOCK_SUBBLOCKS (block));
395
396   /* If this is a function-level BLOCK don't do anything.  Otherwise, if there
397      are no variables free the block and merge its subblocks into those of its
398      parent block. Otherwise, add it to the list of its parent.  */
399   if (TREE_CODE (BLOCK_SUPERCONTEXT (block)) == FUNCTION_DECL)
400     ;
401   else if (BLOCK_VARS (block) == NULL_TREE)
402     {
403       BLOCK_SUBBLOCKS (level->chain->block)
404         = chainon (BLOCK_SUBBLOCKS (block),
405                    BLOCK_SUBBLOCKS (level->chain->block));
406       BLOCK_CHAIN (block) = free_block_chain;
407       free_block_chain = block;
408     }
409   else
410     {
411       BLOCK_CHAIN (block) = BLOCK_SUBBLOCKS (level->chain->block);
412       BLOCK_SUBBLOCKS (level->chain->block) = block;
413       TREE_USED (block) = 1;
414       set_block_for_group (block);
415     }
416
417   /* Free this binding structure.  */
418   current_binding_level = level->chain;
419   level->chain = free_binding_level;
420   free_binding_level = level;
421 }
422
423 \f
424 /* Records a ..._DECL node DECL as belonging to the current lexical scope
425    and uses GNAT_NODE for location information and propagating flags.  */
426
427 void
428 gnat_pushdecl (tree decl, Node_Id gnat_node)
429 {
430   /* If this decl is public external or at toplevel, there is no context.
431      But PARM_DECLs always go in the level of its function.  */
432   if (TREE_CODE (decl) != PARM_DECL
433       && ((DECL_EXTERNAL (decl) && TREE_PUBLIC (decl))
434           || global_bindings_p ()))
435     DECL_CONTEXT (decl) = 0;
436   else
437     {
438       DECL_CONTEXT (decl) = current_function_decl;
439
440       /* Functions imported in another function are not really nested.
441          For really nested functions mark them initially as needing
442          a static chain for uses of that flag before unnesting;
443          lower_nested_functions will then recompute it.  */
444       if (TREE_CODE (decl) == FUNCTION_DECL && !TREE_PUBLIC (decl))
445         DECL_STATIC_CHAIN (decl) = 1;
446     }
447
448   TREE_NO_WARNING (decl) = (gnat_node == Empty || Warnings_Off (gnat_node));
449
450   /* Set the location of DECL and emit a declaration for it.  */
451   if (Present (gnat_node))
452     Sloc_to_locus (Sloc (gnat_node), &DECL_SOURCE_LOCATION (decl));
453   add_decl_expr (decl, gnat_node);
454
455   /* Put the declaration on the list.  The list of declarations is in reverse
456      order.  The list will be reversed later.  Put global variables in the
457      globals list and builtin functions in a dedicated list to speed up
458      further lookups.  Don't put TYPE_DECLs for UNCONSTRAINED_ARRAY_TYPE into
459      the list, as they will cause trouble with the debugger and aren't needed
460      anyway.  */
461   if (TREE_CODE (decl) != TYPE_DECL
462       || TREE_CODE (TREE_TYPE (decl)) != UNCONSTRAINED_ARRAY_TYPE)
463     {
464       if (global_bindings_p ())
465         {
466           VEC_safe_push (tree, gc, global_decls, decl);
467
468           if (TREE_CODE (decl) == FUNCTION_DECL && DECL_BUILT_IN (decl))
469             VEC_safe_push (tree, gc, builtin_decls, decl);
470         }
471       else
472         {
473           TREE_CHAIN (decl) = BLOCK_VARS (current_binding_level->block);
474           BLOCK_VARS (current_binding_level->block) = decl;
475         }
476     }
477
478   /* For the declaration of a type, set its name if it either is not already
479      set or if the previous type name was not derived from a source name.
480      We'd rather have the type named with a real name and all the pointer
481      types to the same object have the same POINTER_TYPE node.  Code in the
482      equivalent function of c-decl.c makes a copy of the type node here, but
483      that may cause us trouble with incomplete types.  We make an exception
484      for fat pointer types because the compiler automatically builds them
485      for unconstrained array types and the debugger uses them to represent
486      both these and pointers to these.  */
487   if (TREE_CODE (decl) == TYPE_DECL && DECL_NAME (decl))
488     {
489       tree t = TREE_TYPE (decl);
490
491       if (!(TYPE_NAME (t) && TREE_CODE (TYPE_NAME (t)) == TYPE_DECL))
492         ;
493       else if (TYPE_IS_FAT_POINTER_P (t))
494         {
495           tree tt = build_variant_type_copy (t);
496           TYPE_NAME (tt) = decl;
497           TREE_USED (tt) = TREE_USED (t);
498           TREE_TYPE (decl) = tt;
499           if (DECL_ORIGINAL_TYPE (TYPE_NAME (t)))
500             DECL_ORIGINAL_TYPE (decl) = DECL_ORIGINAL_TYPE (TYPE_NAME (t));
501           else
502             DECL_ORIGINAL_TYPE (decl) = t;
503           t = NULL_TREE;
504           DECL_ARTIFICIAL (decl) = 0;
505         }
506       else if (DECL_ARTIFICIAL (TYPE_NAME (t)) && !DECL_ARTIFICIAL (decl))
507         ;
508       else
509         t = NULL_TREE;
510
511       /* Propagate the name to all the variants.  This is needed for
512          the type qualifiers machinery to work properly.  */
513       if (t)
514         for (t = TYPE_MAIN_VARIANT (t); t; t = TYPE_NEXT_VARIANT (t))
515           TYPE_NAME (t) = decl;
516     }
517 }
518 \f
519 /* Do little here.  Set up the standard declarations later after the
520    front end has been run.  */
521
522 void
523 gnat_init_decl_processing (void)
524 {
525   /* Make the binding_level structure for global names.  */
526   current_function_decl = 0;
527   current_binding_level = 0;
528   free_binding_level = 0;
529   gnat_pushlevel ();
530
531   build_common_tree_nodes (true, true);
532
533   /* In Ada, we use a signed type for SIZETYPE.  Use the signed type
534      corresponding to the width of Pmode.  In most cases when ptr_mode
535      and Pmode differ, C will use the width of ptr_mode for SIZETYPE.
536      But we get far better code using the width of Pmode.  */
537   size_type_node = gnat_type_for_mode (Pmode, 0);
538   set_sizetype (size_type_node);
539
540   /* In Ada, we use an unsigned 8-bit type for the default boolean type.  */
541   boolean_type_node = make_unsigned_type (8);
542   TREE_SET_CODE (boolean_type_node, BOOLEAN_TYPE);
543   SET_TYPE_RM_MAX_VALUE (boolean_type_node,
544                          build_int_cst (boolean_type_node, 1));
545   SET_TYPE_RM_SIZE (boolean_type_node, bitsize_int (1));
546
547   build_common_tree_nodes_2 (0);
548   boolean_true_node = TYPE_MAX_VALUE (boolean_type_node);
549
550   ptr_void_type_node = build_pointer_type (void_type_node);
551 }
552 \f
553 /* Record TYPE as a builtin type for Ada.  NAME is the name of the type.  */
554
555 void
556 record_builtin_type (const char *name, tree type)
557 {
558   tree type_decl = build_decl (input_location,
559                                TYPE_DECL, get_identifier (name), type);
560
561   gnat_pushdecl (type_decl, Empty);
562
563   if (debug_hooks->type_decl)
564     debug_hooks->type_decl (type_decl, false);
565 }
566 \f
567 /* Given a record type RECORD_TYPE and a chain of FIELD_DECL nodes FIELDLIST,
568    finish constructing the record or union type.  If REP_LEVEL is zero, this
569    record has no representation clause and so will be entirely laid out here.
570    If REP_LEVEL is one, this record has a representation clause and has been
571    laid out already; only set the sizes and alignment.  If REP_LEVEL is two,
572    this record is derived from a parent record and thus inherits its layout;
573    only make a pass on the fields to finalize them.  If DO_NOT_FINALIZE is
574    true, the record type is expected to be modified afterwards so it will
575    not be sent to the back-end for finalization.  */
576
577 void
578 finish_record_type (tree record_type, tree fieldlist, int rep_level,
579                     bool do_not_finalize)
580 {
581   enum tree_code code = TREE_CODE (record_type);
582   tree name = TYPE_NAME (record_type);
583   tree ada_size = bitsize_zero_node;
584   tree size = bitsize_zero_node;
585   bool had_size = TYPE_SIZE (record_type) != 0;
586   bool had_size_unit = TYPE_SIZE_UNIT (record_type) != 0;
587   bool had_align = TYPE_ALIGN (record_type) != 0;
588   tree field;
589
590   TYPE_FIELDS (record_type) = fieldlist;
591
592   /* Always attach the TYPE_STUB_DECL for a record type.  It is required to
593      generate debug info and have a parallel type.  */
594   if (name && TREE_CODE (name) == TYPE_DECL)
595     name = DECL_NAME (name);
596   TYPE_STUB_DECL (record_type) = create_type_stub_decl (name, record_type);
597
598   /* Globally initialize the record first.  If this is a rep'ed record,
599      that just means some initializations; otherwise, layout the record.  */
600   if (rep_level > 0)
601     {
602       TYPE_ALIGN (record_type) = MAX (BITS_PER_UNIT, TYPE_ALIGN (record_type));
603       SET_TYPE_MODE (record_type, BLKmode);
604
605       if (!had_size_unit)
606         TYPE_SIZE_UNIT (record_type) = size_zero_node;
607       if (!had_size)
608         TYPE_SIZE (record_type) = bitsize_zero_node;
609
610       /* For all-repped records with a size specified, lay the QUAL_UNION_TYPE
611          out just like a UNION_TYPE, since the size will be fixed.  */
612       else if (code == QUAL_UNION_TYPE)
613         code = UNION_TYPE;
614     }
615   else
616     {
617       /* Ensure there isn't a size already set.  There can be in an error
618          case where there is a rep clause but all fields have errors and
619          no longer have a position.  */
620       TYPE_SIZE (record_type) = 0;
621       layout_type (record_type);
622     }
623
624   /* At this point, the position and size of each field is known.  It was
625      either set before entry by a rep clause, or by laying out the type above.
626
627      We now run a pass over the fields (in reverse order for QUAL_UNION_TYPEs)
628      to compute the Ada size; the GCC size and alignment (for rep'ed records
629      that are not padding types); and the mode (for rep'ed records).  We also
630      clear the DECL_BIT_FIELD indication for the cases we know have not been
631      handled yet, and adjust DECL_NONADDRESSABLE_P accordingly.  */
632
633   if (code == QUAL_UNION_TYPE)
634     fieldlist = nreverse (fieldlist);
635
636   for (field = fieldlist; field; field = TREE_CHAIN (field))
637     {
638       tree type = TREE_TYPE (field);
639       tree pos = bit_position (field);
640       tree this_size = DECL_SIZE (field);
641       tree this_ada_size;
642
643       if ((TREE_CODE (type) == RECORD_TYPE
644            || TREE_CODE (type) == UNION_TYPE
645            || TREE_CODE (type) == QUAL_UNION_TYPE)
646           && !TYPE_FAT_POINTER_P (type)
647           && !TYPE_CONTAINS_TEMPLATE_P (type)
648           && TYPE_ADA_SIZE (type))
649         this_ada_size = TYPE_ADA_SIZE (type);
650       else
651         this_ada_size = this_size;
652
653       /* Clear DECL_BIT_FIELD for the cases layout_decl does not handle.  */
654       if (DECL_BIT_FIELD (field)
655           && operand_equal_p (this_size, TYPE_SIZE (type), 0))
656         {
657           unsigned int align = TYPE_ALIGN (type);
658
659           /* In the general case, type alignment is required.  */
660           if (value_factor_p (pos, align))
661             {
662               /* The enclosing record type must be sufficiently aligned.
663                  Otherwise, if no alignment was specified for it and it
664                  has been laid out already, bump its alignment to the
665                  desired one if this is compatible with its size.  */
666               if (TYPE_ALIGN (record_type) >= align)
667                 {
668                   DECL_ALIGN (field) = MAX (DECL_ALIGN (field), align);
669                   DECL_BIT_FIELD (field) = 0;
670                 }
671               else if (!had_align
672                        && rep_level == 0
673                        && value_factor_p (TYPE_SIZE (record_type), align))
674                 {
675                   TYPE_ALIGN (record_type) = align;
676                   DECL_ALIGN (field) = MAX (DECL_ALIGN (field), align);
677                   DECL_BIT_FIELD (field) = 0;
678                 }
679             }
680
681           /* In the non-strict alignment case, only byte alignment is.  */
682           if (!STRICT_ALIGNMENT
683               && DECL_BIT_FIELD (field)
684               && value_factor_p (pos, BITS_PER_UNIT))
685             DECL_BIT_FIELD (field) = 0;
686         }
687
688       /* If we still have DECL_BIT_FIELD set at this point, we know that the
689          field is technically not addressable.  Except that it can actually
690          be addressed if it is BLKmode and happens to be properly aligned.  */
691       if (DECL_BIT_FIELD (field)
692           && !(DECL_MODE (field) == BLKmode
693                && value_factor_p (pos, BITS_PER_UNIT)))
694         DECL_NONADDRESSABLE_P (field) = 1;
695
696       /* A type must be as aligned as its most aligned field that is not
697          a bit-field.  But this is already enforced by layout_type.  */
698       if (rep_level > 0 && !DECL_BIT_FIELD (field))
699         TYPE_ALIGN (record_type)
700           = MAX (TYPE_ALIGN (record_type), DECL_ALIGN (field));
701
702       switch (code)
703         {
704         case UNION_TYPE:
705           ada_size = size_binop (MAX_EXPR, ada_size, this_ada_size);
706           size = size_binop (MAX_EXPR, size, this_size);
707           break;
708
709         case QUAL_UNION_TYPE:
710           ada_size
711             = fold_build3 (COND_EXPR, bitsizetype, DECL_QUALIFIER (field),
712                            this_ada_size, ada_size);
713           size = fold_build3 (COND_EXPR, bitsizetype, DECL_QUALIFIER (field),
714                               this_size, size);
715           break;
716
717         case RECORD_TYPE:
718           /* Since we know here that all fields are sorted in order of
719              increasing bit position, the size of the record is one
720              higher than the ending bit of the last field processed
721              unless we have a rep clause, since in that case we might
722              have a field outside a QUAL_UNION_TYPE that has a higher ending
723              position.  So use a MAX in that case.  Also, if this field is a
724              QUAL_UNION_TYPE, we need to take into account the previous size in
725              the case of empty variants.  */
726           ada_size
727             = merge_sizes (ada_size, pos, this_ada_size,
728                            TREE_CODE (type) == QUAL_UNION_TYPE, rep_level > 0);
729           size
730             = merge_sizes (size, pos, this_size,
731                            TREE_CODE (type) == QUAL_UNION_TYPE, rep_level > 0);
732           break;
733
734         default:
735           gcc_unreachable ();
736         }
737     }
738
739   if (code == QUAL_UNION_TYPE)
740     nreverse (fieldlist);
741
742   if (rep_level < 2)
743     {
744       /* If this is a padding record, we never want to make the size smaller
745          than what was specified in it, if any.  */
746       if (TYPE_IS_PADDING_P (record_type) && TYPE_SIZE (record_type))
747         size = TYPE_SIZE (record_type);
748
749       /* Now set any of the values we've just computed that apply.  */
750       if (!TYPE_FAT_POINTER_P (record_type)
751           && !TYPE_CONTAINS_TEMPLATE_P (record_type))
752         SET_TYPE_ADA_SIZE (record_type, ada_size);
753
754       if (rep_level > 0)
755         {
756           tree size_unit = had_size_unit
757                            ? TYPE_SIZE_UNIT (record_type)
758                            : convert (sizetype,
759                                       size_binop (CEIL_DIV_EXPR, size,
760                                                   bitsize_unit_node));
761           unsigned int align = TYPE_ALIGN (record_type);
762
763           TYPE_SIZE (record_type) = variable_size (round_up (size, align));
764           TYPE_SIZE_UNIT (record_type)
765             = variable_size (round_up (size_unit, align / BITS_PER_UNIT));
766
767           compute_record_mode (record_type);
768         }
769     }
770
771   if (!do_not_finalize)
772     rest_of_record_type_compilation (record_type);
773 }
774
775 /* Wrap up compilation of RECORD_TYPE, i.e. most notably output all
776    the debug information associated with it.  It need not be invoked
777    directly in most cases since finish_record_type takes care of doing
778    so, unless explicitly requested not to through DO_NOT_FINALIZE.  */
779
780 void
781 rest_of_record_type_compilation (tree record_type)
782 {
783   tree fieldlist = TYPE_FIELDS (record_type);
784   tree field;
785   enum tree_code code = TREE_CODE (record_type);
786   bool var_size = false;
787
788   for (field = fieldlist; field; field = TREE_CHAIN (field))
789     {
790       /* We need to make an XVE/XVU record if any field has variable size,
791          whether or not the record does.  For example, if we have a union,
792          it may be that all fields, rounded up to the alignment, have the
793          same size, in which case we'll use that size.  But the debug
794          output routines (except Dwarf2) won't be able to output the fields,
795          so we need to make the special record.  */
796       if (TREE_CODE (DECL_SIZE (field)) != INTEGER_CST
797           /* If a field has a non-constant qualifier, the record will have
798              variable size too.  */
799           || (code == QUAL_UNION_TYPE
800               && TREE_CODE (DECL_QUALIFIER (field)) != INTEGER_CST))
801         {
802           var_size = true;
803           break;
804         }
805     }
806
807   /* If this record is of variable size, rename it so that the
808      debugger knows it is and make a new, parallel, record
809      that tells the debugger how the record is laid out.  See
810      exp_dbug.ads.  But don't do this for records that are padding
811      since they confuse GDB.  */
812   if (var_size && !TYPE_IS_PADDING_P (record_type))
813     {
814       tree new_record_type
815         = make_node (TREE_CODE (record_type) == QUAL_UNION_TYPE
816                      ? UNION_TYPE : TREE_CODE (record_type));
817       tree orig_name = TYPE_NAME (record_type), new_name;
818       tree last_pos = bitsize_zero_node;
819       tree old_field, prev_old_field = NULL_TREE;
820
821       if (TREE_CODE (orig_name) == TYPE_DECL)
822         orig_name = DECL_NAME (orig_name);
823
824       new_name
825         = concat_name (orig_name, TREE_CODE (record_type) == QUAL_UNION_TYPE
826                                   ? "XVU" : "XVE");
827       TYPE_NAME (new_record_type) = new_name;
828       TYPE_ALIGN (new_record_type) = BIGGEST_ALIGNMENT;
829       TYPE_STUB_DECL (new_record_type)
830         = create_type_stub_decl (new_name, new_record_type);
831       DECL_IGNORED_P (TYPE_STUB_DECL (new_record_type))
832         = DECL_IGNORED_P (TYPE_STUB_DECL (record_type));
833       TYPE_SIZE (new_record_type) = size_int (TYPE_ALIGN (record_type));
834       TYPE_SIZE_UNIT (new_record_type)
835         = size_int (TYPE_ALIGN (record_type) / BITS_PER_UNIT);
836
837       add_parallel_type (TYPE_STUB_DECL (record_type), new_record_type);
838
839       /* Now scan all the fields, replacing each field with a new
840          field corresponding to the new encoding.  */
841       for (old_field = TYPE_FIELDS (record_type); old_field;
842            old_field = TREE_CHAIN (old_field))
843         {
844           tree field_type = TREE_TYPE (old_field);
845           tree field_name = DECL_NAME (old_field);
846           tree new_field;
847           tree curpos = bit_position (old_field);
848           bool var = false;
849           unsigned int align = 0;
850           tree pos;
851
852           /* See how the position was modified from the last position.
853
854           There are two basic cases we support: a value was added
855           to the last position or the last position was rounded to
856           a boundary and they something was added.  Check for the
857           first case first.  If not, see if there is any evidence
858           of rounding.  If so, round the last position and try
859           again.
860
861           If this is a union, the position can be taken as zero. */
862
863           /* Some computations depend on the shape of the position expression,
864              so strip conversions to make sure it's exposed.  */
865           curpos = remove_conversions (curpos, true);
866
867           if (TREE_CODE (new_record_type) == UNION_TYPE)
868             pos = bitsize_zero_node, align = 0;
869           else
870             pos = compute_related_constant (curpos, last_pos);
871
872           if (!pos && TREE_CODE (curpos) == MULT_EXPR
873               && host_integerp (TREE_OPERAND (curpos, 1), 1))
874             {
875               tree offset = TREE_OPERAND (curpos, 0);
876               align = tree_low_cst (TREE_OPERAND (curpos, 1), 1);
877
878               /* An offset which is a bitwise AND with a negative power of 2
879                  means an alignment corresponding to this power of 2.  */
880               offset = remove_conversions (offset, true);
881               if (TREE_CODE (offset) == BIT_AND_EXPR
882                   && host_integerp (TREE_OPERAND (offset, 1), 0)
883                   && tree_int_cst_sgn (TREE_OPERAND (offset, 1)) < 0)
884                 {
885                   unsigned int pow
886                     = - tree_low_cst (TREE_OPERAND (offset, 1), 0);
887                   if (exact_log2 (pow) > 0)
888                     align *= pow;
889                 }
890
891               pos = compute_related_constant (curpos,
892                                               round_up (last_pos, align));
893             }
894           else if (!pos && TREE_CODE (curpos) == PLUS_EXPR
895                    && TREE_CODE (TREE_OPERAND (curpos, 1)) == INTEGER_CST
896                    && TREE_CODE (TREE_OPERAND (curpos, 0)) == MULT_EXPR
897                    && host_integerp (TREE_OPERAND
898                                      (TREE_OPERAND (curpos, 0), 1),
899                                      1))
900             {
901               align
902                 = tree_low_cst
903                 (TREE_OPERAND (TREE_OPERAND (curpos, 0), 1), 1);
904               pos = compute_related_constant (curpos,
905                                               round_up (last_pos, align));
906             }
907           else if (potential_alignment_gap (prev_old_field, old_field,
908                                             pos))
909             {
910               align = TYPE_ALIGN (field_type);
911               pos = compute_related_constant (curpos,
912                                               round_up (last_pos, align));
913             }
914
915           /* If we can't compute a position, set it to zero.
916
917           ??? We really should abort here, but it's too much work
918           to get this correct for all cases.  */
919
920           if (!pos)
921             pos = bitsize_zero_node;
922
923           /* See if this type is variable-sized and make a pointer type
924              and indicate the indirection if so.  Beware that the debug
925              back-end may adjust the position computed above according
926              to the alignment of the field type, i.e. the pointer type
927              in this case, if we don't preventively counter that.  */
928           if (TREE_CODE (DECL_SIZE (old_field)) != INTEGER_CST)
929             {
930               field_type = build_pointer_type (field_type);
931               if (align != 0 && TYPE_ALIGN (field_type) > align)
932                 {
933                   field_type = copy_node (field_type);
934                   TYPE_ALIGN (field_type) = align;
935                 }
936               var = true;
937             }
938
939           /* Make a new field name, if necessary.  */
940           if (var || align != 0)
941             {
942               char suffix[16];
943
944               if (align != 0)
945                 sprintf (suffix, "XV%c%u", var ? 'L' : 'A',
946                          align / BITS_PER_UNIT);
947               else
948                 strcpy (suffix, "XVL");
949
950               field_name = concat_name (field_name, suffix);
951             }
952
953           new_field = create_field_decl (field_name, field_type,
954                                          new_record_type, 0,
955                                          DECL_SIZE (old_field), pos, 0);
956           TREE_CHAIN (new_field) = TYPE_FIELDS (new_record_type);
957           TYPE_FIELDS (new_record_type) = new_field;
958
959           /* If old_field is a QUAL_UNION_TYPE, take its size as being
960              zero.  The only time it's not the last field of the record
961              is when there are other components at fixed positions after
962              it (meaning there was a rep clause for every field) and we
963              want to be able to encode them.  */
964           last_pos = size_binop (PLUS_EXPR, bit_position (old_field),
965                                  (TREE_CODE (TREE_TYPE (old_field))
966                                   == QUAL_UNION_TYPE)
967                                  ? bitsize_zero_node
968                                  : DECL_SIZE (old_field));
969           prev_old_field = old_field;
970         }
971
972       TYPE_FIELDS (new_record_type)
973         = nreverse (TYPE_FIELDS (new_record_type));
974
975       rest_of_type_decl_compilation (TYPE_STUB_DECL (new_record_type));
976     }
977
978   rest_of_type_decl_compilation (TYPE_STUB_DECL (record_type));
979 }
980
981 /* Append PARALLEL_TYPE on the chain of parallel types for decl.  */
982
983 void
984 add_parallel_type (tree decl, tree parallel_type)
985 {
986   tree d = decl;
987
988   while (DECL_PARALLEL_TYPE (d))
989     d = TYPE_STUB_DECL (DECL_PARALLEL_TYPE (d));
990
991   SET_DECL_PARALLEL_TYPE (d, parallel_type);
992 }
993
994 /* Return the parallel type associated to a type, if any.  */
995
996 tree
997 get_parallel_type (tree type)
998 {
999   if (TYPE_STUB_DECL (type))
1000     return DECL_PARALLEL_TYPE (TYPE_STUB_DECL (type));
1001   else
1002     return NULL_TREE;
1003 }
1004
1005 /* Utility function of above to merge LAST_SIZE, the previous size of a record
1006    with FIRST_BIT and SIZE that describe a field.  SPECIAL is true if this
1007    represents a QUAL_UNION_TYPE in which case we must look for COND_EXPRs and
1008    replace a value of zero with the old size.  If HAS_REP is true, we take the
1009    MAX of the end position of this field with LAST_SIZE.  In all other cases,
1010    we use FIRST_BIT plus SIZE.  Return an expression for the size.  */
1011
1012 static tree
1013 merge_sizes (tree last_size, tree first_bit, tree size, bool special,
1014              bool has_rep)
1015 {
1016   tree type = TREE_TYPE (last_size);
1017   tree new_size;
1018
1019   if (!special || TREE_CODE (size) != COND_EXPR)
1020     {
1021       new_size = size_binop (PLUS_EXPR, first_bit, size);
1022       if (has_rep)
1023         new_size = size_binop (MAX_EXPR, last_size, new_size);
1024     }
1025
1026   else
1027     new_size = fold_build3 (COND_EXPR, type, TREE_OPERAND (size, 0),
1028                             integer_zerop (TREE_OPERAND (size, 1))
1029                             ? last_size : merge_sizes (last_size, first_bit,
1030                                                        TREE_OPERAND (size, 1),
1031                                                        1, has_rep),
1032                             integer_zerop (TREE_OPERAND (size, 2))
1033                             ? last_size : merge_sizes (last_size, first_bit,
1034                                                        TREE_OPERAND (size, 2),
1035                                                        1, has_rep));
1036
1037   /* We don't need any NON_VALUE_EXPRs and they can confuse us (especially
1038      when fed through substitute_in_expr) into thinking that a constant
1039      size is not constant.  */
1040   while (TREE_CODE (new_size) == NON_LVALUE_EXPR)
1041     new_size = TREE_OPERAND (new_size, 0);
1042
1043   return new_size;
1044 }
1045
1046 /* Utility function of above to see if OP0 and OP1, both of SIZETYPE, are
1047    related by the addition of a constant.  Return that constant if so.  */
1048
1049 static tree
1050 compute_related_constant (tree op0, tree op1)
1051 {
1052   tree op0_var, op1_var;
1053   tree op0_con = split_plus (op0, &op0_var);
1054   tree op1_con = split_plus (op1, &op1_var);
1055   tree result = size_binop (MINUS_EXPR, op0_con, op1_con);
1056
1057   if (operand_equal_p (op0_var, op1_var, 0))
1058     return result;
1059   else if (operand_equal_p (op0, size_binop (PLUS_EXPR, op1_var, result), 0))
1060     return result;
1061   else
1062     return 0;
1063 }
1064
1065 /* Utility function of above to split a tree OP which may be a sum, into a
1066    constant part, which is returned, and a variable part, which is stored
1067    in *PVAR.  *PVAR may be bitsize_zero_node.  All operations must be of
1068    bitsizetype.  */
1069
1070 static tree
1071 split_plus (tree in, tree *pvar)
1072 {
1073   /* Strip NOPS in order to ease the tree traversal and maximize the
1074      potential for constant or plus/minus discovery. We need to be careful
1075      to always return and set *pvar to bitsizetype trees, but it's worth
1076      the effort.  */
1077   STRIP_NOPS (in);
1078
1079   *pvar = convert (bitsizetype, in);
1080
1081   if (TREE_CODE (in) == INTEGER_CST)
1082     {
1083       *pvar = bitsize_zero_node;
1084       return convert (bitsizetype, in);
1085     }
1086   else if (TREE_CODE (in) == PLUS_EXPR || TREE_CODE (in) == MINUS_EXPR)
1087     {
1088       tree lhs_var, rhs_var;
1089       tree lhs_con = split_plus (TREE_OPERAND (in, 0), &lhs_var);
1090       tree rhs_con = split_plus (TREE_OPERAND (in, 1), &rhs_var);
1091
1092       if (lhs_var == TREE_OPERAND (in, 0)
1093           && rhs_var == TREE_OPERAND (in, 1))
1094         return bitsize_zero_node;
1095
1096       *pvar = size_binop (TREE_CODE (in), lhs_var, rhs_var);
1097       return size_binop (TREE_CODE (in), lhs_con, rhs_con);
1098     }
1099   else
1100     return bitsize_zero_node;
1101 }
1102 \f
1103 /* Return a FUNCTION_TYPE node. RETURN_TYPE is the type returned by the
1104    subprogram. If it is void_type_node, then we are dealing with a procedure,
1105    otherwise we are dealing with a function. PARAM_DECL_LIST is a list of
1106    PARM_DECL nodes that are the subprogram arguments.  CICO_LIST is the
1107    copy-in/copy-out list to be stored into TYPE_CICO_LIST.
1108    RETURNS_UNCONSTRAINED is true if the function returns an unconstrained
1109    object.  RETURNS_BY_REF is true if the function returns by reference.
1110    RETURNS_BY_TARGET_PTR is true if the function is to be passed (as its
1111    first parameter) the address of the place to copy its result.  */
1112
1113 tree
1114 create_subprog_type (tree return_type, tree param_decl_list, tree cico_list,
1115                      bool returns_unconstrained, bool returns_by_ref,
1116                      bool returns_by_target_ptr)
1117 {
1118   /* A chain of TREE_LIST nodes whose TREE_VALUEs are the data type nodes of
1119      the subprogram formal parameters. This list is generated by traversing the
1120      input list of PARM_DECL nodes.  */
1121   tree param_type_list = NULL;
1122   tree param_decl;
1123   tree type;
1124
1125   for (param_decl = param_decl_list; param_decl;
1126        param_decl = TREE_CHAIN (param_decl))
1127     param_type_list = tree_cons (NULL_TREE, TREE_TYPE (param_decl),
1128                                  param_type_list);
1129
1130   /* The list of the function parameter types has to be terminated by the void
1131      type to signal to the back-end that we are not dealing with a variable
1132      parameter subprogram, but that the subprogram has a fixed number of
1133      parameters.  */
1134   param_type_list = tree_cons (NULL_TREE, void_type_node, param_type_list);
1135
1136   /* The list of argument types has been created in reverse
1137      so nreverse it.   */
1138   param_type_list = nreverse (param_type_list);
1139
1140   type = build_function_type (return_type, param_type_list);
1141
1142   /* TYPE may have been shared since GCC hashes types.  If it has a CICO_LIST
1143      or the new type should, make a copy of TYPE.  Likewise for
1144      RETURNS_UNCONSTRAINED and RETURNS_BY_REF.  */
1145   if (TYPE_CI_CO_LIST (type) || cico_list
1146       || TYPE_RETURNS_UNCONSTRAINED_P (type) != returns_unconstrained
1147       || TYPE_RETURNS_BY_REF_P (type) != returns_by_ref
1148       || TYPE_RETURNS_BY_TARGET_PTR_P (type) != returns_by_target_ptr)
1149     type = copy_type (type);
1150
1151   TYPE_CI_CO_LIST (type) = cico_list;
1152   TYPE_RETURNS_UNCONSTRAINED_P (type) = returns_unconstrained;
1153   TYPE_RETURNS_BY_REF_P (type) = returns_by_ref;
1154   TYPE_RETURNS_BY_TARGET_PTR_P (type) = returns_by_target_ptr;
1155   return type;
1156 }
1157 \f
1158 /* Return a copy of TYPE but safe to modify in any way.  */
1159
1160 tree
1161 copy_type (tree type)
1162 {
1163   tree new_type = copy_node (type);
1164
1165   /* copy_node clears this field instead of copying it, because it is
1166      aliased with TREE_CHAIN.  */
1167   TYPE_STUB_DECL (new_type) = TYPE_STUB_DECL (type);
1168
1169   TYPE_POINTER_TO (new_type) = 0;
1170   TYPE_REFERENCE_TO (new_type) = 0;
1171   TYPE_MAIN_VARIANT (new_type) = new_type;
1172   TYPE_NEXT_VARIANT (new_type) = 0;
1173
1174   return new_type;
1175 }
1176 \f
1177 /* Return a subtype of sizetype with range MIN to MAX and whose
1178    TYPE_INDEX_TYPE is INDEX.  GNAT_NODE is used for the position
1179    of the associated TYPE_DECL.  */
1180
1181 tree
1182 create_index_type (tree min, tree max, tree index, Node_Id gnat_node)
1183 {
1184   /* First build a type for the desired range.  */
1185   tree type = build_index_2_type (min, max);
1186
1187   /* If this type has the TYPE_INDEX_TYPE we want, return it.  */
1188   if (TYPE_INDEX_TYPE (type) == index)
1189     return type;
1190
1191   /* Otherwise, if TYPE_INDEX_TYPE is set, make a copy.  Note that we have
1192      no way of sharing these types, but that's only a small hole.  */
1193   if (TYPE_INDEX_TYPE (type))
1194     type = copy_type (type);
1195
1196   SET_TYPE_INDEX_TYPE (type, index);
1197   create_type_decl (NULL_TREE, type, NULL, true, false, gnat_node);
1198
1199   return type;
1200 }
1201
1202 /* Return a subtype of TYPE with range MIN to MAX.  If TYPE is NULL,
1203    sizetype is used.  */
1204
1205 tree
1206 create_range_type (tree type, tree min, tree max)
1207 {
1208   tree range_type;
1209
1210   if (type == NULL_TREE)
1211     type = sizetype;
1212
1213   /* First build a type with the base range.  */
1214   range_type
1215     = build_range_type (type, TYPE_MIN_VALUE (type), TYPE_MAX_VALUE (type));
1216
1217   min = convert (type, min);
1218   max = convert (type, max);
1219
1220   /* If this type has the TYPE_RM_{MIN,MAX}_VALUE we want, return it.  */
1221   if (TYPE_RM_MIN_VALUE (range_type)
1222       && TYPE_RM_MAX_VALUE (range_type)
1223       && operand_equal_p (TYPE_RM_MIN_VALUE (range_type), min, 0)
1224       && operand_equal_p (TYPE_RM_MAX_VALUE (range_type), max, 0))
1225     return range_type;
1226
1227   /* Otherwise, if TYPE_RM_{MIN,MAX}_VALUE is set, make a copy.  */
1228   if (TYPE_RM_MIN_VALUE (range_type) || TYPE_RM_MAX_VALUE (range_type))
1229     range_type = copy_type (range_type);
1230
1231   /* Then set the actual range.  */
1232   SET_TYPE_RM_MIN_VALUE (range_type, min);
1233   SET_TYPE_RM_MAX_VALUE (range_type, max);
1234
1235   return range_type;
1236 }
1237 \f
1238 /* Return a TYPE_DECL node suitable for the TYPE_STUB_DECL field of a type.
1239    TYPE_NAME gives the name of the type and TYPE is a ..._TYPE node giving
1240    its data type.  */
1241
1242 tree
1243 create_type_stub_decl (tree type_name, tree type)
1244 {
1245   /* Using a named TYPE_DECL ensures that a type name marker is emitted in
1246      STABS while setting DECL_ARTIFICIAL ensures that no DW_TAG_typedef is
1247      emitted in DWARF.  */
1248   tree type_decl = build_decl (input_location,
1249                                TYPE_DECL, type_name, type);
1250   DECL_ARTIFICIAL (type_decl) = 1;
1251   return type_decl;
1252 }
1253
1254 /* Return a TYPE_DECL node.  TYPE_NAME gives the name of the type and TYPE
1255    is a ..._TYPE node giving its data type.  ARTIFICIAL_P is true if this
1256    is a declaration that was generated by the compiler.  DEBUG_INFO_P is
1257    true if we need to write debug information about this type.  GNAT_NODE
1258    is used for the position of the decl.  */
1259
1260 tree
1261 create_type_decl (tree type_name, tree type, struct attrib *attr_list,
1262                   bool artificial_p, bool debug_info_p, Node_Id gnat_node)
1263 {
1264   enum tree_code code = TREE_CODE (type);
1265   bool named = TYPE_NAME (type) && TREE_CODE (TYPE_NAME (type)) == TYPE_DECL;
1266   tree type_decl;
1267
1268   /* Only the builtin TYPE_STUB_DECL should be used for dummy types.  */
1269   gcc_assert (!TYPE_IS_DUMMY_P (type));
1270
1271   /* If the type hasn't been named yet, we're naming it; preserve an existing
1272      TYPE_STUB_DECL that has been attached to it for some purpose.  */
1273   if (!named && TYPE_STUB_DECL (type))
1274     {
1275       type_decl = TYPE_STUB_DECL (type);
1276       DECL_NAME (type_decl) = type_name;
1277     }
1278   else
1279     type_decl = build_decl (input_location,
1280                             TYPE_DECL, type_name, type);
1281
1282   DECL_ARTIFICIAL (type_decl) = artificial_p;
1283   gnat_pushdecl (type_decl, gnat_node);
1284   process_attributes (type_decl, attr_list);
1285
1286   /* If we're naming the type, equate the TYPE_STUB_DECL to the name.
1287      This causes the name to be also viewed as a "tag" by the debug
1288      back-end, with the advantage that no DW_TAG_typedef is emitted
1289      for artificial "tagged" types in DWARF.  */
1290   if (!named)
1291     TYPE_STUB_DECL (type) = type_decl;
1292
1293   /* Pass the type declaration to the debug back-end unless this is an
1294      UNCONSTRAINED_ARRAY_TYPE that the back-end does not support, or a
1295      type for which debugging information was not requested, or else an
1296      ENUMERAL_TYPE or RECORD_TYPE (except for fat pointers) which are
1297      handled separately.  And do not pass dummy types either.  */
1298   if (code == UNCONSTRAINED_ARRAY_TYPE || !debug_info_p)
1299     DECL_IGNORED_P (type_decl) = 1;
1300   else if (code != ENUMERAL_TYPE
1301            && (code != RECORD_TYPE || TYPE_FAT_POINTER_P (type))
1302            && !((code == POINTER_TYPE || code == REFERENCE_TYPE)
1303                 && TYPE_IS_DUMMY_P (TREE_TYPE (type)))
1304            && !(code == RECORD_TYPE
1305                 && TYPE_IS_DUMMY_P
1306                    (TREE_TYPE (TREE_TYPE (TYPE_FIELDS (type))))))
1307     rest_of_type_decl_compilation (type_decl);
1308
1309   return type_decl;
1310 }
1311 \f
1312 /* Return a VAR_DECL or CONST_DECL node.
1313
1314    VAR_NAME gives the name of the variable.  ASM_NAME is its assembler name
1315    (if provided).  TYPE is its data type (a GCC ..._TYPE node).  VAR_INIT is
1316    the GCC tree for an optional initial expression; NULL_TREE if none.
1317
1318    CONST_FLAG is true if this variable is constant, in which case we might
1319    return a CONST_DECL node unless CONST_DECL_ALLOWED_P is false.
1320
1321    PUBLIC_FLAG is true if this is for a reference to a public entity or for a
1322    definition to be made visible outside of the current compilation unit, for
1323    instance variable definitions in a package specification.
1324
1325    EXTERN_FLAG is true when processing an external variable declaration (as
1326    opposed to a definition: no storage is to be allocated for the variable).
1327
1328    STATIC_FLAG is only relevant when not at top level.  In that case
1329    it indicates whether to always allocate storage to the variable.
1330
1331    GNAT_NODE is used for the position of the decl.  */
1332
1333 tree
1334 create_var_decl_1 (tree var_name, tree asm_name, tree type, tree var_init,
1335                    bool const_flag, bool public_flag, bool extern_flag,
1336                    bool static_flag, bool const_decl_allowed_p,
1337                    struct attrib *attr_list, Node_Id gnat_node)
1338 {
1339   bool init_const
1340     = (var_init != 0
1341        && gnat_types_compatible_p (type, TREE_TYPE (var_init))
1342        && (global_bindings_p () || static_flag
1343            ? initializer_constant_valid_p (var_init, TREE_TYPE (var_init)) != 0
1344            : TREE_CONSTANT (var_init)));
1345
1346   /* Whether we will make TREE_CONSTANT the DECL we produce here, in which
1347      case the initializer may be used in-lieu of the DECL node (as done in
1348      Identifier_to_gnu).  This is useful to prevent the need of elaboration
1349      code when an identifier for which such a decl is made is in turn used as
1350      an initializer.  We used to rely on CONST vs VAR_DECL for this purpose,
1351      but extra constraints apply to this choice (see below) and are not
1352      relevant to the distinction we wish to make. */
1353   bool constant_p = const_flag && init_const;
1354
1355   /* The actual DECL node.  CONST_DECL was initially intended for enumerals
1356      and may be used for scalars in general but not for aggregates.  */
1357   tree var_decl
1358     = build_decl (input_location,
1359                   (constant_p && const_decl_allowed_p
1360                    && !AGGREGATE_TYPE_P (type)) ? CONST_DECL : VAR_DECL,
1361                   var_name, type);
1362
1363   /* If this is external, throw away any initializations (they will be done
1364      elsewhere) unless this is a constant for which we would like to remain
1365      able to get the initializer.  If we are defining a global here, leave a
1366      constant initialization and save any variable elaborations for the
1367      elaboration routine.  If we are just annotating types, throw away the
1368      initialization if it isn't a constant.  */
1369   if ((extern_flag && !constant_p)
1370       || (type_annotate_only && var_init && !TREE_CONSTANT (var_init)))
1371     var_init = NULL_TREE;
1372
1373   /* At the global level, an initializer requiring code to be generated
1374      produces elaboration statements.  Check that such statements are allowed,
1375      that is, not violating a No_Elaboration_Code restriction.  */
1376   if (global_bindings_p () && var_init != 0 && ! init_const)
1377     Check_Elaboration_Code_Allowed (gnat_node);
1378
1379   /* Ada doesn't feature Fortran-like COMMON variables so we shouldn't
1380      try to fiddle with DECL_COMMON.  However, on platforms that don't
1381      support global BSS sections, uninitialized global variables would
1382      go in DATA instead, thus increasing the size of the executable.  */
1383   if (!flag_no_common
1384       && TREE_CODE (var_decl) == VAR_DECL
1385       && !have_global_bss_p ())
1386     DECL_COMMON (var_decl) = 1;
1387   DECL_INITIAL  (var_decl) = var_init;
1388   TREE_READONLY (var_decl) = const_flag;
1389   DECL_EXTERNAL (var_decl) = extern_flag;
1390   TREE_PUBLIC   (var_decl) = public_flag || extern_flag;
1391   TREE_CONSTANT (var_decl) = constant_p;
1392   TREE_THIS_VOLATILE (var_decl) = TREE_SIDE_EFFECTS (var_decl)
1393     = TYPE_VOLATILE (type);
1394
1395   /* If it's public and not external, always allocate storage for it.
1396      At the global binding level we need to allocate static storage for the
1397      variable if and only if it's not external. If we are not at the top level
1398      we allocate automatic storage unless requested not to.  */
1399   TREE_STATIC (var_decl)
1400     = !extern_flag && (public_flag || static_flag || global_bindings_p ());
1401
1402   /* For an external constant whose initializer is not absolute, do not emit
1403      debug info.  In DWARF this would mean a global relocation in a read-only
1404      section which runs afoul of the PE-COFF runtime relocation mechanism.  */
1405   if (extern_flag
1406       && constant_p
1407       && initializer_constant_valid_p (var_init, TREE_TYPE (var_init))
1408            != null_pointer_node)
1409     DECL_IGNORED_P (var_decl) = 1;
1410
1411   if (asm_name && VAR_OR_FUNCTION_DECL_P (var_decl))
1412     SET_DECL_ASSEMBLER_NAME (var_decl, asm_name);
1413
1414   process_attributes (var_decl, attr_list);
1415
1416   /* Add this decl to the current binding level.  */
1417   gnat_pushdecl (var_decl, gnat_node);
1418
1419   if (TREE_SIDE_EFFECTS (var_decl))
1420     TREE_ADDRESSABLE (var_decl) = 1;
1421
1422   if (TREE_CODE (var_decl) != CONST_DECL)
1423     {
1424       if (global_bindings_p ())
1425         rest_of_decl_compilation (var_decl, true, 0);
1426     }
1427   else
1428     expand_decl (var_decl);
1429
1430   return var_decl;
1431 }
1432 \f
1433 /* Return true if TYPE, an aggregate type, contains (or is) an array.  */
1434
1435 static bool
1436 aggregate_type_contains_array_p (tree type)
1437 {
1438   switch (TREE_CODE (type))
1439     {
1440     case RECORD_TYPE:
1441     case UNION_TYPE:
1442     case QUAL_UNION_TYPE:
1443       {
1444         tree field;
1445         for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
1446           if (AGGREGATE_TYPE_P (TREE_TYPE (field))
1447               && aggregate_type_contains_array_p (TREE_TYPE (field)))
1448             return true;
1449         return false;
1450       }
1451
1452     case ARRAY_TYPE:
1453       return true;
1454
1455     default:
1456       gcc_unreachable ();
1457     }
1458 }
1459
1460 /* Return a FIELD_DECL node.  FIELD_NAME the field name, FIELD_TYPE is its
1461    type, and RECORD_TYPE is the type of the parent.  PACKED is nonzero if
1462    this field is in a record type with a "pragma pack".  If SIZE is nonzero
1463    it is the specified size for this field.  If POS is nonzero, it is the bit
1464    position.  If ADDRESSABLE is nonzero, it means we are allowed to take
1465    the address of this field for aliasing purposes. If it is negative, we
1466    should not make a bitfield, which is used by make_aligning_type.   */
1467
1468 tree
1469 create_field_decl (tree field_name, tree field_type, tree record_type,
1470                    int packed, tree size, tree pos, int addressable)
1471 {
1472   tree field_decl = build_decl (input_location,
1473                                 FIELD_DECL, field_name, field_type);
1474
1475   DECL_CONTEXT (field_decl) = record_type;
1476   TREE_READONLY (field_decl) = TYPE_READONLY (field_type);
1477
1478   /* If FIELD_TYPE is BLKmode, we must ensure this is aligned to at least a
1479      byte boundary since GCC cannot handle less-aligned BLKmode bitfields.
1480      Likewise for an aggregate without specified position that contains an
1481      array, because in this case slices of variable length of this array
1482      must be handled by GCC and variable-sized objects need to be aligned
1483      to at least a byte boundary.  */
1484   if (packed && (TYPE_MODE (field_type) == BLKmode
1485                  || (!pos
1486                      && AGGREGATE_TYPE_P (field_type)
1487                      && aggregate_type_contains_array_p (field_type))))
1488     DECL_ALIGN (field_decl) = BITS_PER_UNIT;
1489
1490   /* If a size is specified, use it.  Otherwise, if the record type is packed
1491      compute a size to use, which may differ from the object's natural size.
1492      We always set a size in this case to trigger the checks for bitfield
1493      creation below, which is typically required when no position has been
1494      specified.  */
1495   if (size)
1496     size = convert (bitsizetype, size);
1497   else if (packed == 1)
1498     {
1499       size = rm_size (field_type);
1500
1501       /* For a constant size larger than MAX_FIXED_MODE_SIZE, round up to
1502          byte.  */
1503       if (TREE_CODE (size) == INTEGER_CST
1504           && compare_tree_int (size, MAX_FIXED_MODE_SIZE) > 0)
1505         size = round_up (size, BITS_PER_UNIT);
1506     }
1507
1508   /* If we may, according to ADDRESSABLE, make a bitfield if a size is
1509      specified for two reasons: first if the size differs from the natural
1510      size.  Second, if the alignment is insufficient.  There are a number of
1511      ways the latter can be true.
1512
1513      We never make a bitfield if the type of the field has a nonconstant size,
1514      because no such entity requiring bitfield operations should reach here.
1515
1516      We do *preventively* make a bitfield when there might be the need for it
1517      but we don't have all the necessary information to decide, as is the case
1518      of a field with no specified position in a packed record.
1519
1520      We also don't look at STRICT_ALIGNMENT here, and rely on later processing
1521      in layout_decl or finish_record_type to clear the bit_field indication if
1522      it is in fact not needed.  */
1523   if (addressable >= 0
1524       && size
1525       && TREE_CODE (size) == INTEGER_CST
1526       && TREE_CODE (TYPE_SIZE (field_type)) == INTEGER_CST
1527       && (!tree_int_cst_equal (size, TYPE_SIZE (field_type))
1528           || (pos && !value_factor_p (pos, TYPE_ALIGN (field_type)))
1529           || packed
1530           || (TYPE_ALIGN (record_type) != 0
1531               && TYPE_ALIGN (record_type) < TYPE_ALIGN (field_type))))
1532     {
1533       DECL_BIT_FIELD (field_decl) = 1;
1534       DECL_SIZE (field_decl) = size;
1535       if (!packed && !pos)
1536         {
1537           if (TYPE_ALIGN (record_type) != 0
1538               && TYPE_ALIGN (record_type) < TYPE_ALIGN (field_type))
1539             DECL_ALIGN (field_decl) = TYPE_ALIGN (record_type);
1540           else
1541             DECL_ALIGN (field_decl) = TYPE_ALIGN (field_type);
1542         }
1543     }
1544
1545   DECL_PACKED (field_decl) = pos ? DECL_BIT_FIELD (field_decl) : packed;
1546
1547   /* Bump the alignment if need be, either for bitfield/packing purposes or
1548      to satisfy the type requirements if no such consideration applies.  When
1549      we get the alignment from the type, indicate if this is from an explicit
1550      user request, which prevents stor-layout from lowering it later on.  */
1551   {
1552     unsigned int bit_align
1553       = (DECL_BIT_FIELD (field_decl) ? 1
1554          : packed && TYPE_MODE (field_type) != BLKmode ? BITS_PER_UNIT : 0);
1555
1556     if (bit_align > DECL_ALIGN (field_decl))
1557       DECL_ALIGN (field_decl) = bit_align;
1558     else if (!bit_align && TYPE_ALIGN (field_type) > DECL_ALIGN (field_decl))
1559       {
1560         DECL_ALIGN (field_decl) = TYPE_ALIGN (field_type);
1561         DECL_USER_ALIGN (field_decl) = TYPE_USER_ALIGN (field_type);
1562       }
1563   }
1564
1565   if (pos)
1566     {
1567       /* We need to pass in the alignment the DECL is known to have.
1568          This is the lowest-order bit set in POS, but no more than
1569          the alignment of the record, if one is specified.  Note
1570          that an alignment of 0 is taken as infinite.  */
1571       unsigned int known_align;
1572
1573       if (host_integerp (pos, 1))
1574         known_align = tree_low_cst (pos, 1) & - tree_low_cst (pos, 1);
1575       else
1576         known_align = BITS_PER_UNIT;
1577
1578       if (TYPE_ALIGN (record_type)
1579           && (known_align == 0 || known_align > TYPE_ALIGN (record_type)))
1580         known_align = TYPE_ALIGN (record_type);
1581
1582       layout_decl (field_decl, known_align);
1583       SET_DECL_OFFSET_ALIGN (field_decl,
1584                              host_integerp (pos, 1) ? BIGGEST_ALIGNMENT
1585                              : BITS_PER_UNIT);
1586       pos_from_bit (&DECL_FIELD_OFFSET (field_decl),
1587                     &DECL_FIELD_BIT_OFFSET (field_decl),
1588                     DECL_OFFSET_ALIGN (field_decl), pos);
1589     }
1590
1591   /* In addition to what our caller says, claim the field is addressable if we
1592      know that its type is not suitable.
1593
1594      The field may also be "technically" nonaddressable, meaning that even if
1595      we attempt to take the field's address we will actually get the address
1596      of a copy.  This is the case for true bitfields, but the DECL_BIT_FIELD
1597      value we have at this point is not accurate enough, so we don't account
1598      for this here and let finish_record_type decide.  */
1599   if (!addressable && !type_for_nonaliased_component_p (field_type))
1600     addressable = 1;
1601
1602   DECL_NONADDRESSABLE_P (field_decl) = !addressable;
1603
1604   return field_decl;
1605 }
1606 \f
1607 /* Return a PARM_DECL node.  PARAM_NAME is the name of the parameter and
1608    PARAM_TYPE is its type.  READONLY is true if the parameter is readonly
1609    (either an In parameter or an address of a pass-by-ref parameter).  */
1610
1611 tree
1612 create_param_decl (tree param_name, tree param_type, bool readonly)
1613 {
1614   tree param_decl = build_decl (input_location,
1615                                 PARM_DECL, param_name, param_type);
1616
1617   /* Honor TARGET_PROMOTE_PROTOTYPES like the C compiler, as not doing so
1618      can lead to various ABI violations.  */
1619   if (targetm.calls.promote_prototypes (NULL_TREE)
1620       && INTEGRAL_TYPE_P (param_type)
1621       && TYPE_PRECISION (param_type) < TYPE_PRECISION (integer_type_node))
1622     {
1623       /* We have to be careful about biased types here.  Make a subtype
1624          of integer_type_node with the proper biasing.  */
1625       if (TREE_CODE (param_type) == INTEGER_TYPE
1626           && TYPE_BIASED_REPRESENTATION_P (param_type))
1627         {
1628           tree subtype
1629             = make_unsigned_type (TYPE_PRECISION (integer_type_node));
1630           TREE_TYPE (subtype) = integer_type_node;
1631           TYPE_BIASED_REPRESENTATION_P (subtype) = 1;
1632           SET_TYPE_RM_MIN_VALUE (subtype, TYPE_MIN_VALUE (param_type));
1633           SET_TYPE_RM_MAX_VALUE (subtype, TYPE_MAX_VALUE (param_type));
1634           param_type = subtype;
1635         }
1636       else
1637         param_type = integer_type_node;
1638     }
1639
1640   DECL_ARG_TYPE (param_decl) = param_type;
1641   TREE_READONLY (param_decl) = readonly;
1642   return param_decl;
1643 }
1644 \f
1645 /* Given a DECL and ATTR_LIST, process the listed attributes.  */
1646
1647 void
1648 process_attributes (tree decl, struct attrib *attr_list)
1649 {
1650   for (; attr_list; attr_list = attr_list->next)
1651     switch (attr_list->type)
1652       {
1653       case ATTR_MACHINE_ATTRIBUTE:
1654         decl_attributes (&decl, tree_cons (attr_list->name, attr_list->args,
1655                                            NULL_TREE),
1656                          ATTR_FLAG_TYPE_IN_PLACE);
1657         break;
1658
1659       case ATTR_LINK_ALIAS:
1660         if (! DECL_EXTERNAL (decl))
1661           {
1662             TREE_STATIC (decl) = 1;
1663             assemble_alias (decl, attr_list->name);
1664           }
1665         break;
1666
1667       case ATTR_WEAK_EXTERNAL:
1668         if (SUPPORTS_WEAK)
1669           declare_weak (decl);
1670         else
1671           post_error ("?weak declarations not supported on this target",
1672                       attr_list->error_point);
1673         break;
1674
1675       case ATTR_LINK_SECTION:
1676         if (targetm.have_named_sections)
1677           {
1678             DECL_SECTION_NAME (decl)
1679               = build_string (IDENTIFIER_LENGTH (attr_list->name),
1680                               IDENTIFIER_POINTER (attr_list->name));
1681             DECL_COMMON (decl) = 0;
1682           }
1683         else
1684           post_error ("?section attributes are not supported for this target",
1685                       attr_list->error_point);
1686         break;
1687
1688       case ATTR_LINK_CONSTRUCTOR:
1689         DECL_STATIC_CONSTRUCTOR (decl) = 1;
1690         TREE_USED (decl) = 1;
1691         break;
1692
1693       case ATTR_LINK_DESTRUCTOR:
1694         DECL_STATIC_DESTRUCTOR (decl) = 1;
1695         TREE_USED (decl) = 1;
1696         break;
1697
1698       case ATTR_THREAD_LOCAL_STORAGE:
1699         DECL_TLS_MODEL (decl) = decl_default_tls_model (decl);
1700         DECL_COMMON (decl) = 0;
1701         break;
1702       }
1703 }
1704 \f
1705 /* Record DECL as a global renaming pointer.  */
1706
1707 void
1708 record_global_renaming_pointer (tree decl)
1709 {
1710   gcc_assert (DECL_RENAMED_OBJECT (decl));
1711   VEC_safe_push (tree, gc, global_renaming_pointers, decl);
1712 }
1713
1714 /* Invalidate the global renaming pointers.   */
1715
1716 void
1717 invalidate_global_renaming_pointers (void)
1718 {
1719   unsigned int i;
1720   tree iter;
1721
1722   for (i = 0; VEC_iterate(tree, global_renaming_pointers, i, iter); i++)
1723     SET_DECL_RENAMED_OBJECT (iter, NULL_TREE);
1724
1725   VEC_free (tree, gc, global_renaming_pointers);
1726 }
1727
1728 /* Return true if VALUE is a known to be a multiple of FACTOR, which must be
1729    a power of 2. */
1730
1731 bool
1732 value_factor_p (tree value, HOST_WIDE_INT factor)
1733 {
1734   if (host_integerp (value, 1))
1735     return tree_low_cst (value, 1) % factor == 0;
1736
1737   if (TREE_CODE (value) == MULT_EXPR)
1738     return (value_factor_p (TREE_OPERAND (value, 0), factor)
1739             || value_factor_p (TREE_OPERAND (value, 1), factor));
1740
1741   return false;
1742 }
1743
1744 /* Given 2 consecutive field decls PREV_FIELD and CURR_FIELD, return true
1745    unless we can prove these 2 fields are laid out in such a way that no gap
1746    exist between the end of PREV_FIELD and the beginning of CURR_FIELD.  OFFSET
1747    is the distance in bits between the end of PREV_FIELD and the starting
1748    position of CURR_FIELD. It is ignored if null. */
1749
1750 static bool
1751 potential_alignment_gap (tree prev_field, tree curr_field, tree offset)
1752 {
1753   /* If this is the first field of the record, there cannot be any gap */
1754   if (!prev_field)
1755     return false;
1756
1757   /* If the previous field is a union type, then return False: The only
1758      time when such a field is not the last field of the record is when
1759      there are other components at fixed positions after it (meaning there
1760      was a rep clause for every field), in which case we don't want the
1761      alignment constraint to override them. */
1762   if (TREE_CODE (TREE_TYPE (prev_field)) == QUAL_UNION_TYPE)
1763     return false;
1764
1765   /* If the distance between the end of prev_field and the beginning of
1766      curr_field is constant, then there is a gap if the value of this
1767      constant is not null. */
1768   if (offset && host_integerp (offset, 1))
1769     return !integer_zerop (offset);
1770
1771   /* If the size and position of the previous field are constant,
1772      then check the sum of this size and position. There will be a gap
1773      iff it is not multiple of the current field alignment. */
1774   if (host_integerp (DECL_SIZE (prev_field), 1)
1775       && host_integerp (bit_position (prev_field), 1))
1776     return ((tree_low_cst (bit_position (prev_field), 1)
1777              + tree_low_cst (DECL_SIZE (prev_field), 1))
1778             % DECL_ALIGN (curr_field) != 0);
1779
1780   /* If both the position and size of the previous field are multiples
1781      of the current field alignment, there cannot be any gap. */
1782   if (value_factor_p (bit_position (prev_field), DECL_ALIGN (curr_field))
1783       && value_factor_p (DECL_SIZE (prev_field), DECL_ALIGN (curr_field)))
1784     return false;
1785
1786   /* Fallback, return that there may be a potential gap */
1787   return true;
1788 }
1789
1790 /* Returns a LABEL_DECL node for LABEL_NAME.  */
1791
1792 tree
1793 create_label_decl (tree label_name)
1794 {
1795   tree label_decl = build_decl (input_location,
1796                                 LABEL_DECL, label_name, void_type_node);
1797
1798   DECL_CONTEXT (label_decl)     = current_function_decl;
1799   DECL_MODE (label_decl)        = VOIDmode;
1800   DECL_SOURCE_LOCATION (label_decl) = input_location;
1801
1802   return label_decl;
1803 }
1804 \f
1805 /* Returns a FUNCTION_DECL node.  SUBPROG_NAME is the name of the subprogram,
1806    ASM_NAME is its assembler name, SUBPROG_TYPE is its type (a FUNCTION_TYPE
1807    node), PARAM_DECL_LIST is the list of the subprogram arguments (a list of
1808    PARM_DECL nodes chained through the TREE_CHAIN field).
1809
1810    INLINE_FLAG, PUBLIC_FLAG, EXTERN_FLAG, and ATTR_LIST are used to set the
1811    appropriate fields in the FUNCTION_DECL.  GNAT_NODE gives the location.  */
1812
1813 tree
1814 create_subprog_decl (tree subprog_name, tree asm_name,
1815                      tree subprog_type, tree param_decl_list, bool inline_flag,
1816                      bool public_flag, bool extern_flag,
1817                      struct attrib *attr_list, Node_Id gnat_node)
1818 {
1819   tree return_type  = TREE_TYPE (subprog_type);
1820   tree subprog_decl = build_decl (input_location,
1821                                   FUNCTION_DECL, subprog_name, subprog_type);
1822
1823   /* If this is a non-inline function nested inside an inlined external
1824      function, we cannot honor both requests without cloning the nested
1825      function in the current unit since it is private to the other unit.
1826      We could inline the nested function as well but it's probably better
1827      to err on the side of too little inlining.  */
1828   if (!inline_flag
1829       && current_function_decl
1830       && DECL_DECLARED_INLINE_P (current_function_decl)
1831       && DECL_EXTERNAL (current_function_decl))
1832     DECL_DECLARED_INLINE_P (current_function_decl) = 0;
1833
1834   DECL_EXTERNAL (subprog_decl)  = extern_flag;
1835   TREE_PUBLIC (subprog_decl)    = public_flag;
1836   TREE_STATIC (subprog_decl)    = 1;
1837   TREE_READONLY (subprog_decl)  = TYPE_READONLY (subprog_type);
1838   TREE_THIS_VOLATILE (subprog_decl) = TYPE_VOLATILE (subprog_type);
1839   TREE_SIDE_EFFECTS (subprog_decl) = TYPE_VOLATILE (subprog_type);
1840   DECL_DECLARED_INLINE_P (subprog_decl) = inline_flag;
1841   DECL_ARGUMENTS (subprog_decl) = param_decl_list;
1842   DECL_RESULT (subprog_decl)    = build_decl (input_location,
1843                                               RESULT_DECL, 0, return_type);
1844   DECL_ARTIFICIAL (DECL_RESULT (subprog_decl)) = 1;
1845   DECL_IGNORED_P (DECL_RESULT (subprog_decl)) = 1;
1846
1847   /* TREE_ADDRESSABLE is set on the result type to request the use of the
1848      target by-reference return mechanism.  This is not supported all the
1849      way down to RTL expansion with GCC 4, which ICEs on temporary creation
1850      attempts with such a type and expects DECL_BY_REFERENCE to be set on
1851      the RESULT_DECL instead - see gnat_genericize for more details.  */
1852   if (TREE_ADDRESSABLE (TREE_TYPE (DECL_RESULT (subprog_decl))))
1853     {
1854       tree result_decl = DECL_RESULT (subprog_decl);
1855
1856       TREE_ADDRESSABLE (TREE_TYPE (result_decl)) = 0;
1857       DECL_BY_REFERENCE (result_decl) = 1;
1858     }
1859
1860   if (asm_name)
1861     {
1862       SET_DECL_ASSEMBLER_NAME (subprog_decl, asm_name);
1863
1864       /* The expand_main_function circuitry expects "main_identifier_node" to
1865          designate the DECL_NAME of the 'main' entry point, in turn expected
1866          to be declared as the "main" function literally by default.  Ada
1867          program entry points are typically declared with a different name
1868          within the binder generated file, exported as 'main' to satisfy the
1869          system expectations.  Redirect main_identifier_node in this case.  */
1870       if (asm_name == main_identifier_node)
1871         main_identifier_node = DECL_NAME (subprog_decl);
1872     }
1873
1874   process_attributes (subprog_decl, attr_list);
1875
1876   /* Add this decl to the current binding level.  */
1877   gnat_pushdecl (subprog_decl, gnat_node);
1878
1879   /* Output the assembler code and/or RTL for the declaration.  */
1880   rest_of_decl_compilation (subprog_decl, global_bindings_p (), 0);
1881
1882   return subprog_decl;
1883 }
1884 \f
1885 /* Set up the framework for generating code for SUBPROG_DECL, a subprogram
1886    body.  This routine needs to be invoked before processing the declarations
1887    appearing in the subprogram.  */
1888
1889 void
1890 begin_subprog_body (tree subprog_decl)
1891 {
1892   tree param_decl;
1893
1894   current_function_decl = subprog_decl;
1895   announce_function (subprog_decl);
1896
1897   /* Enter a new binding level and show that all the parameters belong to
1898      this function.  */
1899   gnat_pushlevel ();
1900   for (param_decl = DECL_ARGUMENTS (subprog_decl); param_decl;
1901        param_decl = TREE_CHAIN (param_decl))
1902     DECL_CONTEXT (param_decl) = subprog_decl;
1903
1904   make_decl_rtl (subprog_decl);
1905
1906   /* We handle pending sizes via the elaboration of types, so we don't need to
1907      save them.  This causes them to be marked as part of the outer function
1908      and then discarded.  */
1909   get_pending_sizes ();
1910 }
1911
1912
1913 /* Helper for the genericization callback.  Return a dereference of VAL
1914    if it is of a reference type.  */
1915
1916 static tree
1917 convert_from_reference (tree val)
1918 {
1919   tree value_type, ref;
1920
1921   if (TREE_CODE (TREE_TYPE (val)) != REFERENCE_TYPE)
1922     return val;
1923
1924   value_type =  TREE_TYPE (TREE_TYPE (val));
1925   ref = build1 (INDIRECT_REF, value_type, val);
1926
1927   /* See if what we reference is CONST or VOLATILE, which requires
1928      looking into array types to get to the component type.  */
1929
1930   while (TREE_CODE (value_type) == ARRAY_TYPE)
1931     value_type = TREE_TYPE (value_type);
1932
1933   TREE_READONLY (ref)
1934     = (TYPE_QUALS (value_type) & TYPE_QUAL_CONST);
1935   TREE_THIS_VOLATILE (ref)
1936     = (TYPE_QUALS (value_type) & TYPE_QUAL_VOLATILE);
1937
1938   TREE_SIDE_EFFECTS (ref)
1939     = (TREE_THIS_VOLATILE (ref) || TREE_SIDE_EFFECTS (val));
1940
1941   return ref;
1942 }
1943
1944 /* Helper for the genericization callback.  Returns true if T denotes
1945    a RESULT_DECL with DECL_BY_REFERENCE set.  */
1946
1947 static inline bool
1948 is_byref_result (tree t)
1949 {
1950   return (TREE_CODE (t) == RESULT_DECL && DECL_BY_REFERENCE (t));
1951 }
1952
1953
1954 /* Tree walking callback for gnat_genericize. Currently ...
1955
1956    o Adjust references to the function's DECL_RESULT if it is marked
1957      DECL_BY_REFERENCE and so has had its type turned into a reference
1958      type at the end of the function compilation.  */
1959
1960 static tree
1961 gnat_genericize_r (tree *stmt_p, int *walk_subtrees, void *data)
1962 {
1963   /* This implementation is modeled after what the C++ front-end is
1964      doing, basis of the downstream passes behavior.  */
1965
1966   tree stmt = *stmt_p;
1967   struct pointer_set_t *p_set = (struct pointer_set_t*) data;
1968
1969   /* If we have a direct mention of the result decl, dereference.  */
1970   if (is_byref_result (stmt))
1971     {
1972       *stmt_p = convert_from_reference (stmt);
1973       *walk_subtrees = 0;
1974       return NULL;
1975     }
1976
1977   /* Otherwise, no need to walk the same tree twice.  */
1978   if (pointer_set_contains (p_set, stmt))
1979     {
1980       *walk_subtrees = 0;
1981       return NULL_TREE;
1982     }
1983
1984   /* If we are taking the address of what now is a reference, just get the
1985      reference value.  */
1986   if (TREE_CODE (stmt) == ADDR_EXPR
1987       && is_byref_result (TREE_OPERAND (stmt, 0)))
1988     {
1989       *stmt_p = convert (TREE_TYPE (stmt), TREE_OPERAND (stmt, 0));
1990       *walk_subtrees = 0;
1991     }
1992
1993   /* Don't dereference an by-reference RESULT_DECL inside a RETURN_EXPR.  */
1994   else if (TREE_CODE (stmt) == RETURN_EXPR
1995            && TREE_OPERAND (stmt, 0)
1996            && is_byref_result (TREE_OPERAND (stmt, 0)))
1997     *walk_subtrees = 0;
1998
1999   /* Don't look inside trees that cannot embed references of interest.  */
2000   else if (IS_TYPE_OR_DECL_P (stmt))
2001     *walk_subtrees = 0;
2002
2003   pointer_set_insert (p_set, *stmt_p);
2004
2005   return NULL;
2006 }
2007
2008 /* Perform lowering of Ada trees to GENERIC. In particular:
2009
2010    o Turn a DECL_BY_REFERENCE RESULT_DECL into a real by-reference decl
2011      and adjust all the references to this decl accordingly.  */
2012
2013 static void
2014 gnat_genericize (tree fndecl)
2015 {
2016   /* Prior to GCC 4, an explicit By_Reference result mechanism for a function
2017      was handled by simply setting TREE_ADDRESSABLE on the result type.
2018      Everything required to actually pass by invisible ref using the target
2019      mechanism (e.g. extra parameter) was handled at RTL expansion time.
2020
2021      This doesn't work with GCC 4 any more for several reasons.  First, the
2022      gimplification process might need the creation of temporaries of this
2023      type, and the gimplifier ICEs on such attempts.  Second, the middle-end
2024      now relies on a different attribute for such cases (DECL_BY_REFERENCE on
2025      RESULT/PARM_DECLs), and expects the user invisible by-reference-ness to
2026      be explicitly accounted for by the front-end in the function body.
2027
2028      We achieve the complete transformation in two steps:
2029
2030      1/ create_subprog_decl performs early attribute tweaks: it clears
2031         TREE_ADDRESSABLE from the result type and sets DECL_BY_REFERENCE on
2032         the result decl.  The former ensures that the bit isn't set in the GCC
2033         tree saved for the function, so prevents ICEs on temporary creation.
2034         The latter we use here to trigger the rest of the processing.
2035
2036      2/ This function performs the type transformation on the result decl
2037         and adjusts all the references to this decl from the function body
2038         accordingly.
2039
2040      Clearing TREE_ADDRESSABLE from the type differs from the C++ front-end
2041      strategy, which escapes the gimplifier temporary creation issues by
2042      creating it's own temporaries using TARGET_EXPR nodes.  Our way relies
2043      on simple specific support code in aggregate_value_p to look at the
2044      target function result decl explicitly.  */
2045
2046   struct pointer_set_t *p_set;
2047   tree decl_result = DECL_RESULT (fndecl);
2048
2049   if (!DECL_BY_REFERENCE (decl_result))
2050     return;
2051
2052   /* Make the DECL_RESULT explicitly by-reference and adjust all the
2053      occurrences in the function body using the common tree-walking facility.
2054      We want to see every occurrence of the result decl to adjust the
2055      referencing tree, so need to use our own pointer set to control which
2056      trees should be visited again or not.  */
2057
2058   p_set = pointer_set_create ();
2059
2060   TREE_TYPE (decl_result) = build_reference_type (TREE_TYPE (decl_result));
2061   TREE_ADDRESSABLE (decl_result) = 0;
2062   relayout_decl (decl_result);
2063
2064   walk_tree (&DECL_SAVED_TREE (fndecl), gnat_genericize_r, p_set, NULL);
2065
2066   pointer_set_destroy (p_set);
2067 }
2068
2069 /* Finish the definition of the current subprogram BODY and finalize it.  */
2070
2071 void
2072 end_subprog_body (tree body)
2073 {
2074   tree fndecl = current_function_decl;
2075
2076   /* Mark the BLOCK for this level as being for this function and pop the
2077      level.  Since the vars in it are the parameters, clear them.  */
2078   BLOCK_VARS (current_binding_level->block) = 0;
2079   BLOCK_SUPERCONTEXT (current_binding_level->block) = fndecl;
2080   DECL_INITIAL (fndecl) = current_binding_level->block;
2081   gnat_poplevel ();
2082
2083   /* We handle pending sizes via the elaboration of types, so we don't
2084      need to save them.  */
2085   get_pending_sizes ();
2086
2087   /* Mark the RESULT_DECL as being in this subprogram. */
2088   DECL_CONTEXT (DECL_RESULT (fndecl)) = fndecl;
2089
2090   DECL_SAVED_TREE (fndecl) = body;
2091
2092   current_function_decl = DECL_CONTEXT (fndecl);
2093   set_cfun (NULL);
2094
2095   /* We cannot track the location of errors past this point.  */
2096   error_gnat_node = Empty;
2097
2098   /* If we're only annotating types, don't actually compile this function.  */
2099   if (type_annotate_only)
2100     return;
2101
2102   /* Perform the required pre-gimplification transformations on the tree.  */
2103   gnat_genericize (fndecl);
2104
2105   /* Dump functions before gimplification.  */
2106   dump_function (TDI_original, fndecl);
2107
2108   /* ??? This special handling of nested functions is probably obsolete.  */
2109   if (!DECL_CONTEXT (fndecl))
2110     cgraph_finalize_function (fndecl, false);
2111   else
2112     /* Register this function with cgraph just far enough to get it
2113        added to our parent's nested function list.  */
2114     (void) cgraph_node (fndecl);
2115 }
2116
2117 tree
2118 gnat_builtin_function (tree decl)
2119 {
2120   gnat_pushdecl (decl, Empty);
2121   return decl;
2122 }
2123
2124 /* Return an integer type with the number of bits of precision given by
2125    PRECISION.  UNSIGNEDP is nonzero if the type is unsigned; otherwise
2126    it is a signed type.  */
2127
2128 tree
2129 gnat_type_for_size (unsigned precision, int unsignedp)
2130 {
2131   tree t;
2132   char type_name[20];
2133
2134   if (precision <= 2 * MAX_BITS_PER_WORD
2135       && signed_and_unsigned_types[precision][unsignedp])
2136     return signed_and_unsigned_types[precision][unsignedp];
2137
2138  if (unsignedp)
2139     t = make_unsigned_type (precision);
2140   else
2141     t = make_signed_type (precision);
2142
2143   if (precision <= 2 * MAX_BITS_PER_WORD)
2144     signed_and_unsigned_types[precision][unsignedp] = t;
2145
2146   if (!TYPE_NAME (t))
2147     {
2148       sprintf (type_name, "%sSIGNED_%d", unsignedp ? "UN" : "", precision);
2149       TYPE_NAME (t) = get_identifier (type_name);
2150     }
2151
2152   return t;
2153 }
2154
2155 /* Likewise for floating-point types.  */
2156
2157 static tree
2158 float_type_for_precision (int precision, enum machine_mode mode)
2159 {
2160   tree t;
2161   char type_name[20];
2162
2163   if (float_types[(int) mode])
2164     return float_types[(int) mode];
2165
2166   float_types[(int) mode] = t = make_node (REAL_TYPE);
2167   TYPE_PRECISION (t) = precision;
2168   layout_type (t);
2169
2170   gcc_assert (TYPE_MODE (t) == mode);
2171   if (!TYPE_NAME (t))
2172     {
2173       sprintf (type_name, "FLOAT_%d", precision);
2174       TYPE_NAME (t) = get_identifier (type_name);
2175     }
2176
2177   return t;
2178 }
2179
2180 /* Return a data type that has machine mode MODE.  UNSIGNEDP selects
2181    an unsigned type; otherwise a signed type is returned.  */
2182
2183 tree
2184 gnat_type_for_mode (enum machine_mode mode, int unsignedp)
2185 {
2186   if (mode == BLKmode)
2187     return NULL_TREE;
2188   else if (mode == VOIDmode)
2189     return void_type_node;
2190   else if (COMPLEX_MODE_P (mode))
2191     return NULL_TREE;
2192   else if (SCALAR_FLOAT_MODE_P (mode))
2193     return float_type_for_precision (GET_MODE_PRECISION (mode), mode);
2194   else if (SCALAR_INT_MODE_P (mode))
2195     return gnat_type_for_size (GET_MODE_BITSIZE (mode), unsignedp);
2196   else
2197     return NULL_TREE;
2198 }
2199
2200 /* Return the unsigned version of a TYPE_NODE, a scalar type.  */
2201
2202 tree
2203 gnat_unsigned_type (tree type_node)
2204 {
2205   tree type = gnat_type_for_size (TYPE_PRECISION (type_node), 1);
2206
2207   if (TREE_CODE (type_node) == INTEGER_TYPE && TYPE_MODULAR_P (type_node))
2208     {
2209       type = copy_node (type);
2210       TREE_TYPE (type) = type_node;
2211     }
2212   else if (TREE_TYPE (type_node)
2213            && TREE_CODE (TREE_TYPE (type_node)) == INTEGER_TYPE
2214            && TYPE_MODULAR_P (TREE_TYPE (type_node)))
2215     {
2216       type = copy_node (type);
2217       TREE_TYPE (type) = TREE_TYPE (type_node);
2218     }
2219
2220   return type;
2221 }
2222
2223 /* Return the signed version of a TYPE_NODE, a scalar type.  */
2224
2225 tree
2226 gnat_signed_type (tree type_node)
2227 {
2228   tree type = gnat_type_for_size (TYPE_PRECISION (type_node), 0);
2229
2230   if (TREE_CODE (type_node) == INTEGER_TYPE && TYPE_MODULAR_P (type_node))
2231     {
2232       type = copy_node (type);
2233       TREE_TYPE (type) = type_node;
2234     }
2235   else if (TREE_TYPE (type_node)
2236            && TREE_CODE (TREE_TYPE (type_node)) == INTEGER_TYPE
2237            && TYPE_MODULAR_P (TREE_TYPE (type_node)))
2238     {
2239       type = copy_node (type);
2240       TREE_TYPE (type) = TREE_TYPE (type_node);
2241     }
2242
2243   return type;
2244 }
2245
2246 /* Return 1 if the types T1 and T2 are compatible, i.e. if they can be
2247    transparently converted to each other.  */
2248
2249 int
2250 gnat_types_compatible_p (tree t1, tree t2)
2251 {
2252   enum tree_code code;
2253
2254   /* This is the default criterion.  */
2255   if (TYPE_MAIN_VARIANT (t1) == TYPE_MAIN_VARIANT (t2))
2256     return 1;
2257
2258   /* We only check structural equivalence here.  */
2259   if ((code = TREE_CODE (t1)) != TREE_CODE (t2))
2260     return 0;
2261
2262   /* Vector types are also compatible if they have the same number of subparts
2263      and the same form of (scalar) element type.  */
2264   if (code == VECTOR_TYPE
2265       && TYPE_VECTOR_SUBPARTS (t1) == TYPE_VECTOR_SUBPARTS (t2)
2266       && TREE_CODE (TREE_TYPE (t1)) == TREE_CODE (TREE_TYPE (t2))
2267       && TYPE_PRECISION (TREE_TYPE (t1)) == TYPE_PRECISION (TREE_TYPE (t2)))
2268     return 1;
2269
2270   /* Array types are also compatible if they are constrained and have
2271      the same component type and the same domain.  */
2272   if (code == ARRAY_TYPE
2273       && TREE_TYPE (t1) == TREE_TYPE (t2)
2274       && (TYPE_DOMAIN (t1) == TYPE_DOMAIN (t2)
2275           || (TYPE_DOMAIN (t1)
2276               && TYPE_DOMAIN (t2)
2277               && tree_int_cst_equal (TYPE_MIN_VALUE (TYPE_DOMAIN (t1)),
2278                                      TYPE_MIN_VALUE (TYPE_DOMAIN (t2)))
2279               && tree_int_cst_equal (TYPE_MAX_VALUE (TYPE_DOMAIN (t1)),
2280                                      TYPE_MAX_VALUE (TYPE_DOMAIN (t2))))))
2281     return 1;
2282
2283   /* Padding record types are also compatible if they pad the same
2284      type and have the same constant size.  */
2285   if (code == RECORD_TYPE
2286       && TYPE_PADDING_P (t1) && TYPE_PADDING_P (t2)
2287       && TREE_TYPE (TYPE_FIELDS (t1)) == TREE_TYPE (TYPE_FIELDS (t2))
2288       && tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2)))
2289     return 1;
2290
2291   return 0;
2292 }
2293 \f
2294 /* EXP is an expression for the size of an object.  If this size contains
2295    discriminant references, replace them with the maximum (if MAX_P) or
2296    minimum (if !MAX_P) possible value of the discriminant.  */
2297
2298 tree
2299 max_size (tree exp, bool max_p)
2300 {
2301   enum tree_code code = TREE_CODE (exp);
2302   tree type = TREE_TYPE (exp);
2303
2304   switch (TREE_CODE_CLASS (code))
2305     {
2306     case tcc_declaration:
2307     case tcc_constant:
2308       return exp;
2309
2310     case tcc_vl_exp:
2311       if (code == CALL_EXPR)
2312         {
2313           tree t, *argarray;
2314           int n, i;
2315
2316           t = maybe_inline_call_in_expr (exp);
2317           if (t)
2318             return max_size (t, max_p);
2319
2320           n = call_expr_nargs (exp);
2321           gcc_assert (n > 0);
2322           argarray = (tree *) alloca (n * sizeof (tree));
2323           for (i = 0; i < n; i++)
2324             argarray[i] = max_size (CALL_EXPR_ARG (exp, i), max_p);
2325           return build_call_array (type, CALL_EXPR_FN (exp), n, argarray);
2326         }
2327       break;
2328
2329     case tcc_reference:
2330       /* If this contains a PLACEHOLDER_EXPR, it is the thing we want to
2331          modify.  Otherwise, we treat it like a variable.  */
2332       if (!CONTAINS_PLACEHOLDER_P (exp))
2333         return exp;
2334
2335       type = TREE_TYPE (TREE_OPERAND (exp, 1));
2336       return
2337         max_size (max_p ? TYPE_MAX_VALUE (type) : TYPE_MIN_VALUE (type), true);
2338
2339     case tcc_comparison:
2340       return max_p ? size_one_node : size_zero_node;
2341
2342     case tcc_unary:
2343     case tcc_binary:
2344     case tcc_expression:
2345       switch (TREE_CODE_LENGTH (code))
2346         {
2347         case 1:
2348           if (code == NON_LVALUE_EXPR)
2349             return max_size (TREE_OPERAND (exp, 0), max_p);
2350           else
2351             return
2352               fold_build1 (code, type,
2353                            max_size (TREE_OPERAND (exp, 0),
2354                                      code == NEGATE_EXPR ? !max_p : max_p));
2355
2356         case 2:
2357           if (code == COMPOUND_EXPR)
2358             return max_size (TREE_OPERAND (exp, 1), max_p);
2359
2360           /* Calculate "(A ? B : C) - D" as "A ? B - D : C - D" which
2361              may provide a tighter bound on max_size.  */
2362           if (code == MINUS_EXPR
2363               && TREE_CODE (TREE_OPERAND (exp, 0)) == COND_EXPR)
2364             {
2365               tree lhs = fold_build2 (MINUS_EXPR, type,
2366                                       TREE_OPERAND (TREE_OPERAND (exp, 0), 1),
2367                                       TREE_OPERAND (exp, 1));
2368               tree rhs = fold_build2 (MINUS_EXPR, type,
2369                                       TREE_OPERAND (TREE_OPERAND (exp, 0), 2),
2370                                       TREE_OPERAND (exp, 1));
2371               return fold_build2 (max_p ? MAX_EXPR : MIN_EXPR, type,
2372                                   max_size (lhs, max_p),
2373                                   max_size (rhs, max_p));
2374             }
2375
2376           {
2377             tree lhs = max_size (TREE_OPERAND (exp, 0), max_p);
2378             tree rhs = max_size (TREE_OPERAND (exp, 1),
2379                                  code == MINUS_EXPR ? !max_p : max_p);
2380
2381             /* Special-case wanting the maximum value of a MIN_EXPR.
2382                In that case, if one side overflows, return the other.
2383                sizetype is signed, but we know sizes are non-negative.
2384                Likewise, handle a MINUS_EXPR or PLUS_EXPR with the LHS
2385                overflowing or the maximum possible value and the RHS
2386                a variable.  */
2387             if (max_p
2388                 && code == MIN_EXPR
2389                 && TREE_CODE (rhs) == INTEGER_CST
2390                 && TREE_OVERFLOW (rhs))
2391               return lhs;
2392             else if (max_p
2393                      && code == MIN_EXPR
2394                      && TREE_CODE (lhs) == INTEGER_CST
2395                      && TREE_OVERFLOW (lhs))
2396               return rhs;
2397             else if ((code == MINUS_EXPR || code == PLUS_EXPR)
2398                      && ((TREE_CODE (lhs) == INTEGER_CST
2399                           && TREE_OVERFLOW (lhs))
2400                          || operand_equal_p (lhs, TYPE_MAX_VALUE (type), 0))
2401                      && !TREE_CONSTANT (rhs))
2402               return lhs;
2403             else
2404               return fold_build2 (code, type, lhs, rhs);
2405           }
2406
2407         case 3:
2408           if (code == SAVE_EXPR)
2409             return exp;
2410           else if (code == COND_EXPR)
2411             return fold_build2 (max_p ? MAX_EXPR : MIN_EXPR, type,
2412                                 max_size (TREE_OPERAND (exp, 1), max_p),
2413                                 max_size (TREE_OPERAND (exp, 2), max_p));
2414         }
2415
2416       /* Other tree classes cannot happen.  */
2417     default:
2418       break;
2419     }
2420
2421   gcc_unreachable ();
2422 }
2423 \f
2424 /* Build a template of type TEMPLATE_TYPE from the array bounds of ARRAY_TYPE.
2425    EXPR is an expression that we can use to locate any PLACEHOLDER_EXPRs.
2426    Return a constructor for the template.  */
2427
2428 tree
2429 build_template (tree template_type, tree array_type, tree expr)
2430 {
2431   tree template_elts = NULL_TREE;
2432   tree bound_list = NULL_TREE;
2433   tree field;
2434
2435   while (TREE_CODE (array_type) == RECORD_TYPE
2436          && (TYPE_PADDING_P (array_type)
2437              || TYPE_JUSTIFIED_MODULAR_P (array_type)))
2438     array_type = TREE_TYPE (TYPE_FIELDS (array_type));
2439
2440   if (TREE_CODE (array_type) == ARRAY_TYPE
2441       || (TREE_CODE (array_type) == INTEGER_TYPE
2442           && TYPE_HAS_ACTUAL_BOUNDS_P (array_type)))
2443     bound_list = TYPE_ACTUAL_BOUNDS (array_type);
2444
2445   /* First make the list for a CONSTRUCTOR for the template.  Go down the
2446      field list of the template instead of the type chain because this
2447      array might be an Ada array of arrays and we can't tell where the
2448      nested arrays stop being the underlying object.  */
2449
2450   for (field = TYPE_FIELDS (template_type); field;
2451        (bound_list
2452         ? (bound_list = TREE_CHAIN (bound_list))
2453         : (array_type = TREE_TYPE (array_type))),
2454        field = TREE_CHAIN (TREE_CHAIN (field)))
2455     {
2456       tree bounds, min, max;
2457
2458       /* If we have a bound list, get the bounds from there.  Likewise
2459          for an ARRAY_TYPE.  Otherwise, if expr is a PARM_DECL with
2460          DECL_BY_COMPONENT_PTR_P, use the bounds of the field in the template.
2461          This will give us a maximum range.  */
2462       if (bound_list)
2463         bounds = TREE_VALUE (bound_list);
2464       else if (TREE_CODE (array_type) == ARRAY_TYPE)
2465         bounds = TYPE_INDEX_TYPE (TYPE_DOMAIN (array_type));
2466       else if (expr && TREE_CODE (expr) == PARM_DECL
2467                && DECL_BY_COMPONENT_PTR_P (expr))
2468         bounds = TREE_TYPE (field);
2469       else
2470         gcc_unreachable ();
2471
2472       min = convert (TREE_TYPE (field), TYPE_MIN_VALUE (bounds));
2473       max = convert (TREE_TYPE (TREE_CHAIN (field)), TYPE_MAX_VALUE (bounds));
2474
2475       /* If either MIN or MAX involve a PLACEHOLDER_EXPR, we must
2476          substitute it from OBJECT.  */
2477       min = SUBSTITUTE_PLACEHOLDER_IN_EXPR (min, expr);
2478       max = SUBSTITUTE_PLACEHOLDER_IN_EXPR (max, expr);
2479
2480       template_elts = tree_cons (TREE_CHAIN (field), max,
2481                                  tree_cons (field, min, template_elts));
2482     }
2483
2484   return gnat_build_constructor (template_type, nreverse (template_elts));
2485 }
2486 \f
2487 /* Build a 32bit VMS descriptor from a Mechanism_Type, which must specify
2488    a descriptor type, and the GCC type of an object.  Each FIELD_DECL
2489    in the type contains in its DECL_INITIAL the expression to use when
2490    a constructor is made for the type.  GNAT_ENTITY is an entity used
2491    to print out an error message if the mechanism cannot be applied to
2492    an object of that type and also for the name.  */
2493
2494 tree
2495 build_vms_descriptor32 (tree type, Mechanism_Type mech, Entity_Id gnat_entity)
2496 {
2497   tree record_type = make_node (RECORD_TYPE);
2498   tree pointer32_type;
2499   tree field_list = 0;
2500   int klass;
2501   int dtype = 0;
2502   tree inner_type;
2503   int ndim;
2504   int i;
2505   tree *idx_arr;
2506   tree tem;
2507
2508   /* If TYPE is an unconstrained array, use the underlying array type.  */
2509   if (TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE)
2510     type = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (type))));
2511
2512   /* If this is an array, compute the number of dimensions in the array,
2513      get the index types, and point to the inner type.  */
2514   if (TREE_CODE (type) != ARRAY_TYPE)
2515     ndim = 0;
2516   else
2517     for (ndim = 1, inner_type = type;
2518          TREE_CODE (TREE_TYPE (inner_type)) == ARRAY_TYPE
2519          && TYPE_MULTI_ARRAY_P (TREE_TYPE (inner_type));
2520          ndim++, inner_type = TREE_TYPE (inner_type))
2521       ;
2522
2523   idx_arr = (tree *) alloca (ndim * sizeof (tree));
2524
2525   if (mech != By_Descriptor_NCA && mech != By_Short_Descriptor_NCA
2526       && TREE_CODE (type) == ARRAY_TYPE && TYPE_CONVENTION_FORTRAN_P (type))
2527     for (i = ndim - 1, inner_type = type;
2528          i >= 0;
2529          i--, inner_type = TREE_TYPE (inner_type))
2530       idx_arr[i] = TYPE_DOMAIN (inner_type);
2531   else
2532     for (i = 0, inner_type = type;
2533          i < ndim;
2534          i++, inner_type = TREE_TYPE (inner_type))
2535       idx_arr[i] = TYPE_DOMAIN (inner_type);
2536
2537   /* Now get the DTYPE value.  */
2538   switch (TREE_CODE (type))
2539     {
2540     case INTEGER_TYPE:
2541     case ENUMERAL_TYPE:
2542     case BOOLEAN_TYPE:
2543       if (TYPE_VAX_FLOATING_POINT_P (type))
2544         switch (tree_low_cst (TYPE_DIGITS_VALUE (type), 1))
2545           {
2546           case 6:
2547             dtype = 10;
2548             break;
2549           case 9:
2550             dtype = 11;
2551             break;
2552           case 15:
2553             dtype = 27;
2554             break;
2555           }
2556       else
2557         switch (GET_MODE_BITSIZE (TYPE_MODE (type)))
2558           {
2559           case 8:
2560             dtype = TYPE_UNSIGNED (type) ? 2 : 6;
2561             break;
2562           case 16:
2563             dtype = TYPE_UNSIGNED (type) ? 3 : 7;
2564             break;
2565           case 32:
2566             dtype = TYPE_UNSIGNED (type) ? 4 : 8;
2567             break;
2568           case 64:
2569             dtype = TYPE_UNSIGNED (type) ? 5 : 9;
2570             break;
2571           case 128:
2572             dtype = TYPE_UNSIGNED (type) ? 25 : 26;
2573             break;
2574           }
2575       break;
2576
2577     case REAL_TYPE:
2578       dtype = GET_MODE_BITSIZE (TYPE_MODE (type)) == 32 ? 52 : 53;
2579       break;
2580
2581     case COMPLEX_TYPE:
2582       if (TREE_CODE (TREE_TYPE (type)) == INTEGER_TYPE
2583           && TYPE_VAX_FLOATING_POINT_P (type))
2584         switch (tree_low_cst (TYPE_DIGITS_VALUE (type), 1))
2585           {
2586           case 6:
2587             dtype = 12;
2588             break;
2589           case 9:
2590             dtype = 13;
2591             break;
2592           case 15:
2593             dtype = 29;
2594           }
2595       else
2596         dtype = GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (type))) == 32 ? 54: 55;
2597       break;
2598
2599     case ARRAY_TYPE:
2600       dtype = 14;
2601       break;
2602
2603     default:
2604       break;
2605     }
2606
2607   /* Get the CLASS value.  */
2608   switch (mech)
2609     {
2610     case By_Descriptor_A:
2611     case By_Short_Descriptor_A:
2612       klass = 4;
2613       break;
2614     case By_Descriptor_NCA:
2615     case By_Short_Descriptor_NCA:
2616       klass = 10;
2617       break;
2618     case By_Descriptor_SB:
2619     case By_Short_Descriptor_SB:
2620       klass = 15;
2621       break;
2622     case By_Descriptor:
2623     case By_Short_Descriptor:
2624     case By_Descriptor_S:
2625     case By_Short_Descriptor_S:
2626     default:
2627       klass = 1;
2628       break;
2629     }
2630
2631   /* Make the type for a descriptor for VMS.  The first four fields
2632      are the same for all types.  */
2633
2634   field_list
2635     = chainon (field_list,
2636                make_descriptor_field
2637                ("LENGTH", gnat_type_for_size (16, 1), record_type,
2638                 size_in_bytes ((mech == By_Descriptor_A ||
2639                                 mech == By_Short_Descriptor_A)
2640                                ? inner_type : type)));
2641
2642   field_list = chainon (field_list,
2643                         make_descriptor_field ("DTYPE",
2644                                                gnat_type_for_size (8, 1),
2645                                                record_type, size_int (dtype)));
2646   field_list = chainon (field_list,
2647                         make_descriptor_field ("CLASS",
2648                                                gnat_type_for_size (8, 1),
2649                                                record_type, size_int (klass)));
2650
2651   /* Of course this will crash at run-time if the address space is not
2652      within the low 32 bits, but there is nothing else we can do.  */
2653   pointer32_type = build_pointer_type_for_mode (type, SImode, false);
2654
2655   field_list
2656     = chainon (field_list,
2657                make_descriptor_field
2658                ("POINTER", pointer32_type, record_type,
2659                 build_unary_op (ADDR_EXPR,
2660                                 pointer32_type,
2661                                 build0 (PLACEHOLDER_EXPR, type))));
2662
2663   switch (mech)
2664     {
2665     case By_Descriptor:
2666     case By_Short_Descriptor:
2667     case By_Descriptor_S:
2668     case By_Short_Descriptor_S:
2669       break;
2670
2671     case By_Descriptor_SB:
2672     case By_Short_Descriptor_SB:
2673       field_list
2674         = chainon (field_list,
2675                    make_descriptor_field
2676                    ("SB_L1", gnat_type_for_size (32, 1), record_type,
2677                     TREE_CODE (type) == ARRAY_TYPE
2678                     ? TYPE_MIN_VALUE (TYPE_DOMAIN (type)) : size_zero_node));
2679       field_list
2680         = chainon (field_list,
2681                    make_descriptor_field
2682                    ("SB_U1", gnat_type_for_size (32, 1), record_type,
2683                     TREE_CODE (type) == ARRAY_TYPE
2684                     ? TYPE_MAX_VALUE (TYPE_DOMAIN (type)) : size_zero_node));
2685       break;
2686
2687     case By_Descriptor_A:
2688     case By_Short_Descriptor_A:
2689     case By_Descriptor_NCA:
2690     case By_Short_Descriptor_NCA:
2691       field_list = chainon (field_list,
2692                             make_descriptor_field ("SCALE",
2693                                                    gnat_type_for_size (8, 1),
2694                                                    record_type,
2695                                                    size_zero_node));
2696
2697       field_list = chainon (field_list,
2698                             make_descriptor_field ("DIGITS",
2699                                                    gnat_type_for_size (8, 1),
2700                                                    record_type,
2701                                                    size_zero_node));
2702
2703       field_list
2704         = chainon (field_list,
2705                    make_descriptor_field
2706                    ("AFLAGS", gnat_type_for_size (8, 1), record_type,
2707                     size_int ((mech == By_Descriptor_NCA ||
2708                               mech == By_Short_Descriptor_NCA)
2709                               ? 0
2710                               /* Set FL_COLUMN, FL_COEFF, and FL_BOUNDS.  */
2711                               : (TREE_CODE (type) == ARRAY_TYPE
2712                                  && TYPE_CONVENTION_FORTRAN_P (type)
2713                                  ? 224 : 192))));
2714
2715       field_list = chainon (field_list,
2716                             make_descriptor_field ("DIMCT",
2717                                                    gnat_type_for_size (8, 1),
2718                                                    record_type,
2719                                                    size_int (ndim)));
2720
2721       field_list = chainon (field_list,
2722                             make_descriptor_field ("ARSIZE",
2723                                                    gnat_type_for_size (32, 1),
2724                                                    record_type,
2725                                                    size_in_bytes (type)));
2726
2727       /* Now build a pointer to the 0,0,0... element.  */
2728       tem = build0 (PLACEHOLDER_EXPR, type);
2729       for (i = 0, inner_type = type; i < ndim;
2730            i++, inner_type = TREE_TYPE (inner_type))
2731         tem = build4 (ARRAY_REF, TREE_TYPE (inner_type), tem,
2732                       convert (TYPE_DOMAIN (inner_type), size_zero_node),
2733                       NULL_TREE, NULL_TREE);
2734
2735       field_list
2736         = chainon (field_list,
2737                    make_descriptor_field
2738                    ("A0",
2739                     build_pointer_type_for_mode (inner_type, SImode, false),
2740                     record_type,
2741                     build1 (ADDR_EXPR,
2742                             build_pointer_type_for_mode (inner_type, SImode,
2743                                                          false),
2744                             tem)));
2745
2746       /* Next come the addressing coefficients.  */
2747       tem = size_one_node;
2748       for (i = 0; i < ndim; i++)
2749         {
2750           char fname[3];
2751           tree idx_length
2752             = size_binop (MULT_EXPR, tem,
2753                           size_binop (PLUS_EXPR,
2754                                       size_binop (MINUS_EXPR,
2755                                                   TYPE_MAX_VALUE (idx_arr[i]),
2756                                                   TYPE_MIN_VALUE (idx_arr[i])),
2757                                       size_int (1)));
2758
2759           fname[0] = ((mech == By_Descriptor_NCA ||
2760                        mech == By_Short_Descriptor_NCA) ? 'S' : 'M');
2761           fname[1] = '0' + i, fname[2] = 0;
2762           field_list
2763             = chainon (field_list,
2764                        make_descriptor_field (fname,
2765                                               gnat_type_for_size (32, 1),
2766                                               record_type, idx_length));
2767
2768           if (mech == By_Descriptor_NCA || mech == By_Short_Descriptor_NCA)
2769             tem = idx_length;
2770         }
2771
2772       /* Finally here are the bounds.  */
2773       for (i = 0; i < ndim; i++)
2774         {
2775           char fname[3];
2776
2777           fname[0] = 'L', fname[1] = '0' + i, fname[2] = 0;
2778           field_list
2779             = chainon (field_list,
2780                        make_descriptor_field
2781                        (fname, gnat_type_for_size (32, 1), record_type,
2782                         TYPE_MIN_VALUE (idx_arr[i])));
2783
2784           fname[0] = 'U';
2785           field_list
2786             = chainon (field_list,
2787                        make_descriptor_field
2788                        (fname, gnat_type_for_size (32, 1), record_type,
2789                         TYPE_MAX_VALUE (idx_arr[i])));
2790         }
2791       break;
2792
2793     default:
2794       post_error ("unsupported descriptor type for &", gnat_entity);
2795     }
2796
2797   TYPE_NAME (record_type) = create_concat_name (gnat_entity, "DESC");
2798   finish_record_type (record_type, field_list, 0, true);
2799   return record_type;
2800 }
2801
2802 /* Build a 64bit VMS descriptor from a Mechanism_Type, which must specify
2803    a descriptor type, and the GCC type of an object.  Each FIELD_DECL
2804    in the type contains in its DECL_INITIAL the expression to use when
2805    a constructor is made for the type.  GNAT_ENTITY is an entity used
2806    to print out an error message if the mechanism cannot be applied to
2807    an object of that type and also for the name.  */
2808
2809 tree
2810 build_vms_descriptor (tree type, Mechanism_Type mech, Entity_Id gnat_entity)
2811 {
2812   tree record64_type = make_node (RECORD_TYPE);
2813   tree pointer64_type;
2814   tree field_list64 = 0;
2815   int klass;
2816   int dtype = 0;
2817   tree inner_type;
2818   int ndim;
2819   int i;
2820   tree *idx_arr;
2821   tree tem;
2822
2823   /* If TYPE is an unconstrained array, use the underlying array type.  */
2824   if (TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE)
2825     type = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (type))));
2826
2827   /* If this is an array, compute the number of dimensions in the array,
2828      get the index types, and point to the inner type.  */
2829   if (TREE_CODE (type) != ARRAY_TYPE)
2830     ndim = 0;
2831   else
2832     for (ndim = 1, inner_type = type;
2833          TREE_CODE (TREE_TYPE (inner_type)) == ARRAY_TYPE
2834          && TYPE_MULTI_ARRAY_P (TREE_TYPE (inner_type));
2835          ndim++, inner_type = TREE_TYPE (inner_type))
2836       ;
2837
2838   idx_arr = (tree *) alloca (ndim * sizeof (tree));
2839
2840   if (mech != By_Descriptor_NCA
2841       && TREE_CODE (type) == ARRAY_TYPE && TYPE_CONVENTION_FORTRAN_P (type))
2842     for (i = ndim - 1, inner_type = type;
2843          i >= 0;
2844          i--, inner_type = TREE_TYPE (inner_type))
2845       idx_arr[i] = TYPE_DOMAIN (inner_type);
2846   else
2847     for (i = 0, inner_type = type;
2848          i < ndim;
2849          i++, inner_type = TREE_TYPE (inner_type))
2850       idx_arr[i] = TYPE_DOMAIN (inner_type);
2851
2852   /* Now get the DTYPE value.  */
2853   switch (TREE_CODE (type))
2854     {
2855     case INTEGER_TYPE:
2856     case ENUMERAL_TYPE:
2857     case BOOLEAN_TYPE:
2858       if (TYPE_VAX_FLOATING_POINT_P (type))
2859         switch (tree_low_cst (TYPE_DIGITS_VALUE (type), 1))
2860           {
2861           case 6:
2862             dtype = 10;
2863             break;
2864           case 9:
2865             dtype = 11;
2866             break;
2867           case 15:
2868             dtype = 27;
2869             break;
2870           }
2871       else
2872         switch (GET_MODE_BITSIZE (TYPE_MODE (type)))
2873           {
2874           case 8:
2875             dtype = TYPE_UNSIGNED (type) ? 2 : 6;
2876             break;
2877           case 16:
2878             dtype = TYPE_UNSIGNED (type) ? 3 : 7;
2879             break;
2880           case 32:
2881             dtype = TYPE_UNSIGNED (type) ? 4 : 8;
2882             break;
2883           case 64:
2884             dtype = TYPE_UNSIGNED (type) ? 5 : 9;
2885             break;
2886           case 128:
2887             dtype = TYPE_UNSIGNED (type) ? 25 : 26;
2888             break;
2889           }
2890       break;
2891
2892     case REAL_TYPE:
2893       dtype = GET_MODE_BITSIZE (TYPE_MODE (type)) == 32 ? 52 : 53;
2894       break;
2895
2896     case COMPLEX_TYPE:
2897       if (TREE_CODE (TREE_TYPE (type)) == INTEGER_TYPE
2898           && TYPE_VAX_FLOATING_POINT_P (type))
2899         switch (tree_low_cst (TYPE_DIGITS_VALUE (type), 1))
2900           {
2901           case 6:
2902             dtype = 12;
2903             break;
2904           case 9:
2905             dtype = 13;
2906             break;
2907           case 15:
2908             dtype = 29;
2909           }
2910       else
2911         dtype = GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (type))) == 32 ? 54: 55;
2912       break;
2913
2914     case ARRAY_TYPE:
2915       dtype = 14;
2916       break;
2917
2918     default:
2919       break;
2920     }
2921
2922   /* Get the CLASS value.  */
2923   switch (mech)
2924     {
2925     case By_Descriptor_A:
2926       klass = 4;
2927       break;
2928     case By_Descriptor_NCA:
2929       klass = 10;
2930       break;
2931     case By_Descriptor_SB:
2932       klass = 15;
2933       break;
2934     case By_Descriptor:
2935     case By_Descriptor_S:
2936     default:
2937       klass = 1;
2938       break;
2939     }
2940
2941   /* Make the type for a 64bit descriptor for VMS.  The first six fields
2942      are the same for all types.  */
2943
2944   field_list64 = chainon (field_list64,
2945                         make_descriptor_field ("MBO",
2946                                                gnat_type_for_size (16, 1),
2947                                                record64_type, size_int (1)));
2948
2949   field_list64 = chainon (field_list64,
2950                         make_descriptor_field ("DTYPE",
2951                                                gnat_type_for_size (8, 1),
2952                                                record64_type, size_int (dtype)));
2953   field_list64 = chainon (field_list64,
2954                         make_descriptor_field ("CLASS",
2955                                                gnat_type_for_size (8, 1),
2956                                                record64_type, size_int (klass)));
2957
2958   field_list64 = chainon (field_list64,
2959                         make_descriptor_field ("MBMO",
2960                                                gnat_type_for_size (32, 1),
2961                                                record64_type, ssize_int (-1)));
2962
2963   field_list64
2964     = chainon (field_list64,
2965                make_descriptor_field
2966                ("LENGTH", gnat_type_for_size (64, 1), record64_type,
2967                 size_in_bytes (mech == By_Descriptor_A ? inner_type : type)));
2968
2969   pointer64_type = build_pointer_type_for_mode (type, DImode, false);
2970
2971   field_list64
2972     = chainon (field_list64,
2973                make_descriptor_field
2974                ("POINTER", pointer64_type, record64_type,
2975                 build_unary_op (ADDR_EXPR,
2976                                 pointer64_type,
2977                                 build0 (PLACEHOLDER_EXPR, type))));
2978
2979   switch (mech)
2980     {
2981     case By_Descriptor:
2982     case By_Descriptor_S:
2983       break;
2984
2985     case By_Descriptor_SB:
2986       field_list64
2987         = chainon (field_list64,
2988                    make_descriptor_field
2989                    ("SB_L1", gnat_type_for_size (64, 1), record64_type,
2990                     TREE_CODE (type) == ARRAY_TYPE
2991                     ? TYPE_MIN_VALUE (TYPE_DOMAIN (type)) : size_zero_node));
2992       field_list64
2993         = chainon (field_list64,
2994                    make_descriptor_field
2995                    ("SB_U1", gnat_type_for_size (64, 1), record64_type,
2996                     TREE_CODE (type) == ARRAY_TYPE
2997                     ? TYPE_MAX_VALUE (TYPE_DOMAIN (type)) : size_zero_node));
2998       break;
2999
3000     case By_Descriptor_A:
3001     case By_Descriptor_NCA:
3002       field_list64 = chainon (field_list64,
3003                             make_descriptor_field ("SCALE",
3004                                                    gnat_type_for_size (8, 1),
3005                                                    record64_type,
3006                                                    size_zero_node));
3007
3008       field_list64 = chainon (field_list64,
3009                             make_descriptor_field ("DIGITS",
3010                                                    gnat_type_for_size (8, 1),
3011                                                    record64_type,
3012                                                    size_zero_node));
3013
3014       field_list64
3015         = chainon (field_list64,
3016                    make_descriptor_field
3017                    ("AFLAGS", gnat_type_for_size (8, 1), record64_type,
3018                     size_int (mech == By_Descriptor_NCA
3019                               ? 0
3020                               /* Set FL_COLUMN, FL_COEFF, and FL_BOUNDS.  */
3021                               : (TREE_CODE (type) == ARRAY_TYPE
3022                                  && TYPE_CONVENTION_FORTRAN_P (type)
3023                                  ? 224 : 192))));
3024
3025       field_list64 = chainon (field_list64,
3026                             make_descriptor_field ("DIMCT",
3027                                                    gnat_type_for_size (8, 1),
3028                                                    record64_type,
3029                                                    size_int (ndim)));
3030
3031       field_list64 = chainon (field_list64,
3032                             make_descriptor_field ("MBZ",
3033                                                    gnat_type_for_size (32, 1),
3034                                                    record64_type,
3035                                                    size_int (0)));
3036       field_list64 = chainon (field_list64,
3037                             make_descriptor_field ("ARSIZE",
3038                                                    gnat_type_for_size (64, 1),
3039                                                    record64_type,
3040                                                    size_in_bytes (type)));
3041
3042       /* Now build a pointer to the 0,0,0... element.  */
3043       tem = build0 (PLACEHOLDER_EXPR, type);
3044       for (i = 0, inner_type = type; i < ndim;
3045            i++, inner_type = TREE_TYPE (inner_type))
3046         tem = build4 (ARRAY_REF, TREE_TYPE (inner_type), tem,
3047                       convert (TYPE_DOMAIN (inner_type), size_zero_node),
3048                       NULL_TREE, NULL_TREE);
3049
3050       field_list64
3051         = chainon (field_list64,
3052                    make_descriptor_field
3053                    ("A0",
3054                     build_pointer_type_for_mode (inner_type, DImode, false),
3055                     record64_type,
3056                     build1 (ADDR_EXPR,
3057                             build_pointer_type_for_mode (inner_type, DImode,
3058                                                          false),
3059                             tem)));
3060
3061       /* Next come the addressing coefficients.  */
3062       tem = size_one_node;
3063       for (i = 0; i < ndim; i++)
3064         {
3065           char fname[3];
3066           tree idx_length
3067             = size_binop (MULT_EXPR, tem,
3068                           size_binop (PLUS_EXPR,
3069                                       size_binop (MINUS_EXPR,
3070                                                   TYPE_MAX_VALUE (idx_arr[i]),
3071                                                   TYPE_MIN_VALUE (idx_arr[i])),
3072                                       size_int (1)));
3073
3074           fname[0] = (mech == By_Descriptor_NCA ? 'S' : 'M');
3075           fname[1] = '0' + i, fname[2] = 0;
3076           field_list64
3077             = chainon (field_list64,
3078                        make_descriptor_field (fname,
3079                                               gnat_type_for_size (64, 1),
3080                                               record64_type, idx_length));
3081
3082           if (mech == By_Descriptor_NCA)
3083             tem = idx_length;
3084         }
3085
3086       /* Finally here are the bounds.  */
3087       for (i = 0; i < ndim; i++)
3088         {
3089           char fname[3];
3090
3091           fname[0] = 'L', fname[1] = '0' + i, fname[2] = 0;
3092           field_list64
3093             = chainon (field_list64,
3094                        make_descriptor_field
3095                        (fname, gnat_type_for_size (64, 1), record64_type,
3096                         TYPE_MIN_VALUE (idx_arr[i])));
3097
3098           fname[0] = 'U';
3099           field_list64
3100             = chainon (field_list64,
3101                        make_descriptor_field
3102                        (fname, gnat_type_for_size (64, 1), record64_type,
3103                         TYPE_MAX_VALUE (idx_arr[i])));
3104         }
3105       break;
3106
3107     default:
3108       post_error ("unsupported descriptor type for &", gnat_entity);
3109     }
3110
3111   TYPE_NAME (record64_type) = create_concat_name (gnat_entity, "DESC64");
3112   finish_record_type (record64_type, field_list64, 0, true);
3113   return record64_type;
3114 }
3115
3116 /* Utility routine for above code to make a field.  */
3117
3118 static tree
3119 make_descriptor_field (const char *name, tree type,
3120                        tree rec_type, tree initial)
3121 {
3122   tree field
3123     = create_field_decl (get_identifier (name), type, rec_type, 0, 0, 0, 0);
3124
3125   DECL_INITIAL (field) = initial;
3126   return field;
3127 }
3128
3129 /* Convert GNU_EXPR, a pointer to a 64bit VMS descriptor, to GNU_TYPE, a
3130    regular pointer or fat pointer type.  GNAT_SUBPROG is the subprogram to
3131    which the VMS descriptor is passed.  */
3132
3133 static tree
3134 convert_vms_descriptor64 (tree gnu_type, tree gnu_expr, Entity_Id gnat_subprog)
3135 {
3136   tree desc_type = TREE_TYPE (TREE_TYPE (gnu_expr));
3137   tree desc = build1 (INDIRECT_REF, desc_type, gnu_expr);
3138   /* The CLASS field is the 3rd field in the descriptor.  */
3139   tree klass = TREE_CHAIN (TREE_CHAIN (TYPE_FIELDS (desc_type)));
3140   /* The POINTER field is the 6th field in the descriptor.  */
3141   tree pointer64 = TREE_CHAIN (TREE_CHAIN (TREE_CHAIN (klass)));
3142
3143   /* Retrieve the value of the POINTER field.  */
3144   tree gnu_expr64
3145     = build3 (COMPONENT_REF, TREE_TYPE (pointer64), desc, pointer64, NULL_TREE);
3146
3147   if (POINTER_TYPE_P (gnu_type))
3148     return convert (gnu_type, gnu_expr64);
3149
3150   else if (TYPE_IS_FAT_POINTER_P (gnu_type))
3151     {
3152       tree p_array_type = TREE_TYPE (TYPE_FIELDS (gnu_type));
3153       tree p_bounds_type = TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (gnu_type)));
3154       tree template_type = TREE_TYPE (p_bounds_type);
3155       tree min_field = TYPE_FIELDS (template_type);
3156       tree max_field = TREE_CHAIN (TYPE_FIELDS (template_type));
3157       tree template_tree, template_addr, aflags, dimct, t, u;
3158       /* See the head comment of build_vms_descriptor.  */
3159       int iklass = TREE_INT_CST_LOW (DECL_INITIAL (klass));
3160       tree lfield, ufield;
3161
3162       /* Convert POINTER to the type of the P_ARRAY field.  */
3163       gnu_expr64 = convert (p_array_type, gnu_expr64);
3164
3165       switch (iklass)
3166         {
3167         case 1:  /* Class S  */
3168         case 15: /* Class SB */
3169           /* Build {1, LENGTH} template; LENGTH64 is the 5th field.  */
3170           t = TREE_CHAIN (TREE_CHAIN (klass));
3171           t = build3 (COMPONENT_REF, TREE_TYPE (t), desc, t, NULL_TREE);
3172           t = tree_cons (min_field,
3173                          convert (TREE_TYPE (min_field), integer_one_node),
3174                          tree_cons (max_field,
3175                                     convert (TREE_TYPE (max_field), t),
3176                                     NULL_TREE));
3177           template_tree = gnat_build_constructor (template_type, t);
3178           template_addr = build_unary_op (ADDR_EXPR, NULL_TREE, template_tree);
3179
3180           /* For class S, we are done.  */
3181           if (iklass == 1)
3182             break;
3183
3184           /* Test that we really have a SB descriptor, like DEC Ada.  */
3185           t = build3 (COMPONENT_REF, TREE_TYPE (klass), desc, klass, NULL);
3186           u = convert (TREE_TYPE (klass), DECL_INITIAL (klass));
3187           u = build_binary_op (EQ_EXPR, integer_type_node, t, u);
3188           /* If so, there is already a template in the descriptor and
3189              it is located right after the POINTER field.  The fields are
3190              64bits so they must be repacked. */
3191           t = TREE_CHAIN (pointer64);
3192           lfield = build3 (COMPONENT_REF, TREE_TYPE (t), desc, t, NULL_TREE);
3193           lfield = convert (TREE_TYPE (TYPE_FIELDS (template_type)), lfield);
3194
3195           t = TREE_CHAIN (t);
3196           ufield = build3 (COMPONENT_REF, TREE_TYPE (t), desc, t, NULL_TREE);
3197           ufield = convert
3198            (TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (template_type))), ufield);
3199
3200           /* Build the template in the form of a constructor. */
3201           t = tree_cons (TYPE_FIELDS (template_type), lfield,
3202                          tree_cons (TREE_CHAIN (TYPE_FIELDS (template_type)),
3203                                     ufield, NULL_TREE));
3204           template_tree = gnat_build_constructor (template_type, t);
3205
3206           /* Otherwise use the {1, LENGTH} template we build above.  */
3207           template_addr = build3 (COND_EXPR, p_bounds_type, u,
3208                                   build_unary_op (ADDR_EXPR, p_bounds_type,
3209                                                  template_tree),
3210                                   template_addr);
3211           break;
3212
3213         case 4:  /* Class A */
3214           /* The AFLAGS field is the 3rd field after the pointer in the
3215              descriptor.  */
3216           t = TREE_CHAIN (TREE_CHAIN (TREE_CHAIN (pointer64)));
3217           aflags = build3 (COMPONENT_REF, TREE_TYPE (t), desc, t, NULL_TREE);
3218           /* The DIMCT field is the next field in the descriptor after
3219              aflags.  */
3220           t = TREE_CHAIN (t);
3221           dimct = build3 (COMPONENT_REF, TREE_TYPE (t), desc, t, NULL_TREE);
3222           /* Raise CONSTRAINT_ERROR if either more than 1 dimension
3223              or FL_COEFF or FL_BOUNDS not set.  */
3224           u = build_int_cst (TREE_TYPE (aflags), 192);
3225           u = build_binary_op (TRUTH_OR_EXPR, integer_type_node,
3226                                build_binary_op (NE_EXPR, integer_type_node,
3227                                                 dimct,
3228                                                 convert (TREE_TYPE (dimct),
3229                                                          size_one_node)),
3230                                build_binary_op (NE_EXPR, integer_type_node,
3231                                                 build2 (BIT_AND_EXPR,
3232                                                         TREE_TYPE (aflags),
3233                                                         aflags, u),
3234                                                 u));
3235           /* There is already a template in the descriptor and it is located
3236              in block 3.  The fields are 64bits so they must be repacked. */
3237           t = TREE_CHAIN (TREE_CHAIN (TREE_CHAIN (TREE_CHAIN (TREE_CHAIN
3238               (t)))));
3239           lfield = build3 (COMPONENT_REF, TREE_TYPE (t), desc, t, NULL_TREE);
3240           lfield = convert (TREE_TYPE (TYPE_FIELDS (template_type)), lfield);
3241
3242           t = TREE_CHAIN (t);
3243           ufield = build3 (COMPONENT_REF, TREE_TYPE (t), desc, t, NULL_TREE);
3244           ufield = convert
3245            (TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (template_type))), ufield);
3246
3247           /* Build the template in the form of a constructor. */
3248           t = tree_cons (TYPE_FIELDS (template_type), lfield,
3249                          tree_cons (TREE_CHAIN (TYPE_FIELDS (template_type)),
3250                                     ufield, NULL_TREE));
3251           template_tree = gnat_build_constructor (template_type, t);
3252           template_tree = build3 (COND_EXPR, template_type, u,
3253                             build_call_raise (CE_Length_Check_Failed, Empty,
3254                                               N_Raise_Constraint_Error),
3255                             template_tree);
3256           template_addr
3257             = build_unary_op (ADDR_EXPR, p_bounds_type, template_tree);
3258           break;
3259
3260         case 10: /* Class NCA */
3261         default:
3262           post_error ("unsupported descriptor type for &", gnat_subprog);
3263           template_addr = integer_zero_node;
3264           break;
3265         }
3266
3267       /* Build the fat pointer in the form of a constructor.  */
3268       t = tree_cons (TYPE_FIELDS (gnu_type), gnu_expr64,
3269                      tree_cons (TREE_CHAIN (TYPE_FIELDS (gnu_type)),
3270                                 template_addr, NULL_TREE));
3271       return gnat_build_constructor (gnu_type, t);
3272     }
3273
3274   else
3275     gcc_unreachable ();
3276 }
3277
3278 /* Convert GNU_EXPR, a pointer to a 32bit VMS descriptor, to GNU_TYPE, a
3279    regular pointer or fat pointer type.  GNAT_SUBPROG is the subprogram to
3280    which the VMS descriptor is passed.  */
3281
3282 static tree
3283 convert_vms_descriptor32 (tree gnu_type, tree gnu_expr, Entity_Id gnat_subprog)
3284 {
3285   tree desc_type = TREE_TYPE (TREE_TYPE (gnu_expr));
3286   tree desc = build1 (INDIRECT_REF, desc_type, gnu_expr);
3287   /* The CLASS field is the 3rd field in the descriptor.  */
3288   tree klass = TREE_CHAIN (TREE_CHAIN (TYPE_FIELDS (desc_type)));
3289   /* The POINTER field is the 4th field in the descriptor.  */
3290   tree pointer = TREE_CHAIN (klass);
3291
3292   /* Retrieve the value of the POINTER field.  */
3293   tree gnu_expr32
3294     = build3 (COMPONENT_REF, TREE_TYPE (pointer), desc, pointer, NULL_TREE);
3295
3296   if (POINTER_TYPE_P (gnu_type))
3297     return convert (gnu_type, gnu_expr32);
3298
3299   else if (TYPE_IS_FAT_POINTER_P (gnu_type))
3300     {
3301       tree p_array_type = TREE_TYPE (TYPE_FIELDS (gnu_type));
3302       tree p_bounds_type = TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (gnu_type)));
3303       tree template_type = TREE_TYPE (p_bounds_type);
3304       tree min_field = TYPE_FIELDS (template_type);
3305       tree max_field = TREE_CHAIN (TYPE_FIELDS (template_type));
3306       tree template_tree, template_addr, aflags, dimct, t, u;
3307       /* See the head comment of build_vms_descriptor.  */
3308       int iklass = TREE_INT_CST_LOW (DECL_INITIAL (klass));
3309
3310       /* Convert POINTER to the type of the P_ARRAY field.  */
3311       gnu_expr32 = convert (p_array_type, gnu_expr32);
3312
3313       switch (iklass)
3314         {
3315         case 1:  /* Class S  */
3316         case 15: /* Class SB */
3317           /* Build {1, LENGTH} template; LENGTH is the 1st field.  */
3318           t = TYPE_FIELDS (desc_type);
3319           t = build3 (COMPONENT_REF, TREE_TYPE (t), desc, t, NULL_TREE);
3320           t = tree_cons (min_field,
3321                          convert (TREE_TYPE (min_field), integer_one_node),
3322                          tree_cons (max_field,
3323                                     convert (TREE_TYPE (max_field), t),
3324                                     NULL_TREE));
3325           template_tree = gnat_build_constructor (template_type, t);
3326           template_addr = build_unary_op (ADDR_EXPR, NULL_TREE, template_tree);
3327
3328           /* For class S, we are done.  */
3329           if (iklass == 1)
3330             break;
3331
3332           /* Test that we really have a SB descriptor, like DEC Ada.  */
3333           t = build3 (COMPONENT_REF, TREE_TYPE (klass), desc, klass, NULL);
3334           u = convert (TREE_TYPE (klass), DECL_INITIAL (klass));
3335           u = build_binary_op (EQ_EXPR, integer_type_node, t, u);
3336           /* If so, there is already a template in the descriptor and
3337              it is located right after the POINTER field.  */
3338           t = TREE_CHAIN (pointer);
3339           template_tree
3340             = build3 (COMPONENT_REF, TREE_TYPE (t), desc, t, NULL_TREE);
3341           /* Otherwise use the {1, LENGTH} template we build above.  */
3342           template_addr = build3 (COND_EXPR, p_bounds_type, u,
3343                                   build_unary_op (ADDR_EXPR, p_bounds_type,
3344                                                  template_tree),
3345                                   template_addr);
3346           break;
3347
3348         case 4:  /* Class A */
3349           /* The AFLAGS field is the 7th field in the descriptor.  */
3350           t = TREE_CHAIN (TREE_CHAIN (TREE_CHAIN (pointer)));
3351           aflags = build3 (COMPONENT_REF, TREE_TYPE (t), desc, t, NULL_TREE);
3352           /* The DIMCT field is the 8th field in the descriptor.  */
3353           t = TREE_CHAIN (t);
3354           dimct = build3 (COMPONENT_REF, TREE_TYPE (t), desc, t, NULL_TREE);
3355           /* Raise CONSTRAINT_ERROR if either more than 1 dimension
3356              or FL_COEFF or FL_BOUNDS not set.  */
3357           u = build_int_cst (TREE_TYPE (aflags), 192);
3358           u = build_binary_op (TRUTH_OR_EXPR, integer_type_node,
3359                                build_binary_op (NE_EXPR, integer_type_node,
3360                                                 dimct,
3361                                                 convert (TREE_TYPE (dimct),
3362                                                          size_one_node)),
3363                                build_binary_op (NE_EXPR, integer_type_node,
3364                                                 build2 (BIT_AND_EXPR,
3365                                                         TREE_TYPE (aflags),
3366                                                         aflags, u),
3367                                                 u));
3368           /* There is already a template in the descriptor and it is
3369              located at the start of block 3 (12th field).  */
3370           t = TREE_CHAIN (TREE_CHAIN (TREE_CHAIN (TREE_CHAIN (t))));
3371           template_tree
3372             = build3 (COMPONENT_REF, TREE_TYPE (t), desc, t, NULL_TREE);
3373           template_tree = build3 (COND_EXPR, TREE_TYPE (t), u,
3374                             build_call_raise (CE_Length_Check_Failed, Empty,
3375                                               N_Raise_Constraint_Error),
3376                             template_tree);
3377           template_addr
3378             = build_unary_op (ADDR_EXPR, p_bounds_type, template_tree);
3379           break;
3380
3381         case 10: /* Class NCA */
3382         default:
3383           post_error ("unsupported descriptor type for &", gnat_subprog);
3384           template_addr = integer_zero_node;
3385           break;
3386         }
3387
3388       /* Build the fat pointer in the form of a constructor.  */
3389       t = tree_cons (TYPE_FIELDS (gnu_type), gnu_expr32,
3390                      tree_cons (TREE_CHAIN (TYPE_FIELDS (gnu_type)),
3391                                 template_addr, NULL_TREE));
3392
3393       return gnat_build_constructor (gnu_type, t);
3394     }
3395
3396   else
3397     gcc_unreachable ();
3398 }
3399
3400 /* Convert GNU_EXPR, a pointer to a VMS descriptor, to GNU_TYPE, a regular
3401    pointer or fat pointer type.  GNU_EXPR_ALT_TYPE is the alternate (32-bit)
3402    pointer type of GNU_EXPR.  GNAT_SUBPROG is the subprogram to which the
3403    VMS descriptor is passed.  */
3404
3405 static tree
3406 convert_vms_descriptor (tree gnu_type, tree gnu_expr, tree gnu_expr_alt_type,
3407                         Entity_Id gnat_subprog)
3408 {
3409   tree desc_type = TREE_TYPE (TREE_TYPE (gnu_expr));
3410   tree desc = build1 (INDIRECT_REF, desc_type, gnu_expr);
3411   tree mbo = TYPE_FIELDS (desc_type);
3412   const char *mbostr = IDENTIFIER_POINTER (DECL_NAME (mbo));
3413   tree mbmo = TREE_CHAIN (TREE_CHAIN (TREE_CHAIN (mbo)));
3414   tree is64bit, gnu_expr32, gnu_expr64;
3415
3416   /* If the field name is not MBO, it must be 32-bit and no alternate.
3417      Otherwise primary must be 64-bit and alternate 32-bit.  */
3418   if (strcmp (mbostr, "MBO") != 0)
3419     return convert_vms_descriptor32 (gnu_type, gnu_expr, gnat_subprog);
3420
3421   /* Build the test for 64-bit descriptor.  */
3422   mbo = build3 (COMPONENT_REF, TREE_TYPE (mbo), desc, mbo, NULL_TREE);
3423   mbmo = build3 (COMPONENT_REF, TREE_TYPE (mbmo), desc, mbmo, NULL_TREE);
3424   is64bit
3425     = build_binary_op (TRUTH_ANDIF_EXPR, integer_type_node,
3426                        build_binary_op (EQ_EXPR, integer_type_node,
3427                                         convert (integer_type_node, mbo),
3428                                         integer_one_node),
3429                        build_binary_op (EQ_EXPR, integer_type_node,
3430                                         convert (integer_type_node, mbmo),
3431                                         integer_minus_one_node));
3432
3433   /* Build the 2 possible end results.  */
3434   gnu_expr64 = convert_vms_descriptor64 (gnu_type, gnu_expr, gnat_subprog);
3435   gnu_expr = fold_convert (gnu_expr_alt_type, gnu_expr);
3436   gnu_expr32 = convert_vms_descriptor32 (gnu_type, gnu_expr, gnat_subprog);
3437
3438   return build3 (COND_EXPR, gnu_type, is64bit, gnu_expr64, gnu_expr32);
3439 }
3440
3441 /* Build a stub for the subprogram specified by the GCC tree GNU_SUBPROG
3442    and the GNAT node GNAT_SUBPROG.  */
3443
3444 void
3445 build_function_stub (tree gnu_subprog, Entity_Id gnat_subprog)
3446 {
3447   tree gnu_subprog_type, gnu_subprog_addr, gnu_subprog_call;
3448   tree gnu_stub_param, gnu_param_list, gnu_arg_types, gnu_param;
3449   tree gnu_stub_decl = DECL_FUNCTION_STUB (gnu_subprog);
3450   tree gnu_body;
3451
3452   gnu_subprog_type = TREE_TYPE (gnu_subprog);
3453   gnu_param_list = NULL_TREE;
3454
3455   begin_subprog_body (gnu_stub_decl);
3456   gnat_pushlevel ();
3457
3458   start_stmt_group ();
3459
3460   /* Loop over the parameters of the stub and translate any of them
3461      passed by descriptor into a by reference one.  */
3462   for (gnu_stub_param = DECL_ARGUMENTS (gnu_stub_decl),
3463        gnu_arg_types = TYPE_ARG_TYPES (gnu_subprog_type);
3464        gnu_stub_param;
3465        gnu_stub_param = TREE_CHAIN (gnu_stub_param),
3466        gnu_arg_types = TREE_CHAIN (gnu_arg_types))
3467     {
3468       if (DECL_BY_DESCRIPTOR_P (gnu_stub_param))
3469         gnu_param
3470           = convert_vms_descriptor (TREE_VALUE (gnu_arg_types),
3471                                     gnu_stub_param,
3472                                     DECL_PARM_ALT_TYPE (gnu_stub_param),
3473                                     gnat_subprog);
3474       else
3475         gnu_param = gnu_stub_param;
3476
3477       gnu_param_list = tree_cons (NULL_TREE, gnu_param, gnu_param_list);
3478     }
3479
3480   gnu_body = end_stmt_group ();
3481
3482   /* Invoke the internal subprogram.  */
3483   gnu_subprog_addr = build1 (ADDR_EXPR, build_pointer_type (gnu_subprog_type),
3484                              gnu_subprog);
3485   gnu_subprog_call = build_call_list (TREE_TYPE (gnu_subprog_type),
3486                                       gnu_subprog_addr,
3487                                       nreverse (gnu_param_list));
3488
3489   /* Propagate the return value, if any.  */
3490   if (VOID_TYPE_P (TREE_TYPE (gnu_subprog_type)))
3491     append_to_statement_list (gnu_subprog_call, &gnu_body);
3492   else
3493     append_to_statement_list (build_return_expr (DECL_RESULT (gnu_stub_decl),
3494                                                  gnu_subprog_call),
3495                               &gnu_body);
3496
3497   gnat_poplevel ();
3498
3499   allocate_struct_function (gnu_stub_decl, false);
3500   end_subprog_body (gnu_body);
3501 }
3502 \f
3503 /* Build a type to be used to represent an aliased object whose nominal
3504    type is an unconstrained array.  This consists of a RECORD_TYPE containing
3505    a field of TEMPLATE_TYPE and a field of OBJECT_TYPE, which is an
3506    ARRAY_TYPE.  If ARRAY_TYPE is that of the unconstrained array, this
3507    is used to represent an arbitrary unconstrained object.  Use NAME
3508    as the name of the record.  */
3509
3510 tree
3511 build_unc_object_type (tree template_type, tree object_type, tree name)
3512 {
3513   tree type = make_node (RECORD_TYPE);
3514   tree template_field = create_field_decl (get_identifier ("BOUNDS"),
3515                                            template_type, type, 0, 0, 0, 1);
3516   tree array_field = create_field_decl (get_identifier ("ARRAY"), object_type,
3517                                         type, 0, 0, 0, 1);
3518
3519   TYPE_NAME (type) = name;
3520   TYPE_CONTAINS_TEMPLATE_P (type) = 1;
3521   finish_record_type (type,
3522                       chainon (chainon (NULL_TREE, template_field),
3523                                array_field),
3524                       0, false);
3525
3526   return type;
3527 }
3528
3529 /* Same, taking a thin or fat pointer type instead of a template type. */
3530
3531 tree
3532 build_unc_object_type_from_ptr (tree thin_fat_ptr_type, tree object_type,
3533                                 tree name)
3534 {
3535   tree template_type;
3536
3537   gcc_assert (TYPE_IS_FAT_OR_THIN_POINTER_P (thin_fat_ptr_type));
3538
3539   template_type
3540     = (TYPE_IS_FAT_POINTER_P (thin_fat_ptr_type)
3541        ? TREE_TYPE (TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (thin_fat_ptr_type))))
3542        : TREE_TYPE (TYPE_FIELDS (TREE_TYPE (thin_fat_ptr_type))));
3543   return build_unc_object_type (template_type, object_type, name);
3544 }
3545
3546 /* Shift the component offsets within an unconstrained object TYPE to make it
3547    suitable for use as a designated type for thin pointers.  */
3548
3549 void
3550 shift_unc_components_for_thin_pointers (tree type)
3551 {
3552   /* Thin pointer values designate the ARRAY data of an unconstrained object,
3553      allocated past the BOUNDS template.  The designated type is adjusted to
3554      have ARRAY at position zero and the template at a negative offset, so
3555      that COMPONENT_REFs on (*thin_ptr) designate the proper location.  */
3556
3557   tree bounds_field = TYPE_FIELDS (type);
3558   tree array_field  = TREE_CHAIN (TYPE_FIELDS (type));
3559
3560   DECL_FIELD_OFFSET (bounds_field)
3561     = size_binop (MINUS_EXPR, size_zero_node, byte_position (array_field));
3562
3563   DECL_FIELD_OFFSET (array_field) = size_zero_node;
3564   DECL_FIELD_BIT_OFFSET (array_field) = bitsize_zero_node;
3565 }
3566 \f
3567 /* Update anything previously pointing to OLD_TYPE to point to NEW_TYPE.
3568    In the normal case this is just two adjustments, but we have more to
3569    do if NEW_TYPE is an UNCONSTRAINED_ARRAY_TYPE.  */
3570
3571 void
3572 update_pointer_to (tree old_type, tree new_type)
3573 {
3574   tree ptr = TYPE_POINTER_TO (old_type);
3575   tree ref = TYPE_REFERENCE_TO (old_type);
3576   tree ptr1, ref1;
3577   tree type;
3578
3579   /* If this is the main variant, process all the other variants first.  */
3580   if (TYPE_MAIN_VARIANT (old_type) == old_type)
3581     for (type = TYPE_NEXT_VARIANT (old_type); type;
3582          type = TYPE_NEXT_VARIANT (type))
3583       update_pointer_to (type, new_type);
3584
3585   /* If no pointers and no references, we are done.  */
3586   if (!ptr && !ref)
3587     return;
3588
3589   /* Merge the old type qualifiers in the new type.
3590
3591      Each old variant has qualifiers for specific reasons, and the new
3592      designated type as well.  Each set of qualifiers represents useful
3593      information grabbed at some point, and merging the two simply unifies
3594      these inputs into the final type description.
3595
3596      Consider for instance a volatile type frozen after an access to constant
3597      type designating it; after the designated type's freeze, we get here with
3598      a volatile NEW_TYPE and a dummy OLD_TYPE with a readonly variant, created
3599      when the access type was processed.  We will make a volatile and readonly
3600      designated type, because that's what it really is.
3601
3602      We might also get here for a non-dummy OLD_TYPE variant with different
3603      qualifiers than those of NEW_TYPE, for instance in some cases of pointers
3604      to private record type elaboration (see the comments around the call to
3605      this routine in gnat_to_gnu_entity <E_Access_Type>).  We have to merge
3606      the qualifiers in those cases too, to avoid accidentally discarding the
3607      initial set, and will often end up with OLD_TYPE == NEW_TYPE then.  */
3608   new_type
3609     = build_qualified_type (new_type,
3610                             TYPE_QUALS (old_type) | TYPE_QUALS (new_type));
3611
3612   /* If old type and new type are identical, there is nothing to do.  */
3613   if (old_type == new_type)
3614     return;
3615
3616   /* Otherwise, first handle the simple case.  */
3617   if (TREE_CODE (new_type) != UNCONSTRAINED_ARRAY_TYPE)
3618     {
3619       TYPE_POINTER_TO (new_type) = ptr;
3620       TYPE_REFERENCE_TO (new_type) = ref;
3621
3622       for (; ptr; ptr = TYPE_NEXT_PTR_TO (ptr))
3623         for (ptr1 = TYPE_MAIN_VARIANT (ptr); ptr1;
3624              ptr1 = TYPE_NEXT_VARIANT (ptr1))
3625           TREE_TYPE (ptr1) = new_type;
3626
3627       for (; ref; ref = TYPE_NEXT_REF_TO (ref))
3628         for (ref1 = TYPE_MAIN_VARIANT (ref); ref1;
3629              ref1 = TYPE_NEXT_VARIANT (ref1))
3630           TREE_TYPE (ref1) = new_type;
3631     }
3632
3633   /* Now deal with the unconstrained array case.  In this case the "pointer"
3634      is actually a RECORD_TYPE where both fields are pointers to dummy nodes.
3635      Turn them into pointers to the correct types using update_pointer_to.  */
3636   else if (!TYPE_IS_FAT_POINTER_P (ptr))
3637     gcc_unreachable ();
3638
3639   else
3640     {
3641       tree new_obj_rec = TYPE_OBJECT_RECORD_TYPE (new_type);
3642       tree array_field = TYPE_FIELDS (ptr);
3643       tree bounds_field = TREE_CHAIN (TYPE_FIELDS (ptr));
3644       tree new_ptr = TYPE_POINTER_TO (new_type);
3645       tree new_ref;
3646       tree var;
3647
3648       /* Make pointers to the dummy template point to the real template.  */
3649       update_pointer_to
3650         (TREE_TYPE (TREE_TYPE (bounds_field)),
3651          TREE_TYPE (TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (new_ptr)))));
3652
3653       /* The references to the template bounds present in the array type
3654          are made through a PLACEHOLDER_EXPR of type NEW_PTR.  Since we
3655          are updating PTR to make it a full replacement for NEW_PTR as
3656          pointer to NEW_TYPE, we must rework the PLACEHOLDER_EXPR so as
3657          to make it of type PTR.  */
3658       new_ref = build3 (COMPONENT_REF, TREE_TYPE (bounds_field),
3659                         build0 (PLACEHOLDER_EXPR, ptr),
3660                         bounds_field, NULL_TREE);
3661
3662       /* Create the new array for the new PLACEHOLDER_EXPR and make pointers
3663          to the dummy array point to it.  */
3664       update_pointer_to
3665         (TREE_TYPE (TREE_TYPE (array_field)),
3666          substitute_in_type (TREE_TYPE (TREE_TYPE (TYPE_FIELDS (new_ptr))),
3667                              TREE_CHAIN (TYPE_FIELDS (new_ptr)), new_ref));
3668
3669       /* Make PTR the pointer to NEW_TYPE.  */
3670       TYPE_POINTER_TO (new_type) = TYPE_REFERENCE_TO (new_type)
3671         = TREE_TYPE (new_type) = ptr;
3672
3673       /* And show the original pointer NEW_PTR to the debugger.  This is the
3674          counterpart of the equivalent processing in gnat_pushdecl when the
3675          unconstrained array type is frozen after access types to it.  Note
3676          that update_pointer_to can be invoked multiple times on the same
3677          couple of types because of the type variants.  */
3678       if (TYPE_NAME (ptr)
3679           && TREE_CODE (TYPE_NAME (ptr)) == TYPE_DECL
3680           && !DECL_ORIGINAL_TYPE (TYPE_NAME (ptr)))
3681         {
3682           DECL_ORIGINAL_TYPE (TYPE_NAME (ptr)) = new_ptr;
3683           DECL_ARTIFICIAL (TYPE_NAME (ptr)) = 0;
3684         }
3685       for (var = TYPE_MAIN_VARIANT (ptr); var; var = TYPE_NEXT_VARIANT (var))
3686         SET_TYPE_UNCONSTRAINED_ARRAY (var, new_type);
3687
3688       /* Now handle updating the allocation record, what the thin pointer
3689          points to.  Update all pointers from the old record into the new
3690          one, update the type of the array field, and recompute the size.  */
3691       update_pointer_to (TYPE_OBJECT_RECORD_TYPE (old_type), new_obj_rec);
3692
3693       TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (new_obj_rec)))
3694         = TREE_TYPE (TREE_TYPE (array_field));
3695
3696       /* The size recomputation needs to account for alignment constraints, so
3697          we let layout_type work it out.  This will reset the field offsets to
3698          what they would be in a regular record, so we shift them back to what
3699          we want them to be for a thin pointer designated type afterwards.  */
3700       DECL_SIZE (TYPE_FIELDS (new_obj_rec)) = 0;
3701       DECL_SIZE (TREE_CHAIN (TYPE_FIELDS (new_obj_rec))) = 0;
3702       TYPE_SIZE (new_obj_rec) = 0;
3703       layout_type (new_obj_rec);
3704
3705       shift_unc_components_for_thin_pointers (new_obj_rec);
3706
3707       /* We are done, at last.  */
3708       rest_of_record_type_compilation (ptr);
3709     }
3710 }
3711 \f
3712 /* Convert EXPR, a pointer to a constrained array, into a pointer to an
3713    unconstrained one.  This involves making or finding a template.  */
3714
3715 static tree
3716 convert_to_fat_pointer (tree type, tree expr)
3717 {
3718   tree template_type = TREE_TYPE (TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (type))));
3719   tree p_array_type = TREE_TYPE (TYPE_FIELDS (type));
3720   tree etype = TREE_TYPE (expr);
3721   tree template_tree;
3722
3723   /* If EXPR is null, make a fat pointer that contains null pointers to the
3724      template and array.  */
3725   if (integer_zerop (expr))
3726     return
3727       gnat_build_constructor
3728         (type,
3729          tree_cons (TYPE_FIELDS (type),
3730                     convert (p_array_type, expr),
3731                     tree_cons (TREE_CHAIN (TYPE_FIELDS (type)),
3732                                convert (build_pointer_type (template_type),
3733                                         expr),
3734                                NULL_TREE)));
3735
3736   /* If EXPR is a thin pointer, make template and data from the record..  */
3737   else if (TYPE_IS_THIN_POINTER_P (etype))
3738     {
3739       tree fields = TYPE_FIELDS (TREE_TYPE (etype));
3740
3741       expr = save_expr (expr);
3742       if (TREE_CODE (expr) == ADDR_EXPR)
3743         expr = TREE_OPERAND (expr, 0);
3744       else
3745         expr = build1 (INDIRECT_REF, TREE_TYPE (etype), expr);
3746
3747       template_tree = build_component_ref (expr, NULL_TREE, fields, false);
3748       expr = build_unary_op (ADDR_EXPR, NULL_TREE,
3749                              build_component_ref (expr, NULL_TREE,
3750                                                   TREE_CHAIN (fields), false));
3751     }
3752
3753   /* Otherwise, build the constructor for the template.  */
3754   else
3755     template_tree = build_template (template_type, TREE_TYPE (etype), expr);
3756
3757   /* The final result is a constructor for the fat pointer.
3758
3759      If EXPR is an argument of a foreign convention subprogram, the type it
3760      points to is directly the component type.  In this case, the expression
3761      type may not match the corresponding FIELD_DECL type at this point, so we
3762      call "convert" here to fix that up if necessary.  This type consistency is
3763      required, for instance because it ensures that possible later folding of
3764      COMPONENT_REFs against this constructor always yields something of the
3765      same type as the initial reference.
3766
3767      Note that the call to "build_template" above is still fine because it
3768      will only refer to the provided TEMPLATE_TYPE in this case.  */
3769   return
3770     gnat_build_constructor
3771       (type,
3772        tree_cons (TYPE_FIELDS (type),
3773                   convert (p_array_type, expr),
3774                   tree_cons (TREE_CHAIN (TYPE_FIELDS (type)),
3775                              build_unary_op (ADDR_EXPR, NULL_TREE,
3776                                              template_tree),
3777                              NULL_TREE)));
3778 }
3779 \f
3780 /* Convert to a thin pointer type, TYPE.  The only thing we know how to convert
3781    is something that is a fat pointer, so convert to it first if it EXPR
3782    is not already a fat pointer.  */
3783
3784 static tree
3785 convert_to_thin_pointer (tree type, tree expr)
3786 {
3787   if (!TYPE_IS_FAT_POINTER_P (TREE_TYPE (expr)))
3788     expr
3789       = convert_to_fat_pointer
3790         (TREE_TYPE (TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (type))), expr);
3791
3792   /* We get the pointer to the data and use a NOP_EXPR to make it the
3793      proper GCC type.  */
3794   expr = build_component_ref (expr, NULL_TREE, TYPE_FIELDS (TREE_TYPE (expr)),
3795                               false);
3796   expr = build1 (NOP_EXPR, type, expr);
3797
3798   return expr;
3799 }
3800 \f
3801 /* Create an expression whose value is that of EXPR,
3802    converted to type TYPE.  The TREE_TYPE of the value
3803    is always TYPE.  This function implements all reasonable
3804    conversions; callers should filter out those that are
3805    not permitted by the language being compiled.  */
3806
3807 tree
3808 convert (tree type, tree expr)
3809 {
3810   enum tree_code code = TREE_CODE (type);
3811   tree etype = TREE_TYPE (expr);
3812   enum tree_code ecode = TREE_CODE (etype);
3813
3814   /* If EXPR is already the right type, we are done.  */
3815   if (type == etype)
3816     return expr;
3817
3818   /* If both input and output have padding and are of variable size, do this
3819      as an unchecked conversion.  Likewise if one is a mere variant of the
3820      other, so we avoid a pointless unpad/repad sequence.  */
3821   else if (code == RECORD_TYPE && ecode == RECORD_TYPE
3822            && TYPE_PADDING_P (type) && TYPE_PADDING_P (etype)
3823            && (!TREE_CONSTANT (TYPE_SIZE (type))
3824                || !TREE_CONSTANT (TYPE_SIZE (etype))
3825                || gnat_types_compatible_p (type, etype)
3826                || TYPE_NAME (TREE_TYPE (TYPE_FIELDS (type)))
3827                   == TYPE_NAME (TREE_TYPE (TYPE_FIELDS (etype)))))
3828     ;
3829
3830   /* If the output type has padding, convert to the inner type and make a
3831      constructor to build the record, unless a variable size is involved.  */
3832   else if (code == RECORD_TYPE && TYPE_PADDING_P (type))
3833     {
3834       /* If we previously converted from another type and our type is
3835          of variable size, remove the conversion to avoid the need for
3836          variable-sized temporaries.  Likewise for a conversion between
3837          original and packable version.  */
3838       if (TREE_CODE (expr) == VIEW_CONVERT_EXPR
3839           && (!TREE_CONSTANT (TYPE_SIZE (type))
3840               || (ecode == RECORD_TYPE
3841                   && TYPE_NAME (etype)
3842                      == TYPE_NAME (TREE_TYPE (TREE_OPERAND (expr, 0))))))
3843         expr = TREE_OPERAND (expr, 0);
3844
3845       /* If we are just removing the padding from expr, convert the original
3846          object if we have variable size in order to avoid the need for some
3847          variable-sized temporaries.  Likewise if the padding is a variant
3848          of the other, so we avoid a pointless unpad/repad sequence.  */
3849       if (TREE_CODE (expr) == COMPONENT_REF
3850           && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (expr, 0)))
3851           && (!TREE_CONSTANT (TYPE_SIZE (type))
3852               || gnat_types_compatible_p (type,
3853                                           TREE_TYPE (TREE_OPERAND (expr, 0)))
3854               || (ecode == RECORD_TYPE
3855                   && TYPE_NAME (etype)
3856                      == TYPE_NAME (TREE_TYPE (TYPE_FIELDS (type))))))
3857         return convert (type, TREE_OPERAND (expr, 0));
3858
3859       /* If the result type is a padded type with a self-referentially-sized
3860          field and the expression type is a record, do this as an unchecked
3861          conversion.  */
3862       if (TREE_CODE (etype) == RECORD_TYPE
3863           && CONTAINS_PLACEHOLDER_P (DECL_SIZE (TYPE_FIELDS (type))))
3864         return unchecked_convert (type, expr, false);
3865
3866       /* If we are converting between array types with variable size, do the
3867          final conversion as an unchecked conversion, again to avoid the need
3868          for some variable-sized temporaries.  If valid, this conversion is
3869          very likely purely technical and without real effects.  */
3870       if (TREE_CODE (etype) == ARRAY_TYPE
3871           && TREE_CODE (TREE_TYPE (TYPE_FIELDS (type))) == ARRAY_TYPE
3872           && !TREE_CONSTANT (TYPE_SIZE (etype))
3873           && !TREE_CONSTANT (TYPE_SIZE (type)))
3874         return unchecked_convert (type,
3875                                   convert (TREE_TYPE (TYPE_FIELDS (type)),
3876                                            expr),
3877                                   false);
3878
3879       return
3880         gnat_build_constructor (type,
3881                                 tree_cons (TYPE_FIELDS (type),
3882                                            convert (TREE_TYPE
3883                                                     (TYPE_FIELDS (type)),
3884                                                     expr),
3885                                            NULL_TREE));
3886     }
3887
3888   /* If the input type has padding, remove it and convert to the output type.
3889      The conditions ordering is arranged to ensure that the output type is not
3890      a padding type here, as it is not clear whether the conversion would
3891      always be correct if this was to happen.  */
3892   else if (ecode == RECORD_TYPE && TYPE_PADDING_P (etype))
3893     {
3894       tree unpadded;
3895
3896       /* If we have just converted to this padded type, just get the
3897          inner expression.  */
3898       if (TREE_CODE (expr) == CONSTRUCTOR
3899           && !VEC_empty (constructor_elt, CONSTRUCTOR_ELTS (expr))
3900           && VEC_index (constructor_elt, CONSTRUCTOR_ELTS (expr), 0)->index
3901              == TYPE_FIELDS (etype))
3902         unpadded
3903           = VEC_index (constructor_elt, CONSTRUCTOR_ELTS (expr), 0)->value;
3904
3905       /* Otherwise, build an explicit component reference.  */
3906       else
3907         unpadded
3908           = build_component_ref (expr, NULL_TREE, TYPE_FIELDS (etype), false);
3909
3910       return convert (type, unpadded);
3911     }
3912
3913   /* If the input is a biased type, adjust first.  */
3914   if (ecode == INTEGER_TYPE && TYPE_BIASED_REPRESENTATION_P (etype))
3915     return convert (type, fold_build2 (PLUS_EXPR, TREE_TYPE (etype),
3916                                        fold_convert (TREE_TYPE (etype),
3917                                                      expr),
3918                                        TYPE_MIN_VALUE (etype)));
3919
3920   /* If the input is a justified modular type, we need to extract the actual
3921      object before converting it to any other type with the exceptions of an
3922      unconstrained array or of a mere type variant.  It is useful to avoid the
3923      extraction and conversion in the type variant case because it could end
3924      up replacing a VAR_DECL expr by a constructor and we might be about the
3925      take the address of the result.  */
3926   if (ecode == RECORD_TYPE && TYPE_JUSTIFIED_MODULAR_P (etype)
3927       && code != UNCONSTRAINED_ARRAY_TYPE
3928       && TYPE_MAIN_VARIANT (type) != TYPE_MAIN_VARIANT (etype))
3929     return convert (type, build_component_ref (expr, NULL_TREE,
3930                                                TYPE_FIELDS (etype), false));
3931
3932   /* If converting to a type that contains a template, convert to the data
3933      type and then build the template. */
3934   if (code == RECORD_TYPE && TYPE_CONTAINS_TEMPLATE_P (type))
3935     {
3936       tree obj_type = TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (type)));
3937
3938       /* If the source already has a template, get a reference to the
3939          associated array only, as we are going to rebuild a template
3940          for the target type anyway.  */
3941       expr = maybe_unconstrained_array (expr);
3942
3943       return
3944         gnat_build_constructor
3945           (type,
3946            tree_cons (TYPE_FIELDS (type),
3947                       build_template (TREE_TYPE (TYPE_FIELDS (type)),
3948                                       obj_type, NULL_TREE),
3949                       tree_cons (TREE_CHAIN (TYPE_FIELDS (type)),
3950                                  convert (obj_type, expr), NULL_TREE)));
3951     }
3952
3953   /* There are some special cases of expressions that we process
3954      specially.  */
3955   switch (TREE_CODE (expr))
3956     {
3957     case ERROR_MARK:
3958       return expr;
3959
3960     case NULL_EXPR:
3961       /* Just set its type here.  For TRANSFORM_EXPR, we will do the actual
3962          conversion in gnat_expand_expr.  NULL_EXPR does not represent
3963          and actual value, so no conversion is needed.  */
3964       expr = copy_node (expr);
3965       TREE_TYPE (expr) = type;
3966       return expr;
3967
3968     case STRING_CST:
3969       /* If we are converting a STRING_CST to another constrained array type,
3970          just make a new one in the proper type.  */
3971       if (code == ecode && AGGREGATE_TYPE_P (etype)
3972           && !(TREE_CODE (TYPE_SIZE (etype)) == INTEGER_CST
3973                && TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST))
3974         {
3975           expr = copy_node (expr);
3976           TREE_TYPE (expr) = type;
3977           return expr;
3978         }
3979       break;
3980
3981     case VECTOR_CST:
3982       /* If we are converting a VECTOR_CST to a mere variant type, just make
3983          a new one in the proper type.  */
3984       if (code == ecode && gnat_types_compatible_p (type, etype))
3985         {
3986           expr = copy_node (expr);
3987           TREE_TYPE (expr) = type;
3988           return expr;
3989         }
3990
3991     case CONSTRUCTOR:
3992       /* If we are converting a CONSTRUCTOR to a mere variant type, just make
3993          a new one in the proper type.  */
3994       if (code == ecode && gnat_types_compatible_p (type, etype))
3995         {
3996           expr = copy_node (expr);
3997           TREE_TYPE (expr) = type;
3998           return expr;
3999         }
4000
4001       /* Likewise for a conversion between original and packable version, but
4002          we have to work harder in order to preserve type consistency.  */
4003       if (code == ecode
4004           && code == RECORD_TYPE
4005           && TYPE_NAME (type) == TYPE_NAME (etype))
4006         {
4007           VEC(constructor_elt,gc) *e = CONSTRUCTOR_ELTS (expr);
4008           unsigned HOST_WIDE_INT len = VEC_length (constructor_elt, e);
4009           VEC(constructor_elt,gc) *v = VEC_alloc (constructor_elt, gc, len);
4010           tree efield = TYPE_FIELDS (etype), field = TYPE_FIELDS (type);
4011           unsigned HOST_WIDE_INT idx;
4012           tree index, value;
4013
4014           /* Whether we need to clear TREE_CONSTANT et al. on the output
4015              constructor when we convert in place.  */
4016           bool clear_constant = false;
4017
4018           FOR_EACH_CONSTRUCTOR_ELT(e, idx, index, value)
4019             {
4020               constructor_elt *elt = VEC_quick_push (constructor_elt, v, NULL);
4021               /* We expect only simple constructors.  Otherwise, punt.  */
4022               if (!(index == efield || index == DECL_ORIGINAL_FIELD (efield)))
4023                 break;
4024               elt->index = field;
4025               elt->value = convert (TREE_TYPE (field), value);
4026
4027               /* If packing has made this field a bitfield and the input
4028                  value couldn't be emitted statically any more, we need to
4029                  clear TREE_CONSTANT on our output.  */
4030               if (!clear_constant && TREE_CONSTANT (expr)
4031                   && !CONSTRUCTOR_BITFIELD_P (efield)
4032                   && CONSTRUCTOR_BITFIELD_P (field)
4033                   && !initializer_constant_valid_for_bitfield_p (value))
4034                 clear_constant = true;
4035
4036               efield = TREE_CHAIN (efield);
4037               field = TREE_CHAIN (field);
4038             }
4039
4040           /* If we have been able to match and convert all the input fields
4041              to their output type, convert in place now.  We'll fallback to a
4042              view conversion downstream otherwise.  */
4043           if (idx == len)
4044             {
4045               expr = copy_node (expr);
4046               TREE_TYPE (expr) = type;
4047               CONSTRUCTOR_ELTS (expr) = v;
4048               if (clear_constant)
4049                 TREE_CONSTANT (expr) = TREE_STATIC (expr) = false;
4050               return expr;
4051             }
4052         }
4053
4054       /* Likewise for a conversion between array type and vector type with a
4055          compatible representative array.  */
4056       else if (code == VECTOR_TYPE
4057                && ecode == ARRAY_TYPE
4058                && gnat_types_compatible_p (TYPE_REPRESENTATIVE_ARRAY (type),
4059                                            etype))
4060         {
4061           VEC(constructor_elt,gc) *e = CONSTRUCTOR_ELTS (expr);
4062           unsigned HOST_WIDE_INT len = VEC_length (constructor_elt, e);
4063           VEC(constructor_elt,gc) *v;
4064           unsigned HOST_WIDE_INT ix;
4065           tree value;
4066
4067           /* Build a VECTOR_CST from a *constant* array constructor.  */
4068           if (TREE_CONSTANT (expr))
4069             {
4070               bool constant_p = true;
4071
4072               /* Iterate through elements and check if all constructor
4073                  elements are *_CSTs.  */
4074               FOR_EACH_CONSTRUCTOR_VALUE (e, ix, value)
4075                 if (!CONSTANT_CLASS_P (value))
4076                   {
4077                     constant_p = false;
4078                     break;
4079                   }
4080
4081               if (constant_p)
4082                 return build_vector_from_ctor (type,
4083                                                CONSTRUCTOR_ELTS (expr));
4084             }
4085
4086           /* Otherwise, build a regular vector constructor.  */
4087           v = VEC_alloc (constructor_elt, gc, len);
4088           FOR_EACH_CONSTRUCTOR_VALUE (e, ix, value)
4089             {
4090               constructor_elt *elt = VEC_quick_push (constructor_elt, v, NULL);
4091               elt->index = NULL_TREE;
4092               elt->value = value;
4093             }
4094           expr = copy_node (expr);
4095           TREE_TYPE (expr) = type;
4096           CONSTRUCTOR_ELTS (expr) = v;
4097           return expr;
4098         }
4099       break;
4100
4101     case UNCONSTRAINED_ARRAY_REF:
4102       /* Convert this to the type of the inner array by getting the address of
4103          the array from the template.  */
4104       expr = build_unary_op (INDIRECT_REF, NULL_TREE,
4105                              build_component_ref (TREE_OPERAND (expr, 0),
4106                                                   get_identifier ("P_ARRAY"),
4107                                                   NULL_TREE, false));
4108       etype = TREE_TYPE (expr);
4109       ecode = TREE_CODE (etype);
4110       break;
4111
4112     case VIEW_CONVERT_EXPR:
4113       {
4114         /* GCC 4.x is very sensitive to type consistency overall, and view
4115            conversions thus are very frequent.  Even though just "convert"ing
4116            the inner operand to the output type is fine in most cases, it
4117            might expose unexpected input/output type mismatches in special
4118            circumstances so we avoid such recursive calls when we can.  */
4119         tree op0 = TREE_OPERAND (expr, 0);
4120
4121         /* If we are converting back to the original type, we can just
4122            lift the input conversion.  This is a common occurrence with
4123            switches back-and-forth amongst type variants.  */
4124         if (type == TREE_TYPE (op0))
4125           return op0;
4126
4127         /* Otherwise, if we're converting between two aggregate or vector
4128            types, we might be allowed to substitute the VIEW_CONVERT_EXPR
4129            target type in place or to just convert the inner expression.  */
4130         if ((AGGREGATE_TYPE_P (type) && AGGREGATE_TYPE_P (etype))
4131             || (VECTOR_TYPE_P (type) && VECTOR_TYPE_P (etype)))
4132           {
4133             /* If we are converting between mere variants, we can just
4134                substitute the VIEW_CONVERT_EXPR in place.  */
4135             if (gnat_types_compatible_p (type, etype))
4136               return build1 (VIEW_CONVERT_EXPR, type, op0);
4137
4138             /* Otherwise, we may just bypass the input view conversion unless
4139                one of the types is a fat pointer,  which is handled by
4140                specialized code below which relies on exact type matching.  */
4141             else if (!TYPE_IS_FAT_POINTER_P (type)
4142                      && !TYPE_IS_FAT_POINTER_P (etype))
4143               return convert (type, op0);
4144           }
4145       }
4146       break;
4147
4148     case INDIRECT_REF:
4149       /* If both types are record types, just convert the pointer and
4150          make a new INDIRECT_REF.
4151
4152          ??? Disable this for now since it causes problems with the
4153          code in build_binary_op for MODIFY_EXPR which wants to
4154          strip off conversions.  But that code really is a mess and
4155          we need to do this a much better way some time.  */
4156       if (0
4157           && (TREE_CODE (type) == RECORD_TYPE
4158               || TREE_CODE (type) == UNION_TYPE)
4159           && (TREE_CODE (etype) == RECORD_TYPE
4160               || TREE_CODE (etype) == UNION_TYPE)
4161           && !TYPE_IS_FAT_POINTER_P (type) && !TYPE_IS_FAT_POINTER_P (etype))
4162         return build_unary_op (INDIRECT_REF, NULL_TREE,
4163                                convert (build_pointer_type (type),
4164                                         TREE_OPERAND (expr, 0)));
4165       break;
4166
4167     default:
4168       break;
4169     }
4170
4171   /* Check for converting to a pointer to an unconstrained array.  */
4172   if (TYPE_IS_FAT_POINTER_P (type) && !TYPE_IS_FAT_POINTER_P (etype))
4173     return convert_to_fat_pointer (type, expr);
4174
4175   /* If we are converting between two aggregate or vector types that are mere
4176      variants, just make a VIEW_CONVERT_EXPR.  Likewise when we are converting
4177      to a vector type from its representative array type.  */
4178   else if ((code == ecode
4179             && (AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type))
4180             && gnat_types_compatible_p (type, etype))
4181            || (code == VECTOR_TYPE
4182                && ecode == ARRAY_TYPE
4183                && gnat_types_compatible_p (TYPE_REPRESENTATIVE_ARRAY (type),
4184                                            etype)))
4185     return build1 (VIEW_CONVERT_EXPR, type, expr);
4186
4187   /* In all other cases of related types, make a NOP_EXPR.  */
4188   else if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (etype)
4189            || (code == INTEGER_CST && ecode == INTEGER_CST
4190                && (type == TREE_TYPE (etype) || etype == TREE_TYPE (type))))
4191     return fold_convert (type, expr);
4192
4193   switch (code)
4194     {
4195     case VOID_TYPE:
4196       return fold_build1 (CONVERT_EXPR, type, expr);
4197
4198     case INTEGER_TYPE:
4199       if (TYPE_HAS_ACTUAL_BOUNDS_P (type)
4200           && (ecode == ARRAY_TYPE || ecode == UNCONSTRAINED_ARRAY_TYPE
4201               || (ecode == RECORD_TYPE && TYPE_CONTAINS_TEMPLATE_P (etype))))
4202         return unchecked_convert (type, expr, false);
4203       else if (TYPE_BIASED_REPRESENTATION_P (type))
4204         return fold_convert (type,
4205                              fold_build2 (MINUS_EXPR, TREE_TYPE (type),
4206                                           convert (TREE_TYPE (type), expr),
4207                                           TYPE_MIN_VALUE (type)));
4208
4209       /* ... fall through ... */
4210
4211     case ENUMERAL_TYPE:
4212     case BOOLEAN_TYPE:
4213       /* If we are converting an additive expression to an integer type
4214          with lower precision, be wary of the optimization that can be
4215          applied by convert_to_integer.  There are 2 problematic cases:
4216            - if the first operand was originally of a biased type,
4217              because we could be recursively called to convert it
4218              to an intermediate type and thus rematerialize the
4219              additive operator endlessly,
4220            - if the expression contains a placeholder, because an
4221              intermediate conversion that changes the sign could
4222              be inserted and thus introduce an artificial overflow
4223              at compile time when the placeholder is substituted.  */
4224       if (code == INTEGER_TYPE
4225           && ecode == INTEGER_TYPE
4226           && TYPE_PRECISION (type) < TYPE_PRECISION (etype)
4227           && (TREE_CODE (expr) == PLUS_EXPR || TREE_CODE (expr) == MINUS_EXPR))
4228         {
4229           tree op0 = get_unwidened (TREE_OPERAND (expr, 0), type);
4230
4231           if ((TREE_CODE (TREE_TYPE (op0)) == INTEGER_TYPE
4232                && TYPE_BIASED_REPRESENTATION_P (TREE_TYPE (op0)))
4233               || CONTAINS_PLACEHOLDER_P (expr))
4234             return build1 (NOP_EXPR, type, expr);
4235         }
4236
4237       return fold (convert_to_integer (type, expr));
4238
4239     case POINTER_TYPE:
4240     case REFERENCE_TYPE:
4241       /* If converting between two pointers to records denoting
4242          both a template and type, adjust if needed to account
4243          for any differing offsets, since one might be negative.  */
4244       if (TYPE_IS_THIN_POINTER_P (etype) && TYPE_IS_THIN_POINTER_P (type))
4245         {
4246           tree bit_diff
4247             = size_diffop (bit_position (TYPE_FIELDS (TREE_TYPE (etype))),
4248                            bit_position (TYPE_FIELDS (TREE_TYPE (type))));
4249           tree byte_diff = size_binop (CEIL_DIV_EXPR, bit_diff,
4250                                        sbitsize_int (BITS_PER_UNIT));
4251
4252           expr = build1 (NOP_EXPR, type, expr);
4253           TREE_CONSTANT (expr) = TREE_CONSTANT (TREE_OPERAND (expr, 0));
4254           if (integer_zerop (byte_diff))
4255             return expr;
4256
4257           return build_binary_op (POINTER_PLUS_EXPR, type, expr,
4258                                   fold (convert (sizetype, byte_diff)));
4259         }
4260
4261       /* If converting to a thin pointer, handle specially.  */
4262       if (TYPE_IS_THIN_POINTER_P (type)
4263           && TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (type)))
4264         return convert_to_thin_pointer (type, expr);
4265
4266       /* If converting fat pointer to normal pointer, get the pointer to the
4267          array and then convert it.  */
4268       else if (TYPE_IS_FAT_POINTER_P (etype))
4269         expr = build_component_ref (expr, get_identifier ("P_ARRAY"),
4270                                     NULL_TREE, false);
4271
4272       return fold (convert_to_pointer (type, expr));
4273
4274     case REAL_TYPE:
4275       return fold (convert_to_real (type, expr));
4276
4277     case RECORD_TYPE:
4278       if (TYPE_JUSTIFIED_MODULAR_P (type) && !AGGREGATE_TYPE_P (etype))
4279         return
4280           gnat_build_constructor
4281             (type, tree_cons (TYPE_FIELDS (type),
4282                               convert (TREE_TYPE (TYPE_FIELDS (type)), expr),
4283                               NULL_TREE));
4284
4285       /* ... fall through ... */
4286
4287     case ARRAY_TYPE:
4288       /* In these cases, assume the front-end has validated the conversion.
4289          If the conversion is valid, it will be a bit-wise conversion, so
4290          it can be viewed as an unchecked conversion.  */
4291       return unchecked_convert (type, expr, false);
4292
4293     case UNION_TYPE:
4294       /* This is a either a conversion between a tagged type and some
4295          subtype, which we have to mark as a UNION_TYPE because of
4296          overlapping fields or a conversion of an Unchecked_Union.  */
4297       return unchecked_convert (type, expr, false);
4298
4299     case UNCONSTRAINED_ARRAY_TYPE:
4300       /* If the input is a VECTOR_TYPE, convert to the representative
4301          array type first.  */
4302       if (ecode == VECTOR_TYPE)
4303         {
4304           expr = convert (TYPE_REPRESENTATIVE_ARRAY (etype), expr);
4305           etype = TREE_TYPE (expr);
4306           ecode = TREE_CODE (etype);
4307         }
4308
4309       /* If EXPR is a constrained array, take its address, convert it to a
4310          fat pointer, and then dereference it.  Likewise if EXPR is a
4311          record containing both a template and a constrained array.
4312          Note that a record representing a justified modular type
4313          always represents a packed constrained array.  */
4314       if (ecode == ARRAY_TYPE
4315           || (ecode == INTEGER_TYPE && TYPE_HAS_ACTUAL_BOUNDS_P (etype))
4316           || (ecode == RECORD_TYPE && TYPE_CONTAINS_TEMPLATE_P (etype))
4317           || (ecode == RECORD_TYPE && TYPE_JUSTIFIED_MODULAR_P (etype)))
4318         return
4319           build_unary_op
4320             (INDIRECT_REF, NULL_TREE,
4321              convert_to_fat_pointer (TREE_TYPE (type),
4322                                      build_unary_op (ADDR_EXPR,
4323                                                      NULL_TREE, expr)));
4324
4325       /* Do something very similar for converting one unconstrained
4326          array to another.  */
4327       else if (ecode == UNCONSTRAINED_ARRAY_TYPE)
4328         return
4329           build_unary_op (INDIRECT_REF, NULL_TREE,
4330                           convert (TREE_TYPE (type),
4331                                    build_unary_op (ADDR_EXPR,
4332                                                    NULL_TREE, expr)));
4333       else
4334         gcc_unreachable ();
4335
4336     case COMPLEX_TYPE:
4337       return fold (convert_to_complex (type, expr));
4338
4339     default:
4340       gcc_unreachable ();
4341     }
4342 }
4343 \f
4344 /* Remove all conversions that are done in EXP.  This includes converting
4345    from a padded type or to a justified modular type.  If TRUE_ADDRESS
4346    is true, always return the address of the containing object even if
4347    the address is not bit-aligned.  */
4348
4349 tree
4350 remove_conversions (tree exp, bool true_address)
4351 {
4352   switch (TREE_CODE (exp))
4353     {
4354     case CONSTRUCTOR:
4355       if (true_address
4356           && TREE_CODE (TREE_TYPE (exp)) == RECORD_TYPE
4357           && TYPE_JUSTIFIED_MODULAR_P (TREE_TYPE (exp)))
4358         return
4359           remove_conversions (VEC_index (constructor_elt,
4360                                          CONSTRUCTOR_ELTS (exp), 0)->value,
4361                               true);
4362       break;
4363
4364     case COMPONENT_REF:
4365       if (TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (exp, 0))))
4366         return remove_conversions (TREE_OPERAND (exp, 0), true_address);
4367       break;
4368
4369     case VIEW_CONVERT_EXPR:  case NON_LVALUE_EXPR:
4370     CASE_CONVERT:
4371       return remove_conversions (TREE_OPERAND (exp, 0), true_address);
4372
4373     default:
4374       break;
4375     }
4376
4377   return exp;
4378 }
4379 \f
4380 /* If EXP's type is an UNCONSTRAINED_ARRAY_TYPE, return an expression that
4381    refers to the underlying array.  If its type has TYPE_CONTAINS_TEMPLATE_P,
4382    likewise return an expression pointing to the underlying array.  */
4383
4384 tree
4385 maybe_unconstrained_array (tree exp)
4386 {
4387   enum tree_code code = TREE_CODE (exp);
4388   tree new_exp;
4389
4390   switch (TREE_CODE (TREE_TYPE (exp)))
4391     {
4392     case UNCONSTRAINED_ARRAY_TYPE:
4393       if (code == UNCONSTRAINED_ARRAY_REF)
4394         {
4395           new_exp
4396             = build_unary_op (INDIRECT_REF, NULL_TREE,
4397                               build_component_ref (TREE_OPERAND (exp, 0),
4398                                                    get_identifier ("P_ARRAY"),
4399                                                    NULL_TREE, false));
4400           TREE_READONLY (new_exp) = TREE_STATIC (new_exp)
4401             = TREE_READONLY (exp);
4402           return new_exp;
4403         }
4404
4405       else if (code == NULL_EXPR)
4406         return build1 (NULL_EXPR,
4407                        TREE_TYPE (TREE_TYPE (TYPE_FIELDS
4408                                              (TREE_TYPE (TREE_TYPE (exp))))),
4409                        TREE_OPERAND (exp, 0));
4410
4411     case RECORD_TYPE:
4412       /* If this is a padded type, convert to the unpadded type and see if
4413          it contains a template.  */
4414       if (TYPE_PADDING_P (TREE_TYPE (exp)))
4415         {
4416           new_exp = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (exp))), exp);
4417           if (TREE_CODE (TREE_TYPE (new_exp)) == RECORD_TYPE
4418               && TYPE_CONTAINS_TEMPLATE_P (TREE_TYPE (new_exp)))
4419             return
4420               build_component_ref (new_exp, NULL_TREE,
4421                                    TREE_CHAIN
4422                                    (TYPE_FIELDS (TREE_TYPE (new_exp))),
4423                                    0);
4424         }
4425       else if (TYPE_CONTAINS_TEMPLATE_P (TREE_TYPE (exp)))
4426         return
4427           build_component_ref (exp, NULL_TREE,
4428                                TREE_CHAIN (TYPE_FIELDS (TREE_TYPE (exp))), 0);
4429       break;
4430
4431     default:
4432       break;
4433     }
4434
4435   return exp;
4436 }
4437
4438 /* If EXP's type is a VECTOR_TYPE, return EXP converted to the associated
4439    TYPE_REPRESENTATIVE_ARRAY.  */
4440
4441 tree
4442 maybe_vector_array (tree exp)
4443 {
4444   tree etype = TREE_TYPE (exp);
4445
4446   if (VECTOR_TYPE_P (etype))
4447     exp = convert (TYPE_REPRESENTATIVE_ARRAY (etype), exp);
4448
4449   return exp;
4450 }
4451 \f
4452 /* Return true if EXPR is an expression that can be folded as an operand
4453    of a VIEW_CONVERT_EXPR.  See ada-tree.h for a complete rationale.  */
4454
4455 static bool
4456 can_fold_for_view_convert_p (tree expr)
4457 {
4458   tree t1, t2;
4459
4460   /* The folder will fold NOP_EXPRs between integral types with the same
4461      precision (in the middle-end's sense).  We cannot allow it if the
4462      types don't have the same precision in the Ada sense as well.  */
4463   if (TREE_CODE (expr) != NOP_EXPR)
4464     return true;
4465
4466   t1 = TREE_TYPE (expr);
4467   t2 = TREE_TYPE (TREE_OPERAND (expr, 0));
4468
4469   /* Defer to the folder for non-integral conversions.  */
4470   if (!(INTEGRAL_TYPE_P (t1) && INTEGRAL_TYPE_P (t2)))
4471     return true;
4472
4473   /* Only fold conversions that preserve both precisions.  */
4474   if (TYPE_PRECISION (t1) == TYPE_PRECISION (t2)
4475       && operand_equal_p (rm_size (t1), rm_size (t2), 0))
4476     return true;
4477
4478   return false;
4479 }
4480
4481 /* Return an expression that does an unchecked conversion of EXPR to TYPE.
4482    If NOTRUNC_P is true, truncation operations should be suppressed.
4483
4484    Special care is required with (source or target) integral types whose
4485    precision is not equal to their size, to make sure we fetch or assign
4486    the value bits whose location might depend on the endianness, e.g.
4487
4488      Rmsize : constant := 8;
4489      subtype Int is Integer range 0 .. 2 ** Rmsize - 1;
4490
4491      type Bit_Array is array (1 .. Rmsize) of Boolean;
4492      pragma Pack (Bit_Array);
4493
4494      function To_Bit_Array is new Unchecked_Conversion (Int, Bit_Array);
4495
4496      Value : Int := 2#1000_0001#;
4497      Vbits : Bit_Array := To_Bit_Array (Value);
4498
4499    we expect the 8 bits at Vbits'Address to always contain Value, while
4500    their original location depends on the endianness, at Value'Address
4501    on a little-endian architecture but not on a big-endian one.  */
4502
4503 tree
4504 unchecked_convert (tree type, tree expr, bool notrunc_p)
4505 {
4506   tree etype = TREE_TYPE (expr);
4507
4508   /* If the expression is already the right type, we are done.  */
4509   if (etype == type)
4510     return expr;
4511
4512   /* If both types types are integral just do a normal conversion.
4513      Likewise for a conversion to an unconstrained array.  */
4514   if ((((INTEGRAL_TYPE_P (type)
4515          && !(TREE_CODE (type) == INTEGER_TYPE
4516               && TYPE_VAX_FLOATING_POINT_P (type)))
4517         || (POINTER_TYPE_P (type) && ! TYPE_IS_THIN_POINTER_P (type))
4518         || (TREE_CODE (type) == RECORD_TYPE
4519             && TYPE_JUSTIFIED_MODULAR_P (type)))
4520        && ((INTEGRAL_TYPE_P (etype)
4521             && !(TREE_CODE (etype) == INTEGER_TYPE
4522                  && TYPE_VAX_FLOATING_POINT_P (etype)))
4523            || (POINTER_TYPE_P (etype) && !TYPE_IS_THIN_POINTER_P (etype))
4524            || (TREE_CODE (etype) == RECORD_TYPE
4525                && TYPE_JUSTIFIED_MODULAR_P (etype))))
4526       || TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE)
4527     {
4528       if (TREE_CODE (etype) == INTEGER_TYPE
4529           && TYPE_BIASED_REPRESENTATION_P (etype))
4530         {
4531           tree ntype = copy_type (etype);
4532           TYPE_BIASED_REPRESENTATION_P (ntype) = 0;
4533           TYPE_MAIN_VARIANT (ntype) = ntype;
4534           expr = build1 (NOP_EXPR, ntype, expr);
4535         }
4536
4537       if (TREE_CODE (type) == INTEGER_TYPE
4538           && TYPE_BIASED_REPRESENTATION_P (type))
4539         {
4540           tree rtype = copy_type (type);
4541           TYPE_BIASED_REPRESENTATION_P (rtype) = 0;
4542           TYPE_MAIN_VARIANT (rtype) = rtype;
4543           expr = convert (rtype, expr);
4544           expr = build1 (NOP_EXPR, type, expr);
4545         }
4546       else
4547         expr = convert (type, expr);
4548     }
4549
4550   /* If we are converting to an integral type whose precision is not equal
4551      to its size, first unchecked convert to a record that contains an
4552      object of the output type.  Then extract the field. */
4553   else if (INTEGRAL_TYPE_P (type) && TYPE_RM_SIZE (type)
4554            && 0 != compare_tree_int (TYPE_RM_SIZE (type),
4555                                      GET_MODE_BITSIZE (TYPE_MODE (type))))
4556     {
4557       tree rec_type = make_node (RECORD_TYPE);
4558       tree field = create_field_decl (get_identifier ("OBJ"), type,
4559                                       rec_type, 1, 0, 0, 0);
4560
4561       TYPE_FIELDS (rec_type) = field;
4562       layout_type (rec_type);
4563
4564       expr = unchecked_convert (rec_type, expr, notrunc_p);
4565       expr = build_component_ref (expr, NULL_TREE, field, 0);
4566     }
4567
4568   /* Similarly if we are converting from an integral type whose precision
4569      is not equal to its size.  */
4570   else if (INTEGRAL_TYPE_P (etype) && TYPE_RM_SIZE (etype)
4571       && 0 != compare_tree_int (TYPE_RM_SIZE (etype),
4572                                 GET_MODE_BITSIZE (TYPE_MODE (etype))))
4573     {
4574       tree rec_type = make_node (RECORD_TYPE);
4575       tree field
4576         = create_field_decl (get_identifier ("OBJ"), etype, rec_type,
4577                              1, 0, 0, 0);
4578
4579       TYPE_FIELDS (rec_type) = field;
4580       layout_type (rec_type);
4581
4582       expr = gnat_build_constructor (rec_type, build_tree_list (field, expr));
4583       expr = unchecked_convert (type, expr, notrunc_p);
4584     }
4585
4586   /* We have a special case when we are converting between two unconstrained
4587      array types.  In that case, take the address, convert the fat pointer
4588      types, and dereference.  */
4589   else if (TREE_CODE (etype) == UNCONSTRAINED_ARRAY_TYPE
4590            && TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE)
4591     expr = build_unary_op (INDIRECT_REF, NULL_TREE,
4592                            build1 (VIEW_CONVERT_EXPR, TREE_TYPE (type),
4593                                    build_unary_op (ADDR_EXPR, NULL_TREE,
4594                                                    expr)));
4595
4596   /* Another special case is when we are converting to a vector type from its
4597      representative array type; this a regular conversion.  */
4598   else if (TREE_CODE (type) == VECTOR_TYPE
4599            && TREE_CODE (etype) == ARRAY_TYPE
4600            && gnat_types_compatible_p (TYPE_REPRESENTATIVE_ARRAY (type),
4601                                        etype))
4602     expr = convert (type, expr);
4603
4604   else
4605     {
4606       expr = maybe_unconstrained_array (expr);
4607       etype = TREE_TYPE (expr);
4608       if (can_fold_for_view_convert_p (expr))
4609         expr = fold_build1 (VIEW_CONVERT_EXPR, type, expr);
4610       else
4611         expr = build1 (VIEW_CONVERT_EXPR, type, expr);
4612     }
4613
4614   /* If the result is an integral type whose precision is not equal to its
4615      size, sign- or zero-extend the result.  We need not do this if the input
4616      is an integral type of the same precision and signedness or if the output
4617      is a biased type or if both the input and output are unsigned.  */
4618   if (!notrunc_p
4619       && INTEGRAL_TYPE_P (type) && TYPE_RM_SIZE (type)
4620       && !(TREE_CODE (type) == INTEGER_TYPE
4621            && TYPE_BIASED_REPRESENTATION_P (type))
4622       && 0 != compare_tree_int (TYPE_RM_SIZE (type),
4623                                 GET_MODE_BITSIZE (TYPE_MODE (type)))
4624       && !(INTEGRAL_TYPE_P (etype)
4625            && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (etype)
4626            && operand_equal_p (TYPE_RM_SIZE (type),
4627                                (TYPE_RM_SIZE (etype) != 0
4628                                 ? TYPE_RM_SIZE (etype) : TYPE_SIZE (etype)),
4629                                0))
4630       && !(TYPE_UNSIGNED (type) && TYPE_UNSIGNED (etype)))
4631     {
4632       tree base_type = gnat_type_for_mode (TYPE_MODE (type),
4633                                            TYPE_UNSIGNED (type));
4634       tree shift_expr
4635         = convert (base_type,
4636                    size_binop (MINUS_EXPR,
4637                                bitsize_int
4638                                (GET_MODE_BITSIZE (TYPE_MODE (type))),
4639                                TYPE_RM_SIZE (type)));
4640       expr
4641         = convert (type,
4642                    build_binary_op (RSHIFT_EXPR, base_type,
4643                                     build_binary_op (LSHIFT_EXPR, base_type,
4644                                                      convert (base_type, expr),
4645                                                      shift_expr),
4646                                     shift_expr));
4647     }
4648
4649   /* An unchecked conversion should never raise Constraint_Error.  The code
4650      below assumes that GCC's conversion routines overflow the same way that
4651      the underlying hardware does.  This is probably true.  In the rare case
4652      when it is false, we can rely on the fact that such conversions are
4653      erroneous anyway.  */
4654   if (TREE_CODE (expr) == INTEGER_CST)
4655     TREE_OVERFLOW (expr) = 0;
4656
4657   /* If the sizes of the types differ and this is an VIEW_CONVERT_EXPR,
4658      show no longer constant.  */
4659   if (TREE_CODE (expr) == VIEW_CONVERT_EXPR
4660       && !operand_equal_p (TYPE_SIZE_UNIT (type), TYPE_SIZE_UNIT (etype),
4661                            OEP_ONLY_CONST))
4662     TREE_CONSTANT (expr) = 0;
4663
4664   return expr;
4665 }
4666 \f
4667 /* Return the appropriate GCC tree code for the specified GNAT_TYPE,
4668    the latter being a record type as predicated by Is_Record_Type.  */
4669
4670 enum tree_code
4671 tree_code_for_record_type (Entity_Id gnat_type)
4672 {
4673   Node_Id component_list
4674     = Component_List (Type_Definition
4675                       (Declaration_Node
4676                        (Implementation_Base_Type (gnat_type))));
4677   Node_Id component;
4678
4679  /* Make this a UNION_TYPE unless it's either not an Unchecked_Union or
4680     we have a non-discriminant field outside a variant.  In either case,
4681     it's a RECORD_TYPE.  */
4682
4683   if (!Is_Unchecked_Union (gnat_type))
4684     return RECORD_TYPE;
4685
4686   for (component = First_Non_Pragma (Component_Items (component_list));
4687        Present (component);
4688        component = Next_Non_Pragma (component))
4689     if (Ekind (Defining_Entity (component)) == E_Component)
4690       return RECORD_TYPE;
4691
4692   return UNION_TYPE;
4693 }
4694
4695 /* Return true if GNAT_TYPE is a "double" floating-point type, i.e. whose
4696    size is equal to 64 bits, or an array of such a type.  Set ALIGN_CLAUSE
4697    according to the presence of an alignment clause on the type or, if it
4698    is an array, on the component type.  */
4699
4700 bool
4701 is_double_float_or_array (Entity_Id gnat_type, bool *align_clause)
4702 {
4703   gnat_type = Underlying_Type (gnat_type);
4704
4705   *align_clause = Present (Alignment_Clause (gnat_type));
4706
4707   if (Is_Array_Type (gnat_type))
4708     {
4709       gnat_type = Underlying_Type (Component_Type (gnat_type));
4710       if (Present (Alignment_Clause (gnat_type)))
4711         *align_clause = true;
4712     }
4713
4714   if (!Is_Floating_Point_Type (gnat_type))
4715     return false;
4716
4717   if (UI_To_Int (Esize (gnat_type)) != 64)
4718     return false;
4719
4720   return true;
4721 }
4722
4723 /* Return true if GNAT_TYPE is a "double" or larger scalar type, i.e. whose
4724    size is greater or equal to 64 bits, or an array of such a type.  Set
4725    ALIGN_CLAUSE according to the presence of an alignment clause on the
4726    type or, if it is an array, on the component type.  */
4727
4728 bool
4729 is_double_scalar_or_array (Entity_Id gnat_type, bool *align_clause)
4730 {
4731   gnat_type = Underlying_Type (gnat_type);
4732
4733   *align_clause = Present (Alignment_Clause (gnat_type));
4734
4735   if (Is_Array_Type (gnat_type))
4736     {
4737       gnat_type = Underlying_Type (Component_Type (gnat_type));
4738       if (Present (Alignment_Clause (gnat_type)))
4739         *align_clause = true;
4740     }
4741
4742   if (!Is_Scalar_Type (gnat_type))
4743     return false;
4744
4745   if (UI_To_Int (Esize (gnat_type)) < 64)
4746     return false;
4747
4748   return true;
4749 }
4750
4751 /* Return true if GNU_TYPE is suitable as the type of a non-aliased
4752    component of an aggregate type.  */
4753
4754 bool
4755 type_for_nonaliased_component_p (tree gnu_type)
4756 {
4757   /* If the type is passed by reference, we may have pointers to the
4758      component so it cannot be made non-aliased. */
4759   if (must_pass_by_ref (gnu_type) || default_pass_by_ref (gnu_type))
4760     return false;
4761
4762   /* We used to say that any component of aggregate type is aliased
4763      because the front-end may take 'Reference of it.  The front-end
4764      has been enhanced in the meantime so as to use a renaming instead
4765      in most cases, but the back-end can probably take the address of
4766      such a component too so we go for the conservative stance.
4767
4768      For instance, we might need the address of any array type, even
4769      if normally passed by copy, to construct a fat pointer if the
4770      component is used as an actual for an unconstrained formal.
4771
4772      Likewise for record types: even if a specific record subtype is
4773      passed by copy, the parent type might be passed by ref (e.g. if
4774      it's of variable size) and we might take the address of a child
4775      component to pass to a parent formal.  We have no way to check
4776      for such conditions here.  */
4777   if (AGGREGATE_TYPE_P (gnu_type))
4778     return false;
4779
4780   return true;
4781 }
4782
4783 /* Perform final processing on global variables.  */
4784
4785 void
4786 gnat_write_global_declarations (void)
4787 {
4788   /* Proceed to optimize and emit assembly.
4789      FIXME: shouldn't be the front end's responsibility to call this.  */
4790   cgraph_finalize_compilation_unit ();
4791
4792   /* Emit debug info for all global declarations.  */
4793   emit_debug_global_declarations (VEC_address (tree, global_decls),
4794                                   VEC_length (tree, global_decls));
4795 }
4796
4797 /* ************************************************************************
4798  * *                           GCC builtins support                       *
4799  * ************************************************************************ */
4800
4801 /* The general scheme is fairly simple:
4802
4803    For each builtin function/type to be declared, gnat_install_builtins calls
4804    internal facilities which eventually get to gnat_push_decl, which in turn
4805    tracks the so declared builtin function decls in the 'builtin_decls' global
4806    datastructure. When an Intrinsic subprogram declaration is processed, we
4807    search this global datastructure to retrieve the associated BUILT_IN DECL
4808    node.  */
4809
4810 /* Search the chain of currently available builtin declarations for a node
4811    corresponding to function NAME (an IDENTIFIER_NODE).  Return the first node
4812    found, if any, or NULL_TREE otherwise.  */
4813 tree
4814 builtin_decl_for (tree name)
4815 {
4816   unsigned i;
4817   tree decl;
4818
4819   for (i = 0; VEC_iterate(tree, builtin_decls, i, decl); i++)
4820     if (DECL_NAME (decl) == name)
4821       return decl;
4822
4823   return NULL_TREE;
4824 }
4825
4826 /* The code below eventually exposes gnat_install_builtins, which declares
4827    the builtin types and functions we might need, either internally or as
4828    user accessible facilities.
4829
4830    ??? This is a first implementation shot, still in rough shape.  It is
4831    heavily inspired from the "C" family implementation, with chunks copied
4832    verbatim from there.
4833
4834    Two obvious TODO candidates are
4835    o Use a more efficient name/decl mapping scheme
4836    o Devise a middle-end infrastructure to avoid having to copy
4837      pieces between front-ends.  */
4838
4839 /* ----------------------------------------------------------------------- *
4840  *                         BUILTIN ELEMENTARY TYPES                        *
4841  * ----------------------------------------------------------------------- */
4842
4843 /* Standard data types to be used in builtin argument declarations.  */
4844
4845 enum c_tree_index
4846 {
4847     CTI_SIGNED_SIZE_TYPE, /* For format checking only.  */
4848     CTI_STRING_TYPE,
4849     CTI_CONST_STRING_TYPE,
4850
4851     CTI_MAX
4852 };
4853
4854 static tree c_global_trees[CTI_MAX];
4855
4856 #define signed_size_type_node   c_global_trees[CTI_SIGNED_SIZE_TYPE]
4857 #define string_type_node        c_global_trees[CTI_STRING_TYPE]
4858 #define const_string_type_node  c_global_trees[CTI_CONST_STRING_TYPE]
4859
4860 /* ??? In addition some attribute handlers, we currently don't support a
4861    (small) number of builtin-types, which in turns inhibits support for a
4862    number of builtin functions.  */
4863 #define wint_type_node    void_type_node
4864 #define intmax_type_node  void_type_node
4865 #define uintmax_type_node void_type_node
4866
4867 /* Build the void_list_node (void_type_node having been created).  */
4868
4869 static tree
4870 build_void_list_node (void)
4871 {
4872   tree t = build_tree_list (NULL_TREE, void_type_node);
4873   return t;
4874 }
4875
4876 /* Used to help initialize the builtin-types.def table.  When a type of
4877    the correct size doesn't exist, use error_mark_node instead of NULL.
4878    The later results in segfaults even when a decl using the type doesn't
4879    get invoked.  */
4880
4881 static tree
4882 builtin_type_for_size (int size, bool unsignedp)
4883 {
4884   tree type = lang_hooks.types.type_for_size (size, unsignedp);
4885   return type ? type : error_mark_node;
4886 }
4887
4888 /* Build/push the elementary type decls that builtin functions/types
4889    will need.  */
4890
4891 static void
4892 install_builtin_elementary_types (void)
4893 {
4894   signed_size_type_node = size_type_node;
4895   pid_type_node = integer_type_node;
4896   void_list_node = build_void_list_node ();
4897
4898   string_type_node = build_pointer_type (char_type_node);
4899   const_string_type_node
4900     = build_pointer_type (build_qualified_type
4901                           (char_type_node, TYPE_QUAL_CONST));
4902 }
4903
4904 /* ----------------------------------------------------------------------- *
4905  *                          BUILTIN FUNCTION TYPES                         *
4906  * ----------------------------------------------------------------------- */
4907
4908 /* Now, builtin function types per se.  */
4909
4910 enum c_builtin_type
4911 {
4912 #define DEF_PRIMITIVE_TYPE(NAME, VALUE) NAME,
4913 #define DEF_FUNCTION_TYPE_0(NAME, RETURN) NAME,
4914 #define DEF_FUNCTION_TYPE_1(NAME, RETURN, ARG1) NAME,
4915 #define DEF_FUNCTION_TYPE_2(NAME, RETURN, ARG1, ARG2) NAME,
4916 #define DEF_FUNCTION_TYPE_3(NAME, RETURN, ARG1, ARG2, ARG3) NAME,
4917 #define DEF_FUNCTION_TYPE_4(NAME, RETURN, ARG1, ARG2, ARG3, ARG4) NAME,
4918 #define DEF_FUNCTION_TYPE_5(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) NAME,
4919 #define DEF_FUNCTION_TYPE_6(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6) NAME,
4920 #define DEF_FUNCTION_TYPE_7(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7) NAME,
4921 #define DEF_FUNCTION_TYPE_VAR_0(NAME, RETURN) NAME,
4922 #define DEF_FUNCTION_TYPE_VAR_1(NAME, RETURN, ARG1) NAME,
4923 #define DEF_FUNCTION_TYPE_VAR_2(NAME, RETURN, ARG1, ARG2) NAME,
4924 #define DEF_FUNCTION_TYPE_VAR_3(NAME, RETURN, ARG1, ARG2, ARG3) NAME,
4925 #define DEF_FUNCTION_TYPE_VAR_4(NAME, RETURN, ARG1, ARG2, ARG3, ARG4) NAME,
4926 #define DEF_FUNCTION_TYPE_VAR_5(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG6) \
4927   NAME,
4928 #define DEF_POINTER_TYPE(NAME, TYPE) NAME,
4929 #include "builtin-types.def"
4930 #undef DEF_PRIMITIVE_TYPE
4931 #undef DEF_FUNCTION_TYPE_0
4932 #undef DEF_FUNCTION_TYPE_1
4933 #undef DEF_FUNCTION_TYPE_2
4934 #undef DEF_FUNCTION_TYPE_3
4935 #undef DEF_FUNCTION_TYPE_4
4936 #undef DEF_FUNCTION_TYPE_5
4937 #undef DEF_FUNCTION_TYPE_6
4938 #undef DEF_FUNCTION_TYPE_7
4939 #undef DEF_FUNCTION_TYPE_VAR_0
4940 #undef DEF_FUNCTION_TYPE_VAR_1
4941 #undef DEF_FUNCTION_TYPE_VAR_2
4942 #undef DEF_FUNCTION_TYPE_VAR_3
4943 #undef DEF_FUNCTION_TYPE_VAR_4
4944 #undef DEF_FUNCTION_TYPE_VAR_5
4945 #undef DEF_POINTER_TYPE
4946   BT_LAST
4947 };
4948
4949 typedef enum c_builtin_type builtin_type;
4950
4951 /* A temporary array used in communication with def_fn_type.  */
4952 static GTY(()) tree builtin_types[(int) BT_LAST + 1];
4953
4954 /* A helper function for install_builtin_types.  Build function type
4955    for DEF with return type RET and N arguments.  If VAR is true, then the
4956    function should be variadic after those N arguments.
4957
4958    Takes special care not to ICE if any of the types involved are
4959    error_mark_node, which indicates that said type is not in fact available
4960    (see builtin_type_for_size).  In which case the function type as a whole
4961    should be error_mark_node.  */
4962
4963 static void
4964 def_fn_type (builtin_type def, builtin_type ret, bool var, int n, ...)
4965 {
4966   tree args = NULL, t;
4967   va_list list;
4968   int i;
4969
4970   va_start (list, n);
4971   for (i = 0; i < n; ++i)
4972     {
4973       builtin_type a = (builtin_type) va_arg (list, int);
4974       t = builtin_types[a];
4975       if (t == error_mark_node)
4976         goto egress;
4977       args = tree_cons (NULL_TREE, t, args);
4978     }
4979   va_end (list);
4980
4981   args = nreverse (args);
4982   if (!var)
4983     args = chainon (args, void_list_node);
4984
4985   t = builtin_types[ret];
4986   if (t == error_mark_node)
4987     goto egress;
4988   t = build_function_type (t, args);
4989
4990  egress:
4991   builtin_types[def] = t;
4992 }
4993
4994 /* Build the builtin function types and install them in the builtin_types
4995    array for later use in builtin function decls.  */
4996
4997 static void
4998 install_builtin_function_types (void)
4999 {
5000   tree va_list_ref_type_node;
5001   tree va_list_arg_type_node;
5002
5003   if (TREE_CODE (va_list_type_node) == ARRAY_TYPE)
5004     {
5005       va_list_arg_type_node = va_list_ref_type_node =
5006         build_pointer_type (TREE_TYPE (va_list_type_node));
5007     }
5008   else
5009     {
5010       va_list_arg_type_node = va_list_type_node;
5011       va_list_ref_type_node = build_reference_type (va_list_type_node);
5012     }
5013
5014 #define DEF_PRIMITIVE_TYPE(ENUM, VALUE) \
5015   builtin_types[ENUM] = VALUE;
5016 #define DEF_FUNCTION_TYPE_0(ENUM, RETURN) \
5017   def_fn_type (ENUM, RETURN, 0, 0);
5018 #define DEF_FUNCTION_TYPE_1(ENUM, RETURN, ARG1) \
5019   def_fn_type (ENUM, RETURN, 0, 1, ARG1);
5020 #define DEF_FUNCTION_TYPE_2(ENUM, RETURN, ARG1, ARG2) \
5021   def_fn_type (ENUM, RETURN, 0, 2, ARG1, ARG2);
5022 #define DEF_FUNCTION_TYPE_3(ENUM, RETURN, ARG1, ARG2, ARG3) \
5023   def_fn_type (ENUM, RETURN, 0, 3, ARG1, ARG2, ARG3);
5024 #define DEF_FUNCTION_TYPE_4(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4) \
5025   def_fn_type (ENUM, RETURN, 0, 4, ARG1, ARG2, ARG3, ARG4);
5026 #define DEF_FUNCTION_TYPE_5(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
5027   def_fn_type (ENUM, RETURN, 0, 5, ARG1, ARG2, ARG3, ARG4, ARG5);
5028 #define DEF_FUNCTION_TYPE_6(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
5029                             ARG6)                                       \
5030   def_fn_type (ENUM, RETURN, 0, 6, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6);
5031 #define DEF_FUNCTION_TYPE_7(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
5032                             ARG6, ARG7)                                 \
5033   def_fn_type (ENUM, RETURN, 0, 7, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7);
5034 #define DEF_FUNCTION_TYPE_VAR_0(ENUM, RETURN) \
5035   def_fn_type (ENUM, RETURN, 1, 0);
5036 #define DEF_FUNCTION_TYPE_VAR_1(ENUM, RETURN, ARG1) \
5037   def_fn_type (ENUM, RETURN, 1, 1, ARG1);
5038 #define DEF_FUNCTION_TYPE_VAR_2(ENUM, RETURN, ARG1, ARG2) \
5039   def_fn_type (ENUM, RETURN, 1, 2, ARG1, ARG2);
5040 #define DEF_FUNCTION_TYPE_VAR_3(ENUM, RETURN, ARG1, ARG2, ARG3) \
5041   def_fn_type (ENUM, RETURN, 1, 3, ARG1, ARG2, ARG3);
5042 #define DEF_FUNCTION_TYPE_VAR_4(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4) \
5043   def_fn_type (ENUM, RETURN, 1, 4, ARG1, ARG2, ARG3, ARG4);
5044 #define DEF_FUNCTION_TYPE_VAR_5(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
5045   def_fn_type (ENUM, RETURN, 1, 5, ARG1, ARG2, ARG3, ARG4, ARG5);
5046 #define DEF_POINTER_TYPE(ENUM, TYPE) \
5047   builtin_types[(int) ENUM] = build_pointer_type (builtin_types[(int) TYPE]);
5048
5049 #include "builtin-types.def"
5050
5051 #undef DEF_PRIMITIVE_TYPE
5052 #undef DEF_FUNCTION_TYPE_1
5053 #undef DEF_FUNCTION_TYPE_2
5054 #undef DEF_FUNCTION_TYPE_3
5055 #undef DEF_FUNCTION_TYPE_4
5056 #undef DEF_FUNCTION_TYPE_5
5057 #undef DEF_FUNCTION_TYPE_6
5058 #undef DEF_FUNCTION_TYPE_VAR_0
5059 #undef DEF_FUNCTION_TYPE_VAR_1
5060 #undef DEF_FUNCTION_TYPE_VAR_2
5061 #undef DEF_FUNCTION_TYPE_VAR_3
5062 #undef DEF_FUNCTION_TYPE_VAR_4
5063 #undef DEF_FUNCTION_TYPE_VAR_5
5064 #undef DEF_POINTER_TYPE
5065   builtin_types[(int) BT_LAST] = NULL_TREE;
5066 }
5067
5068 /* ----------------------------------------------------------------------- *
5069  *                            BUILTIN ATTRIBUTES                           *
5070  * ----------------------------------------------------------------------- */
5071
5072 enum built_in_attribute
5073 {
5074 #define DEF_ATTR_NULL_TREE(ENUM) ENUM,
5075 #define DEF_ATTR_INT(ENUM, VALUE) ENUM,
5076 #define DEF_ATTR_IDENT(ENUM, STRING) ENUM,
5077 #define DEF_ATTR_TREE_LIST(ENUM, PURPOSE, VALUE, CHAIN) ENUM,
5078 #include "builtin-attrs.def"
5079 #undef DEF_ATTR_NULL_TREE
5080 #undef DEF_ATTR_INT
5081 #undef DEF_ATTR_IDENT
5082 #undef DEF_ATTR_TREE_LIST
5083   ATTR_LAST
5084 };
5085
5086 static GTY(()) tree built_in_attributes[(int) ATTR_LAST];
5087
5088 static void
5089 install_builtin_attributes (void)
5090 {
5091   /* Fill in the built_in_attributes array.  */
5092 #define DEF_ATTR_NULL_TREE(ENUM)                                \
5093   built_in_attributes[(int) ENUM] = NULL_TREE;
5094 #define DEF_ATTR_INT(ENUM, VALUE)                               \
5095   built_in_attributes[(int) ENUM] = build_int_cst (NULL_TREE, VALUE);
5096 #define DEF_ATTR_IDENT(ENUM, STRING)                            \
5097   built_in_attributes[(int) ENUM] = get_identifier (STRING);
5098 #define DEF_ATTR_TREE_LIST(ENUM, PURPOSE, VALUE, CHAIN) \
5099   built_in_attributes[(int) ENUM]                       \
5100     = tree_cons (built_in_attributes[(int) PURPOSE],    \
5101                  built_in_attributes[(int) VALUE],      \
5102                  built_in_attributes[(int) CHAIN]);
5103 #include "builtin-attrs.def"
5104 #undef DEF_ATTR_NULL_TREE
5105 #undef DEF_ATTR_INT
5106 #undef DEF_ATTR_IDENT
5107 #undef DEF_ATTR_TREE_LIST
5108 }
5109
5110 /* Handle a "const" attribute; arguments as in
5111    struct attribute_spec.handler.  */
5112
5113 static tree
5114 handle_const_attribute (tree *node, tree ARG_UNUSED (name),
5115                         tree ARG_UNUSED (args), int ARG_UNUSED (flags),
5116                         bool *no_add_attrs)
5117 {
5118   if (TREE_CODE (*node) == FUNCTION_DECL)
5119     TREE_READONLY (*node) = 1;
5120   else
5121     *no_add_attrs = true;
5122
5123   return NULL_TREE;
5124 }
5125
5126 /* Handle a "nothrow" attribute; arguments as in
5127    struct attribute_spec.handler.  */
5128
5129 static tree
5130 handle_nothrow_attribute (tree *node, tree ARG_UNUSED (name),
5131                           tree ARG_UNUSED (args), int ARG_UNUSED (flags),
5132                           bool *no_add_attrs)
5133 {
5134   if (TREE_CODE (*node) == FUNCTION_DECL)
5135     TREE_NOTHROW (*node) = 1;
5136   else
5137     *no_add_attrs = true;
5138
5139   return NULL_TREE;
5140 }
5141
5142 /* Handle a "pure" attribute; arguments as in
5143    struct attribute_spec.handler.  */
5144
5145 static tree
5146 handle_pure_attribute (tree *node, tree name, tree ARG_UNUSED (args),
5147                        int ARG_UNUSED (flags), bool *no_add_attrs)
5148 {
5149   if (TREE_CODE (*node) == FUNCTION_DECL)
5150     DECL_PURE_P (*node) = 1;
5151   /* ??? TODO: Support types.  */
5152   else
5153     {
5154       warning (OPT_Wattributes, "%qs attribute ignored",
5155                IDENTIFIER_POINTER (name));
5156       *no_add_attrs = true;
5157     }
5158
5159   return NULL_TREE;
5160 }
5161
5162 /* Handle a "no vops" attribute; arguments as in
5163    struct attribute_spec.handler.  */
5164
5165 static tree
5166 handle_novops_attribute (tree *node, tree ARG_UNUSED (name),
5167                          tree ARG_UNUSED (args), int ARG_UNUSED (flags),
5168                          bool *ARG_UNUSED (no_add_attrs))
5169 {
5170   gcc_assert (TREE_CODE (*node) == FUNCTION_DECL);
5171   DECL_IS_NOVOPS (*node) = 1;
5172   return NULL_TREE;
5173 }
5174
5175 /* Helper for nonnull attribute handling; fetch the operand number
5176    from the attribute argument list.  */
5177
5178 static bool
5179 get_nonnull_operand (tree arg_num_expr, unsigned HOST_WIDE_INT *valp)
5180 {
5181   /* Verify the arg number is a constant.  */
5182   if (TREE_CODE (arg_num_expr) != INTEGER_CST
5183       || TREE_INT_CST_HIGH (arg_num_expr) != 0)
5184     return false;
5185
5186   *valp = TREE_INT_CST_LOW (arg_num_expr);
5187   return true;
5188 }
5189
5190 /* Handle the "nonnull" attribute.  */
5191 static tree
5192 handle_nonnull_attribute (tree *node, tree ARG_UNUSED (name),
5193                           tree args, int ARG_UNUSED (flags),
5194                           bool *no_add_attrs)
5195 {
5196   tree type = *node;
5197   unsigned HOST_WIDE_INT attr_arg_num;
5198
5199   /* If no arguments are specified, all pointer arguments should be
5200      non-null.  Verify a full prototype is given so that the arguments
5201      will have the correct types when we actually check them later.  */
5202   if (!args)
5203     {
5204       if (!TYPE_ARG_TYPES (type))
5205         {
5206           error ("nonnull attribute without arguments on a non-prototype");
5207           *no_add_attrs = true;
5208         }
5209       return NULL_TREE;
5210     }
5211
5212   /* Argument list specified.  Verify that each argument number references
5213      a pointer argument.  */
5214   for (attr_arg_num = 1; args; args = TREE_CHAIN (args))
5215     {
5216       tree argument;
5217       unsigned HOST_WIDE_INT arg_num = 0, ck_num;
5218
5219       if (!get_nonnull_operand (TREE_VALUE (args), &arg_num))
5220         {
5221           error ("nonnull argument has invalid operand number (argument %lu)",
5222                  (unsigned long) attr_arg_num);
5223           *no_add_attrs = true;
5224           return NULL_TREE;
5225         }
5226
5227       argument = TYPE_ARG_TYPES (type);
5228       if (argument)
5229         {
5230           for (ck_num = 1; ; ck_num++)
5231             {
5232               if (!argument || ck_num == arg_num)
5233                 break;
5234               argument = TREE_CHAIN (argument);
5235             }
5236
5237           if (!argument
5238               || TREE_CODE (TREE_VALUE (argument)) == VOID_TYPE)
5239             {
5240               error ("nonnull argument with out-of-range operand number (argument %lu, operand %lu)",
5241                      (unsigned long) attr_arg_num, (unsigned long) arg_num);
5242               *no_add_attrs = true;
5243               return NULL_TREE;
5244             }
5245
5246           if (TREE_CODE (TREE_VALUE (argument)) != POINTER_TYPE)
5247             {
5248               error ("nonnull argument references non-pointer operand (argument %lu, operand %lu)",
5249                    (unsigned long) attr_arg_num, (unsigned long) arg_num);
5250               *no_add_attrs = true;
5251               return NULL_TREE;
5252             }
5253         }
5254     }
5255
5256   return NULL_TREE;
5257 }
5258
5259 /* Handle a "sentinel" attribute.  */
5260
5261 static tree
5262 handle_sentinel_attribute (tree *node, tree name, tree args,
5263                            int ARG_UNUSED (flags), bool *no_add_attrs)
5264 {
5265   tree params = TYPE_ARG_TYPES (*node);
5266
5267   if (!params)
5268     {
5269       warning (OPT_Wattributes,
5270                "%qs attribute requires prototypes with named arguments",
5271                IDENTIFIER_POINTER (name));
5272       *no_add_attrs = true;
5273     }
5274   else
5275     {
5276       while (TREE_CHAIN (params))
5277         params = TREE_CHAIN (params);
5278
5279       if (VOID_TYPE_P (TREE_VALUE (params)))
5280         {
5281           warning (OPT_Wattributes,
5282                    "%qs attribute only applies to variadic functions",
5283                    IDENTIFIER_POINTER (name));
5284           *no_add_attrs = true;
5285         }
5286     }
5287
5288   if (args)
5289     {
5290       tree position = TREE_VALUE (args);
5291
5292       if (TREE_CODE (position) != INTEGER_CST)
5293         {
5294           warning (0, "requested position is not an integer constant");
5295           *no_add_attrs = true;
5296         }
5297       else
5298         {
5299           if (tree_int_cst_lt (position, integer_zero_node))
5300             {
5301               warning (0, "requested position is less than zero");
5302               *no_add_attrs = true;
5303             }
5304         }
5305     }
5306
5307   return NULL_TREE;
5308 }
5309
5310 /* Handle a "noreturn" attribute; arguments as in
5311    struct attribute_spec.handler.  */
5312
5313 static tree
5314 handle_noreturn_attribute (tree *node, tree name, tree ARG_UNUSED (args),
5315                            int ARG_UNUSED (flags), bool *no_add_attrs)
5316 {
5317   tree type = TREE_TYPE (*node);
5318
5319   /* See FIXME comment in c_common_attribute_table.  */
5320   if (TREE_CODE (*node) == FUNCTION_DECL)
5321     TREE_THIS_VOLATILE (*node) = 1;
5322   else if (TREE_CODE (type) == POINTER_TYPE
5323            && TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE)
5324     TREE_TYPE (*node)
5325       = build_pointer_type
5326         (build_type_variant (TREE_TYPE (type),
5327                              TYPE_READONLY (TREE_TYPE (type)), 1));
5328   else
5329     {
5330       warning (OPT_Wattributes, "%qs attribute ignored",
5331                IDENTIFIER_POINTER (name));
5332       *no_add_attrs = true;
5333     }
5334
5335   return NULL_TREE;
5336 }
5337
5338 /* Handle a "malloc" attribute; arguments as in
5339    struct attribute_spec.handler.  */
5340
5341 static tree
5342 handle_malloc_attribute (tree *node, tree name, tree ARG_UNUSED (args),
5343                          int ARG_UNUSED (flags), bool *no_add_attrs)
5344 {
5345   if (TREE_CODE (*node) == FUNCTION_DECL
5346       && POINTER_TYPE_P (TREE_TYPE (TREE_TYPE (*node))))
5347     DECL_IS_MALLOC (*node) = 1;
5348   else
5349     {
5350       warning (OPT_Wattributes, "%qs attribute ignored",
5351                IDENTIFIER_POINTER (name));
5352       *no_add_attrs = true;
5353     }
5354
5355   return NULL_TREE;
5356 }
5357
5358 /* Fake handler for attributes we don't properly support.  */
5359
5360 tree
5361 fake_attribute_handler (tree * ARG_UNUSED (node),
5362                         tree ARG_UNUSED (name),
5363                         tree ARG_UNUSED (args),
5364                         int  ARG_UNUSED (flags),
5365                         bool * ARG_UNUSED (no_add_attrs))
5366 {
5367   return NULL_TREE;
5368 }
5369
5370 /* Handle a "type_generic" attribute.  */
5371
5372 static tree
5373 handle_type_generic_attribute (tree *node, tree ARG_UNUSED (name),
5374                                tree ARG_UNUSED (args), int ARG_UNUSED (flags),
5375                                bool * ARG_UNUSED (no_add_attrs))
5376 {
5377   tree params;
5378
5379   /* Ensure we have a function type.  */
5380   gcc_assert (TREE_CODE (*node) == FUNCTION_TYPE);
5381
5382   params = TYPE_ARG_TYPES (*node);
5383   while (params && ! VOID_TYPE_P (TREE_VALUE (params)))
5384     params = TREE_CHAIN (params);
5385
5386   /* Ensure we have a variadic function.  */
5387   gcc_assert (!params);
5388
5389   return NULL_TREE;
5390 }
5391
5392 /* Handle a "vector_size" attribute; arguments as in
5393    struct attribute_spec.handler.  */
5394
5395 static tree
5396 handle_vector_size_attribute (tree *node, tree name, tree args,
5397                               int ARG_UNUSED (flags),
5398                               bool *no_add_attrs)
5399 {
5400   unsigned HOST_WIDE_INT vecsize, nunits;
5401   enum machine_mode orig_mode;
5402   tree type = *node, new_type, size;
5403
5404   *no_add_attrs = true;
5405
5406   size = TREE_VALUE (args);
5407
5408   if (!host_integerp (size, 1))
5409     {
5410       warning (OPT_Wattributes, "%qs attribute ignored",
5411                IDENTIFIER_POINTER (name));
5412       return NULL_TREE;
5413     }
5414
5415   /* Get the vector size (in bytes).  */
5416   vecsize = tree_low_cst (size, 1);
5417
5418   /* We need to provide for vector pointers, vector arrays, and
5419      functions returning vectors.  For example:
5420
5421        __attribute__((vector_size(16))) short *foo;
5422
5423      In this case, the mode is SI, but the type being modified is
5424      HI, so we need to look further.  */
5425
5426   while (POINTER_TYPE_P (type)
5427          || TREE_CODE (type) == FUNCTION_TYPE
5428          || TREE_CODE (type) == METHOD_TYPE
5429          || TREE_CODE (type) == ARRAY_TYPE
5430          || TREE_CODE (type) == OFFSET_TYPE)
5431     type = TREE_TYPE (type);
5432
5433   /* Get the mode of the type being modified.  */
5434   orig_mode = TYPE_MODE (type);
5435
5436   if ((!INTEGRAL_TYPE_P (type)
5437        && !SCALAR_FLOAT_TYPE_P (type)
5438        && !FIXED_POINT_TYPE_P (type))
5439       || (!SCALAR_FLOAT_MODE_P (orig_mode)
5440           && GET_MODE_CLASS (orig_mode) != MODE_INT
5441           && !ALL_SCALAR_FIXED_POINT_MODE_P (orig_mode))
5442       || !host_integerp (TYPE_SIZE_UNIT (type), 1)
5443       || TREE_CODE (type) == BOOLEAN_TYPE)
5444     {
5445       error ("invalid vector type for attribute %qs",
5446              IDENTIFIER_POINTER (name));
5447       return NULL_TREE;
5448     }
5449
5450   if (vecsize % tree_low_cst (TYPE_SIZE_UNIT (type), 1))
5451     {
5452       error ("vector size not an integral multiple of component size");
5453       return NULL;
5454     }
5455
5456   if (vecsize == 0)
5457     {
5458       error ("zero vector size");
5459       return NULL;
5460     }
5461
5462   /* Calculate how many units fit in the vector.  */
5463   nunits = vecsize / tree_low_cst (TYPE_SIZE_UNIT (type), 1);
5464   if (nunits & (nunits - 1))
5465     {
5466       error ("number of components of the vector not a power of two");
5467       return NULL_TREE;
5468     }
5469
5470   new_type = build_vector_type (type, nunits);
5471
5472   /* Build back pointers if needed.  */
5473   *node = lang_hooks.types.reconstruct_complex_type (*node, new_type);
5474
5475   return NULL_TREE;
5476 }
5477
5478 /* Handle a "vector_type" attribute; arguments as in
5479    struct attribute_spec.handler.  */
5480
5481 static tree
5482 handle_vector_type_attribute (tree *node, tree name, tree ARG_UNUSED (args),
5483                               int ARG_UNUSED (flags),
5484                               bool *no_add_attrs)
5485 {
5486   /* Vector representative type and size.  */
5487   tree rep_type = *node;
5488   tree rep_size = TYPE_SIZE_UNIT (rep_type);
5489   tree rep_name;
5490
5491   /* Vector size in bytes and number of units.  */
5492   unsigned HOST_WIDE_INT vec_bytes, vec_units;
5493
5494   /* Vector element type and mode.  */
5495   tree elem_type;
5496   enum machine_mode elem_mode;
5497
5498   *no_add_attrs = true;
5499
5500   /* Get the representative array type, possibly nested within a
5501      padding record e.g. for alignment purposes.  */
5502
5503   if (TYPE_IS_PADDING_P (rep_type))
5504     rep_type = TREE_TYPE (TYPE_FIELDS (rep_type));
5505
5506   if (TREE_CODE (rep_type) != ARRAY_TYPE)
5507     {
5508       error ("attribute %qs applies to array types only",
5509              IDENTIFIER_POINTER (name));
5510       return NULL_TREE;
5511     }
5512
5513   /* Silently punt on variable sizes.  We can't make vector types for them,
5514      need to ignore them on front-end generated subtypes of unconstrained
5515      bases, and this attribute is for binding implementors, not end-users, so
5516      we should never get there from legitimate explicit uses.  */
5517
5518   if (!host_integerp (rep_size, 1))
5519     return NULL_TREE;
5520
5521   /* Get the element type/mode and check this is something we know
5522      how to make vectors of.  */
5523
5524   elem_type = TREE_TYPE (rep_type);
5525   elem_mode = TYPE_MODE (elem_type);
5526
5527   if ((!INTEGRAL_TYPE_P (elem_type)
5528        && !SCALAR_FLOAT_TYPE_P (elem_type)
5529        && !FIXED_POINT_TYPE_P (elem_type))
5530       || (!SCALAR_FLOAT_MODE_P (elem_mode)
5531           && GET_MODE_CLASS (elem_mode) != MODE_INT
5532           && !ALL_SCALAR_FIXED_POINT_MODE_P (elem_mode))
5533       || !host_integerp (TYPE_SIZE_UNIT (elem_type), 1))
5534     {
5535       error ("invalid element type for attribute %qs",
5536              IDENTIFIER_POINTER (name));
5537       return NULL_TREE;
5538     }
5539
5540   /* Sanity check the vector size and element type consistency.  */
5541
5542   vec_bytes = tree_low_cst (rep_size, 1);
5543
5544   if (vec_bytes % tree_low_cst (TYPE_SIZE_UNIT (elem_type), 1))
5545     {
5546       error ("vector size not an integral multiple of component size");
5547       return NULL;
5548     }
5549
5550   if (vec_bytes == 0)
5551     {
5552       error ("zero vector size");
5553       return NULL;
5554     }
5555
5556   vec_units = vec_bytes / tree_low_cst (TYPE_SIZE_UNIT (elem_type), 1);
5557   if (vec_units & (vec_units - 1))
5558     {
5559       error ("number of components of the vector not a power of two");
5560       return NULL_TREE;
5561     }
5562
5563   /* Build the vector type and replace.  */
5564
5565   *node = build_vector_type (elem_type, vec_units);
5566   rep_name = TYPE_NAME (rep_type);
5567   if (TREE_CODE (rep_name) == TYPE_DECL)
5568     rep_name = DECL_NAME (rep_name);
5569   TYPE_NAME (*node) = rep_name;
5570   TYPE_REPRESENTATIVE_ARRAY (*node) = rep_type;
5571
5572   return NULL_TREE;
5573 }
5574
5575 /* ----------------------------------------------------------------------- *
5576  *                              BUILTIN FUNCTIONS                          *
5577  * ----------------------------------------------------------------------- */
5578
5579 /* Worker for DEF_BUILTIN.  Possibly define a builtin function with one or two
5580    names.  Does not declare a non-__builtin_ function if flag_no_builtin, or
5581    if nonansi_p and flag_no_nonansi_builtin.  */
5582
5583 static void
5584 def_builtin_1 (enum built_in_function fncode,
5585                const char *name,
5586                enum built_in_class fnclass,
5587                tree fntype, tree libtype,
5588                bool both_p, bool fallback_p,
5589                bool nonansi_p ATTRIBUTE_UNUSED,
5590                tree fnattrs, bool implicit_p)
5591 {
5592   tree decl;
5593   const char *libname;
5594
5595   /* Preserve an already installed decl.  It most likely was setup in advance
5596      (e.g. as part of the internal builtins) for specific reasons.  */
5597   if (built_in_decls[(int) fncode] != NULL_TREE)
5598     return;
5599
5600   gcc_assert ((!both_p && !fallback_p)
5601               || !strncmp (name, "__builtin_",
5602                            strlen ("__builtin_")));
5603
5604   libname = name + strlen ("__builtin_");
5605   decl = add_builtin_function (name, fntype, fncode, fnclass,
5606                                (fallback_p ? libname : NULL),
5607                                fnattrs);
5608   if (both_p)
5609     /* ??? This is normally further controlled by command-line options
5610        like -fno-builtin, but we don't have them for Ada.  */
5611     add_builtin_function (libname, libtype, fncode, fnclass,
5612                           NULL, fnattrs);
5613
5614   built_in_decls[(int) fncode] = decl;
5615   if (implicit_p)
5616     implicit_built_in_decls[(int) fncode] = decl;
5617 }
5618
5619 static int flag_isoc94 = 0;
5620 static int flag_isoc99 = 0;
5621
5622 /* Install what the common builtins.def offers.  */
5623
5624 static void
5625 install_builtin_functions (void)
5626 {
5627 #define DEF_BUILTIN(ENUM, NAME, CLASS, TYPE, LIBTYPE, BOTH_P, FALLBACK_P, \
5628                     NONANSI_P, ATTRS, IMPLICIT, COND)                   \
5629   if (NAME && COND)                                                     \
5630     def_builtin_1 (ENUM, NAME, CLASS,                                   \
5631                    builtin_types[(int) TYPE],                           \
5632                    builtin_types[(int) LIBTYPE],                        \
5633                    BOTH_P, FALLBACK_P, NONANSI_P,                       \
5634                    built_in_attributes[(int) ATTRS], IMPLICIT);
5635 #include "builtins.def"
5636 #undef DEF_BUILTIN
5637 }
5638
5639 /* ----------------------------------------------------------------------- *
5640  *                              BUILTIN FUNCTIONS                          *
5641  * ----------------------------------------------------------------------- */
5642
5643 /* Install the builtin functions we might need.  */
5644
5645 void
5646 gnat_install_builtins (void)
5647 {
5648   install_builtin_elementary_types ();
5649   install_builtin_function_types ();
5650   install_builtin_attributes ();
5651
5652   /* Install builtins used by generic middle-end pieces first.  Some of these
5653      know about internal specificities and control attributes accordingly, for
5654      instance __builtin_alloca vs no-throw and -fstack-check.  We will ignore
5655      the generic definition from builtins.def.  */
5656   build_common_builtin_nodes ();
5657
5658   /* Now, install the target specific builtins, such as the AltiVec family on
5659      ppc, and the common set as exposed by builtins.def.  */
5660   targetm.init_builtins ();
5661   install_builtin_functions ();
5662 }
5663
5664 #include "gt-ada-utils.h"
5665 #include "gtype-ada.h"