OSDN Git Service

* gcc/java/decl.c: Include langhooks.h.
[pf3gnuchains/gcc-fork.git] / gcc / ada / 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-2006, 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 2,  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  distributed with GNAT;  see file COPYING.  If not, write *
19  * to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor, *
20  * Boston, MA 02110-1301, USA.                                              *
21  *                                                                          *
22  * GNAT was originally developed  by the GNAT team at  New York University. *
23  * Extensive contributions were provided by Ada Core Technologies Inc.      *
24  *                                                                          *
25  ****************************************************************************/
26
27 #include "config.h"
28 #include "system.h"
29 #include "coretypes.h"
30 #include "tm.h"
31 #include "tree.h"
32 #include "flags.h"
33 #include "defaults.h"
34 #include "toplev.h"
35 #include "output.h"
36 #include "ggc.h"
37 #include "debug.h"
38 #include "convert.h"
39 #include "target.h"
40 #include "function.h"
41 #include "cgraph.h"
42 #include "tree-inline.h"
43 #include "tree-gimple.h"
44 #include "tree-dump.h"
45
46 #include "ada.h"
47 #include "types.h"
48 #include "atree.h"
49 #include "elists.h"
50 #include "namet.h"
51 #include "nlists.h"
52 #include "stringt.h"
53 #include "uintp.h"
54 #include "fe.h"
55 #include "sinfo.h"
56 #include "einfo.h"
57 #include "ada-tree.h"
58 #include "gigi.h"
59
60 #ifndef MAX_FIXED_MODE_SIZE
61 #define MAX_FIXED_MODE_SIZE GET_MODE_BITSIZE (DImode)
62 #endif
63
64 #ifndef MAX_BITS_PER_WORD
65 #define MAX_BITS_PER_WORD  BITS_PER_WORD
66 #endif
67
68 /* If nonzero, pretend we are allocating at global level.  */
69 int force_global;
70
71 /* Tree nodes for the various types and decls we create.  */
72 tree gnat_std_decls[(int) ADT_LAST];
73
74 /* Functions to call for each of the possible raise reasons.  */
75 tree gnat_raise_decls[(int) LAST_REASON_CODE + 1];
76
77 /* List of functions called automatically at the beginning and
78    end of execution, on targets without .ctors/.dtors sections.  */
79 tree static_ctors;
80 tree static_dtors;
81
82 /* Forward declarations for handlers of attributes.  */
83 static tree handle_const_attribute (tree *, tree, tree, int, bool *);
84 static tree handle_nothrow_attribute (tree *, tree, tree, int, bool *);
85
86 /* Table of machine-independent internal attributes for Ada.  We support
87    this minimal set of attributes to accommodate the Alpha back-end which
88    unconditionally puts them on its builtins.  */
89 const struct attribute_spec gnat_internal_attribute_table[] =
90 {
91   /* { name, min_len, max_len, decl_req, type_req, fn_type_req, handler } */
92   { "const",   0, 0, true,  false, false, handle_const_attribute   },
93   { "nothrow", 0, 0, true,  false, false, handle_nothrow_attribute },
94   { NULL,      0, 0, false, false, false, NULL }
95 };
96
97 /* Associates a GNAT tree node to a GCC tree node. It is used in
98    `save_gnu_tree', `get_gnu_tree' and `present_gnu_tree'. See documentation
99    of `save_gnu_tree' for more info.  */
100 static GTY((length ("max_gnat_nodes"))) tree *associate_gnat_to_gnu;
101
102 /* This variable keeps a table for types for each precision so that we only
103    allocate each of them once. Signed and unsigned types are kept separate.
104
105    Note that these types are only used when fold-const requests something
106    special.  Perhaps we should NOT share these types; we'll see how it
107    goes later.  */
108 static GTY(()) tree signed_and_unsigned_types[2 * MAX_BITS_PER_WORD + 1][2];
109
110 /* Likewise for float types, but record these by mode.  */
111 static GTY(()) tree float_types[NUM_MACHINE_MODES];
112
113 /* For each binding contour we allocate a binding_level structure to indicate
114    the binding depth.  */
115
116 struct gnat_binding_level GTY((chain_next ("%h.chain")))
117 {
118   /* The binding level containing this one (the enclosing binding level). */
119   struct gnat_binding_level *chain;
120   /* The BLOCK node for this level.  */
121   tree block;
122   /* If nonzero, the setjmp buffer that needs to be updated for any
123      variable-sized definition within this context.  */
124   tree jmpbuf_decl;
125 };
126
127 /* The binding level currently in effect.  */
128 static GTY(()) struct gnat_binding_level *current_binding_level;
129
130 /* A chain of gnat_binding_level structures awaiting reuse.  */
131 static GTY((deletable)) struct gnat_binding_level *free_binding_level;
132
133 /* A chain of unused BLOCK nodes. */
134 static GTY((deletable)) tree free_block_chain;
135
136 struct language_function GTY(())
137 {
138   int unused;
139 };
140
141 static void gnat_install_builtins (void);
142 static tree merge_sizes (tree, tree, tree, bool, bool);
143 static tree compute_related_constant (tree, tree);
144 static tree split_plus (tree, tree *);
145 static bool value_zerop (tree);
146 static void gnat_gimplify_function (tree);
147 static tree float_type_for_precision (int, enum machine_mode);
148 static tree convert_to_fat_pointer (tree, tree);
149 static tree convert_to_thin_pointer (tree, tree);
150 static tree make_descriptor_field (const char *,tree, tree, tree);
151 static bool potential_alignment_gap (tree, tree, tree);
152 \f
153 /* Initialize the association of GNAT nodes to GCC trees.  */
154
155 void
156 init_gnat_to_gnu (void)
157 {
158   associate_gnat_to_gnu
159     = (tree *) ggc_alloc_cleared (max_gnat_nodes * sizeof (tree));
160 }
161
162 /* GNAT_ENTITY is a GNAT tree node for an entity.   GNU_DECL is the GCC tree
163    which is to be associated with GNAT_ENTITY. Such GCC tree node is always
164    a ..._DECL node.  If NO_CHECK is nonzero, the latter check is suppressed.
165
166    If GNU_DECL is zero, a previous association is to be reset.  */
167
168 void
169 save_gnu_tree (Entity_Id gnat_entity, tree gnu_decl, bool no_check)
170 {
171   /* Check that GNAT_ENTITY is not already defined and that it is being set
172      to something which is a decl.  Raise gigi 401 if not.  Usually, this
173      means GNAT_ENTITY is defined twice, but occasionally is due to some
174      Gigi problem.  */
175   gcc_assert (!gnu_decl
176               || (!associate_gnat_to_gnu[gnat_entity - First_Node_Id]
177                   && (no_check || DECL_P (gnu_decl))));
178   associate_gnat_to_gnu[gnat_entity - First_Node_Id] = gnu_decl;
179 }
180
181 /* GNAT_ENTITY is a GNAT tree node for a defining identifier.
182    Return the ..._DECL node that was associated with it.  If there is no tree
183    node associated with GNAT_ENTITY, abort.
184
185    In some cases, such as delayed elaboration or expressions that need to
186    be elaborated only once, GNAT_ENTITY is really not an entity.  */
187
188 tree
189 get_gnu_tree (Entity_Id gnat_entity)
190 {
191   gcc_assert (associate_gnat_to_gnu[gnat_entity - First_Node_Id]);
192   return associate_gnat_to_gnu[gnat_entity - First_Node_Id];
193 }
194
195 /* Return nonzero if a GCC tree has been associated with GNAT_ENTITY.  */
196
197 bool
198 present_gnu_tree (Entity_Id gnat_entity)
199 {
200   return (associate_gnat_to_gnu[gnat_entity - First_Node_Id]) != 0;
201 }
202
203 \f
204 /* Return nonzero if we are currently in the global binding level.  */
205
206 int
207 global_bindings_p (void)
208 {
209   return ((force_global || !current_function_decl) ? -1 : 0);
210 }
211
212 /* Enter a new binding level. */
213
214 void
215 gnat_pushlevel ()
216 {
217   struct gnat_binding_level *newlevel = NULL;
218
219   /* Reuse a struct for this binding level, if there is one.  */
220   if (free_binding_level)
221     {
222       newlevel = free_binding_level;
223       free_binding_level = free_binding_level->chain;
224     }
225   else
226     newlevel
227       = (struct gnat_binding_level *)
228         ggc_alloc (sizeof (struct gnat_binding_level));
229
230   /* Use a free BLOCK, if any; otherwise, allocate one.  */
231   if (free_block_chain)
232     {
233       newlevel->block = free_block_chain;
234       free_block_chain = TREE_CHAIN (free_block_chain);
235       TREE_CHAIN (newlevel->block) = NULL_TREE;
236     }
237   else
238     newlevel->block = make_node (BLOCK);
239
240   /* Point the BLOCK we just made to its parent.  */
241   if (current_binding_level)
242     BLOCK_SUPERCONTEXT (newlevel->block) = current_binding_level->block;
243
244   BLOCK_VARS (newlevel->block) = BLOCK_SUBBLOCKS (newlevel->block) = NULL_TREE;
245   TREE_USED (newlevel->block) = 1;
246
247   /* Add this level to the front of the chain (stack) of levels that are
248      active.  */
249   newlevel->chain = current_binding_level;
250   newlevel->jmpbuf_decl = NULL_TREE;
251   current_binding_level = newlevel;
252 }
253
254 /* Set SUPERCONTEXT of the BLOCK for the current binding level to FNDECL
255    and point FNDECL to this BLOCK.  */
256
257 void
258 set_current_block_context (tree fndecl)
259 {
260   BLOCK_SUPERCONTEXT (current_binding_level->block) = fndecl;
261   DECL_INITIAL (fndecl) = current_binding_level->block;
262 }
263
264 /* Set the jmpbuf_decl for the current binding level to DECL.  */
265
266 void
267 set_block_jmpbuf_decl (tree decl)
268 {
269   current_binding_level->jmpbuf_decl = decl;
270 }
271
272 /* Get the jmpbuf_decl, if any, for the current binding level.  */
273
274 tree
275 get_block_jmpbuf_decl ()
276 {
277   return current_binding_level->jmpbuf_decl;
278 }
279
280 /* Exit a binding level. Set any BLOCK into the current code group.  */
281
282 void
283 gnat_poplevel ()
284 {
285   struct gnat_binding_level *level = current_binding_level;
286   tree block = level->block;
287
288   BLOCK_VARS (block) = nreverse (BLOCK_VARS (block));
289   BLOCK_SUBBLOCKS (block) = nreverse (BLOCK_SUBBLOCKS (block));
290
291   /* If this is a function-level BLOCK don't do anything.  Otherwise, if there
292      are no variables free the block and merge its subblocks into those of its
293      parent block. Otherwise, add it to the list of its parent.  */
294   if (TREE_CODE (BLOCK_SUPERCONTEXT (block)) == FUNCTION_DECL)
295     ;
296   else if (BLOCK_VARS (block) == NULL_TREE)
297     {
298       BLOCK_SUBBLOCKS (level->chain->block)
299         = chainon (BLOCK_SUBBLOCKS (block),
300                    BLOCK_SUBBLOCKS (level->chain->block));
301       TREE_CHAIN (block) = free_block_chain;
302       free_block_chain = block;
303     }
304   else
305     {
306       TREE_CHAIN (block) = BLOCK_SUBBLOCKS (level->chain->block);
307       BLOCK_SUBBLOCKS (level->chain->block) = block;
308       TREE_USED (block) = 1;
309       set_block_for_group (block);
310     }
311
312   /* Free this binding structure.  */
313   current_binding_level = level->chain;
314   level->chain = free_binding_level;
315   free_binding_level = level;
316 }
317
318 /* Insert BLOCK at the end of the list of subblocks of the
319    current binding level.  This is used when a BIND_EXPR is expanded,
320    to handle the BLOCK node inside the BIND_EXPR.  */
321
322 void
323 insert_block (tree block)
324 {
325   TREE_USED (block) = 1;
326   TREE_CHAIN (block) = BLOCK_SUBBLOCKS (current_binding_level->block);
327   BLOCK_SUBBLOCKS (current_binding_level->block) = block;
328 }
329 \f
330 /* Records a ..._DECL node DECL as belonging to the current lexical scope
331    and uses GNAT_NODE for location information and propagating flags.  */
332
333 void
334 gnat_pushdecl (tree decl, Node_Id gnat_node)
335 {
336   /* If at top level, there is no context. But PARM_DECLs always go in the
337      level of its function.  */
338   if (global_bindings_p () && TREE_CODE (decl) != PARM_DECL)
339     DECL_CONTEXT (decl) = 0;
340   else
341     {
342       DECL_CONTEXT (decl) = current_function_decl;
343
344       /* Functions imported in another function are not really nested.  */
345       if (TREE_CODE (decl) == FUNCTION_DECL && TREE_PUBLIC (decl))
346         DECL_NO_STATIC_CHAIN (decl) = 1;
347     }
348
349   TREE_NO_WARNING (decl) = (gnat_node == Empty || Warnings_Off (gnat_node));
350
351   /* Set the location of DECL and emit a declaration for it.  */
352   if (Present (gnat_node))
353     Sloc_to_locus (Sloc (gnat_node), &DECL_SOURCE_LOCATION (decl));
354   add_decl_expr (decl, gnat_node);
355
356   /* Put the declaration on the list.  The list of declarations is in reverse
357      order. The list will be reversed later.  We don't do this for global
358      variables.  Also, don't put TYPE_DECLs for UNCONSTRAINED_ARRAY_TYPE into
359      the list.  They will cause trouble with the debugger and aren't needed
360      anyway.  */
361   if (!global_bindings_p ()
362       && (TREE_CODE (decl) != TYPE_DECL
363           || TREE_CODE (TREE_TYPE (decl)) != UNCONSTRAINED_ARRAY_TYPE))
364     {
365       TREE_CHAIN (decl) = BLOCK_VARS (current_binding_level->block);
366       BLOCK_VARS (current_binding_level->block) = decl;
367     }
368
369   /* For the declaration of a type, set its name if it either is not already
370      set, was set to an IDENTIFIER_NODE, indicating an internal name,
371      or if the previous type name was not derived from a source name.
372      We'd rather have the type named with a real name and all the pointer
373      types to the same object have the same POINTER_TYPE node.  Code in this
374      function in c-decl.c makes a copy of the type node here, but that may
375      cause us trouble with incomplete types, so let's not try it (at least
376      for now).  */
377
378   if (TREE_CODE (decl) == TYPE_DECL
379       && DECL_NAME (decl)
380       && (!TYPE_NAME (TREE_TYPE (decl))
381           || TREE_CODE (TYPE_NAME (TREE_TYPE (decl))) == IDENTIFIER_NODE
382           || (TREE_CODE (TYPE_NAME (TREE_TYPE (decl))) == TYPE_DECL
383               && DECL_ARTIFICIAL (TYPE_NAME (TREE_TYPE (decl)))
384               && !DECL_ARTIFICIAL (decl))))
385     TYPE_NAME (TREE_TYPE (decl)) = decl;
386
387   /*  if (TREE_CODE (decl) != CONST_DECL)
388       rest_of_decl_compilation (decl, global_bindings_p (), 0); */
389 }
390 \f
391 /* Do little here.  Set up the standard declarations later after the
392    front end has been run.  */
393
394 void
395 gnat_init_decl_processing (void)
396 {
397   input_line = 0;
398
399   /* Make the binding_level structure for global names.  */
400   current_function_decl = 0;
401   current_binding_level = 0;
402   free_binding_level = 0;
403   gnat_pushlevel ();
404
405   build_common_tree_nodes (true, true);
406
407   /* In Ada, we use a signed type for SIZETYPE.  Use the signed type
408      corresponding to the size of Pmode.  In most cases when ptr_mode and
409      Pmode differ, C will use the width of ptr_mode as sizetype.  But we get
410      far better code using the width of Pmode.  Make this here since we need
411      this before we can expand the GNAT types.  */
412   size_type_node = gnat_type_for_size (GET_MODE_BITSIZE (Pmode), 0);
413   set_sizetype (size_type_node);
414   build_common_tree_nodes_2 (0);
415
416   /* Give names and make TYPE_DECLs for common types.  */
417   gnat_pushdecl (build_decl (TYPE_DECL, get_identifier (SIZE_TYPE), sizetype),
418                  Empty);
419   gnat_pushdecl (build_decl (TYPE_DECL, get_identifier ("integer"),
420                              integer_type_node),
421                  Empty);
422   gnat_pushdecl (build_decl (TYPE_DECL, get_identifier ("unsigned char"),
423                              char_type_node),
424                  Empty);
425   gnat_pushdecl (build_decl (TYPE_DECL, get_identifier ("long integer"),
426                              long_integer_type_node),
427                  Empty);
428
429   ptr_void_type_node = build_pointer_type (void_type_node);
430
431   gnat_install_builtins ();
432 }
433
434 /* Install the builtin functions the middle-end needs.  */
435
436 static void
437 gnat_install_builtins ()
438 {
439   /* Builtins used by generic optimizers.  */
440   build_common_builtin_nodes ();
441
442   /* Target specific builtins, such as the AltiVec family on ppc.  */
443   targetm.init_builtins ();
444 }
445
446 /* Create the predefined scalar types such as `integer_type_node' needed
447    in the gcc back-end and initialize the global binding level.  */
448
449 void
450 init_gigi_decls (tree long_long_float_type, tree exception_type)
451 {
452   tree endlink, decl;
453   unsigned int i;
454
455   /* Set the types that GCC and Gigi use from the front end.  We would like
456      to do this for char_type_node, but it needs to correspond to the C
457      char type.  */
458   if (TREE_CODE (TREE_TYPE (long_long_float_type)) == INTEGER_TYPE)
459     {
460       /* In this case, the builtin floating point types are VAX float,
461          so make up a type for use.  */
462       longest_float_type_node = make_node (REAL_TYPE);
463       TYPE_PRECISION (longest_float_type_node) = LONG_DOUBLE_TYPE_SIZE;
464       layout_type (longest_float_type_node);
465       create_type_decl (get_identifier ("longest float type"),
466                         longest_float_type_node, NULL, false, true, Empty);
467     }
468   else
469     longest_float_type_node = TREE_TYPE (long_long_float_type);
470
471   except_type_node = TREE_TYPE (exception_type);
472
473   unsigned_type_node = gnat_type_for_size (INT_TYPE_SIZE, 1);
474   create_type_decl (get_identifier ("unsigned int"), unsigned_type_node,
475                     NULL, false, true, Empty);
476
477   void_type_decl_node = create_type_decl (get_identifier ("void"),
478                                           void_type_node, NULL, false, true,
479                                           Empty);
480
481   void_ftype = build_function_type (void_type_node, NULL_TREE);
482   ptr_void_ftype = build_pointer_type (void_ftype);
483
484   /* Now declare runtime functions. */
485   endlink = tree_cons (NULL_TREE, void_type_node, NULL_TREE);
486
487   /* malloc is a function declaration tree for a function to allocate
488      memory.  */
489   malloc_decl = create_subprog_decl (get_identifier ("__gnat_malloc"),
490                                      NULL_TREE,
491                                      build_function_type (ptr_void_type_node,
492                                                           tree_cons (NULL_TREE,
493                                                                      sizetype,
494                                                                      endlink)),
495                                      NULL_TREE, false, true, true, NULL,
496                                      Empty);
497
498   /* free is a function declaration tree for a function to free memory.  */
499   free_decl
500     = create_subprog_decl (get_identifier ("__gnat_free"), NULL_TREE,
501                            build_function_type (void_type_node,
502                                                 tree_cons (NULL_TREE,
503                                                            ptr_void_type_node,
504                                                            endlink)),
505                            NULL_TREE, false, true, true, NULL, Empty);
506
507   /* Make the types and functions used for exception processing.    */
508   jmpbuf_type
509     = build_array_type (gnat_type_for_mode (Pmode, 0),
510                         build_index_type (build_int_cst (NULL_TREE, 5)));
511   create_type_decl (get_identifier ("JMPBUF_T"), jmpbuf_type, NULL,
512                     false, true, Empty);
513   jmpbuf_ptr_type = build_pointer_type (jmpbuf_type);
514
515   /* Functions to get and set the jumpbuf pointer for the current thread.  */
516   get_jmpbuf_decl
517     = create_subprog_decl
518     (get_identifier ("system__soft_links__get_jmpbuf_address_soft"),
519      NULL_TREE, build_function_type (jmpbuf_ptr_type, NULL_TREE),
520      NULL_TREE, false, true, true, NULL, Empty);
521   /* Avoid creating superfluous edges to __builtin_setjmp receivers.  */
522   DECL_IS_PURE (get_jmpbuf_decl) = 1;
523
524   set_jmpbuf_decl
525     = create_subprog_decl
526     (get_identifier ("system__soft_links__set_jmpbuf_address_soft"),
527      NULL_TREE,
528      build_function_type (void_type_node,
529                           tree_cons (NULL_TREE, jmpbuf_ptr_type, endlink)),
530      NULL_TREE, false, true, true, NULL, Empty);
531
532   /* Function to get the current exception.  */
533   get_excptr_decl
534     = create_subprog_decl
535     (get_identifier ("system__soft_links__get_gnat_exception"),
536      NULL_TREE,
537      build_function_type (build_pointer_type (except_type_node), NULL_TREE),
538      NULL_TREE, false, true, true, NULL, Empty);
539   /* Avoid creating superfluous edges to __builtin_setjmp receivers.  */
540   DECL_IS_PURE (get_excptr_decl) = 1;
541
542   /* Functions that raise exceptions. */
543   raise_nodefer_decl
544     = create_subprog_decl
545       (get_identifier ("__gnat_raise_nodefer_with_msg"), NULL_TREE,
546        build_function_type (void_type_node,
547                             tree_cons (NULL_TREE,
548                                        build_pointer_type (except_type_node),
549                                        endlink)),
550        NULL_TREE, false, true, true, NULL, Empty);
551
552   /* Dummy objects to materialize "others" and "all others" in the exception
553      tables.  These are exported by a-exexpr.adb, so see this unit for the
554      types to use.  */
555
556   others_decl
557     = create_var_decl (get_identifier ("OTHERS"),
558                        get_identifier ("__gnat_others_value"),
559                        integer_type_node, 0, 1, 0, 1, 1, 0, Empty);
560
561   all_others_decl
562     = create_var_decl (get_identifier ("ALL_OTHERS"),
563                        get_identifier ("__gnat_all_others_value"),
564                        integer_type_node, 0, 1, 0, 1, 1, 0, Empty);
565
566   /* Hooks to call when entering/leaving an exception handler.  */
567   begin_handler_decl
568     = create_subprog_decl (get_identifier ("__gnat_begin_handler"), NULL_TREE,
569                            build_function_type (void_type_node,
570                                                 tree_cons (NULL_TREE,
571                                                            ptr_void_type_node,
572                                                            endlink)),
573                            NULL_TREE, false, true, true, NULL, Empty);
574
575   end_handler_decl
576     = create_subprog_decl (get_identifier ("__gnat_end_handler"), NULL_TREE,
577                            build_function_type (void_type_node,
578                                                 tree_cons (NULL_TREE,
579                                                            ptr_void_type_node,
580                                                            endlink)),
581                            NULL_TREE, false, true, true, NULL, Empty);
582
583   /* If in no exception handlers mode, all raise statements are redirected to
584      __gnat_last_chance_handler. No need to redefine raise_nodefer_decl, since
585      this procedure will never be called in this mode.  */
586   if (No_Exception_Handlers_Set ())
587     {
588       decl
589         = create_subprog_decl
590           (get_identifier ("__gnat_last_chance_handler"), NULL_TREE,
591            build_function_type (void_type_node,
592                                 tree_cons (NULL_TREE,
593                                            build_pointer_type (char_type_node),
594                                            tree_cons (NULL_TREE,
595                                                       integer_type_node,
596                                                       endlink))),
597            NULL_TREE, false, true, true, NULL, Empty);
598
599       for (i = 0; i < ARRAY_SIZE (gnat_raise_decls); i++)
600         gnat_raise_decls[i] = decl;
601     }
602   else
603     /* Otherwise, make one decl for each exception reason.  */
604     for (i = 0; i < ARRAY_SIZE (gnat_raise_decls); i++)
605       {
606         char name[17];
607
608         sprintf (name, "__gnat_rcheck_%.2d", i);
609         gnat_raise_decls[i]
610           = create_subprog_decl
611             (get_identifier (name), NULL_TREE,
612              build_function_type (void_type_node,
613                                   tree_cons (NULL_TREE,
614                                              build_pointer_type
615                                              (char_type_node),
616                                              tree_cons (NULL_TREE,
617                                                         integer_type_node,
618                                                         endlink))),
619              NULL_TREE, false, true, true, NULL, Empty);
620       }
621
622   /* Indicate that these never return.  */
623   TREE_THIS_VOLATILE (raise_nodefer_decl) = 1;
624   TREE_SIDE_EFFECTS (raise_nodefer_decl) = 1;
625   TREE_TYPE (raise_nodefer_decl)
626     = build_qualified_type (TREE_TYPE (raise_nodefer_decl),
627                             TYPE_QUAL_VOLATILE);
628
629   for (i = 0; i < ARRAY_SIZE (gnat_raise_decls); i++)
630     {
631       TREE_THIS_VOLATILE (gnat_raise_decls[i]) = 1;
632       TREE_SIDE_EFFECTS (gnat_raise_decls[i]) = 1;
633       TREE_TYPE (gnat_raise_decls[i])
634         = build_qualified_type (TREE_TYPE (gnat_raise_decls[i]),
635                                 TYPE_QUAL_VOLATILE);
636     }
637
638   /* setjmp returns an integer and has one operand, which is a pointer to
639      a jmpbuf.  */
640   setjmp_decl
641     = create_subprog_decl
642       (get_identifier ("__builtin_setjmp"), NULL_TREE,
643        build_function_type (integer_type_node,
644                             tree_cons (NULL_TREE,  jmpbuf_ptr_type, endlink)),
645        NULL_TREE, false, true, true, NULL, Empty);
646
647   DECL_BUILT_IN_CLASS (setjmp_decl) = BUILT_IN_NORMAL;
648   DECL_FUNCTION_CODE (setjmp_decl) = BUILT_IN_SETJMP;
649
650   /* update_setjmp_buf updates a setjmp buffer from the current stack pointer
651      address.  */
652   update_setjmp_buf_decl
653     = create_subprog_decl
654       (get_identifier ("__builtin_update_setjmp_buf"), NULL_TREE,
655        build_function_type (void_type_node,
656                             tree_cons (NULL_TREE,  jmpbuf_ptr_type, endlink)),
657        NULL_TREE, false, true, true, NULL, Empty);
658
659   DECL_BUILT_IN_CLASS (update_setjmp_buf_decl) = BUILT_IN_NORMAL;
660   DECL_FUNCTION_CODE (update_setjmp_buf_decl) = BUILT_IN_UPDATE_SETJMP_BUF;
661
662   main_identifier_node = get_identifier ("main");
663 }
664 \f
665 /* Given a record type (RECORD_TYPE) and a chain of FIELD_DECL nodes
666    (FIELDLIST), finish constructing the record or union type.  If HAS_REP is
667    true, this record has a rep clause; don't call layout_type but merely set
668    the size and alignment ourselves.  If DEFER_DEBUG is true, do not call
669    the debugging routines on this type; it will be done later. */
670
671 void
672 finish_record_type (tree record_type, tree fieldlist, bool has_rep,
673                     bool defer_debug)
674 {
675   enum tree_code code = TREE_CODE (record_type);
676   tree ada_size = bitsize_zero_node;
677   tree size = bitsize_zero_node;
678   bool var_size = false;
679   bool had_size = TYPE_SIZE (record_type) != 0;
680   bool had_size_unit = TYPE_SIZE_UNIT (record_type) != 0;
681   tree field;
682
683   TYPE_FIELDS (record_type) = fieldlist;
684   TYPE_STUB_DECL (record_type)
685     = build_decl (TYPE_DECL, NULL_TREE, record_type);
686
687   /* We don't need both the typedef name and the record name output in
688      the debugging information, since they are the same.  */
689   DECL_ARTIFICIAL (TYPE_STUB_DECL (record_type)) = 1;
690
691   /* Globally initialize the record first.  If this is a rep'ed record,
692      that just means some initializations; otherwise, layout the record.  */
693
694   if (has_rep)
695     {
696       TYPE_ALIGN (record_type) = MAX (BITS_PER_UNIT, TYPE_ALIGN (record_type));
697       TYPE_MODE (record_type) = BLKmode;
698
699       if (!had_size_unit)
700         TYPE_SIZE_UNIT (record_type) = size_zero_node;
701       if (!had_size)
702         TYPE_SIZE (record_type) = bitsize_zero_node;
703
704       /* For all-repped records with a size specified, lay the QUAL_UNION_TYPE
705          out just like a UNION_TYPE, since the size will be fixed.  */
706       else if (code == QUAL_UNION_TYPE)
707         code = UNION_TYPE;
708     }
709   else
710     {
711       /* Ensure there isn't a size already set.  There can be in an error
712          case where there is a rep clause but all fields have errors and
713          no longer have a position.  */
714       TYPE_SIZE (record_type) = 0;
715       layout_type (record_type);
716     }
717
718   /* At this point, the position and size of each field is known.  It was
719      either set before entry by a rep clause, or by laying out the type above.
720
721      We now run a pass over the fields (in reverse order for QUAL_UNION_TYPEs)
722      to compute the Ada size; the GCC size and alignment (for rep'ed records
723      that are not padding types); and the mode (for rep'ed records).  We also
724      clear the DECL_BIT_FIELD indication for the cases we know have not been
725      handled yet, and adjust DECL_NONADDRESSABLE_P accordingly.  */
726
727   if (code == QUAL_UNION_TYPE)
728     fieldlist = nreverse (fieldlist);
729
730   for (field = fieldlist; field; field = TREE_CHAIN (field))
731     {
732       tree pos = bit_position (field);
733
734       tree type = TREE_TYPE (field);
735       tree this_size = DECL_SIZE (field);
736       tree this_ada_size = DECL_SIZE (field);
737
738       /* We need to make an XVE/XVU record if any field has variable size,
739          whether or not the record does.  For example, if we have a union,
740          it may be that all fields, rounded up to the alignment, have the
741          same size, in which case we'll use that size.  But the debug
742          output routines (except Dwarf2) won't be able to output the fields,
743          so we need to make the special record.  */
744       if (TREE_CODE (this_size) != INTEGER_CST)
745         var_size = true;
746
747       if ((TREE_CODE (type) == RECORD_TYPE || TREE_CODE (type) == UNION_TYPE
748           || TREE_CODE (type) == QUAL_UNION_TYPE)
749           && !TYPE_IS_FAT_POINTER_P (type)
750           && !TYPE_CONTAINS_TEMPLATE_P (type)
751           && TYPE_ADA_SIZE (type))
752         this_ada_size = TYPE_ADA_SIZE (type);
753
754       /* Clear DECL_BIT_FIELD for the cases layout_decl does not handle.  */
755       if (DECL_BIT_FIELD (field) && !STRICT_ALIGNMENT
756           && value_factor_p (pos, BITS_PER_UNIT)
757           && operand_equal_p (this_size, TYPE_SIZE (type), 0))
758         DECL_BIT_FIELD (field) = 0;
759
760       /* If we still have DECL_BIT_FIELD set at this point, we know the field
761          is technically not addressable.  Except that it can actually be
762          addressed if the field is BLKmode and happens to be properly
763          aligned.  */
764       DECL_NONADDRESSABLE_P (field)
765         |= DECL_BIT_FIELD (field) && DECL_MODE (field) != BLKmode;
766
767       if (has_rep && !DECL_BIT_FIELD (field))
768         TYPE_ALIGN (record_type)
769           = MAX (TYPE_ALIGN (record_type), DECL_ALIGN (field));
770
771       switch (code)
772         {
773         case UNION_TYPE:
774           ada_size = size_binop (MAX_EXPR, ada_size, this_ada_size);
775           size = size_binop (MAX_EXPR, size, this_size);
776           break;
777
778         case QUAL_UNION_TYPE:
779           ada_size
780             = fold (build3 (COND_EXPR, bitsizetype, DECL_QUALIFIER (field),
781                             this_ada_size, ada_size));
782           size = fold (build3 (COND_EXPR, bitsizetype, DECL_QUALIFIER (field),
783                                this_size, size));
784           break;
785
786         case RECORD_TYPE:
787           /* Since we know here that all fields are sorted in order of
788              increasing bit position, the size of the record is one
789              higher than the ending bit of the last field processed
790              unless we have a rep clause, since in that case we might
791              have a field outside a QUAL_UNION_TYPE that has a higher ending
792              position.  So use a MAX in that case.  Also, if this field is a
793              QUAL_UNION_TYPE, we need to take into account the previous size in
794              the case of empty variants.  */
795           ada_size
796             = merge_sizes (ada_size, pos, this_ada_size,
797                            TREE_CODE (type) == QUAL_UNION_TYPE, has_rep);
798           size = merge_sizes (size, pos, this_size,
799                               TREE_CODE (type) == QUAL_UNION_TYPE, has_rep);
800           break;
801
802         default:
803           gcc_unreachable ();
804         }
805     }
806
807   if (code == QUAL_UNION_TYPE)
808     nreverse (fieldlist);
809
810   /* If this is a padding record, we never want to make the size smaller than
811      what was specified in it, if any.  */
812   if (TREE_CODE (record_type) == RECORD_TYPE
813       && TYPE_IS_PADDING_P (record_type) && TYPE_SIZE (record_type))
814     size = TYPE_SIZE (record_type);
815
816   /* Now set any of the values we've just computed that apply.  */
817   if (!TYPE_IS_FAT_POINTER_P (record_type)
818       && !TYPE_CONTAINS_TEMPLATE_P (record_type))
819     SET_TYPE_ADA_SIZE (record_type, ada_size);
820
821   if (has_rep)
822     {
823       tree size_unit
824         = (had_size_unit ? TYPE_SIZE_UNIT (record_type)
825            : convert (sizetype, size_binop (CEIL_DIV_EXPR, size,
826                                             bitsize_unit_node)));
827
828       TYPE_SIZE (record_type)
829         = variable_size (round_up (size, TYPE_ALIGN (record_type)));
830       TYPE_SIZE_UNIT (record_type)
831         = variable_size (round_up (size_unit,
832                                    TYPE_ALIGN (record_type) / BITS_PER_UNIT));
833
834       compute_record_mode (record_type);
835     }
836
837   if (!defer_debug)
838     write_record_type_debug_info (record_type);
839 }
840
841 /* Output the debug information associated to a record type.  */
842
843 void
844 write_record_type_debug_info (tree record_type)
845 {
846   tree fieldlist = TYPE_FIELDS (record_type);
847   tree field;
848   bool var_size = false;
849
850   for (field = fieldlist; field; field = TREE_CHAIN (field))
851     {
852       /* We need to make an XVE/XVU record if any field has variable size,
853          whether or not the record does.  For example, if we have a union,
854          it may be that all fields, rounded up to the alignment, have the
855          same size, in which case we'll use that size.  But the debug
856          output routines (except Dwarf2) won't be able to output the fields,
857          so we need to make the special record.  */
858       if (TREE_CODE (DECL_SIZE (field)) != INTEGER_CST)
859         {
860           var_size = true;
861           break;
862         }
863     }
864
865   /* If this record is of variable size, rename it so that the
866      debugger knows it is and make a new, parallel, record
867      that tells the debugger how the record is laid out.  See
868      exp_dbug.ads.  But don't do this for records that are padding
869      since they confuse GDB.  */
870   if (var_size
871       && !(TREE_CODE (record_type) == RECORD_TYPE
872            && TYPE_IS_PADDING_P (record_type)))
873     {
874       tree new_record_type
875         = make_node (TREE_CODE (record_type) == QUAL_UNION_TYPE
876                      ? UNION_TYPE : TREE_CODE (record_type));
877       tree orig_name = TYPE_NAME (record_type);
878       tree orig_id
879         = (TREE_CODE (orig_name) == TYPE_DECL ? DECL_NAME (orig_name)
880            : orig_name);
881       tree new_id
882         = concat_id_with_name (orig_id,
883                                TREE_CODE (record_type) == QUAL_UNION_TYPE
884                                ? "XVU" : "XVE");
885       tree last_pos = bitsize_zero_node;
886       tree old_field;
887       tree prev_old_field = 0;
888
889       TYPE_NAME (new_record_type) = new_id;
890       TYPE_ALIGN (new_record_type) = BIGGEST_ALIGNMENT;
891       TYPE_STUB_DECL (new_record_type)
892         = build_decl (TYPE_DECL, NULL_TREE, new_record_type);
893       DECL_ARTIFICIAL (TYPE_STUB_DECL (new_record_type)) = 1;
894       DECL_IGNORED_P (TYPE_STUB_DECL (new_record_type))
895         = DECL_IGNORED_P (TYPE_STUB_DECL (record_type));
896       TYPE_SIZE (new_record_type) = size_int (TYPE_ALIGN (record_type));
897       TYPE_SIZE_UNIT (new_record_type)
898         = size_int (TYPE_ALIGN (record_type) / BITS_PER_UNIT);
899
900       /* Now scan all the fields, replacing each field with a new
901          field corresponding to the new encoding.  */
902       for (old_field = TYPE_FIELDS (record_type); old_field;
903            old_field = TREE_CHAIN (old_field))
904         {
905           tree field_type = TREE_TYPE (old_field);
906           tree field_name = DECL_NAME (old_field);
907           tree new_field;
908           tree curpos = bit_position (old_field);
909           bool var = false;
910           unsigned int align = 0;
911           tree pos;
912
913           /* See how the position was modified from the last position.
914
915           There are two basic cases we support: a value was added
916           to the last position or the last position was rounded to
917           a boundary and they something was added.  Check for the
918           first case first.  If not, see if there is any evidence
919           of rounding.  If so, round the last position and try
920           again.
921
922           If this is a union, the position can be taken as zero. */
923
924           if (TREE_CODE (new_record_type) == UNION_TYPE)
925             pos = bitsize_zero_node, align = 0;
926           else
927             pos = compute_related_constant (curpos, last_pos);
928
929           if (!pos && TREE_CODE (curpos) == MULT_EXPR
930               && TREE_CODE (TREE_OPERAND (curpos, 1)) == INTEGER_CST)
931             {
932               align = TREE_INT_CST_LOW (TREE_OPERAND (curpos, 1));
933               pos = compute_related_constant (curpos,
934                                               round_up (last_pos, align));
935             }
936           else if (!pos && TREE_CODE (curpos) == PLUS_EXPR
937                    && TREE_CODE (TREE_OPERAND (curpos, 1)) == INTEGER_CST
938                    && TREE_CODE (TREE_OPERAND (curpos, 0)) == MULT_EXPR
939                    && host_integerp (TREE_OPERAND
940                                      (TREE_OPERAND (curpos, 0), 1),
941                                      1))
942             {
943               align
944                 = tree_low_cst
945                 (TREE_OPERAND (TREE_OPERAND (curpos, 0), 1), 1);
946               pos = compute_related_constant (curpos,
947                                               round_up (last_pos, align));
948             }
949           else if (potential_alignment_gap (prev_old_field, old_field,
950                                             pos))
951             {
952               align = TYPE_ALIGN (field_type);
953               pos = compute_related_constant (curpos,
954                                               round_up (last_pos, align));
955             }
956
957           /* If we can't compute a position, set it to zero.
958
959           ??? We really should abort here, but it's too much work
960           to get this correct for all cases.  */
961
962           if (!pos)
963             pos = bitsize_zero_node;
964
965           /* See if this type is variable-size and make a new type
966              and indicate the indirection if so.  */
967           if (TREE_CODE (DECL_SIZE (old_field)) != INTEGER_CST)
968             {
969               field_type = build_pointer_type (field_type);
970               var = true;
971             }
972
973           /* Make a new field name, if necessary.  */
974           if (var || align != 0)
975             {
976               char suffix[6];
977
978               if (align != 0)
979                 sprintf (suffix, "XV%c%u", var ? 'L' : 'A',
980                          align / BITS_PER_UNIT);
981               else
982                 strcpy (suffix, "XVL");
983
984               field_name = concat_id_with_name (field_name, suffix);
985             }
986
987           new_field = create_field_decl (field_name, field_type,
988                                          new_record_type, 0,
989                                          DECL_SIZE (old_field), pos, 0);
990           TREE_CHAIN (new_field) = TYPE_FIELDS (new_record_type);
991           TYPE_FIELDS (new_record_type) = new_field;
992
993           /* If old_field is a QUAL_UNION_TYPE, take its size as being
994              zero.  The only time it's not the last field of the record
995              is when there are other components at fixed positions after
996              it (meaning there was a rep clause for every field) and we
997              want to be able to encode them.  */
998           last_pos = size_binop (PLUS_EXPR, bit_position (old_field),
999                                  (TREE_CODE (TREE_TYPE (old_field))
1000                                   == QUAL_UNION_TYPE)
1001                                  ? bitsize_zero_node
1002                                  : DECL_SIZE (old_field));
1003           prev_old_field = old_field;
1004         }
1005
1006       TYPE_FIELDS (new_record_type)
1007         = nreverse (TYPE_FIELDS (new_record_type));
1008
1009       rest_of_type_compilation (new_record_type, global_bindings_p ());
1010     }
1011
1012   rest_of_type_compilation (record_type, global_bindings_p ());
1013 }
1014
1015 /* Utility function of above to merge LAST_SIZE, the previous size of a record
1016    with FIRST_BIT and SIZE that describe a field.  SPECIAL is nonzero
1017    if this represents a QUAL_UNION_TYPE in which case we must look for
1018    COND_EXPRs and replace a value of zero with the old size.  If HAS_REP
1019    is nonzero, we must take the MAX of the end position of this field
1020    with LAST_SIZE.  In all other cases, we use FIRST_BIT plus SIZE.
1021
1022    We return an expression for the size.  */
1023
1024 static tree
1025 merge_sizes (tree last_size, tree first_bit, tree size, bool special,
1026              bool has_rep)
1027 {
1028   tree type = TREE_TYPE (last_size);
1029   tree new;
1030
1031   if (!special || TREE_CODE (size) != COND_EXPR)
1032     {
1033       new = size_binop (PLUS_EXPR, first_bit, size);
1034       if (has_rep)
1035         new = size_binop (MAX_EXPR, last_size, new);
1036     }
1037
1038   else
1039     new = fold (build3 (COND_EXPR, type, TREE_OPERAND (size, 0),
1040                         integer_zerop (TREE_OPERAND (size, 1))
1041                         ? last_size : merge_sizes (last_size, first_bit,
1042                                                    TREE_OPERAND (size, 1),
1043                                                    1, has_rep),
1044                         integer_zerop (TREE_OPERAND (size, 2))
1045                         ? last_size : merge_sizes (last_size, first_bit,
1046                                                    TREE_OPERAND (size, 2),
1047                                                    1, has_rep)));
1048
1049   /* We don't need any NON_VALUE_EXPRs and they can confuse us (especially
1050      when fed through substitute_in_expr) into thinking that a constant
1051      size is not constant.  */
1052   while (TREE_CODE (new) == NON_LVALUE_EXPR)
1053     new = TREE_OPERAND (new, 0);
1054
1055   return new;
1056 }
1057
1058 /* Utility function of above to see if OP0 and OP1, both of SIZETYPE, are
1059    related by the addition of a constant.  Return that constant if so.  */
1060
1061 static tree
1062 compute_related_constant (tree op0, tree op1)
1063 {
1064   tree op0_var, op1_var;
1065   tree op0_con = split_plus (op0, &op0_var);
1066   tree op1_con = split_plus (op1, &op1_var);
1067   tree result = size_binop (MINUS_EXPR, op0_con, op1_con);
1068
1069   if (operand_equal_p (op0_var, op1_var, 0))
1070     return result;
1071   else if (operand_equal_p (op0, size_binop (PLUS_EXPR, op1_var, result), 0))
1072     return result;
1073   else
1074     return 0;
1075 }
1076
1077 /* Utility function of above to split a tree OP which may be a sum, into a
1078    constant part, which is returned, and a variable part, which is stored
1079    in *PVAR.  *PVAR may be bitsize_zero_node.  All operations must be of
1080    bitsizetype.  */
1081
1082 static tree
1083 split_plus (tree in, tree *pvar)
1084 {
1085   /* Strip NOPS in order to ease the tree traversal and maximize the
1086      potential for constant or plus/minus discovery. We need to be careful
1087      to always return and set *pvar to bitsizetype trees, but it's worth
1088      the effort.  */
1089   STRIP_NOPS (in);
1090
1091   *pvar = convert (bitsizetype, in);
1092
1093   if (TREE_CODE (in) == INTEGER_CST)
1094     {
1095       *pvar = bitsize_zero_node;
1096       return convert (bitsizetype, in);
1097     }
1098   else if (TREE_CODE (in) == PLUS_EXPR || TREE_CODE (in) == MINUS_EXPR)
1099     {
1100       tree lhs_var, rhs_var;
1101       tree lhs_con = split_plus (TREE_OPERAND (in, 0), &lhs_var);
1102       tree rhs_con = split_plus (TREE_OPERAND (in, 1), &rhs_var);
1103
1104       if (lhs_var == TREE_OPERAND (in, 0)
1105           && rhs_var == TREE_OPERAND (in, 1))
1106         return bitsize_zero_node;
1107
1108       *pvar = size_binop (TREE_CODE (in), lhs_var, rhs_var);
1109       return size_binop (TREE_CODE (in), lhs_con, rhs_con);
1110     }
1111   else
1112     return bitsize_zero_node;
1113 }
1114 \f
1115 /* Return a FUNCTION_TYPE node. RETURN_TYPE is the type returned by the
1116    subprogram. If it is void_type_node, then we are dealing with a procedure,
1117    otherwise we are dealing with a function. PARAM_DECL_LIST is a list of
1118    PARM_DECL nodes that are the subprogram arguments.  CICO_LIST is the
1119    copy-in/copy-out list to be stored into TYPE_CICO_LIST.
1120    RETURNS_UNCONSTRAINED is nonzero if the function returns an unconstrained
1121    object.  RETURNS_BY_REF is nonzero if the function returns by reference.
1122    RETURNS_WITH_DSP is nonzero if the function is to return with a
1123    depressed stack pointer.  RETURNS_BY_TARGET_PTR is true if the function
1124    is to be passed (as its first parameter) the address of the place to copy
1125    its result.  */
1126
1127 tree
1128 create_subprog_type (tree return_type, tree param_decl_list, tree cico_list,
1129                      bool returns_unconstrained, bool returns_by_ref,
1130                      bool returns_with_dsp, bool returns_by_target_ptr)
1131 {
1132   /* A chain of TREE_LIST nodes whose TREE_VALUEs are the data type nodes of
1133      the subprogram formal parameters. This list is generated by traversing the
1134      input list of PARM_DECL nodes.  */
1135   tree param_type_list = NULL;
1136   tree param_decl;
1137   tree type;
1138
1139   for (param_decl = param_decl_list; param_decl;
1140        param_decl = TREE_CHAIN (param_decl))
1141     param_type_list = tree_cons (NULL_TREE, TREE_TYPE (param_decl),
1142                                  param_type_list);
1143
1144   /* The list of the function parameter types has to be terminated by the void
1145      type to signal to the back-end that we are not dealing with a variable
1146      parameter subprogram, but that the subprogram has a fixed number of
1147      parameters.  */
1148   param_type_list = tree_cons (NULL_TREE, void_type_node, param_type_list);
1149
1150   /* The list of argument types has been created in reverse
1151      so nreverse it.   */
1152   param_type_list = nreverse (param_type_list);
1153
1154   type = build_function_type (return_type, param_type_list);
1155
1156   /* TYPE may have been shared since GCC hashes types.  If it has a CICO_LIST
1157      or the new type should, make a copy of TYPE.  Likewise for
1158      RETURNS_UNCONSTRAINED and RETURNS_BY_REF.  */
1159   if (TYPE_CI_CO_LIST (type) || cico_list
1160       || TYPE_RETURNS_UNCONSTRAINED_P (type) != returns_unconstrained
1161       || TYPE_RETURNS_BY_REF_P (type) != returns_by_ref
1162       || TYPE_RETURNS_BY_TARGET_PTR_P (type) != returns_by_target_ptr)
1163     type = copy_type (type);
1164
1165   TYPE_CI_CO_LIST (type) = cico_list;
1166   TYPE_RETURNS_UNCONSTRAINED_P (type) = returns_unconstrained;
1167   TYPE_RETURNS_STACK_DEPRESSED (type) = returns_with_dsp;
1168   TYPE_RETURNS_BY_REF_P (type) = returns_by_ref;
1169   TYPE_RETURNS_BY_TARGET_PTR_P (type) = returns_by_target_ptr;
1170   return type;
1171 }
1172 \f
1173 /* Return a copy of TYPE but safe to modify in any way.  */
1174
1175 tree
1176 copy_type (tree type)
1177 {
1178   tree new = copy_node (type);
1179
1180   /* copy_node clears this field instead of copying it, because it is
1181      aliased with TREE_CHAIN.  */
1182   TYPE_STUB_DECL (new) = TYPE_STUB_DECL (type);
1183
1184   TYPE_POINTER_TO (new) = 0;
1185   TYPE_REFERENCE_TO (new) = 0;
1186   TYPE_MAIN_VARIANT (new) = new;
1187   TYPE_NEXT_VARIANT (new) = 0;
1188
1189   return new;
1190 }
1191 \f
1192 /* Return an INTEGER_TYPE of SIZETYPE with range MIN to MAX and whose
1193    TYPE_INDEX_TYPE is INDEX.  */
1194
1195 tree
1196 create_index_type (tree min, tree max, tree index)
1197 {
1198   /* First build a type for the desired range.  */
1199   tree type = build_index_2_type (min, max);
1200
1201   /* If this type has the TYPE_INDEX_TYPE we want, return it.  Otherwise, if it
1202      doesn't have TYPE_INDEX_TYPE set, set it to INDEX.  If TYPE_INDEX_TYPE
1203      is set, but not to INDEX, make a copy of this type with the requested
1204      index type.  Note that we have no way of sharing these types, but that's
1205      only a small hole.  */
1206   if (TYPE_INDEX_TYPE (type) == index)
1207     return type;
1208   else if (TYPE_INDEX_TYPE (type))
1209     type = copy_type (type);
1210
1211   SET_TYPE_INDEX_TYPE (type, index);
1212   create_type_decl (NULL_TREE, type, NULL, true, false, Empty);
1213   return type;
1214 }
1215 \f
1216 /* Return a TYPE_DECL node. TYPE_NAME gives the name of the type (a character
1217    string) and TYPE is a ..._TYPE node giving its data type.
1218    ARTIFICIAL_P is true if this is a declaration that was generated
1219    by the compiler.  DEBUG_INFO_P is true if we need to write debugging
1220    information about this type.  GNAT_NODE is used for the position of
1221    the decl.  */
1222
1223 tree
1224 create_type_decl (tree type_name, tree type, struct attrib *attr_list,
1225                   bool artificial_p, bool debug_info_p, Node_Id gnat_node)
1226 {
1227   tree type_decl = build_decl (TYPE_DECL, type_name, type);
1228   enum tree_code code = TREE_CODE (type);
1229
1230   DECL_ARTIFICIAL (type_decl) = artificial_p;
1231
1232   process_attributes (type_decl, attr_list);
1233
1234   /* Pass type declaration information to the debugger unless this is an
1235      UNCONSTRAINED_ARRAY_TYPE, which the debugger does not support,
1236      and ENUMERAL_TYPE or RECORD_TYPE which is handled separately, or
1237      type for which debugging information was not requested.  */
1238   if (code == UNCONSTRAINED_ARRAY_TYPE || ! debug_info_p)
1239     DECL_IGNORED_P (type_decl) = 1;
1240   if (code == UNCONSTRAINED_ARRAY_TYPE || TYPE_IS_DUMMY_P (type)
1241       || !debug_info_p)
1242     DECL_IGNORED_P (type_decl) = 1;
1243   else if (code != ENUMERAL_TYPE && code != RECORD_TYPE
1244            && !((code == POINTER_TYPE || code == REFERENCE_TYPE)
1245                 && TYPE_IS_DUMMY_P (TREE_TYPE (type))))
1246     rest_of_decl_compilation (type_decl, global_bindings_p (), 0);
1247
1248   if (!TYPE_IS_DUMMY_P (type))
1249     gnat_pushdecl (type_decl, gnat_node);
1250
1251   return type_decl;
1252 }
1253
1254 /* Returns a GCC VAR_DECL node. VAR_NAME gives the name of the variable.
1255    ASM_NAME is its assembler name (if provided).  TYPE is its data type
1256    (a GCC ..._TYPE node).  VAR_INIT is the GCC tree for an optional initial
1257    expression; NULL_TREE if none.
1258
1259    CONST_FLAG is true if this variable is constant.
1260
1261    PUBLIC_FLAG is true if this definition is to be made visible outside of
1262    the current compilation unit. This flag should be set when processing the
1263    variable definitions in a package specification.  EXTERN_FLAG is nonzero
1264    when processing an external variable declaration (as opposed to a
1265    definition: no storage is to be allocated for the variable here).
1266
1267    STATIC_FLAG is only relevant when not at top level.  In that case
1268    it indicates whether to always allocate storage to the variable.
1269
1270    GNAT_NODE is used for the position of the decl.  */
1271
1272 tree
1273 create_var_decl (tree var_name, tree asm_name, tree type, tree var_init,
1274                  bool const_flag, bool public_flag, bool extern_flag,
1275                  bool static_flag, struct attrib *attr_list, Node_Id gnat_node)
1276 {
1277   bool init_const
1278     = (!var_init
1279        ? false
1280        : (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (TREE_TYPE (var_init))
1281           && (global_bindings_p () || static_flag
1282               ? 0 != initializer_constant_valid_p (var_init,
1283                                                    TREE_TYPE (var_init))
1284               : TREE_CONSTANT (var_init))));
1285   tree var_decl
1286     = build_decl ((const_flag && init_const
1287                    /* Only make a CONST_DECL for sufficiently-small objects.
1288                       We consider complex double "sufficiently-small"  */
1289                    && TYPE_SIZE (type) != 0
1290                    && host_integerp (TYPE_SIZE_UNIT (type), 1)
1291                    && 0 >= compare_tree_int (TYPE_SIZE_UNIT (type),
1292                                              GET_MODE_SIZE (DCmode)))
1293                   ? CONST_DECL : VAR_DECL, var_name, type);
1294
1295   /* If this is external, throw away any initializations unless this is a
1296      CONST_DECL (meaning we have a constant); they will be done elsewhere.
1297      If we are defining a global here, leave a constant initialization and
1298      save any variable elaborations for the elaboration routine.  If we are
1299      just annotating types, throw away the initialization if it isn't a
1300      constant.  */
1301   if ((extern_flag && TREE_CODE (var_decl) != CONST_DECL)
1302       || (type_annotate_only && var_init && !TREE_CONSTANT (var_init)))
1303     var_init = NULL_TREE;
1304
1305   /* At the global level, an initializer requiring code to be generated
1306      produces elaboration statements.  Check that such statements are allowed,
1307      that is, not violating a No_Elaboration_Code restriction.  */
1308   if (global_bindings_p () && var_init != 0 && ! init_const)
1309     Check_Elaboration_Code_Allowed (gnat_node);
1310
1311   /* Ada doesn't feature Fortran-like COMMON variables so we shouldn't
1312      try to fiddle with DECL_COMMON.  However, on platforms that don't
1313      support global BSS sections, uninitialized global variables would
1314      go in DATA instead, thus increasing the size of the executable.  */
1315   if (!flag_no_common
1316       && TREE_CODE (var_decl) == VAR_DECL
1317       && !have_global_bss_p ())
1318     DECL_COMMON (var_decl) = 1;
1319   DECL_INITIAL  (var_decl) = var_init;
1320   TREE_READONLY (var_decl) = const_flag;
1321   DECL_EXTERNAL (var_decl) = extern_flag;
1322   TREE_PUBLIC   (var_decl) = public_flag || extern_flag;
1323   TREE_CONSTANT (var_decl) = TREE_CODE (var_decl) == CONST_DECL;
1324   TREE_THIS_VOLATILE (var_decl) = TREE_SIDE_EFFECTS (var_decl)
1325     = TYPE_VOLATILE (type);
1326
1327   /* If it's public and not external, always allocate storage for it.
1328      At the global binding level we need to allocate static storage for the
1329      variable if and only if it's not external. If we are not at the top level
1330      we allocate automatic storage unless requested not to.  */
1331   TREE_STATIC (var_decl)
1332     = public_flag || (global_bindings_p () ? !extern_flag : static_flag);
1333
1334   if (asm_name && VAR_OR_FUNCTION_DECL_P (var_decl))
1335     SET_DECL_ASSEMBLER_NAME (var_decl, asm_name);
1336
1337   process_attributes (var_decl, attr_list);
1338
1339   /* Add this decl to the current binding level.  */
1340   gnat_pushdecl (var_decl, gnat_node);
1341
1342   if (TREE_SIDE_EFFECTS (var_decl))
1343     TREE_ADDRESSABLE (var_decl) = 1;
1344
1345   if (TREE_CODE (var_decl) != CONST_DECL)
1346     rest_of_decl_compilation (var_decl, global_bindings_p (), 0);
1347   else
1348     /* expand CONST_DECLs to set their MODE, ALIGN, SIZE and SIZE_UNIT,
1349        which we need for later back-annotations.  */
1350     expand_decl (var_decl);
1351
1352   return var_decl;
1353 }
1354 \f
1355 /* Returns a FIELD_DECL node. FIELD_NAME the field name, FIELD_TYPE is its
1356    type, and RECORD_TYPE is the type of the parent.  PACKED is nonzero if
1357    this field is in a record type with a "pragma pack".  If SIZE is nonzero
1358    it is the specified size for this field.  If POS is nonzero, it is the bit
1359    position.  If ADDRESSABLE is nonzero, it means we are allowed to take
1360    the address of this field for aliasing purposes. If it is negative, we
1361    should not make a bitfield, which is used by make_aligning_type.   */
1362
1363 tree
1364 create_field_decl (tree field_name, tree field_type, tree record_type,
1365                    int packed, tree size, tree pos, int addressable)
1366 {
1367   tree field_decl = build_decl (FIELD_DECL, field_name, field_type);
1368
1369   DECL_CONTEXT (field_decl) = record_type;
1370   TREE_READONLY (field_decl) = TYPE_READONLY (field_type);
1371
1372   /* If FIELD_TYPE is BLKmode, we must ensure this is aligned to at least a
1373      byte boundary since GCC cannot handle less-aligned BLKmode bitfields.  */
1374   if (packed && TYPE_MODE (field_type) == BLKmode)
1375     DECL_ALIGN (field_decl) = BITS_PER_UNIT;
1376
1377   /* If a size is specified, use it.  Otherwise, if the record type is packed
1378      compute a size to use, which may differ from the object's natural size.
1379      We always set a size in this case to trigger the checks for bitfield
1380      creation below, which is typically required when no position has been
1381      specified.  */
1382   if (size)
1383     size = convert (bitsizetype, size);
1384   else if (packed == 1)
1385     {
1386       size = rm_size (field_type);
1387
1388       /* For a constant size larger than MAX_FIXED_MODE_SIZE, round up to
1389          byte.  */
1390       if (TREE_CODE (size) == INTEGER_CST
1391           && compare_tree_int (size, MAX_FIXED_MODE_SIZE) > 0)
1392         size = round_up (size, BITS_PER_UNIT);
1393     }
1394
1395   /* If we may, according to ADDRESSABLE, make a bitfield if a size is
1396      specified for two reasons: first if the size differs from the natural
1397      size.  Second, if the alignment is insufficient.  There are a number of
1398      ways the latter can be true.
1399
1400      We never make a bitfield if the type of the field has a nonconstant size,
1401      because no such entity requiring bitfield operations should reach here.
1402
1403      We do *preventively* make a bitfield when there might be the need for it
1404      but we don't have all the necessary information to decide, as is the case
1405      of a field with no specified position in a packed record.
1406
1407      We also don't look at STRICT_ALIGNMENT here, and rely on later processing
1408      in layout_decl or finish_record_type to clear the bit_field indication if
1409      it is in fact not needed.  */
1410   if (addressable >= 0
1411       && size
1412       && TREE_CODE (size) == INTEGER_CST
1413       && TREE_CODE (TYPE_SIZE (field_type)) == INTEGER_CST
1414       && (!operand_equal_p (TYPE_SIZE (field_type), size, 0)
1415           || (pos && !value_factor_p (pos, TYPE_ALIGN (field_type)))
1416           || packed
1417           || (TYPE_ALIGN (record_type) != 0
1418               && TYPE_ALIGN (record_type) < TYPE_ALIGN (field_type))))
1419     {
1420       DECL_BIT_FIELD (field_decl) = 1;
1421       DECL_SIZE (field_decl) = size;
1422       if (!packed && !pos)
1423         DECL_ALIGN (field_decl)
1424           = (TYPE_ALIGN (record_type) != 0
1425              ? MIN (TYPE_ALIGN (record_type), TYPE_ALIGN (field_type))
1426              : TYPE_ALIGN (field_type));
1427     }
1428
1429   DECL_PACKED (field_decl) = pos ? DECL_BIT_FIELD (field_decl) : packed;
1430   DECL_ALIGN (field_decl)
1431     = MAX (DECL_ALIGN (field_decl),
1432            DECL_BIT_FIELD (field_decl) ? 1
1433            : packed && TYPE_MODE (field_type) != BLKmode ? BITS_PER_UNIT
1434            : TYPE_ALIGN (field_type));
1435
1436   if (pos)
1437     {
1438       /* We need to pass in the alignment the DECL is known to have.
1439          This is the lowest-order bit set in POS, but no more than
1440          the alignment of the record, if one is specified.  Note
1441          that an alignment of 0 is taken as infinite.  */
1442       unsigned int known_align;
1443
1444       if (host_integerp (pos, 1))
1445         known_align = tree_low_cst (pos, 1) & - tree_low_cst (pos, 1);
1446       else
1447         known_align = BITS_PER_UNIT;
1448
1449       if (TYPE_ALIGN (record_type)
1450           && (known_align == 0 || known_align > TYPE_ALIGN (record_type)))
1451         known_align = TYPE_ALIGN (record_type);
1452
1453       layout_decl (field_decl, known_align);
1454       SET_DECL_OFFSET_ALIGN (field_decl,
1455                              host_integerp (pos, 1) ? BIGGEST_ALIGNMENT
1456                              : BITS_PER_UNIT);
1457       pos_from_bit (&DECL_FIELD_OFFSET (field_decl),
1458                     &DECL_FIELD_BIT_OFFSET (field_decl),
1459                     DECL_OFFSET_ALIGN (field_decl), pos);
1460
1461       DECL_HAS_REP_P (field_decl) = 1;
1462     }
1463
1464   /* If the field type is passed by reference, we will have pointers to the
1465      field, so it is addressable. */
1466   if (must_pass_by_ref (field_type) || default_pass_by_ref (field_type))
1467     addressable = 1;
1468
1469   /* ??? For now, we say that any field of aggregate type is addressable
1470      because the front end may take 'Reference of it.  */
1471   if (AGGREGATE_TYPE_P (field_type))
1472     addressable = 1;
1473
1474   /* Mark the decl as nonaddressable if it is indicated so semantically,
1475      meaning we won't ever attempt to take the address of the field.
1476
1477      It may also be "technically" nonaddressable, meaning that even if we
1478      attempt to take the field's address we will actually get the address of a
1479      copy. This is the case for true bitfields, but the DECL_BIT_FIELD value
1480      we have at this point is not accurate enough, so we don't account for
1481      this here and let finish_record_type decide.  */
1482   DECL_NONADDRESSABLE_P (field_decl) = !addressable;
1483
1484   return field_decl;
1485 }
1486
1487 /* Subroutine of previous function: return nonzero if EXP, ignoring any side
1488    effects, has the value of zero.  */
1489
1490 static bool
1491 value_zerop (tree exp)
1492 {
1493   if (TREE_CODE (exp) == COMPOUND_EXPR)
1494     return value_zerop (TREE_OPERAND (exp, 1));
1495
1496   return integer_zerop (exp);
1497 }
1498 \f
1499 /* Returns a PARM_DECL node. PARAM_NAME is the name of the parameter,
1500    PARAM_TYPE is its type.  READONLY is true if the parameter is
1501    readonly (either an IN parameter or an address of a pass-by-ref
1502    parameter). */
1503
1504 tree
1505 create_param_decl (tree param_name, tree param_type, bool readonly)
1506 {
1507   tree param_decl = build_decl (PARM_DECL, param_name, param_type);
1508
1509   /* Honor targetm.calls.promote_prototypes(), as not doing so can
1510      lead to various ABI violations.  */
1511   if (targetm.calls.promote_prototypes (param_type)
1512       && (TREE_CODE (param_type) == INTEGER_TYPE
1513           || TREE_CODE (param_type) == ENUMERAL_TYPE)
1514       && TYPE_PRECISION (param_type) < TYPE_PRECISION (integer_type_node))
1515     {
1516       /* We have to be careful about biased types here.  Make a subtype
1517          of integer_type_node with the proper biasing.  */
1518       if (TREE_CODE (param_type) == INTEGER_TYPE
1519           && TYPE_BIASED_REPRESENTATION_P (param_type))
1520         {
1521           param_type
1522             = copy_type (build_range_type (integer_type_node,
1523                                            TYPE_MIN_VALUE (param_type),
1524                                            TYPE_MAX_VALUE (param_type)));
1525
1526           TYPE_BIASED_REPRESENTATION_P (param_type) = 1;
1527         }
1528       else
1529         param_type = integer_type_node;
1530     }
1531
1532   DECL_ARG_TYPE (param_decl) = param_type;
1533   TREE_READONLY (param_decl) = readonly;
1534   return param_decl;
1535 }
1536 \f
1537 /* Given a DECL and ATTR_LIST, process the listed attributes.  */
1538
1539 void
1540 process_attributes (tree decl, struct attrib *attr_list)
1541 {
1542   for (; attr_list; attr_list = attr_list->next)
1543     switch (attr_list->type)
1544       {
1545       case ATTR_MACHINE_ATTRIBUTE:
1546         decl_attributes (&decl, tree_cons (attr_list->name, attr_list->args,
1547                                            NULL_TREE),
1548                          ATTR_FLAG_TYPE_IN_PLACE);
1549         break;
1550
1551       case ATTR_LINK_ALIAS:
1552         if (! DECL_EXTERNAL (decl))
1553           {
1554             TREE_STATIC (decl) = 1;
1555             assemble_alias (decl, attr_list->name);
1556           }
1557         break;
1558
1559       case ATTR_WEAK_EXTERNAL:
1560         if (SUPPORTS_WEAK)
1561           declare_weak (decl);
1562         else
1563           post_error ("?weak declarations not supported on this target",
1564                       attr_list->error_point);
1565         break;
1566
1567       case ATTR_LINK_SECTION:
1568         if (targetm.have_named_sections)
1569           {
1570             DECL_SECTION_NAME (decl)
1571               = build_string (IDENTIFIER_LENGTH (attr_list->name),
1572                               IDENTIFIER_POINTER (attr_list->name));
1573             DECL_COMMON (decl) = 0;
1574           }
1575         else
1576           post_error ("?section attributes are not supported for this target",
1577                       attr_list->error_point);
1578         break;
1579
1580       case ATTR_LINK_CONSTRUCTOR:
1581         DECL_STATIC_CONSTRUCTOR (decl) = 1;
1582         TREE_USED (decl) = 1;
1583         break;
1584
1585       case ATTR_LINK_DESTRUCTOR:
1586         DECL_STATIC_DESTRUCTOR (decl) = 1;
1587         TREE_USED (decl) = 1;
1588         break;
1589       }
1590 }
1591 \f
1592 /* Return true if VALUE is a known to be a multiple of FACTOR, which must be
1593    a power of 2. */
1594
1595 bool
1596 value_factor_p (tree value, HOST_WIDE_INT factor)
1597 {
1598   if (host_integerp (value, 1))
1599     return tree_low_cst (value, 1) % factor == 0;
1600
1601   if (TREE_CODE (value) == MULT_EXPR)
1602     return (value_factor_p (TREE_OPERAND (value, 0), factor)
1603             || value_factor_p (TREE_OPERAND (value, 1), factor));
1604
1605   return 0;
1606 }
1607
1608 /* Given 2 consecutive field decls PREV_FIELD and CURR_FIELD, return true
1609    unless we can prove these 2 fields are laid out in such a way that no gap
1610    exist between the end of PREV_FIELD and the beginning of CURR_FIELD.  OFFSET
1611    is the distance in bits between the end of PREV_FIELD and the starting
1612    position of CURR_FIELD. It is ignored if null. */
1613
1614 static bool
1615 potential_alignment_gap (tree prev_field, tree curr_field, tree offset)
1616 {
1617   /* If this is the first field of the record, there cannot be any gap */
1618   if (!prev_field)
1619     return false;
1620
1621   /* If the previous field is a union type, then return False: The only
1622      time when such a field is not the last field of the record is when
1623      there are other components at fixed positions after it (meaning there
1624      was a rep clause for every field), in which case we don't want the
1625      alignment constraint to override them. */
1626   if (TREE_CODE (TREE_TYPE (prev_field)) == QUAL_UNION_TYPE)
1627     return false;
1628
1629   /* If the distance between the end of prev_field and the beginning of
1630      curr_field is constant, then there is a gap if the value of this
1631      constant is not null. */
1632   if (offset && host_integerp (offset, 1))
1633     return !integer_zerop (offset);
1634
1635   /* If the size and position of the previous field are constant,
1636      then check the sum of this size and position. There will be a gap
1637      iff it is not multiple of the current field alignment. */
1638   if (host_integerp (DECL_SIZE (prev_field), 1)
1639       && host_integerp (bit_position (prev_field), 1))
1640     return ((tree_low_cst (bit_position (prev_field), 1)
1641              + tree_low_cst (DECL_SIZE (prev_field), 1))
1642             % DECL_ALIGN (curr_field) != 0);
1643
1644   /* If both the position and size of the previous field are multiples
1645      of the current field alignment, there cannot be any gap. */
1646   if (value_factor_p (bit_position (prev_field), DECL_ALIGN (curr_field))
1647       && value_factor_p (DECL_SIZE (prev_field), DECL_ALIGN (curr_field)))
1648     return false;
1649
1650   /* Fallback, return that there may be a potential gap */
1651   return true;
1652 }
1653
1654 /* Returns a LABEL_DECL node for LABEL_NAME.  */
1655
1656 tree
1657 create_label_decl (tree label_name)
1658 {
1659   tree label_decl = build_decl (LABEL_DECL, label_name, void_type_node);
1660
1661   DECL_CONTEXT (label_decl)     = current_function_decl;
1662   DECL_MODE (label_decl)        = VOIDmode;
1663   DECL_SOURCE_LOCATION (label_decl) = input_location;
1664
1665   return label_decl;
1666 }
1667 \f
1668 /* Returns a FUNCTION_DECL node.  SUBPROG_NAME is the name of the subprogram,
1669    ASM_NAME is its assembler name, SUBPROG_TYPE is its type (a FUNCTION_TYPE
1670    node), PARAM_DECL_LIST is the list of the subprogram arguments (a list of
1671    PARM_DECL nodes chained through the TREE_CHAIN field).
1672
1673    INLINE_FLAG, PUBLIC_FLAG, EXTERN_FLAG, and ATTR_LIST are used to set the
1674    appropriate fields in the FUNCTION_DECL.  GNAT_NODE gives the location.  */
1675
1676 tree
1677 create_subprog_decl (tree subprog_name, tree asm_name,
1678                      tree subprog_type, tree param_decl_list, bool inline_flag,
1679                      bool public_flag, bool extern_flag,
1680                      struct attrib *attr_list, Node_Id gnat_node)
1681 {
1682   tree return_type  = TREE_TYPE (subprog_type);
1683   tree subprog_decl = build_decl (FUNCTION_DECL, subprog_name, subprog_type);
1684
1685   /* If this is a function nested inside an inlined external function, it
1686      means we aren't going to compile the outer function unless it is
1687      actually inlined, so do the same for us.  */
1688   if (current_function_decl && DECL_INLINE (current_function_decl)
1689       && DECL_EXTERNAL (current_function_decl))
1690     extern_flag = true;
1691
1692   DECL_EXTERNAL (subprog_decl)  = extern_flag;
1693   TREE_PUBLIC (subprog_decl)    = public_flag;
1694   TREE_STATIC (subprog_decl)    = 1;
1695   TREE_READONLY (subprog_decl)  = TYPE_READONLY (subprog_type);
1696   TREE_THIS_VOLATILE (subprog_decl) = TYPE_VOLATILE (subprog_type);
1697   TREE_SIDE_EFFECTS (subprog_decl) = TYPE_VOLATILE (subprog_type);
1698   DECL_ARGUMENTS (subprog_decl) = param_decl_list;
1699   DECL_RESULT (subprog_decl)    = build_decl (RESULT_DECL, 0, return_type);
1700   DECL_ARTIFICIAL (DECL_RESULT (subprog_decl)) = 1;
1701   DECL_IGNORED_P (DECL_RESULT (subprog_decl)) = 1;
1702
1703   if (inline_flag)
1704     DECL_DECLARED_INLINE_P (subprog_decl) = 1;
1705
1706   if (asm_name)
1707     SET_DECL_ASSEMBLER_NAME (subprog_decl, asm_name);
1708
1709   process_attributes (subprog_decl, attr_list);
1710
1711   /* Add this decl to the current binding level.  */
1712   gnat_pushdecl (subprog_decl, gnat_node);
1713
1714   /* Output the assembler code and/or RTL for the declaration.  */
1715   rest_of_decl_compilation (subprog_decl, global_bindings_p (), 0);
1716
1717   return subprog_decl;
1718 }
1719 \f
1720 /* Set up the framework for generating code for SUBPROG_DECL, a subprogram
1721    body. This routine needs to be invoked before processing the declarations
1722    appearing in the subprogram.  */
1723
1724 void
1725 begin_subprog_body (tree subprog_decl)
1726 {
1727   tree param_decl;
1728
1729   current_function_decl = subprog_decl;
1730   announce_function (subprog_decl);
1731
1732   /* Enter a new binding level and show that all the parameters belong to
1733      this function.  */
1734   gnat_pushlevel ();
1735   for (param_decl = DECL_ARGUMENTS (subprog_decl); param_decl;
1736        param_decl = TREE_CHAIN (param_decl))
1737     DECL_CONTEXT (param_decl) = subprog_decl;
1738
1739   make_decl_rtl (subprog_decl);
1740
1741   /* We handle pending sizes via the elaboration of types, so we don't need to
1742      save them.  This causes them to be marked as part of the outer function
1743      and then discarded.  */
1744   get_pending_sizes ();
1745 }
1746
1747 /* Finish the definition of the current subprogram and compile it all the way
1748    to assembler language output.  BODY is the tree corresponding to
1749    the subprogram.  */
1750
1751 void
1752 end_subprog_body (tree body)
1753 {
1754   tree fndecl = current_function_decl;
1755
1756   /* Mark the BLOCK for this level as being for this function and pop the
1757      level.  Since the vars in it are the parameters, clear them.  */
1758   BLOCK_VARS (current_binding_level->block) = 0;
1759   BLOCK_SUPERCONTEXT (current_binding_level->block) = fndecl;
1760   DECL_INITIAL (fndecl) = current_binding_level->block;
1761   gnat_poplevel ();
1762
1763   /* Deal with inline.  If declared inline or we should default to inline,
1764      set the flag in the decl.  */
1765   DECL_INLINE (fndecl)
1766     = DECL_DECLARED_INLINE_P (fndecl) || flag_inline_trees == 2;
1767
1768   /* We handle pending sizes via the elaboration of types, so we don't
1769      need to save them.  */
1770   get_pending_sizes ();
1771
1772   /* Mark the RESULT_DECL as being in this subprogram. */
1773   DECL_CONTEXT (DECL_RESULT (fndecl)) = fndecl;
1774
1775   DECL_SAVED_TREE (fndecl) = body;
1776
1777   current_function_decl = DECL_CONTEXT (fndecl);
1778   cfun = NULL;
1779
1780   /* If we're only annotating types, don't actually compile this function.  */
1781   if (type_annotate_only)
1782     return;
1783
1784   /* If we don't have .ctors/.dtors sections, and this is a static
1785      constructor or destructor, it must be recorded now.  */
1786   if (DECL_STATIC_CONSTRUCTOR (fndecl) && !targetm.have_ctors_dtors)
1787     static_ctors = tree_cons (NULL_TREE, fndecl, static_ctors);
1788
1789   if (DECL_STATIC_DESTRUCTOR (fndecl) && !targetm.have_ctors_dtors)
1790     static_dtors = tree_cons (NULL_TREE, fndecl, static_dtors);
1791
1792   /* We do different things for nested and non-nested functions.
1793      ??? This should be in cgraph.  */
1794   if (!DECL_CONTEXT (fndecl))
1795     {
1796       gnat_gimplify_function (fndecl);
1797       cgraph_finalize_function (fndecl, false);
1798     }
1799   else
1800     /* Register this function with cgraph just far enough to get it
1801        added to our parent's nested function list.  */
1802     (void) cgraph_node (fndecl);
1803 }
1804
1805 /* Convert FNDECL's code to GIMPLE and handle any nested functions.  */
1806
1807 static void
1808 gnat_gimplify_function (tree fndecl)
1809 {
1810   struct cgraph_node *cgn;
1811
1812   dump_function (TDI_original, fndecl);
1813   gimplify_function_tree (fndecl);
1814   dump_function (TDI_generic, fndecl);
1815
1816   /* Convert all nested functions to GIMPLE now.  We do things in this order
1817      so that items like VLA sizes are expanded properly in the context of the
1818      correct function.  */
1819   cgn = cgraph_node (fndecl);
1820   for (cgn = cgn->nested; cgn; cgn = cgn->next_nested)
1821     gnat_gimplify_function (cgn->decl);
1822 }
1823 \f
1824
1825 tree
1826 gnat_builtin_function (tree decl)
1827 {
1828   gnat_pushdecl (decl, Empty);
1829   return decl;
1830 }
1831
1832 /* Handle a "const" attribute; arguments as in
1833    struct attribute_spec.handler.  */
1834
1835 static tree
1836 handle_const_attribute (tree *node, tree ARG_UNUSED (name),
1837                         tree ARG_UNUSED (args), int ARG_UNUSED (flags),
1838                         bool *no_add_attrs)
1839 {
1840   if (TREE_CODE (*node) == FUNCTION_DECL)
1841     TREE_READONLY (*node) = 1;
1842   else
1843     *no_add_attrs = true;
1844
1845   return NULL_TREE;
1846 }
1847
1848 /* Handle a "nothrow" attribute; arguments as in
1849    struct attribute_spec.handler.  */
1850
1851 static tree
1852 handle_nothrow_attribute (tree *node, tree ARG_UNUSED (name),
1853                           tree ARG_UNUSED (args), int ARG_UNUSED (flags),
1854                           bool *no_add_attrs)
1855 {
1856   if (TREE_CODE (*node) == FUNCTION_DECL)
1857     TREE_NOTHROW (*node) = 1;
1858   else
1859     *no_add_attrs = true;
1860
1861   return NULL_TREE;
1862 }
1863
1864 /* Return an integer type with the number of bits of precision given by
1865    PRECISION.  UNSIGNEDP is nonzero if the type is unsigned; otherwise
1866    it is a signed type.  */
1867
1868 tree
1869 gnat_type_for_size (unsigned precision, int unsignedp)
1870 {
1871   tree t;
1872   char type_name[20];
1873
1874   if (precision <= 2 * MAX_BITS_PER_WORD
1875       && signed_and_unsigned_types[precision][unsignedp])
1876     return signed_and_unsigned_types[precision][unsignedp];
1877
1878  if (unsignedp)
1879     t = make_unsigned_type (precision);
1880   else
1881     t = make_signed_type (precision);
1882
1883   if (precision <= 2 * MAX_BITS_PER_WORD)
1884     signed_and_unsigned_types[precision][unsignedp] = t;
1885
1886   if (!TYPE_NAME (t))
1887     {
1888       sprintf (type_name, "%sSIGNED_%d", unsignedp ? "UN" : "", precision);
1889       TYPE_NAME (t) = get_identifier (type_name);
1890     }
1891
1892   return t;
1893 }
1894
1895 /* Likewise for floating-point types.  */
1896
1897 static tree
1898 float_type_for_precision (int precision, enum machine_mode mode)
1899 {
1900   tree t;
1901   char type_name[20];
1902
1903   if (float_types[(int) mode])
1904     return float_types[(int) mode];
1905
1906   float_types[(int) mode] = t = make_node (REAL_TYPE);
1907   TYPE_PRECISION (t) = precision;
1908   layout_type (t);
1909
1910   gcc_assert (TYPE_MODE (t) == mode);
1911   if (!TYPE_NAME (t))
1912     {
1913       sprintf (type_name, "FLOAT_%d", precision);
1914       TYPE_NAME (t) = get_identifier (type_name);
1915     }
1916
1917   return t;
1918 }
1919
1920 /* Return a data type that has machine mode MODE.  UNSIGNEDP selects
1921    an unsigned type; otherwise a signed type is returned.  */
1922
1923 tree
1924 gnat_type_for_mode (enum machine_mode mode, int unsignedp)
1925 {
1926   if (mode == BLKmode)
1927     return NULL_TREE;
1928   else if (mode == VOIDmode)
1929     return void_type_node;
1930   else if (COMPLEX_MODE_P (mode))
1931     return NULL_TREE;
1932   else if (SCALAR_FLOAT_MODE_P (mode))
1933     return float_type_for_precision (GET_MODE_PRECISION (mode), mode);
1934   else if (SCALAR_INT_MODE_P (mode))
1935     return gnat_type_for_size (GET_MODE_BITSIZE (mode), unsignedp);
1936   else
1937     return NULL_TREE;
1938 }
1939
1940 /* Return the unsigned version of a TYPE_NODE, a scalar type.  */
1941
1942 tree
1943 gnat_unsigned_type (tree type_node)
1944 {
1945   tree type = gnat_type_for_size (TYPE_PRECISION (type_node), 1);
1946
1947   if (TREE_CODE (type_node) == INTEGER_TYPE && TYPE_MODULAR_P (type_node))
1948     {
1949       type = copy_node (type);
1950       TREE_TYPE (type) = type_node;
1951     }
1952   else if (TREE_TYPE (type_node)
1953            && TREE_CODE (TREE_TYPE (type_node)) == INTEGER_TYPE
1954            && TYPE_MODULAR_P (TREE_TYPE (type_node)))
1955     {
1956       type = copy_node (type);
1957       TREE_TYPE (type) = TREE_TYPE (type_node);
1958     }
1959
1960   return type;
1961 }
1962
1963 /* Return the signed version of a TYPE_NODE, a scalar type.  */
1964
1965 tree
1966 gnat_signed_type (tree type_node)
1967 {
1968   tree type = gnat_type_for_size (TYPE_PRECISION (type_node), 0);
1969
1970   if (TREE_CODE (type_node) == INTEGER_TYPE && TYPE_MODULAR_P (type_node))
1971     {
1972       type = copy_node (type);
1973       TREE_TYPE (type) = type_node;
1974     }
1975   else if (TREE_TYPE (type_node)
1976            && TREE_CODE (TREE_TYPE (type_node)) == INTEGER_TYPE
1977            && TYPE_MODULAR_P (TREE_TYPE (type_node)))
1978     {
1979       type = copy_node (type);
1980       TREE_TYPE (type) = TREE_TYPE (type_node);
1981     }
1982
1983   return type;
1984 }
1985
1986 /* Return a type the same as TYPE except unsigned or signed according to
1987    UNSIGNEDP.  */
1988
1989 tree
1990 gnat_signed_or_unsigned_type (int unsignedp, tree type)
1991 {
1992   if (!INTEGRAL_TYPE_P (type) || TYPE_UNSIGNED (type) == unsignedp)
1993     return type;
1994   else
1995     return gnat_type_for_size (TYPE_PRECISION (type), unsignedp);
1996 }
1997 \f
1998 /* EXP is an expression for the size of an object.  If this size contains
1999    discriminant references, replace them with the maximum (if MAX_P) or
2000    minimum (if !MAX_P) possible value of the discriminant.  */
2001
2002 tree
2003 max_size (tree exp, bool max_p)
2004 {
2005   enum tree_code code = TREE_CODE (exp);
2006   tree type = TREE_TYPE (exp);
2007
2008   switch (TREE_CODE_CLASS (code))
2009     {
2010     case tcc_declaration:
2011     case tcc_constant:
2012       return exp;
2013
2014     case tcc_exceptional:
2015       if (code == TREE_LIST)
2016         return tree_cons (TREE_PURPOSE (exp),
2017                           max_size (TREE_VALUE (exp), max_p),
2018                           TREE_CHAIN (exp)
2019                           ? max_size (TREE_CHAIN (exp), max_p) : NULL_TREE);
2020       break;
2021
2022     case tcc_reference:
2023       /* If this contains a PLACEHOLDER_EXPR, it is the thing we want to
2024          modify.  Otherwise, we treat it like a variable.  */
2025       if (!CONTAINS_PLACEHOLDER_P (exp))
2026         return exp;
2027
2028       type = TREE_TYPE (TREE_OPERAND (exp, 1));
2029       return
2030         max_size (max_p ? TYPE_MAX_VALUE (type) : TYPE_MIN_VALUE (type), true);
2031
2032     case tcc_comparison:
2033       return max_p ? size_one_node : size_zero_node;
2034
2035     case tcc_unary:
2036     case tcc_binary:
2037     case tcc_expression:
2038       switch (TREE_CODE_LENGTH (code))
2039         {
2040         case 1:
2041           if (code == NON_LVALUE_EXPR)
2042             return max_size (TREE_OPERAND (exp, 0), max_p);
2043           else
2044             return
2045               fold (build1 (code, type,
2046                             max_size (TREE_OPERAND (exp, 0),
2047                                       code == NEGATE_EXPR ? !max_p : max_p)));
2048
2049         case 2:
2050           if (code == COMPOUND_EXPR)
2051             return max_size (TREE_OPERAND (exp, 1), max_p);
2052
2053           /* Calculate "(A ? B : C) - D" as "A ? B - D : C - D" which
2054              may provide a tighter bound on max_size.  */
2055           if (code == MINUS_EXPR
2056               && TREE_CODE (TREE_OPERAND (exp, 0)) == COND_EXPR)
2057             {
2058               tree lhs = fold_build2 (MINUS_EXPR, type,
2059                                       TREE_OPERAND (TREE_OPERAND (exp, 0), 1),
2060                                       TREE_OPERAND (exp, 1));
2061               tree rhs = fold_build2 (MINUS_EXPR, type,
2062                                       TREE_OPERAND (TREE_OPERAND (exp, 0), 2),
2063                                       TREE_OPERAND (exp, 1));
2064               return fold_build2 (max_p ? MAX_EXPR : MIN_EXPR, type,
2065                                   max_size (lhs, max_p),
2066                                   max_size (rhs, max_p));
2067             }
2068
2069           {
2070             tree lhs = max_size (TREE_OPERAND (exp, 0), max_p);
2071             tree rhs = max_size (TREE_OPERAND (exp, 1),
2072                                  code == MINUS_EXPR ? !max_p : max_p);
2073
2074             /* Special-case wanting the maximum value of a MIN_EXPR.
2075                In that case, if one side overflows, return the other.
2076                sizetype is signed, but we know sizes are non-negative.
2077                Likewise, handle a MINUS_EXPR or PLUS_EXPR with the LHS
2078                overflowing or the maximum possible value and the RHS
2079                a variable.  */
2080             if (max_p
2081                 && code == MIN_EXPR
2082                 && TREE_CODE (rhs) == INTEGER_CST
2083                 && TREE_OVERFLOW (rhs))
2084               return lhs;
2085             else if (max_p
2086                      && code == MIN_EXPR
2087                      && TREE_CODE (lhs) == INTEGER_CST
2088                      && TREE_OVERFLOW (lhs))
2089               return rhs;
2090             else if ((code == MINUS_EXPR || code == PLUS_EXPR)
2091                      && ((TREE_CODE (lhs) == INTEGER_CST
2092                           && TREE_OVERFLOW (lhs))
2093                          || operand_equal_p (lhs, TYPE_MAX_VALUE (type), 0))
2094                      && !TREE_CONSTANT (rhs))
2095               return lhs;
2096             else
2097               return fold (build2 (code, type, lhs, rhs));
2098           }
2099
2100         case 3:
2101           if (code == SAVE_EXPR)
2102             return exp;
2103           else if (code == COND_EXPR)
2104             return fold (build2 (max_p ? MAX_EXPR : MIN_EXPR, type,
2105                                  max_size (TREE_OPERAND (exp, 1), max_p),
2106                                  max_size (TREE_OPERAND (exp, 2), max_p)));
2107           else if (code == CALL_EXPR && TREE_OPERAND (exp, 1))
2108             return build3 (CALL_EXPR, type, TREE_OPERAND (exp, 0),
2109                            max_size (TREE_OPERAND (exp, 1), max_p), NULL);
2110         }
2111
2112       /* Other tree classes cannot happen.  */
2113     default:
2114       break;
2115     }
2116
2117   gcc_unreachable ();
2118 }
2119 \f
2120 /* Build a template of type TEMPLATE_TYPE from the array bounds of ARRAY_TYPE.
2121    EXPR is an expression that we can use to locate any PLACEHOLDER_EXPRs.
2122    Return a constructor for the template.  */
2123
2124 tree
2125 build_template (tree template_type, tree array_type, tree expr)
2126 {
2127   tree template_elts = NULL_TREE;
2128   tree bound_list = NULL_TREE;
2129   tree field;
2130
2131   if (TREE_CODE (array_type) == RECORD_TYPE
2132       && (TYPE_IS_PADDING_P (array_type)
2133           || TYPE_JUSTIFIED_MODULAR_P (array_type)))
2134     array_type = TREE_TYPE (TYPE_FIELDS (array_type));
2135
2136   if (TREE_CODE (array_type) == ARRAY_TYPE
2137       || (TREE_CODE (array_type) == INTEGER_TYPE
2138           && TYPE_HAS_ACTUAL_BOUNDS_P (array_type)))
2139     bound_list = TYPE_ACTUAL_BOUNDS (array_type);
2140
2141   /* First make the list for a CONSTRUCTOR for the template.   Go down the
2142      field list of the template instead of the type chain because this
2143      array might be an Ada array of arrays and we can't tell where the
2144      nested arrays stop being the underlying object.  */
2145
2146   for (field = TYPE_FIELDS (template_type); field;
2147        (bound_list
2148         ? (bound_list = TREE_CHAIN (bound_list))
2149         : (array_type = TREE_TYPE (array_type))),
2150        field = TREE_CHAIN (TREE_CHAIN (field)))
2151     {
2152       tree bounds, min, max;
2153
2154       /* If we have a bound list, get the bounds from there.  Likewise
2155          for an ARRAY_TYPE.  Otherwise, if expr is a PARM_DECL with
2156          DECL_BY_COMPONENT_PTR_P, use the bounds of the field in the template.
2157          This will give us a maximum range.  */
2158       if (bound_list)
2159         bounds = TREE_VALUE (bound_list);
2160       else if (TREE_CODE (array_type) == ARRAY_TYPE)
2161         bounds = TYPE_INDEX_TYPE (TYPE_DOMAIN (array_type));
2162       else if (expr && TREE_CODE (expr) == PARM_DECL
2163                && DECL_BY_COMPONENT_PTR_P (expr))
2164         bounds = TREE_TYPE (field);
2165       else
2166         gcc_unreachable ();
2167
2168       min = convert (TREE_TYPE (TREE_CHAIN (field)), TYPE_MIN_VALUE (bounds));
2169       max = convert (TREE_TYPE (field), TYPE_MAX_VALUE (bounds));
2170
2171       /* If either MIN or MAX involve a PLACEHOLDER_EXPR, we must
2172          substitute it from OBJECT.  */
2173       min = SUBSTITUTE_PLACEHOLDER_IN_EXPR (min, expr);
2174       max = SUBSTITUTE_PLACEHOLDER_IN_EXPR (max, expr);
2175
2176       template_elts = tree_cons (TREE_CHAIN (field), max,
2177                                  tree_cons (field, min, template_elts));
2178     }
2179
2180   return gnat_build_constructor (template_type, nreverse (template_elts));
2181 }
2182 \f
2183 /* Build a VMS descriptor from a Mechanism_Type, which must specify
2184    a descriptor type, and the GCC type of an object.  Each FIELD_DECL
2185    in the type contains in its DECL_INITIAL the expression to use when
2186    a constructor is made for the type.  GNAT_ENTITY is an entity used
2187    to print out an error message if the mechanism cannot be applied to
2188    an object of that type and also for the name.  */
2189
2190 tree
2191 build_vms_descriptor (tree type, Mechanism_Type mech, Entity_Id gnat_entity)
2192 {
2193   tree record_type = make_node (RECORD_TYPE);
2194   tree field_list = 0;
2195   int class;
2196   int dtype = 0;
2197   tree inner_type;
2198   int ndim;
2199   int i;
2200   tree *idx_arr;
2201   tree tem;
2202
2203   /* If TYPE is an unconstrained array, use the underlying array type.  */
2204   if (TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE)
2205     type = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (type))));
2206
2207   /* If this is an array, compute the number of dimensions in the array,
2208      get the index types, and point to the inner type.  */
2209   if (TREE_CODE (type) != ARRAY_TYPE)
2210     ndim = 0;
2211   else
2212     for (ndim = 1, inner_type = type;
2213          TREE_CODE (TREE_TYPE (inner_type)) == ARRAY_TYPE
2214          && TYPE_MULTI_ARRAY_P (TREE_TYPE (inner_type));
2215          ndim++, inner_type = TREE_TYPE (inner_type))
2216       ;
2217
2218   idx_arr = (tree *) alloca (ndim * sizeof (tree));
2219
2220   if (mech != By_Descriptor_NCA
2221       && TREE_CODE (type) == ARRAY_TYPE && TYPE_CONVENTION_FORTRAN_P (type))
2222     for (i = ndim - 1, inner_type = type;
2223          i >= 0;
2224          i--, inner_type = TREE_TYPE (inner_type))
2225       idx_arr[i] = TYPE_DOMAIN (inner_type);
2226   else
2227     for (i = 0, inner_type = type;
2228          i < ndim;
2229          i++, inner_type = TREE_TYPE (inner_type))
2230       idx_arr[i] = TYPE_DOMAIN (inner_type);
2231
2232   /* Now get the DTYPE value.  */
2233   switch (TREE_CODE (type))
2234     {
2235     case INTEGER_TYPE:
2236     case ENUMERAL_TYPE:
2237       if (TYPE_VAX_FLOATING_POINT_P (type))
2238         switch (tree_low_cst (TYPE_DIGITS_VALUE (type), 1))
2239           {
2240           case 6:
2241             dtype = 10;
2242             break;
2243           case 9:
2244             dtype = 11;
2245             break;
2246           case 15:
2247             dtype = 27;
2248             break;
2249           }
2250       else
2251         switch (GET_MODE_BITSIZE (TYPE_MODE (type)))
2252           {
2253           case 8:
2254             dtype = TYPE_UNSIGNED (type) ? 2 : 6;
2255             break;
2256           case 16:
2257             dtype = TYPE_UNSIGNED (type) ? 3 : 7;
2258             break;
2259           case 32:
2260             dtype = TYPE_UNSIGNED (type) ? 4 : 8;
2261             break;
2262           case 64:
2263             dtype = TYPE_UNSIGNED (type) ? 5 : 9;
2264             break;
2265           case 128:
2266             dtype = TYPE_UNSIGNED (type) ? 25 : 26;
2267             break;
2268           }
2269       break;
2270
2271     case REAL_TYPE:
2272       dtype = GET_MODE_BITSIZE (TYPE_MODE (type)) == 32 ? 52 : 53;
2273       break;
2274
2275     case COMPLEX_TYPE:
2276       if (TREE_CODE (TREE_TYPE (type)) == INTEGER_TYPE
2277           && TYPE_VAX_FLOATING_POINT_P (type))
2278         switch (tree_low_cst (TYPE_DIGITS_VALUE (type), 1))
2279           {
2280           case 6:
2281             dtype = 12;
2282             break;
2283           case 9:
2284             dtype = 13;
2285             break;
2286           case 15:
2287             dtype = 29;
2288           }
2289       else
2290         dtype = GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (type))) == 32 ? 54: 55;
2291       break;
2292
2293     case ARRAY_TYPE:
2294       dtype = 14;
2295       break;
2296
2297     default:
2298       break;
2299     }
2300
2301   /* Get the CLASS value.  */
2302   switch (mech)
2303     {
2304     case By_Descriptor_A:
2305       class = 4;
2306       break;
2307     case By_Descriptor_NCA:
2308       class = 10;
2309       break;
2310     case By_Descriptor_SB:
2311       class = 15;
2312       break;
2313     default:
2314       class = 1;
2315     }
2316
2317   /* Make the type for a descriptor for VMS.  The first four fields
2318      are the same for all types.  */
2319
2320   field_list
2321     = chainon (field_list,
2322                make_descriptor_field
2323                ("LENGTH", gnat_type_for_size (16, 1), record_type,
2324                 size_in_bytes (mech == By_Descriptor_A ? inner_type : type)));
2325
2326   field_list = chainon (field_list,
2327                         make_descriptor_field ("DTYPE",
2328                                                gnat_type_for_size (8, 1),
2329                                                record_type, size_int (dtype)));
2330   field_list = chainon (field_list,
2331                         make_descriptor_field ("CLASS",
2332                                                gnat_type_for_size (8, 1),
2333                                                record_type, size_int (class)));
2334
2335   field_list
2336     = chainon (field_list,
2337                make_descriptor_field
2338                ("POINTER",
2339                 build_pointer_type_for_mode (type, SImode, false), record_type,
2340                 build1 (ADDR_EXPR,
2341                         build_pointer_type_for_mode (type, SImode, false),
2342                         build0 (PLACEHOLDER_EXPR, type))));
2343
2344   switch (mech)
2345     {
2346     case By_Descriptor:
2347     case By_Descriptor_S:
2348       break;
2349
2350     case By_Descriptor_SB:
2351       field_list
2352         = chainon (field_list,
2353                    make_descriptor_field
2354                    ("SB_L1", gnat_type_for_size (32, 1), record_type,
2355                     TREE_CODE (type) == ARRAY_TYPE
2356                     ? TYPE_MIN_VALUE (TYPE_DOMAIN (type)) : size_zero_node));
2357       field_list
2358         = chainon (field_list,
2359                    make_descriptor_field
2360                    ("SB_L2", gnat_type_for_size (32, 1), record_type,
2361                     TREE_CODE (type) == ARRAY_TYPE
2362                     ? TYPE_MAX_VALUE (TYPE_DOMAIN (type)) : size_zero_node));
2363       break;
2364
2365     case By_Descriptor_A:
2366     case By_Descriptor_NCA:
2367       field_list = chainon (field_list,
2368                             make_descriptor_field ("SCALE",
2369                                                    gnat_type_for_size (8, 1),
2370                                                    record_type,
2371                                                    size_zero_node));
2372
2373       field_list = chainon (field_list,
2374                             make_descriptor_field ("DIGITS",
2375                                                    gnat_type_for_size (8, 1),
2376                                                    record_type,
2377                                                    size_zero_node));
2378
2379       field_list
2380         = chainon (field_list,
2381                    make_descriptor_field
2382                    ("AFLAGS", gnat_type_for_size (8, 1), record_type,
2383                     size_int (mech == By_Descriptor_NCA
2384                               ? 0
2385                               /* Set FL_COLUMN, FL_COEFF, and FL_BOUNDS.  */
2386                               : (TREE_CODE (type) == ARRAY_TYPE
2387                                  && TYPE_CONVENTION_FORTRAN_P (type)
2388                                  ? 224 : 192))));
2389
2390       field_list = chainon (field_list,
2391                             make_descriptor_field ("DIMCT",
2392                                                    gnat_type_for_size (8, 1),
2393                                                    record_type,
2394                                                    size_int (ndim)));
2395
2396       field_list = chainon (field_list,
2397                             make_descriptor_field ("ARSIZE",
2398                                                    gnat_type_for_size (32, 1),
2399                                                    record_type,
2400                                                    size_in_bytes (type)));
2401
2402       /* Now build a pointer to the 0,0,0... element.  */
2403       tem = build0 (PLACEHOLDER_EXPR, type);
2404       for (i = 0, inner_type = type; i < ndim;
2405            i++, inner_type = TREE_TYPE (inner_type))
2406         tem = build4 (ARRAY_REF, TREE_TYPE (inner_type), tem,
2407                       convert (TYPE_DOMAIN (inner_type), size_zero_node),
2408                       NULL_TREE, NULL_TREE);
2409
2410       field_list
2411         = chainon (field_list,
2412                    make_descriptor_field
2413                    ("A0",
2414                     build_pointer_type_for_mode (inner_type, SImode, false),
2415                     record_type,
2416                     build1 (ADDR_EXPR,
2417                             build_pointer_type_for_mode (inner_type, SImode,
2418                                                          false),
2419                             tem)));
2420
2421       /* Next come the addressing coefficients.  */
2422       tem = size_int (1);
2423       for (i = 0; i < ndim; i++)
2424         {
2425           char fname[3];
2426           tree idx_length
2427             = size_binop (MULT_EXPR, tem,
2428                           size_binop (PLUS_EXPR,
2429                                       size_binop (MINUS_EXPR,
2430                                                   TYPE_MAX_VALUE (idx_arr[i]),
2431                                                   TYPE_MIN_VALUE (idx_arr[i])),
2432                                       size_int (1)));
2433
2434           fname[0] = (mech == By_Descriptor_NCA ? 'S' : 'M');
2435           fname[1] = '0' + i, fname[2] = 0;
2436           field_list
2437             = chainon (field_list,
2438                        make_descriptor_field (fname,
2439                                               gnat_type_for_size (32, 1),
2440                                               record_type, idx_length));
2441
2442           if (mech == By_Descriptor_NCA)
2443             tem = idx_length;
2444         }
2445
2446       /* Finally here are the bounds.  */
2447       for (i = 0; i < ndim; i++)
2448         {
2449           char fname[3];
2450
2451           fname[0] = 'L', fname[1] = '0' + i, fname[2] = 0;
2452           field_list
2453             = chainon (field_list,
2454                        make_descriptor_field
2455                        (fname, gnat_type_for_size (32, 1), record_type,
2456                         TYPE_MIN_VALUE (idx_arr[i])));
2457
2458           fname[0] = 'U';
2459           field_list
2460             = chainon (field_list,
2461                        make_descriptor_field
2462                        (fname, gnat_type_for_size (32, 1), record_type,
2463                         TYPE_MAX_VALUE (idx_arr[i])));
2464         }
2465       break;
2466
2467     default:
2468       post_error ("unsupported descriptor type for &", gnat_entity);
2469     }
2470
2471   finish_record_type (record_type, field_list, false, true);
2472   create_type_decl (create_concat_name (gnat_entity, "DESC"), record_type,
2473                     NULL, true, false, gnat_entity);
2474
2475   return record_type;
2476 }
2477
2478 /* Utility routine for above code to make a field.  */
2479
2480 static tree
2481 make_descriptor_field (const char *name, tree type,
2482                        tree rec_type, tree initial)
2483 {
2484   tree field
2485     = create_field_decl (get_identifier (name), type, rec_type, 0, 0, 0, 0);
2486
2487   DECL_INITIAL (field) = initial;
2488   return field;
2489 }
2490 \f
2491 /* Build a type to be used to represent an aliased object whose nominal
2492    type is an unconstrained array.  This consists of a RECORD_TYPE containing
2493    a field of TEMPLATE_TYPE and a field of OBJECT_TYPE, which is an
2494    ARRAY_TYPE.  If ARRAY_TYPE is that of the unconstrained array, this
2495    is used to represent an arbitrary unconstrained object.  Use NAME
2496    as the name of the record.  */
2497
2498 tree
2499 build_unc_object_type (tree template_type, tree object_type, tree name)
2500 {
2501   tree type = make_node (RECORD_TYPE);
2502   tree template_field = create_field_decl (get_identifier ("BOUNDS"),
2503                                            template_type, type, 0, 0, 0, 1);
2504   tree array_field = create_field_decl (get_identifier ("ARRAY"), object_type,
2505                                         type, 0, 0, 0, 1);
2506
2507   TYPE_NAME (type) = name;
2508   TYPE_CONTAINS_TEMPLATE_P (type) = 1;
2509   finish_record_type (type,
2510                       chainon (chainon (NULL_TREE, template_field),
2511                                array_field),
2512                       false, false);
2513
2514   return type;
2515 }
2516
2517 /* Same, taking a thin or fat pointer type instead of a template type. */
2518
2519 tree
2520 build_unc_object_type_from_ptr (tree thin_fat_ptr_type, tree object_type,
2521                                 tree name)
2522 {
2523   tree template_type;
2524
2525   gcc_assert (TYPE_FAT_OR_THIN_POINTER_P (thin_fat_ptr_type));
2526
2527   template_type
2528     = (TYPE_FAT_POINTER_P (thin_fat_ptr_type)
2529        ? TREE_TYPE (TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (thin_fat_ptr_type))))
2530        : TREE_TYPE (TYPE_FIELDS (TREE_TYPE (thin_fat_ptr_type))));
2531   return build_unc_object_type (template_type, object_type, name);
2532 }
2533 \f
2534 /* Update anything previously pointing to OLD_TYPE to point to NEW_TYPE.  In
2535    the normal case this is just two adjustments, but we have more to do
2536    if NEW is an UNCONSTRAINED_ARRAY_TYPE.  */
2537
2538 void
2539 update_pointer_to (tree old_type, tree new_type)
2540 {
2541   tree ptr = TYPE_POINTER_TO (old_type);
2542   tree ref = TYPE_REFERENCE_TO (old_type);
2543   tree ptr1, ref1;
2544   tree type;
2545
2546   /* If this is the main variant, process all the other variants first.  */
2547   if (TYPE_MAIN_VARIANT (old_type) == old_type)
2548     for (type = TYPE_NEXT_VARIANT (old_type); type;
2549          type = TYPE_NEXT_VARIANT (type))
2550       update_pointer_to (type, new_type);
2551
2552   /* If no pointer or reference, we are done.  */
2553   if (!ptr && !ref)
2554     return;
2555
2556   /* Merge the old type qualifiers in the new type.
2557
2558      Each old variant has qualifiers for specific reasons, and the new
2559      designated type as well. Each set of qualifiers represents useful
2560      information grabbed at some point, and merging the two simply unifies
2561      these inputs into the final type description.
2562
2563      Consider for instance a volatile type frozen after an access to constant
2564      type designating it. After the designated type freeze, we get here with a
2565      volatile new_type and a dummy old_type with a readonly variant, created
2566      when the access type was processed. We shall make a volatile and readonly
2567      designated type, because that's what it really is.
2568
2569      We might also get here for a non-dummy old_type variant with different
2570      qualifiers than the new_type ones, for instance in some cases of pointers
2571      to private record type elaboration (see the comments around the call to
2572      this routine from gnat_to_gnu_entity/E_Access_Type). We have to merge the
2573      qualifiers in thoses cases too, to avoid accidentally discarding the
2574      initial set, and will often end up with old_type == new_type then.  */
2575   new_type = build_qualified_type (new_type,
2576                                    TYPE_QUALS (old_type)
2577                                    | TYPE_QUALS (new_type));
2578
2579   /* If the new type and the old one are identical, there is nothing to
2580      update.  */
2581   if (old_type == new_type)
2582     return;
2583
2584   /* Otherwise, first handle the simple case.  */
2585   if (TREE_CODE (new_type) != UNCONSTRAINED_ARRAY_TYPE)
2586     {
2587       TYPE_POINTER_TO (new_type) = ptr;
2588       TYPE_REFERENCE_TO (new_type) = ref;
2589
2590       for (; ptr; ptr = TYPE_NEXT_PTR_TO (ptr))
2591         for (ptr1 = TYPE_MAIN_VARIANT (ptr); ptr1;
2592              ptr1 = TYPE_NEXT_VARIANT (ptr1))
2593           TREE_TYPE (ptr1) = new_type;
2594
2595       for (; ref; ref = TYPE_NEXT_REF_TO (ref))
2596         for (ref1 = TYPE_MAIN_VARIANT (ref); ref1;
2597              ref1 = TYPE_NEXT_VARIANT (ref1))
2598           TREE_TYPE (ref1) = new_type;
2599     }
2600
2601   /* Now deal with the unconstrained array case. In this case the "pointer"
2602      is actually a RECORD_TYPE where the types of both fields are
2603      pointers to void.  In that case, copy the field list from the
2604      old type to the new one and update the fields' context. */
2605   else if (TREE_CODE (ptr) != RECORD_TYPE || !TYPE_IS_FAT_POINTER_P (ptr))
2606     gcc_unreachable ();
2607
2608   else
2609     {
2610       tree new_obj_rec = TYPE_OBJECT_RECORD_TYPE (new_type);
2611       tree ptr_temp_type;
2612       tree new_ref;
2613       tree var;
2614
2615       SET_DECL_ORIGINAL_FIELD (TYPE_FIELDS (ptr),
2616                                TYPE_FIELDS (TYPE_POINTER_TO (new_type)));
2617       SET_DECL_ORIGINAL_FIELD (TREE_CHAIN (TYPE_FIELDS (ptr)),
2618                                TREE_CHAIN (TYPE_FIELDS
2619                                            (TYPE_POINTER_TO (new_type))));
2620
2621       TYPE_FIELDS (ptr) = TYPE_FIELDS (TYPE_POINTER_TO (new_type));
2622       DECL_CONTEXT (TYPE_FIELDS (ptr)) = ptr;
2623       DECL_CONTEXT (TREE_CHAIN (TYPE_FIELDS (ptr))) = ptr;
2624
2625       /* Rework the PLACEHOLDER_EXPR inside the reference to the
2626          template bounds.
2627
2628          ??? This is now the only use of gnat_substitute_in_type, which
2629          is now a very "heavy" routine to do this, so it should be replaced
2630          at some point.  */
2631       ptr_temp_type = TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (ptr)));
2632       new_ref = build3 (COMPONENT_REF, ptr_temp_type,
2633                         build0 (PLACEHOLDER_EXPR, ptr),
2634                         TREE_CHAIN (TYPE_FIELDS (ptr)), NULL_TREE);
2635
2636       update_pointer_to
2637         (TREE_TYPE (TREE_TYPE (TYPE_FIELDS (ptr))),
2638          gnat_substitute_in_type (TREE_TYPE (TREE_TYPE (TYPE_FIELDS (ptr))),
2639                                   TREE_CHAIN (TYPE_FIELDS (ptr)), new_ref));
2640
2641       for (var = TYPE_MAIN_VARIANT (ptr); var; var = TYPE_NEXT_VARIANT (var))
2642         {
2643           SET_TYPE_UNCONSTRAINED_ARRAY (var, new_type);
2644
2645           /* This may seem a bit gross, in particular wrt DECL_CONTEXT, but
2646              actually is in keeping with what build_qualified_type does.  */
2647           TYPE_FIELDS (var) = TYPE_FIELDS (ptr);
2648         }
2649
2650       TYPE_POINTER_TO (new_type) = TYPE_REFERENCE_TO (new_type)
2651         = TREE_TYPE (new_type) = ptr;
2652
2653       /* Now handle updating the allocation record, what the thin pointer
2654          points to.  Update all pointers from the old record into the new
2655          one, update the types of the fields, and recompute the size.  */
2656
2657       update_pointer_to (TYPE_OBJECT_RECORD_TYPE (old_type), new_obj_rec);
2658
2659       TREE_TYPE (TYPE_FIELDS (new_obj_rec)) = TREE_TYPE (ptr_temp_type);
2660       TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (new_obj_rec)))
2661         = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (ptr)));
2662       DECL_SIZE (TREE_CHAIN (TYPE_FIELDS (new_obj_rec)))
2663         = TYPE_SIZE (TREE_TYPE (TREE_TYPE (TYPE_FIELDS (ptr))));
2664       DECL_SIZE_UNIT (TREE_CHAIN (TYPE_FIELDS (new_obj_rec)))
2665         = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (TYPE_FIELDS (ptr))));
2666
2667       TYPE_SIZE (new_obj_rec)
2668         = size_binop (PLUS_EXPR,
2669                       DECL_SIZE (TYPE_FIELDS (new_obj_rec)),
2670                       DECL_SIZE (TREE_CHAIN (TYPE_FIELDS (new_obj_rec))));
2671       TYPE_SIZE_UNIT (new_obj_rec)
2672         = size_binop (PLUS_EXPR,
2673                       DECL_SIZE_UNIT (TYPE_FIELDS (new_obj_rec)),
2674                       DECL_SIZE_UNIT (TREE_CHAIN (TYPE_FIELDS (new_obj_rec))));
2675       rest_of_type_compilation (ptr, global_bindings_p ());
2676     }
2677 }
2678 \f
2679 /* Convert a pointer to a constrained array into a pointer to a fat
2680    pointer.  This involves making or finding a template.  */
2681
2682 static tree
2683 convert_to_fat_pointer (tree type, tree expr)
2684 {
2685   tree template_type = TREE_TYPE (TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (type))));
2686   tree template, template_addr;
2687   tree etype = TREE_TYPE (expr);
2688
2689   /* If EXPR is a constant of zero, we make a fat pointer that has a null
2690      pointer to the template and array.  */
2691   if (integer_zerop (expr))
2692     return
2693       gnat_build_constructor
2694         (type,
2695          tree_cons (TYPE_FIELDS (type),
2696                     convert (TREE_TYPE (TYPE_FIELDS (type)), expr),
2697                     tree_cons (TREE_CHAIN (TYPE_FIELDS (type)),
2698                                convert (build_pointer_type (template_type),
2699                                         expr),
2700                                NULL_TREE)));
2701
2702   /* If EXPR is a thin pointer, make the template and data from the record.  */
2703
2704   else if (TYPE_THIN_POINTER_P (etype))
2705     {
2706       tree fields = TYPE_FIELDS (TREE_TYPE (etype));
2707
2708       expr = save_expr (expr);
2709       if (TREE_CODE (expr) == ADDR_EXPR)
2710         expr = TREE_OPERAND (expr, 0);
2711       else
2712         expr = build1 (INDIRECT_REF, TREE_TYPE (etype), expr);
2713
2714       template = build_component_ref (expr, NULL_TREE, fields, false);
2715       expr = build_unary_op (ADDR_EXPR, NULL_TREE,
2716                              build_component_ref (expr, NULL_TREE,
2717                                                   TREE_CHAIN (fields), false));
2718     }
2719   else
2720     /* Otherwise, build the constructor for the template.  */
2721     template = build_template (template_type, TREE_TYPE (etype), expr);
2722
2723   template_addr = build_unary_op (ADDR_EXPR, NULL_TREE, template);
2724
2725   /* The result is a CONSTRUCTOR for the fat pointer.
2726
2727      If expr is an argument of a foreign convention subprogram, the type it
2728      points to is directly the component type. In this case, the expression
2729      type may not match the corresponding FIELD_DECL type at this point, so we
2730      call "convert" here to fix that up if necessary. This type consistency is
2731      required, for instance because it ensures that possible later folding of
2732      component_refs against this constructor always yields something of the
2733      same type as the initial reference.
2734
2735      Note that the call to "build_template" above is still fine, because it
2736      will only refer to the provided template_type in this case.  */
2737    return
2738      gnat_build_constructor
2739      (type, tree_cons (TYPE_FIELDS (type),
2740                       convert (TREE_TYPE (TYPE_FIELDS (type)), expr),
2741                       tree_cons (TREE_CHAIN (TYPE_FIELDS (type)),
2742                                  template_addr, NULL_TREE)));
2743 }
2744 \f
2745 /* Convert to a thin pointer type, TYPE.  The only thing we know how to convert
2746    is something that is a fat pointer, so convert to it first if it EXPR
2747    is not already a fat pointer.  */
2748
2749 static tree
2750 convert_to_thin_pointer (tree type, tree expr)
2751 {
2752   if (!TYPE_FAT_POINTER_P (TREE_TYPE (expr)))
2753     expr
2754       = convert_to_fat_pointer
2755         (TREE_TYPE (TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (type))), expr);
2756
2757   /* We get the pointer to the data and use a NOP_EXPR to make it the
2758      proper GCC type.  */
2759   expr = build_component_ref (expr, NULL_TREE, TYPE_FIELDS (TREE_TYPE (expr)),
2760                               false);
2761   expr = build1 (NOP_EXPR, type, expr);
2762
2763   return expr;
2764 }
2765 \f
2766 /* Create an expression whose value is that of EXPR,
2767    converted to type TYPE.  The TREE_TYPE of the value
2768    is always TYPE.  This function implements all reasonable
2769    conversions; callers should filter out those that are
2770    not permitted by the language being compiled.  */
2771
2772 tree
2773 convert (tree type, tree expr)
2774 {
2775   enum tree_code code = TREE_CODE (type);
2776   tree etype = TREE_TYPE (expr);
2777   enum tree_code ecode = TREE_CODE (etype);
2778
2779   /* If EXPR is already the right type, we are done.  */
2780   if (type == etype)
2781     return expr;
2782
2783   /* If the input type has padding, remove it by doing a component reference
2784      to the field.  If the output type has padding, make a constructor
2785      to build the record.  If both input and output have padding and are
2786      of variable size, do this as an unchecked conversion.  */
2787   else if (ecode == RECORD_TYPE && code == RECORD_TYPE
2788       && TYPE_IS_PADDING_P (type) && TYPE_IS_PADDING_P (etype)
2789       && (!TREE_CONSTANT (TYPE_SIZE (type))
2790           || !TREE_CONSTANT (TYPE_SIZE (etype))))
2791     ;
2792   else if (ecode == RECORD_TYPE && TYPE_IS_PADDING_P (etype))
2793     {
2794       /* If we have just converted to this padded type, just get
2795          the inner expression.  */
2796       if (TREE_CODE (expr) == CONSTRUCTOR
2797           && !VEC_empty (constructor_elt, CONSTRUCTOR_ELTS (expr))
2798           && VEC_index (constructor_elt, CONSTRUCTOR_ELTS (expr), 0)->index
2799              == TYPE_FIELDS (etype))
2800         return VEC_index (constructor_elt, CONSTRUCTOR_ELTS (expr), 0)->value;
2801       else
2802         return convert (type,
2803                         build_component_ref (expr, NULL_TREE,
2804                                              TYPE_FIELDS (etype), false));
2805     }
2806   else if (code == RECORD_TYPE && TYPE_IS_PADDING_P (type))
2807     {
2808       /* If we previously converted from another type and our type is
2809          of variable size, remove the conversion to avoid the need for
2810          variable-size temporaries.  */
2811       if (TREE_CODE (expr) == VIEW_CONVERT_EXPR
2812           && !TREE_CONSTANT (TYPE_SIZE (type)))
2813         expr = TREE_OPERAND (expr, 0);
2814
2815       /* If we are just removing the padding from expr, convert the original
2816          object if we have variable size.  That will avoid the need
2817          for some variable-size temporaries.  */
2818       if (TREE_CODE (expr) == COMPONENT_REF
2819           && TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == RECORD_TYPE
2820           && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (expr, 0)))
2821           && !TREE_CONSTANT (TYPE_SIZE (type)))
2822         return convert (type, TREE_OPERAND (expr, 0));
2823
2824       /* If the result type is a padded type with a self-referentially-sized
2825          field and the expression type is a record, do this as an
2826          unchecked conversion.  */
2827       else if (TREE_CODE (etype) == RECORD_TYPE
2828                && CONTAINS_PLACEHOLDER_P (DECL_SIZE (TYPE_FIELDS (type))))
2829         return unchecked_convert (type, expr, false);
2830
2831       else
2832         return
2833           gnat_build_constructor (type,
2834                              tree_cons (TYPE_FIELDS (type),
2835                                         convert (TREE_TYPE
2836                                                  (TYPE_FIELDS (type)),
2837                                                  expr),
2838                                         NULL_TREE));
2839     }
2840
2841   /* If the input is a biased type, adjust first.  */
2842   if (ecode == INTEGER_TYPE && TYPE_BIASED_REPRESENTATION_P (etype))
2843     return convert (type, fold (build2 (PLUS_EXPR, TREE_TYPE (etype),
2844                                         fold_convert (TREE_TYPE (etype),
2845                                                       expr),
2846                                         TYPE_MIN_VALUE (etype))));
2847
2848   /* If the input is a justified modular type, we need to extract the actual
2849      object before converting it to any other type with the exceptions of an
2850      unconstrained array or of a mere type variant.  It is useful to avoid the
2851      extraction and conversion in the type variant case because it could end
2852      up replacing a VAR_DECL expr by a constructor and we might be about the
2853      take the address of the result.  */
2854   if (ecode == RECORD_TYPE && TYPE_JUSTIFIED_MODULAR_P (etype)
2855       && code != UNCONSTRAINED_ARRAY_TYPE
2856       && TYPE_MAIN_VARIANT (type) != TYPE_MAIN_VARIANT (etype))
2857     return convert (type, build_component_ref (expr, NULL_TREE,
2858                                                TYPE_FIELDS (etype), false));
2859
2860   /* If converting to a type that contains a template, convert to the data
2861      type and then build the template. */
2862   if (code == RECORD_TYPE && TYPE_CONTAINS_TEMPLATE_P (type))
2863     {
2864       tree obj_type = TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (type)));
2865
2866       /* If the source already has a template, get a reference to the
2867          associated array only, as we are going to rebuild a template
2868          for the target type anyway.  */
2869       expr = maybe_unconstrained_array (expr);
2870
2871       return
2872         gnat_build_constructor
2873           (type,
2874            tree_cons (TYPE_FIELDS (type),
2875                       build_template (TREE_TYPE (TYPE_FIELDS (type)),
2876                                       obj_type, NULL_TREE),
2877                       tree_cons (TREE_CHAIN (TYPE_FIELDS (type)),
2878                                  convert (obj_type, expr), NULL_TREE)));
2879     }
2880
2881   /* There are some special cases of expressions that we process
2882      specially.  */
2883   switch (TREE_CODE (expr))
2884     {
2885     case ERROR_MARK:
2886       return expr;
2887
2888     case NULL_EXPR:
2889       /* Just set its type here.  For TRANSFORM_EXPR, we will do the actual
2890          conversion in gnat_expand_expr.  NULL_EXPR does not represent
2891          and actual value, so no conversion is needed.  */
2892       expr = copy_node (expr);
2893       TREE_TYPE (expr) = type;
2894       return expr;
2895
2896     case STRING_CST:
2897       /* If we are converting a STRING_CST to another constrained array type,
2898          just make a new one in the proper type.  */
2899       if (code == ecode && AGGREGATE_TYPE_P (etype)
2900           && !(TREE_CODE (TYPE_SIZE (etype)) == INTEGER_CST
2901                && TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST))
2902         {
2903           expr = copy_node (expr);
2904           TREE_TYPE (expr) = type;
2905           return expr;
2906         }
2907       break;
2908
2909     case UNCONSTRAINED_ARRAY_REF:
2910       /* Convert this to the type of the inner array by getting the address of
2911          the array from the template.  */
2912       expr = build_unary_op (INDIRECT_REF, NULL_TREE,
2913                              build_component_ref (TREE_OPERAND (expr, 0),
2914                                                   get_identifier ("P_ARRAY"),
2915                                                   NULL_TREE, false));
2916       etype = TREE_TYPE (expr);
2917       ecode = TREE_CODE (etype);
2918       break;
2919
2920     case VIEW_CONVERT_EXPR:
2921       {
2922         /* GCC 4.x is very sensitive to type consistency overall, and view
2923            conversions thus are very frequent.  Even though just "convert"ing
2924            the inner operand to the output type is fine in most cases, it
2925            might expose unexpected input/output type mismatches in special
2926            circumstances so we avoid such recursive calls when we can.  */
2927
2928         tree op0 = TREE_OPERAND (expr, 0);
2929
2930         /* If we are converting back to the original type, we can just
2931            lift the input conversion.  This is a common occurrence with
2932            switches back-and-forth amongst type variants.  */
2933         if (type == TREE_TYPE (op0))
2934           return op0;
2935
2936         /* Otherwise, if we're converting between two aggregate types, we
2937            might be allowed to substitute the VIEW_CONVERT target type in
2938            place or to just convert the inner expression.  */
2939         if (AGGREGATE_TYPE_P (type) && AGGREGATE_TYPE_P (etype))
2940           {
2941             /* If we are converting between type variants, we can just
2942                substitute the VIEW_CONVERT in place.  */
2943             if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (etype))
2944               return build1 (VIEW_CONVERT_EXPR, type, op0);
2945
2946             /* Otherwise, we may just bypass the input view conversion unless
2947                one of the types is a fat pointer,  which is handled by
2948                specialized code below which relies on exact type matching.  */
2949             else if (!TYPE_FAT_POINTER_P (type) && !TYPE_FAT_POINTER_P (etype))
2950               return convert (type, op0);
2951           }
2952       }
2953       break;
2954
2955     case INDIRECT_REF:
2956       /* If both types are record types, just convert the pointer and
2957          make a new INDIRECT_REF.
2958
2959          ??? Disable this for now since it causes problems with the
2960          code in build_binary_op for MODIFY_EXPR which wants to
2961          strip off conversions.  But that code really is a mess and
2962          we need to do this a much better way some time.  */
2963       if (0
2964           && (TREE_CODE (type) == RECORD_TYPE
2965               || TREE_CODE (type) == UNION_TYPE)
2966           && (TREE_CODE (etype) == RECORD_TYPE
2967               || TREE_CODE (etype) == UNION_TYPE)
2968           && !TYPE_FAT_POINTER_P (type) && !TYPE_FAT_POINTER_P (etype))
2969         return build_unary_op (INDIRECT_REF, NULL_TREE,
2970                                convert (build_pointer_type (type),
2971                                         TREE_OPERAND (expr, 0)));
2972       break;
2973
2974     default:
2975       break;
2976     }
2977
2978   /* Check for converting to a pointer to an unconstrained array.  */
2979   if (TYPE_FAT_POINTER_P (type) && !TYPE_FAT_POINTER_P (etype))
2980     return convert_to_fat_pointer (type, expr);
2981
2982   /* If we're converting between two aggregate types that have the same main
2983      variant, just make a VIEW_CONVER_EXPR.  */
2984   else if (AGGREGATE_TYPE_P (type)
2985            && TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (etype))
2986     return build1 (VIEW_CONVERT_EXPR, type, expr);
2987
2988   /* In all other cases of related types, make a NOP_EXPR.  */
2989   else if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (etype)
2990            || (code == INTEGER_CST && ecode == INTEGER_CST
2991                && (type == TREE_TYPE (etype) || etype == TREE_TYPE (type))))
2992     return fold_convert (type, expr);
2993
2994   switch (code)
2995     {
2996     case VOID_TYPE:
2997       return build1 (CONVERT_EXPR, type, expr);
2998
2999     case BOOLEAN_TYPE:
3000       return fold_convert (type, gnat_truthvalue_conversion (expr));
3001
3002     case INTEGER_TYPE:
3003       if (TYPE_HAS_ACTUAL_BOUNDS_P (type)
3004           && (ecode == ARRAY_TYPE || ecode == UNCONSTRAINED_ARRAY_TYPE
3005               || (ecode == RECORD_TYPE && TYPE_CONTAINS_TEMPLATE_P (etype))))
3006         return unchecked_convert (type, expr, false);
3007       else if (TYPE_BIASED_REPRESENTATION_P (type))
3008         return fold_convert (type,
3009                              fold_build2 (MINUS_EXPR, TREE_TYPE (type),
3010                                           convert (TREE_TYPE (type), expr),
3011                                           TYPE_MIN_VALUE (type)));
3012
3013       /* ... fall through ... */
3014
3015     case ENUMERAL_TYPE:
3016       return fold (convert_to_integer (type, expr));
3017
3018     case POINTER_TYPE:
3019     case REFERENCE_TYPE:
3020       /* If converting between two pointers to records denoting
3021          both a template and type, adjust if needed to account
3022          for any differing offsets, since one might be negative.  */
3023       if (TYPE_THIN_POINTER_P (etype) && TYPE_THIN_POINTER_P (type))
3024         {
3025           tree bit_diff
3026             = size_diffop (bit_position (TYPE_FIELDS (TREE_TYPE (etype))),
3027                            bit_position (TYPE_FIELDS (TREE_TYPE (type))));
3028           tree byte_diff = size_binop (CEIL_DIV_EXPR, bit_diff,
3029                                        sbitsize_int (BITS_PER_UNIT));
3030
3031           expr = build1 (NOP_EXPR, type, expr);
3032           TREE_CONSTANT (expr) = TREE_CONSTANT (TREE_OPERAND (expr, 0));
3033           if (integer_zerop (byte_diff))
3034             return expr;
3035
3036           return build_binary_op (PLUS_EXPR, type, expr,
3037                                   fold (convert_to_pointer (type, byte_diff)));
3038         }
3039
3040       /* If converting to a thin pointer, handle specially.  */
3041       if (TYPE_THIN_POINTER_P (type)
3042           && TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (type)))
3043         return convert_to_thin_pointer (type, expr);
3044
3045       /* If converting fat pointer to normal pointer, get the pointer to the
3046          array and then convert it.  */
3047       else if (TYPE_FAT_POINTER_P (etype))
3048         expr = build_component_ref (expr, get_identifier ("P_ARRAY"),
3049                                     NULL_TREE, false);
3050
3051       return fold (convert_to_pointer (type, expr));
3052
3053     case REAL_TYPE:
3054       return fold (convert_to_real (type, expr));
3055
3056     case RECORD_TYPE:
3057       if (TYPE_JUSTIFIED_MODULAR_P (type) && !AGGREGATE_TYPE_P (etype))
3058         return
3059           gnat_build_constructor
3060             (type, tree_cons (TYPE_FIELDS (type),
3061                               convert (TREE_TYPE (TYPE_FIELDS (type)), expr),
3062                               NULL_TREE));
3063
3064       /* ... fall through ... */
3065
3066     case ARRAY_TYPE:
3067       /* In these cases, assume the front-end has validated the conversion.
3068          If the conversion is valid, it will be a bit-wise conversion, so
3069          it can be viewed as an unchecked conversion.  */
3070       return unchecked_convert (type, expr, false);
3071
3072     case UNION_TYPE:
3073       /* This is a either a conversion between a tagged type and some
3074          subtype, which we have to mark as a UNION_TYPE because of
3075          overlapping fields or a conversion of an Unchecked_Union.  */
3076       return unchecked_convert (type, expr, false);
3077
3078     case UNCONSTRAINED_ARRAY_TYPE:
3079       /* If EXPR is a constrained array, take its address, convert it to a
3080          fat pointer, and then dereference it.  Likewise if EXPR is a
3081          record containing both a template and a constrained array.
3082          Note that a record representing a justified modular type
3083          always represents a packed constrained array.  */
3084       if (ecode == ARRAY_TYPE
3085           || (ecode == INTEGER_TYPE && TYPE_HAS_ACTUAL_BOUNDS_P (etype))
3086           || (ecode == RECORD_TYPE && TYPE_CONTAINS_TEMPLATE_P (etype))
3087           || (ecode == RECORD_TYPE && TYPE_JUSTIFIED_MODULAR_P (etype)))
3088         return
3089           build_unary_op
3090             (INDIRECT_REF, NULL_TREE,
3091              convert_to_fat_pointer (TREE_TYPE (type),
3092                                      build_unary_op (ADDR_EXPR,
3093                                                      NULL_TREE, expr)));
3094
3095       /* Do something very similar for converting one unconstrained
3096          array to another.  */
3097       else if (ecode == UNCONSTRAINED_ARRAY_TYPE)
3098         return
3099           build_unary_op (INDIRECT_REF, NULL_TREE,
3100                           convert (TREE_TYPE (type),
3101                                    build_unary_op (ADDR_EXPR,
3102                                                    NULL_TREE, expr)));
3103       else
3104         gcc_unreachable ();
3105
3106     case COMPLEX_TYPE:
3107       return fold (convert_to_complex (type, expr));
3108
3109     default:
3110       gcc_unreachable ();
3111     }
3112 }
3113 \f
3114 /* Remove all conversions that are done in EXP.  This includes converting
3115    from a padded type or to a justified modular type.  If TRUE_ADDRESS
3116    is true, always return the address of the containing object even if
3117    the address is not bit-aligned.  */
3118
3119 tree
3120 remove_conversions (tree exp, bool true_address)
3121 {
3122   switch (TREE_CODE (exp))
3123     {
3124     case CONSTRUCTOR:
3125       if (true_address
3126           && TREE_CODE (TREE_TYPE (exp)) == RECORD_TYPE
3127           && TYPE_JUSTIFIED_MODULAR_P (TREE_TYPE (exp)))
3128         return
3129           remove_conversions (VEC_index (constructor_elt,
3130                                          CONSTRUCTOR_ELTS (exp), 0)->value,
3131                               true);
3132       break;
3133
3134     case COMPONENT_REF:
3135       if (TREE_CODE (TREE_TYPE (TREE_OPERAND (exp, 0))) == RECORD_TYPE
3136           && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (exp, 0))))
3137         return remove_conversions (TREE_OPERAND (exp, 0), true_address);
3138       break;
3139
3140     case VIEW_CONVERT_EXPR:  case NON_LVALUE_EXPR:
3141     case NOP_EXPR:  case CONVERT_EXPR:
3142       return remove_conversions (TREE_OPERAND (exp, 0), true_address);
3143
3144     default:
3145       break;
3146     }
3147
3148   return exp;
3149 }
3150 \f
3151 /* If EXP's type is an UNCONSTRAINED_ARRAY_TYPE, return an expression that
3152    refers to the underlying array.  If its type has TYPE_CONTAINS_TEMPLATE_P,
3153    likewise return an expression pointing to the underlying array.  */
3154
3155 tree
3156 maybe_unconstrained_array (tree exp)
3157 {
3158   enum tree_code code = TREE_CODE (exp);
3159   tree new;
3160
3161   switch (TREE_CODE (TREE_TYPE (exp)))
3162     {
3163     case UNCONSTRAINED_ARRAY_TYPE:
3164       if (code == UNCONSTRAINED_ARRAY_REF)
3165         {
3166           new
3167             = build_unary_op (INDIRECT_REF, NULL_TREE,
3168                               build_component_ref (TREE_OPERAND (exp, 0),
3169                                                    get_identifier ("P_ARRAY"),
3170                                                    NULL_TREE, false));
3171           TREE_READONLY (new) = TREE_STATIC (new) = TREE_READONLY (exp);
3172           return new;
3173         }
3174
3175       else if (code == NULL_EXPR)
3176         return build1 (NULL_EXPR,
3177                        TREE_TYPE (TREE_TYPE (TYPE_FIELDS
3178                                              (TREE_TYPE (TREE_TYPE (exp))))),
3179                        TREE_OPERAND (exp, 0));
3180
3181     case RECORD_TYPE:
3182       /* If this is a padded type, convert to the unpadded type and see if
3183          it contains a template.  */
3184       if (TYPE_IS_PADDING_P (TREE_TYPE (exp)))
3185         {
3186           new = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (exp))), exp);
3187           if (TREE_CODE (TREE_TYPE (new)) == RECORD_TYPE
3188               && TYPE_CONTAINS_TEMPLATE_P (TREE_TYPE (new)))
3189             return
3190               build_component_ref (new, NULL_TREE,
3191                                    TREE_CHAIN (TYPE_FIELDS (TREE_TYPE (new))),
3192                                    0);
3193         }
3194       else if (TYPE_CONTAINS_TEMPLATE_P (TREE_TYPE (exp)))
3195         return
3196           build_component_ref (exp, NULL_TREE,
3197                                TREE_CHAIN (TYPE_FIELDS (TREE_TYPE (exp))), 0);
3198       break;
3199
3200     default:
3201       break;
3202     }
3203
3204   return exp;
3205 }
3206 \f
3207 /* Return an expression that does an unchecked conversion of EXPR to TYPE.
3208    If NOTRUNC_P is true, truncation operations should be suppressed.  */
3209
3210 tree
3211 unchecked_convert (tree type, tree expr, bool notrunc_p)
3212 {
3213   tree etype = TREE_TYPE (expr);
3214
3215   /* If the expression is already the right type, we are done.  */
3216   if (etype == type)
3217     return expr;
3218
3219   /* If both types types are integral just do a normal conversion.
3220      Likewise for a conversion to an unconstrained array.  */
3221   if ((((INTEGRAL_TYPE_P (type)
3222          && !(TREE_CODE (type) == INTEGER_TYPE
3223               && TYPE_VAX_FLOATING_POINT_P (type)))
3224         || (POINTER_TYPE_P (type) && ! TYPE_THIN_POINTER_P (type))
3225         || (TREE_CODE (type) == RECORD_TYPE
3226             && TYPE_JUSTIFIED_MODULAR_P (type)))
3227        && ((INTEGRAL_TYPE_P (etype)
3228             && !(TREE_CODE (etype) == INTEGER_TYPE
3229                  && TYPE_VAX_FLOATING_POINT_P (etype)))
3230            || (POINTER_TYPE_P (etype) && !TYPE_THIN_POINTER_P (etype))
3231            || (TREE_CODE (etype) == RECORD_TYPE
3232                && TYPE_JUSTIFIED_MODULAR_P (etype))))
3233       || TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE)
3234     {
3235       tree rtype = type;
3236
3237       if (TREE_CODE (etype) == INTEGER_TYPE
3238           && TYPE_BIASED_REPRESENTATION_P (etype))
3239         {
3240           tree ntype = copy_type (etype);
3241
3242           TYPE_BIASED_REPRESENTATION_P (ntype) = 0;
3243           TYPE_MAIN_VARIANT (ntype) = ntype;
3244           expr = build1 (NOP_EXPR, ntype, expr);
3245         }
3246
3247       if (TREE_CODE (type) == INTEGER_TYPE
3248           && TYPE_BIASED_REPRESENTATION_P (type))
3249         {
3250           rtype = copy_type (type);
3251           TYPE_BIASED_REPRESENTATION_P (rtype) = 0;
3252           TYPE_MAIN_VARIANT (rtype) = rtype;
3253         }
3254
3255       expr = convert (rtype, expr);
3256       if (type != rtype)
3257         expr = build1 (NOP_EXPR, type, expr);
3258     }
3259
3260   /* If we are converting TO an integral type whose precision is not the
3261      same as its size, first unchecked convert to a record that contains
3262      an object of the output type.  Then extract the field. */
3263   else if (INTEGRAL_TYPE_P (type) && TYPE_RM_SIZE (type)
3264            && 0 != compare_tree_int (TYPE_RM_SIZE (type),
3265                                      GET_MODE_BITSIZE (TYPE_MODE (type))))
3266     {
3267       tree rec_type = make_node (RECORD_TYPE);
3268       tree field = create_field_decl (get_identifier ("OBJ"), type,
3269                                       rec_type, 1, 0, 0, 0);
3270
3271       TYPE_FIELDS (rec_type) = field;
3272       layout_type (rec_type);
3273
3274       expr = unchecked_convert (rec_type, expr, notrunc_p);
3275       expr = build_component_ref (expr, NULL_TREE, field, 0);
3276     }
3277
3278   /* Similarly for integral input type whose precision is not equal to its
3279      size.  */
3280   else if (INTEGRAL_TYPE_P (etype) && TYPE_RM_SIZE (etype)
3281       && 0 != compare_tree_int (TYPE_RM_SIZE (etype),
3282                                 GET_MODE_BITSIZE (TYPE_MODE (etype))))
3283     {
3284       tree rec_type = make_node (RECORD_TYPE);
3285       tree field
3286         = create_field_decl (get_identifier ("OBJ"), etype, rec_type,
3287                              1, 0, 0, 0);
3288
3289       TYPE_FIELDS (rec_type) = field;
3290       layout_type (rec_type);
3291
3292       expr = gnat_build_constructor (rec_type, build_tree_list (field, expr));
3293       expr = unchecked_convert (type, expr, notrunc_p);
3294     }
3295
3296   /* We have a special case when we are converting between two
3297      unconstrained array types.  In that case, take the address,
3298      convert the fat pointer types, and dereference.  */
3299   else if (TREE_CODE (etype) == UNCONSTRAINED_ARRAY_TYPE
3300            && TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE)
3301     expr = build_unary_op (INDIRECT_REF, NULL_TREE,
3302                            build1 (VIEW_CONVERT_EXPR, TREE_TYPE (type),
3303                                    build_unary_op (ADDR_EXPR, NULL_TREE,
3304                                                    expr)));
3305   else
3306     {
3307       expr = maybe_unconstrained_array (expr);
3308
3309       /* There's no point in doing two unchecked conversions in a row.  */
3310       if (TREE_CODE (expr) == VIEW_CONVERT_EXPR)
3311         expr = TREE_OPERAND (expr, 0);
3312
3313       etype = TREE_TYPE (expr);
3314       expr = build1 (VIEW_CONVERT_EXPR, type, expr);
3315     }
3316
3317   /* If the result is an integral type whose size is not equal to
3318      the size of the underlying machine type, sign- or zero-extend
3319      the result.  We need not do this in the case where the input is
3320      an integral type of the same precision and signedness or if the output
3321      is a biased type or if both the input and output are unsigned.  */
3322   if (!notrunc_p
3323       && INTEGRAL_TYPE_P (type) && TYPE_RM_SIZE (type)
3324       && !(TREE_CODE (type) == INTEGER_TYPE
3325            && TYPE_BIASED_REPRESENTATION_P (type))
3326       && 0 != compare_tree_int (TYPE_RM_SIZE (type),
3327                                 GET_MODE_BITSIZE (TYPE_MODE (type)))
3328       && !(INTEGRAL_TYPE_P (etype)
3329            && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (etype)
3330            && operand_equal_p (TYPE_RM_SIZE (type),
3331                                (TYPE_RM_SIZE (etype) != 0
3332                                 ? TYPE_RM_SIZE (etype) : TYPE_SIZE (etype)),
3333                                0))
3334       && !(TYPE_UNSIGNED (type) && TYPE_UNSIGNED (etype)))
3335     {
3336       tree base_type = gnat_type_for_mode (TYPE_MODE (type),
3337                                            TYPE_UNSIGNED (type));
3338       tree shift_expr
3339         = convert (base_type,
3340                    size_binop (MINUS_EXPR,
3341                                bitsize_int
3342                                (GET_MODE_BITSIZE (TYPE_MODE (type))),
3343                                TYPE_RM_SIZE (type)));
3344       expr
3345         = convert (type,
3346                    build_binary_op (RSHIFT_EXPR, base_type,
3347                                     build_binary_op (LSHIFT_EXPR, base_type,
3348                                                      convert (base_type, expr),
3349                                                      shift_expr),
3350                                     shift_expr));
3351     }
3352
3353   /* An unchecked conversion should never raise Constraint_Error.  The code
3354      below assumes that GCC's conversion routines overflow the same way that
3355      the underlying hardware does.  This is probably true.  In the rare case
3356      when it is false, we can rely on the fact that such conversions are
3357      erroneous anyway.  */
3358   if (TREE_CODE (expr) == INTEGER_CST)
3359     TREE_OVERFLOW (expr) = TREE_CONSTANT_OVERFLOW (expr) = 0;
3360
3361   /* If the sizes of the types differ and this is an VIEW_CONVERT_EXPR,
3362      show no longer constant.  */
3363   if (TREE_CODE (expr) == VIEW_CONVERT_EXPR
3364       && !operand_equal_p (TYPE_SIZE_UNIT (type), TYPE_SIZE_UNIT (etype),
3365                            OEP_ONLY_CONST))
3366     TREE_CONSTANT (expr) = 0;
3367
3368   return expr;
3369 }
3370 \f
3371 /* Search the chain of currently reachable declarations for a builtin
3372    FUNCTION_DECL node corresponding to function NAME (an IDENTIFIER_NODE).
3373    Return the first node found, if any, or NULL_TREE otherwise.  */
3374
3375 tree
3376 builtin_decl_for (tree name __attribute__ ((unused)))
3377 {
3378   /* ??? not clear yet how to implement this function in tree-ssa, so
3379      return NULL_TREE for now */
3380   return NULL_TREE;
3381 }
3382
3383 #include "gt-ada-utils.h"
3384 #include "gtype-ada.h"