OSDN Git Service

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