OSDN Git Service

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