OSDN Git Service

gcc/java/ChangeLog:
[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 \f
2311 /* EXP is an expression for the size of an object.  If this size contains
2312    discriminant references, replace them with the maximum (if MAX_P) or
2313    minimum (if !MAX_P) possible value of the discriminant.  */
2314
2315 tree
2316 max_size (tree exp, bool max_p)
2317 {
2318   enum tree_code code = TREE_CODE (exp);
2319   tree type = TREE_TYPE (exp);
2320
2321   switch (TREE_CODE_CLASS (code))
2322     {
2323     case tcc_declaration:
2324     case tcc_constant:
2325       return exp;
2326
2327     case tcc_vl_exp:
2328       if (code == CALL_EXPR)
2329         {
2330           tree *argarray;
2331           int i, n = call_expr_nargs (exp);
2332           gcc_assert (n > 0);
2333
2334           argarray = (tree *) alloca (n * sizeof (tree));
2335           for (i = 0; i < n; i++)
2336             argarray[i] = max_size (CALL_EXPR_ARG (exp, i), max_p);
2337           return build_call_array (type, CALL_EXPR_FN (exp), n, argarray);
2338         }
2339       break;
2340
2341     case tcc_reference:
2342       /* If this contains a PLACEHOLDER_EXPR, it is the thing we want to
2343          modify.  Otherwise, we treat it like a variable.  */
2344       if (!CONTAINS_PLACEHOLDER_P (exp))
2345         return exp;
2346
2347       type = TREE_TYPE (TREE_OPERAND (exp, 1));
2348       return
2349         max_size (max_p ? TYPE_MAX_VALUE (type) : TYPE_MIN_VALUE (type), true);
2350
2351     case tcc_comparison:
2352       return max_p ? size_one_node : size_zero_node;
2353
2354     case tcc_unary:
2355     case tcc_binary:
2356     case tcc_expression:
2357       switch (TREE_CODE_LENGTH (code))
2358         {
2359         case 1:
2360           if (code == NON_LVALUE_EXPR)
2361             return max_size (TREE_OPERAND (exp, 0), max_p);
2362           else
2363             return
2364               fold_build1 (code, type,
2365                            max_size (TREE_OPERAND (exp, 0),
2366                                      code == NEGATE_EXPR ? !max_p : max_p));
2367
2368         case 2:
2369           if (code == COMPOUND_EXPR)
2370             return max_size (TREE_OPERAND (exp, 1), max_p);
2371
2372           /* Calculate "(A ? B : C) - D" as "A ? B - D : C - D" which
2373              may provide a tighter bound on max_size.  */
2374           if (code == MINUS_EXPR
2375               && TREE_CODE (TREE_OPERAND (exp, 0)) == COND_EXPR)
2376             {
2377               tree lhs = fold_build2 (MINUS_EXPR, type,
2378                                       TREE_OPERAND (TREE_OPERAND (exp, 0), 1),
2379                                       TREE_OPERAND (exp, 1));
2380               tree rhs = fold_build2 (MINUS_EXPR, type,
2381                                       TREE_OPERAND (TREE_OPERAND (exp, 0), 2),
2382                                       TREE_OPERAND (exp, 1));
2383               return fold_build2 (max_p ? MAX_EXPR : MIN_EXPR, type,
2384                                   max_size (lhs, max_p),
2385                                   max_size (rhs, max_p));
2386             }
2387
2388           {
2389             tree lhs = max_size (TREE_OPERAND (exp, 0), max_p);
2390             tree rhs = max_size (TREE_OPERAND (exp, 1),
2391                                  code == MINUS_EXPR ? !max_p : max_p);
2392
2393             /* Special-case wanting the maximum value of a MIN_EXPR.
2394                In that case, if one side overflows, return the other.
2395                sizetype is signed, but we know sizes are non-negative.
2396                Likewise, handle a MINUS_EXPR or PLUS_EXPR with the LHS
2397                overflowing or the maximum possible value and the RHS
2398                a variable.  */
2399             if (max_p
2400                 && code == MIN_EXPR
2401                 && TREE_CODE (rhs) == INTEGER_CST
2402                 && TREE_OVERFLOW (rhs))
2403               return lhs;
2404             else if (max_p
2405                      && code == MIN_EXPR
2406                      && TREE_CODE (lhs) == INTEGER_CST
2407                      && TREE_OVERFLOW (lhs))
2408               return rhs;
2409             else if ((code == MINUS_EXPR || code == PLUS_EXPR)
2410                      && ((TREE_CODE (lhs) == INTEGER_CST
2411                           && TREE_OVERFLOW (lhs))
2412                          || operand_equal_p (lhs, TYPE_MAX_VALUE (type), 0))
2413                      && !TREE_CONSTANT (rhs))
2414               return lhs;
2415             else
2416               return fold_build2 (code, type, lhs, rhs);
2417           }
2418
2419         case 3:
2420           if (code == SAVE_EXPR)
2421             return exp;
2422           else if (code == COND_EXPR)
2423             return fold_build2 (max_p ? MAX_EXPR : MIN_EXPR, type,
2424                                 max_size (TREE_OPERAND (exp, 1), max_p),
2425                                 max_size (TREE_OPERAND (exp, 2), max_p));
2426         }
2427
2428       /* Other tree classes cannot happen.  */
2429     default:
2430       break;
2431     }
2432
2433   gcc_unreachable ();
2434 }
2435 \f
2436 /* Build a template of type TEMPLATE_TYPE from the array bounds of ARRAY_TYPE.
2437    EXPR is an expression that we can use to locate any PLACEHOLDER_EXPRs.
2438    Return a constructor for the template.  */
2439
2440 tree
2441 build_template (tree template_type, tree array_type, tree expr)
2442 {
2443   tree template_elts = NULL_TREE;
2444   tree bound_list = NULL_TREE;
2445   tree field;
2446
2447   if (TREE_CODE (array_type) == RECORD_TYPE
2448       && (TYPE_IS_PADDING_P (array_type)
2449           || TYPE_JUSTIFIED_MODULAR_P (array_type)))
2450     array_type = TREE_TYPE (TYPE_FIELDS (array_type));
2451
2452   if (TREE_CODE (array_type) == ARRAY_TYPE
2453       || (TREE_CODE (array_type) == INTEGER_TYPE
2454           && TYPE_HAS_ACTUAL_BOUNDS_P (array_type)))
2455     bound_list = TYPE_ACTUAL_BOUNDS (array_type);
2456
2457   /* First make the list for a CONSTRUCTOR for the template.   Go down the
2458      field list of the template instead of the type chain because this
2459      array might be an Ada array of arrays and we can't tell where the
2460      nested arrays stop being the underlying object.  */
2461
2462   for (field = TYPE_FIELDS (template_type); field;
2463        (bound_list
2464         ? (bound_list = TREE_CHAIN (bound_list))
2465         : (array_type = TREE_TYPE (array_type))),
2466        field = TREE_CHAIN (TREE_CHAIN (field)))
2467     {
2468       tree bounds, min, max;
2469
2470       /* If we have a bound list, get the bounds from there.  Likewise
2471          for an ARRAY_TYPE.  Otherwise, if expr is a PARM_DECL with
2472          DECL_BY_COMPONENT_PTR_P, use the bounds of the field in the template.
2473          This will give us a maximum range.  */
2474       if (bound_list)
2475         bounds = TREE_VALUE (bound_list);
2476       else if (TREE_CODE (array_type) == ARRAY_TYPE)
2477         bounds = TYPE_INDEX_TYPE (TYPE_DOMAIN (array_type));
2478       else if (expr && TREE_CODE (expr) == PARM_DECL
2479                && DECL_BY_COMPONENT_PTR_P (expr))
2480         bounds = TREE_TYPE (field);
2481       else
2482         gcc_unreachable ();
2483
2484       min = convert (TREE_TYPE (TREE_CHAIN (field)), TYPE_MIN_VALUE (bounds));
2485       max = convert (TREE_TYPE (field), TYPE_MAX_VALUE (bounds));
2486
2487       /* If either MIN or MAX involve a PLACEHOLDER_EXPR, we must
2488          substitute it from OBJECT.  */
2489       min = SUBSTITUTE_PLACEHOLDER_IN_EXPR (min, expr);
2490       max = SUBSTITUTE_PLACEHOLDER_IN_EXPR (max, expr);
2491
2492       template_elts = tree_cons (TREE_CHAIN (field), max,
2493                                  tree_cons (field, min, template_elts));
2494     }
2495
2496   return gnat_build_constructor (template_type, nreverse (template_elts));
2497 }
2498 \f
2499 /* Build a VMS descriptor from a Mechanism_Type, which must specify
2500    a descriptor type, and the GCC type of an object.  Each FIELD_DECL
2501    in the type contains in its DECL_INITIAL the expression to use when
2502    a constructor is made for the type.  GNAT_ENTITY is an entity used
2503    to print out an error message if the mechanism cannot be applied to
2504    an object of that type and also for the name.  */
2505
2506 tree
2507 build_vms_descriptor (tree type, Mechanism_Type mech, Entity_Id gnat_entity)
2508 {
2509   tree record_type = make_node (RECORD_TYPE);
2510   tree field_list = 0;
2511   int class;
2512   int dtype = 0;
2513   tree inner_type;
2514   int ndim;
2515   int i;
2516   tree *idx_arr;
2517   tree tem;
2518
2519   /* If TYPE is an unconstrained array, use the underlying array type.  */
2520   if (TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE)
2521     type = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (type))));
2522
2523   /* If this is an array, compute the number of dimensions in the array,
2524      get the index types, and point to the inner type.  */
2525   if (TREE_CODE (type) != ARRAY_TYPE)
2526     ndim = 0;
2527   else
2528     for (ndim = 1, inner_type = type;
2529          TREE_CODE (TREE_TYPE (inner_type)) == ARRAY_TYPE
2530          && TYPE_MULTI_ARRAY_P (TREE_TYPE (inner_type));
2531          ndim++, inner_type = TREE_TYPE (inner_type))
2532       ;
2533
2534   idx_arr = (tree *) alloca (ndim * sizeof (tree));
2535
2536   if (mech != By_Descriptor_NCA
2537       && TREE_CODE (type) == ARRAY_TYPE && TYPE_CONVENTION_FORTRAN_P (type))
2538     for (i = ndim - 1, inner_type = type;
2539          i >= 0;
2540          i--, inner_type = TREE_TYPE (inner_type))
2541       idx_arr[i] = TYPE_DOMAIN (inner_type);
2542   else
2543     for (i = 0, inner_type = type;
2544          i < ndim;
2545          i++, inner_type = TREE_TYPE (inner_type))
2546       idx_arr[i] = TYPE_DOMAIN (inner_type);
2547
2548   /* Now get the DTYPE value.  */
2549   switch (TREE_CODE (type))
2550     {
2551     case INTEGER_TYPE:
2552     case ENUMERAL_TYPE:
2553       if (TYPE_VAX_FLOATING_POINT_P (type))
2554         switch (tree_low_cst (TYPE_DIGITS_VALUE (type), 1))
2555           {
2556           case 6:
2557             dtype = 10;
2558             break;
2559           case 9:
2560             dtype = 11;
2561             break;
2562           case 15:
2563             dtype = 27;
2564             break;
2565           }
2566       else
2567         switch (GET_MODE_BITSIZE (TYPE_MODE (type)))
2568           {
2569           case 8:
2570             dtype = TYPE_UNSIGNED (type) ? 2 : 6;
2571             break;
2572           case 16:
2573             dtype = TYPE_UNSIGNED (type) ? 3 : 7;
2574             break;
2575           case 32:
2576             dtype = TYPE_UNSIGNED (type) ? 4 : 8;
2577             break;
2578           case 64:
2579             dtype = TYPE_UNSIGNED (type) ? 5 : 9;
2580             break;
2581           case 128:
2582             dtype = TYPE_UNSIGNED (type) ? 25 : 26;
2583             break;
2584           }
2585       break;
2586
2587     case REAL_TYPE:
2588       dtype = GET_MODE_BITSIZE (TYPE_MODE (type)) == 32 ? 52 : 53;
2589       break;
2590
2591     case COMPLEX_TYPE:
2592       if (TREE_CODE (TREE_TYPE (type)) == INTEGER_TYPE
2593           && TYPE_VAX_FLOATING_POINT_P (type))
2594         switch (tree_low_cst (TYPE_DIGITS_VALUE (type), 1))
2595           {
2596           case 6:
2597             dtype = 12;
2598             break;
2599           case 9:
2600             dtype = 13;
2601             break;
2602           case 15:
2603             dtype = 29;
2604           }
2605       else
2606         dtype = GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (type))) == 32 ? 54: 55;
2607       break;
2608
2609     case ARRAY_TYPE:
2610       dtype = 14;
2611       break;
2612
2613     default:
2614       break;
2615     }
2616
2617   /* Get the CLASS value.  */
2618   switch (mech)
2619     {
2620     case By_Descriptor_A:
2621       class = 4;
2622       break;
2623     case By_Descriptor_NCA:
2624       class = 10;
2625       break;
2626     case By_Descriptor_SB:
2627       class = 15;
2628       break;
2629     default:
2630       class = 1;
2631     }
2632
2633   /* Make the type for a descriptor for VMS.  The first four fields
2634      are the same for all types.  */
2635
2636   field_list
2637     = chainon (field_list,
2638                make_descriptor_field
2639                ("LENGTH", gnat_type_for_size (16, 1), record_type,
2640                 size_in_bytes (mech == By_Descriptor_A ? inner_type : type)));
2641
2642   field_list = chainon (field_list,
2643                         make_descriptor_field ("DTYPE",
2644                                                gnat_type_for_size (8, 1),
2645                                                record_type, size_int (dtype)));
2646   field_list = chainon (field_list,
2647                         make_descriptor_field ("CLASS",
2648                                                gnat_type_for_size (8, 1),
2649                                                record_type, size_int (class)));
2650
2651   field_list
2652     = chainon (field_list,
2653                make_descriptor_field
2654                ("POINTER",
2655                 build_pointer_type_for_mode (type, SImode, false), record_type,
2656                 build1 (ADDR_EXPR,
2657                         build_pointer_type_for_mode (type, SImode, false),
2658                         build0 (PLACEHOLDER_EXPR, type))));
2659
2660   switch (mech)
2661     {
2662     case By_Descriptor:
2663     case By_Descriptor_S:
2664       break;
2665
2666     case By_Descriptor_SB:
2667       field_list
2668         = chainon (field_list,
2669                    make_descriptor_field
2670                    ("SB_L1", gnat_type_for_size (32, 1), record_type,
2671                     TREE_CODE (type) == ARRAY_TYPE
2672                     ? TYPE_MIN_VALUE (TYPE_DOMAIN (type)) : size_zero_node));
2673       field_list
2674         = chainon (field_list,
2675                    make_descriptor_field
2676                    ("SB_L2", gnat_type_for_size (32, 1), record_type,
2677                     TREE_CODE (type) == ARRAY_TYPE
2678                     ? TYPE_MAX_VALUE (TYPE_DOMAIN (type)) : size_zero_node));
2679       break;
2680
2681     case By_Descriptor_A:
2682     case By_Descriptor_NCA:
2683       field_list = chainon (field_list,
2684                             make_descriptor_field ("SCALE",
2685                                                    gnat_type_for_size (8, 1),
2686                                                    record_type,
2687                                                    size_zero_node));
2688
2689       field_list = chainon (field_list,
2690                             make_descriptor_field ("DIGITS",
2691                                                    gnat_type_for_size (8, 1),
2692                                                    record_type,
2693                                                    size_zero_node));
2694
2695       field_list
2696         = chainon (field_list,
2697                    make_descriptor_field
2698                    ("AFLAGS", gnat_type_for_size (8, 1), record_type,
2699                     size_int (mech == By_Descriptor_NCA
2700                               ? 0
2701                               /* Set FL_COLUMN, FL_COEFF, and FL_BOUNDS.  */
2702                               : (TREE_CODE (type) == ARRAY_TYPE
2703                                  && TYPE_CONVENTION_FORTRAN_P (type)
2704                                  ? 224 : 192))));
2705
2706       field_list = chainon (field_list,
2707                             make_descriptor_field ("DIMCT",
2708                                                    gnat_type_for_size (8, 1),
2709                                                    record_type,
2710                                                    size_int (ndim)));
2711
2712       field_list = chainon (field_list,
2713                             make_descriptor_field ("ARSIZE",
2714                                                    gnat_type_for_size (32, 1),
2715                                                    record_type,
2716                                                    size_in_bytes (type)));
2717
2718       /* Now build a pointer to the 0,0,0... element.  */
2719       tem = build0 (PLACEHOLDER_EXPR, type);
2720       for (i = 0, inner_type = type; i < ndim;
2721            i++, inner_type = TREE_TYPE (inner_type))
2722         tem = build4 (ARRAY_REF, TREE_TYPE (inner_type), tem,
2723                       convert (TYPE_DOMAIN (inner_type), size_zero_node),
2724                       NULL_TREE, NULL_TREE);
2725
2726       field_list
2727         = chainon (field_list,
2728                    make_descriptor_field
2729                    ("A0",
2730                     build_pointer_type_for_mode (inner_type, SImode, false),
2731                     record_type,
2732                     build1 (ADDR_EXPR,
2733                             build_pointer_type_for_mode (inner_type, SImode,
2734                                                          false),
2735                             tem)));
2736
2737       /* Next come the addressing coefficients.  */
2738       tem = size_int (1);
2739       for (i = 0; i < ndim; i++)
2740         {
2741           char fname[3];
2742           tree idx_length
2743             = size_binop (MULT_EXPR, tem,
2744                           size_binop (PLUS_EXPR,
2745                                       size_binop (MINUS_EXPR,
2746                                                   TYPE_MAX_VALUE (idx_arr[i]),
2747                                                   TYPE_MIN_VALUE (idx_arr[i])),
2748                                       size_int (1)));
2749
2750           fname[0] = (mech == By_Descriptor_NCA ? 'S' : 'M');
2751           fname[1] = '0' + i, fname[2] = 0;
2752           field_list
2753             = chainon (field_list,
2754                        make_descriptor_field (fname,
2755                                               gnat_type_for_size (32, 1),
2756                                               record_type, idx_length));
2757
2758           if (mech == By_Descriptor_NCA)
2759             tem = idx_length;
2760         }
2761
2762       /* Finally here are the bounds.  */
2763       for (i = 0; i < ndim; i++)
2764         {
2765           char fname[3];
2766
2767           fname[0] = 'L', fname[1] = '0' + i, fname[2] = 0;
2768           field_list
2769             = chainon (field_list,
2770                        make_descriptor_field
2771                        (fname, gnat_type_for_size (32, 1), record_type,
2772                         TYPE_MIN_VALUE (idx_arr[i])));
2773
2774           fname[0] = 'U';
2775           field_list
2776             = chainon (field_list,
2777                        make_descriptor_field
2778                        (fname, gnat_type_for_size (32, 1), record_type,
2779                         TYPE_MAX_VALUE (idx_arr[i])));
2780         }
2781       break;
2782
2783     default:
2784       post_error ("unsupported descriptor type for &", gnat_entity);
2785     }
2786
2787   finish_record_type (record_type, field_list, false, true);
2788   create_type_decl (create_concat_name (gnat_entity, "DESC"), record_type,
2789                     NULL, true, false, gnat_entity);
2790
2791   return record_type;
2792 }
2793
2794 /* Utility routine for above code to make a field.  */
2795
2796 static tree
2797 make_descriptor_field (const char *name, tree type,
2798                        tree rec_type, tree initial)
2799 {
2800   tree field
2801     = create_field_decl (get_identifier (name), type, rec_type, 0, 0, 0, 0);
2802
2803   DECL_INITIAL (field) = initial;
2804   return field;
2805 }
2806 \f
2807 /* Build a type to be used to represent an aliased object whose nominal
2808    type is an unconstrained array.  This consists of a RECORD_TYPE containing
2809    a field of TEMPLATE_TYPE and a field of OBJECT_TYPE, which is an
2810    ARRAY_TYPE.  If ARRAY_TYPE is that of the unconstrained array, this
2811    is used to represent an arbitrary unconstrained object.  Use NAME
2812    as the name of the record.  */
2813
2814 tree
2815 build_unc_object_type (tree template_type, tree object_type, tree name)
2816 {
2817   tree type = make_node (RECORD_TYPE);
2818   tree template_field = create_field_decl (get_identifier ("BOUNDS"),
2819                                            template_type, type, 0, 0, 0, 1);
2820   tree array_field = create_field_decl (get_identifier ("ARRAY"), object_type,
2821                                         type, 0, 0, 0, 1);
2822
2823   TYPE_NAME (type) = name;
2824   TYPE_CONTAINS_TEMPLATE_P (type) = 1;
2825   finish_record_type (type,
2826                       chainon (chainon (NULL_TREE, template_field),
2827                                array_field),
2828                       false, false);
2829
2830   return type;
2831 }
2832
2833 /* Same, taking a thin or fat pointer type instead of a template type. */
2834
2835 tree
2836 build_unc_object_type_from_ptr (tree thin_fat_ptr_type, tree object_type,
2837                                 tree name)
2838 {
2839   tree template_type;
2840
2841   gcc_assert (TYPE_FAT_OR_THIN_POINTER_P (thin_fat_ptr_type));
2842
2843   template_type
2844     = (TYPE_FAT_POINTER_P (thin_fat_ptr_type)
2845        ? TREE_TYPE (TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (thin_fat_ptr_type))))
2846        : TREE_TYPE (TYPE_FIELDS (TREE_TYPE (thin_fat_ptr_type))));
2847   return build_unc_object_type (template_type, object_type, name);
2848 }
2849 \f
2850 /* Update anything previously pointing to OLD_TYPE to point to NEW_TYPE.  In
2851    the normal case this is just two adjustments, but we have more to do
2852    if NEW is an UNCONSTRAINED_ARRAY_TYPE.  */
2853
2854 void
2855 update_pointer_to (tree old_type, tree new_type)
2856 {
2857   tree ptr = TYPE_POINTER_TO (old_type);
2858   tree ref = TYPE_REFERENCE_TO (old_type);
2859   tree ptr1, ref1;
2860   tree type;
2861
2862   /* If this is the main variant, process all the other variants first.  */
2863   if (TYPE_MAIN_VARIANT (old_type) == old_type)
2864     for (type = TYPE_NEXT_VARIANT (old_type); type;
2865          type = TYPE_NEXT_VARIANT (type))
2866       update_pointer_to (type, new_type);
2867
2868   /* If no pointer or reference, we are done.  */
2869   if (!ptr && !ref)
2870     return;
2871
2872   /* Merge the old type qualifiers in the new type.
2873
2874      Each old variant has qualifiers for specific reasons, and the new
2875      designated type as well. Each set of qualifiers represents useful
2876      information grabbed at some point, and merging the two simply unifies
2877      these inputs into the final type description.
2878
2879      Consider for instance a volatile type frozen after an access to constant
2880      type designating it. After the designated type freeze, we get here with a
2881      volatile new_type and a dummy old_type with a readonly variant, created
2882      when the access type was processed. We shall make a volatile and readonly
2883      designated type, because that's what it really is.
2884
2885      We might also get here for a non-dummy old_type variant with different
2886      qualifiers than the new_type ones, for instance in some cases of pointers
2887      to private record type elaboration (see the comments around the call to
2888      this routine from gnat_to_gnu_entity/E_Access_Type). We have to merge the
2889      qualifiers in thoses cases too, to avoid accidentally discarding the
2890      initial set, and will often end up with old_type == new_type then.  */
2891   new_type = build_qualified_type (new_type,
2892                                    TYPE_QUALS (old_type)
2893                                    | TYPE_QUALS (new_type));
2894
2895   /* If the new type and the old one are identical, there is nothing to
2896      update.  */
2897   if (old_type == new_type)
2898     return;
2899
2900   /* Otherwise, first handle the simple case.  */
2901   if (TREE_CODE (new_type) != UNCONSTRAINED_ARRAY_TYPE)
2902     {
2903       TYPE_POINTER_TO (new_type) = ptr;
2904       TYPE_REFERENCE_TO (new_type) = ref;
2905
2906       for (; ptr; ptr = TYPE_NEXT_PTR_TO (ptr))
2907         for (ptr1 = TYPE_MAIN_VARIANT (ptr); ptr1;
2908              ptr1 = TYPE_NEXT_VARIANT (ptr1))
2909           TREE_TYPE (ptr1) = new_type;
2910
2911       for (; ref; ref = TYPE_NEXT_REF_TO (ref))
2912         for (ref1 = TYPE_MAIN_VARIANT (ref); ref1;
2913              ref1 = TYPE_NEXT_VARIANT (ref1))
2914           TREE_TYPE (ref1) = new_type;
2915     }
2916
2917   /* Now deal with the unconstrained array case. In this case the "pointer"
2918      is actually a RECORD_TYPE where the types of both fields are
2919      pointers to void.  In that case, copy the field list from the
2920      old type to the new one and update the fields' context. */
2921   else if (TREE_CODE (ptr) != RECORD_TYPE || !TYPE_IS_FAT_POINTER_P (ptr))
2922     gcc_unreachable ();
2923
2924   else
2925     {
2926       tree new_obj_rec = TYPE_OBJECT_RECORD_TYPE (new_type);
2927       tree ptr_temp_type;
2928       tree new_ref;
2929       tree var;
2930
2931       SET_DECL_ORIGINAL_FIELD (TYPE_FIELDS (ptr),
2932                                TYPE_FIELDS (TYPE_POINTER_TO (new_type)));
2933       SET_DECL_ORIGINAL_FIELD (TREE_CHAIN (TYPE_FIELDS (ptr)),
2934                                TREE_CHAIN (TYPE_FIELDS
2935                                            (TYPE_POINTER_TO (new_type))));
2936
2937       TYPE_FIELDS (ptr) = TYPE_FIELDS (TYPE_POINTER_TO (new_type));
2938       DECL_CONTEXT (TYPE_FIELDS (ptr)) = ptr;
2939       DECL_CONTEXT (TREE_CHAIN (TYPE_FIELDS (ptr))) = ptr;
2940
2941       /* Rework the PLACEHOLDER_EXPR inside the reference to the
2942          template bounds.
2943
2944          ??? This is now the only use of gnat_substitute_in_type, which
2945          is now a very "heavy" routine to do this, so it should be replaced
2946          at some point.  */
2947       ptr_temp_type = TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (ptr)));
2948       new_ref = build3 (COMPONENT_REF, ptr_temp_type,
2949                         build0 (PLACEHOLDER_EXPR, ptr),
2950                         TREE_CHAIN (TYPE_FIELDS (ptr)), NULL_TREE);
2951
2952       update_pointer_to
2953         (TREE_TYPE (TREE_TYPE (TYPE_FIELDS (ptr))),
2954          gnat_substitute_in_type (TREE_TYPE (TREE_TYPE (TYPE_FIELDS (ptr))),
2955                                   TREE_CHAIN (TYPE_FIELDS (ptr)), new_ref));
2956
2957       for (var = TYPE_MAIN_VARIANT (ptr); var; var = TYPE_NEXT_VARIANT (var))
2958         {
2959           SET_TYPE_UNCONSTRAINED_ARRAY (var, new_type);
2960
2961           /* This may seem a bit gross, in particular wrt DECL_CONTEXT, but
2962              actually is in keeping with what build_qualified_type does.  */
2963           TYPE_FIELDS (var) = TYPE_FIELDS (ptr);
2964         }
2965
2966       TYPE_POINTER_TO (new_type) = TYPE_REFERENCE_TO (new_type)
2967         = TREE_TYPE (new_type) = ptr;
2968
2969       /* Now handle updating the allocation record, what the thin pointer
2970          points to.  Update all pointers from the old record into the new
2971          one, update the types of the fields, and recompute the size.  */
2972
2973       update_pointer_to (TYPE_OBJECT_RECORD_TYPE (old_type), new_obj_rec);
2974
2975       TREE_TYPE (TYPE_FIELDS (new_obj_rec)) = TREE_TYPE (ptr_temp_type);
2976       TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (new_obj_rec)))
2977         = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (ptr)));
2978       DECL_SIZE (TREE_CHAIN (TYPE_FIELDS (new_obj_rec)))
2979         = TYPE_SIZE (TREE_TYPE (TREE_TYPE (TYPE_FIELDS (ptr))));
2980       DECL_SIZE_UNIT (TREE_CHAIN (TYPE_FIELDS (new_obj_rec)))
2981         = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (TYPE_FIELDS (ptr))));
2982
2983       TYPE_SIZE (new_obj_rec)
2984         = size_binop (PLUS_EXPR,
2985                       DECL_SIZE (TYPE_FIELDS (new_obj_rec)),
2986                       DECL_SIZE (TREE_CHAIN (TYPE_FIELDS (new_obj_rec))));
2987       TYPE_SIZE_UNIT (new_obj_rec)
2988         = size_binop (PLUS_EXPR,
2989                       DECL_SIZE_UNIT (TYPE_FIELDS (new_obj_rec)),
2990                       DECL_SIZE_UNIT (TREE_CHAIN (TYPE_FIELDS (new_obj_rec))));
2991       rest_of_type_compilation (ptr, global_bindings_p ());
2992     }
2993 }
2994 \f
2995 /* Convert a pointer to a constrained array into a pointer to a fat
2996    pointer.  This involves making or finding a template.  */
2997
2998 static tree
2999 convert_to_fat_pointer (tree type, tree expr)
3000 {
3001   tree template_type = TREE_TYPE (TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (type))));
3002   tree template, template_addr;
3003   tree etype = TREE_TYPE (expr);
3004
3005   /* If EXPR is a constant of zero, we make a fat pointer that has a null
3006      pointer to the template and array.  */
3007   if (integer_zerop (expr))
3008     return
3009       gnat_build_constructor
3010         (type,
3011          tree_cons (TYPE_FIELDS (type),
3012                     convert (TREE_TYPE (TYPE_FIELDS (type)), expr),
3013                     tree_cons (TREE_CHAIN (TYPE_FIELDS (type)),
3014                                convert (build_pointer_type (template_type),
3015                                         expr),
3016                                NULL_TREE)));
3017
3018   /* If EXPR is a thin pointer, make the template and data from the record.  */
3019
3020   else if (TYPE_THIN_POINTER_P (etype))
3021     {
3022       tree fields = TYPE_FIELDS (TREE_TYPE (etype));
3023
3024       expr = save_expr (expr);
3025       if (TREE_CODE (expr) == ADDR_EXPR)
3026         expr = TREE_OPERAND (expr, 0);
3027       else
3028         expr = build1 (INDIRECT_REF, TREE_TYPE (etype), expr);
3029
3030       template = build_component_ref (expr, NULL_TREE, fields, false);
3031       expr = build_unary_op (ADDR_EXPR, NULL_TREE,
3032                              build_component_ref (expr, NULL_TREE,
3033                                                   TREE_CHAIN (fields), false));
3034     }
3035   else
3036     /* Otherwise, build the constructor for the template.  */
3037     template = build_template (template_type, TREE_TYPE (etype), expr);
3038
3039   template_addr = build_unary_op (ADDR_EXPR, NULL_TREE, template);
3040
3041   /* The result is a CONSTRUCTOR for the fat pointer.
3042
3043      If expr is an argument of a foreign convention subprogram, the type it
3044      points to is directly the component type. In this case, the expression
3045      type may not match the corresponding FIELD_DECL type at this point, so we
3046      call "convert" here to fix that up if necessary. This type consistency is
3047      required, for instance because it ensures that possible later folding of
3048      component_refs against this constructor always yields something of the
3049      same type as the initial reference.
3050
3051      Note that the call to "build_template" above is still fine, because it
3052      will only refer to the provided template_type in this case.  */
3053    return
3054      gnat_build_constructor
3055      (type, tree_cons (TYPE_FIELDS (type),
3056                       convert (TREE_TYPE (TYPE_FIELDS (type)), expr),
3057                       tree_cons (TREE_CHAIN (TYPE_FIELDS (type)),
3058                                  template_addr, NULL_TREE)));
3059 }
3060 \f
3061 /* Convert to a thin pointer type, TYPE.  The only thing we know how to convert
3062    is something that is a fat pointer, so convert to it first if it EXPR
3063    is not already a fat pointer.  */
3064
3065 static tree
3066 convert_to_thin_pointer (tree type, tree expr)
3067 {
3068   if (!TYPE_FAT_POINTER_P (TREE_TYPE (expr)))
3069     expr
3070       = convert_to_fat_pointer
3071         (TREE_TYPE (TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (type))), expr);
3072
3073   /* We get the pointer to the data and use a NOP_EXPR to make it the
3074      proper GCC type.  */
3075   expr = build_component_ref (expr, NULL_TREE, TYPE_FIELDS (TREE_TYPE (expr)),
3076                               false);
3077   expr = build1 (NOP_EXPR, type, expr);
3078
3079   return expr;
3080 }
3081 \f
3082 /* Create an expression whose value is that of EXPR,
3083    converted to type TYPE.  The TREE_TYPE of the value
3084    is always TYPE.  This function implements all reasonable
3085    conversions; callers should filter out those that are
3086    not permitted by the language being compiled.  */
3087
3088 tree
3089 convert (tree type, tree expr)
3090 {
3091   enum tree_code code = TREE_CODE (type);
3092   tree etype = TREE_TYPE (expr);
3093   enum tree_code ecode = TREE_CODE (etype);
3094
3095   /* If EXPR is already the right type, we are done.  */
3096   if (type == etype)
3097     return expr;
3098
3099   /* If the input type has padding, remove it by doing a component reference
3100      to the field.  If the output type has padding, make a constructor
3101      to build the record.  If both input and output have padding and are
3102      of variable size, do this as an unchecked conversion.  */
3103   else if (ecode == RECORD_TYPE && code == RECORD_TYPE
3104       && TYPE_IS_PADDING_P (type) && TYPE_IS_PADDING_P (etype)
3105       && (!TREE_CONSTANT (TYPE_SIZE (type))
3106           || !TREE_CONSTANT (TYPE_SIZE (etype))))
3107     ;
3108   else if (ecode == RECORD_TYPE && TYPE_IS_PADDING_P (etype))
3109     {
3110       /* If we have just converted to this padded type, just get
3111          the inner expression.  */
3112       if (TREE_CODE (expr) == CONSTRUCTOR
3113           && !VEC_empty (constructor_elt, CONSTRUCTOR_ELTS (expr))
3114           && VEC_index (constructor_elt, CONSTRUCTOR_ELTS (expr), 0)->index
3115              == TYPE_FIELDS (etype))
3116         return VEC_index (constructor_elt, CONSTRUCTOR_ELTS (expr), 0)->value;
3117       else
3118         return convert (type,
3119                         build_component_ref (expr, NULL_TREE,
3120                                              TYPE_FIELDS (etype), false));
3121     }
3122   else if (code == RECORD_TYPE && TYPE_IS_PADDING_P (type))
3123     {
3124       /* If we previously converted from another type and our type is
3125          of variable size, remove the conversion to avoid the need for
3126          variable-size temporaries.  */
3127       if (TREE_CODE (expr) == VIEW_CONVERT_EXPR
3128           && !TREE_CONSTANT (TYPE_SIZE (type)))
3129         expr = TREE_OPERAND (expr, 0);
3130
3131       /* If we are just removing the padding from expr, convert the original
3132          object if we have variable size.  That will avoid the need
3133          for some variable-size temporaries.  */
3134       if (TREE_CODE (expr) == COMPONENT_REF
3135           && TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == RECORD_TYPE
3136           && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (expr, 0)))
3137           && !TREE_CONSTANT (TYPE_SIZE (type)))
3138         return convert (type, TREE_OPERAND (expr, 0));
3139
3140       /* If the result type is a padded type with a self-referentially-sized
3141          field and the expression type is a record, do this as an
3142          unchecked conversion.  */
3143       else if (TREE_CODE (etype) == RECORD_TYPE
3144                && CONTAINS_PLACEHOLDER_P (DECL_SIZE (TYPE_FIELDS (type))))
3145         return unchecked_convert (type, expr, false);
3146
3147       else
3148         return
3149           gnat_build_constructor (type,
3150                              tree_cons (TYPE_FIELDS (type),
3151                                         convert (TREE_TYPE
3152                                                  (TYPE_FIELDS (type)),
3153                                                  expr),
3154                                         NULL_TREE));
3155     }
3156
3157   /* If the input is a biased type, adjust first.  */
3158   if (ecode == INTEGER_TYPE && TYPE_BIASED_REPRESENTATION_P (etype))
3159     return convert (type, fold_build2 (PLUS_EXPR, TREE_TYPE (etype),
3160                                        fold_convert (TREE_TYPE (etype),
3161                                                      expr),
3162                                        TYPE_MIN_VALUE (etype)));
3163
3164   /* If the input is a justified modular type, we need to extract the actual
3165      object before converting it to any other type with the exceptions of an
3166      unconstrained array or of a mere type variant.  It is useful to avoid the
3167      extraction and conversion in the type variant case because it could end
3168      up replacing a VAR_DECL expr by a constructor and we might be about the
3169      take the address of the result.  */
3170   if (ecode == RECORD_TYPE && TYPE_JUSTIFIED_MODULAR_P (etype)
3171       && code != UNCONSTRAINED_ARRAY_TYPE
3172       && TYPE_MAIN_VARIANT (type) != TYPE_MAIN_VARIANT (etype))
3173     return convert (type, build_component_ref (expr, NULL_TREE,
3174                                                TYPE_FIELDS (etype), false));
3175
3176   /* If converting to a type that contains a template, convert to the data
3177      type and then build the template. */
3178   if (code == RECORD_TYPE && TYPE_CONTAINS_TEMPLATE_P (type))
3179     {
3180       tree obj_type = TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (type)));
3181
3182       /* If the source already has a template, get a reference to the
3183          associated array only, as we are going to rebuild a template
3184          for the target type anyway.  */
3185       expr = maybe_unconstrained_array (expr);
3186
3187       return
3188         gnat_build_constructor
3189           (type,
3190            tree_cons (TYPE_FIELDS (type),
3191                       build_template (TREE_TYPE (TYPE_FIELDS (type)),
3192                                       obj_type, NULL_TREE),
3193                       tree_cons (TREE_CHAIN (TYPE_FIELDS (type)),
3194                                  convert (obj_type, expr), NULL_TREE)));
3195     }
3196
3197   /* There are some special cases of expressions that we process
3198      specially.  */
3199   switch (TREE_CODE (expr))
3200     {
3201     case ERROR_MARK:
3202       return expr;
3203
3204     case NULL_EXPR:
3205       /* Just set its type here.  For TRANSFORM_EXPR, we will do the actual
3206          conversion in gnat_expand_expr.  NULL_EXPR does not represent
3207          and actual value, so no conversion is needed.  */
3208       expr = copy_node (expr);
3209       TREE_TYPE (expr) = type;
3210       return expr;
3211
3212     case STRING_CST:
3213       /* If we are converting a STRING_CST to another constrained array type,
3214          just make a new one in the proper type.  */
3215       if (code == ecode && AGGREGATE_TYPE_P (etype)
3216           && !(TREE_CODE (TYPE_SIZE (etype)) == INTEGER_CST
3217                && TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST))
3218         {
3219           expr = copy_node (expr);
3220           TREE_TYPE (expr) = type;
3221           return expr;
3222         }
3223       break;
3224
3225     case UNCONSTRAINED_ARRAY_REF:
3226       /* Convert this to the type of the inner array by getting the address of
3227          the array from the template.  */
3228       expr = build_unary_op (INDIRECT_REF, NULL_TREE,
3229                              build_component_ref (TREE_OPERAND (expr, 0),
3230                                                   get_identifier ("P_ARRAY"),
3231                                                   NULL_TREE, false));
3232       etype = TREE_TYPE (expr);
3233       ecode = TREE_CODE (etype);
3234       break;
3235
3236     case VIEW_CONVERT_EXPR:
3237       {
3238         /* GCC 4.x is very sensitive to type consistency overall, and view
3239            conversions thus are very frequent.  Even though just "convert"ing
3240            the inner operand to the output type is fine in most cases, it
3241            might expose unexpected input/output type mismatches in special
3242            circumstances so we avoid such recursive calls when we can.  */
3243
3244         tree op0 = TREE_OPERAND (expr, 0);
3245
3246         /* If we are converting back to the original type, we can just
3247            lift the input conversion.  This is a common occurrence with
3248            switches back-and-forth amongst type variants.  */
3249         if (type == TREE_TYPE (op0))
3250           return op0;
3251
3252         /* Otherwise, if we're converting between two aggregate types, we
3253            might be allowed to substitute the VIEW_CONVERT target type in
3254            place or to just convert the inner expression.  */
3255         if (AGGREGATE_TYPE_P (type) && AGGREGATE_TYPE_P (etype))
3256           {
3257             /* If we are converting between type variants, we can just
3258                substitute the VIEW_CONVERT in place.  */
3259             if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (etype))
3260               return build1 (VIEW_CONVERT_EXPR, type, op0);
3261
3262             /* Otherwise, we may just bypass the input view conversion unless
3263                one of the types is a fat pointer,  which is handled by
3264                specialized code below which relies on exact type matching.  */
3265             else if (!TYPE_FAT_POINTER_P (type) && !TYPE_FAT_POINTER_P (etype))
3266               return convert (type, op0);
3267           }
3268       }
3269       break;
3270
3271     case INDIRECT_REF:
3272       /* If both types are record types, just convert the pointer and
3273          make a new INDIRECT_REF.
3274
3275          ??? Disable this for now since it causes problems with the
3276          code in build_binary_op for MODIFY_EXPR which wants to
3277          strip off conversions.  But that code really is a mess and
3278          we need to do this a much better way some time.  */
3279       if (0
3280           && (TREE_CODE (type) == RECORD_TYPE
3281               || TREE_CODE (type) == UNION_TYPE)
3282           && (TREE_CODE (etype) == RECORD_TYPE
3283               || TREE_CODE (etype) == UNION_TYPE)
3284           && !TYPE_FAT_POINTER_P (type) && !TYPE_FAT_POINTER_P (etype))
3285         return build_unary_op (INDIRECT_REF, NULL_TREE,
3286                                convert (build_pointer_type (type),
3287                                         TREE_OPERAND (expr, 0)));
3288       break;
3289
3290     default:
3291       break;
3292     }
3293
3294   /* Check for converting to a pointer to an unconstrained array.  */
3295   if (TYPE_FAT_POINTER_P (type) && !TYPE_FAT_POINTER_P (etype))
3296     return convert_to_fat_pointer (type, expr);
3297
3298   /* If we're converting between two aggregate types that have the same main
3299      variant, just make a VIEW_CONVER_EXPR.  */
3300   else if (AGGREGATE_TYPE_P (type)
3301            && TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (etype))
3302     return build1 (VIEW_CONVERT_EXPR, type, expr);
3303
3304   /* In all other cases of related types, make a NOP_EXPR.  */
3305   else if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (etype)
3306            || (code == INTEGER_CST && ecode == INTEGER_CST
3307                && (type == TREE_TYPE (etype) || etype == TREE_TYPE (type))))
3308     return fold_convert (type, expr);
3309
3310   switch (code)
3311     {
3312     case VOID_TYPE:
3313       return fold_build1 (CONVERT_EXPR, type, expr);
3314
3315     case BOOLEAN_TYPE:
3316       return fold_convert (type, gnat_truthvalue_conversion (expr));
3317
3318     case INTEGER_TYPE:
3319       if (TYPE_HAS_ACTUAL_BOUNDS_P (type)
3320           && (ecode == ARRAY_TYPE || ecode == UNCONSTRAINED_ARRAY_TYPE
3321               || (ecode == RECORD_TYPE && TYPE_CONTAINS_TEMPLATE_P (etype))))
3322         return unchecked_convert (type, expr, false);
3323       else if (TYPE_BIASED_REPRESENTATION_P (type))
3324         return fold_convert (type,
3325                              fold_build2 (MINUS_EXPR, TREE_TYPE (type),
3326                                           convert (TREE_TYPE (type), expr),
3327                                           TYPE_MIN_VALUE (type)));
3328
3329       /* ... fall through ... */
3330
3331     case ENUMERAL_TYPE:
3332       return fold (convert_to_integer (type, expr));
3333
3334     case POINTER_TYPE:
3335     case REFERENCE_TYPE:
3336       /* If converting between two pointers to records denoting
3337          both a template and type, adjust if needed to account
3338          for any differing offsets, since one might be negative.  */
3339       if (TYPE_THIN_POINTER_P (etype) && TYPE_THIN_POINTER_P (type))
3340         {
3341           tree bit_diff
3342             = size_diffop (bit_position (TYPE_FIELDS (TREE_TYPE (etype))),
3343                            bit_position (TYPE_FIELDS (TREE_TYPE (type))));
3344           tree byte_diff = size_binop (CEIL_DIV_EXPR, bit_diff,
3345                                        sbitsize_int (BITS_PER_UNIT));
3346
3347           expr = build1 (NOP_EXPR, type, expr);
3348           TREE_CONSTANT (expr) = TREE_CONSTANT (TREE_OPERAND (expr, 0));
3349           if (integer_zerop (byte_diff))
3350             return expr;
3351
3352           return build_binary_op (PLUS_EXPR, type, expr,
3353                                   fold (convert_to_pointer (type, byte_diff)));
3354         }
3355
3356       /* If converting to a thin pointer, handle specially.  */
3357       if (TYPE_THIN_POINTER_P (type)
3358           && TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (type)))
3359         return convert_to_thin_pointer (type, expr);
3360
3361       /* If converting fat pointer to normal pointer, get the pointer to the
3362          array and then convert it.  */
3363       else if (TYPE_FAT_POINTER_P (etype))
3364         expr = build_component_ref (expr, get_identifier ("P_ARRAY"),
3365                                     NULL_TREE, false);
3366
3367       return fold (convert_to_pointer (type, expr));
3368
3369     case REAL_TYPE:
3370       return fold (convert_to_real (type, expr));
3371
3372     case RECORD_TYPE:
3373       if (TYPE_JUSTIFIED_MODULAR_P (type) && !AGGREGATE_TYPE_P (etype))
3374         return
3375           gnat_build_constructor
3376             (type, tree_cons (TYPE_FIELDS (type),
3377                               convert (TREE_TYPE (TYPE_FIELDS (type)), expr),
3378                               NULL_TREE));
3379
3380       /* ... fall through ... */
3381
3382     case ARRAY_TYPE:
3383       /* In these cases, assume the front-end has validated the conversion.
3384          If the conversion is valid, it will be a bit-wise conversion, so
3385          it can be viewed as an unchecked conversion.  */
3386       return unchecked_convert (type, expr, false);
3387
3388     case UNION_TYPE:
3389       /* This is a either a conversion between a tagged type and some
3390          subtype, which we have to mark as a UNION_TYPE because of
3391          overlapping fields or a conversion of an Unchecked_Union.  */
3392       return unchecked_convert (type, expr, false);
3393
3394     case UNCONSTRAINED_ARRAY_TYPE:
3395       /* If EXPR is a constrained array, take its address, convert it to a
3396          fat pointer, and then dereference it.  Likewise if EXPR is a
3397          record containing both a template and a constrained array.
3398          Note that a record representing a justified modular type
3399          always represents a packed constrained array.  */
3400       if (ecode == ARRAY_TYPE
3401           || (ecode == INTEGER_TYPE && TYPE_HAS_ACTUAL_BOUNDS_P (etype))
3402           || (ecode == RECORD_TYPE && TYPE_CONTAINS_TEMPLATE_P (etype))
3403           || (ecode == RECORD_TYPE && TYPE_JUSTIFIED_MODULAR_P (etype)))
3404         return
3405           build_unary_op
3406             (INDIRECT_REF, NULL_TREE,
3407              convert_to_fat_pointer (TREE_TYPE (type),
3408                                      build_unary_op (ADDR_EXPR,
3409                                                      NULL_TREE, expr)));
3410
3411       /* Do something very similar for converting one unconstrained
3412          array to another.  */
3413       else if (ecode == UNCONSTRAINED_ARRAY_TYPE)
3414         return
3415           build_unary_op (INDIRECT_REF, NULL_TREE,
3416                           convert (TREE_TYPE (type),
3417                                    build_unary_op (ADDR_EXPR,
3418                                                    NULL_TREE, expr)));
3419       else
3420         gcc_unreachable ();
3421
3422     case COMPLEX_TYPE:
3423       return fold (convert_to_complex (type, expr));
3424
3425     default:
3426       gcc_unreachable ();
3427     }
3428 }
3429 \f
3430 /* Remove all conversions that are done in EXP.  This includes converting
3431    from a padded type or to a justified modular type.  If TRUE_ADDRESS
3432    is true, always return the address of the containing object even if
3433    the address is not bit-aligned.  */
3434
3435 tree
3436 remove_conversions (tree exp, bool true_address)
3437 {
3438   switch (TREE_CODE (exp))
3439     {
3440     case CONSTRUCTOR:
3441       if (true_address
3442           && TREE_CODE (TREE_TYPE (exp)) == RECORD_TYPE
3443           && TYPE_JUSTIFIED_MODULAR_P (TREE_TYPE (exp)))
3444         return
3445           remove_conversions (VEC_index (constructor_elt,
3446                                          CONSTRUCTOR_ELTS (exp), 0)->value,
3447                               true);
3448       break;
3449
3450     case COMPONENT_REF:
3451       if (TREE_CODE (TREE_TYPE (TREE_OPERAND (exp, 0))) == RECORD_TYPE
3452           && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (exp, 0))))
3453         return remove_conversions (TREE_OPERAND (exp, 0), true_address);
3454       break;
3455
3456     case VIEW_CONVERT_EXPR:  case NON_LVALUE_EXPR:
3457     case NOP_EXPR:  case CONVERT_EXPR:
3458       return remove_conversions (TREE_OPERAND (exp, 0), true_address);
3459
3460     default:
3461       break;
3462     }
3463
3464   return exp;
3465 }
3466 \f
3467 /* If EXP's type is an UNCONSTRAINED_ARRAY_TYPE, return an expression that
3468    refers to the underlying array.  If its type has TYPE_CONTAINS_TEMPLATE_P,
3469    likewise return an expression pointing to the underlying array.  */
3470
3471 tree
3472 maybe_unconstrained_array (tree exp)
3473 {
3474   enum tree_code code = TREE_CODE (exp);
3475   tree new;
3476
3477   switch (TREE_CODE (TREE_TYPE (exp)))
3478     {
3479     case UNCONSTRAINED_ARRAY_TYPE:
3480       if (code == UNCONSTRAINED_ARRAY_REF)
3481         {
3482           new
3483             = build_unary_op (INDIRECT_REF, NULL_TREE,
3484                               build_component_ref (TREE_OPERAND (exp, 0),
3485                                                    get_identifier ("P_ARRAY"),
3486                                                    NULL_TREE, false));
3487           TREE_READONLY (new) = TREE_STATIC (new) = TREE_READONLY (exp);
3488           return new;
3489         }
3490
3491       else if (code == NULL_EXPR)
3492         return build1 (NULL_EXPR,
3493                        TREE_TYPE (TREE_TYPE (TYPE_FIELDS
3494                                              (TREE_TYPE (TREE_TYPE (exp))))),
3495                        TREE_OPERAND (exp, 0));
3496
3497     case RECORD_TYPE:
3498       /* If this is a padded type, convert to the unpadded type and see if
3499          it contains a template.  */
3500       if (TYPE_IS_PADDING_P (TREE_TYPE (exp)))
3501         {
3502           new = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (exp))), exp);
3503           if (TREE_CODE (TREE_TYPE (new)) == RECORD_TYPE
3504               && TYPE_CONTAINS_TEMPLATE_P (TREE_TYPE (new)))
3505             return
3506               build_component_ref (new, NULL_TREE,
3507                                    TREE_CHAIN (TYPE_FIELDS (TREE_TYPE (new))),
3508                                    0);
3509         }
3510       else if (TYPE_CONTAINS_TEMPLATE_P (TREE_TYPE (exp)))
3511         return
3512           build_component_ref (exp, NULL_TREE,
3513                                TREE_CHAIN (TYPE_FIELDS (TREE_TYPE (exp))), 0);
3514       break;
3515
3516     default:
3517       break;
3518     }
3519
3520   return exp;
3521 }
3522 \f
3523 /* Return an expression that does an unchecked conversion of EXPR to TYPE.
3524    If NOTRUNC_P is true, truncation operations should be suppressed.  */
3525
3526 tree
3527 unchecked_convert (tree type, tree expr, bool notrunc_p)
3528 {
3529   tree etype = TREE_TYPE (expr);
3530
3531   /* If the expression is already the right type, we are done.  */
3532   if (etype == type)
3533     return expr;
3534
3535   /* If both types types are integral just do a normal conversion.
3536      Likewise for a conversion to an unconstrained array.  */
3537   if ((((INTEGRAL_TYPE_P (type)
3538          && !(TREE_CODE (type) == INTEGER_TYPE
3539               && TYPE_VAX_FLOATING_POINT_P (type)))
3540         || (POINTER_TYPE_P (type) && ! TYPE_THIN_POINTER_P (type))
3541         || (TREE_CODE (type) == RECORD_TYPE
3542             && TYPE_JUSTIFIED_MODULAR_P (type)))
3543        && ((INTEGRAL_TYPE_P (etype)
3544             && !(TREE_CODE (etype) == INTEGER_TYPE
3545                  && TYPE_VAX_FLOATING_POINT_P (etype)))
3546            || (POINTER_TYPE_P (etype) && !TYPE_THIN_POINTER_P (etype))
3547            || (TREE_CODE (etype) == RECORD_TYPE
3548                && TYPE_JUSTIFIED_MODULAR_P (etype))))
3549       || TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE)
3550     {
3551       tree rtype = type;
3552
3553       if (TREE_CODE (etype) == INTEGER_TYPE
3554           && TYPE_BIASED_REPRESENTATION_P (etype))
3555         {
3556           tree ntype = copy_type (etype);
3557
3558           TYPE_BIASED_REPRESENTATION_P (ntype) = 0;
3559           TYPE_MAIN_VARIANT (ntype) = ntype;
3560           expr = build1 (NOP_EXPR, ntype, expr);
3561         }
3562
3563       if (TREE_CODE (type) == INTEGER_TYPE
3564           && TYPE_BIASED_REPRESENTATION_P (type))
3565         {
3566           rtype = copy_type (type);
3567           TYPE_BIASED_REPRESENTATION_P (rtype) = 0;
3568           TYPE_MAIN_VARIANT (rtype) = rtype;
3569         }
3570
3571       expr = convert (rtype, expr);
3572       if (type != rtype)
3573         expr = build1 (NOP_EXPR, type, expr);
3574     }
3575
3576   /* If we are converting TO an integral type whose precision is not the
3577      same as its size, first unchecked convert to a record that contains
3578      an object of the output type.  Then extract the field. */
3579   else if (INTEGRAL_TYPE_P (type) && TYPE_RM_SIZE (type)
3580            && 0 != compare_tree_int (TYPE_RM_SIZE (type),
3581                                      GET_MODE_BITSIZE (TYPE_MODE (type))))
3582     {
3583       tree rec_type = make_node (RECORD_TYPE);
3584       tree field = create_field_decl (get_identifier ("OBJ"), type,
3585                                       rec_type, 1, 0, 0, 0);
3586
3587       TYPE_FIELDS (rec_type) = field;
3588       layout_type (rec_type);
3589
3590       expr = unchecked_convert (rec_type, expr, notrunc_p);
3591       expr = build_component_ref (expr, NULL_TREE, field, 0);
3592     }
3593
3594   /* Similarly for integral input type whose precision is not equal to its
3595      size.  */
3596   else if (INTEGRAL_TYPE_P (etype) && TYPE_RM_SIZE (etype)
3597       && 0 != compare_tree_int (TYPE_RM_SIZE (etype),
3598                                 GET_MODE_BITSIZE (TYPE_MODE (etype))))
3599     {
3600       tree rec_type = make_node (RECORD_TYPE);
3601       tree field
3602         = create_field_decl (get_identifier ("OBJ"), etype, rec_type,
3603                              1, 0, 0, 0);
3604
3605       TYPE_FIELDS (rec_type) = field;
3606       layout_type (rec_type);
3607
3608       expr = gnat_build_constructor (rec_type, build_tree_list (field, expr));
3609       expr = unchecked_convert (type, expr, notrunc_p);
3610     }
3611
3612   /* We have a special case when we are converting between two
3613      unconstrained array types.  In that case, take the address,
3614      convert the fat pointer types, and dereference.  */
3615   else if (TREE_CODE (etype) == UNCONSTRAINED_ARRAY_TYPE
3616            && TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE)
3617     expr = build_unary_op (INDIRECT_REF, NULL_TREE,
3618                            build1 (VIEW_CONVERT_EXPR, TREE_TYPE (type),
3619                                    build_unary_op (ADDR_EXPR, NULL_TREE,
3620                                                    expr)));
3621   else
3622     {
3623       expr = maybe_unconstrained_array (expr);
3624
3625       /* There's no point in doing two unchecked conversions in a row.  */
3626       if (TREE_CODE (expr) == VIEW_CONVERT_EXPR)
3627         expr = TREE_OPERAND (expr, 0);
3628
3629       etype = TREE_TYPE (expr);
3630       expr = build1 (VIEW_CONVERT_EXPR, type, expr);
3631     }
3632
3633   /* If the result is an integral type whose size is not equal to
3634      the size of the underlying machine type, sign- or zero-extend
3635      the result.  We need not do this in the case where the input is
3636      an integral type of the same precision and signedness or if the output
3637      is a biased type or if both the input and output are unsigned.  */
3638   if (!notrunc_p
3639       && INTEGRAL_TYPE_P (type) && TYPE_RM_SIZE (type)
3640       && !(TREE_CODE (type) == INTEGER_TYPE
3641            && TYPE_BIASED_REPRESENTATION_P (type))
3642       && 0 != compare_tree_int (TYPE_RM_SIZE (type),
3643                                 GET_MODE_BITSIZE (TYPE_MODE (type)))
3644       && !(INTEGRAL_TYPE_P (etype)
3645            && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (etype)
3646            && operand_equal_p (TYPE_RM_SIZE (type),
3647                                (TYPE_RM_SIZE (etype) != 0
3648                                 ? TYPE_RM_SIZE (etype) : TYPE_SIZE (etype)),
3649                                0))
3650       && !(TYPE_UNSIGNED (type) && TYPE_UNSIGNED (etype)))
3651     {
3652       tree base_type = gnat_type_for_mode (TYPE_MODE (type),
3653                                            TYPE_UNSIGNED (type));
3654       tree shift_expr
3655         = convert (base_type,
3656                    size_binop (MINUS_EXPR,
3657                                bitsize_int
3658                                (GET_MODE_BITSIZE (TYPE_MODE (type))),
3659                                TYPE_RM_SIZE (type)));
3660       expr
3661         = convert (type,
3662                    build_binary_op (RSHIFT_EXPR, base_type,
3663                                     build_binary_op (LSHIFT_EXPR, base_type,
3664                                                      convert (base_type, expr),
3665                                                      shift_expr),
3666                                     shift_expr));
3667     }
3668
3669   /* An unchecked conversion should never raise Constraint_Error.  The code
3670      below assumes that GCC's conversion routines overflow the same way that
3671      the underlying hardware does.  This is probably true.  In the rare case
3672      when it is false, we can rely on the fact that such conversions are
3673      erroneous anyway.  */
3674   if (TREE_CODE (expr) == INTEGER_CST)
3675     TREE_OVERFLOW (expr) = 0;
3676
3677   /* If the sizes of the types differ and this is an VIEW_CONVERT_EXPR,
3678      show no longer constant.  */
3679   if (TREE_CODE (expr) == VIEW_CONVERT_EXPR
3680       && !operand_equal_p (TYPE_SIZE_UNIT (type), TYPE_SIZE_UNIT (etype),
3681                            OEP_ONLY_CONST))
3682     TREE_CONSTANT (expr) = 0;
3683
3684   return expr;
3685 }
3686 \f
3687 /* Search the chain of currently reachable declarations for a builtin
3688    FUNCTION_DECL node corresponding to function NAME (an IDENTIFIER_NODE).
3689    Return the first node found, if any, or NULL_TREE otherwise.  */
3690 tree
3691 builtin_decl_for (tree name __attribute__ ((unused)))
3692 {
3693   /* ??? not clear yet how to implement this function in tree-ssa, so
3694      return NULL_TREE for now */
3695   return NULL_TREE;
3696 }
3697
3698 /* Return the appropriate GCC tree code for the specified GNAT type,
3699    the latter being a record type as predicated by Is_Record_Type.  */
3700
3701 enum tree_code
3702 tree_code_for_record_type (Entity_Id gnat_type)
3703 {
3704   Node_Id component_list
3705     = Component_List (Type_Definition
3706                       (Declaration_Node
3707                        (Implementation_Base_Type (gnat_type))));
3708   Node_Id component;
3709
3710  /* Make this a UNION_TYPE unless it's either not an Unchecked_Union or
3711     we have a non-discriminant field outside a variant.  In either case,
3712     it's a RECORD_TYPE.  */
3713
3714   if (!Is_Unchecked_Union (gnat_type))
3715     return RECORD_TYPE;
3716
3717   for (component = First_Non_Pragma (Component_Items (component_list));
3718        Present (component);
3719        component = Next_Non_Pragma (component))
3720     if (Ekind (Defining_Entity (component)) == E_Component)
3721       return RECORD_TYPE;
3722
3723   return UNION_TYPE;
3724 }
3725
3726 /* Build a global constructor or destructor function.  METHOD_TYPE gives
3727    the type of the function and VEC points to the vector of constructor
3728    or destructor functions to be invoked.  FIXME: Migrate into cgraph.  */
3729
3730 static void
3731 build_global_cdtor (int method_type, tree *vec, int len)
3732 {
3733   tree body = NULL_TREE;
3734   int i;
3735
3736   for (i = 0; i < len; i++)
3737     {
3738       tree fntype = TREE_TYPE (vec[i]);
3739       tree fnaddr = build1 (ADDR_EXPR, build_pointer_type (fntype), vec[i]);
3740       tree fncall = build_call_nary (TREE_TYPE (fntype), fnaddr, 0);
3741       append_to_statement_list (fncall, &body);
3742     }
3743
3744   if (body)
3745     cgraph_build_static_cdtor (method_type, body, DEFAULT_INIT_PRIORITY);
3746 }
3747
3748 /* Perform final processing on global variables.  */
3749
3750 void
3751 gnat_write_global_declarations (void)
3752 {
3753   /* Generate functions to call static constructors and destructors
3754      for targets that do not support .ctors/.dtors sections.  These
3755      functions have magic names which are detected by collect2.  */
3756   build_global_cdtor ('I', VEC_address (tree, static_ctors),
3757                            VEC_length (tree, static_ctors));
3758   build_global_cdtor ('D', VEC_address (tree, static_dtors),
3759                            VEC_length (tree, static_dtors));
3760
3761   /* Proceed to optimize and emit assembly.
3762      FIXME: shouldn't be the front end's responsibility to call this.  */
3763   cgraph_optimize ();
3764
3765   /* Emit debug info for all global declarations.  */
3766   emit_debug_global_declarations (VEC_address (tree, global_decls),
3767                                   VEC_length (tree, global_decls));
3768 }
3769
3770 #include "gt-ada-utils.h"
3771 #include "gtype-ada.h"