coretypes.h: Include input.h and as-a.h.
[platform/upstream/gcc.git] / gcc / ada / gcc-interface / decl.c
1 /****************************************************************************
2  *                                                                          *
3  *                         GNAT COMPILER COMPONENTS                         *
4  *                                                                          *
5  *                                 D E C L                                  *
6  *                                                                          *
7  *                          C Implementation File                           *
8  *                                                                          *
9  *          Copyright (C) 1992-2015, 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 "vec.h"
31 #include "alias.h"
32 #include "symtab.h"
33 #include "inchash.h"
34 #include "tree.h"
35 #include "fold-const.h"
36 #include "stringpool.h"
37 #include "stor-layout.h"
38 #include "flags.h"
39 #include "toplev.h"
40 #include "ggc.h"
41 #include "target.h"
42 #include "tree-inline.h"
43 #include "diagnostic-core.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 "repinfo.h"
52 #include "snames.h"
53 #include "stringt.h"
54 #include "uintp.h"
55 #include "fe.h"
56 #include "sinfo.h"
57 #include "einfo.h"
58 #include "ada-tree.h"
59 #include "gigi.h"
60
61 /* "stdcall" and "thiscall" conventions should be processed in a specific way
62    on 32-bit x86/Windows only.  The macros below are helpers to avoid having
63    to check for a Windows specific attribute throughout this unit.  */
64
65 #if TARGET_DLLIMPORT_DECL_ATTRIBUTES
66 #ifdef TARGET_64BIT
67 #define Has_Stdcall_Convention(E) \
68   (!TARGET_64BIT && Convention (E) == Convention_Stdcall)
69 #define Has_Thiscall_Convention(E) \
70   (!TARGET_64BIT && is_cplusplus_method (E))
71 #else
72 #define Has_Stdcall_Convention(E) (Convention (E) == Convention_Stdcall)
73 #define Has_Thiscall_Convention(E) (is_cplusplus_method (E))
74 #endif
75 #else
76 #define Has_Stdcall_Convention(E) 0
77 #define Has_Thiscall_Convention(E) 0
78 #endif
79
80 #define STDCALL_PREFIX "_imp__"
81
82 /* Stack realignment is necessary for functions with foreign conventions when
83    the ABI doesn't mandate as much as what the compiler assumes - that is, up
84    to PREFERRED_STACK_BOUNDARY.
85
86    Such realignment can be requested with a dedicated function type attribute
87    on the targets that support it.  We define FOREIGN_FORCE_REALIGN_STACK to
88    characterize the situations where the attribute should be set.  We rely on
89    compiler configuration settings for 'main' to decide.  */
90
91 #ifdef MAIN_STACK_BOUNDARY
92 #define FOREIGN_FORCE_REALIGN_STACK \
93   (MAIN_STACK_BOUNDARY < PREFERRED_STACK_BOUNDARY)
94 #else
95 #define FOREIGN_FORCE_REALIGN_STACK 0
96 #endif
97
98 struct incomplete
99 {
100   struct incomplete *next;
101   tree old_type;
102   Entity_Id full_type;
103 };
104
105 /* These variables are used to defer recursively expanding incomplete types
106    while we are processing an array, a record or a subprogram type.  */
107 static int defer_incomplete_level = 0;
108 static struct incomplete *defer_incomplete_list;
109
110 /* This variable is used to delay expanding From_Limited_With types until the
111    end of the spec.  */
112 static struct incomplete *defer_limited_with;
113
114 typedef struct subst_pair_d {
115   tree discriminant;
116   tree replacement;
117 } subst_pair;
118
119
120 typedef struct variant_desc_d {
121   /* The type of the variant.  */
122   tree type;
123
124   /* The associated field.  */
125   tree field;
126
127   /* The value of the qualifier.  */
128   tree qual;
129
130   /* The type of the variant after transformation.  */
131   tree new_type;
132 } variant_desc;
133
134
135 /* A hash table used to cache the result of annotate_value.  */
136
137 struct value_annotation_hasher : ggc_cache_hasher<tree_int_map *>
138 {
139   static inline hashval_t
140   hash (tree_int_map *m)
141   {
142     return htab_hash_pointer (m->base.from);
143   }
144
145   static inline bool
146   equal (tree_int_map *a, tree_int_map *b)
147   {
148     return a->base.from == b->base.from;
149   }
150
151   static void
152   handle_cache_entry (tree_int_map *&m)
153   {
154     extern void gt_ggc_mx (tree_int_map *&);
155     if (m == HTAB_EMPTY_ENTRY || m == HTAB_DELETED_ENTRY)
156       return;
157     else if (ggc_marked_p (m->base.from))
158       gt_ggc_mx (m);
159     else
160       m = static_cast<tree_int_map *> (HTAB_DELETED_ENTRY);
161   }
162 };
163
164 static GTY ((cache)) hash_table<value_annotation_hasher> *annotate_value_cache;
165
166 static void prepend_one_attribute (struct attrib **,
167                                    enum attr_type, tree, tree, Node_Id);
168 static void prepend_one_attribute_pragma (struct attrib **, Node_Id);
169 static void prepend_attributes (struct attrib **, Entity_Id);
170 static tree elaborate_expression (Node_Id, Entity_Id, const char *, bool, bool,
171                                   bool);
172 static bool type_has_variable_size (tree);
173 static tree elaborate_expression_1 (tree, Entity_Id, const char *, bool, bool);
174 static tree elaborate_expression_2 (tree, Entity_Id, const char *, bool, bool,
175                                     unsigned int);
176 static tree elaborate_reference (tree, Entity_Id, bool, tree *);
177 static tree gnat_to_gnu_component_type (Entity_Id, bool, bool);
178 static tree gnat_to_gnu_param (Entity_Id, Mechanism_Type, Entity_Id, bool,
179                                bool *);
180 static tree gnat_to_gnu_field (Entity_Id, tree, int, bool, bool);
181 static bool is_from_limited_with_of_main (Entity_Id);
182 static tree change_qualified_type (tree, int);
183 static bool same_discriminant_p (Entity_Id, Entity_Id);
184 static bool array_type_has_nonaliased_component (tree, Entity_Id);
185 static bool compile_time_known_address_p (Node_Id);
186 static bool cannot_be_superflat (Node_Id);
187 static bool constructor_address_p (tree);
188 static bool allocatable_size_p (tree, bool);
189 static bool initial_value_needs_conversion (tree, tree);
190 static int compare_field_bitpos (const PTR, const PTR);
191 static bool components_to_record (tree, Node_Id, tree, int, bool, bool, bool,
192                                   bool, bool, bool, bool, bool, tree, tree *);
193 static Uint annotate_value (tree);
194 static void annotate_rep (Entity_Id, tree);
195 static tree build_position_list (tree, bool, tree, tree, unsigned int, tree);
196 static vec<subst_pair> build_subst_list (Entity_Id, Entity_Id, bool);
197 static vec<variant_desc> build_variant_list (tree,
198                                                    vec<subst_pair> ,
199                                                    vec<variant_desc> );
200 static tree validate_size (Uint, tree, Entity_Id, enum tree_code, bool, bool);
201 static void set_rm_size (Uint, tree, Entity_Id);
202 static unsigned int validate_alignment (Uint, Entity_Id, unsigned int);
203 static void check_ok_for_atomic_type (tree, Entity_Id, bool);
204 static tree create_field_decl_from (tree, tree, tree, tree, tree,
205                                     vec<subst_pair> );
206 static tree create_rep_part (tree, tree, tree);
207 static tree get_rep_part (tree);
208 static tree create_variant_part_from (tree, vec<variant_desc> , tree,
209                                       tree, vec<subst_pair> );
210 static void copy_and_substitute_in_size (tree, tree, vec<subst_pair> );
211 static void add_parallel_type_for_packed_array (tree, Entity_Id);
212 static const char *get_entity_char (Entity_Id);
213
214 /* The relevant constituents of a subprogram binding to a GCC builtin.  Used
215    to pass around calls performing profile compatibility checks.  */
216
217 typedef struct {
218   Entity_Id gnat_entity;  /* The Ada subprogram entity.  */
219   tree ada_fntype;        /* The corresponding GCC type node.  */
220   tree btin_fntype;       /* The GCC builtin function type node.  */
221 } intrin_binding_t;
222
223 static bool intrin_profiles_compatible_p (intrin_binding_t *);
224 \f
225 /* Given GNAT_ENTITY, a GNAT defining identifier node, which denotes some Ada
226    entity, return the equivalent GCC tree for that entity (a ..._DECL node)
227    and associate the ..._DECL node with the input GNAT defining identifier.
228
229    If GNAT_ENTITY is a variable or a constant declaration, GNU_EXPR gives its
230    initial value (in GCC tree form).  This is optional for a variable.  For
231    a renamed entity, GNU_EXPR gives the object being renamed.
232
233    DEFINITION is nonzero if this call is intended for a definition.  This is
234    used for separate compilation where it is necessary to know whether an
235    external declaration or a definition must be created if the GCC equivalent
236    was not created previously.  The value of 1 is normally used for a nonzero
237    DEFINITION, but a value of 2 is used in special circumstances, defined in
238    the code.  */
239
240 tree
241 gnat_to_gnu_entity (Entity_Id gnat_entity, tree gnu_expr, int definition)
242 {
243   /* Contains the kind of the input GNAT node.  */
244   const Entity_Kind kind = Ekind (gnat_entity);
245   /* True if this is a type.  */
246   const bool is_type = IN (kind, Type_Kind);
247   /* True if debug info is requested for this entity.  */
248   const bool debug_info_p = Needs_Debug_Info (gnat_entity);
249   /* True if this entity is to be considered as imported.  */
250   const bool imported_p
251     = (Is_Imported (gnat_entity) && No (Address_Clause (gnat_entity)));
252   /* For a type, contains the equivalent GNAT node to be used in gigi.  */
253   Entity_Id gnat_equiv_type = Empty;
254   /* Temporary used to walk the GNAT tree.  */
255   Entity_Id gnat_temp;
256   /* Contains the GCC DECL node which is equivalent to the input GNAT node.
257      This node will be associated with the GNAT node by calling at the end
258      of the `switch' statement.  */
259   tree gnu_decl = NULL_TREE;
260   /* Contains the GCC type to be used for the GCC node.  */
261   tree gnu_type = NULL_TREE;
262   /* Contains the GCC size tree to be used for the GCC node.  */
263   tree gnu_size = NULL_TREE;
264   /* Contains the GCC name to be used for the GCC node.  */
265   tree gnu_entity_name;
266   /* True if we have already saved gnu_decl as a GNAT association.  */
267   bool saved = false;
268   /* True if we incremented defer_incomplete_level.  */
269   bool this_deferred = false;
270   /* True if we incremented force_global.  */
271   bool this_global = false;
272   /* True if we should check to see if elaborated during processing.  */
273   bool maybe_present = false;
274   /* True if we made GNU_DECL and its type here.  */
275   bool this_made_decl = false;
276   /* Size and alignment of the GCC node, if meaningful.  */
277   unsigned int esize = 0, align = 0;
278   /* Contains the list of attributes directly attached to the entity.  */
279   struct attrib *attr_list = NULL;
280
281   /* Since a use of an Itype is a definition, process it as such if it
282      is not in a with'ed unit.  */
283   if (!definition
284       && is_type
285       && Is_Itype (gnat_entity)
286       && !present_gnu_tree (gnat_entity)
287       && In_Extended_Main_Code_Unit (gnat_entity))
288     {
289       /* Ensure that we are in a subprogram mentioned in the Scope chain of
290          this entity, our current scope is global, or we encountered a task
291          or entry (where we can't currently accurately check scoping).  */
292       if (!current_function_decl
293           || DECL_ELABORATION_PROC_P (current_function_decl))
294         {
295           process_type (gnat_entity);
296           return get_gnu_tree (gnat_entity);
297         }
298
299       for (gnat_temp = Scope (gnat_entity);
300            Present (gnat_temp);
301            gnat_temp = Scope (gnat_temp))
302         {
303           if (Is_Type (gnat_temp))
304             gnat_temp = Underlying_Type (gnat_temp);
305
306           if (Ekind (gnat_temp) == E_Subprogram_Body)
307             gnat_temp
308               = Corresponding_Spec (Parent (Declaration_Node (gnat_temp)));
309
310           if (IN (Ekind (gnat_temp), Subprogram_Kind)
311               && Present (Protected_Body_Subprogram (gnat_temp)))
312             gnat_temp = Protected_Body_Subprogram (gnat_temp);
313
314           if (Ekind (gnat_temp) == E_Entry
315               || Ekind (gnat_temp) == E_Entry_Family
316               || Ekind (gnat_temp) == E_Task_Type
317               || (IN (Ekind (gnat_temp), Subprogram_Kind)
318                   && present_gnu_tree (gnat_temp)
319                   && (current_function_decl
320                       == gnat_to_gnu_entity (gnat_temp, NULL_TREE, 0))))
321             {
322               process_type (gnat_entity);
323               return get_gnu_tree (gnat_entity);
324             }
325         }
326
327       /* This abort means the Itype has an incorrect scope, i.e. that its
328          scope does not correspond to the subprogram it is declared in.  */
329       gcc_unreachable ();
330     }
331
332   /* If we've already processed this entity, return what we got last time.
333      If we are defining the node, we should not have already processed it.
334      In that case, we will abort below when we try to save a new GCC tree
335      for this object.  We also need to handle the case of getting a dummy
336      type when a Full_View exists but be careful so as not to trigger its
337      premature elaboration.  */
338   if ((!definition || (is_type && imported_p))
339       && present_gnu_tree (gnat_entity))
340     {
341       gnu_decl = get_gnu_tree (gnat_entity);
342
343       if (TREE_CODE (gnu_decl) == TYPE_DECL
344           && TYPE_IS_DUMMY_P (TREE_TYPE (gnu_decl))
345           && IN (kind, Incomplete_Or_Private_Kind)
346           && Present (Full_View (gnat_entity))
347           && (present_gnu_tree (Full_View (gnat_entity))
348               || No (Freeze_Node (Full_View (gnat_entity)))))
349         {
350           gnu_decl
351             = gnat_to_gnu_entity (Full_View (gnat_entity), NULL_TREE, 0);
352           save_gnu_tree (gnat_entity, NULL_TREE, false);
353           save_gnu_tree (gnat_entity, gnu_decl, false);
354         }
355
356       return gnu_decl;
357     }
358
359   /* If this is a numeric or enumeral type, or an access type, a nonzero Esize
360      must be specified unless it was specified by the programmer.  Exceptions
361      are for access-to-protected-subprogram types and all access subtypes, as
362      another GNAT type is used to lay out the GCC type for them.  */
363   gcc_assert (!Unknown_Esize (gnat_entity)
364               || Has_Size_Clause (gnat_entity)
365               || (!IN (kind, Numeric_Kind)
366                   && !IN (kind, Enumeration_Kind)
367                   && (!IN (kind, Access_Kind)
368                       || kind == E_Access_Protected_Subprogram_Type
369                       || kind == E_Anonymous_Access_Protected_Subprogram_Type
370                       || kind == E_Access_Subtype
371                       || type_annotate_only)));
372
373   /* The RM size must be specified for all discrete and fixed-point types.  */
374   gcc_assert (!(IN (kind, Discrete_Or_Fixed_Point_Kind)
375                 && Unknown_RM_Size (gnat_entity)));
376
377   /* If we get here, it means we have not yet done anything with this entity.
378      If we are not defining it, it must be a type or an entity that is defined
379      elsewhere or externally, otherwise we should have defined it already.  */
380   gcc_assert (definition
381               || type_annotate_only
382               || is_type
383               || kind == E_Discriminant
384               || kind == E_Component
385               || kind == E_Label
386               || (kind == E_Constant && Present (Full_View (gnat_entity)))
387               || Is_Public (gnat_entity));
388
389   /* Get the name of the entity and set up the line number and filename of
390      the original definition for use in any decl we make.  Make sure we do not
391      inherit another source location.  */
392   gnu_entity_name = get_entity_name (gnat_entity);
393   if (Sloc (gnat_entity) != No_Location
394       && !renaming_from_generic_instantiation_p (gnat_entity))
395     Sloc_to_locus (Sloc (gnat_entity), &input_location);
396
397   /* For cases when we are not defining (i.e., we are referencing from
398      another compilation unit) public entities, show we are at global level
399      for the purpose of computing scopes.  Don't do this for components or
400      discriminants since the relevant test is whether or not the record is
401      being defined.  */
402   if (!definition
403       && kind != E_Component
404       && kind != E_Discriminant
405       && Is_Public (gnat_entity)
406       && !Is_Statically_Allocated (gnat_entity))
407     force_global++, this_global = true;
408
409   /* Handle any attributes directly attached to the entity.  */
410   if (Has_Gigi_Rep_Item (gnat_entity))
411     prepend_attributes (&attr_list, gnat_entity);
412
413   /* Do some common processing for types.  */
414   if (is_type)
415     {
416       /* Compute the equivalent type to be used in gigi.  */
417       gnat_equiv_type = Gigi_Equivalent_Type (gnat_entity);
418
419       /* Machine_Attributes on types are expected to be propagated to
420          subtypes.  The corresponding Gigi_Rep_Items are only attached
421          to the first subtype though, so we handle the propagation here.  */
422       if (Base_Type (gnat_entity) != gnat_entity
423           && !Is_First_Subtype (gnat_entity)
424           && Has_Gigi_Rep_Item (First_Subtype (Base_Type (gnat_entity))))
425         prepend_attributes (&attr_list,
426                             First_Subtype (Base_Type (gnat_entity)));
427
428       /* Compute a default value for the size of an elementary type.  */
429       if (Known_Esize (gnat_entity) && Is_Elementary_Type (gnat_entity))
430         {
431           unsigned int max_esize;
432
433           gcc_assert (UI_Is_In_Int_Range (Esize (gnat_entity)));
434           esize = UI_To_Int (Esize (gnat_entity));
435
436           if (IN (kind, Float_Kind))
437             max_esize = fp_prec_to_size (LONG_DOUBLE_TYPE_SIZE);
438           else if (IN (kind, Access_Kind))
439             max_esize = POINTER_SIZE * 2;
440           else
441             max_esize = LONG_LONG_TYPE_SIZE;
442
443           if (esize > max_esize)
444            esize = max_esize;
445         }
446     }
447
448   switch (kind)
449     {
450     case E_Component:
451     case E_Discriminant:
452       {
453         /* The GNAT record where the component was defined.  */
454         Entity_Id gnat_record = Underlying_Type (Scope (gnat_entity));
455
456         /* If the entity is a discriminant of an extended tagged type used to
457            rename a discriminant of the parent type, return the latter.  */
458         if (Is_Tagged_Type (gnat_record)
459             && Present (Corresponding_Discriminant (gnat_entity)))
460           {
461             gnu_decl
462               = gnat_to_gnu_entity (Corresponding_Discriminant (gnat_entity),
463                                     gnu_expr, definition);
464             saved = true;
465             break;
466           }
467
468         /* If the entity is an inherited component (in the case of extended
469            tagged record types), just return the original entity, which must
470            be a FIELD_DECL.  Likewise for discriminants.  If the entity is a
471            non-girder discriminant (in the case of derived untagged record
472            types), return the stored discriminant it renames.  */
473         else if (Present (Original_Record_Component (gnat_entity))
474                  && Original_Record_Component (gnat_entity) != gnat_entity)
475           {
476             gnu_decl
477               = gnat_to_gnu_entity (Original_Record_Component (gnat_entity),
478                                     gnu_expr, definition);
479             saved = true;
480             break;
481           }
482
483         /* Otherwise, if we are not defining this and we have no GCC type
484            for the containing record, make one for it.  Then we should
485            have made our own equivalent.  */
486         else if (!definition && !present_gnu_tree (gnat_record))
487           {
488             /* ??? If this is in a record whose scope is a protected
489                type and we have an Original_Record_Component, use it.
490                This is a workaround for major problems in protected type
491                handling.  */
492             Entity_Id Scop = Scope (Scope (gnat_entity));
493             if (Is_Protected_Type (Underlying_Type (Scop))
494                 && Present (Original_Record_Component (gnat_entity)))
495               {
496                 gnu_decl
497                   = gnat_to_gnu_entity (Original_Record_Component
498                                         (gnat_entity),
499                                         gnu_expr, 0);
500                 saved = true;
501                 break;
502               }
503
504             gnat_to_gnu_entity (Scope (gnat_entity), NULL_TREE, 0);
505             gnu_decl = get_gnu_tree (gnat_entity);
506             saved = true;
507             break;
508           }
509
510         else
511           /* Here we have no GCC type and this is a reference rather than a
512              definition.  This should never happen.  Most likely the cause is
513              reference before declaration in the GNAT tree for gnat_entity.  */
514           gcc_unreachable ();
515       }
516
517     case E_Constant:
518       /* Ignore constant definitions already marked with the error node.  See
519          the N_Object_Declaration case of gnat_to_gnu for the rationale.  */
520       if (definition
521           && gnu_expr
522           && present_gnu_tree (gnat_entity)
523           && get_gnu_tree (gnat_entity) == error_mark_node)
524         {
525           maybe_present = true;
526           break;
527         }
528
529       /* Ignore deferred constant definitions without address clause since
530          they are processed fully in the front-end.  If No_Initialization
531          is set, this is not a deferred constant but a constant whose value
532          is built manually.  And constants that are renamings are handled
533          like variables.  */
534       if (definition
535           && !gnu_expr
536           && No (Address_Clause (gnat_entity))
537           && !No_Initialization (Declaration_Node (gnat_entity))
538           && No (Renamed_Object (gnat_entity)))
539         {
540           gnu_decl = error_mark_node;
541           saved = true;
542           break;
543         }
544
545       /* If this is a use of a deferred constant without address clause,
546          get its full definition.  */
547       if (!definition
548           && No (Address_Clause (gnat_entity))
549           && Present (Full_View (gnat_entity)))
550         {
551           gnu_decl
552             = gnat_to_gnu_entity (Full_View (gnat_entity), gnu_expr, 0);
553           saved = true;
554           break;
555         }
556
557       /* If we have a constant that we are not defining, get the expression it
558          was defined to represent.  This is necessary to avoid generating dumb
559          elaboration code in simple cases, but we may throw it away later if it
560          is not a constant.  But do not retrieve it if it is an allocator since
561          the designated type might still be dummy at this point.  */
562       if (!definition
563           && !No_Initialization (Declaration_Node (gnat_entity))
564           && Present (Expression (Declaration_Node (gnat_entity)))
565           && Nkind (Expression (Declaration_Node (gnat_entity)))
566              != N_Allocator)
567         {
568           bool went_into_elab_proc = false;
569           int save_force_global = force_global;
570
571           /* The expression may contain N_Expression_With_Actions nodes and
572              thus object declarations from other units.  In this case, even
573              though the expression will eventually be discarded since not a
574              constant, the declarations would be stuck either in the global
575              varpool or in the current scope.  Therefore we force the local
576              context and create a fake scope that we'll zap at the end.  */
577           if (!current_function_decl)
578             {
579               current_function_decl = get_elaboration_procedure ();
580               went_into_elab_proc = true;
581             }
582           force_global = 0;
583           gnat_pushlevel ();
584
585           gnu_expr = gnat_to_gnu (Expression (Declaration_Node (gnat_entity)));
586
587           gnat_zaplevel ();
588           force_global = save_force_global;
589           if (went_into_elab_proc)
590             current_function_decl = NULL_TREE;
591         }
592
593       /* ... fall through ... */
594
595     case E_Exception:
596     case E_Loop_Parameter:
597     case E_Out_Parameter:
598     case E_Variable:
599       {
600         /* Always create a variable for volatile objects and variables seen
601            constant but with a Linker_Section pragma.  */
602         bool const_flag
603           = ((kind == E_Constant || kind == E_Variable)
604              && Is_True_Constant (gnat_entity)
605              && !(kind == E_Variable
606                   && Present (Linker_Section_Pragma (gnat_entity)))
607              && !Treat_As_Volatile (gnat_entity)
608              && (((Nkind (Declaration_Node (gnat_entity))
609                    == N_Object_Declaration)
610                   && Present (Expression (Declaration_Node (gnat_entity))))
611                  || Present (Renamed_Object (gnat_entity))
612                  || imported_p));
613         bool inner_const_flag = const_flag;
614         bool static_p = Is_Statically_Allocated (gnat_entity);
615         bool mutable_p = false;
616         bool used_by_ref = false;
617         tree gnu_ext_name = NULL_TREE;
618         tree renamed_obj = NULL_TREE;
619         tree gnu_object_size;
620
621         if (Present (Renamed_Object (gnat_entity)) && !definition)
622           {
623             if (kind == E_Exception)
624               gnu_expr = gnat_to_gnu_entity (Renamed_Entity (gnat_entity),
625                                              NULL_TREE, 0);
626             else
627               gnu_expr = gnat_to_gnu (Renamed_Object (gnat_entity));
628           }
629
630         /* Get the type after elaborating the renamed object.  */
631         gnu_type = gnat_to_gnu_type (Etype (gnat_entity));
632
633         /* If this is a standard exception definition, then use the standard
634            exception type.  This is necessary to make sure that imported and
635            exported views of exceptions are properly merged in LTO mode.  */
636         if (TREE_CODE (TYPE_NAME (gnu_type)) == TYPE_DECL
637             && DECL_NAME (TYPE_NAME (gnu_type)) == exception_data_name_id)
638           gnu_type = except_type_node;
639
640         /* For a debug renaming declaration, build a debug-only entity.  */
641         if (Present (Debug_Renaming_Link (gnat_entity)))
642           {
643             /* Force a non-null value to make sure the symbol is retained.  */
644             tree value = build1 (INDIRECT_REF, gnu_type,
645                                  build1 (NOP_EXPR,
646                                          build_pointer_type (gnu_type),
647                                          integer_minus_one_node));
648             gnu_decl = build_decl (input_location,
649                                    VAR_DECL, gnu_entity_name, gnu_type);
650             SET_DECL_VALUE_EXPR (gnu_decl, value);
651             DECL_HAS_VALUE_EXPR_P (gnu_decl) = 1;
652             gnat_pushdecl (gnu_decl, gnat_entity);
653             break;
654           }
655
656         /* If this is a loop variable, its type should be the base type.
657            This is because the code for processing a loop determines whether
658            a normal loop end test can be done by comparing the bounds of the
659            loop against those of the base type, which is presumed to be the
660            size used for computation.  But this is not correct when the size
661            of the subtype is smaller than the type.  */
662         if (kind == E_Loop_Parameter)
663           gnu_type = get_base_type (gnu_type);
664
665         /* Reject non-renamed objects whose type is an unconstrained array or
666            any object whose type is a dummy type or void.  */
667         if ((TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE
668              && No (Renamed_Object (gnat_entity)))
669             || TYPE_IS_DUMMY_P (gnu_type)
670             || TREE_CODE (gnu_type) == VOID_TYPE)
671           {
672             gcc_assert (type_annotate_only);
673             if (this_global)
674               force_global--;
675             return error_mark_node;
676           }
677
678         /* If an alignment is specified, use it if valid.  Note that exceptions
679            are objects but don't have an alignment.  We must do this before we
680            validate the size, since the alignment can affect the size.  */
681         if (kind != E_Exception && Known_Alignment (gnat_entity))
682           {
683             gcc_assert (Present (Alignment (gnat_entity)));
684
685             align = validate_alignment (Alignment (gnat_entity), gnat_entity,
686                                         TYPE_ALIGN (gnu_type));
687
688             /* No point in changing the type if there is an address clause
689                as the final type of the object will be a reference type.  */
690             if (Present (Address_Clause (gnat_entity)))
691               align = 0;
692             else
693               {
694                 tree orig_type = gnu_type;
695
696                 gnu_type
697                   = maybe_pad_type (gnu_type, NULL_TREE, align, gnat_entity,
698                                     false, false, definition, true);
699
700                 /* If a padding record was made, declare it now since it will
701                    never be declared otherwise.  This is necessary to ensure
702                    that its subtrees are properly marked.  */
703                 if (gnu_type != orig_type && !DECL_P (TYPE_NAME (gnu_type)))
704                   create_type_decl (TYPE_NAME (gnu_type), gnu_type, true,
705                                     debug_info_p, gnat_entity);
706               }
707           }
708
709         /* If we are defining the object, see if it has a Size and validate it
710            if so.  If we are not defining the object and a Size clause applies,
711            simply retrieve the value.  We don't want to ignore the clause and
712            it is expected to have been validated already.  Then get the new
713            type, if any.  */
714         if (definition)
715           gnu_size = validate_size (Esize (gnat_entity), gnu_type,
716                                     gnat_entity, VAR_DECL, false,
717                                     Has_Size_Clause (gnat_entity));
718         else if (Has_Size_Clause (gnat_entity))
719           gnu_size = UI_To_gnu (Esize (gnat_entity), bitsizetype);
720
721         if (gnu_size)
722           {
723             gnu_type
724               = make_type_from_size (gnu_type, gnu_size,
725                                      Has_Biased_Representation (gnat_entity));
726
727             if (operand_equal_p (TYPE_SIZE (gnu_type), gnu_size, 0))
728               gnu_size = NULL_TREE;
729           }
730
731         /* If this object has self-referential size, it must be a record with
732            a default discriminant.  We are supposed to allocate an object of
733            the maximum size in this case, unless it is a constant with an
734            initializing expression, in which case we can get the size from
735            that.  Note that the resulting size may still be a variable, so
736            this may end up with an indirect allocation.  */
737         if (No (Renamed_Object (gnat_entity))
738             && CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_type)))
739           {
740             if (gnu_expr && kind == E_Constant)
741               {
742                 tree size = TYPE_SIZE (TREE_TYPE (gnu_expr));
743                 if (CONTAINS_PLACEHOLDER_P (size))
744                   {
745                     /* If the initializing expression is itself a constant,
746                        despite having a nominal type with self-referential
747                        size, we can get the size directly from it.  */
748                     if (TREE_CODE (gnu_expr) == COMPONENT_REF
749                         && TYPE_IS_PADDING_P
750                            (TREE_TYPE (TREE_OPERAND (gnu_expr, 0)))
751                         && TREE_CODE (TREE_OPERAND (gnu_expr, 0)) == VAR_DECL
752                         && (TREE_READONLY (TREE_OPERAND (gnu_expr, 0))
753                             || DECL_READONLY_ONCE_ELAB
754                                (TREE_OPERAND (gnu_expr, 0))))
755                       gnu_size = DECL_SIZE (TREE_OPERAND (gnu_expr, 0));
756                     else
757                       gnu_size
758                         = SUBSTITUTE_PLACEHOLDER_IN_EXPR (size, gnu_expr);
759                   }
760                 else
761                   gnu_size = size;
762               }
763             /* We may have no GNU_EXPR because No_Initialization is
764                set even though there's an Expression.  */
765             else if (kind == E_Constant
766                      && (Nkind (Declaration_Node (gnat_entity))
767                          == N_Object_Declaration)
768                      && Present (Expression (Declaration_Node (gnat_entity))))
769               gnu_size
770                 = TYPE_SIZE (gnat_to_gnu_type
771                              (Etype
772                               (Expression (Declaration_Node (gnat_entity)))));
773             else
774               {
775                 gnu_size = max_size (TYPE_SIZE (gnu_type), true);
776                 mutable_p = true;
777               }
778
779             /* If we are at global level and the size isn't constant, call
780                elaborate_expression_1 to make a variable for it rather than
781                calculating it each time.  */
782             if (global_bindings_p () && !TREE_CONSTANT (gnu_size))
783               gnu_size = elaborate_expression_1 (gnu_size, gnat_entity,
784                                                  "SIZE", definition, false);
785           }
786
787         /* If the size is zero byte, make it one byte since some linkers have
788            troubles with zero-sized objects.  If the object will have a
789            template, that will make it nonzero so don't bother.  Also avoid
790            doing that for an object renaming or an object with an address
791            clause, as we would lose useful information on the view size
792            (e.g. for null array slices) and we are not allocating the object
793            here anyway.  */
794         if (((gnu_size
795               && integer_zerop (gnu_size)
796               && !TREE_OVERFLOW (gnu_size))
797              || (TYPE_SIZE (gnu_type)
798                  && integer_zerop (TYPE_SIZE (gnu_type))
799                  && !TREE_OVERFLOW (TYPE_SIZE (gnu_type))))
800             && !Is_Constr_Subt_For_UN_Aliased (Etype (gnat_entity))
801             && No (Renamed_Object (gnat_entity))
802             && No (Address_Clause (gnat_entity)))
803           gnu_size = bitsize_unit_node;
804
805         /* If this is an object with no specified size and alignment, and
806            if either it is atomic or we are not optimizing alignment for
807            space and it is composite and not an exception, an Out parameter
808            or a reference to another object, and the size of its type is a
809            constant, set the alignment to the smallest one which is not
810            smaller than the size, with an appropriate cap.  */
811         if (!gnu_size && align == 0
812             && (Is_Atomic_Or_VFA (gnat_entity)
813                 || (!Optimize_Alignment_Space (gnat_entity)
814                     && kind != E_Exception
815                     && kind != E_Out_Parameter
816                     && Is_Composite_Type (Etype (gnat_entity))
817                     && !Is_Constr_Subt_For_UN_Aliased (Etype (gnat_entity))
818                     && !Is_Exported (gnat_entity)
819                     && !imported_p
820                     && No (Renamed_Object (gnat_entity))
821                     && No (Address_Clause (gnat_entity))))
822             && TREE_CODE (TYPE_SIZE (gnu_type)) == INTEGER_CST)
823           {
824             unsigned int size_cap, align_cap;
825
826             /* No point in promoting the alignment if this doesn't prevent
827                BLKmode access to the object, in particular block copy, as
828                this will for example disable the NRV optimization for it.
829                No point in jumping through all the hoops needed in order
830                to support BIGGEST_ALIGNMENT if we don't really have to.
831                So we cap to the smallest alignment that corresponds to
832                a known efficient memory access pattern of the target.  */
833             if (Is_Atomic_Or_VFA (gnat_entity))
834               {
835                 size_cap = UINT_MAX;
836                 align_cap = BIGGEST_ALIGNMENT;
837               }
838             else
839               {
840                 size_cap = MAX_FIXED_MODE_SIZE;
841                 align_cap = get_mode_alignment (ptr_mode);
842               }
843
844             if (!tree_fits_uhwi_p (TYPE_SIZE (gnu_type))
845                 || compare_tree_int (TYPE_SIZE (gnu_type), size_cap) > 0)
846               align = 0;
847             else if (compare_tree_int (TYPE_SIZE (gnu_type), align_cap) > 0)
848               align = align_cap;
849             else
850               align = ceil_pow2 (tree_to_uhwi (TYPE_SIZE (gnu_type)));
851
852             /* But make sure not to under-align the object.  */
853             if (align <= TYPE_ALIGN (gnu_type))
854               align = 0;
855
856             /* And honor the minimum valid atomic alignment, if any.  */
857 #ifdef MINIMUM_ATOMIC_ALIGNMENT
858             else if (align < MINIMUM_ATOMIC_ALIGNMENT)
859               align = MINIMUM_ATOMIC_ALIGNMENT;
860 #endif
861           }
862
863         /* If the object is set to have atomic components, find the component
864            type and validate it.
865
866            ??? Note that we ignore Has_Volatile_Components on objects; it's
867            not at all clear what to do in that case.  */
868         if (Has_Atomic_Components (gnat_entity))
869           {
870             tree gnu_inner = (TREE_CODE (gnu_type) == ARRAY_TYPE
871                               ? TREE_TYPE (gnu_type) : gnu_type);
872
873             while (TREE_CODE (gnu_inner) == ARRAY_TYPE
874                    && TYPE_MULTI_ARRAY_P (gnu_inner))
875               gnu_inner = TREE_TYPE (gnu_inner);
876
877             check_ok_for_atomic_type (gnu_inner, gnat_entity, true);
878           }
879
880         /* If this is an aliased object with an unconstrained array nominal
881            subtype, make a type that includes the template.  We will either
882            allocate or create a variable of that type, see below.  */
883         if (Is_Constr_Subt_For_UN_Aliased (Etype (gnat_entity))
884             && Is_Array_Type (Underlying_Type (Etype (gnat_entity)))
885             && !type_annotate_only)
886           {
887             tree gnu_array
888               = gnat_to_gnu_type (Base_Type (Etype (gnat_entity)));
889             gnu_type
890               = build_unc_object_type_from_ptr (TREE_TYPE (gnu_array),
891                                                 gnu_type,
892                                                 concat_name (gnu_entity_name,
893                                                              "UNC"),
894                                                 debug_info_p);
895           }
896
897         /* ??? If this is an object of CW type initialized to a value, try to
898            ensure that the object is sufficient aligned for this value, but
899            without pessimizing the allocation.  This is a kludge necessary
900            because we don't support dynamic alignment.  */
901         if (align == 0
902             && Ekind (Etype (gnat_entity)) == E_Class_Wide_Subtype
903             && No (Renamed_Object (gnat_entity))
904             && No (Address_Clause (gnat_entity)))
905           align = get_target_system_allocator_alignment () * BITS_PER_UNIT;
906
907 #ifdef MINIMUM_ATOMIC_ALIGNMENT
908         /* If the size is a constant and no alignment is specified, force
909            the alignment to be the minimum valid atomic alignment.  The
910            restriction on constant size avoids problems with variable-size
911            temporaries; if the size is variable, there's no issue with
912            atomic access.  Also don't do this for a constant, since it isn't
913            necessary and can interfere with constant replacement.  Finally,
914            do not do it for Out parameters since that creates an
915            size inconsistency with In parameters.  */
916         if (align == 0
917             && MINIMUM_ATOMIC_ALIGNMENT > TYPE_ALIGN (gnu_type)
918             && !FLOAT_TYPE_P (gnu_type)
919             && !const_flag && No (Renamed_Object (gnat_entity))
920             && !imported_p && No (Address_Clause (gnat_entity))
921             && kind != E_Out_Parameter
922             && (gnu_size ? TREE_CODE (gnu_size) == INTEGER_CST
923                 : TREE_CODE (TYPE_SIZE (gnu_type)) == INTEGER_CST))
924           align = MINIMUM_ATOMIC_ALIGNMENT;
925 #endif
926
927         /* Make a new type with the desired size and alignment, if needed.
928            But do not take into account alignment promotions to compute the
929            size of the object.  */
930         gnu_object_size = gnu_size ? gnu_size : TYPE_SIZE (gnu_type);
931         if (gnu_size || align > 0)
932           {
933             tree orig_type = gnu_type;
934
935             gnu_type = maybe_pad_type (gnu_type, gnu_size, align, gnat_entity,
936                                        false, false, definition, true);
937
938             /* If a padding record was made, declare it now since it will
939                never be declared otherwise.  This is necessary to ensure
940                that its subtrees are properly marked.  */
941             if (gnu_type != orig_type && !DECL_P (TYPE_NAME (gnu_type)))
942               create_type_decl (TYPE_NAME (gnu_type), gnu_type, true,
943                                 debug_info_p, gnat_entity);
944           }
945
946         /* Now check if the type of the object allows atomic access.  */
947         if (Is_Atomic_Or_VFA (gnat_entity))
948           check_ok_for_atomic_type (gnu_type, gnat_entity, false);
949
950         /* If this is a renaming, avoid as much as possible to create a new
951            object.  However, in some cases, creating it is required because
952            renaming can be applied to objects that are not names in Ada.
953            This processing needs to be applied to the raw expression so as
954            to make it more likely to rename the underlying object.  */
955         if (Present (Renamed_Object (gnat_entity)))
956           {
957             /* If the renamed object had padding, strip off the reference to
958                the inner object and reset our type.  */
959             if ((TREE_CODE (gnu_expr) == COMPONENT_REF
960                  && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_expr, 0))))
961                 /* Strip useless conversions around the object.  */
962                 || gnat_useless_type_conversion (gnu_expr))
963               {
964                 gnu_expr = TREE_OPERAND (gnu_expr, 0);
965                 gnu_type = TREE_TYPE (gnu_expr);
966               }
967
968             /* Or else, if the renamed object has an unconstrained type with
969                default discriminant, use the padded type.  */
970             else if (type_is_padding_self_referential (TREE_TYPE (gnu_expr)))
971               gnu_type = TREE_TYPE (gnu_expr);
972
973             /* Case 1: if this is a constant renaming stemming from a function
974                call, treat it as a normal object whose initial value is what
975                is being renamed.  RM 3.3 says that the result of evaluating a
976                function call is a constant object.  Therefore, it can be the
977                inner object of a constant renaming and the renaming must be
978                fully instantiated, i.e. it cannot be a reference to (part of)
979                an existing object.  And treat null expressions, constructors
980                and literals the same way.  */
981             tree inner = gnu_expr;
982             while (handled_component_p (inner) || CONVERT_EXPR_P (inner))
983               inner = TREE_OPERAND (inner, 0);
984             /* Expand_Dispatching_Call can prepend a comparison of the tags
985                before the call to "=".  */
986             if (TREE_CODE (inner) == TRUTH_ANDIF_EXPR)
987               inner = TREE_OPERAND (inner, 1);
988             if ((TREE_CODE (inner) == CALL_EXPR
989                  && !call_is_atomic_load (inner))
990                 || TREE_CODE (inner) == NULL_EXPR
991                 || TREE_CODE (inner) == CONSTRUCTOR
992                 || CONSTANT_CLASS_P (inner))
993               ;
994
995             /* Case 2: if the renaming entity need not be materialized, use
996                the elaborated renamed expression for the renaming.  But this
997                means that the caller is responsible for evaluating the address
998                of the renaming in the correct place for the definition case to
999                instantiate the SAVE_EXPRs.  */
1000             else if (TREE_CODE (inner) != COMPOUND_EXPR
1001                      && !Materialize_Entity (gnat_entity))
1002               {
1003                 tree init = NULL_TREE;
1004
1005                 gnu_decl
1006                   = elaborate_reference (gnu_expr, gnat_entity, definition,
1007                                          &init);
1008
1009                 /* We cannot evaluate the first arm of a COMPOUND_EXPR in the
1010                    correct place for this case, hence the above test.  */
1011                 gcc_assert (init == NULL_TREE);
1012
1013                 /* No DECL_EXPR will be created so the expression needs to be
1014                    marked manually because it will likely be shared.  */
1015                 if (global_bindings_p ())
1016                   MARK_VISITED (gnu_decl);
1017
1018                 /* This assertion will fail if the renamed object isn't aligned
1019                    enough as to make it possible to honor the alignment set on
1020                    the renaming.  */
1021                 if (align)
1022                   {
1023                     unsigned int ralign = DECL_P (gnu_decl)
1024                                           ? DECL_ALIGN (gnu_decl)
1025                                           : TYPE_ALIGN (TREE_TYPE (gnu_decl));
1026                     gcc_assert (ralign >= align);
1027                   }
1028
1029                 save_gnu_tree (gnat_entity, gnu_decl, true);
1030                 saved = true;
1031                 annotate_object (gnat_entity, gnu_type, NULL_TREE, false);
1032                 break;
1033               }
1034
1035             /* Case 3: otherwise, make a constant pointer to the object we
1036                are renaming and attach the object to the pointer after it is
1037                elaborated.  The object will be referenced directly instead
1038                of indirectly via the pointer to avoid aliasing problems with
1039                non-addressable entities.  The pointer is called a "renaming"
1040                pointer in this case.  Note that we also need to preserve the
1041                volatility of the renamed object through the indirection.  */
1042             else
1043               {
1044                 tree init = NULL_TREE;
1045
1046                 if (TREE_THIS_VOLATILE (gnu_expr) && !TYPE_VOLATILE (gnu_type))
1047                   gnu_type
1048                     = change_qualified_type (gnu_type, TYPE_QUAL_VOLATILE);
1049
1050                 gnu_type = build_reference_type (gnu_type);
1051                 used_by_ref = true;
1052                 const_flag = true;
1053                 inner_const_flag = TREE_READONLY (gnu_expr);
1054                 gnu_size = NULL_TREE;
1055
1056                 renamed_obj
1057                   = elaborate_reference (gnu_expr, gnat_entity, definition,
1058                                          &init);
1059
1060                 /* If we are not defining the entity, the expression will not
1061                    be attached through DECL_INITIAL so it needs to be marked
1062                    manually because it will likely be shared.  Likewise for a
1063                    dereference as it will be folded by the ADDR_EXPR below.  */
1064                 if ((!definition || TREE_CODE (renamed_obj) == INDIRECT_REF)
1065                     && global_bindings_p ())
1066                   MARK_VISITED (renamed_obj);
1067
1068                 if (type_annotate_only
1069                     && TREE_CODE (renamed_obj) == ERROR_MARK)
1070                   gnu_expr = NULL_TREE;
1071                 else
1072                   {
1073                     gnu_expr
1074                       = build_unary_op (ADDR_EXPR, gnu_type, renamed_obj);
1075                     if (init)
1076                       gnu_expr
1077                         = build_compound_expr (TREE_TYPE (gnu_expr), init,
1078                                                gnu_expr);
1079                   }
1080               }
1081           }
1082
1083         /* Make a volatile version of this object's type if we are to make
1084            the object volatile.  We also interpret 13.3(19) conservatively
1085            and disallow any optimizations for such a non-constant object.  */
1086         if ((Treat_As_Volatile (gnat_entity)
1087              || (!const_flag
1088                  && gnu_type != except_type_node
1089                  && (Is_Exported (gnat_entity)
1090                      || imported_p
1091                      || Present (Address_Clause (gnat_entity)))))
1092             && !TYPE_VOLATILE (gnu_type))
1093           {
1094             const int quals
1095               = TYPE_QUAL_VOLATILE
1096                 | (Is_Atomic_Or_VFA (gnat_entity) ? TYPE_QUAL_ATOMIC : 0);
1097             gnu_type = change_qualified_type (gnu_type, quals);
1098           }
1099
1100         /* If we are defining an aliased object whose nominal subtype is
1101            unconstrained, the object is a record that contains both the
1102            template and the object.  If there is an initializer, it will
1103            have already been converted to the right type, but we need to
1104            create the template if there is no initializer.  */
1105         if (definition
1106             && !gnu_expr
1107             && TREE_CODE (gnu_type) == RECORD_TYPE
1108             && (TYPE_CONTAINS_TEMPLATE_P (gnu_type)
1109                 /* Beware that padding might have been introduced above.  */
1110                 || (TYPE_PADDING_P (gnu_type)
1111                     && TREE_CODE (TREE_TYPE (TYPE_FIELDS (gnu_type)))
1112                        == RECORD_TYPE
1113                     && TYPE_CONTAINS_TEMPLATE_P
1114                        (TREE_TYPE (TYPE_FIELDS (gnu_type))))))
1115           {
1116             tree template_field
1117               = TYPE_PADDING_P (gnu_type)
1118                 ? TYPE_FIELDS (TREE_TYPE (TYPE_FIELDS (gnu_type)))
1119                 : TYPE_FIELDS (gnu_type);
1120             vec<constructor_elt, va_gc> *v;
1121             vec_alloc (v, 1);
1122             tree t = build_template (TREE_TYPE (template_field),
1123                                      TREE_TYPE (DECL_CHAIN (template_field)),
1124                                      NULL_TREE);
1125             CONSTRUCTOR_APPEND_ELT (v, template_field, t);
1126             gnu_expr = gnat_build_constructor (gnu_type, v);
1127           }
1128
1129         /* Convert the expression to the type of the object if need be.  */
1130         if (gnu_expr && initial_value_needs_conversion (gnu_type, gnu_expr))
1131           gnu_expr = convert (gnu_type, gnu_expr);
1132
1133         /* If this is a pointer that doesn't have an initializing expression,
1134            initialize it to NULL, unless the object is imported.  */
1135         if (definition
1136             && (POINTER_TYPE_P (gnu_type) || TYPE_IS_FAT_POINTER_P (gnu_type))
1137             && !gnu_expr
1138             && !Is_Imported (gnat_entity))
1139           gnu_expr = integer_zero_node;
1140
1141         /* If we are defining the object and it has an Address clause, we must
1142            either get the address expression from the saved GCC tree for the
1143            object if it has a Freeze node, or elaborate the address expression
1144            here since the front-end has guaranteed that the elaboration has no
1145            effects in this case.  */
1146         if (definition && Present (Address_Clause (gnat_entity)))
1147           {
1148             const Node_Id gnat_clause = Address_Clause (gnat_entity);
1149             Node_Id gnat_expr = Expression (gnat_clause);
1150             tree gnu_address
1151               = present_gnu_tree (gnat_entity)
1152                 ? get_gnu_tree (gnat_entity) : gnat_to_gnu (gnat_expr);
1153
1154             save_gnu_tree (gnat_entity, NULL_TREE, false);
1155
1156             /* Convert the type of the object to a reference type that can
1157                alias everything as per 13.3(19).  */
1158             gnu_type
1159               = build_reference_type_for_mode (gnu_type, ptr_mode, true);
1160             gnu_address = convert (gnu_type, gnu_address);
1161             used_by_ref = true;
1162             const_flag
1163               = !Is_Public (gnat_entity)
1164                 || compile_time_known_address_p (gnat_expr);
1165             gnu_size = NULL_TREE;
1166
1167             /* If this is an aliased object with an unconstrained array nominal
1168                subtype, then it can overlay only another aliased object with an
1169                unconstrained array nominal subtype and compatible template.  */
1170             if (Is_Constr_Subt_For_UN_Aliased (Etype (gnat_entity))
1171                 && Is_Array_Type (Underlying_Type (Etype (gnat_entity)))
1172                 && !type_annotate_only)
1173               {
1174                 tree rec_type = TREE_TYPE (gnu_type);
1175                 tree off = byte_position (DECL_CHAIN (TYPE_FIELDS (rec_type)));
1176
1177                 /* This is the pattern built for a regular object.  */
1178                 if (TREE_CODE (gnu_address) == POINTER_PLUS_EXPR
1179                     && TREE_OPERAND (gnu_address, 1) == off)
1180                   gnu_address = TREE_OPERAND (gnu_address, 0);
1181                 /* This is the pattern built for an overaligned object.  */
1182                 else if (TREE_CODE (gnu_address) == POINTER_PLUS_EXPR
1183                          && TREE_CODE (TREE_OPERAND (gnu_address, 1))
1184                             == PLUS_EXPR
1185                          && TREE_OPERAND (TREE_OPERAND (gnu_address, 1), 1)
1186                             == off)
1187                   gnu_address
1188                     = build2 (POINTER_PLUS_EXPR, gnu_type,
1189                               TREE_OPERAND (gnu_address, 0),
1190                               TREE_OPERAND (TREE_OPERAND (gnu_address, 1), 0));
1191                 else
1192                   {
1193                     post_error_ne ("aliased object& with unconstrained array "
1194                                    "nominal subtype", gnat_clause,
1195                                    gnat_entity);
1196                     post_error ("\\can overlay only aliased object with "
1197                                 "compatible subtype", gnat_clause);
1198                   }
1199               }
1200
1201             /* If this is a deferred constant, the initializer is attached to
1202                the full view.  */
1203             if (kind == E_Constant && Present (Full_View (gnat_entity)))
1204               gnu_expr
1205                 = gnat_to_gnu
1206                     (Expression (Declaration_Node (Full_View (gnat_entity))));
1207
1208             /* If we don't have an initializing expression for the underlying
1209                variable, the initializing expression for the pointer is the
1210                specified address.  Otherwise, we have to make a COMPOUND_EXPR
1211                to assign both the address and the initial value.  */
1212             if (!gnu_expr)
1213               gnu_expr = gnu_address;
1214             else
1215               gnu_expr
1216                 = build2 (COMPOUND_EXPR, gnu_type,
1217                           build_binary_op (INIT_EXPR, NULL_TREE,
1218                                            build_unary_op (INDIRECT_REF,
1219                                                            NULL_TREE,
1220                                                            gnu_address),
1221                                            gnu_expr),
1222                           gnu_address);
1223           }
1224
1225         /* If it has an address clause and we are not defining it, mark it
1226            as an indirect object.  Likewise for Stdcall objects that are
1227            imported.  */
1228         if ((!definition && Present (Address_Clause (gnat_entity)))
1229             || (Is_Imported (gnat_entity)
1230                 && Has_Stdcall_Convention (gnat_entity)))
1231           {
1232             /* Convert the type of the object to a reference type that can
1233                alias everything as per 13.3(19).  */
1234             gnu_type
1235               = build_reference_type_for_mode (gnu_type, ptr_mode, true);
1236             used_by_ref = true;
1237             gnu_size = NULL_TREE;
1238
1239             /* No point in taking the address of an initializing expression
1240                that isn't going to be used.  */
1241             gnu_expr = NULL_TREE;
1242
1243             /* If it has an address clause whose value is known at compile
1244                time, make the object a CONST_DECL.  This will avoid a
1245                useless dereference.  */
1246             if (Present (Address_Clause (gnat_entity)))
1247               {
1248                 Node_Id gnat_address
1249                   = Expression (Address_Clause (gnat_entity));
1250
1251                 if (compile_time_known_address_p (gnat_address))
1252                   {
1253                     gnu_expr = gnat_to_gnu (gnat_address);
1254                     const_flag = true;
1255                   }
1256               }
1257           }
1258
1259         /* If we are at top level and this object is of variable size,
1260            make the actual type a hidden pointer to the real type and
1261            make the initializer be a memory allocation and initialization.
1262            Likewise for objects we aren't defining (presumed to be
1263            external references from other packages), but there we do
1264            not set up an initialization.
1265
1266            If the object's size overflows, make an allocator too, so that
1267            Storage_Error gets raised.  Note that we will never free
1268            such memory, so we presume it never will get allocated.  */
1269         if (!allocatable_size_p (TYPE_SIZE_UNIT (gnu_type),
1270                                  global_bindings_p ()
1271                                  || !definition
1272                                  || static_p)
1273             || (gnu_size
1274                 && !allocatable_size_p (convert (sizetype,
1275                                                  size_binop
1276                                                  (CEIL_DIV_EXPR, gnu_size,
1277                                                   bitsize_unit_node)),
1278                                         global_bindings_p ()
1279                                         || !definition
1280                                         || static_p)))
1281           {
1282             gnu_type = build_reference_type (gnu_type);
1283             used_by_ref = true;
1284             const_flag = true;
1285             gnu_size = NULL_TREE;
1286
1287             /* In case this was a aliased object whose nominal subtype is
1288                unconstrained, the pointer above will be a thin pointer and
1289                build_allocator will automatically make the template.
1290
1291                If we have a template initializer only (that we made above),
1292                pretend there is none and rely on what build_allocator creates
1293                again anyway.  Otherwise (if we have a full initializer), get
1294                the data part and feed that to build_allocator.
1295
1296                If we are elaborating a mutable object, tell build_allocator to
1297                ignore a possibly simpler size from the initializer, if any, as
1298                we must allocate the maximum possible size in this case.  */
1299             if (definition && !imported_p)
1300               {
1301                 tree gnu_alloc_type = TREE_TYPE (gnu_type);
1302
1303                 if (TREE_CODE (gnu_alloc_type) == RECORD_TYPE
1304                     && TYPE_CONTAINS_TEMPLATE_P (gnu_alloc_type))
1305                   {
1306                     gnu_alloc_type
1307                       = TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (gnu_alloc_type)));
1308
1309                     if (TREE_CODE (gnu_expr) == CONSTRUCTOR
1310                         && vec_safe_length (CONSTRUCTOR_ELTS (gnu_expr)) == 1)
1311                       gnu_expr = NULL_TREE;
1312                     else
1313                       gnu_expr
1314                         = build_component_ref
1315                             (gnu_expr, NULL_TREE,
1316                              DECL_CHAIN (TYPE_FIELDS (TREE_TYPE (gnu_expr))),
1317                              false);
1318                   }
1319
1320                 if (TREE_CODE (TYPE_SIZE_UNIT (gnu_alloc_type)) == INTEGER_CST
1321                     && !valid_constant_size_p (TYPE_SIZE_UNIT (gnu_alloc_type)))
1322                   post_error ("?`Storage_Error` will be raised at run time!",
1323                               gnat_entity);
1324
1325                 gnu_expr
1326                   = build_allocator (gnu_alloc_type, gnu_expr, gnu_type,
1327                                      Empty, Empty, gnat_entity, mutable_p);
1328               }
1329             else
1330               gnu_expr = NULL_TREE;
1331           }
1332
1333         /* If this object would go into the stack and has an alignment larger
1334            than the largest stack alignment the back-end can honor, resort to
1335            a variable of "aligning type".  */
1336         if (definition
1337             && !global_bindings_p ()
1338             && !static_p
1339             && !imported_p
1340             && TYPE_ALIGN (gnu_type) > BIGGEST_ALIGNMENT)
1341           {
1342             /* Create the new variable.  No need for extra room before the
1343                aligned field as this is in automatic storage.  */
1344             tree gnu_new_type
1345               = make_aligning_type (gnu_type, TYPE_ALIGN (gnu_type),
1346                                     TYPE_SIZE_UNIT (gnu_type),
1347                                     BIGGEST_ALIGNMENT, 0, gnat_entity);
1348             tree gnu_new_var
1349               = create_var_decl (create_concat_name (gnat_entity, "ALIGN"),
1350                                  NULL_TREE, gnu_new_type, NULL_TREE, false,
1351                                  false, false, false, NULL, gnat_entity);
1352             DECL_ARTIFICIAL (gnu_new_var) = 1;
1353
1354             /* Initialize the aligned field if we have an initializer.  */
1355             if (gnu_expr)
1356               add_stmt_with_node
1357                 (build_binary_op (INIT_EXPR, NULL_TREE,
1358                                   build_component_ref
1359                                   (gnu_new_var, NULL_TREE,
1360                                    TYPE_FIELDS (gnu_new_type), false),
1361                                   gnu_expr),
1362                  gnat_entity);
1363
1364             /* And setup this entity as a reference to the aligned field.  */
1365             gnu_type = build_reference_type (gnu_type);
1366             gnu_expr
1367               = build_unary_op
1368                 (ADDR_EXPR, NULL_TREE,
1369                  build_component_ref (gnu_new_var, NULL_TREE,
1370                                       TYPE_FIELDS (gnu_new_type), false));
1371             TREE_CONSTANT (gnu_expr) = 1;
1372
1373             used_by_ref = true;
1374             const_flag = true;
1375             gnu_size = NULL_TREE;
1376           }
1377
1378         /* If this is an aliased object with an unconstrained array nominal
1379            subtype, we make its type a thin reference, i.e. the reference
1380            counterpart of a thin pointer, so it points to the array part.
1381            This is aimed to make it easier for the debugger to decode the
1382            object.  Note that we have to do it this late because of the
1383            couple of allocation adjustments that might be made above.  */
1384         if (Is_Constr_Subt_For_UN_Aliased (Etype (gnat_entity))
1385             && Is_Array_Type (Underlying_Type (Etype (gnat_entity)))
1386             && !type_annotate_only)
1387           {
1388             /* In case the object with the template has already been allocated
1389                just above, we have nothing to do here.  */
1390             if (!TYPE_IS_THIN_POINTER_P (gnu_type))
1391               {
1392                 tree gnu_unc_var
1393                    = create_var_decl (concat_name (gnu_entity_name, "UNC"),
1394                                       NULL_TREE, gnu_type, gnu_expr,
1395                                       const_flag, Is_Public (gnat_entity),
1396                                       imported_p || !definition, static_p,
1397                                       NULL, gnat_entity);
1398                 gnu_expr = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_unc_var);
1399                 TREE_CONSTANT (gnu_expr) = 1;
1400
1401                 used_by_ref = true;
1402                 const_flag = true;
1403                 inner_const_flag = TREE_READONLY (gnu_unc_var);
1404                 gnu_size = NULL_TREE;
1405               }
1406
1407             tree gnu_array
1408               = gnat_to_gnu_type (Base_Type (Etype (gnat_entity)));
1409             gnu_type
1410               = build_reference_type (TYPE_OBJECT_RECORD_TYPE (gnu_array));
1411           }
1412
1413         if (const_flag)
1414           gnu_type = change_qualified_type (gnu_type, TYPE_QUAL_CONST);
1415
1416         /* Convert the expression to the type of the object if need be.  */
1417         if (gnu_expr && initial_value_needs_conversion (gnu_type, gnu_expr))
1418           gnu_expr = convert (gnu_type, gnu_expr);
1419
1420         /* If this name is external or a name was specified, use it, but don't
1421            use the Interface_Name with an address clause (see cd30005).  */
1422         if ((Present (Interface_Name (gnat_entity))
1423              && No (Address_Clause (gnat_entity)))
1424             || (Is_Public (gnat_entity)
1425                 && (!Is_Imported (gnat_entity) || Is_Exported (gnat_entity))))
1426           gnu_ext_name = create_concat_name (gnat_entity, NULL);
1427
1428         /* If this is an aggregate constant initialized to a constant, force it
1429            to be statically allocated.  This saves an initialization copy.  */
1430         if (!static_p
1431             && const_flag
1432             && gnu_expr && TREE_CONSTANT (gnu_expr)
1433             && AGGREGATE_TYPE_P (gnu_type)
1434             && tree_fits_uhwi_p (TYPE_SIZE_UNIT (gnu_type))
1435             && !(TYPE_IS_PADDING_P (gnu_type)
1436                  && !tree_fits_uhwi_p (TYPE_SIZE_UNIT
1437                                        (TREE_TYPE (TYPE_FIELDS (gnu_type))))))
1438           static_p = true;
1439
1440         /* Deal with a pragma Linker_Section on a constant or variable.  */
1441         if ((kind == E_Constant || kind == E_Variable)
1442             && Present (Linker_Section_Pragma (gnat_entity)))
1443           prepend_one_attribute_pragma (&attr_list,
1444                                         Linker_Section_Pragma (gnat_entity));
1445
1446         /* Now create the variable or the constant and set various flags.  */
1447         gnu_decl
1448           = create_var_decl_1 (gnu_entity_name, gnu_ext_name, gnu_type,
1449                                gnu_expr, const_flag, Is_Public (gnat_entity),
1450                                imported_p || !definition, static_p,
1451                                !renamed_obj, attr_list, gnat_entity);
1452         DECL_BY_REF_P (gnu_decl) = used_by_ref;
1453         DECL_POINTS_TO_READONLY_P (gnu_decl) = used_by_ref && inner_const_flag;
1454         DECL_CAN_NEVER_BE_NULL_P (gnu_decl) = Can_Never_Be_Null (gnat_entity);
1455
1456         /* If we are defining an Out parameter and optimization isn't enabled,
1457            create a fake PARM_DECL for debugging purposes and make it point to
1458            the VAR_DECL.  Suppress debug info for the latter but make sure it
1459            will live in memory so that it can be accessed from within the
1460            debugger through the PARM_DECL.  */
1461         if (kind == E_Out_Parameter
1462             && definition
1463             && debug_info_p
1464             && !optimize
1465             && !flag_generate_lto)
1466           {
1467             tree param = create_param_decl (gnu_entity_name, gnu_type, false);
1468             gnat_pushdecl (param, gnat_entity);
1469             SET_DECL_VALUE_EXPR (param, gnu_decl);
1470             DECL_HAS_VALUE_EXPR_P (param) = 1;
1471             DECL_IGNORED_P (gnu_decl) = 1;
1472             TREE_ADDRESSABLE (gnu_decl) = 1;
1473           }
1474
1475         /* If this is a loop parameter, set the corresponding flag.  */
1476         else if (kind == E_Loop_Parameter)
1477           DECL_LOOP_PARM_P (gnu_decl) = 1;
1478
1479         /* If this is a renaming pointer, attach the renamed object to it.  */
1480         if (renamed_obj)
1481           SET_DECL_RENAMED_OBJECT (gnu_decl, renamed_obj);
1482
1483         /* If this is a constant and we are defining it or it generates a real
1484            symbol at the object level and we are referencing it, we may want
1485            or need to have a true variable to represent it:
1486              - if optimization isn't enabled, for debugging purposes,
1487              - if the constant is public and not overlaid on something else,
1488              - if its address is taken,
1489              - if either itself or its type is aliased.  */
1490         if (TREE_CODE (gnu_decl) == CONST_DECL
1491             && (definition || Sloc (gnat_entity) > Standard_Location)
1492             && ((!optimize && debug_info_p)
1493                 || (Is_Public (gnat_entity)
1494                     && No (Address_Clause (gnat_entity)))
1495                 || Address_Taken (gnat_entity)
1496                 || Is_Aliased (gnat_entity)
1497                 || Is_Aliased (Etype (gnat_entity))))
1498           {
1499             tree gnu_corr_var
1500               = create_true_var_decl (gnu_entity_name, gnu_ext_name, gnu_type,
1501                                       gnu_expr, true, Is_Public (gnat_entity),
1502                                       !definition, static_p, attr_list,
1503                                       gnat_entity);
1504
1505             SET_DECL_CONST_CORRESPONDING_VAR (gnu_decl, gnu_corr_var);
1506
1507             /* As debugging information will be generated for the variable,
1508                do not generate debugging information for the constant.  */
1509             if (debug_info_p)
1510               DECL_IGNORED_P (gnu_decl) = 1;
1511             else
1512               DECL_IGNORED_P (gnu_corr_var) = 1;
1513           }
1514
1515         /* If this is a constant, even if we don't need a true variable, we
1516            may need to avoid returning the initializer in every case.  That
1517            can happen for the address of a (constant) constructor because,
1518            upon dereferencing it, the constructor will be reinjected in the
1519            tree, which may not be valid in every case; see lvalue_required_p
1520            for more details.  */
1521         if (TREE_CODE (gnu_decl) == CONST_DECL)
1522           DECL_CONST_ADDRESS_P (gnu_decl) = constructor_address_p (gnu_expr);
1523
1524         /* If this object is declared in a block that contains a block with an
1525            exception handler, and we aren't using the GCC exception mechanism,
1526            we must force this variable in memory in order to avoid an invalid
1527            optimization.  */
1528         if (Exception_Mechanism != Back_End_Exceptions
1529             && Has_Nested_Block_With_Handler (Scope (gnat_entity)))
1530           TREE_ADDRESSABLE (gnu_decl) = 1;
1531
1532         /* If this is a local variable with non-BLKmode and aggregate type,
1533            and optimization isn't enabled, then force it in memory so that
1534            a register won't be allocated to it with possible subparts left
1535            uninitialized and reaching the register allocator.  */
1536         else if (TREE_CODE (gnu_decl) == VAR_DECL
1537                  && !DECL_EXTERNAL (gnu_decl)
1538                  && !TREE_STATIC (gnu_decl)
1539                  && DECL_MODE (gnu_decl) != BLKmode
1540                  && AGGREGATE_TYPE_P (TREE_TYPE (gnu_decl))
1541                  && !TYPE_IS_FAT_POINTER_P (TREE_TYPE (gnu_decl))
1542                  && !optimize)
1543           TREE_ADDRESSABLE (gnu_decl) = 1;
1544
1545         /* If we are defining an object with variable size or an object with
1546            fixed size that will be dynamically allocated, and we are using the
1547            setjmp/longjmp exception mechanism, update the setjmp buffer.  */
1548         if (definition
1549             && Exception_Mechanism == Setjmp_Longjmp
1550             && get_block_jmpbuf_decl ()
1551             && DECL_SIZE_UNIT (gnu_decl)
1552             && (TREE_CODE (DECL_SIZE_UNIT (gnu_decl)) != INTEGER_CST
1553                 || (flag_stack_check == GENERIC_STACK_CHECK
1554                     && compare_tree_int (DECL_SIZE_UNIT (gnu_decl),
1555                                          STACK_CHECK_MAX_VAR_SIZE) > 0)))
1556           add_stmt_with_node (build_call_n_expr
1557                               (update_setjmp_buf_decl, 1,
1558                                build_unary_op (ADDR_EXPR, NULL_TREE,
1559                                                get_block_jmpbuf_decl ())),
1560                               gnat_entity);
1561
1562         /* Back-annotate Esize and Alignment of the object if not already
1563            known.  Note that we pick the values of the type, not those of
1564            the object, to shield ourselves from low-level platform-dependent
1565            adjustments like alignment promotion.  This is both consistent with
1566            all the treatment above, where alignment and size are set on the
1567            type of the object and not on the object directly, and makes it
1568            possible to support all confirming representation clauses.  */
1569         annotate_object (gnat_entity, TREE_TYPE (gnu_decl), gnu_object_size,
1570                          used_by_ref);
1571       }
1572       break;
1573
1574     case E_Void:
1575       /* Return a TYPE_DECL for "void" that we previously made.  */
1576       gnu_decl = TYPE_NAME (void_type_node);
1577       break;
1578
1579     case E_Enumeration_Type:
1580       /* A special case: for the types Character and Wide_Character in
1581          Standard, we do not list all the literals.  So if the literals
1582          are not specified, make this an unsigned integer type.  */
1583       if (No (First_Literal (gnat_entity)))
1584         {
1585           gnu_type = make_unsigned_type (esize);
1586           TYPE_NAME (gnu_type) = gnu_entity_name;
1587
1588           /* Set TYPE_STRING_FLAG for Character and Wide_Character types.
1589              This is needed by the DWARF-2 back-end to distinguish between
1590              unsigned integer types and character types.  */
1591           TYPE_STRING_FLAG (gnu_type) = 1;
1592         }
1593       else
1594         {
1595           /* We have a list of enumeral constants in First_Literal.  We make a
1596              CONST_DECL for each one and build into GNU_LITERAL_LIST the list
1597              to be placed into TYPE_FIELDS.  Each node is itself a TREE_LIST
1598              whose TREE_VALUE is the literal name and whose TREE_PURPOSE is the
1599              value of the literal.  But when we have a regular boolean type, we
1600              simplify this a little by using a BOOLEAN_TYPE.  */
1601           const bool is_boolean = Is_Boolean_Type (gnat_entity)
1602                                   && !Has_Non_Standard_Rep (gnat_entity);
1603           const bool is_unsigned = Is_Unsigned_Type (gnat_entity);
1604           tree gnu_list = NULL_TREE;
1605           Entity_Id gnat_literal;
1606
1607           gnu_type = make_node (is_boolean ? BOOLEAN_TYPE : ENUMERAL_TYPE);
1608           TYPE_PRECISION (gnu_type) = esize;
1609           TYPE_UNSIGNED (gnu_type) = is_unsigned;
1610           set_min_and_max_values_for_integral_type (gnu_type, esize,
1611                                                     TYPE_SIGN (gnu_type));
1612           process_attributes (&gnu_type, &attr_list, true, gnat_entity);
1613           layout_type (gnu_type);
1614
1615           for (gnat_literal = First_Literal (gnat_entity);
1616                Present (gnat_literal);
1617                gnat_literal = Next_Literal (gnat_literal))
1618             {
1619               tree gnu_value
1620                 = UI_To_gnu (Enumeration_Rep (gnat_literal), gnu_type);
1621               tree gnu_literal
1622                 = create_var_decl (get_entity_name (gnat_literal), NULL_TREE,
1623                                    gnu_type, gnu_value, true, false, false,
1624                                    false, NULL, gnat_literal);
1625               /* Do not generate debug info for individual enumerators.  */
1626               DECL_IGNORED_P (gnu_literal) = 1;
1627               save_gnu_tree (gnat_literal, gnu_literal, false);
1628               gnu_list
1629                 = tree_cons (DECL_NAME (gnu_literal), gnu_value, gnu_list);
1630             }
1631
1632           if (!is_boolean)
1633             TYPE_VALUES (gnu_type) = nreverse (gnu_list);
1634
1635           /* Note that the bounds are updated at the end of this function
1636              to avoid an infinite recursion since they refer to the type.  */
1637           goto discrete_type;
1638         }
1639       break;
1640
1641     case E_Signed_Integer_Type:
1642     case E_Ordinary_Fixed_Point_Type:
1643     case E_Decimal_Fixed_Point_Type:
1644       /* For integer types, just make a signed type the appropriate number
1645          of bits.  */
1646       gnu_type = make_signed_type (esize);
1647       goto discrete_type;
1648
1649     case E_Modular_Integer_Type:
1650       {
1651         /* For modular types, make the unsigned type of the proper number
1652            of bits and then set up the modulus, if required.  */
1653         tree gnu_modulus, gnu_high = NULL_TREE;
1654
1655         /* Packed Array Impl. Types are supposed to be subtypes only.  */
1656         gcc_assert (!Is_Packed_Array_Impl_Type (gnat_entity));
1657
1658         gnu_type = make_unsigned_type (esize);
1659
1660         /* Get the modulus in this type.  If it overflows, assume it is because
1661            it is equal to 2**Esize.  Note that there is no overflow checking
1662            done on unsigned type, so we detect the overflow by looking for
1663            a modulus of zero, which is otherwise invalid.  */
1664         gnu_modulus = UI_To_gnu (Modulus (gnat_entity), gnu_type);
1665
1666         if (!integer_zerop (gnu_modulus))
1667           {
1668             TYPE_MODULAR_P (gnu_type) = 1;
1669             SET_TYPE_MODULUS (gnu_type, gnu_modulus);
1670             gnu_high = fold_build2 (MINUS_EXPR, gnu_type, gnu_modulus,
1671                                     convert (gnu_type, integer_one_node));
1672           }
1673
1674         /* If the upper bound is not maximal, make an extra subtype.  */
1675         if (gnu_high
1676             && !tree_int_cst_equal (gnu_high, TYPE_MAX_VALUE (gnu_type)))
1677           {
1678             tree gnu_subtype = make_unsigned_type (esize);
1679             SET_TYPE_RM_MAX_VALUE (gnu_subtype, gnu_high);
1680             TREE_TYPE (gnu_subtype) = gnu_type;
1681             TYPE_EXTRA_SUBTYPE_P (gnu_subtype) = 1;
1682             TYPE_NAME (gnu_type) = create_concat_name (gnat_entity, "UMT");
1683             gnu_type = gnu_subtype;
1684           }
1685       }
1686       goto discrete_type;
1687
1688     case E_Signed_Integer_Subtype:
1689     case E_Enumeration_Subtype:
1690     case E_Modular_Integer_Subtype:
1691     case E_Ordinary_Fixed_Point_Subtype:
1692     case E_Decimal_Fixed_Point_Subtype:
1693
1694       /* For integral subtypes, we make a new INTEGER_TYPE.  Note that we do
1695          not want to call create_range_type since we would like each subtype
1696          node to be distinct.  ??? Historically this was in preparation for
1697          when memory aliasing is implemented, but that's obsolete now given
1698          the call to relate_alias_sets below.
1699
1700          The TREE_TYPE field of the INTEGER_TYPE points to the base type;
1701          this fact is used by the arithmetic conversion functions.
1702
1703          We elaborate the Ancestor_Subtype if it is not in the current unit
1704          and one of our bounds is non-static.  We do this to ensure consistent
1705          naming in the case where several subtypes share the same bounds, by
1706          elaborating the first such subtype first, thus using its name.  */
1707
1708       if (!definition
1709           && Present (Ancestor_Subtype (gnat_entity))
1710           && !In_Extended_Main_Code_Unit (Ancestor_Subtype (gnat_entity))
1711           && (!Compile_Time_Known_Value (Type_Low_Bound (gnat_entity))
1712               || !Compile_Time_Known_Value (Type_High_Bound (gnat_entity))))
1713         gnat_to_gnu_entity (Ancestor_Subtype (gnat_entity), gnu_expr, 0);
1714
1715       /* Set the precision to the Esize except for bit-packed arrays.  */
1716       if (Is_Packed_Array_Impl_Type (gnat_entity)
1717           && Is_Bit_Packed_Array (Original_Array_Type (gnat_entity)))
1718         esize = UI_To_Int (RM_Size (gnat_entity));
1719
1720       /* This should be an unsigned type if the base type is unsigned or
1721          if the lower bound is constant and non-negative or if the type
1722          is biased.  */
1723       if (Is_Unsigned_Type (Etype (gnat_entity))
1724           || Is_Unsigned_Type (gnat_entity)
1725           || Has_Biased_Representation (gnat_entity))
1726         gnu_type = make_unsigned_type (esize);
1727       else
1728         gnu_type = make_signed_type (esize);
1729       TREE_TYPE (gnu_type) = get_unpadded_type (Etype (gnat_entity));
1730
1731       SET_TYPE_RM_MIN_VALUE
1732         (gnu_type, elaborate_expression (Type_Low_Bound (gnat_entity),
1733                                          gnat_entity, "L", definition, true,
1734                                          Needs_Debug_Info (gnat_entity)));
1735
1736       SET_TYPE_RM_MAX_VALUE
1737         (gnu_type, elaborate_expression (Type_High_Bound (gnat_entity),
1738                                          gnat_entity, "U", definition, true,
1739                                          Needs_Debug_Info (gnat_entity)));
1740
1741       TYPE_BIASED_REPRESENTATION_P (gnu_type)
1742         = Has_Biased_Representation (gnat_entity);
1743
1744       /* Inherit our alias set from what we're a subtype of.  Subtypes
1745          are not different types and a pointer can designate any instance
1746          within a subtype hierarchy.  */
1747       relate_alias_sets (gnu_type, TREE_TYPE (gnu_type), ALIAS_SET_COPY);
1748
1749       /* One of the above calls might have caused us to be elaborated,
1750          so don't blow up if so.  */
1751       if (present_gnu_tree (gnat_entity))
1752         {
1753           maybe_present = true;
1754           break;
1755         }
1756
1757       /* Attach the TYPE_STUB_DECL in case we have a parallel type.  */
1758       TYPE_STUB_DECL (gnu_type)
1759         = create_type_stub_decl (gnu_entity_name, gnu_type);
1760
1761       /* For a packed array, make the original array type a parallel type.  */
1762       if (debug_info_p && Is_Packed_Array_Impl_Type (gnat_entity))
1763         add_parallel_type_for_packed_array (gnu_type, gnat_entity);
1764
1765     discrete_type:
1766
1767       /* We have to handle clauses that under-align the type specially.  */
1768       if ((Present (Alignment_Clause (gnat_entity))
1769            || (Is_Packed_Array_Impl_Type (gnat_entity)
1770                && Present
1771                   (Alignment_Clause (Original_Array_Type (gnat_entity)))))
1772           && UI_Is_In_Int_Range (Alignment (gnat_entity)))
1773         {
1774           align = UI_To_Int (Alignment (gnat_entity)) * BITS_PER_UNIT;
1775           if (align >= TYPE_ALIGN (gnu_type))
1776             align = 0;
1777         }
1778
1779       /* If the type we are dealing with represents a bit-packed array,
1780          we need to have the bits left justified on big-endian targets
1781          and right justified on little-endian targets.  We also need to
1782          ensure that when the value is read (e.g. for comparison of two
1783          such values), we only get the good bits, since the unused bits
1784          are uninitialized.  Both goals are accomplished by wrapping up
1785          the modular type in an enclosing record type.  */
1786       if (Is_Packed_Array_Impl_Type (gnat_entity)
1787           && Is_Bit_Packed_Array (Original_Array_Type (gnat_entity)))
1788         {
1789           tree gnu_field_type, gnu_field;
1790
1791           /* Set the RM size before wrapping up the original type.  */
1792           SET_TYPE_RM_SIZE (gnu_type,
1793                             UI_To_gnu (RM_Size (gnat_entity), bitsizetype));
1794           TYPE_PACKED_ARRAY_TYPE_P (gnu_type) = 1;
1795
1796           /* Create a stripped-down declaration, mainly for debugging.  */
1797           create_type_decl (gnu_entity_name, gnu_type, true, debug_info_p,
1798                             gnat_entity);
1799
1800           /* Now save it and build the enclosing record type.  */
1801           gnu_field_type = gnu_type;
1802
1803           gnu_type = make_node (RECORD_TYPE);
1804           TYPE_NAME (gnu_type) = create_concat_name (gnat_entity, "JM");
1805           TYPE_PACKED (gnu_type) = 1;
1806           TYPE_SIZE (gnu_type) = TYPE_SIZE (gnu_field_type);
1807           TYPE_SIZE_UNIT (gnu_type) = TYPE_SIZE_UNIT (gnu_field_type);
1808           SET_TYPE_ADA_SIZE (gnu_type, TYPE_RM_SIZE (gnu_field_type));
1809
1810           /* Propagate the alignment of the modular type to the record type,
1811              unless there is an alignment clause that under-aligns the type.
1812              This means that bit-packed arrays are given "ceil" alignment for
1813              their size by default, which may seem counter-intuitive but makes
1814              it possible to overlay them on modular types easily.  */
1815           TYPE_ALIGN (gnu_type)
1816             = align > 0 ? align : TYPE_ALIGN (gnu_field_type);
1817
1818           relate_alias_sets (gnu_type, gnu_field_type, ALIAS_SET_COPY);
1819
1820           /* Don't declare the field as addressable since we won't be taking
1821              its address and this would prevent create_field_decl from making
1822              a bitfield.  */
1823           gnu_field
1824             = create_field_decl (get_identifier ("OBJECT"), gnu_field_type,
1825                                  gnu_type, NULL_TREE, bitsize_zero_node, 1, 0);
1826
1827           /* Do not emit debug info until after the parallel type is added.  */
1828           finish_record_type (gnu_type, gnu_field, 2, false);
1829           compute_record_mode (gnu_type);
1830           TYPE_JUSTIFIED_MODULAR_P (gnu_type) = 1;
1831
1832           if (debug_info_p)
1833             {
1834               /* Make the original array type a parallel type.  */
1835               add_parallel_type_for_packed_array (gnu_type, gnat_entity);
1836
1837               rest_of_record_type_compilation (gnu_type);
1838             }
1839         }
1840
1841       /* If the type we are dealing with has got a smaller alignment than the
1842          natural one, we need to wrap it up in a record type and misalign the
1843          latter; we reuse the padding machinery for this purpose.  Note that,
1844          even if the record type is marked as packed because of misalignment,
1845          we don't pack the field so as to give it the size of the type.  */
1846       else if (align > 0)
1847         {
1848           tree gnu_field_type, gnu_field;
1849
1850           /* Set the RM size before wrapping up the type.  */
1851           SET_TYPE_RM_SIZE (gnu_type,
1852                             UI_To_gnu (RM_Size (gnat_entity), bitsizetype));
1853
1854           /* Create a stripped-down declaration, mainly for debugging.  */
1855           create_type_decl (gnu_entity_name, gnu_type, true, debug_info_p,
1856                             gnat_entity);
1857
1858           /* Now save it and build the enclosing record type.  */
1859           gnu_field_type = gnu_type;
1860
1861           gnu_type = make_node (RECORD_TYPE);
1862           TYPE_NAME (gnu_type) = create_concat_name (gnat_entity, "PAD");
1863           TYPE_PACKED (gnu_type) = 1;
1864           TYPE_SIZE (gnu_type) = TYPE_SIZE (gnu_field_type);
1865           TYPE_SIZE_UNIT (gnu_type) = TYPE_SIZE_UNIT (gnu_field_type);
1866           SET_TYPE_ADA_SIZE (gnu_type, TYPE_RM_SIZE (gnu_field_type));
1867           TYPE_ALIGN (gnu_type) = align;
1868           relate_alias_sets (gnu_type, gnu_field_type, ALIAS_SET_COPY);
1869
1870           /* Don't declare the field as addressable since we won't be taking
1871              its address and this would prevent create_field_decl from making
1872              a bitfield.  */
1873           gnu_field
1874             = create_field_decl (get_identifier ("F"), gnu_field_type,
1875                                  gnu_type, TYPE_SIZE (gnu_field_type),
1876                                  bitsize_zero_node, 0, 0);
1877
1878           finish_record_type (gnu_type, gnu_field, 2, debug_info_p);
1879           compute_record_mode (gnu_type);
1880           TYPE_PADDING_P (gnu_type) = 1;
1881         }
1882
1883       break;
1884
1885     case E_Floating_Point_Type:
1886       /* The type of the Low and High bounds can be our type if this is
1887          a type from Standard, so set them at the end of the function.  */
1888       gnu_type = make_node (REAL_TYPE);
1889       TYPE_PRECISION (gnu_type) = fp_size_to_prec (esize);
1890       layout_type (gnu_type);
1891       break;
1892
1893     case E_Floating_Point_Subtype:
1894       /* See the E_Signed_Integer_Subtype case for the rationale.  */
1895       if (!definition
1896           && Present (Ancestor_Subtype (gnat_entity))
1897           && !In_Extended_Main_Code_Unit (Ancestor_Subtype (gnat_entity))
1898           && (!Compile_Time_Known_Value (Type_Low_Bound (gnat_entity))
1899               || !Compile_Time_Known_Value (Type_High_Bound (gnat_entity))))
1900         gnat_to_gnu_entity (Ancestor_Subtype (gnat_entity), gnu_expr, 0);
1901
1902       gnu_type = make_node (REAL_TYPE);
1903       TREE_TYPE (gnu_type) = get_unpadded_type (Etype (gnat_entity));
1904       TYPE_PRECISION (gnu_type) = fp_size_to_prec (esize);
1905       TYPE_GCC_MIN_VALUE (gnu_type)
1906         = TYPE_GCC_MIN_VALUE (TREE_TYPE (gnu_type));
1907       TYPE_GCC_MAX_VALUE (gnu_type)
1908         = TYPE_GCC_MAX_VALUE (TREE_TYPE (gnu_type));
1909       layout_type (gnu_type);
1910
1911       SET_TYPE_RM_MIN_VALUE
1912         (gnu_type, elaborate_expression (Type_Low_Bound (gnat_entity),
1913                                          gnat_entity, "L", definition, true,
1914                                          Needs_Debug_Info (gnat_entity)));
1915
1916       SET_TYPE_RM_MAX_VALUE
1917         (gnu_type, elaborate_expression (Type_High_Bound (gnat_entity),
1918                                          gnat_entity, "U", definition, true,
1919                                          Needs_Debug_Info (gnat_entity)));
1920
1921       /* Inherit our alias set from what we're a subtype of, as for
1922          integer subtypes.  */
1923       relate_alias_sets (gnu_type, TREE_TYPE (gnu_type), ALIAS_SET_COPY);
1924
1925       /* One of the above calls might have caused us to be elaborated,
1926          so don't blow up if so.  */
1927       maybe_present = true;
1928       break;
1929
1930       /* Array Types and Subtypes
1931
1932          Unconstrained array types are represented by E_Array_Type and
1933          constrained array types are represented by E_Array_Subtype.  There
1934          are no actual objects of an unconstrained array type; all we have
1935          are pointers to that type.
1936
1937          The following fields are defined on array types and subtypes:
1938
1939                 Component_Type     Component type of the array.
1940                 Number_Dimensions  Number of dimensions (an int).
1941                 First_Index        Type of first index.  */
1942
1943     case E_Array_Type:
1944       {
1945         const bool convention_fortran_p
1946           = (Convention (gnat_entity) == Convention_Fortran);
1947         const int ndim = Number_Dimensions (gnat_entity);
1948         tree gnu_template_type;
1949         tree gnu_ptr_template;
1950         tree gnu_template_reference, gnu_template_fields, gnu_fat_type;
1951         tree *gnu_index_types = XALLOCAVEC (tree, ndim);
1952         tree *gnu_temp_fields = XALLOCAVEC (tree, ndim);
1953         tree gnu_max_size = size_one_node, gnu_max_size_unit, tem, t;
1954         Entity_Id gnat_index, gnat_name;
1955         int index;
1956         tree comp_type;
1957
1958         /* Create the type for the component now, as it simplifies breaking
1959            type reference loops.  */
1960         comp_type
1961           = gnat_to_gnu_component_type (gnat_entity, definition, debug_info_p);
1962         if (present_gnu_tree (gnat_entity))
1963           {
1964             /* As a side effect, the type may have been translated.  */
1965             maybe_present = true;
1966             break;
1967           }
1968
1969         /* We complete an existing dummy fat pointer type in place.  This both
1970            avoids further complex adjustments in update_pointer_to and yields
1971            better debugging information in DWARF by leveraging the support for
1972            incomplete declarations of "tagged" types in the DWARF back-end.  */
1973         gnu_type = get_dummy_type (gnat_entity);
1974         if (gnu_type && TYPE_POINTER_TO (gnu_type))
1975           {
1976             gnu_fat_type = TYPE_MAIN_VARIANT (TYPE_POINTER_TO (gnu_type));
1977             TYPE_NAME (gnu_fat_type) = NULL_TREE;
1978             /* Save the contents of the dummy type for update_pointer_to.  */
1979             TYPE_POINTER_TO (gnu_type) = copy_type (gnu_fat_type);
1980             gnu_ptr_template =
1981               TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (gnu_fat_type)));
1982             gnu_template_type = TREE_TYPE (gnu_ptr_template);
1983           }
1984         else
1985           {
1986             gnu_fat_type = make_node (RECORD_TYPE);
1987             gnu_template_type = make_node (RECORD_TYPE);
1988             gnu_ptr_template = build_pointer_type (gnu_template_type);
1989           }
1990
1991         /* Make a node for the array.  If we are not defining the array
1992            suppress expanding incomplete types.  */
1993         gnu_type = make_node (UNCONSTRAINED_ARRAY_TYPE);
1994
1995         if (!definition)
1996           {
1997             defer_incomplete_level++;
1998             this_deferred = true;
1999           }
2000
2001         /* Build the fat pointer type.  Use a "void *" object instead of
2002            a pointer to the array type since we don't have the array type
2003            yet (it will reference the fat pointer via the bounds).  */
2004         tem
2005           = create_field_decl (get_identifier ("P_ARRAY"), ptr_type_node,
2006                                gnu_fat_type, NULL_TREE, NULL_TREE, 0, 0);
2007         DECL_CHAIN (tem)
2008           = create_field_decl (get_identifier ("P_BOUNDS"), gnu_ptr_template,
2009                                gnu_fat_type, NULL_TREE, NULL_TREE, 0, 0);
2010
2011         if (COMPLETE_TYPE_P (gnu_fat_type))
2012           {
2013             /* We are going to lay it out again so reset the alias set.  */
2014             alias_set_type alias_set = TYPE_ALIAS_SET (gnu_fat_type);
2015             TYPE_ALIAS_SET (gnu_fat_type) = -1;
2016             finish_fat_pointer_type (gnu_fat_type, tem);
2017             TYPE_ALIAS_SET (gnu_fat_type) = alias_set;
2018             for (t = gnu_fat_type; t; t = TYPE_NEXT_VARIANT (t))
2019               {
2020                 TYPE_FIELDS (t) = tem;
2021                 SET_TYPE_UNCONSTRAINED_ARRAY (t, gnu_type);
2022               }
2023           }
2024         else
2025           {
2026             finish_fat_pointer_type (gnu_fat_type, tem);
2027             SET_TYPE_UNCONSTRAINED_ARRAY (gnu_fat_type, gnu_type);
2028           }
2029
2030         /* Build a reference to the template from a PLACEHOLDER_EXPR that
2031            is the fat pointer.  This will be used to access the individual
2032            fields once we build them.  */
2033         tem = build3 (COMPONENT_REF, gnu_ptr_template,
2034                       build0 (PLACEHOLDER_EXPR, gnu_fat_type),
2035                       DECL_CHAIN (TYPE_FIELDS (gnu_fat_type)), NULL_TREE);
2036         gnu_template_reference
2037           = build_unary_op (INDIRECT_REF, gnu_template_type, tem);
2038         TREE_READONLY (gnu_template_reference) = 1;
2039         TREE_THIS_NOTRAP (gnu_template_reference) = 1;
2040
2041         /* Now create the GCC type for each index and add the fields for that
2042            index to the template.  */
2043         for (index = (convention_fortran_p ? ndim - 1 : 0),
2044              gnat_index = First_Index (gnat_entity);
2045              0 <= index && index < ndim;
2046              index += (convention_fortran_p ? - 1 : 1),
2047              gnat_index = Next_Index (gnat_index))
2048           {
2049             char field_name[16];
2050             tree gnu_index_base_type
2051               = get_unpadded_type (Base_Type (Etype (gnat_index)));
2052             tree gnu_lb_field, gnu_hb_field, gnu_orig_min, gnu_orig_max;
2053             tree gnu_min, gnu_max, gnu_high;
2054
2055             /* Make the FIELD_DECLs for the low and high bounds of this
2056                type and then make extractions of these fields from the
2057                template.  */
2058             sprintf (field_name, "LB%d", index);
2059             gnu_lb_field = create_field_decl (get_identifier (field_name),
2060                                               gnu_index_base_type,
2061                                               gnu_template_type, NULL_TREE,
2062                                               NULL_TREE, 0, 0);
2063             Sloc_to_locus (Sloc (gnat_entity),
2064                            &DECL_SOURCE_LOCATION (gnu_lb_field));
2065
2066             field_name[0] = 'U';
2067             gnu_hb_field = create_field_decl (get_identifier (field_name),
2068                                               gnu_index_base_type,
2069                                               gnu_template_type, NULL_TREE,
2070                                               NULL_TREE, 0, 0);
2071             Sloc_to_locus (Sloc (gnat_entity),
2072                            &DECL_SOURCE_LOCATION (gnu_hb_field));
2073
2074             gnu_temp_fields[index] = chainon (gnu_lb_field, gnu_hb_field);
2075
2076             /* We can't use build_component_ref here since the template type
2077                isn't complete yet.  */
2078             gnu_orig_min = build3 (COMPONENT_REF, gnu_index_base_type,
2079                                    gnu_template_reference, gnu_lb_field,
2080                                    NULL_TREE);
2081             gnu_orig_max = build3 (COMPONENT_REF, gnu_index_base_type,
2082                                    gnu_template_reference, gnu_hb_field,
2083                                    NULL_TREE);
2084             TREE_READONLY (gnu_orig_min) = TREE_READONLY (gnu_orig_max) = 1;
2085
2086             gnu_min = convert (sizetype, gnu_orig_min);
2087             gnu_max = convert (sizetype, gnu_orig_max);
2088
2089             /* Compute the size of this dimension.  See the E_Array_Subtype
2090                case below for the rationale.  */
2091             gnu_high
2092               = build3 (COND_EXPR, sizetype,
2093                         build2 (GE_EXPR, boolean_type_node,
2094                                 gnu_orig_max, gnu_orig_min),
2095                         gnu_max,
2096                         size_binop (MINUS_EXPR, gnu_min, size_one_node));
2097
2098             /* Make a range type with the new range in the Ada base type.
2099                Then make an index type with the size range in sizetype.  */
2100             gnu_index_types[index]
2101               = create_index_type (gnu_min, gnu_high,
2102                                    create_range_type (gnu_index_base_type,
2103                                                       gnu_orig_min,
2104                                                       gnu_orig_max),
2105                                    gnat_entity);
2106
2107             /* Update the maximum size of the array in elements.  */
2108             if (gnu_max_size)
2109               {
2110                 tree gnu_index_type = get_unpadded_type (Etype (gnat_index));
2111                 tree gnu_min
2112                   = convert (sizetype, TYPE_MIN_VALUE (gnu_index_type));
2113                 tree gnu_max
2114                   = convert (sizetype, TYPE_MAX_VALUE (gnu_index_type));
2115                 tree gnu_this_max
2116                   = size_binop (PLUS_EXPR, size_one_node,
2117                                 size_binop (MINUS_EXPR, gnu_max, gnu_min));
2118
2119                 if (TREE_CODE (gnu_this_max) == INTEGER_CST
2120                     && TREE_OVERFLOW (gnu_this_max))
2121                   gnu_max_size = NULL_TREE;
2122                 else
2123                   gnu_max_size
2124                     = size_binop (MULT_EXPR, gnu_max_size, gnu_this_max);
2125               }
2126
2127             TYPE_NAME (gnu_index_types[index])
2128               = create_concat_name (gnat_entity, field_name);
2129           }
2130
2131         /* Install all the fields into the template.  */
2132         TYPE_NAME (gnu_template_type)
2133           = create_concat_name (gnat_entity, "XUB");
2134         gnu_template_fields = NULL_TREE;
2135         for (index = 0; index < ndim; index++)
2136           gnu_template_fields
2137             = chainon (gnu_template_fields, gnu_temp_fields[index]);
2138         finish_record_type (gnu_template_type, gnu_template_fields, 0,
2139                             debug_info_p);
2140         TYPE_READONLY (gnu_template_type) = 1;
2141
2142         /* If Component_Size is not already specified, annotate it with the
2143            size of the component.  */
2144         if (Unknown_Component_Size (gnat_entity))
2145           Set_Component_Size (gnat_entity,
2146                               annotate_value (TYPE_SIZE (comp_type)));
2147
2148         /* Compute the maximum size of the array in units and bits.  */
2149         if (gnu_max_size)
2150           {
2151             gnu_max_size_unit = size_binop (MULT_EXPR, gnu_max_size,
2152                                             TYPE_SIZE_UNIT (comp_type));
2153             gnu_max_size = size_binop (MULT_EXPR,
2154                                        convert (bitsizetype, gnu_max_size),
2155                                        TYPE_SIZE (comp_type));
2156           }
2157         else
2158           gnu_max_size_unit = NULL_TREE;
2159
2160         /* Now build the array type.  */
2161         tem = comp_type;
2162         for (index = ndim - 1; index >= 0; index--)
2163           {
2164             tem = build_nonshared_array_type (tem, gnu_index_types[index]);
2165             if (Reverse_Storage_Order (gnat_entity) && !GNAT_Mode)
2166               sorry ("non-default Scalar_Storage_Order");
2167             TYPE_MULTI_ARRAY_P (tem) = (index > 0);
2168             if (array_type_has_nonaliased_component (tem, gnat_entity))
2169               TYPE_NONALIASED_COMPONENT (tem) = 1;
2170           }
2171
2172         /* If an alignment is specified, use it if valid.  But ignore it
2173            for the original type of packed array types.  If the alignment
2174            was requested with an explicit alignment clause, state so.  */
2175         if (No (Packed_Array_Impl_Type (gnat_entity))
2176             && Known_Alignment (gnat_entity))
2177           {
2178             TYPE_ALIGN (tem)
2179               = validate_alignment (Alignment (gnat_entity), gnat_entity,
2180                                     TYPE_ALIGN (tem));
2181             if (Present (Alignment_Clause (gnat_entity)))
2182               TYPE_USER_ALIGN (tem) = 1;
2183           }
2184
2185         TYPE_CONVENTION_FORTRAN_P (tem) = convention_fortran_p;
2186
2187         if (Treat_As_Volatile (gnat_entity))
2188           tem = change_qualified_type (tem, TYPE_QUAL_VOLATILE);
2189
2190         /* Adjust the type of the pointer-to-array field of the fat pointer
2191            and record the aliasing relationships if necessary.  */
2192         TREE_TYPE (TYPE_FIELDS (gnu_fat_type)) = build_pointer_type (tem);
2193         if (TYPE_ALIAS_SET_KNOWN_P (gnu_fat_type))
2194           record_component_aliases (gnu_fat_type);
2195
2196         /* The result type is an UNCONSTRAINED_ARRAY_TYPE that indicates the
2197            corresponding fat pointer.  */
2198         TREE_TYPE (gnu_type) = gnu_fat_type;
2199         TYPE_POINTER_TO (gnu_type) = gnu_fat_type;
2200         TYPE_REFERENCE_TO (gnu_type) = gnu_fat_type;
2201         SET_TYPE_MODE (gnu_type, BLKmode);
2202         TYPE_ALIGN (gnu_type) = TYPE_ALIGN (tem);
2203
2204         /* If the maximum size doesn't overflow, use it.  */
2205         if (gnu_max_size
2206             && TREE_CODE (gnu_max_size) == INTEGER_CST
2207             && !TREE_OVERFLOW (gnu_max_size)
2208             && TREE_CODE (gnu_max_size_unit) == INTEGER_CST
2209             && !TREE_OVERFLOW (gnu_max_size_unit))
2210           {
2211             TYPE_SIZE (tem) = size_binop (MIN_EXPR, gnu_max_size,
2212                                           TYPE_SIZE (tem));
2213             TYPE_SIZE_UNIT (tem) = size_binop (MIN_EXPR, gnu_max_size_unit,
2214                                                TYPE_SIZE_UNIT (tem));
2215           }
2216
2217         create_type_decl (create_concat_name (gnat_entity, "XUA"), tem,
2218                           !Comes_From_Source (gnat_entity), debug_info_p,
2219                           gnat_entity);
2220
2221         /* Give the fat pointer type a name.  If this is a packed array, tell
2222            the debugger how to interpret the underlying bits.  */
2223         if (Present (Packed_Array_Impl_Type (gnat_entity)))
2224           gnat_name = Packed_Array_Impl_Type (gnat_entity);
2225         else
2226           gnat_name = gnat_entity;
2227         create_type_decl (create_concat_name (gnat_name, "XUP"), gnu_fat_type,
2228                           !Comes_From_Source (gnat_entity), debug_info_p,
2229                           gnat_entity);
2230
2231         /* Create the type to be designated by thin pointers: a record type for
2232            the array and its template.  We used to shift the fields to have the
2233            template at a negative offset, but this was somewhat of a kludge; we
2234            now shift thin pointer values explicitly but only those which have a
2235            TYPE_UNCONSTRAINED_ARRAY attached to the designated RECORD_TYPE.  */
2236         tem = build_unc_object_type (gnu_template_type, tem,
2237                                      create_concat_name (gnat_name, "XUT"),
2238                                      debug_info_p);
2239
2240         SET_TYPE_UNCONSTRAINED_ARRAY (tem, gnu_type);
2241         TYPE_OBJECT_RECORD_TYPE (gnu_type) = tem;
2242       }
2243       break;
2244
2245     case E_Array_Subtype:
2246
2247       /* This is the actual data type for array variables.  Multidimensional
2248          arrays are implemented as arrays of arrays.  Note that arrays which
2249          have sparse enumeration subtypes as index components create sparse
2250          arrays, which is obviously space inefficient but so much easier to
2251          code for now.
2252
2253          Also note that the subtype never refers to the unconstrained array
2254          type, which is somewhat at variance with Ada semantics.
2255
2256          First check to see if this is simply a renaming of the array type.
2257          If so, the result is the array type.  */
2258
2259       gnu_type = TYPE_MAIN_VARIANT (gnat_to_gnu_type (Etype (gnat_entity)));
2260       if (!Is_Constrained (gnat_entity))
2261         ;
2262       else
2263         {
2264           Entity_Id gnat_index, gnat_base_index;
2265           const bool convention_fortran_p
2266             = (Convention (gnat_entity) == Convention_Fortran);
2267           const int ndim = Number_Dimensions (gnat_entity);
2268           tree gnu_base_type = gnu_type;
2269           tree *gnu_index_types = XALLOCAVEC (tree, ndim);
2270           tree gnu_max_size = size_one_node, gnu_max_size_unit;
2271           bool need_index_type_struct = false;
2272           int index;
2273
2274           /* First create the GCC type for each index and find out whether
2275              special types are needed for debugging information.  */
2276           for (index = (convention_fortran_p ? ndim - 1 : 0),
2277                gnat_index = First_Index (gnat_entity),
2278                gnat_base_index
2279                  = First_Index (Implementation_Base_Type (gnat_entity));
2280                0 <= index && index < ndim;
2281                index += (convention_fortran_p ? - 1 : 1),
2282                gnat_index = Next_Index (gnat_index),
2283                gnat_base_index = Next_Index (gnat_base_index))
2284             {
2285               tree gnu_index_type = get_unpadded_type (Etype (gnat_index));
2286               tree gnu_index_base_type = get_base_type (gnu_index_type);
2287               tree gnu_orig_min
2288                 = convert (gnu_index_base_type,
2289                            TYPE_MIN_VALUE (gnu_index_type));
2290               tree gnu_orig_max
2291                 = convert (gnu_index_base_type,
2292                            TYPE_MAX_VALUE (gnu_index_type));
2293               tree gnu_min = convert (sizetype, gnu_orig_min);
2294               tree gnu_max = convert (sizetype, gnu_orig_max);
2295               tree gnu_base_index_type
2296                 = get_unpadded_type (Etype (gnat_base_index));
2297               tree gnu_base_index_base_type
2298                 = get_base_type (gnu_base_index_type);
2299               tree gnu_base_orig_min
2300                 = convert (gnu_base_index_base_type,
2301                            TYPE_MIN_VALUE (gnu_base_index_type));
2302               tree gnu_base_orig_max
2303                 = convert (gnu_base_index_base_type,
2304                            TYPE_MAX_VALUE (gnu_base_index_type));
2305               tree gnu_high;
2306
2307               /* See if the base array type is already flat.  If it is, we
2308                  are probably compiling an ACATS test but it will cause the
2309                  code below to malfunction if we don't handle it specially.  */
2310               if (TREE_CODE (gnu_base_orig_min) == INTEGER_CST
2311                   && TREE_CODE (gnu_base_orig_max) == INTEGER_CST
2312                   && tree_int_cst_lt (gnu_base_orig_max, gnu_base_orig_min))
2313                 {
2314                   gnu_min = size_one_node;
2315                   gnu_max = size_zero_node;
2316                   gnu_high = gnu_max;
2317                 }
2318
2319               /* Similarly, if one of the values overflows in sizetype and the
2320                  range is null, use 1..0 for the sizetype bounds.  */
2321               else if (TREE_CODE (gnu_min) == INTEGER_CST
2322                        && TREE_CODE (gnu_max) == INTEGER_CST
2323                        && (TREE_OVERFLOW (gnu_min) || TREE_OVERFLOW (gnu_max))
2324                        && tree_int_cst_lt (gnu_orig_max, gnu_orig_min))
2325                 {
2326                   gnu_min = size_one_node;
2327                   gnu_max = size_zero_node;
2328                   gnu_high = gnu_max;
2329                 }
2330
2331               /* If the minimum and maximum values both overflow in sizetype,
2332                  but the difference in the original type does not overflow in
2333                  sizetype, ignore the overflow indication.  */
2334               else if (TREE_CODE (gnu_min) == INTEGER_CST
2335                        && TREE_CODE (gnu_max) == INTEGER_CST
2336                        && TREE_OVERFLOW (gnu_min) && TREE_OVERFLOW (gnu_max)
2337                        && !TREE_OVERFLOW
2338                            (convert (sizetype,
2339                                      fold_build2 (MINUS_EXPR, gnu_index_type,
2340                                                   gnu_orig_max,
2341                                                   gnu_orig_min))))
2342                 {
2343                   TREE_OVERFLOW (gnu_min) = 0;
2344                   TREE_OVERFLOW (gnu_max) = 0;
2345                   gnu_high = gnu_max;
2346                 }
2347
2348               /* Compute the size of this dimension in the general case.  We
2349                  need to provide GCC with an upper bound to use but have to
2350                  deal with the "superflat" case.  There are three ways to do
2351                  this.  If we can prove that the array can never be superflat,
2352                  we can just use the high bound of the index type.  */
2353               else if ((Nkind (gnat_index) == N_Range
2354                         && cannot_be_superflat (gnat_index))
2355                        /* Bit-Packed Array Impl. Types are never superflat.  */
2356                        || (Is_Packed_Array_Impl_Type (gnat_entity)
2357                            && Is_Bit_Packed_Array
2358                               (Original_Array_Type (gnat_entity))))
2359                 gnu_high = gnu_max;
2360
2361               /* Otherwise, if the high bound is constant but the low bound is
2362                  not, we use the expression (hb >= lb) ? lb : hb + 1 for the
2363                  lower bound.  Note that the comparison must be done in the
2364                  original type to avoid any overflow during the conversion.  */
2365               else if (TREE_CODE (gnu_max) == INTEGER_CST
2366                        && TREE_CODE (gnu_min) != INTEGER_CST)
2367                 {
2368                   gnu_high = gnu_max;
2369                   gnu_min
2370                     = build_cond_expr (sizetype,
2371                                        build_binary_op (GE_EXPR,
2372                                                         boolean_type_node,
2373                                                         gnu_orig_max,
2374                                                         gnu_orig_min),
2375                                        gnu_min,
2376                                        int_const_binop (PLUS_EXPR, gnu_max,
2377                                                         size_one_node));
2378                 }
2379
2380               /* Finally we use (hb >= lb) ? hb : lb - 1 for the upper bound
2381                  in all the other cases.  Note that, here as well as above,
2382                  the condition used in the comparison must be equivalent to
2383                  the condition (length != 0).  This is relied upon in order
2384                  to optimize array comparisons in compare_arrays.  Moreover
2385                  we use int_const_binop for the shift by 1 if the bound is
2386                  constant to avoid any unwanted overflow.  */
2387               else
2388                 gnu_high
2389                   = build_cond_expr (sizetype,
2390                                      build_binary_op (GE_EXPR,
2391                                                       boolean_type_node,
2392                                                       gnu_orig_max,
2393                                                       gnu_orig_min),
2394                                      gnu_max,
2395                                      TREE_CODE (gnu_min) == INTEGER_CST
2396                                      ? int_const_binop (MINUS_EXPR, gnu_min,
2397                                                         size_one_node)
2398                                      : size_binop (MINUS_EXPR, gnu_min,
2399                                                    size_one_node));
2400
2401               /* Reuse the index type for the range type.  Then make an index
2402                  type with the size range in sizetype.  */
2403               gnu_index_types[index]
2404                 = create_index_type (gnu_min, gnu_high, gnu_index_type,
2405                                      gnat_entity);
2406
2407               /* Update the maximum size of the array in elements.  Here we
2408                  see if any constraint on the index type of the base type
2409                  can be used in the case of self-referential bound on the
2410                  index type of the subtype.  We look for a non-"infinite"
2411                  and non-self-referential bound from any type involved and
2412                  handle each bound separately.  */
2413               if (gnu_max_size)
2414                 {
2415                   tree gnu_base_min = convert (sizetype, gnu_base_orig_min);
2416                   tree gnu_base_max = convert (sizetype, gnu_base_orig_max);
2417                   tree gnu_base_index_base_type
2418                     = get_base_type (gnu_base_index_type);
2419                   tree gnu_base_base_min
2420                     = convert (sizetype,
2421                                TYPE_MIN_VALUE (gnu_base_index_base_type));
2422                   tree gnu_base_base_max
2423                     = convert (sizetype,
2424                                TYPE_MAX_VALUE (gnu_base_index_base_type));
2425
2426                   if (!CONTAINS_PLACEHOLDER_P (gnu_min)
2427                       || !(TREE_CODE (gnu_base_min) == INTEGER_CST
2428                            && !TREE_OVERFLOW (gnu_base_min)))
2429                     gnu_base_min = gnu_min;
2430
2431                   if (!CONTAINS_PLACEHOLDER_P (gnu_max)
2432                       || !(TREE_CODE (gnu_base_max) == INTEGER_CST
2433                            && !TREE_OVERFLOW (gnu_base_max)))
2434                     gnu_base_max = gnu_max;
2435
2436                   if ((TREE_CODE (gnu_base_min) == INTEGER_CST
2437                        && TREE_OVERFLOW (gnu_base_min))
2438                       || operand_equal_p (gnu_base_min, gnu_base_base_min, 0)
2439                       || (TREE_CODE (gnu_base_max) == INTEGER_CST
2440                           && TREE_OVERFLOW (gnu_base_max))
2441                       || operand_equal_p (gnu_base_max, gnu_base_base_max, 0))
2442                     gnu_max_size = NULL_TREE;
2443                   else
2444                     {
2445                       tree gnu_this_max;
2446
2447                       /* Use int_const_binop if the bounds are constant to
2448                          avoid any unwanted overflow.  */
2449                       if (TREE_CODE (gnu_base_min) == INTEGER_CST
2450                           && TREE_CODE (gnu_base_max) == INTEGER_CST)
2451                         gnu_this_max
2452                           = int_const_binop (PLUS_EXPR, size_one_node,
2453                                              int_const_binop (MINUS_EXPR,
2454                                                               gnu_base_max,
2455                                                               gnu_base_min));
2456                       else
2457                         gnu_this_max
2458                           = size_binop (PLUS_EXPR, size_one_node,
2459                                         size_binop (MINUS_EXPR,
2460                                                     gnu_base_max,
2461                                                     gnu_base_min));
2462
2463                       gnu_max_size
2464                         = size_binop (MULT_EXPR, gnu_max_size, gnu_this_max);
2465                     }
2466                 }
2467
2468               /* We need special types for debugging information to point to
2469                  the index types if they have variable bounds, are not integer
2470                  types or are biased.  */
2471               if (TREE_CODE (gnu_orig_min) != INTEGER_CST
2472                   || TREE_CODE (gnu_orig_max) != INTEGER_CST
2473                   || TREE_CODE (gnu_index_type) != INTEGER_TYPE
2474                   || (TREE_TYPE (gnu_index_type)
2475                       && TREE_CODE (TREE_TYPE (gnu_index_type))
2476                          != INTEGER_TYPE)
2477                   || TYPE_BIASED_REPRESENTATION_P (gnu_index_type))
2478                 need_index_type_struct = true;
2479             }
2480
2481           /* Then flatten: create the array of arrays.  For an array type
2482              used to implement a packed array, get the component type from
2483              the original array type since the representation clauses that
2484              can affect it are on the latter.  */
2485           if (Is_Packed_Array_Impl_Type (gnat_entity)
2486               && !Is_Bit_Packed_Array (Original_Array_Type (gnat_entity)))
2487             {
2488               gnu_type = gnat_to_gnu_type (Original_Array_Type (gnat_entity));
2489               for (index = ndim - 1; index >= 0; index--)
2490                 gnu_type = TREE_TYPE (gnu_type);
2491
2492               /* One of the above calls might have caused us to be elaborated,
2493                  so don't blow up if so.  */
2494               if (present_gnu_tree (gnat_entity))
2495                 {
2496                   maybe_present = true;
2497                   break;
2498                 }
2499             }
2500           else
2501             {
2502               gnu_type = gnat_to_gnu_component_type (gnat_entity, definition,
2503                                                      debug_info_p);
2504
2505               /* One of the above calls might have caused us to be elaborated,
2506                  so don't blow up if so.  */
2507               if (present_gnu_tree (gnat_entity))
2508                 {
2509                   maybe_present = true;
2510                   break;
2511                 }
2512             }
2513
2514           /* Compute the maximum size of the array in units and bits.  */
2515           if (gnu_max_size)
2516             {
2517               gnu_max_size_unit = size_binop (MULT_EXPR, gnu_max_size,
2518                                               TYPE_SIZE_UNIT (gnu_type));
2519               gnu_max_size = size_binop (MULT_EXPR,
2520                                          convert (bitsizetype, gnu_max_size),
2521                                          TYPE_SIZE (gnu_type));
2522             }
2523           else
2524             gnu_max_size_unit = NULL_TREE;
2525
2526           /* Now build the array type.  */
2527           for (index = ndim - 1; index >= 0; index --)
2528             {
2529               gnu_type = build_nonshared_array_type (gnu_type,
2530                                                      gnu_index_types[index]);
2531               TYPE_MULTI_ARRAY_P (gnu_type) = (index > 0);
2532               if (array_type_has_nonaliased_component (gnu_type, gnat_entity))
2533                 TYPE_NONALIASED_COMPONENT (gnu_type) = 1;
2534             }
2535
2536           /* Attach the TYPE_STUB_DECL in case we have a parallel type.  */
2537           TYPE_STUB_DECL (gnu_type)
2538             = create_type_stub_decl (gnu_entity_name, gnu_type);
2539
2540           /* If we are at file level and this is a multi-dimensional array,
2541              we need to make a variable corresponding to the stride of the
2542              inner dimensions.   */
2543           if (global_bindings_p () && ndim > 1)
2544             {
2545               tree gnu_arr_type;
2546
2547               for (gnu_arr_type = TREE_TYPE (gnu_type), index = 1;
2548                    TREE_CODE (gnu_arr_type) == ARRAY_TYPE;
2549                    gnu_arr_type = TREE_TYPE (gnu_arr_type), index++)
2550                 {
2551                   tree eltype = TREE_TYPE (gnu_arr_type);
2552                   char stride_name[32];
2553
2554                   sprintf (stride_name, "ST%d", index);
2555                   TYPE_SIZE (gnu_arr_type)
2556                     = elaborate_expression_1 (TYPE_SIZE (gnu_arr_type),
2557                                               gnat_entity, stride_name,
2558                                               definition, false);
2559
2560                   /* ??? For now, store the size as a multiple of the
2561                      alignment of the element type in bytes so that we
2562                      can see the alignment from the tree.  */
2563                   sprintf (stride_name, "ST%d_A_UNIT", index);
2564                   TYPE_SIZE_UNIT (gnu_arr_type)
2565                     = elaborate_expression_2 (TYPE_SIZE_UNIT (gnu_arr_type),
2566                                               gnat_entity, stride_name,
2567                                               definition, false,
2568                                               TYPE_ALIGN (eltype));
2569
2570                   /* ??? create_type_decl is not invoked on the inner types so
2571                      the MULT_EXPR node built above will never be marked.  */
2572                   MARK_VISITED (TYPE_SIZE_UNIT (gnu_arr_type));
2573                 }
2574             }
2575
2576           /* If we need to write out a record type giving the names of the
2577              bounds for debugging purposes, do it now and make the record
2578              type a parallel type.  This is not needed for a packed array
2579              since the bounds are conveyed by the original array type.  */
2580           if (need_index_type_struct
2581               && debug_info_p
2582               && !Is_Packed_Array_Impl_Type (gnat_entity))
2583             {
2584               tree gnu_bound_rec = make_node (RECORD_TYPE);
2585               tree gnu_field_list = NULL_TREE;
2586               tree gnu_field;
2587
2588               TYPE_NAME (gnu_bound_rec)
2589                 = create_concat_name (gnat_entity, "XA");
2590
2591               for (index = ndim - 1; index >= 0; index--)
2592                 {
2593                   tree gnu_index = TYPE_INDEX_TYPE (gnu_index_types[index]);
2594                   tree gnu_index_name = TYPE_IDENTIFIER (gnu_index);
2595
2596                   /* Make sure to reference the types themselves, and not just
2597                      their names, as the debugger may fall back on them.  */
2598                   gnu_field = create_field_decl (gnu_index_name, gnu_index,
2599                                                  gnu_bound_rec, NULL_TREE,
2600                                                  NULL_TREE, 0, 0);
2601                   DECL_CHAIN (gnu_field) = gnu_field_list;
2602                   gnu_field_list = gnu_field;
2603                 }
2604
2605               finish_record_type (gnu_bound_rec, gnu_field_list, 0, true);
2606               add_parallel_type (gnu_type, gnu_bound_rec);
2607             }
2608
2609           /* If this is a packed array type, make the original array type a
2610              parallel type.  Otherwise, do it for the base array type if it
2611              isn't artificial to make sure it is kept in the debug info.  */
2612           if (debug_info_p)
2613             {
2614               if (Is_Packed_Array_Impl_Type (gnat_entity))
2615                 add_parallel_type_for_packed_array (gnu_type, gnat_entity);
2616               else
2617                 {
2618                   tree gnu_base_decl
2619                     = gnat_to_gnu_entity (Etype (gnat_entity), NULL_TREE, 0);
2620                   if (!DECL_ARTIFICIAL (gnu_base_decl))
2621                     add_parallel_type (gnu_type,
2622                                        TREE_TYPE (TREE_TYPE (gnu_base_decl)));
2623                 }
2624             }
2625
2626           TYPE_CONVENTION_FORTRAN_P (gnu_type) = convention_fortran_p;
2627           TYPE_PACKED_ARRAY_TYPE_P (gnu_type)
2628             = (Is_Packed_Array_Impl_Type (gnat_entity)
2629                && Is_Bit_Packed_Array (Original_Array_Type (gnat_entity)));
2630
2631           /* If the size is self-referential and the maximum size doesn't
2632              overflow, use it.  */
2633           if (CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_type))
2634               && gnu_max_size
2635               && !(TREE_CODE (gnu_max_size) == INTEGER_CST
2636                    && TREE_OVERFLOW (gnu_max_size))
2637               && !(TREE_CODE (gnu_max_size_unit) == INTEGER_CST
2638                    && TREE_OVERFLOW (gnu_max_size_unit)))
2639             {
2640               TYPE_SIZE (gnu_type) = size_binop (MIN_EXPR, gnu_max_size,
2641                                                  TYPE_SIZE (gnu_type));
2642               TYPE_SIZE_UNIT (gnu_type)
2643                 = size_binop (MIN_EXPR, gnu_max_size_unit,
2644                               TYPE_SIZE_UNIT (gnu_type));
2645             }
2646
2647           /* Set our alias set to that of our base type.  This gives all
2648              array subtypes the same alias set.  */
2649           relate_alias_sets (gnu_type, gnu_base_type, ALIAS_SET_COPY);
2650
2651           /* If this is a packed type, make this type the same as the packed
2652              array type, but do some adjusting in the type first.  */
2653           if (Present (Packed_Array_Impl_Type (gnat_entity)))
2654             {
2655               Entity_Id gnat_index;
2656               tree gnu_inner;
2657
2658               /* First finish the type we had been making so that we output
2659                  debugging information for it.  */
2660               process_attributes (&gnu_type, &attr_list, false, gnat_entity);
2661               if (Treat_As_Volatile (gnat_entity))
2662                 {
2663                   const int quals
2664                     = TYPE_QUAL_VOLATILE
2665                       | (Is_Atomic_Or_VFA (gnat_entity) ? TYPE_QUAL_ATOMIC : 0);
2666                   gnu_type = change_qualified_type (gnu_type, quals);
2667                 }
2668               /* Make it artificial only if the base type was artificial too.
2669                  That's sort of "morally" true and will make it possible for
2670                  the debugger to look it up by name in DWARF, which is needed
2671                  in order to decode the packed array type.  */
2672               gnu_decl
2673                 = create_type_decl (gnu_entity_name, gnu_type,
2674                                     !Comes_From_Source (Etype (gnat_entity))
2675                                     && !Comes_From_Source (gnat_entity),
2676                                     debug_info_p, gnat_entity);
2677
2678               /* Save it as our equivalent in case the call below elaborates
2679                  this type again.  */
2680               save_gnu_tree (gnat_entity, gnu_decl, false);
2681
2682               gnu_decl
2683                 = gnat_to_gnu_entity (Packed_Array_Impl_Type (gnat_entity),
2684                                       NULL_TREE, 0);
2685               this_made_decl = true;
2686               gnu_type = TREE_TYPE (gnu_decl);
2687               save_gnu_tree (gnat_entity, NULL_TREE, false);
2688
2689               gnu_inner = gnu_type;
2690               while (TREE_CODE (gnu_inner) == RECORD_TYPE
2691                      && (TYPE_JUSTIFIED_MODULAR_P (gnu_inner)
2692                          || TYPE_PADDING_P (gnu_inner)))
2693                 gnu_inner = TREE_TYPE (TYPE_FIELDS (gnu_inner));
2694
2695               /* We need to attach the index type to the type we just made so
2696                  that the actual bounds can later be put into a template.  */
2697               if ((TREE_CODE (gnu_inner) == ARRAY_TYPE
2698                    && !TYPE_ACTUAL_BOUNDS (gnu_inner))
2699                   || (TREE_CODE (gnu_inner) == INTEGER_TYPE
2700                       && !TYPE_HAS_ACTUAL_BOUNDS_P (gnu_inner)))
2701                 {
2702                   if (TREE_CODE (gnu_inner) == INTEGER_TYPE)
2703                     {
2704                       /* The TYPE_ACTUAL_BOUNDS field is overloaded with the
2705                          TYPE_MODULUS for modular types so we make an extra
2706                          subtype if necessary.  */
2707                       if (TYPE_MODULAR_P (gnu_inner))
2708                         {
2709                           tree gnu_subtype
2710                             = make_unsigned_type (TYPE_PRECISION (gnu_inner));
2711                           TREE_TYPE (gnu_subtype) = gnu_inner;
2712                           TYPE_EXTRA_SUBTYPE_P (gnu_subtype) = 1;
2713                           SET_TYPE_RM_MIN_VALUE (gnu_subtype,
2714                                                  TYPE_MIN_VALUE (gnu_inner));
2715                           SET_TYPE_RM_MAX_VALUE (gnu_subtype,
2716                                                  TYPE_MAX_VALUE (gnu_inner));
2717                           gnu_inner = gnu_subtype;
2718                         }
2719
2720                       TYPE_HAS_ACTUAL_BOUNDS_P (gnu_inner) = 1;
2721
2722 #ifdef ENABLE_CHECKING
2723                       /* Check for other cases of overloading.  */
2724                       gcc_assert (!TYPE_ACTUAL_BOUNDS (gnu_inner));
2725 #endif
2726                     }
2727
2728                   for (gnat_index = First_Index (gnat_entity);
2729                        Present (gnat_index);
2730                        gnat_index = Next_Index (gnat_index))
2731                     SET_TYPE_ACTUAL_BOUNDS
2732                       (gnu_inner,
2733                        tree_cons (NULL_TREE,
2734                                   get_unpadded_type (Etype (gnat_index)),
2735                                   TYPE_ACTUAL_BOUNDS (gnu_inner)));
2736
2737                   if (Convention (gnat_entity) != Convention_Fortran)
2738                     SET_TYPE_ACTUAL_BOUNDS
2739                       (gnu_inner, nreverse (TYPE_ACTUAL_BOUNDS (gnu_inner)));
2740
2741                   if (TREE_CODE (gnu_type) == RECORD_TYPE
2742                       && TYPE_JUSTIFIED_MODULAR_P (gnu_type))
2743                     TREE_TYPE (TYPE_FIELDS (gnu_type)) = gnu_inner;
2744                 }
2745             }
2746
2747           else
2748             /* Abort if packed array with no Packed_Array_Impl_Type.  */
2749             gcc_assert (!Is_Packed (gnat_entity));
2750         }
2751       break;
2752
2753     case E_String_Literal_Subtype:
2754       /* Create the type for a string literal.  */
2755       {
2756         Entity_Id gnat_full_type
2757           = (IN (Ekind (Etype (gnat_entity)), Private_Kind)
2758              && Present (Full_View (Etype (gnat_entity)))
2759              ? Full_View (Etype (gnat_entity)) : Etype (gnat_entity));
2760         tree gnu_string_type = get_unpadded_type (gnat_full_type);
2761         tree gnu_string_array_type
2762           = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_string_type))));
2763         tree gnu_string_index_type
2764           = get_base_type (TREE_TYPE (TYPE_INDEX_TYPE
2765                                       (TYPE_DOMAIN (gnu_string_array_type))));
2766         tree gnu_lower_bound
2767           = convert (gnu_string_index_type,
2768                      gnat_to_gnu (String_Literal_Low_Bound (gnat_entity)));
2769         tree gnu_length
2770           = UI_To_gnu (String_Literal_Length (gnat_entity),
2771                        gnu_string_index_type);
2772         tree gnu_upper_bound
2773           = build_binary_op (PLUS_EXPR, gnu_string_index_type,
2774                              gnu_lower_bound,
2775                              int_const_binop (MINUS_EXPR, gnu_length,
2776                                               convert (gnu_string_index_type,
2777                                                        integer_one_node)));
2778         tree gnu_index_type
2779           = create_index_type (convert (sizetype, gnu_lower_bound),
2780                                convert (sizetype, gnu_upper_bound),
2781                                create_range_type (gnu_string_index_type,
2782                                                   gnu_lower_bound,
2783                                                   gnu_upper_bound),
2784                                gnat_entity);
2785
2786         gnu_type
2787           = build_nonshared_array_type (gnat_to_gnu_type
2788                                         (Component_Type (gnat_entity)),
2789                                         gnu_index_type);
2790         if (array_type_has_nonaliased_component (gnu_type, gnat_entity))
2791           TYPE_NONALIASED_COMPONENT (gnu_type) = 1;
2792         relate_alias_sets (gnu_type, gnu_string_type, ALIAS_SET_COPY);
2793       }
2794       break;
2795
2796     /* Record Types and Subtypes
2797
2798        The following fields are defined on record types:
2799
2800                 Has_Discriminants       True if the record has discriminants
2801                 First_Discriminant      Points to head of list of discriminants
2802                 First_Entity            Points to head of list of fields
2803                 Is_Tagged_Type          True if the record is tagged
2804
2805        Implementation of Ada records and discriminated records:
2806
2807        A record type definition is transformed into the equivalent of a C
2808        struct definition.  The fields that are the discriminants which are
2809        found in the Full_Type_Declaration node and the elements of the
2810        Component_List found in the Record_Type_Definition node.  The
2811        Component_List can be a recursive structure since each Variant of
2812        the Variant_Part of the Component_List has a Component_List.
2813
2814        Processing of a record type definition comprises starting the list of
2815        field declarations here from the discriminants and the calling the
2816        function components_to_record to add the rest of the fields from the
2817        component list and return the gnu type node.  The function
2818        components_to_record will call itself recursively as it traverses
2819        the tree.  */
2820
2821     case E_Record_Type:
2822       if (Has_Complex_Representation (gnat_entity))
2823         {
2824           gnu_type
2825             = build_complex_type
2826               (get_unpadded_type
2827                (Etype (Defining_Entity
2828                        (First (Component_Items
2829                                (Component_List
2830                                 (Type_Definition
2831                                  (Declaration_Node (gnat_entity)))))))));
2832
2833           break;
2834         }
2835
2836       {
2837         Node_Id full_definition = Declaration_Node (gnat_entity);
2838         Node_Id record_definition = Type_Definition (full_definition);
2839         Node_Id gnat_constr;
2840         Entity_Id gnat_field;
2841         tree gnu_field, gnu_field_list = NULL_TREE;
2842         tree gnu_get_parent;
2843         /* Set PACKED in keeping with gnat_to_gnu_field.  */
2844         const int packed
2845           = Is_Packed (gnat_entity)
2846             ? 1
2847             : Component_Alignment (gnat_entity) == Calign_Storage_Unit
2848               ? -1
2849               : (Known_Alignment (gnat_entity)
2850                  || (Strict_Alignment (gnat_entity)
2851                      && Known_RM_Size (gnat_entity)))
2852                 ? -2
2853                 : 0;
2854         const bool has_discr = Has_Discriminants (gnat_entity);
2855         const bool has_rep = Has_Specified_Layout (gnat_entity);
2856         const bool is_extension
2857           = (Is_Tagged_Type (gnat_entity)
2858              && Nkind (record_definition) == N_Derived_Type_Definition);
2859         const bool is_unchecked_union = Is_Unchecked_Union (gnat_entity);
2860         bool all_rep = has_rep;
2861
2862         /* See if all fields have a rep clause.  Stop when we find one
2863            that doesn't.  */
2864         if (all_rep)
2865           for (gnat_field = First_Entity (gnat_entity);
2866                Present (gnat_field);
2867                gnat_field = Next_Entity (gnat_field))
2868             if ((Ekind (gnat_field) == E_Component
2869                  || Ekind (gnat_field) == E_Discriminant)
2870                 && No (Component_Clause (gnat_field)))
2871               {
2872                 all_rep = false;
2873                 break;
2874               }
2875
2876         /* If this is a record extension, go a level further to find the
2877            record definition.  Also, verify we have a Parent_Subtype.  */
2878         if (is_extension)
2879           {
2880             if (!type_annotate_only
2881                 || Present (Record_Extension_Part (record_definition)))
2882               record_definition = Record_Extension_Part (record_definition);
2883
2884             gcc_assert (type_annotate_only
2885                         || Present (Parent_Subtype (gnat_entity)));
2886           }
2887
2888         /* Make a node for the record.  If we are not defining the record,
2889            suppress expanding incomplete types.  */
2890         gnu_type = make_node (tree_code_for_record_type (gnat_entity));
2891         TYPE_NAME (gnu_type) = gnu_entity_name;
2892         TYPE_PACKED (gnu_type) = (packed != 0) || has_rep;
2893         if (Reverse_Storage_Order (gnat_entity) && !GNAT_Mode)
2894           sorry ("non-default Scalar_Storage_Order");
2895         process_attributes (&gnu_type, &attr_list, true, gnat_entity);
2896
2897         if (!definition)
2898           {
2899             defer_incomplete_level++;
2900             this_deferred = true;
2901           }
2902
2903         /* If both a size and rep clause was specified, put the size in
2904            the record type now so that it can get the proper mode.  */
2905         if (has_rep && Known_RM_Size (gnat_entity))
2906           TYPE_SIZE (gnu_type)
2907             = UI_To_gnu (RM_Size (gnat_entity), bitsizetype);
2908
2909         /* Always set the alignment here so that it can be used to
2910            set the mode, if it is making the alignment stricter.  If
2911            it is invalid, it will be checked again below.  If this is to
2912            be Atomic, choose a default alignment of a word unless we know
2913            the size and it's smaller.  */
2914         if (Known_Alignment (gnat_entity))
2915           TYPE_ALIGN (gnu_type)
2916             = validate_alignment (Alignment (gnat_entity), gnat_entity, 0);
2917         else if (Is_Atomic_Or_VFA (gnat_entity) && Known_Esize (gnat_entity))
2918           {
2919             unsigned int size = UI_To_Int (Esize (gnat_entity));
2920             TYPE_ALIGN (gnu_type)
2921               = size >= BITS_PER_WORD ? BITS_PER_WORD : ceil_pow2 (size);
2922           }
2923         /* If a type needs strict alignment, the minimum size will be the
2924            type size instead of the RM size (see validate_size).  Cap the
2925            alignment, lest it causes this type size to become too large.  */
2926         else if (Strict_Alignment (gnat_entity) && Known_RM_Size (gnat_entity))
2927           {
2928             unsigned int raw_size = UI_To_Int (RM_Size (gnat_entity));
2929             unsigned int raw_align = raw_size & -raw_size;
2930             if (raw_align < BIGGEST_ALIGNMENT)
2931               TYPE_ALIGN (gnu_type) = raw_align;
2932           }
2933         else
2934           TYPE_ALIGN (gnu_type) = 0;
2935
2936         /* If we have a Parent_Subtype, make a field for the parent.  If
2937            this record has rep clauses, force the position to zero.  */
2938         if (Present (Parent_Subtype (gnat_entity)))
2939           {
2940             Entity_Id gnat_parent = Parent_Subtype (gnat_entity);
2941             tree gnu_dummy_parent_type = make_node (RECORD_TYPE);
2942             tree gnu_parent;
2943
2944             /* A major complexity here is that the parent subtype will
2945                reference our discriminants in its Stored_Constraint list.
2946                But those must reference the parent component of this record
2947                which is precisely of the parent subtype we have not built yet!
2948                To break the circle we first build a dummy COMPONENT_REF which
2949                represents the "get to the parent" operation and initialize
2950                each of those discriminants to a COMPONENT_REF of the above
2951                dummy parent referencing the corresponding discriminant of the
2952                base type of the parent subtype.  */
2953             gnu_get_parent = build3 (COMPONENT_REF, gnu_dummy_parent_type,
2954                                      build0 (PLACEHOLDER_EXPR, gnu_type),
2955                                      build_decl (input_location,
2956                                                  FIELD_DECL, NULL_TREE,
2957                                                  gnu_dummy_parent_type),
2958                                      NULL_TREE);
2959
2960             if (has_discr)
2961               for (gnat_field = First_Stored_Discriminant (gnat_entity);
2962                    Present (gnat_field);
2963                    gnat_field = Next_Stored_Discriminant (gnat_field))
2964                 if (Present (Corresponding_Discriminant (gnat_field)))
2965                   {
2966                     tree gnu_field
2967                       = gnat_to_gnu_field_decl (Corresponding_Discriminant
2968                                                 (gnat_field));
2969                     save_gnu_tree
2970                       (gnat_field,
2971                        build3 (COMPONENT_REF, TREE_TYPE (gnu_field),
2972                                gnu_get_parent, gnu_field, NULL_TREE),
2973                        true);
2974                   }
2975
2976             /* Then we build the parent subtype.  If it has discriminants but
2977                the type itself has unknown discriminants, this means that it
2978                doesn't contain information about how the discriminants are
2979                derived from those of the ancestor type, so it cannot be used
2980                directly.  Instead it is built by cloning the parent subtype
2981                of the underlying record view of the type, for which the above
2982                derivation of discriminants has been made explicit.  */
2983             if (Has_Discriminants (gnat_parent)
2984                 && Has_Unknown_Discriminants (gnat_entity))
2985               {
2986                 Entity_Id gnat_uview = Underlying_Record_View (gnat_entity);
2987
2988                 /* If we are defining the type, the underlying record
2989                    view must already have been elaborated at this point.
2990                    Otherwise do it now as its parent subtype cannot be
2991                    technically elaborated on its own.  */
2992                 if (definition)
2993                   gcc_assert (present_gnu_tree (gnat_uview));
2994                 else
2995                   gnat_to_gnu_entity (gnat_uview, NULL_TREE, 0);
2996
2997                 gnu_parent = gnat_to_gnu_type (Parent_Subtype (gnat_uview));
2998
2999                 /* Substitute the "get to the parent" of the type for that
3000                    of its underlying record view in the cloned type.  */
3001                 for (gnat_field = First_Stored_Discriminant (gnat_uview);
3002                      Present (gnat_field);
3003                      gnat_field = Next_Stored_Discriminant (gnat_field))
3004                   if (Present (Corresponding_Discriminant (gnat_field)))
3005                     {
3006                       tree gnu_field = gnat_to_gnu_field_decl (gnat_field);
3007                       tree gnu_ref
3008                         = build3 (COMPONENT_REF, TREE_TYPE (gnu_field),
3009                                   gnu_get_parent, gnu_field, NULL_TREE);
3010                       gnu_parent
3011                         = substitute_in_type (gnu_parent, gnu_field, gnu_ref);
3012                     }
3013               }
3014             else
3015               gnu_parent = gnat_to_gnu_type (gnat_parent);
3016
3017             /* The parent field needs strict alignment so, if it is to
3018                be created with a component clause below, then we need
3019                to apply the same adjustment as in gnat_to_gnu_field.  */
3020             if (has_rep && TYPE_ALIGN (gnu_type) < TYPE_ALIGN (gnu_parent))
3021               TYPE_ALIGN (gnu_type) = TYPE_ALIGN (gnu_parent);
3022
3023             /* Finally we fix up both kinds of twisted COMPONENT_REF we have
3024                initially built.  The discriminants must reference the fields
3025                of the parent subtype and not those of its base type for the
3026                placeholder machinery to properly work.  */
3027             if (has_discr)
3028               {
3029                 /* The actual parent subtype is the full view.  */
3030                 if (IN (Ekind (gnat_parent), Private_Kind))
3031                   {
3032                     if (Present (Full_View (gnat_parent)))
3033                       gnat_parent = Full_View (gnat_parent);
3034                     else
3035                       gnat_parent = Underlying_Full_View (gnat_parent);
3036                   }
3037
3038                 for (gnat_field = First_Stored_Discriminant (gnat_entity);
3039                      Present (gnat_field);
3040                      gnat_field = Next_Stored_Discriminant (gnat_field))
3041                   if (Present (Corresponding_Discriminant (gnat_field)))
3042                     {
3043                       Entity_Id field;
3044                       for (field = First_Stored_Discriminant (gnat_parent);
3045                            Present (field);
3046                            field = Next_Stored_Discriminant (field))
3047                         if (same_discriminant_p (gnat_field, field))
3048                           break;
3049                       gcc_assert (Present (field));
3050                       TREE_OPERAND (get_gnu_tree (gnat_field), 1)
3051                         = gnat_to_gnu_field_decl (field);
3052                     }
3053               }
3054
3055             /* The "get to the parent" COMPONENT_REF must be given its
3056                proper type...  */
3057             TREE_TYPE (gnu_get_parent) = gnu_parent;
3058
3059             /* ...and reference the _Parent field of this record.  */
3060             gnu_field
3061               = create_field_decl (parent_name_id,
3062                                    gnu_parent, gnu_type,
3063                                    has_rep
3064                                    ? TYPE_SIZE (gnu_parent) : NULL_TREE,
3065                                    has_rep
3066                                    ? bitsize_zero_node : NULL_TREE,
3067                                    0, 1);
3068             DECL_INTERNAL_P (gnu_field) = 1;
3069             TREE_OPERAND (gnu_get_parent, 1) = gnu_field;
3070             TYPE_FIELDS (gnu_type) = gnu_field;
3071           }
3072
3073         /* Make the fields for the discriminants and put them into the record
3074            unless it's an Unchecked_Union.  */
3075         if (has_discr)
3076           for (gnat_field = First_Stored_Discriminant (gnat_entity);
3077                Present (gnat_field);
3078                gnat_field = Next_Stored_Discriminant (gnat_field))
3079             {
3080               /* If this is a record extension and this discriminant is the
3081                  renaming of another discriminant, we've handled it above.  */
3082               if (Present (Parent_Subtype (gnat_entity))
3083                   && Present (Corresponding_Discriminant (gnat_field)))
3084                 continue;
3085
3086               gnu_field
3087                 = gnat_to_gnu_field (gnat_field, gnu_type, packed, definition,
3088                                      debug_info_p);
3089
3090               /* Make an expression using a PLACEHOLDER_EXPR from the
3091                  FIELD_DECL node just created and link that with the
3092                  corresponding GNAT defining identifier.  */
3093               save_gnu_tree (gnat_field,
3094                              build3 (COMPONENT_REF, TREE_TYPE (gnu_field),
3095                                      build0 (PLACEHOLDER_EXPR, gnu_type),
3096                                      gnu_field, NULL_TREE),
3097                              true);
3098
3099               if (!is_unchecked_union)
3100                 {
3101                   DECL_CHAIN (gnu_field) = gnu_field_list;
3102                   gnu_field_list = gnu_field;
3103                 }
3104             }
3105
3106         /* If we have a derived untagged type that renames discriminants in
3107            the root type, the (stored) discriminants are a just copy of the
3108            discriminants of the root type.  This means that any constraints
3109            added by the renaming in the derivation are disregarded as far
3110            as the layout of the derived type is concerned.  To rescue them,
3111            we change the type of the (stored) discriminants to a subtype
3112            with the bounds of the type of the visible discriminants.  */
3113         if (has_discr
3114             && !is_extension
3115             && Stored_Constraint (gnat_entity) != No_Elist)
3116           for (gnat_constr = First_Elmt (Stored_Constraint (gnat_entity));
3117                gnat_constr != No_Elmt;
3118                gnat_constr = Next_Elmt (gnat_constr))
3119             if (Nkind (Node (gnat_constr)) == N_Identifier
3120                 /* Ignore access discriminants.  */
3121                 && !Is_Access_Type (Etype (Node (gnat_constr)))
3122                 && Ekind (Entity (Node (gnat_constr))) == E_Discriminant)
3123               {
3124                 Entity_Id gnat_discr = Entity (Node (gnat_constr));
3125                 tree gnu_discr_type, gnu_ref;
3126
3127                 /* If the scope of the discriminant is not the record type,
3128                    this means that we're processing the implicit full view
3129                    of a type derived from a private discriminated type: in
3130                    this case, the Stored_Constraint list is simply copied
3131                    from the partial view, see Build_Derived_Private_Type.
3132                    So we need to retrieve the corresponding discriminant
3133                    of the implicit full view, otherwise we will abort.  */
3134                 if (Scope (gnat_discr) != gnat_entity)
3135                   {
3136                     Entity_Id field;
3137                     for (field = First_Entity (gnat_entity);
3138                          Present (field);
3139                          field = Next_Entity (field))
3140                       if (Ekind (field) == E_Discriminant
3141                           && same_discriminant_p (gnat_discr, field))
3142                         break;
3143                     gcc_assert (Present (field));
3144                     gnat_discr = field;
3145                   }
3146
3147                 gnu_discr_type = gnat_to_gnu_type (Etype (gnat_discr));
3148                 gnu_ref
3149                   = gnat_to_gnu_entity (Original_Record_Component (gnat_discr),
3150                                         NULL_TREE, 0);
3151
3152                 /* GNU_REF must be an expression using a PLACEHOLDER_EXPR built
3153                    just above for one of the stored discriminants.  */
3154                 gcc_assert (TREE_TYPE (TREE_OPERAND (gnu_ref, 0)) == gnu_type);
3155
3156                 if (gnu_discr_type != TREE_TYPE (gnu_ref))
3157                   {
3158                     const unsigned prec = TYPE_PRECISION (TREE_TYPE (gnu_ref));
3159                     tree gnu_subtype
3160                       = TYPE_UNSIGNED (TREE_TYPE (gnu_ref))
3161                         ? make_unsigned_type (prec) : make_signed_type (prec);
3162                     TREE_TYPE (gnu_subtype) = TREE_TYPE (gnu_ref);
3163                     TYPE_EXTRA_SUBTYPE_P (gnu_subtype) = 1;
3164                     SET_TYPE_RM_MIN_VALUE (gnu_subtype,
3165                                            TYPE_MIN_VALUE (gnu_discr_type));
3166                     SET_TYPE_RM_MAX_VALUE (gnu_subtype,
3167                                            TYPE_MAX_VALUE (gnu_discr_type));
3168                     TREE_TYPE (gnu_ref)
3169                       = TREE_TYPE (TREE_OPERAND (gnu_ref, 1)) = gnu_subtype;
3170                   }
3171               }
3172
3173         /* Add the fields into the record type and finish it up.  */
3174         components_to_record (gnu_type, Component_List (record_definition),
3175                               gnu_field_list, packed, definition, false,
3176                               all_rep, is_unchecked_union,
3177                               !Comes_From_Source (gnat_entity), debug_info_p,
3178                               false, OK_To_Reorder_Components (gnat_entity),
3179                               all_rep ? NULL_TREE : bitsize_zero_node, NULL);
3180
3181         /* Fill in locations of fields.  */
3182         annotate_rep (gnat_entity, gnu_type);
3183
3184         /* If there are any entities in the chain corresponding to components
3185            that we did not elaborate, ensure we elaborate their types if they
3186            are Itypes.  */
3187         for (gnat_temp = First_Entity (gnat_entity);
3188              Present (gnat_temp);
3189              gnat_temp = Next_Entity (gnat_temp))
3190           if ((Ekind (gnat_temp) == E_Component
3191                || Ekind (gnat_temp) == E_Discriminant)
3192               && Is_Itype (Etype (gnat_temp))
3193               && !present_gnu_tree (gnat_temp))
3194             gnat_to_gnu_entity (Etype (gnat_temp), NULL_TREE, 0);
3195
3196         /* If this is a record type associated with an exception definition,
3197            equate its fields to those of the standard exception type.  This
3198            will make it possible to convert between them.  */
3199         if (gnu_entity_name == exception_data_name_id)
3200           {
3201             tree gnu_std_field;
3202             for (gnu_field = TYPE_FIELDS (gnu_type),
3203                  gnu_std_field = TYPE_FIELDS (except_type_node);
3204                  gnu_field;
3205                  gnu_field = DECL_CHAIN (gnu_field),
3206                  gnu_std_field = DECL_CHAIN (gnu_std_field))
3207               SET_DECL_ORIGINAL_FIELD_TO_FIELD (gnu_field, gnu_std_field);
3208             gcc_assert (!gnu_std_field);
3209           }
3210       }
3211       break;
3212
3213     case E_Class_Wide_Subtype:
3214       /* If an equivalent type is present, that is what we should use.
3215          Otherwise, fall through to handle this like a record subtype
3216          since it may have constraints.  */
3217       if (gnat_equiv_type != gnat_entity)
3218         {
3219           gnu_decl = gnat_to_gnu_entity (gnat_equiv_type, NULL_TREE, 0);
3220           maybe_present = true;
3221           break;
3222         }
3223
3224       /* ... fall through ... */
3225
3226     case E_Record_Subtype:
3227       /* If Cloned_Subtype is Present it means this record subtype has
3228          identical layout to that type or subtype and we should use
3229          that GCC type for this one.  The front end guarantees that
3230          the component list is shared.  */
3231       if (Present (Cloned_Subtype (gnat_entity)))
3232         {
3233           gnu_decl = gnat_to_gnu_entity (Cloned_Subtype (gnat_entity),
3234                                          NULL_TREE, 0);
3235           maybe_present = true;
3236           break;
3237         }
3238
3239       /* Otherwise, first ensure the base type is elaborated.  Then, if we are
3240          changing the type, make a new type with each field having the type of
3241          the field in the new subtype but the position computed by transforming
3242          every discriminant reference according to the constraints.  We don't
3243          see any difference between private and non-private type here since
3244          derivations from types should have been deferred until the completion
3245          of the private type.  */
3246       else
3247         {
3248           Entity_Id gnat_base_type = Implementation_Base_Type (gnat_entity);
3249           tree gnu_base_type;
3250
3251           if (!definition)
3252             {
3253               defer_incomplete_level++;
3254               this_deferred = true;
3255             }
3256
3257           gnu_base_type
3258             = TYPE_MAIN_VARIANT (gnat_to_gnu_type (gnat_base_type));
3259
3260           if (present_gnu_tree (gnat_entity))
3261             {
3262               maybe_present = true;
3263               break;
3264             }
3265
3266           /* If this is a record subtype associated with a dispatch table,
3267              strip the suffix.  This is necessary to make sure 2 different
3268              subtypes associated with the imported and exported views of a
3269              dispatch table are properly merged in LTO mode.  */
3270           if (Is_Dispatch_Table_Entity (gnat_entity))
3271             {
3272               char *p;
3273               Get_Encoded_Name (gnat_entity);
3274               p = strchr (Name_Buffer, '_');
3275               gcc_assert (p);
3276               strcpy (p+2, "dtS");
3277               gnu_entity_name = get_identifier (Name_Buffer);
3278             }
3279
3280           /* When the subtype has discriminants and these discriminants affect
3281              the initial shape it has inherited, factor them in.  But for an
3282              Unchecked_Union (it must be an Itype), just return the type.
3283              We can't just test Is_Constrained because private subtypes without
3284              discriminants of types with discriminants with default expressions
3285              are Is_Constrained but aren't constrained!  */
3286           if (IN (Ekind (gnat_base_type), Record_Kind)
3287               && !Is_Unchecked_Union (gnat_base_type)
3288               && !Is_For_Access_Subtype (gnat_entity)
3289               && Has_Discriminants (gnat_entity)
3290               && Is_Constrained (gnat_entity)
3291               && Stored_Constraint (gnat_entity) != No_Elist)
3292             {
3293               vec<subst_pair> gnu_subst_list
3294                 = build_subst_list (gnat_entity, gnat_base_type, definition);
3295               tree gnu_unpad_base_type, gnu_rep_part, gnu_variant_part;
3296               tree gnu_pos_list, gnu_field_list = NULL_TREE;
3297               bool selected_variant = false, all_constant_pos = true;
3298               Entity_Id gnat_field;
3299               vec<variant_desc> gnu_variant_list;
3300
3301               gnu_type = make_node (RECORD_TYPE);
3302               TYPE_NAME (gnu_type) = gnu_entity_name;
3303               TYPE_PACKED (gnu_type) = TYPE_PACKED (gnu_base_type);
3304               process_attributes (&gnu_type, &attr_list, true, gnat_entity);
3305
3306               /* Set the size, alignment and alias set of the new type to
3307                  match that of the old one, doing required substitutions.  */
3308               copy_and_substitute_in_size (gnu_type, gnu_base_type,
3309                                            gnu_subst_list);
3310
3311               if (TYPE_IS_PADDING_P (gnu_base_type))
3312                 gnu_unpad_base_type = TREE_TYPE (TYPE_FIELDS (gnu_base_type));
3313               else
3314                 gnu_unpad_base_type = gnu_base_type;
3315
3316               /* Look for REP and variant parts in the base type.  */
3317               gnu_rep_part = get_rep_part (gnu_unpad_base_type);
3318               gnu_variant_part = get_variant_part (gnu_unpad_base_type);
3319
3320               /* If there is a variant part, we must compute whether the
3321                  constraints statically select a particular variant.  If
3322                  so, we simply drop the qualified union and flatten the
3323                  list of fields.  Otherwise we'll build a new qualified
3324                  union for the variants that are still relevant.  */
3325               if (gnu_variant_part)
3326                 {
3327                   variant_desc *v;
3328                   unsigned int i;
3329
3330                   gnu_variant_list
3331                     = build_variant_list (TREE_TYPE (gnu_variant_part),
3332                                           gnu_subst_list,
3333                                           vNULL);
3334
3335                   /* If all the qualifiers are unconditionally true, the
3336                      innermost variant is statically selected.  */
3337                   selected_variant = true;
3338                   FOR_EACH_VEC_ELT (gnu_variant_list, i, v)
3339                     if (!integer_onep (v->qual))
3340                       {
3341                         selected_variant = false;
3342                         break;
3343                       }
3344
3345                   /* Otherwise, create the new variants.  */
3346                   if (!selected_variant)
3347                     FOR_EACH_VEC_ELT (gnu_variant_list, i, v)
3348                       {
3349                         tree old_variant = v->type;
3350                         tree new_variant = make_node (RECORD_TYPE);
3351                         tree suffix
3352                           = concat_name (DECL_NAME (gnu_variant_part),
3353                                          IDENTIFIER_POINTER
3354                                          (DECL_NAME (v->field)));
3355                         TYPE_NAME (new_variant)
3356                           = concat_name (TYPE_NAME (gnu_type),
3357                                          IDENTIFIER_POINTER (suffix));
3358                         copy_and_substitute_in_size (new_variant, old_variant,
3359                                                      gnu_subst_list);
3360                         v->new_type = new_variant;
3361                       }
3362                 }
3363               else
3364                 {
3365                   gnu_variant_list.create (0);
3366                   selected_variant = false;
3367                 }
3368
3369               /* Make a list of fields and their position in the base type.  */
3370               gnu_pos_list
3371                 = build_position_list (gnu_unpad_base_type,
3372                                        gnu_variant_list.exists ()
3373                                        && !selected_variant,
3374                                        size_zero_node, bitsize_zero_node,
3375                                        BIGGEST_ALIGNMENT, NULL_TREE);
3376
3377               /* Now go down every component in the subtype and compute its
3378                  size and position from those of the component in the base
3379                  type and from the constraints of the subtype.  */
3380               for (gnat_field = First_Entity (gnat_entity);
3381                    Present (gnat_field);
3382                    gnat_field = Next_Entity (gnat_field))
3383                 if ((Ekind (gnat_field) == E_Component
3384                      || Ekind (gnat_field) == E_Discriminant)
3385                     && !(Present (Corresponding_Discriminant (gnat_field))
3386                          && Is_Tagged_Type (gnat_base_type))
3387                     && Underlying_Type
3388                        (Scope (Original_Record_Component (gnat_field)))
3389                        == gnat_base_type)
3390                   {
3391                     Name_Id gnat_name = Chars (gnat_field);
3392                     Entity_Id gnat_old_field
3393                       = Original_Record_Component (gnat_field);
3394                     tree gnu_old_field
3395                       = gnat_to_gnu_field_decl (gnat_old_field);
3396                     tree gnu_context = DECL_CONTEXT (gnu_old_field);
3397                     tree gnu_field, gnu_field_type, gnu_size, gnu_pos;
3398                     tree gnu_cont_type, gnu_last = NULL_TREE;
3399
3400                     /* If the type is the same, retrieve the GCC type from the
3401                        old field to take into account possible adjustments.  */
3402                     if (Etype (gnat_field) == Etype (gnat_old_field))
3403                       gnu_field_type = TREE_TYPE (gnu_old_field);
3404                     else
3405                       gnu_field_type = gnat_to_gnu_type (Etype (gnat_field));
3406
3407                     /* If there was a component clause, the field types must be
3408                        the same for the type and subtype, so copy the data from
3409                        the old field to avoid recomputation here.  Also if the
3410                        field is justified modular and the optimization in
3411                        gnat_to_gnu_field was applied.  */
3412                     if (Present (Component_Clause (gnat_old_field))
3413                         || (TREE_CODE (gnu_field_type) == RECORD_TYPE
3414                             && TYPE_JUSTIFIED_MODULAR_P (gnu_field_type)
3415                             && TREE_TYPE (TYPE_FIELDS (gnu_field_type))
3416                                == TREE_TYPE (gnu_old_field)))
3417                       {
3418                         gnu_size = DECL_SIZE (gnu_old_field);
3419                         gnu_field_type = TREE_TYPE (gnu_old_field);
3420                       }
3421
3422                     /* If the old field was packed and of constant size, we
3423                        have to get the old size here, as it might differ from
3424                        what the Etype conveys and the latter might overlap
3425                        onto the following field.  Try to arrange the type for
3426                        possible better packing along the way.  */
3427                     else if (DECL_PACKED (gnu_old_field)
3428                              && TREE_CODE (DECL_SIZE (gnu_old_field))
3429                                 == INTEGER_CST)
3430                       {
3431                         gnu_size = DECL_SIZE (gnu_old_field);
3432                         if (RECORD_OR_UNION_TYPE_P (gnu_field_type)
3433                             && !TYPE_FAT_POINTER_P (gnu_field_type)
3434                             && tree_fits_uhwi_p (TYPE_SIZE (gnu_field_type)))
3435                           gnu_field_type
3436                             = make_packable_type (gnu_field_type, true);
3437                       }
3438
3439                     else
3440                       gnu_size = TYPE_SIZE (gnu_field_type);
3441
3442                     /* If the context of the old field is the base type or its
3443                        REP part (if any), put the field directly in the new
3444                        type; otherwise look up the context in the variant list
3445                        and put the field either in the new type if there is a
3446                        selected variant or in one of the new variants.  */
3447                     if (gnu_context == gnu_unpad_base_type
3448                         || (gnu_rep_part
3449                             && gnu_context == TREE_TYPE (gnu_rep_part)))
3450                       gnu_cont_type = gnu_type;
3451                     else
3452                       {
3453                         variant_desc *v;
3454                         unsigned int i;
3455                         tree rep_part;
3456
3457                         FOR_EACH_VEC_ELT (gnu_variant_list, i, v)
3458                           if (gnu_context == v->type
3459                               || ((rep_part = get_rep_part (v->type))
3460                                   && gnu_context == TREE_TYPE (rep_part)))
3461                             break;
3462                         if (v)
3463                           {
3464                             if (selected_variant)
3465                               gnu_cont_type = gnu_type;
3466                             else
3467                               gnu_cont_type = v->new_type;
3468                           }
3469                         else
3470                           /* The front-end may pass us "ghost" components if
3471                              it fails to recognize that a constrained subtype
3472                              is statically constrained.  Discard them.  */
3473                           continue;
3474                       }
3475
3476                     /* Now create the new field modeled on the old one.  */
3477                     gnu_field
3478                       = create_field_decl_from (gnu_old_field, gnu_field_type,
3479                                                 gnu_cont_type, gnu_size,
3480                                                 gnu_pos_list, gnu_subst_list);
3481                     gnu_pos = DECL_FIELD_OFFSET (gnu_field);
3482
3483                     /* Put it in one of the new variants directly.  */
3484                     if (gnu_cont_type != gnu_type)
3485                       {
3486                         DECL_CHAIN (gnu_field) = TYPE_FIELDS (gnu_cont_type);
3487                         TYPE_FIELDS (gnu_cont_type) = gnu_field;
3488                       }
3489
3490                     /* To match the layout crafted in components_to_record,
3491                        if this is the _Tag or _Parent field, put it before
3492                        any other fields.  */
3493                     else if (gnat_name == Name_uTag
3494                              || gnat_name == Name_uParent)
3495                       gnu_field_list = chainon (gnu_field_list, gnu_field);
3496
3497                     /* Similarly, if this is the _Controller field, put
3498                        it before the other fields except for the _Tag or
3499                        _Parent field.  */
3500                     else if (gnat_name == Name_uController && gnu_last)
3501                       {
3502                         DECL_CHAIN (gnu_field) = DECL_CHAIN (gnu_last);
3503                         DECL_CHAIN (gnu_last) = gnu_field;
3504                       }
3505
3506                     /* Otherwise, if this is a regular field, put it after
3507                        the other fields.  */
3508                     else
3509                       {
3510                         DECL_CHAIN (gnu_field) = gnu_field_list;
3511                         gnu_field_list = gnu_field;
3512                         if (!gnu_last)
3513                           gnu_last = gnu_field;
3514                         if (TREE_CODE (gnu_pos) != INTEGER_CST)
3515                           all_constant_pos = false;
3516                       }
3517
3518                     save_gnu_tree (gnat_field, gnu_field, false);
3519                   }
3520
3521               /* If there is a variant list, a selected variant and the fields
3522                  all have a constant position, put them in order of increasing
3523                  position to match that of constant CONSTRUCTORs.  Likewise if
3524                  there is no variant list but a REP part, since the latter has
3525                  been flattened in the process.  */
3526               if (((gnu_variant_list.exists () && selected_variant)
3527                    || (!gnu_variant_list.exists () && gnu_rep_part))
3528                   && all_constant_pos)
3529                 {
3530                   const int len = list_length (gnu_field_list);
3531                   tree *field_arr = XALLOCAVEC (tree, len), t;
3532                   int i;
3533
3534                   for (t = gnu_field_list, i = 0; t; t = DECL_CHAIN (t), i++)
3535                     field_arr[i] = t;
3536
3537                   qsort (field_arr, len, sizeof (tree), compare_field_bitpos);
3538
3539                   gnu_field_list = NULL_TREE;
3540                   for (i = 0; i < len; i++)
3541                     {
3542                       DECL_CHAIN (field_arr[i]) = gnu_field_list;
3543                       gnu_field_list = field_arr[i];
3544                     }
3545                 }
3546
3547               /* If there is a variant list and no selected variant, we need
3548                  to create the nest of variant parts from the old nest.  */
3549               else if (gnu_variant_list.exists () && !selected_variant)
3550                 {
3551                   tree new_variant_part
3552                     = create_variant_part_from (gnu_variant_part,
3553                                                 gnu_variant_list, gnu_type,
3554                                                 gnu_pos_list, gnu_subst_list);
3555                   DECL_CHAIN (new_variant_part) = gnu_field_list;
3556                   gnu_field_list = new_variant_part;
3557                 }
3558
3559               /* Now go through the entities again looking for Itypes that
3560                  we have not elaborated but should (e.g., Etypes of fields
3561                  that have Original_Components).  */
3562               for (gnat_field = First_Entity (gnat_entity);
3563                    Present (gnat_field); gnat_field = Next_Entity (gnat_field))
3564                 if ((Ekind (gnat_field) == E_Discriminant
3565                      || Ekind (gnat_field) == E_Component)
3566                     && !present_gnu_tree (Etype (gnat_field)))
3567                   gnat_to_gnu_entity (Etype (gnat_field), NULL_TREE, 0);
3568
3569               /* Do not emit debug info for the type yet since we're going to
3570                  modify it below.  */
3571               finish_record_type (gnu_type, nreverse (gnu_field_list), 2,
3572                                   false);
3573               compute_record_mode (gnu_type);
3574
3575               /* Fill in locations of fields.  */
3576               annotate_rep (gnat_entity, gnu_type);
3577
3578               /* If debugging information is being written for the type, write
3579                  a record that shows what we are a subtype of and also make a
3580                  variable that indicates our size, if still variable.  */
3581               if (debug_info_p)
3582                 {
3583                   tree gnu_subtype_marker = make_node (RECORD_TYPE);
3584                   tree gnu_unpad_base_name
3585                     = TYPE_IDENTIFIER (gnu_unpad_base_type);
3586                   tree gnu_size_unit = TYPE_SIZE_UNIT (gnu_type);
3587
3588                   TYPE_NAME (gnu_subtype_marker)
3589                     = create_concat_name (gnat_entity, "XVS");
3590                   finish_record_type (gnu_subtype_marker,
3591                                       create_field_decl (gnu_unpad_base_name,
3592                                                          build_reference_type
3593                                                          (gnu_unpad_base_type),
3594                                                          gnu_subtype_marker,
3595                                                          NULL_TREE, NULL_TREE,
3596                                                          0, 0),
3597                                       0, true);
3598
3599                   add_parallel_type (gnu_type, gnu_subtype_marker);
3600
3601                   if (definition
3602                       && TREE_CODE (gnu_size_unit) != INTEGER_CST
3603                       && !CONTAINS_PLACEHOLDER_P (gnu_size_unit))
3604                     TYPE_SIZE_UNIT (gnu_subtype_marker)
3605                       = create_var_decl (create_concat_name (gnat_entity,
3606                                                              "XVZ"),
3607                                          NULL_TREE, sizetype, gnu_size_unit,
3608                                          false, false, false, false, NULL,
3609                                          gnat_entity);
3610                 }
3611
3612               gnu_variant_list.release ();
3613               gnu_subst_list.release ();
3614
3615               /* Now we can finalize it.  */
3616               rest_of_record_type_compilation (gnu_type);
3617             }
3618
3619           /* Otherwise, go down all the components in the new type and make
3620              them equivalent to those in the base type.  */
3621           else
3622             {
3623               gnu_type = gnu_base_type;
3624
3625               for (gnat_temp = First_Entity (gnat_entity);
3626                    Present (gnat_temp);
3627                    gnat_temp = Next_Entity (gnat_temp))
3628                 if ((Ekind (gnat_temp) == E_Discriminant
3629                      && !Is_Unchecked_Union (gnat_base_type))
3630                     || Ekind (gnat_temp) == E_Component)
3631                   save_gnu_tree (gnat_temp,
3632                                  gnat_to_gnu_field_decl
3633                                  (Original_Record_Component (gnat_temp)),
3634                                  false);
3635             }
3636         }
3637       break;
3638
3639     case E_Access_Subprogram_Type:
3640       /* Use the special descriptor type for dispatch tables if needed,
3641          that is to say for the Prim_Ptr of a-tags.ads and its clones.
3642          Note that we are only required to do so for static tables in
3643          order to be compatible with the C++ ABI, but Ada 2005 allows
3644          to extend library level tagged types at the local level so
3645          we do it in the non-static case as well.  */
3646       if (TARGET_VTABLE_USES_DESCRIPTORS
3647           && Is_Dispatch_Table_Entity (gnat_entity))
3648         {
3649             gnu_type = fdesc_type_node;
3650             gnu_size = TYPE_SIZE (gnu_type);
3651             break;
3652         }
3653
3654       /* ... fall through ... */
3655
3656     case E_Anonymous_Access_Subprogram_Type:
3657       /* If we are not defining this entity, and we have incomplete
3658          entities being processed above us, make a dummy type and
3659          fill it in later.  */
3660       if (!definition && defer_incomplete_level != 0)
3661         {
3662           struct incomplete *p = XNEW (struct incomplete);
3663
3664           gnu_type
3665             = build_pointer_type
3666               (make_dummy_type (Directly_Designated_Type (gnat_entity)));
3667           gnu_decl = create_type_decl (gnu_entity_name, gnu_type,
3668                                        !Comes_From_Source (gnat_entity),
3669                                        debug_info_p, gnat_entity);
3670           this_made_decl = true;
3671           gnu_type = TREE_TYPE (gnu_decl);
3672           save_gnu_tree (gnat_entity, gnu_decl, false);
3673           saved = true;
3674
3675           p->old_type = TREE_TYPE (gnu_type);
3676           p->full_type = Directly_Designated_Type (gnat_entity);
3677           p->next = defer_incomplete_list;
3678           defer_incomplete_list = p;
3679           break;
3680         }
3681
3682       /* ... fall through ... */
3683
3684     case E_Allocator_Type:
3685     case E_Access_Type:
3686     case E_Access_Attribute_Type:
3687     case E_Anonymous_Access_Type:
3688     case E_General_Access_Type:
3689       {
3690         /* The designated type and its equivalent type for gigi.  */
3691         Entity_Id gnat_desig_type = Directly_Designated_Type (gnat_entity);
3692         Entity_Id gnat_desig_equiv = Gigi_Equivalent_Type (gnat_desig_type);
3693         /* Whether it comes from a limited with.  */
3694         bool is_from_limited_with
3695           = (IN (Ekind (gnat_desig_equiv), Incomplete_Kind)
3696              && From_Limited_With (gnat_desig_equiv));
3697         /* The "full view" of the designated type.  If this is an incomplete
3698            entity from a limited with, treat its non-limited view as the full
3699            view.  Otherwise, if this is an incomplete or private type, use the
3700            full view.  In the former case, we might point to a private type,
3701            in which case, we need its full view.  Also, we want to look at the
3702            actual type used for the representation, so this takes a total of
3703            three steps.  */
3704         Entity_Id gnat_desig_full_direct_first
3705           = (is_from_limited_with
3706              ? Non_Limited_View (gnat_desig_equiv)
3707              : (IN (Ekind (gnat_desig_equiv), Incomplete_Or_Private_Kind)
3708                 ? Full_View (gnat_desig_equiv) : Empty));
3709         Entity_Id gnat_desig_full_direct
3710           = ((is_from_limited_with
3711               && Present (gnat_desig_full_direct_first)
3712               && IN (Ekind (gnat_desig_full_direct_first), Private_Kind))
3713              ? Full_View (gnat_desig_full_direct_first)
3714              : gnat_desig_full_direct_first);
3715         Entity_Id gnat_desig_full
3716           = Gigi_Equivalent_Type (gnat_desig_full_direct);
3717         /* The type actually used to represent the designated type, either
3718            gnat_desig_full or gnat_desig_equiv.  */
3719         Entity_Id gnat_desig_rep;
3720         /* True if this is a pointer to an unconstrained array.  */
3721         bool is_unconstrained_array;
3722         /* We want to know if we'll be seeing the freeze node for any
3723            incomplete type we may be pointing to.  */
3724         bool in_main_unit
3725           = (Present (gnat_desig_full)
3726              ? In_Extended_Main_Code_Unit (gnat_desig_full)
3727              : In_Extended_Main_Code_Unit (gnat_desig_type));
3728         /* True if we make a dummy type here.  */
3729         bool made_dummy = false;
3730         /* The mode to be used for the pointer type.  */
3731         machine_mode p_mode = mode_for_size (esize, MODE_INT, 0);
3732         /* The GCC type used for the designated type.  */
3733         tree gnu_desig_type = NULL_TREE;
3734
3735         if (!targetm.valid_pointer_mode (p_mode))
3736           p_mode = ptr_mode;
3737
3738         /* If either the designated type or its full view is an unconstrained
3739            array subtype, replace it with the type it's a subtype of.  This
3740            avoids problems with multiple copies of unconstrained array types.
3741            Likewise, if the designated type is a subtype of an incomplete
3742            record type, use the parent type to avoid order of elaboration
3743            issues.  This can lose some code efficiency, but there is no
3744            alternative.  */
3745         if (Ekind (gnat_desig_equiv) == E_Array_Subtype
3746             && !Is_Constrained (gnat_desig_equiv))
3747           gnat_desig_equiv = Etype (gnat_desig_equiv);
3748         if (Present (gnat_desig_full)
3749             && ((Ekind (gnat_desig_full) == E_Array_Subtype
3750                  && !Is_Constrained (gnat_desig_full))
3751                 || (Ekind (gnat_desig_full) == E_Record_Subtype
3752                     && Ekind (Etype (gnat_desig_full)) == E_Record_Type)))
3753           gnat_desig_full = Etype (gnat_desig_full);
3754
3755         /* Set the type that's actually the representation of the designated
3756            type and also flag whether we have a unconstrained array.  */
3757         gnat_desig_rep
3758           = Present (gnat_desig_full) ? gnat_desig_full : gnat_desig_equiv;
3759         is_unconstrained_array
3760           = Is_Array_Type (gnat_desig_rep) && !Is_Constrained (gnat_desig_rep);
3761
3762         /* If we are pointing to an incomplete type whose completion is an
3763            unconstrained array, make dummy fat and thin pointer types to it.
3764            Likewise if the type itself is dummy or an unconstrained array.  */
3765         if (is_unconstrained_array
3766             && (Present (gnat_desig_full)
3767                 || (present_gnu_tree (gnat_desig_equiv)
3768                     && TYPE_IS_DUMMY_P
3769                        (TREE_TYPE (get_gnu_tree (gnat_desig_equiv))))
3770                 || (!in_main_unit
3771                     && defer_incomplete_level != 0
3772                     && !present_gnu_tree (gnat_desig_equiv))
3773                 || (in_main_unit
3774                     && is_from_limited_with
3775                     && Present (Freeze_Node (gnat_desig_equiv)))))
3776           {
3777             if (present_gnu_tree (gnat_desig_rep))
3778               gnu_desig_type = TREE_TYPE (get_gnu_tree (gnat_desig_rep));
3779             else
3780               {
3781                 gnu_desig_type = make_dummy_type (gnat_desig_rep);
3782                 made_dummy = true;
3783               }
3784
3785             /* If the call above got something that has a pointer, the pointer
3786                is our type.  This could have happened either because the type
3787                was elaborated or because somebody else executed the code.  */
3788             if (!TYPE_POINTER_TO (gnu_desig_type))
3789               build_dummy_unc_pointer_types (gnat_desig_equiv, gnu_desig_type);
3790             gnu_type = TYPE_POINTER_TO (gnu_desig_type);
3791           }
3792
3793         /* If we already know what the full type is, use it.  */
3794         else if (Present (gnat_desig_full)
3795                  && present_gnu_tree (gnat_desig_full))
3796           gnu_desig_type = TREE_TYPE (get_gnu_tree (gnat_desig_full));
3797
3798         /* Get the type of the thing we are to point to and build a pointer to
3799            it.  If it is a reference to an incomplete or private type with a
3800            full view that is a record, make a dummy type node and get the
3801            actual type later when we have verified it is safe.  */
3802         else if ((!in_main_unit
3803                   && !present_gnu_tree (gnat_desig_equiv)
3804                   && Present (gnat_desig_full)
3805                   && !present_gnu_tree (gnat_desig_full)
3806                   && Is_Record_Type (gnat_desig_full))
3807                  /* Likewise if we are pointing to a record or array and we are
3808                     to defer elaborating incomplete types.  We do this as this
3809                     access type may be the full view of a private type.  Note
3810                     that the unconstrained array case is handled above.  */
3811                  || ((!in_main_unit || imported_p)
3812                      && defer_incomplete_level != 0
3813                      && !present_gnu_tree (gnat_desig_equiv)
3814                      && (Is_Record_Type (gnat_desig_rep)
3815                          || Is_Array_Type (gnat_desig_rep)))
3816                  /* If this is a reference from a limited_with type back to our
3817                     main unit and there's a freeze node for it, either we have
3818                     already processed the declaration and made the dummy type,
3819                     in which case we just reuse the latter, or we have not yet,
3820                     in which case we make the dummy type and it will be reused
3821                     when the declaration is finally processed.  In both cases,
3822                     the pointer eventually created below will be automatically
3823                     adjusted when the freeze node is processed.  Note that the
3824                     unconstrained array case is handled above.  */
3825                  ||  (in_main_unit
3826                       && is_from_limited_with
3827                       && Present (Freeze_Node (gnat_desig_rep))))
3828           {
3829             gnu_desig_type = make_dummy_type (gnat_desig_equiv);
3830             made_dummy = true;
3831           }
3832
3833         /* Otherwise handle the case of a pointer to itself.  */
3834         else if (gnat_desig_equiv == gnat_entity)
3835           {
3836             gnu_type
3837               = build_pointer_type_for_mode (void_type_node, p_mode,
3838                                              No_Strict_Aliasing (gnat_entity));
3839             TREE_TYPE (gnu_type) = TYPE_POINTER_TO (gnu_type) = gnu_type;
3840           }
3841
3842         /* If expansion is disabled, the equivalent type of a concurrent type
3843            is absent, so build a dummy pointer type.  */
3844         else if (type_annotate_only && No (gnat_desig_equiv))
3845           gnu_type = ptr_type_node;
3846
3847         /* Finally, handle the default case where we can just elaborate our
3848            designated type.  */
3849         else
3850           gnu_desig_type = gnat_to_gnu_type (gnat_desig_equiv);
3851
3852         /* It is possible that a call to gnat_to_gnu_type above resolved our
3853            type.  If so, just return it.  */
3854         if (present_gnu_tree (gnat_entity))
3855           {
3856             maybe_present = true;
3857             break;
3858           }
3859
3860         /* If we haven't done it yet, build the pointer type the usual way.  */
3861         if (!gnu_type)
3862           {
3863             /* Modify the designated type if we are pointing only to constant
3864                objects, but don't do it for unconstrained arrays.  */
3865             if (Is_Access_Constant (gnat_entity)
3866                 && TREE_CODE (gnu_desig_type) != UNCONSTRAINED_ARRAY_TYPE)
3867               {
3868                 gnu_desig_type
3869                   = change_qualified_type (gnu_desig_type, TYPE_QUAL_CONST);
3870
3871                 /* Some extra processing is required if we are building a
3872                    pointer to an incomplete type (in the GCC sense).  We might
3873                    have such a type if we just made a dummy, or directly out
3874                    of the call to gnat_to_gnu_type above if we are processing
3875                    an access type for a record component designating the
3876                    record type itself.  */
3877                 if (TYPE_MODE (gnu_desig_type) == VOIDmode)
3878                   {
3879                     /* We must ensure that the pointer to variant we make will
3880                        be processed by update_pointer_to when the initial type
3881                        is completed.  Pretend we made a dummy and let further
3882                        processing act as usual.  */
3883                     made_dummy = true;
3884
3885                     /* We must ensure that update_pointer_to will not retrieve
3886                        the dummy variant when building a properly qualified
3887                        version of the complete type.  We take advantage of the
3888                        fact that get_qualified_type is requiring TYPE_NAMEs to
3889                        match to influence build_qualified_type and then also
3890                        update_pointer_to here.  */
3891                     TYPE_NAME (gnu_desig_type)
3892                       = create_concat_name (gnat_desig_type, "INCOMPLETE_CST");
3893                   }
3894               }
3895
3896             gnu_type
3897               = build_pointer_type_for_mode (gnu_desig_type, p_mode,
3898                                              No_Strict_Aliasing (gnat_entity));
3899           }
3900
3901         /* If we are not defining this object and we have made a dummy pointer,
3902            save our current definition, evaluate the actual type, and replace
3903            the tentative type we made with the actual one.  If we are to defer
3904            actually looking up the actual type, make an entry in the deferred
3905            list.  If this is from a limited with, we may have to defer to the
3906            end of the current unit.  */
3907         if ((!in_main_unit || is_from_limited_with) && made_dummy)
3908           {
3909             tree gnu_old_desig_type;
3910
3911             if (TYPE_IS_FAT_POINTER_P (gnu_type))
3912               {
3913                 gnu_old_desig_type = TYPE_UNCONSTRAINED_ARRAY (gnu_type);
3914                 if (esize == POINTER_SIZE)
3915                   gnu_type = build_pointer_type
3916                              (TYPE_OBJECT_RECORD_TYPE (gnu_old_desig_type));
3917               }
3918             else
3919               gnu_old_desig_type = TREE_TYPE (gnu_type);
3920
3921             process_attributes (&gnu_type, &attr_list, false, gnat_entity);
3922             gnu_decl = create_type_decl (gnu_entity_name, gnu_type,
3923                                          !Comes_From_Source (gnat_entity),
3924                                          debug_info_p, gnat_entity);
3925             this_made_decl = true;
3926             gnu_type = TREE_TYPE (gnu_decl);
3927             save_gnu_tree (gnat_entity, gnu_decl, false);
3928             saved = true;
3929
3930             /* Note that the call to gnat_to_gnu_type on gnat_desig_equiv might
3931                update gnu_old_desig_type directly, in which case it will not be
3932                a dummy type any more when we get into update_pointer_to.
3933
3934                This can happen e.g. when the designated type is a record type,
3935                because their elaboration starts with an initial node from
3936                make_dummy_type, which may be the same node as the one we got.
3937
3938                Besides, variants of this non-dummy type might have been created
3939                along the way.  update_pointer_to is expected to properly take
3940                care of those situations.  */
3941             if (defer_incomplete_level == 0 && !is_from_limited_with)
3942               {
3943                 update_pointer_to (TYPE_MAIN_VARIANT (gnu_old_desig_type),
3944                                    gnat_to_gnu_type (gnat_desig_equiv));
3945               }
3946             else
3947               {
3948                 struct incomplete *p = XNEW (struct incomplete);
3949                 struct incomplete **head
3950                   = (is_from_limited_with
3951                      ? &defer_limited_with : &defer_incomplete_list);
3952                 p->old_type = gnu_old_desig_type;
3953                 p->full_type = gnat_desig_equiv;
3954                 p->next = *head;
3955                 *head = p;
3956               }
3957           }
3958       }
3959       break;
3960
3961     case E_Access_Protected_Subprogram_Type:
3962     case E_Anonymous_Access_Protected_Subprogram_Type:
3963       if (type_annotate_only && No (gnat_equiv_type))
3964         gnu_type = ptr_type_node;
3965       else
3966         {
3967           /* The run-time representation is the equivalent type.  */
3968           gnu_type = gnat_to_gnu_type (gnat_equiv_type);
3969           maybe_present = true;
3970         }
3971
3972       if (Is_Itype (Directly_Designated_Type (gnat_entity))
3973           && !present_gnu_tree (Directly_Designated_Type (gnat_entity))
3974           && No (Freeze_Node (Directly_Designated_Type (gnat_entity)))
3975           && !Is_Record_Type (Scope (Directly_Designated_Type (gnat_entity))))
3976         gnat_to_gnu_entity (Directly_Designated_Type (gnat_entity),
3977                             NULL_TREE, 0);
3978
3979       break;
3980
3981     case E_Access_Subtype:
3982
3983       /* We treat this as identical to its base type; any constraint is
3984          meaningful only to the front-end.
3985
3986          The designated type must be elaborated as well, if it does
3987          not have its own freeze node.  Designated (sub)types created
3988          for constrained components of records with discriminants are
3989          not frozen by the front-end and thus not elaborated by gigi,
3990          because their use may appear before the base type is frozen,
3991          and because it is not clear that they are needed anywhere in
3992          gigi.  With the current model, there is no correct place where
3993          they could be elaborated.  */
3994
3995       gnu_type = gnat_to_gnu_type (Etype (gnat_entity));
3996       if (Is_Itype (Directly_Designated_Type (gnat_entity))
3997           && !present_gnu_tree (Directly_Designated_Type (gnat_entity))
3998           && Is_Frozen (Directly_Designated_Type (gnat_entity))
3999           && No (Freeze_Node (Directly_Designated_Type (gnat_entity))))
4000         {
4001           /* If we are not defining this entity, and we have incomplete
4002              entities being processed above us, make a dummy type and
4003              elaborate it later.  */
4004           if (!definition && defer_incomplete_level != 0)
4005             {
4006               struct incomplete *p = XNEW (struct incomplete);
4007
4008               p->old_type
4009                 = make_dummy_type (Directly_Designated_Type (gnat_entity));
4010               p->full_type = Directly_Designated_Type (gnat_entity);
4011               p->next = defer_incomplete_list;
4012               defer_incomplete_list = p;
4013             }
4014           else if (!IN (Ekind (Base_Type
4015                                (Directly_Designated_Type (gnat_entity))),
4016                         Incomplete_Or_Private_Kind))
4017             gnat_to_gnu_entity (Directly_Designated_Type (gnat_entity),
4018                                 NULL_TREE, 0);
4019         }
4020
4021       maybe_present = true;
4022       break;
4023
4024     /* Subprogram Entities
4025
4026        The following access functions are defined for subprograms:
4027
4028                 Etype           Return type or Standard_Void_Type.
4029                 First_Formal    The first formal parameter.
4030                 Is_Imported     Indicates that the subprogram has appeared in
4031                                 an INTERFACE or IMPORT pragma.  For now we
4032                                 assume that the external language is C.
4033                 Is_Exported     Likewise but for an EXPORT pragma.
4034                 Is_Inlined      True if the subprogram is to be inlined.
4035
4036        Each parameter is first checked by calling must_pass_by_ref on its
4037        type to determine if it is passed by reference.  For parameters which
4038        are copied in, if they are Ada In Out or Out parameters, their return
4039        value becomes part of a record which becomes the return type of the
4040        function (C function - note that this applies only to Ada procedures
4041        so there is no Ada return type).  Additional code to store back the
4042        parameters will be generated on the caller side.  This transformation
4043        is done here, not in the front-end.
4044
4045        The intended result of the transformation can be seen from the
4046        equivalent source rewritings that follow:
4047
4048                                                 struct temp {int a,b};
4049        procedure P (A,B: In Out ...) is         temp P (int A,B)
4050        begin                                    {
4051          ..                                       ..
4052        end P;                                     return {A,B};
4053                                                 }
4054
4055                                                 temp t;
4056        P(X,Y);                                  t = P(X,Y);
4057                                                 X = t.a , Y = t.b;
4058
4059        For subprogram types we need to perform mainly the same conversions to
4060        GCC form that are needed for procedures and function declarations.  The
4061        only difference is that at the end, we make a type declaration instead
4062        of a function declaration.  */
4063
4064     case E_Subprogram_Type:
4065     case E_Function:
4066     case E_Procedure:
4067       {
4068         /* The type returned by a function or else Standard_Void_Type for a
4069            procedure.  */
4070         Entity_Id gnat_return_type = Etype (gnat_entity);
4071         tree gnu_return_type;
4072         /* The first GCC parameter declaration (a PARM_DECL node).  The
4073            PARM_DECL nodes are chained through the DECL_CHAIN field, so this
4074            actually is the head of this parameter list.  */
4075         tree gnu_param_list = NULL_TREE;
4076         /* Non-null for subprograms containing parameters passed by copy-in
4077            copy-out (Ada In Out or Out parameters not passed by reference),
4078            in which case it is the list of nodes used to specify the values
4079            of the In Out/Out parameters that are returned as a record upon
4080            procedure return.  The TREE_PURPOSE of an element of this list is
4081            a field of the record and the TREE_VALUE is the PARM_DECL
4082            corresponding to that field.  This list will be saved in the
4083            TYPE_CI_CO_LIST field of the FUNCTION_TYPE node we create.  */
4084         tree gnu_cico_list = NULL_TREE;
4085         /* List of fields in return type of procedure with copy-in copy-out
4086            parameters.  */
4087         tree gnu_field_list = NULL_TREE;
4088         /* If an import pragma asks to map this subprogram to a GCC builtin,
4089            this is the builtin DECL node.  */
4090         tree gnu_builtin_decl = NULL_TREE;
4091         tree gnu_ext_name = create_concat_name (gnat_entity, NULL);
4092         Entity_Id gnat_param;
4093         enum inline_status_t inline_status
4094           = Has_Pragma_No_Inline (gnat_entity)
4095             ? is_suppressed
4096             : Has_Pragma_Inline_Always (gnat_entity)
4097               ? is_required
4098               : (Is_Inlined (gnat_entity) ? is_enabled : is_disabled);
4099         bool public_flag = Is_Public (gnat_entity) || imported_p;
4100         /* Subprograms marked both Intrinsic and Always_Inline need not
4101            have a body of their own.  */
4102         bool extern_flag
4103           = ((Is_Public (gnat_entity) && !definition)
4104              || imported_p
4105              || (Convention (gnat_entity) == Convention_Intrinsic
4106                  && Has_Pragma_Inline_Always (gnat_entity)));
4107         bool artificial_flag = !Comes_From_Source (gnat_entity);
4108        /* The semantics of "pure" in Ada essentially matches that of "const"
4109           in the back-end.  In particular, both properties are orthogonal to
4110           the "nothrow" property if the EH circuitry is explicit in the
4111           internal representation of the back-end.  If we are to completely
4112           hide the EH circuitry from it, we need to declare that calls to pure
4113           Ada subprograms that can throw have side effects since they can
4114           trigger an "abnormal" transfer of control flow; thus they can be
4115           neither "const" nor "pure" in the back-end sense.  */
4116         bool const_flag
4117           = (Exception_Mechanism == Back_End_Exceptions
4118              && Is_Pure (gnat_entity));
4119         bool noreturn_flag = No_Return (gnat_entity);
4120         bool return_by_direct_ref_p = false;
4121         bool return_by_invisi_ref_p = false;
4122         bool return_unconstrained_p = false;
4123         int parmnum;
4124
4125         /* A parameter may refer to this type, so defer completion of any
4126            incomplete types.  */
4127         if (kind == E_Subprogram_Type && !definition)
4128           {
4129             defer_incomplete_level++;
4130             this_deferred = true;
4131           }
4132
4133         /* If the subprogram has an alias, it is probably inherited, so
4134            we can use the original one.  If the original "subprogram"
4135            is actually an enumeration literal, it may be the first use
4136            of its type, so we must elaborate that type now.  */
4137         if (Present (Alias (gnat_entity)))
4138           {
4139             if (Ekind (Alias (gnat_entity)) == E_Enumeration_Literal)
4140               gnat_to_gnu_entity (Etype (Alias (gnat_entity)), NULL_TREE, 0);
4141
4142             gnu_decl = gnat_to_gnu_entity (Alias (gnat_entity), gnu_expr, 0);
4143
4144             /* Elaborate any Itypes in the parameters of this entity.  */
4145             for (gnat_temp = First_Formal_With_Extras (gnat_entity);
4146                  Present (gnat_temp);
4147                  gnat_temp = Next_Formal_With_Extras (gnat_temp))
4148               if (Is_Itype (Etype (gnat_temp)))
4149                 gnat_to_gnu_entity (Etype (gnat_temp), NULL_TREE, 0);
4150
4151             break;
4152           }
4153
4154         /* If this subprogram is expectedly bound to a GCC builtin, fetch the
4155            corresponding DECL node.  Proper generation of calls later on need
4156            proper parameter associations so we don't "break;" here.  */
4157         if (Convention (gnat_entity) == Convention_Intrinsic
4158             && Present (Interface_Name (gnat_entity)))
4159           {
4160             gnu_builtin_decl = builtin_decl_for (gnu_ext_name);
4161
4162             /* Inability to find the builtin decl most often indicates a
4163                genuine mistake, but imports of unregistered intrinsics are
4164                sometimes issued on purpose to allow hooking in alternate
4165                bodies.  We post a warning conditioned on Wshadow in this case,
4166                to let developers be notified on demand without risking false
4167                positives with common default sets of options.  */
4168
4169             if (gnu_builtin_decl == NULL_TREE && warn_shadow)
4170               post_error ("?gcc intrinsic not found for&!", gnat_entity);
4171           }
4172
4173         /* ??? What if we don't find the builtin node above ? warn ? err ?
4174            In the current state we neither warn nor err, and calls will just
4175            be handled as for regular subprograms.  */
4176
4177         /* Look into the return type and get its associated GCC tree.  If it
4178            is not void, compute various flags for the subprogram type.  */
4179         if (Ekind (gnat_return_type) == E_Void)
4180           gnu_return_type = void_type_node;
4181         else
4182           {
4183             /* Ada 2012 (AI05-0151): Incomplete types coming from a limited
4184                context may now appear in parameter and result profiles.  If
4185                we are only annotating types, break circularities here.  */
4186             if (type_annotate_only
4187                 && is_from_limited_with_of_main (gnat_return_type))
4188               gnu_return_type = void_type_node;
4189             else
4190               gnu_return_type = gnat_to_gnu_type (gnat_return_type);
4191
4192             /* If this function returns by reference, make the actual return
4193                type the pointer type and make a note of that.  */
4194             if (Returns_By_Ref (gnat_entity))
4195               {
4196                 gnu_return_type = build_reference_type (gnu_return_type);
4197                 return_by_direct_ref_p = true;
4198               }
4199
4200             /* If the return type is an unconstrained array type, the return
4201                value will be allocated on the secondary stack so the actual
4202                return type is the fat pointer type.  */
4203             else if (TREE_CODE (gnu_return_type) == UNCONSTRAINED_ARRAY_TYPE)
4204               {
4205                 gnu_return_type = TREE_TYPE (gnu_return_type);
4206                 return_unconstrained_p = true;
4207               }
4208
4209             /* Likewise, if the return type requires a transient scope, the
4210                return value will also be allocated on the secondary stack so
4211                the actual return type is the pointer type.  */
4212             else if (Requires_Transient_Scope (gnat_return_type))
4213               {
4214                 gnu_return_type = build_reference_type (gnu_return_type);
4215                 return_unconstrained_p = true;
4216               }
4217
4218             /* If the Mechanism is By_Reference, ensure this function uses the
4219                target's by-invisible-reference mechanism, which may not be the
4220                same as above (e.g. it might be passing an extra parameter).  */
4221             else if (kind == E_Function
4222                      && Mechanism (gnat_entity) == By_Reference)
4223               return_by_invisi_ref_p = true;
4224
4225             /* Likewise, if the return type is itself By_Reference.  */
4226             else if (TYPE_IS_BY_REFERENCE_P (gnu_return_type))
4227               return_by_invisi_ref_p = true;
4228
4229             /* If the type is a padded type and the underlying type would not
4230                be passed by reference or the function has a foreign convention,
4231                return the underlying type.  */
4232             else if (TYPE_IS_PADDING_P (gnu_return_type)
4233                      && (!default_pass_by_ref
4234                           (TREE_TYPE (TYPE_FIELDS (gnu_return_type)))
4235                          || Has_Foreign_Convention (gnat_entity)))
4236               gnu_return_type = TREE_TYPE (TYPE_FIELDS (gnu_return_type));
4237
4238             /* If the return type is unconstrained, that means it must have a
4239                maximum size.  Use the padded type as the effective return type.
4240                And ensure the function uses the target's by-invisible-reference
4241                mechanism to avoid copying too much data when it returns.  */
4242             if (CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_return_type)))
4243               {
4244                 tree orig_type = gnu_return_type;
4245
4246                 gnu_return_type
4247                   = maybe_pad_type (gnu_return_type,
4248                                     max_size (TYPE_SIZE (gnu_return_type),
4249                                               true),
4250                                     0, gnat_entity, false, false, definition,
4251                                     true);
4252
4253                 /* Declare it now since it will never be declared otherwise.
4254                    This is necessary to ensure that its subtrees are properly
4255                    marked.  */
4256                 if (gnu_return_type != orig_type
4257                     && !DECL_P (TYPE_NAME (gnu_return_type)))
4258                   create_type_decl (TYPE_NAME (gnu_return_type),
4259                                     gnu_return_type, true, debug_info_p,
4260                                     gnat_entity);
4261
4262                 return_by_invisi_ref_p = true;
4263               }
4264
4265             /* If the return type has a size that overflows, we cannot have
4266                a function that returns that type.  This usage doesn't make
4267                sense anyway, so give an error here.  */
4268             if (!return_by_invisi_ref_p
4269                 && TYPE_SIZE_UNIT (gnu_return_type)
4270                 && TREE_CODE (TYPE_SIZE_UNIT (gnu_return_type)) == INTEGER_CST
4271                 && !valid_constant_size_p (TYPE_SIZE_UNIT (gnu_return_type)))
4272               {
4273                 post_error ("cannot return type whose size overflows",
4274                             gnat_entity);
4275                 gnu_return_type = copy_node (gnu_return_type);
4276                 TYPE_SIZE (gnu_return_type) = bitsize_zero_node;
4277                 TYPE_SIZE_UNIT (gnu_return_type) = size_zero_node;
4278                 TYPE_MAIN_VARIANT (gnu_return_type) = gnu_return_type;
4279                 TYPE_NEXT_VARIANT (gnu_return_type) = NULL_TREE;
4280               }
4281           }
4282
4283         /* Loop over the parameters and get their associated GCC tree.  While
4284            doing this, build a copy-in copy-out structure if we need one.  */
4285         for (gnat_param = First_Formal_With_Extras (gnat_entity), parmnum = 0;
4286              Present (gnat_param);
4287              gnat_param = Next_Formal_With_Extras (gnat_param), parmnum++)
4288           {
4289             Entity_Id gnat_param_type = Etype (gnat_param);
4290             tree gnu_param_name = get_entity_name (gnat_param);
4291             tree gnu_param_type, gnu_param, gnu_field;
4292             Mechanism_Type mech = Mechanism (gnat_param);
4293             bool copy_in_copy_out = false, fake_param_type;
4294
4295             /* Ada 2012 (AI05-0151): Incomplete types coming from a limited
4296                context may now appear in parameter and result profiles.  If
4297                we are only annotating types, break circularities here.  */
4298             if (type_annotate_only
4299                 && is_from_limited_with_of_main (gnat_param_type))
4300               {
4301                 gnu_param_type = void_type_node;
4302                 fake_param_type = true;
4303               }
4304             else
4305               {
4306                 gnu_param_type = gnat_to_gnu_type (gnat_param_type);
4307                 fake_param_type = false;
4308               }
4309
4310             /* Builtins are expanded inline and there is no real call sequence
4311                involved.  So the type expected by the underlying expander is
4312                always the type of each argument "as is".  */
4313             if (gnu_builtin_decl)
4314               mech = By_Copy;
4315             /* Handle the first parameter of a valued procedure specially.  */
4316             else if (Is_Valued_Procedure (gnat_entity) && parmnum == 0)
4317               mech = By_Copy_Return;
4318             /* Otherwise, see if a Mechanism was supplied that forced this
4319                parameter to be passed one way or another.  */
4320             else if (mech == Default
4321                      || mech == By_Copy
4322                      || mech == By_Reference)
4323               ;
4324             else if (mech > 0)
4325               {
4326                 if (TREE_CODE (gnu_param_type) == UNCONSTRAINED_ARRAY_TYPE
4327                     || TREE_CODE (TYPE_SIZE (gnu_param_type)) != INTEGER_CST
4328                     || 0 < compare_tree_int (TYPE_SIZE (gnu_param_type),
4329                                              mech))
4330                   mech = By_Reference;
4331                 else
4332                   mech = By_Copy;
4333               }
4334             else
4335               {
4336                 post_error ("unsupported mechanism for&", gnat_param);
4337                 mech = Default;
4338               }
4339
4340             /* Do not call gnat_to_gnu_param for a fake parameter type since
4341                it will try to use the real type again.  */
4342             if (fake_param_type)
4343               {
4344                 if (Ekind (gnat_param) == E_Out_Parameter)
4345                   gnu_param = NULL_TREE;
4346                 else
4347                   {
4348                     gnu_param
4349                       = create_param_decl (gnu_param_name, gnu_param_type,
4350                                            false);
4351                     Set_Mechanism (gnat_param,
4352                                    mech == Default ? By_Copy : mech);
4353                     if (Ekind (gnat_param) == E_In_Out_Parameter)
4354                       copy_in_copy_out = true;
4355                   }
4356               }
4357             else
4358               gnu_param
4359                 = gnat_to_gnu_param (gnat_param, mech, gnat_entity,
4360                                      Has_Foreign_Convention (gnat_entity),
4361                                      &copy_in_copy_out);
4362
4363             /* We are returned either a PARM_DECL or a type if no parameter
4364                needs to be passed; in either case, adjust the type.  */
4365             if (DECL_P (gnu_param))
4366               gnu_param_type = TREE_TYPE (gnu_param);
4367             else
4368               {
4369                 gnu_param_type = gnu_param;
4370                 gnu_param = NULL_TREE;
4371               }
4372
4373             /* The failure of this assertion will very likely come from an
4374                order of elaboration issue for the type of the parameter.  */
4375             gcc_assert (kind == E_Subprogram_Type
4376                         || !TYPE_IS_DUMMY_P (gnu_param_type)
4377                         || type_annotate_only);
4378
4379             if (gnu_param)
4380               {
4381                 gnu_param_list = chainon (gnu_param, gnu_param_list);
4382                 Sloc_to_locus (Sloc (gnat_param),
4383                                &DECL_SOURCE_LOCATION (gnu_param));
4384                 save_gnu_tree (gnat_param, gnu_param, false);
4385
4386                 /* If a parameter is a pointer, this function may modify
4387                    memory through it and thus shouldn't be considered
4388                    a const function.  Also, the memory may be modified
4389                    between two calls, so they can't be CSE'ed.  The latter
4390                    case also handles by-ref parameters.  */
4391                 if (POINTER_TYPE_P (gnu_param_type)
4392                     || TYPE_IS_FAT_POINTER_P (gnu_param_type))
4393                   const_flag = false;
4394               }
4395
4396             if (copy_in_copy_out)
4397               {
4398                 if (!gnu_cico_list)
4399                   {
4400                     tree gnu_new_ret_type = make_node (RECORD_TYPE);
4401
4402                     /* If this is a function, we also need a field for the
4403                        return value to be placed.  */
4404                     if (TREE_CODE (gnu_return_type) != VOID_TYPE)
4405                       {
4406                         gnu_field
4407                           = create_field_decl (get_identifier ("RETVAL"),
4408                                                gnu_return_type,
4409                                                gnu_new_ret_type, NULL_TREE,
4410                                                NULL_TREE, 0, 0);
4411                         Sloc_to_locus (Sloc (gnat_entity),
4412                                        &DECL_SOURCE_LOCATION (gnu_field));
4413                         gnu_field_list = gnu_field;
4414                         gnu_cico_list
4415                           = tree_cons (gnu_field, void_type_node, NULL_TREE);
4416                       }
4417
4418                     gnu_return_type = gnu_new_ret_type;
4419                     TYPE_NAME (gnu_return_type) = get_identifier ("RETURN");
4420                     /* Set a default alignment to speed up accesses.  But we
4421                        shouldn't increase the size of the structure too much,
4422                        lest it doesn't fit in return registers anymore.  */
4423                     TYPE_ALIGN (gnu_return_type)
4424                       = get_mode_alignment (ptr_mode);
4425                   }
4426
4427                 gnu_field
4428                   = create_field_decl (gnu_param_name, gnu_param_type,
4429                                        gnu_return_type, NULL_TREE, NULL_TREE,
4430                                        0, 0);
4431                 Sloc_to_locus (Sloc (gnat_param),
4432                                &DECL_SOURCE_LOCATION (gnu_field));
4433                 DECL_CHAIN (gnu_field) = gnu_field_list;
4434                 gnu_field_list = gnu_field;
4435                 gnu_cico_list
4436                   = tree_cons (gnu_field, gnu_param, gnu_cico_list);
4437               }
4438           }
4439
4440         if (gnu_cico_list)
4441           {
4442             /* If we have a CICO list but it has only one entry, we convert
4443                this function into a function that returns this object.  */
4444             if (list_length (gnu_cico_list) == 1)
4445               gnu_return_type = TREE_TYPE (TREE_PURPOSE (gnu_cico_list));
4446
4447             /* Do not finalize the return type if the subprogram is stubbed
4448                since structures are incomplete for the back-end.  */
4449             else if (Convention (gnat_entity) != Convention_Stubbed)
4450               {
4451                 finish_record_type (gnu_return_type, nreverse (gnu_field_list),
4452                                     0, false);
4453
4454                 /* Try to promote the mode of the return type if it is passed
4455                    in registers, again to speed up accesses.  */
4456                 if (TYPE_MODE (gnu_return_type) == BLKmode
4457                     && !targetm.calls.return_in_memory (gnu_return_type,
4458                                                         NULL_TREE))
4459                   {
4460                     unsigned int size
4461                       = TREE_INT_CST_LOW (TYPE_SIZE (gnu_return_type));
4462                     unsigned int i = BITS_PER_UNIT;
4463                     machine_mode mode;
4464
4465                     while (i < size)
4466                       i <<= 1;
4467                     mode = mode_for_size (i, MODE_INT, 0);
4468                     if (mode != BLKmode)
4469                       {
4470                         SET_TYPE_MODE (gnu_return_type, mode);
4471                         TYPE_ALIGN (gnu_return_type)
4472                           = GET_MODE_ALIGNMENT (mode);
4473                         TYPE_SIZE (gnu_return_type)
4474                           = bitsize_int (GET_MODE_BITSIZE (mode));
4475                         TYPE_SIZE_UNIT (gnu_return_type)
4476                           = size_int (GET_MODE_SIZE (mode));
4477                       }
4478                   }
4479
4480                 if (debug_info_p)
4481                   rest_of_record_type_compilation (gnu_return_type);
4482               }
4483           }
4484
4485         /* Deal with platform-specific calling conventions.  */
4486         if (Has_Stdcall_Convention (gnat_entity))
4487           prepend_one_attribute
4488             (&attr_list, ATTR_MACHINE_ATTRIBUTE,
4489              get_identifier ("stdcall"), NULL_TREE,
4490              gnat_entity);
4491         else if (Has_Thiscall_Convention (gnat_entity))
4492           prepend_one_attribute
4493             (&attr_list, ATTR_MACHINE_ATTRIBUTE,
4494              get_identifier ("thiscall"), NULL_TREE,
4495              gnat_entity);
4496
4497         /* If we should request stack realignment for a foreign convention
4498            subprogram, do so.  Note that this applies to task entry points
4499            in particular.  */
4500         if (FOREIGN_FORCE_REALIGN_STACK
4501             && Has_Foreign_Convention (gnat_entity))
4502           prepend_one_attribute
4503             (&attr_list, ATTR_MACHINE_ATTRIBUTE,
4504              get_identifier ("force_align_arg_pointer"), NULL_TREE,
4505              gnat_entity);
4506
4507         /* Deal with a pragma Linker_Section on a subprogram.  */
4508         if ((kind == E_Function || kind == E_Procedure)
4509             && Present (Linker_Section_Pragma (gnat_entity)))
4510           prepend_one_attribute_pragma (&attr_list,
4511                                         Linker_Section_Pragma (gnat_entity));
4512
4513         /* The lists have been built in reverse.  */
4514         gnu_param_list = nreverse (gnu_param_list);
4515         gnu_cico_list = nreverse (gnu_cico_list);
4516
4517         if (kind == E_Function)
4518           Set_Mechanism (gnat_entity, return_unconstrained_p
4519                                       || return_by_direct_ref_p
4520                                       || return_by_invisi_ref_p
4521                                       ? By_Reference : By_Copy);
4522         gnu_type
4523           = create_subprog_type (gnu_return_type, gnu_param_list,
4524                                  gnu_cico_list, return_unconstrained_p,
4525                                  return_by_direct_ref_p,
4526                                  return_by_invisi_ref_p);
4527
4528         /* A procedure (something that doesn't return anything) shouldn't be
4529            considered const since there would be no reason for calling such a
4530            subprogram.  Note that procedures with Out (or In Out) parameters
4531            have already been converted into a function with a return type.
4532            Similarly, if the function returns an unconstrained type, then the
4533            function will allocate the return value on the secondary stack and
4534            thus calls to it cannot be CSE'ed, lest the stack be reclaimed.  */
4535         if (TREE_CODE (gnu_return_type) == VOID_TYPE || return_unconstrained_p)
4536           const_flag = false;
4537
4538         if (const_flag || noreturn_flag)
4539           {
4540             const int quals
4541               = (const_flag ? TYPE_QUAL_CONST : 0)
4542                 | (noreturn_flag ? TYPE_QUAL_VOLATILE : 0);
4543             gnu_type = change_qualified_type (gnu_type, quals);
4544           }
4545
4546         /* If we have a builtin decl for that function, use it.  Check if the
4547            profiles are compatible and warn if they are not.  The checker is
4548            expected to post extra diagnostics in this case.  */
4549         if (gnu_builtin_decl)
4550           {
4551             intrin_binding_t inb;
4552
4553             inb.gnat_entity = gnat_entity;
4554             inb.ada_fntype = gnu_type;
4555             inb.btin_fntype = TREE_TYPE (gnu_builtin_decl);
4556
4557             if (!intrin_profiles_compatible_p (&inb))
4558               post_error
4559                 ("?profile of& doesn''t match the builtin it binds!",
4560                  gnat_entity);
4561
4562             gnu_decl = gnu_builtin_decl;
4563             gnu_type = TREE_TYPE (gnu_builtin_decl);
4564             break;
4565           }
4566
4567         /* If there was no specified Interface_Name and the external and
4568            internal names of the subprogram are the same, only use the
4569            internal name to allow disambiguation of nested subprograms.  */
4570         if (No (Interface_Name (gnat_entity))
4571             && gnu_ext_name == gnu_entity_name)
4572           gnu_ext_name = NULL_TREE;
4573
4574         /* If we are defining the subprogram and it has an Address clause
4575            we must get the address expression from the saved GCC tree for the
4576            subprogram if it has a Freeze_Node.  Otherwise, we elaborate
4577            the address expression here since the front-end has guaranteed
4578            in that case that the elaboration has no effects.  If there is
4579            an Address clause and we are not defining the object, just
4580            make it a constant.  */
4581         if (Present (Address_Clause (gnat_entity)))
4582           {
4583             tree gnu_address = NULL_TREE;
4584
4585             if (definition)
4586               gnu_address
4587                 = (present_gnu_tree (gnat_entity)
4588                    ? get_gnu_tree (gnat_entity)
4589                    : gnat_to_gnu (Expression (Address_Clause (gnat_entity))));
4590
4591             save_gnu_tree (gnat_entity, NULL_TREE, false);
4592
4593             /* Convert the type of the object to a reference type that can
4594                alias everything as per 13.3(19).  */
4595             gnu_type
4596               = build_reference_type_for_mode (gnu_type, ptr_mode, true);
4597             if (gnu_address)
4598               gnu_address = convert (gnu_type, gnu_address);
4599
4600             gnu_decl
4601               = create_var_decl (gnu_entity_name, gnu_ext_name, gnu_type,
4602                                  gnu_address, false, Is_Public (gnat_entity),
4603                                  extern_flag, false, NULL, gnat_entity);
4604             DECL_BY_REF_P (gnu_decl) = 1;
4605           }
4606
4607         else if (kind == E_Subprogram_Type)
4608           {
4609             process_attributes (&gnu_type, &attr_list, false, gnat_entity);
4610             gnu_decl
4611               = create_type_decl (gnu_entity_name, gnu_type, artificial_flag,
4612                                   debug_info_p, gnat_entity);
4613           }
4614         else
4615           {
4616             gnu_decl
4617               = create_subprog_decl (gnu_entity_name, gnu_ext_name, gnu_type,
4618                                      gnu_param_list, inline_status,
4619                                      public_flag, extern_flag, artificial_flag,
4620                                      attr_list, gnat_entity);
4621             /* This is unrelated to the stub built right above.  */
4622             DECL_STUBBED_P (gnu_decl)
4623               = Convention (gnat_entity) == Convention_Stubbed;
4624           }
4625       }
4626       break;
4627
4628     case E_Incomplete_Type:
4629     case E_Incomplete_Subtype:
4630     case E_Private_Type:
4631     case E_Private_Subtype:
4632     case E_Limited_Private_Type:
4633     case E_Limited_Private_Subtype:
4634     case E_Record_Type_With_Private:
4635     case E_Record_Subtype_With_Private:
4636       {
4637         bool is_from_limited_with
4638           = (IN (kind, Incomplete_Kind) && From_Limited_With (gnat_entity));
4639         /* Get the "full view" of this entity.  If this is an incomplete
4640            entity from a limited with, treat its non-limited view as the
4641            full view.  Otherwise, use either the full view or the underlying
4642            full view, whichever is present.  This is used in all the tests
4643            below.  */
4644         Entity_Id full_view
4645           = is_from_limited_with
4646             ? Non_Limited_View (gnat_entity)
4647             : Present (Full_View (gnat_entity))
4648               ? Full_View (gnat_entity)
4649               : IN (kind, Private_Kind)
4650                 ? Underlying_Full_View (gnat_entity)
4651                 : Empty;
4652
4653         /* If this is an incomplete type with no full view, it must be a Taft
4654            Amendment type, in which case we return a dummy type.  Otherwise,
4655            just get the type from its Etype.  */
4656         if (No (full_view))
4657           {
4658             if (kind == E_Incomplete_Type)
4659               {
4660                 gnu_type = make_dummy_type (gnat_entity);
4661                 gnu_decl = TYPE_STUB_DECL (gnu_type);
4662               }
4663             else
4664               {
4665                 gnu_decl = gnat_to_gnu_entity (Etype (gnat_entity),
4666                                                NULL_TREE, 0);
4667                 maybe_present = true;
4668               }
4669             break;
4670           }
4671
4672         /* If we already made a type for the full view, reuse it.  */
4673         else if (present_gnu_tree (full_view))
4674           {
4675             gnu_decl = get_gnu_tree (full_view);
4676             break;
4677           }
4678
4679         /* Otherwise, if we are not defining the type now, get the type
4680            from the full view.  But always get the type from the full view
4681            for define on use types, since otherwise we won't see them.
4682            Likewise if this is a non-limited view not declared in the main
4683            unit, which can happen for incomplete formal types instantiated
4684            on a type coming from a limited_with clause.  */
4685         else if (!definition
4686                  || (Is_Itype (full_view) && No (Freeze_Node (gnat_entity)))
4687                  || (Is_Itype (gnat_entity) && No (Freeze_Node (full_view)))
4688                  || (is_from_limited_with
4689                      && !In_Extended_Main_Code_Unit (full_view)))
4690           {
4691             gnu_decl = gnat_to_gnu_entity (full_view, NULL_TREE, 0);
4692             maybe_present = true;
4693             break;
4694           }
4695
4696         /* For incomplete types, make a dummy type entry which will be
4697            replaced later.  Save it as the full declaration's type so
4698            we can do any needed updates when we see it.  */
4699         gnu_type = make_dummy_type (gnat_entity);
4700         gnu_decl = TYPE_STUB_DECL (gnu_type);
4701         if (Has_Completion_In_Body (gnat_entity))
4702           DECL_TAFT_TYPE_P (gnu_decl) = 1;
4703         save_gnu_tree (full_view, gnu_decl, 0);
4704         break;
4705       }
4706
4707     case E_Class_Wide_Type:
4708       /* Class-wide types are always transformed into their root type.  */
4709       gnu_decl = gnat_to_gnu_entity (gnat_equiv_type, NULL_TREE, 0);
4710       maybe_present = true;
4711       break;
4712
4713     case E_Task_Type:
4714     case E_Task_Subtype:
4715     case E_Protected_Type:
4716     case E_Protected_Subtype:
4717       /* Concurrent types are always transformed into their record type.  */
4718       if (type_annotate_only && No (gnat_equiv_type))
4719         gnu_type = void_type_node;
4720       else
4721         gnu_decl = gnat_to_gnu_entity (gnat_equiv_type, NULL_TREE, 0);
4722       maybe_present = true;
4723       break;
4724
4725     case E_Label:
4726       gnu_decl = create_label_decl (gnu_entity_name, gnat_entity);
4727       break;
4728
4729     case E_Block:
4730     case E_Loop:
4731       /* Nothing at all to do here, so just return an ERROR_MARK and claim
4732          we've already saved it, so we don't try to.  */
4733       gnu_decl = error_mark_node;
4734       saved = true;
4735       break;
4736
4737     case E_Abstract_State:
4738       /* This is a SPARK annotation that only reaches here when compiling in
4739          ASIS mode.  */
4740       gcc_assert (type_annotate_only);
4741       gnu_decl = error_mark_node;
4742       saved = true;
4743       break;
4744
4745     default:
4746       gcc_unreachable ();
4747     }
4748
4749   /* If we had a case where we evaluated another type and it might have
4750      defined this one, handle it here.  */
4751   if (maybe_present && present_gnu_tree (gnat_entity))
4752     {
4753       gnu_decl = get_gnu_tree (gnat_entity);
4754       saved = true;
4755     }
4756
4757   /* If we are processing a type and there is either no decl for it or
4758      we just made one, do some common processing for the type, such as
4759      handling alignment and possible padding.  */
4760   if (is_type && (!gnu_decl || this_made_decl))
4761     {
4762       /* Process the attributes, if not already done.  Note that the type is
4763          already defined so we cannot pass true for IN_PLACE here.  */
4764       process_attributes (&gnu_type, &attr_list, false, gnat_entity);
4765
4766       /* Tell the middle-end that objects of tagged types are guaranteed to
4767          be properly aligned.  This is necessary because conversions to the
4768          class-wide type are translated into conversions to the root type,
4769          which can be less aligned than some of its derived types.  */
4770       if (Is_Tagged_Type (gnat_entity)
4771           || Is_Class_Wide_Equivalent_Type (gnat_entity))
4772         TYPE_ALIGN_OK (gnu_type) = 1;
4773
4774       /* Record whether the type is passed by reference.  */
4775       if (!VOID_TYPE_P (gnu_type) && Is_By_Reference_Type (gnat_entity))
4776         TYPE_BY_REFERENCE_P (gnu_type) = 1;
4777
4778       /* ??? Don't set the size for a String_Literal since it is either
4779          confirming or we don't handle it properly (if the low bound is
4780          non-constant).  */
4781       if (!gnu_size && kind != E_String_Literal_Subtype)
4782         {
4783           Uint gnat_size = Known_Esize (gnat_entity)
4784                            ? Esize (gnat_entity) : RM_Size (gnat_entity);
4785           gnu_size
4786             = validate_size (gnat_size, gnu_type, gnat_entity, TYPE_DECL,
4787                              false, Has_Size_Clause (gnat_entity));
4788         }
4789
4790       /* If a size was specified, see if we can make a new type of that size
4791          by rearranging the type, for example from a fat to a thin pointer.  */
4792       if (gnu_size)
4793         {
4794           gnu_type
4795             = make_type_from_size (gnu_type, gnu_size,
4796                                    Has_Biased_Representation (gnat_entity));
4797
4798           if (operand_equal_p (TYPE_SIZE (gnu_type), gnu_size, 0)
4799               && operand_equal_p (rm_size (gnu_type), gnu_size, 0))
4800             gnu_size = NULL_TREE;
4801         }
4802
4803       /* If the alignment has not already been processed and this is not
4804          an unconstrained array type, see if an alignment is specified.
4805          If not, we pick a default alignment for atomic objects.  */
4806       if (align != 0 || TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE)
4807         ;
4808       else if (Known_Alignment (gnat_entity))
4809         {
4810           align = validate_alignment (Alignment (gnat_entity), gnat_entity,
4811                                       TYPE_ALIGN (gnu_type));
4812
4813           /* Warn on suspiciously large alignments.  This should catch
4814              errors about the (alignment,byte)/(size,bit) discrepancy.  */
4815           if (align > BIGGEST_ALIGNMENT && Has_Alignment_Clause (gnat_entity))
4816             {
4817               tree size;
4818
4819               /* If a size was specified, take it into account.  Otherwise
4820                  use the RM size for records or unions as the type size has
4821                  already been adjusted to the alignment.  */
4822               if (gnu_size)
4823                 size = gnu_size;
4824               else if (RECORD_OR_UNION_TYPE_P (gnu_type)
4825                        && !TYPE_FAT_POINTER_P (gnu_type))
4826                 size = rm_size (gnu_type);
4827               else
4828                 size = TYPE_SIZE (gnu_type);
4829
4830               /* Consider an alignment as suspicious if the alignment/size
4831                  ratio is greater or equal to the byte/bit ratio.  */
4832               if (tree_fits_uhwi_p (size)
4833                   && align >= tree_to_uhwi (size) * BITS_PER_UNIT)
4834                 post_error_ne ("?suspiciously large alignment specified for&",
4835                                Expression (Alignment_Clause (gnat_entity)),
4836                                gnat_entity);
4837             }
4838         }
4839       else if (Is_Atomic_Or_VFA (gnat_entity) && !gnu_size
4840                && tree_fits_uhwi_p (TYPE_SIZE (gnu_type))
4841                && integer_pow2p (TYPE_SIZE (gnu_type)))
4842         align = MIN (BIGGEST_ALIGNMENT,
4843                      tree_to_uhwi (TYPE_SIZE (gnu_type)));
4844       else if (Is_Atomic_Or_VFA (gnat_entity) && gnu_size
4845                && tree_fits_uhwi_p (gnu_size)
4846                && integer_pow2p (gnu_size))
4847         align = MIN (BIGGEST_ALIGNMENT, tree_to_uhwi (gnu_size));
4848
4849       /* See if we need to pad the type.  If we did, and made a record,
4850          the name of the new type may be changed.  So get it back for
4851          us when we make the new TYPE_DECL below.  */
4852       if (gnu_size || align > 0)
4853         gnu_type = maybe_pad_type (gnu_type, gnu_size, align, gnat_entity,
4854                                    false, !gnu_decl, definition, false);
4855
4856       if (TYPE_IS_PADDING_P (gnu_type))
4857         gnu_entity_name = TYPE_IDENTIFIER (gnu_type);
4858
4859       /* Now set the RM size of the type.  We cannot do it before padding
4860          because we need to accept arbitrary RM sizes on integral types.  */
4861       set_rm_size (RM_Size (gnat_entity), gnu_type, gnat_entity);
4862
4863       /* If we are at global level, GCC will have applied variable_size to
4864          the type, but that won't have done anything.  So, if it's not
4865          a constant or self-referential, call elaborate_expression_1 to
4866          make a variable for the size rather than calculating it each time.
4867          Handle both the RM size and the actual size.  */
4868       if (global_bindings_p ()
4869           && TYPE_SIZE (gnu_type)
4870           && !TREE_CONSTANT (TYPE_SIZE (gnu_type))
4871           && !CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_type)))
4872         {
4873           tree size = TYPE_SIZE (gnu_type);
4874
4875           TYPE_SIZE (gnu_type)
4876             = elaborate_expression_1 (size, gnat_entity, "SIZE", definition,
4877                                       false);
4878
4879           /* ??? For now, store the size as a multiple of the alignment in
4880              bytes so that we can see the alignment from the tree.  */
4881           TYPE_SIZE_UNIT (gnu_type)
4882             = elaborate_expression_2 (TYPE_SIZE_UNIT (gnu_type), gnat_entity,
4883                                       "SIZE_A_UNIT", definition, false,
4884                                       TYPE_ALIGN (gnu_type));
4885
4886           /* ??? gnu_type may come from an existing type so the MULT_EXPR node
4887              may not be marked by the call to create_type_decl below.  */
4888           MARK_VISITED (TYPE_SIZE_UNIT (gnu_type));
4889
4890           if (TREE_CODE (gnu_type) == RECORD_TYPE)
4891             {
4892               tree variant_part = get_variant_part (gnu_type);
4893               tree ada_size = TYPE_ADA_SIZE (gnu_type);
4894
4895               if (variant_part)
4896                 {
4897                   tree union_type = TREE_TYPE (variant_part);
4898                   tree offset = DECL_FIELD_OFFSET (variant_part);
4899
4900                   /* If the position of the variant part is constant, subtract
4901                      it from the size of the type of the parent to get the new
4902                      size.  This manual CSE reduces the data size.  */
4903                   if (TREE_CODE (offset) == INTEGER_CST)
4904                     {
4905                       tree bitpos = DECL_FIELD_BIT_OFFSET (variant_part);
4906                       TYPE_SIZE (union_type)
4907                         = size_binop (MINUS_EXPR, TYPE_SIZE (gnu_type),
4908                                       bit_from_pos (offset, bitpos));
4909                       TYPE_SIZE_UNIT (union_type)
4910                         = size_binop (MINUS_EXPR, TYPE_SIZE_UNIT (gnu_type),
4911                                       byte_from_pos (offset, bitpos));
4912                     }
4913                   else
4914                     {
4915                       TYPE_SIZE (union_type)
4916                         = elaborate_expression_1 (TYPE_SIZE (union_type),
4917                                                   gnat_entity, "VSIZE",
4918                                                   definition, false);
4919
4920                       /* ??? For now, store the size as a multiple of the
4921                          alignment in bytes so that we can see the alignment
4922                          from the tree.  */
4923                       TYPE_SIZE_UNIT (union_type)
4924                         = elaborate_expression_2 (TYPE_SIZE_UNIT (union_type),
4925                                                   gnat_entity, "VSIZE_A_UNIT",
4926                                                   definition, false,
4927                                                   TYPE_ALIGN (union_type));
4928
4929                       /* ??? For now, store the offset as a multiple of the
4930                          alignment in bytes so that we can see the alignment
4931                          from the tree.  */
4932                       DECL_FIELD_OFFSET (variant_part)
4933                         = elaborate_expression_2 (offset, gnat_entity,
4934                                                   "VOFFSET", definition, false,
4935                                                   DECL_OFFSET_ALIGN
4936                                                   (variant_part));
4937                     }
4938
4939                   DECL_SIZE (variant_part) = TYPE_SIZE (union_type);
4940                   DECL_SIZE_UNIT (variant_part) = TYPE_SIZE_UNIT (union_type);
4941                 }
4942
4943               if (operand_equal_p (ada_size, size, 0))
4944                 ada_size = TYPE_SIZE (gnu_type);
4945               else
4946                 ada_size
4947                   = elaborate_expression_1 (ada_size, gnat_entity, "RM_SIZE",
4948                                             definition, false);
4949               SET_TYPE_ADA_SIZE (gnu_type, ada_size);
4950             }
4951         }
4952
4953       /* If this is a record type or subtype, call elaborate_expression_2 on
4954          any field position.  Do this for both global and local types.
4955          Skip any fields that we haven't made trees for to avoid problems with
4956          class wide types.  */
4957       if (IN (kind, Record_Kind))
4958         for (gnat_temp = First_Entity (gnat_entity); Present (gnat_temp);
4959              gnat_temp = Next_Entity (gnat_temp))
4960           if (Ekind (gnat_temp) == E_Component && present_gnu_tree (gnat_temp))
4961             {
4962               tree gnu_field = get_gnu_tree (gnat_temp);
4963
4964               /* ??? For now, store the offset as a multiple of the alignment
4965                  in bytes so that we can see the alignment from the tree.  */
4966               if (!CONTAINS_PLACEHOLDER_P (DECL_FIELD_OFFSET (gnu_field)))
4967                 {
4968                   DECL_FIELD_OFFSET (gnu_field)
4969                     = elaborate_expression_2 (DECL_FIELD_OFFSET (gnu_field),
4970                                               gnat_temp, "OFFSET", definition,
4971                                               false,
4972                                               DECL_OFFSET_ALIGN (gnu_field));
4973
4974                   /* ??? The context of gnu_field is not necessarily gnu_type
4975                      so the MULT_EXPR node built above may not be marked by
4976                      the call to create_type_decl below.  */
4977                   if (global_bindings_p ())
4978                     MARK_VISITED (DECL_FIELD_OFFSET (gnu_field));
4979                 }
4980             }
4981
4982       if (Is_Atomic_Or_VFA (gnat_entity))
4983         check_ok_for_atomic_type (gnu_type, gnat_entity, false);
4984
4985       /* If this is not an unconstrained array type, set some flags.  */
4986       if (TREE_CODE (gnu_type) != UNCONSTRAINED_ARRAY_TYPE)
4987         {
4988           if (Present (Alignment_Clause (gnat_entity)))
4989             TYPE_USER_ALIGN (gnu_type) = 1;
4990
4991           if (Universal_Aliasing (gnat_entity))
4992             TYPE_UNIVERSAL_ALIASING_P (gnu_type) = 1;
4993
4994           /* If it is passed by reference, force BLKmode to ensure that
4995              objects of this type will always be put in memory.  */
4996           if (TYPE_MODE (gnu_type) != BLKmode
4997               && AGGREGATE_TYPE_P (gnu_type)
4998               && TYPE_BY_REFERENCE_P (gnu_type))
4999             SET_TYPE_MODE (gnu_type, BLKmode);
5000
5001           if (Treat_As_Volatile (gnat_entity))
5002             {
5003               const int quals
5004                 = TYPE_QUAL_VOLATILE
5005                   | (Is_Atomic_Or_VFA (gnat_entity) ? TYPE_QUAL_ATOMIC : 0);
5006               gnu_type = change_qualified_type (gnu_type, quals);
5007             }
5008         }
5009
5010       if (!gnu_decl)
5011         gnu_decl = create_type_decl (gnu_entity_name, gnu_type,
5012                                      !Comes_From_Source (gnat_entity),
5013                                      debug_info_p, gnat_entity);
5014       else
5015         {
5016           TREE_TYPE (gnu_decl) = gnu_type;
5017           TYPE_STUB_DECL (gnu_type) = gnu_decl;
5018         }
5019     }
5020
5021   if (is_type && !TYPE_IS_DUMMY_P (TREE_TYPE (gnu_decl)))
5022     {
5023       gnu_type = TREE_TYPE (gnu_decl);
5024
5025       /* If this is a derived type, relate its alias set to that of its parent
5026          to avoid troubles when a call to an inherited primitive is inlined in
5027          a context where a derived object is accessed.  The inlined code works
5028          on the parent view so the resulting code may access the same object
5029          using both the parent and the derived alias sets, which thus have to
5030          conflict.  As the same issue arises with component references, the
5031          parent alias set also has to conflict with composite types enclosing
5032          derived components.  For instance, if we have:
5033
5034             type D is new T;
5035             type R is record
5036                Component : D;
5037             end record;
5038
5039          we want T to conflict with both D and R, in addition to R being a
5040          superset of D by record/component construction.
5041
5042          One way to achieve this is to perform an alias set copy from the
5043          parent to the derived type.  This is not quite appropriate, though,
5044          as we don't want separate derived types to conflict with each other:
5045
5046             type I1 is new Integer;
5047             type I2 is new Integer;
5048
5049          We want I1 and I2 to both conflict with Integer but we do not want
5050          I1 to conflict with I2, and an alias set copy on derivation would
5051          have that effect.
5052
5053          The option chosen is to make the alias set of the derived type a
5054          superset of that of its parent type.  It trivially fulfills the
5055          simple requirement for the Integer derivation example above, and
5056          the component case as well by superset transitivity:
5057
5058                    superset      superset
5059                 R ----------> D ----------> T
5060
5061          However, for composite types, conversions between derived types are
5062          translated into VIEW_CONVERT_EXPRs so a sequence like:
5063
5064             type Comp1 is new Comp;
5065             type Comp2 is new Comp;
5066             procedure Proc (C : Comp1);
5067
5068             C : Comp2;
5069             Proc (Comp1 (C));
5070
5071          is translated into:
5072
5073             C : Comp2;
5074             Proc ((Comp1 &) &VIEW_CONVERT_EXPR <Comp1> (C));
5075
5076          and gimplified into:
5077
5078             C : Comp2;
5079             Comp1 *C.0;
5080             C.0 = (Comp1 *) &C;
5081             Proc (C.0);
5082
5083          i.e. generates code involving type punning.  Therefore, Comp1 needs
5084          to conflict with Comp2 and an alias set copy is required.
5085
5086          The language rules ensure the parent type is already frozen here.  */
5087       if (kind != E_Subprogram_Type
5088           && Is_Derived_Type (gnat_entity)
5089           && !type_annotate_only)
5090         {
5091           Entity_Id gnat_parent_type = Underlying_Type (Etype (gnat_entity));
5092           /* For constrained packed array subtypes, the implementation type is
5093              used instead of the nominal type.  */
5094           if (kind == E_Array_Subtype
5095               && Is_Constrained (gnat_entity)
5096               && Present (Packed_Array_Impl_Type (gnat_parent_type)))
5097             gnat_parent_type = Packed_Array_Impl_Type (gnat_parent_type);
5098           relate_alias_sets (gnu_type, gnat_to_gnu_type (gnat_parent_type),
5099                              Is_Composite_Type (gnat_entity)
5100                              ? ALIAS_SET_COPY : ALIAS_SET_SUPERSET);
5101         }
5102
5103       /* Back-annotate the Alignment of the type if not already in the
5104          tree.  Likewise for sizes.  */
5105       if (Unknown_Alignment (gnat_entity))
5106         {
5107           unsigned int double_align, align;
5108           bool is_capped_double, align_clause;
5109
5110           /* If the default alignment of "double" or larger scalar types is
5111              specifically capped and this is not an array with an alignment
5112              clause on the component type, return the cap.  */
5113           if ((double_align = double_float_alignment) > 0)
5114             is_capped_double
5115               = is_double_float_or_array (gnat_entity, &align_clause);
5116           else if ((double_align = double_scalar_alignment) > 0)
5117             is_capped_double
5118               = is_double_scalar_or_array (gnat_entity, &align_clause);
5119           else
5120             is_capped_double = align_clause = false;
5121
5122           if (is_capped_double && !align_clause)
5123             align = double_align;
5124           else
5125             align = TYPE_ALIGN (gnu_type) / BITS_PER_UNIT;
5126
5127           Set_Alignment (gnat_entity, UI_From_Int (align));
5128         }
5129
5130       if (Unknown_Esize (gnat_entity) && TYPE_SIZE (gnu_type))
5131         {
5132           tree gnu_size = TYPE_SIZE (gnu_type);
5133
5134           /* If the size is self-referential, annotate the maximum value.  */
5135           if (CONTAINS_PLACEHOLDER_P (gnu_size))
5136             gnu_size = max_size (gnu_size, true);
5137
5138           /* If we are just annotating types and the type is tagged, the tag
5139              and the parent components are not generated by the front-end so
5140              sizes must be adjusted if there is no representation clause.  */
5141           if (type_annotate_only
5142               && Is_Tagged_Type (gnat_entity)
5143               && !VOID_TYPE_P (gnu_type)
5144               && (!TYPE_FIELDS (gnu_type)
5145                   || integer_zerop (bit_position (TYPE_FIELDS (gnu_type)))))
5146             {
5147               tree pointer_size = bitsize_int (POINTER_SIZE), offset;
5148               Uint uint_size;
5149
5150               if (Is_Derived_Type (gnat_entity))
5151                 {
5152                   Entity_Id gnat_parent = Etype (Base_Type (gnat_entity));
5153                   offset = UI_To_gnu (Esize (gnat_parent), bitsizetype);
5154                   Set_Alignment (gnat_entity, Alignment (gnat_parent));
5155                 }
5156               else
5157                 offset = pointer_size;
5158
5159               if (TYPE_FIELDS (gnu_type))
5160                 offset
5161                   = round_up (offset, DECL_ALIGN (TYPE_FIELDS (gnu_type)));
5162
5163               gnu_size = size_binop (PLUS_EXPR, gnu_size, offset);
5164               gnu_size = round_up (gnu_size, POINTER_SIZE);
5165               uint_size = annotate_value (gnu_size);
5166               Set_Esize (gnat_entity, uint_size);
5167               Set_RM_Size (gnat_entity, uint_size);
5168             }
5169           else
5170             Set_Esize (gnat_entity, annotate_value (gnu_size));
5171         }
5172
5173       if (Unknown_RM_Size (gnat_entity) && rm_size (gnu_type))
5174         Set_RM_Size (gnat_entity, annotate_value (rm_size (gnu_type)));
5175     }
5176
5177   /* If we really have a ..._DECL node, set a couple of flags on it.  But we
5178      cannot do so if we are reusing the ..._DECL node made for an equivalent
5179      type or an alias or a renamed object as the predicates don't apply to it
5180      but to GNAT_ENTITY.  */
5181   if (DECL_P (gnu_decl)
5182       && !(is_type && gnat_equiv_type != gnat_entity)
5183       && !Present (Alias (gnat_entity))
5184       && !(Present (Renamed_Object (gnat_entity)) && saved))
5185     {
5186       /* ??? DECL_ARTIFICIAL, and possibly DECL_IGNORED_P below, should
5187          be set before calling rest_of_decl_compilation above (through
5188          create_var_decl_1).  This is because rest_of_decl_compilation
5189          calls the debugging backend and will create a DIE without
5190          DW_AT_artificial.
5191
5192          This is currently causing gnat.dg/specs/debug1.ads to FAIL.  */
5193       if (!Comes_From_Source (gnat_entity))
5194         DECL_ARTIFICIAL (gnu_decl) = 1;
5195
5196       if (!debug_info_p)
5197         DECL_IGNORED_P (gnu_decl) = 1;
5198     }
5199
5200   /* If we haven't already, associate the ..._DECL node that we just made with
5201      the input GNAT entity node.  */
5202   if (!saved)
5203     save_gnu_tree (gnat_entity, gnu_decl, false);
5204
5205   /* Now we are sure gnat_entity has a corresponding ..._DECL node,
5206      eliminate as many deferred computations as possible.  */
5207   process_deferred_decl_context (false);
5208
5209   /* If this is an enumeration or floating-point type, we were not able to set
5210      the bounds since they refer to the type.  These are always static.  */
5211   if ((kind == E_Enumeration_Type && Present (First_Literal (gnat_entity)))
5212       || (kind == E_Floating_Point_Type))
5213     {
5214       tree gnu_scalar_type = gnu_type;
5215       tree gnu_low_bound, gnu_high_bound;
5216
5217       /* If this is a padded type, we need to use the underlying type.  */
5218       if (TYPE_IS_PADDING_P (gnu_scalar_type))
5219         gnu_scalar_type = TREE_TYPE (TYPE_FIELDS (gnu_scalar_type));
5220
5221       /* If this is a floating point type and we haven't set a floating
5222          point type yet, use this in the evaluation of the bounds.  */
5223       if (!longest_float_type_node && kind == E_Floating_Point_Type)
5224         longest_float_type_node = gnu_scalar_type;
5225
5226       gnu_low_bound = gnat_to_gnu (Type_Low_Bound (gnat_entity));
5227       gnu_high_bound = gnat_to_gnu (Type_High_Bound (gnat_entity));
5228
5229       if (kind == E_Enumeration_Type)
5230         {
5231           /* Enumeration types have specific RM bounds.  */
5232           SET_TYPE_RM_MIN_VALUE (gnu_scalar_type, gnu_low_bound);
5233           SET_TYPE_RM_MAX_VALUE (gnu_scalar_type, gnu_high_bound);
5234         }
5235       else
5236         {
5237           /* Floating-point types don't have specific RM bounds.  */
5238           TYPE_GCC_MIN_VALUE (gnu_scalar_type) = gnu_low_bound;
5239           TYPE_GCC_MAX_VALUE (gnu_scalar_type) = gnu_high_bound;
5240         }
5241     }
5242
5243   /* If we deferred processing of incomplete types, re-enable it.  If there
5244      were no other disables and we have deferred types to process, do so.  */
5245   if (this_deferred
5246       && --defer_incomplete_level == 0
5247       && defer_incomplete_list)
5248     {
5249       struct incomplete *p, *next;
5250
5251       /* We are back to level 0 for the deferring of incomplete types.
5252          But processing these incomplete types below may itself require
5253          deferring, so preserve what we have and restart from scratch.  */
5254       p = defer_incomplete_list;
5255       defer_incomplete_list = NULL;
5256
5257       for (; p; p = next)
5258         {
5259           next = p->next;
5260
5261           if (p->old_type)
5262             update_pointer_to (TYPE_MAIN_VARIANT (p->old_type),
5263                                gnat_to_gnu_type (p->full_type));
5264           free (p);
5265         }
5266     }
5267
5268   /* If we are not defining this type, see if it's on one of the lists of
5269      incomplete types.  If so, handle the list entry now.  */
5270   if (is_type && !definition)
5271     {
5272       struct incomplete *p;
5273
5274       for (p = defer_incomplete_list; p; p = p->next)
5275         if (p->old_type && p->full_type == gnat_entity)
5276           {
5277             update_pointer_to (TYPE_MAIN_VARIANT (p->old_type),
5278                                TREE_TYPE (gnu_decl));
5279             p->old_type = NULL_TREE;
5280           }
5281
5282       for (p = defer_limited_with; p; p = p->next)
5283         if (p->old_type && Non_Limited_View (p->full_type) == gnat_entity)
5284           {
5285             update_pointer_to (TYPE_MAIN_VARIANT (p->old_type),
5286                                TREE_TYPE (gnu_decl));
5287             p->old_type = NULL_TREE;
5288           }
5289     }
5290
5291   if (this_global)
5292     force_global--;
5293
5294   /* If this is a packed array type whose original array type is itself
5295      an Itype without freeze node, make sure the latter is processed.  */
5296   if (Is_Packed_Array_Impl_Type (gnat_entity)
5297       && Is_Itype (Original_Array_Type (gnat_entity))
5298       && No (Freeze_Node (Original_Array_Type (gnat_entity)))
5299       && !present_gnu_tree (Original_Array_Type (gnat_entity)))
5300     gnat_to_gnu_entity (Original_Array_Type (gnat_entity), NULL_TREE, 0);
5301
5302   return gnu_decl;
5303 }
5304
5305 /* Similar, but if the returned value is a COMPONENT_REF, return the
5306    FIELD_DECL.  */
5307
5308 tree
5309 gnat_to_gnu_field_decl (Entity_Id gnat_entity)
5310 {
5311   tree gnu_field = gnat_to_gnu_entity (gnat_entity, NULL_TREE, 0);
5312
5313   if (TREE_CODE (gnu_field) == COMPONENT_REF)
5314     gnu_field = TREE_OPERAND (gnu_field, 1);
5315
5316   return gnu_field;
5317 }
5318
5319 /* Similar, but GNAT_ENTITY is assumed to refer to a GNAT type.  Return
5320    the GCC type corresponding to that entity.  */
5321
5322 tree
5323 gnat_to_gnu_type (Entity_Id gnat_entity)
5324 {
5325   tree gnu_decl;
5326
5327   /* The back end never attempts to annotate generic types.  */
5328   if (Is_Generic_Type (gnat_entity) && type_annotate_only)
5329      return void_type_node;
5330
5331   gnu_decl = gnat_to_gnu_entity (gnat_entity, NULL_TREE, 0);
5332   gcc_assert (TREE_CODE (gnu_decl) == TYPE_DECL);
5333
5334   return TREE_TYPE (gnu_decl);
5335 }
5336
5337 /* Similar, but GNAT_ENTITY is assumed to refer to a GNAT type.  Return
5338    the unpadded version of the GCC type corresponding to that entity.  */
5339
5340 tree
5341 get_unpadded_type (Entity_Id gnat_entity)
5342 {
5343   tree type = gnat_to_gnu_type (gnat_entity);
5344
5345   if (TYPE_IS_PADDING_P (type))
5346     type = TREE_TYPE (TYPE_FIELDS (type));
5347
5348   return type;
5349 }
5350
5351 /* Return the DECL associated with the public subprogram GNAT_ENTITY but whose
5352    type has been changed to that of the parameterless procedure, except if an
5353    alias is already present, in which case it is returned instead.  */
5354
5355 tree
5356 get_minimal_subprog_decl (Entity_Id gnat_entity)
5357 {
5358   tree gnu_entity_name, gnu_ext_name;
5359   struct attrib *attr_list = NULL;
5360
5361   /* See the E_Function/E_Procedure case of gnat_to_gnu_entity for the model
5362      of the handling applied here.  */
5363
5364   while (Present (Alias (gnat_entity)))
5365     {
5366       gnat_entity = Alias (gnat_entity);
5367       if (present_gnu_tree (gnat_entity))
5368         return get_gnu_tree (gnat_entity);
5369     }
5370
5371   gnu_entity_name = get_entity_name (gnat_entity);
5372   gnu_ext_name = create_concat_name (gnat_entity, NULL);
5373
5374   if (Has_Stdcall_Convention (gnat_entity))
5375     prepend_one_attribute (&attr_list, ATTR_MACHINE_ATTRIBUTE,
5376                            get_identifier ("stdcall"), NULL_TREE,
5377                            gnat_entity);
5378   else if (Has_Thiscall_Convention (gnat_entity))
5379     prepend_one_attribute (&attr_list, ATTR_MACHINE_ATTRIBUTE,
5380                            get_identifier ("thiscall"), NULL_TREE,
5381                            gnat_entity);
5382
5383   if (No (Interface_Name (gnat_entity)) && gnu_ext_name == gnu_entity_name)
5384     gnu_ext_name = NULL_TREE;
5385
5386   return
5387     create_subprog_decl (gnu_entity_name, gnu_ext_name, void_ftype, NULL_TREE,
5388                          is_disabled, true, true, true, attr_list, gnat_entity);
5389 }
5390
5391 /* Return whether the E_Subprogram_Type/E_Function/E_Procedure GNAT_ENTITY is
5392    a C++ imported method or equivalent.
5393
5394    We use the predicate on 32-bit x86/Windows to find out whether we need to
5395    use the "thiscall" calling convention for GNAT_ENTITY.  This convention is
5396    used for C++ methods (functions with METHOD_TYPE) by the back-end.  */
5397
5398 bool
5399 is_cplusplus_method (Entity_Id gnat_entity)
5400 {
5401   if (Convention (gnat_entity) != Convention_CPP)
5402     return false;
5403
5404   /* This is the main case: C++ method imported as a primitive operation.
5405      Note that a C++ class with no virtual functions can be imported as a
5406      limited record type so the operation is not necessarily dispatching.  */
5407   if (Is_Primitive (gnat_entity))
5408     return true;
5409
5410   /* A thunk needs to be handled like its associated primitive operation.  */
5411   if (Is_Subprogram (gnat_entity) && Is_Thunk (gnat_entity))
5412     return true;
5413
5414   /* A constructor is a method on the C++ side.  */
5415   if (Is_Constructor (gnat_entity))
5416     return true;
5417
5418   /* This is set on the E_Subprogram_Type built for a dispatching call.  */
5419   if (Is_Dispatch_Table_Entity (gnat_entity))
5420     return true;
5421
5422   return false;
5423 }
5424
5425 /* Finalize the processing of From_Limited_With incomplete types.  */
5426
5427 void
5428 finalize_from_limited_with (void)
5429 {
5430   struct incomplete *p, *next;
5431
5432   p = defer_limited_with;
5433   defer_limited_with = NULL;
5434
5435   for (; p; p = next)
5436     {
5437       next = p->next;
5438
5439       if (p->old_type)
5440         update_pointer_to (TYPE_MAIN_VARIANT (p->old_type),
5441                            gnat_to_gnu_type (p->full_type));
5442       free (p);
5443     }
5444 }
5445
5446 /* Return the equivalent type to be used for GNAT_ENTITY, if it's a
5447    kind of type (such E_Task_Type) that has a different type which Gigi
5448    uses for its representation.  If the type does not have a special type
5449    for its representation, return GNAT_ENTITY.  If a type is supposed to
5450    exist, but does not, abort unless annotating types, in which case
5451    return Empty.  If GNAT_ENTITY is Empty, return Empty.  */
5452
5453 Entity_Id
5454 Gigi_Equivalent_Type (Entity_Id gnat_entity)
5455 {
5456   Entity_Id gnat_equiv = gnat_entity;
5457
5458   if (No (gnat_entity))
5459     return gnat_entity;
5460
5461   switch (Ekind (gnat_entity))
5462     {
5463     case E_Class_Wide_Subtype:
5464       if (Present (Equivalent_Type (gnat_entity)))
5465         gnat_equiv = Equivalent_Type (gnat_entity);
5466       break;
5467
5468     case E_Access_Protected_Subprogram_Type:
5469     case E_Anonymous_Access_Protected_Subprogram_Type:
5470       gnat_equiv = Equivalent_Type (gnat_entity);
5471       break;
5472
5473     case E_Class_Wide_Type:
5474       gnat_equiv = Root_Type (gnat_entity);
5475       break;
5476
5477     case E_Task_Type:
5478     case E_Task_Subtype:
5479     case E_Protected_Type:
5480     case E_Protected_Subtype:
5481       gnat_equiv = Corresponding_Record_Type (gnat_entity);
5482       break;
5483
5484     default:
5485       break;
5486     }
5487
5488   gcc_assert (Present (gnat_equiv) || type_annotate_only);
5489
5490   return gnat_equiv;
5491 }
5492
5493 /* Return a GCC tree for a type corresponding to the component type of the
5494    array type or subtype GNAT_ARRAY.  DEFINITION is true if this component
5495    is for an array being defined.  DEBUG_INFO_P is true if we need to write
5496    debug information for other types that we may create in the process.  */
5497
5498 static tree
5499 gnat_to_gnu_component_type (Entity_Id gnat_array, bool definition,
5500                             bool debug_info_p)
5501 {
5502   const Entity_Id gnat_type = Component_Type (gnat_array);
5503   tree gnu_type = gnat_to_gnu_type (gnat_type);
5504   tree gnu_comp_size;
5505
5506   /* Try to get a smaller form of the component if needed.  */
5507   if ((Is_Packed (gnat_array)
5508        || Has_Component_Size_Clause (gnat_array))
5509       && !Is_Bit_Packed_Array (gnat_array)
5510       && !Has_Aliased_Components (gnat_array)
5511       && !Strict_Alignment (gnat_type)
5512       && RECORD_OR_UNION_TYPE_P (gnu_type)
5513       && !TYPE_FAT_POINTER_P (gnu_type)
5514       && tree_fits_uhwi_p (TYPE_SIZE (gnu_type)))
5515     gnu_type = make_packable_type (gnu_type, false);
5516
5517   if (Has_Atomic_Components (gnat_array))
5518     check_ok_for_atomic_type (gnu_type, gnat_array, true);
5519
5520   /* Get and validate any specified Component_Size.  */
5521   gnu_comp_size
5522     = validate_size (Component_Size (gnat_array), gnu_type, gnat_array,
5523                      Is_Bit_Packed_Array (gnat_array) ? TYPE_DECL : VAR_DECL,
5524                      true, Has_Component_Size_Clause (gnat_array));
5525
5526   /* If the array has aliased components and the component size can be zero,
5527      force at least unit size to ensure that the components have distinct
5528      addresses.  */
5529   if (!gnu_comp_size
5530       && Has_Aliased_Components (gnat_array)
5531       && (integer_zerop (TYPE_SIZE (gnu_type))
5532           || (TREE_CODE (gnu_type) == ARRAY_TYPE
5533               && !TREE_CONSTANT (TYPE_SIZE (gnu_type)))))
5534     gnu_comp_size
5535       = size_binop (MAX_EXPR, TYPE_SIZE (gnu_type), bitsize_unit_node);
5536
5537   /* If the component type is a RECORD_TYPE that has a self-referential size,
5538      then use the maximum size for the component size.  */
5539   if (!gnu_comp_size
5540       && TREE_CODE (gnu_type) == RECORD_TYPE
5541       && CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_type)))
5542     gnu_comp_size = max_size (TYPE_SIZE (gnu_type), true);
5543
5544   /* Honor the component size.  This is not needed for bit-packed arrays.  */
5545   if (gnu_comp_size && !Is_Bit_Packed_Array (gnat_array))
5546     {
5547       tree orig_type = gnu_type;
5548       unsigned int max_align;
5549
5550       /* If an alignment is specified, use it as a cap on the component type
5551          so that it can be honored for the whole type.  But ignore it for the
5552          original type of packed array types.  */
5553       if (No (Packed_Array_Impl_Type (gnat_array))
5554           && Known_Alignment (gnat_array))
5555         max_align = validate_alignment (Alignment (gnat_array), gnat_array, 0);
5556       else
5557         max_align = 0;
5558
5559       gnu_type = make_type_from_size (gnu_type, gnu_comp_size, false);
5560       if (max_align > 0 && TYPE_ALIGN (gnu_type) > max_align)
5561         gnu_type = orig_type;
5562       else
5563         orig_type = gnu_type;
5564
5565       gnu_type = maybe_pad_type (gnu_type, gnu_comp_size, 0, gnat_array,
5566                                  true, false, definition, true);
5567
5568       /* If a padding record was made, declare it now since it will never be
5569          declared otherwise.  This is necessary to ensure that its subtrees
5570          are properly marked.  */
5571       if (gnu_type != orig_type && !DECL_P (TYPE_NAME (gnu_type)))
5572         create_type_decl (TYPE_NAME (gnu_type), gnu_type, true, debug_info_p,
5573                           gnat_array);
5574     }
5575
5576   if (Has_Volatile_Components (gnat_array))
5577     {
5578       const int quals
5579         = TYPE_QUAL_VOLATILE
5580           | (Has_Atomic_Components (gnat_array) ? TYPE_QUAL_ATOMIC : 0);
5581       gnu_type = change_qualified_type (gnu_type, quals);
5582     }
5583
5584   return gnu_type;
5585 }
5586
5587 /* Return a GCC tree for a parameter corresponding to GNAT_PARAM and
5588    using MECH as its passing mechanism, to be placed in the parameter
5589    list built for GNAT_SUBPROG.  Assume a foreign convention for the
5590    latter if FOREIGN is true.  Also set CICO to true if the parameter
5591    must use the copy-in copy-out implementation mechanism.
5592
5593    The returned tree is a PARM_DECL, except for those cases where no
5594    parameter needs to be actually passed to the subprogram; the type
5595    of this "shadow" parameter is then returned instead.  */
5596
5597 static tree
5598 gnat_to_gnu_param (Entity_Id gnat_param, Mechanism_Type mech,
5599                    Entity_Id gnat_subprog, bool foreign, bool *cico)
5600 {
5601   tree gnu_param_name = get_entity_name (gnat_param);
5602   tree gnu_param_type = gnat_to_gnu_type (Etype (gnat_param));
5603   bool in_param = (Ekind (gnat_param) == E_In_Parameter);
5604   /* The parameter can be indirectly modified if its address is taken.  */
5605   bool ro_param = in_param && !Address_Taken (gnat_param);
5606   bool by_return = false, by_component_ptr = false;
5607   bool by_ref = false;
5608   tree gnu_param;
5609
5610   /* Copy-return is used only for the first parameter of a valued procedure.
5611      It's a copy mechanism for which a parameter is never allocated.  */
5612   if (mech == By_Copy_Return)
5613     {
5614       gcc_assert (Ekind (gnat_param) == E_Out_Parameter);
5615       mech = By_Copy;
5616       by_return = true;
5617     }
5618
5619   /* If this is either a foreign function or if the underlying type won't
5620      be passed by reference and is as aligned as the original type, strip
5621      off possible padding type.  */
5622   if (TYPE_IS_PADDING_P (gnu_param_type))
5623     {
5624       tree unpadded_type = TREE_TYPE (TYPE_FIELDS (gnu_param_type));
5625
5626       if (foreign
5627           || (!must_pass_by_ref (unpadded_type)
5628               && mech != By_Reference
5629               && (mech == By_Copy || !default_pass_by_ref (unpadded_type))
5630               && TYPE_ALIGN (unpadded_type) >= TYPE_ALIGN (gnu_param_type)))
5631         gnu_param_type = unpadded_type;
5632     }
5633
5634   /* If this is a read-only parameter, make a variant of the type that is
5635      read-only.  ??? However, if this is an unconstrained array, that type
5636      can be very complex, so skip it for now.  Likewise for any other
5637      self-referential type.  */
5638   if (ro_param
5639       && TREE_CODE (gnu_param_type) != UNCONSTRAINED_ARRAY_TYPE
5640       && !CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_param_type)))
5641     gnu_param_type = change_qualified_type (gnu_param_type, TYPE_QUAL_CONST);
5642
5643   /* For foreign conventions, pass arrays as pointers to the element type.
5644      First check for unconstrained array and get the underlying array.  */
5645   if (foreign && TREE_CODE (gnu_param_type) == UNCONSTRAINED_ARRAY_TYPE)
5646     gnu_param_type
5647       = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_param_type))));
5648
5649   /* For GCC builtins, pass Address integer types as (void *)  */
5650   if (Convention (gnat_subprog) == Convention_Intrinsic
5651       && Present (Interface_Name (gnat_subprog))
5652       && Is_Descendent_Of_Address (Etype (gnat_param)))
5653     gnu_param_type = ptr_type_node;
5654
5655   /* Arrays are passed as pointers to element type for foreign conventions.  */
5656   if (foreign && mech != By_Copy && TREE_CODE (gnu_param_type) == ARRAY_TYPE)
5657     {
5658       /* Strip off any multi-dimensional entries, then strip
5659          off the last array to get the component type.  */
5660       while (TREE_CODE (TREE_TYPE (gnu_param_type)) == ARRAY_TYPE
5661              && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_param_type)))
5662         gnu_param_type = TREE_TYPE (gnu_param_type);
5663
5664       by_component_ptr = true;
5665       gnu_param_type = TREE_TYPE (gnu_param_type);
5666
5667       if (ro_param)
5668         gnu_param_type
5669           = change_qualified_type (gnu_param_type, TYPE_QUAL_CONST);
5670
5671       gnu_param_type = build_pointer_type (gnu_param_type);
5672     }
5673
5674   /* Fat pointers are passed as thin pointers for foreign conventions.  */
5675   else if (foreign && TYPE_IS_FAT_POINTER_P (gnu_param_type))
5676     gnu_param_type
5677       = make_type_from_size (gnu_param_type, size_int (POINTER_SIZE), 0);
5678
5679   /* If we must pass or were requested to pass by reference, do so.
5680      If we were requested to pass by copy, do so.
5681      Otherwise, for foreign conventions, pass In Out or Out parameters
5682      or aggregates by reference.  For COBOL and Fortran, pass all
5683      integer and FP types that way too.  For Convention Ada, use
5684      the standard Ada default.  */
5685   else if (must_pass_by_ref (gnu_param_type)
5686            || mech == By_Reference
5687            || (mech != By_Copy
5688                && ((foreign
5689                     && (!in_param || AGGREGATE_TYPE_P (gnu_param_type)))
5690                    || (foreign
5691                        && (Convention (gnat_subprog) == Convention_Fortran
5692                            || Convention (gnat_subprog) == Convention_COBOL)
5693                        && (INTEGRAL_TYPE_P (gnu_param_type)
5694                            || FLOAT_TYPE_P (gnu_param_type)))
5695                    || (!foreign
5696                        && default_pass_by_ref (gnu_param_type)))))
5697     {
5698       /* We take advantage of 6.2(12) by considering that references built for
5699          parameters whose type isn't by-ref and for which the mechanism hasn't
5700          been forced to by-ref are restrict-qualified in the C sense.  */
5701       bool restrict_p
5702         = !TYPE_IS_BY_REFERENCE_P (gnu_param_type) && mech != By_Reference;
5703       gnu_param_type = build_reference_type (gnu_param_type);
5704       if (restrict_p)
5705         gnu_param_type
5706           = change_qualified_type (gnu_param_type, TYPE_QUAL_RESTRICT);
5707       by_ref = true;
5708     }
5709
5710   /* Pass In Out or Out parameters using copy-in copy-out mechanism.  */
5711   else if (!in_param)
5712     *cico = true;
5713
5714   if (mech == By_Copy && (by_ref || by_component_ptr))
5715     post_error ("?cannot pass & by copy", gnat_param);
5716
5717   /* If this is an Out parameter that isn't passed by reference and isn't
5718      a pointer or aggregate, we don't make a PARM_DECL for it.  Instead,
5719      it will be a VAR_DECL created when we process the procedure, so just
5720      return its type.  For the special parameter of a valued procedure,
5721      never pass it in.
5722
5723      An exception is made to cover the RM-6.4.1 rule requiring "by copy"
5724      Out parameters with discriminants or implicit initial values to be
5725      handled like In Out parameters.  These type are normally built as
5726      aggregates, hence passed by reference, except for some packed arrays
5727      which end up encoded in special integer types.  Note that scalars can
5728      be given implicit initial values using the Default_Value aspect.
5729
5730      The exception we need to make is then for packed arrays of records
5731      with discriminants or implicit initial values.  We have no light/easy
5732      way to check for the latter case, so we merely check for packed arrays
5733      of records.  This may lead to useless copy-in operations, but in very
5734      rare cases only, as these would be exceptions in a set of already
5735      exceptional situations.  */
5736   if (Ekind (gnat_param) == E_Out_Parameter
5737       && !by_ref
5738       && (by_return
5739           || (!POINTER_TYPE_P (gnu_param_type)
5740               && !AGGREGATE_TYPE_P (gnu_param_type)
5741               && !Has_Default_Aspect (Etype (gnat_param))))
5742       && !(Is_Array_Type (Etype (gnat_param))
5743            && Is_Packed (Etype (gnat_param))
5744            && Is_Composite_Type (Component_Type (Etype (gnat_param)))))
5745     return gnu_param_type;
5746
5747   gnu_param = create_param_decl (gnu_param_name, gnu_param_type,
5748                                  ro_param || by_ref || by_component_ptr);
5749   DECL_BY_REF_P (gnu_param) = by_ref;
5750   DECL_BY_COMPONENT_PTR_P (gnu_param) = by_component_ptr;
5751   DECL_POINTS_TO_READONLY_P (gnu_param)
5752     = (ro_param && (by_ref || by_component_ptr));
5753   DECL_CAN_NEVER_BE_NULL_P (gnu_param) = Can_Never_Be_Null (gnat_param);
5754
5755   /* If no Mechanism was specified, indicate what we're using, then
5756      back-annotate it.  */
5757   if (mech == Default)
5758     mech = (by_ref || by_component_ptr) ? By_Reference : By_Copy;
5759
5760   Set_Mechanism (gnat_param, mech);
5761   return gnu_param;
5762 }
5763
5764 /* Return true if GNAT_ENTITY is an incomplete entity coming from a limited
5765    with of the main unit and whose full view has not been elaborated yet.  */
5766
5767 static bool
5768 is_from_limited_with_of_main (Entity_Id gnat_entity)
5769 {
5770   /* Class-wide types are always transformed into their root type.  */
5771   if (Ekind (gnat_entity) == E_Class_Wide_Type)
5772     gnat_entity = Root_Type (gnat_entity);
5773
5774   if (IN (Ekind (gnat_entity), Incomplete_Kind)
5775       && From_Limited_With (gnat_entity))
5776     {
5777       Entity_Id gnat_full_view = Non_Limited_View (gnat_entity);
5778
5779       if (present_gnu_tree (gnat_full_view))
5780         return false;
5781
5782       return In_Extended_Main_Code_Unit (gnat_full_view);
5783     }
5784
5785   return false;
5786 }
5787
5788 /* Like build_qualified_type, but TYPE_QUALS is added to the existing
5789    qualifiers on TYPE.  */
5790
5791 static tree
5792 change_qualified_type (tree type, int type_quals)
5793 {
5794   return build_qualified_type (type, TYPE_QUALS (type) | type_quals);
5795 }
5796
5797 /* Return true if DISCR1 and DISCR2 represent the same discriminant.  */
5798
5799 static bool
5800 same_discriminant_p (Entity_Id discr1, Entity_Id discr2)
5801 {
5802   while (Present (Corresponding_Discriminant (discr1)))
5803     discr1 = Corresponding_Discriminant (discr1);
5804
5805   while (Present (Corresponding_Discriminant (discr2)))
5806     discr2 = Corresponding_Discriminant (discr2);
5807
5808   return
5809     Original_Record_Component (discr1) == Original_Record_Component (discr2);
5810 }
5811
5812 /* Return true if the array type GNU_TYPE, which represents a dimension of
5813    GNAT_TYPE, has a non-aliased component in the back-end sense.  */
5814
5815 static bool
5816 array_type_has_nonaliased_component (tree gnu_type, Entity_Id gnat_type)
5817 {
5818   /* If the array type is not the innermost dimension of the GNAT type,
5819      then it has a non-aliased component.  */
5820   if (TREE_CODE (TREE_TYPE (gnu_type)) == ARRAY_TYPE
5821       && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type)))
5822     return true;
5823
5824   /* If the array type has an aliased component in the front-end sense,
5825      then it also has an aliased component in the back-end sense.  */
5826   if (Has_Aliased_Components (gnat_type))
5827     return false;
5828
5829   /* If this is a derived type, then it has a non-aliased component if
5830      and only if its parent type also has one.  */
5831   if (Is_Derived_Type (gnat_type))
5832     {
5833       tree gnu_parent_type = gnat_to_gnu_type (Etype (gnat_type));
5834       int index;
5835       if (TREE_CODE (gnu_parent_type) == UNCONSTRAINED_ARRAY_TYPE)
5836         gnu_parent_type
5837           = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_parent_type))));
5838       for (index = Number_Dimensions (gnat_type) - 1; index > 0; index--)
5839         gnu_parent_type = TREE_TYPE (gnu_parent_type);
5840       return TYPE_NONALIASED_COMPONENT (gnu_parent_type);
5841     }
5842
5843   /* Otherwise, rely exclusively on properties of the element type.  */
5844   return type_for_nonaliased_component_p (TREE_TYPE (gnu_type));
5845 }
5846
5847 /* Return true if GNAT_ADDRESS is a value known at compile-time.  */
5848
5849 static bool
5850 compile_time_known_address_p (Node_Id gnat_address)
5851 {
5852   /* Catch System'To_Address.  */
5853   if (Nkind (gnat_address) == N_Unchecked_Type_Conversion)
5854     gnat_address = Expression (gnat_address);
5855
5856   return Compile_Time_Known_Value (gnat_address);
5857 }
5858
5859 /* Return true if GNAT_RANGE, a N_Range node, cannot be superflat, i.e. if the
5860    inequality HB >= LB-1 is true.  LB and HB are the low and high bounds.  */
5861
5862 static bool
5863 cannot_be_superflat (Node_Id gnat_range)
5864 {
5865   Node_Id gnat_lb = Low_Bound (gnat_range), gnat_hb = High_Bound (gnat_range);
5866   Node_Id scalar_range;
5867   tree gnu_lb, gnu_hb, gnu_lb_minus_one;
5868
5869   /* If the low bound is not constant, try to find an upper bound.  */
5870   while (Nkind (gnat_lb) != N_Integer_Literal
5871          && (Ekind (Etype (gnat_lb)) == E_Signed_Integer_Subtype
5872              || Ekind (Etype (gnat_lb)) == E_Modular_Integer_Subtype)
5873          && (scalar_range = Scalar_Range (Etype (gnat_lb)))
5874          && (Nkind (scalar_range) == N_Signed_Integer_Type_Definition
5875              || Nkind (scalar_range) == N_Range))
5876     gnat_lb = High_Bound (scalar_range);
5877
5878   /* If the high bound is not constant, try to find a lower bound.  */
5879   while (Nkind (gnat_hb) != N_Integer_Literal
5880          && (Ekind (Etype (gnat_hb)) == E_Signed_Integer_Subtype
5881              || Ekind (Etype (gnat_hb)) == E_Modular_Integer_Subtype)
5882          && (scalar_range = Scalar_Range (Etype (gnat_hb)))
5883          && (Nkind (scalar_range) == N_Signed_Integer_Type_Definition
5884              || Nkind (scalar_range) == N_Range))
5885     gnat_hb = Low_Bound (scalar_range);
5886
5887   /* If we have failed to find constant bounds, punt.  */
5888   if (Nkind (gnat_lb) != N_Integer_Literal
5889       || Nkind (gnat_hb) != N_Integer_Literal)
5890     return false;
5891
5892   /* We need at least a signed 64-bit type to catch most cases.  */
5893   gnu_lb = UI_To_gnu (Intval (gnat_lb), sbitsizetype);
5894   gnu_hb = UI_To_gnu (Intval (gnat_hb), sbitsizetype);
5895   if (TREE_OVERFLOW (gnu_lb) || TREE_OVERFLOW (gnu_hb))
5896     return false;
5897
5898   /* If the low bound is the smallest integer, nothing can be smaller.  */
5899   gnu_lb_minus_one = size_binop (MINUS_EXPR, gnu_lb, sbitsize_one_node);
5900   if (TREE_OVERFLOW (gnu_lb_minus_one))
5901     return true;
5902
5903   return !tree_int_cst_lt (gnu_hb, gnu_lb_minus_one);
5904 }
5905
5906 /* Return true if GNU_EXPR is (essentially) the address of a CONSTRUCTOR.  */
5907
5908 static bool
5909 constructor_address_p (tree gnu_expr)
5910 {
5911   while (TREE_CODE (gnu_expr) == NOP_EXPR
5912          || TREE_CODE (gnu_expr) == CONVERT_EXPR
5913          || TREE_CODE (gnu_expr) == NON_LVALUE_EXPR)
5914     gnu_expr = TREE_OPERAND (gnu_expr, 0);
5915
5916   return (TREE_CODE (gnu_expr) == ADDR_EXPR
5917           && TREE_CODE (TREE_OPERAND (gnu_expr, 0)) == CONSTRUCTOR);
5918 }
5919
5920 /* Return true if the size in units represented by GNU_SIZE can be handled by
5921    an allocation.  If STATIC_P is true, consider only what can be done with a
5922    static allocation.  */
5923
5924 static bool
5925 allocatable_size_p (tree gnu_size, bool static_p)
5926 {
5927   /* We can allocate a fixed size if it is a valid for the middle-end.  */
5928   if (TREE_CODE (gnu_size) == INTEGER_CST)
5929     return valid_constant_size_p (gnu_size);
5930
5931   /* We can allocate a variable size if this isn't a static allocation.  */
5932   else
5933     return !static_p;
5934 }
5935
5936 /* Return true if GNU_EXPR needs a conversion to GNU_TYPE when used as the
5937    initial value of an object of GNU_TYPE.  */
5938
5939 static bool
5940 initial_value_needs_conversion (tree gnu_type, tree gnu_expr)
5941 {
5942   /* Do not convert if the object's type is unconstrained because this would
5943      generate useless evaluations of the CONSTRUCTOR to compute the size.  */
5944   if (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE
5945       || CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_type)))
5946     return false;
5947
5948   /* Do not convert if the object's type is a padding record whose field is of
5949      self-referential size because we want to copy only the actual data.  */
5950   if (type_is_padding_self_referential (gnu_type))
5951     return false;
5952
5953   /* Do not convert a call to a function that returns with variable size since
5954      we want to use the return slot optimization in this case.  */
5955   if (TREE_CODE (gnu_expr) == CALL_EXPR
5956       && return_type_with_variable_size_p (TREE_TYPE (gnu_expr)))
5957     return false;
5958
5959   /* Do not convert to a record type with a variant part from a record type
5960      without one, to keep the object simpler.  */
5961   if (TREE_CODE (gnu_type) == RECORD_TYPE
5962       && TREE_CODE (TREE_TYPE (gnu_expr)) == RECORD_TYPE
5963       && get_variant_part (gnu_type) != NULL_TREE
5964       && get_variant_part (TREE_TYPE (gnu_expr)) == NULL_TREE)
5965     return false;
5966
5967   /* In all the other cases, convert the expression to the object's type.  */
5968   return true;
5969 }
5970 \f
5971 /* Given GNAT_ENTITY, elaborate all expressions that are required to
5972    be elaborated at the point of its definition, but do nothing else.  */
5973
5974 void
5975 elaborate_entity (Entity_Id gnat_entity)
5976 {
5977   switch (Ekind (gnat_entity))
5978     {
5979     case E_Signed_Integer_Subtype:
5980     case E_Modular_Integer_Subtype:
5981     case E_Enumeration_Subtype:
5982     case E_Ordinary_Fixed_Point_Subtype:
5983     case E_Decimal_Fixed_Point_Subtype:
5984     case E_Floating_Point_Subtype:
5985       {
5986         Node_Id gnat_lb = Type_Low_Bound (gnat_entity);
5987         Node_Id gnat_hb = Type_High_Bound (gnat_entity);
5988
5989         /* ??? Tests to avoid Constraint_Error in static expressions
5990            are needed until after the front stops generating bogus
5991            conversions on bounds of real types.  */
5992         if (!Raises_Constraint_Error (gnat_lb))
5993           elaborate_expression (gnat_lb, gnat_entity, "L", true, false,
5994                                 Needs_Debug_Info (gnat_entity));
5995         if (!Raises_Constraint_Error (gnat_hb))
5996           elaborate_expression (gnat_hb, gnat_entity, "U", true, false,
5997                                 Needs_Debug_Info (gnat_entity));
5998       break;
5999       }
6000
6001     case E_Record_Subtype:
6002     case E_Private_Subtype:
6003     case E_Limited_Private_Subtype:
6004     case E_Record_Subtype_With_Private:
6005       if (Has_Discriminants (gnat_entity) && Is_Constrained (gnat_entity))
6006         {
6007           Node_Id gnat_discriminant_expr;
6008           Entity_Id gnat_field;
6009
6010           for (gnat_field
6011                = First_Discriminant (Implementation_Base_Type (gnat_entity)),
6012                gnat_discriminant_expr
6013                = First_Elmt (Discriminant_Constraint (gnat_entity));
6014                Present (gnat_field);
6015                gnat_field = Next_Discriminant (gnat_field),
6016                gnat_discriminant_expr = Next_Elmt (gnat_discriminant_expr))
6017             /* Ignore access discriminants.  */
6018             if (!Is_Access_Type (Etype (Node (gnat_discriminant_expr))))
6019               elaborate_expression (Node (gnat_discriminant_expr),
6020                                     gnat_entity, get_entity_char (gnat_field),
6021                                     true, false, false);
6022         }
6023       break;
6024
6025     }
6026 }
6027 \f
6028 /* Prepend to ATTR_LIST an entry for an attribute with provided TYPE,
6029    NAME, ARGS and ERROR_POINT.  */
6030
6031 static void
6032 prepend_one_attribute (struct attrib **attr_list,
6033                        enum attr_type attr_type,
6034                        tree attr_name,
6035                        tree attr_args,
6036                        Node_Id attr_error_point)
6037 {
6038   struct attrib * attr = (struct attrib *) xmalloc (sizeof (struct attrib));
6039
6040   attr->type = attr_type;
6041   attr->name = attr_name;
6042   attr->args = attr_args;
6043   attr->error_point = attr_error_point;
6044
6045   attr->next = *attr_list;
6046   *attr_list = attr;
6047 }
6048
6049 /* Prepend to ATTR_LIST an entry for an attribute provided by GNAT_PRAGMA.  */
6050
6051 static void
6052 prepend_one_attribute_pragma (struct attrib **attr_list, Node_Id gnat_pragma)
6053 {
6054   const Node_Id gnat_arg = Pragma_Argument_Associations (gnat_pragma);
6055   tree gnu_arg0 = NULL_TREE, gnu_arg1 = NULL_TREE;
6056   enum attr_type etype;
6057
6058   /* Map the pragma at hand.  Skip if this isn't one we know how to handle.  */
6059   switch (Get_Pragma_Id (Chars (Pragma_Identifier (gnat_pragma))))
6060     {
6061     case Pragma_Machine_Attribute:
6062       etype = ATTR_MACHINE_ATTRIBUTE;
6063       break;
6064
6065     case Pragma_Linker_Alias:
6066       etype = ATTR_LINK_ALIAS;
6067       break;
6068
6069     case Pragma_Linker_Section:
6070       etype = ATTR_LINK_SECTION;
6071       break;
6072
6073     case Pragma_Linker_Constructor:
6074       etype = ATTR_LINK_CONSTRUCTOR;
6075       break;
6076
6077     case Pragma_Linker_Destructor:
6078       etype = ATTR_LINK_DESTRUCTOR;
6079       break;
6080
6081     case Pragma_Weak_External:
6082       etype = ATTR_WEAK_EXTERNAL;
6083       break;
6084
6085     case Pragma_Thread_Local_Storage:
6086       etype = ATTR_THREAD_LOCAL_STORAGE;
6087       break;
6088
6089     default:
6090       return;
6091     }
6092
6093   /* See what arguments we have and turn them into GCC trees for attribute
6094      handlers.  These expect identifier for strings.  We handle at most two
6095      arguments and static expressions only.  */
6096   if (Present (gnat_arg) && Present (First (gnat_arg)))
6097     {
6098       Node_Id gnat_arg0 = Next (First (gnat_arg));
6099       Node_Id gnat_arg1 = Empty;
6100
6101       if (Present (gnat_arg0)
6102           && Is_OK_Static_Expression (Expression (gnat_arg0)))
6103         {
6104           gnu_arg0 = gnat_to_gnu (Expression (gnat_arg0));
6105
6106           if (TREE_CODE (gnu_arg0) == STRING_CST)
6107             {
6108               gnu_arg0 = get_identifier (TREE_STRING_POINTER (gnu_arg0));
6109               if (IDENTIFIER_LENGTH (gnu_arg0) == 0)
6110                 return;
6111             }
6112
6113           gnat_arg1 = Next (gnat_arg0);
6114         }
6115
6116       if (Present (gnat_arg1)
6117           && Is_OK_Static_Expression (Expression (gnat_arg1)))
6118         {
6119           gnu_arg1 = gnat_to_gnu (Expression (gnat_arg1));
6120
6121           if (TREE_CODE (gnu_arg1) == STRING_CST)
6122            gnu_arg1 = get_identifier (TREE_STRING_POINTER (gnu_arg1));
6123         }
6124     }
6125
6126   /* Prepend to the list.  Make a list of the argument we might have, as GCC
6127      expects it.  */
6128   prepend_one_attribute (attr_list, etype, gnu_arg0,
6129                          gnu_arg1
6130                          ? build_tree_list (NULL_TREE, gnu_arg1) : NULL_TREE,
6131                          Present (Next (First (gnat_arg)))
6132                          ? Expression (Next (First (gnat_arg))) : gnat_pragma);
6133 }
6134
6135 /* Prepend to ATTR_LIST the list of attributes for GNAT_ENTITY, if any.  */
6136
6137 static void
6138 prepend_attributes (struct attrib **attr_list, Entity_Id gnat_entity)
6139 {
6140   Node_Id gnat_temp;
6141
6142   /* Attributes are stored as Representation Item pragmas.  */
6143   for (gnat_temp = First_Rep_Item (gnat_entity);
6144        Present (gnat_temp);
6145        gnat_temp = Next_Rep_Item (gnat_temp))
6146     if (Nkind (gnat_temp) == N_Pragma)
6147       prepend_one_attribute_pragma (attr_list, gnat_temp);
6148 }
6149 \f
6150 /* Given a GNAT tree GNAT_EXPR, for an expression which is a value within a
6151    type definition (either a bound or a discriminant value) for GNAT_ENTITY,
6152    return the GCC tree to use for that expression.  S is the suffix to use
6153    if a variable needs to be created and DEFINITION is true if this is done
6154    for a definition of GNAT_ENTITY.  If NEED_VALUE is true, we need a result;
6155    otherwise, we are just elaborating the expression for side-effects.  If
6156    NEED_DEBUG is true, we need a variable for debugging purposes even if it
6157    isn't needed for code generation.  */
6158
6159 static tree
6160 elaborate_expression (Node_Id gnat_expr, Entity_Id gnat_entity, const char *s,
6161                       bool definition, bool need_value, bool need_debug)
6162 {
6163   tree gnu_expr;
6164
6165   /* If we already elaborated this expression (e.g. it was involved
6166      in the definition of a private type), use the old value.  */
6167   if (present_gnu_tree (gnat_expr))
6168     return get_gnu_tree (gnat_expr);
6169
6170   /* If we don't need a value and this is static or a discriminant,
6171      we don't need to do anything.  */
6172   if (!need_value
6173       && (Is_OK_Static_Expression (gnat_expr)
6174           || (Nkind (gnat_expr) == N_Identifier
6175               && Ekind (Entity (gnat_expr)) == E_Discriminant)))
6176     return NULL_TREE;
6177
6178   /* If it's a static expression, we don't need a variable for debugging.  */
6179   if (need_debug && Is_OK_Static_Expression (gnat_expr))
6180     need_debug = false;
6181
6182   /* Otherwise, convert this tree to its GCC equivalent and elaborate it.  */
6183   gnu_expr = elaborate_expression_1 (gnat_to_gnu (gnat_expr), gnat_entity, s,
6184                                      definition, need_debug);
6185
6186   /* Save the expression in case we try to elaborate this entity again.  Since
6187      it's not a DECL, don't check it.  Don't save if it's a discriminant.  */
6188   if (!CONTAINS_PLACEHOLDER_P (gnu_expr))
6189     save_gnu_tree (gnat_expr, gnu_expr, true);
6190
6191   return need_value ? gnu_expr : error_mark_node;
6192 }
6193
6194 /* Similar, but take a GNU expression and always return a result.  */
6195
6196 static tree
6197 elaborate_expression_1 (tree gnu_expr, Entity_Id gnat_entity, const char *s,
6198                         bool definition, bool need_debug)
6199 {
6200   const bool expr_public_p = Is_Public (gnat_entity);
6201   const bool expr_global_p = expr_public_p || global_bindings_p ();
6202   bool expr_variable_p, use_variable;
6203
6204   /* If GNU_EXPR contains a placeholder, just return it.  We rely on the fact
6205      that an expression cannot contain both a discriminant and a variable.  */
6206   if (CONTAINS_PLACEHOLDER_P (gnu_expr))
6207     return gnu_expr;
6208
6209   /* If GNU_EXPR is neither a constant nor based on a read-only variable, make
6210      a variable that is initialized to contain the expression when the package
6211      containing the definition is elaborated.  If this entity is defined at top
6212      level, replace the expression by the variable; otherwise use a SAVE_EXPR
6213      if this is necessary.  */
6214   if (TREE_CONSTANT (gnu_expr))
6215     expr_variable_p = false;
6216   else
6217     {
6218       /* Skip any conversions and simple constant arithmetics to see if the
6219          expression is based on a read-only variable.  */
6220       tree inner = remove_conversions (gnu_expr, true);
6221
6222       inner = skip_simple_constant_arithmetic (inner);
6223
6224       if (handled_component_p (inner))
6225         inner = get_inner_constant_reference (inner);
6226
6227       expr_variable_p
6228         = !(inner
6229             && TREE_CODE (inner) == VAR_DECL
6230             && (TREE_READONLY (inner) || DECL_READONLY_ONCE_ELAB (inner)));
6231     }
6232
6233   /* We only need to use the variable if we are in a global context since GCC
6234      can do the right thing in the local case.  However, when not optimizing,
6235      use it for bounds of loop iteration scheme to avoid code duplication.  */
6236   use_variable = expr_variable_p
6237                  && (expr_global_p
6238                      || (!optimize
6239                          && definition
6240                          && Is_Itype (gnat_entity)
6241                          && Nkind (Associated_Node_For_Itype (gnat_entity))
6242                             == N_Loop_Parameter_Specification));
6243
6244   /* Now create it, possibly only for debugging purposes.  */
6245   if (use_variable || need_debug)
6246     {
6247       /* The following variable creation can happen when processing the body
6248          of subprograms that are defined out of the extended main unit and
6249          inlined.  In this case, we are not at the global scope, and thus the
6250          new variable must not be tagged "external", as we used to do here as
6251          soon as DEFINITION was false.  */
6252       tree gnu_decl
6253         = create_var_decl_1 (create_concat_name (gnat_entity, s), NULL_TREE,
6254                              TREE_TYPE (gnu_expr), gnu_expr, true,
6255                              expr_public_p, !definition && expr_global_p,
6256                              expr_global_p, !need_debug, NULL, gnat_entity);
6257
6258       /* Whether or not gnat_entity comes from source, this variable is a
6259          compilation artifact.  */
6260       DECL_ARTIFICIAL (gnu_decl) = 1;
6261
6262       /* Using this variable at debug time (if need_debug is true) requires a
6263          proper location.  The back-end will compute a location for this
6264          variable only if the variable is used by the generated code.
6265          Returning the variable ensures the caller will use it in generated
6266          code.  Note that there is no need for a location if the debug info
6267          contains an integer constant.
6268          FIXME: when the encoding-based debug scheme is dropped, move this
6269          condition to the top-level IF block: we will not need to create a
6270          variable anymore in such cases, then.  */
6271       if (use_variable || (need_debug && !TREE_CONSTANT (gnu_expr)))
6272         return gnu_decl;
6273     }
6274
6275   return expr_variable_p ? gnat_save_expr (gnu_expr) : gnu_expr;
6276 }
6277
6278 /* Similar, but take an alignment factor and make it explicit in the tree.  */
6279
6280 static tree
6281 elaborate_expression_2 (tree gnu_expr, Entity_Id gnat_entity, const char *s,
6282                         bool definition, bool need_debug, unsigned int align)
6283 {
6284   tree unit_align = size_int (align / BITS_PER_UNIT);
6285   return
6286     size_binop (MULT_EXPR,
6287                 elaborate_expression_1 (size_binop (EXACT_DIV_EXPR,
6288                                                     gnu_expr,
6289                                                     unit_align),
6290                                         gnat_entity, s, definition,
6291                                         need_debug),
6292                 unit_align);
6293 }
6294
6295 /* Structure to hold internal data for elaborate_reference.  */
6296
6297 struct er_data
6298 {
6299   Entity_Id entity;
6300   bool definition;
6301   unsigned int n;
6302 };
6303
6304 /* Wrapper function around elaborate_expression_1 for elaborate_reference.  */
6305
6306 static tree
6307 elaborate_reference_1 (tree ref, void *data)
6308 {
6309   struct er_data *er = (struct er_data *)data;
6310   char suffix[16];
6311
6312   /* This is what elaborate_expression_1 does if NEED_DEBUG is false.  */
6313   if (TREE_CONSTANT (ref))
6314     return ref;
6315
6316   /* If this is a COMPONENT_REF of a fat pointer, elaborate the entire fat
6317      pointer.  This may be more efficient, but will also allow us to more
6318      easily find the match for the PLACEHOLDER_EXPR.  */
6319   if (TREE_CODE (ref) == COMPONENT_REF
6320       && TYPE_IS_FAT_POINTER_P (TREE_TYPE (TREE_OPERAND (ref, 0))))
6321     return build3 (COMPONENT_REF, TREE_TYPE (ref),
6322                    elaborate_reference_1 (TREE_OPERAND (ref, 0), data),
6323                    TREE_OPERAND (ref, 1), TREE_OPERAND (ref, 2));
6324
6325   sprintf (suffix, "EXP%d", ++er->n);
6326   return
6327     elaborate_expression_1 (ref, er->entity, suffix, er->definition, false);
6328 }
6329
6330 /* Elaborate the reference REF to be used as renamed object for GNAT_ENTITY.
6331    DEFINITION is true if this is done for a definition of GNAT_ENTITY and
6332    INIT is set to the first arm of a COMPOUND_EXPR present in REF, if any.  */
6333
6334 static tree
6335 elaborate_reference (tree ref, Entity_Id gnat_entity, bool definition,
6336                      tree *init)
6337 {
6338   struct er_data er = { gnat_entity, definition, 0 };
6339   return gnat_rewrite_reference (ref, elaborate_reference_1, &er, init);
6340 }
6341 \f
6342 /* Given a GNU tree and a GNAT list of choices, generate an expression to test
6343    the value passed against the list of choices.  */
6344
6345 tree
6346 choices_to_gnu (tree operand, Node_Id choices)
6347 {
6348   Node_Id choice;
6349   Node_Id gnat_temp;
6350   tree result = boolean_false_node;
6351   tree this_test, low = 0, high = 0, single = 0;
6352
6353   for (choice = First (choices); Present (choice); choice = Next (choice))
6354     {
6355       switch (Nkind (choice))
6356         {
6357         case N_Range:
6358           low = gnat_to_gnu (Low_Bound (choice));
6359           high = gnat_to_gnu (High_Bound (choice));
6360
6361           this_test
6362             = build_binary_op (TRUTH_ANDIF_EXPR, boolean_type_node,
6363                                build_binary_op (GE_EXPR, boolean_type_node,
6364                                                 operand, low),
6365                                build_binary_op (LE_EXPR, boolean_type_node,
6366                                                 operand, high));
6367
6368           break;
6369
6370         case N_Subtype_Indication:
6371           gnat_temp = Range_Expression (Constraint (choice));
6372           low = gnat_to_gnu (Low_Bound (gnat_temp));
6373           high = gnat_to_gnu (High_Bound (gnat_temp));
6374
6375           this_test
6376             = build_binary_op (TRUTH_ANDIF_EXPR, boolean_type_node,
6377                                build_binary_op (GE_EXPR, boolean_type_node,
6378                                                 operand, low),
6379                                build_binary_op (LE_EXPR, boolean_type_node,
6380                                                 operand, high));
6381           break;
6382
6383         case N_Identifier:
6384         case N_Expanded_Name:
6385           /* This represents either a subtype range, an enumeration
6386              literal, or a constant  Ekind says which.  If an enumeration
6387              literal or constant, fall through to the next case.  */
6388           if (Ekind (Entity (choice)) != E_Enumeration_Literal
6389               && Ekind (Entity (choice)) != E_Constant)
6390             {
6391               tree type = gnat_to_gnu_type (Entity (choice));
6392
6393               low = TYPE_MIN_VALUE (type);
6394               high = TYPE_MAX_VALUE (type);
6395
6396               this_test
6397                 = build_binary_op (TRUTH_ANDIF_EXPR, boolean_type_node,
6398                                    build_binary_op (GE_EXPR, boolean_type_node,
6399                                                     operand, low),
6400                                    build_binary_op (LE_EXPR, boolean_type_node,
6401                                                     operand, high));
6402               break;
6403             }
6404
6405           /* ... fall through ... */
6406
6407         case N_Character_Literal:
6408         case N_Integer_Literal:
6409           single = gnat_to_gnu (choice);
6410           this_test = build_binary_op (EQ_EXPR, boolean_type_node, operand,
6411                                        single);
6412           break;
6413
6414         case N_Others_Choice:
6415           this_test = boolean_true_node;
6416           break;
6417
6418         default:
6419           gcc_unreachable ();
6420         }
6421
6422       result = build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node, result,
6423                                 this_test);
6424     }
6425
6426   return result;
6427 }
6428 \f
6429 /* Adjust PACKED setting as passed to gnat_to_gnu_field for a field of
6430    type FIELD_TYPE to be placed in RECORD_TYPE.  Return the result.  */
6431
6432 static int
6433 adjust_packed (tree field_type, tree record_type, int packed)
6434 {
6435   /* If the field contains an item of variable size, we cannot pack it
6436      because we cannot create temporaries of non-fixed size in case
6437      we need to take the address of the field.  See addressable_p and
6438      the notes on the addressability issues for further details.  */
6439   if (type_has_variable_size (field_type))
6440     return 0;
6441
6442   /* If the alignment of the record is specified and the field type
6443      is over-aligned, request Storage_Unit alignment for the field.  */
6444   if (packed == -2)
6445     {
6446       if (TYPE_ALIGN (field_type) > TYPE_ALIGN (record_type))
6447         return -1;
6448       else
6449         return 0;
6450     }
6451
6452   return packed;
6453 }
6454
6455 /* Return a GCC tree for a field corresponding to GNAT_FIELD to be
6456    placed in GNU_RECORD_TYPE.
6457
6458    PACKED is 1 if the enclosing record is packed, -1 if the enclosing
6459    record has Component_Alignment of Storage_Unit, -2 if the enclosing
6460    record has a specified alignment.
6461
6462    DEFINITION is true if this field is for a record being defined.
6463
6464    DEBUG_INFO_P is true if we need to write debug information for types
6465    that we may create in the process.  */
6466
6467 static tree
6468 gnat_to_gnu_field (Entity_Id gnat_field, tree gnu_record_type, int packed,
6469                    bool definition, bool debug_info_p)
6470 {
6471   const Entity_Id gnat_field_type = Etype (gnat_field);
6472   const bool is_aliased
6473     = Is_Aliased (gnat_field);
6474   const bool is_atomic
6475     = (Is_Atomic_Or_VFA (gnat_field) || Is_Atomic_Or_VFA (gnat_field_type));
6476   const bool is_independent
6477     = (Is_Independent (gnat_field) || Is_Independent (gnat_field_type));
6478   const bool is_volatile
6479     = (Treat_As_Volatile (gnat_field) || Treat_As_Volatile (gnat_field_type));
6480   const bool needs_strict_alignment
6481     = (is_aliased
6482        || is_independent
6483        || is_volatile
6484        || Strict_Alignment (gnat_field_type));
6485   tree gnu_field_type = gnat_to_gnu_type (gnat_field_type);
6486   tree gnu_field_id = get_entity_name (gnat_field);
6487   tree gnu_field, gnu_size, gnu_pos;
6488
6489   /* If this field requires strict alignment, we cannot pack it because
6490      it would very likely be under-aligned in the record.  */
6491   if (needs_strict_alignment)
6492     packed = 0;
6493   else
6494     packed = adjust_packed (gnu_field_type, gnu_record_type, packed);
6495
6496   /* If a size is specified, use it.  Otherwise, if the record type is packed,
6497      use the official RM size.  See "Handling of Type'Size Values" in Einfo
6498      for further details.  */
6499   if (Known_Esize (gnat_field))
6500     gnu_size = validate_size (Esize (gnat_field), gnu_field_type,
6501                               gnat_field, FIELD_DECL, false, true);
6502   else if (packed == 1)
6503     gnu_size = validate_size (RM_Size (gnat_field_type), gnu_field_type,
6504                               gnat_field, FIELD_DECL, false, true);
6505   else
6506     gnu_size = NULL_TREE;
6507
6508   /* If we have a specified size that is smaller than that of the field's type,
6509      or a position is specified, and the field's type is a record that doesn't
6510      require strict alignment, see if we can get either an integral mode form
6511      of the type or a smaller form.  If we can, show a size was specified for
6512      the field if there wasn't one already, so we know to make this a bitfield
6513      and avoid making things wider.
6514
6515      Changing to an integral mode form is useful when the record is packed as
6516      we can then place the field at a non-byte-aligned position and so achieve
6517      tighter packing.  This is in addition required if the field shares a byte
6518      with another field and the front-end lets the back-end handle the access
6519      to the field, because GCC cannot handle non-byte-aligned BLKmode fields.
6520
6521      Changing to a smaller form is required if the specified size is smaller
6522      than that of the field's type and the type contains sub-fields that are
6523      padded, in order to avoid generating accesses to these sub-fields that
6524      are wider than the field.
6525
6526      We avoid the transformation if it is not required or potentially useful,
6527      as it might entail an increase of the field's alignment and have ripple
6528      effects on the outer record type.  A typical case is a field known to be
6529      byte-aligned and not to share a byte with another field.  */
6530   if (!needs_strict_alignment
6531       && RECORD_OR_UNION_TYPE_P (gnu_field_type)
6532       && !TYPE_FAT_POINTER_P (gnu_field_type)
6533       && tree_fits_uhwi_p (TYPE_SIZE (gnu_field_type))
6534       && (packed == 1
6535           || (gnu_size
6536               && (tree_int_cst_lt (gnu_size, TYPE_SIZE (gnu_field_type))
6537                   || (Present (Component_Clause (gnat_field))
6538                       && !(UI_To_Int (Component_Bit_Offset (gnat_field))
6539                            % BITS_PER_UNIT == 0
6540                            && value_factor_p (gnu_size, BITS_PER_UNIT)))))))
6541     {
6542       tree gnu_packable_type = make_packable_type (gnu_field_type, true);
6543       if (gnu_packable_type != gnu_field_type)
6544         {
6545           gnu_field_type = gnu_packable_type;
6546           if (!gnu_size)
6547             gnu_size = rm_size (gnu_field_type);
6548         }
6549     }
6550
6551   if (Is_Atomic_Or_VFA (gnat_field))
6552     check_ok_for_atomic_type (gnu_field_type, gnat_field, false);
6553
6554   if (Present (Component_Clause (gnat_field)))
6555     {
6556       Node_Id gnat_clause = Component_Clause (gnat_field);
6557       Entity_Id gnat_parent
6558         = Parent_Subtype (Underlying_Type (Scope (gnat_field)));
6559
6560       gnu_pos = UI_To_gnu (Component_Bit_Offset (gnat_field), bitsizetype);
6561       gnu_size = validate_size (Esize (gnat_field), gnu_field_type,
6562                                 gnat_field, FIELD_DECL, false, true);
6563
6564       /* Ensure the position does not overlap with the parent subtype, if there
6565          is one.  This test is omitted if the parent of the tagged type has a
6566          full rep clause since, in this case, component clauses are allowed to
6567          overlay the space allocated for the parent type and the front-end has
6568          checked that there are no overlapping components.  */
6569       if (Present (gnat_parent) && !Is_Fully_Repped_Tagged_Type (gnat_parent))
6570         {
6571           tree gnu_parent = gnat_to_gnu_type (gnat_parent);
6572
6573           if (TREE_CODE (TYPE_SIZE (gnu_parent)) == INTEGER_CST
6574               && tree_int_cst_lt (gnu_pos, TYPE_SIZE (gnu_parent)))
6575             post_error_ne_tree
6576               ("offset of& must be beyond parent{, minimum allowed is ^}",
6577                Position (gnat_clause), gnat_field, TYPE_SIZE_UNIT (gnu_parent));
6578         }
6579
6580       /* If this field needs strict alignment, make sure that the record is
6581          sufficiently aligned and that the position and size are consistent
6582          with the type.  But don't do it if we are just annotating types and
6583          the field's type is tagged, since tagged types aren't fully laid out
6584          in this mode.  Also, note that atomic implies volatile so the inner
6585          test sequences ordering is significant here.  */
6586       if (needs_strict_alignment
6587           && !(type_annotate_only && Is_Tagged_Type (gnat_field_type)))
6588         {
6589           const unsigned int type_align = TYPE_ALIGN (gnu_field_type);
6590
6591           if (TYPE_ALIGN (gnu_record_type) < type_align)
6592             TYPE_ALIGN (gnu_record_type) = type_align;
6593
6594           /* If the position is not a multiple of the alignment of the type,
6595              then error out and reset the position.  */
6596           if (!integer_zerop (size_binop (TRUNC_MOD_EXPR, gnu_pos,
6597                                           bitsize_int (type_align))))
6598             {
6599               const char *s;
6600
6601               if (is_atomic)
6602                 s = "position of atomic field& must be multiple of ^ bits";
6603               else if (is_aliased)
6604                 s = "position of aliased field& must be multiple of ^ bits";
6605               else if (is_independent)
6606                 s = "position of independent field& must be multiple of ^ bits";
6607               else if (is_volatile)
6608                 s = "position of volatile field& must be multiple of ^ bits";
6609               else if (Strict_Alignment (gnat_field_type))
6610                 s = "position of & with aliased or tagged part must be"
6611                     " multiple of ^ bits";
6612               else
6613                 gcc_unreachable ();
6614
6615               post_error_ne_num (s, First_Bit (gnat_clause), gnat_field,
6616                                  type_align);
6617               gnu_pos = NULL_TREE;
6618             }
6619
6620           if (gnu_size)
6621             {
6622               tree gnu_type_size = TYPE_SIZE (gnu_field_type);
6623               const int cmp = tree_int_cst_compare (gnu_size, gnu_type_size);
6624
6625               /* If the size is lower than that of the type, or greater for
6626                  atomic and aliased, then error out and reset the size.  */
6627               if (cmp < 0 || (cmp > 0 && (is_atomic || is_aliased)))
6628                 {
6629                   const char *s;
6630
6631                   if (is_atomic)
6632                     s = "size of atomic field& must be ^ bits";
6633                   else if (is_aliased)
6634                     s = "size of aliased field& must be ^ bits";
6635                   else if (is_independent)
6636                     s = "size of independent field& must be at least ^ bits";
6637                   else if (is_volatile)
6638                     s = "size of volatile field& must be at least ^ bits";
6639                   else if (Strict_Alignment (gnat_field_type))
6640                     s = "size of & with aliased or tagged part must be"
6641                         " at least ^ bits";
6642                   else
6643                     gcc_unreachable ();
6644
6645                   post_error_ne_tree (s, Last_Bit (gnat_clause), gnat_field,
6646                                       gnu_type_size);
6647                   gnu_size = NULL_TREE;
6648                 }
6649
6650               /* Likewise if the size is not a multiple of a byte,  */
6651               else if (!integer_zerop (size_binop (TRUNC_MOD_EXPR, gnu_size,
6652                                                    bitsize_unit_node)))
6653                 {
6654                   const char *s;
6655
6656                   if (is_independent)
6657                     s = "size of independent field& must be multiple of"
6658                         " Storage_Unit";
6659                   else if (is_volatile)
6660                     s = "size of volatile field& must be multiple of"
6661                         " Storage_Unit";
6662                   else if (Strict_Alignment (gnat_field_type))
6663                     s = "size of & with aliased or tagged part must be"
6664                         " multiple of Storage_Unit";
6665                   else
6666                     gcc_unreachable ();
6667
6668                   post_error_ne (s, Last_Bit (gnat_clause), gnat_field);
6669                   gnu_size = NULL_TREE;
6670                 }
6671             }
6672         }
6673     }
6674
6675   /* If the record has rep clauses and this is the tag field, make a rep
6676      clause for it as well.  */
6677   else if (Has_Specified_Layout (Scope (gnat_field))
6678            && Chars (gnat_field) == Name_uTag)
6679     {
6680       gnu_pos = bitsize_zero_node;
6681       gnu_size = TYPE_SIZE (gnu_field_type);
6682     }
6683
6684   else
6685     {
6686       gnu_pos = NULL_TREE;
6687
6688       /* If we are packing the record and the field is BLKmode, round the
6689          size up to a byte boundary.  */
6690       if (packed && TYPE_MODE (gnu_field_type) == BLKmode && gnu_size)
6691         gnu_size = round_up (gnu_size, BITS_PER_UNIT);
6692     }
6693
6694   /* We need to make the size the maximum for the type if it is
6695      self-referential and an unconstrained type.  In that case, we can't
6696      pack the field since we can't make a copy to align it.  */
6697   if (TREE_CODE (gnu_field_type) == RECORD_TYPE
6698       && !gnu_size
6699       && CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_field_type))
6700       && !Is_Constrained (Underlying_Type (gnat_field_type)))
6701     {
6702       gnu_size = max_size (TYPE_SIZE (gnu_field_type), true);
6703       packed = 0;
6704     }
6705
6706   /* If a size is specified, adjust the field's type to it.  */
6707   if (gnu_size)
6708     {
6709       tree orig_field_type;
6710
6711       /* If the field's type is justified modular, we would need to remove
6712          the wrapper to (better) meet the layout requirements.  However we
6713          can do so only if the field is not aliased to preserve the unique
6714          layout and if the prescribed size is not greater than that of the
6715          packed array to preserve the justification.  */
6716       if (!needs_strict_alignment
6717           && TREE_CODE (gnu_field_type) == RECORD_TYPE
6718           && TYPE_JUSTIFIED_MODULAR_P (gnu_field_type)
6719           && tree_int_cst_compare (gnu_size, TYPE_ADA_SIZE (gnu_field_type))
6720                <= 0)
6721         gnu_field_type = TREE_TYPE (TYPE_FIELDS (gnu_field_type));
6722
6723       /* Similarly if the field's type is a misaligned integral type, but
6724          there is no restriction on the size as there is no justification.  */
6725       if (!needs_strict_alignment
6726           && TYPE_IS_PADDING_P (gnu_field_type)
6727           && INTEGRAL_TYPE_P (TREE_TYPE (TYPE_FIELDS (gnu_field_type))))
6728         gnu_field_type = TREE_TYPE (TYPE_FIELDS (gnu_field_type));
6729
6730       gnu_field_type
6731         = make_type_from_size (gnu_field_type, gnu_size,
6732                                Has_Biased_Representation (gnat_field));
6733
6734       orig_field_type = gnu_field_type;
6735       gnu_field_type = maybe_pad_type (gnu_field_type, gnu_size, 0, gnat_field,
6736                                        false, false, definition, true);
6737
6738       /* If a padding record was made, declare it now since it will never be
6739          declared otherwise.  This is necessary to ensure that its subtrees
6740          are properly marked.  */
6741       if (gnu_field_type != orig_field_type
6742           && !DECL_P (TYPE_NAME (gnu_field_type)))
6743         create_type_decl (TYPE_NAME (gnu_field_type), gnu_field_type, true,
6744                           debug_info_p, gnat_field);
6745     }
6746
6747   /* Otherwise (or if there was an error), don't specify a position.  */
6748   else
6749     gnu_pos = NULL_TREE;
6750
6751   gcc_assert (TREE_CODE (gnu_field_type) != RECORD_TYPE
6752               || !TYPE_CONTAINS_TEMPLATE_P (gnu_field_type));
6753
6754   /* Now create the decl for the field.  */
6755   gnu_field
6756     = create_field_decl (gnu_field_id, gnu_field_type, gnu_record_type,
6757                          gnu_size, gnu_pos, packed, Is_Aliased (gnat_field));
6758   Sloc_to_locus (Sloc (gnat_field), &DECL_SOURCE_LOCATION (gnu_field));
6759   DECL_ALIASED_P (gnu_field) = Is_Aliased (gnat_field);
6760   TREE_THIS_VOLATILE (gnu_field) = TREE_SIDE_EFFECTS (gnu_field) = is_volatile;
6761
6762   if (Ekind (gnat_field) == E_Discriminant)
6763     DECL_DISCRIMINANT_NUMBER (gnu_field)
6764       = UI_To_gnu (Discriminant_Number (gnat_field), sizetype);
6765
6766   return gnu_field;
6767 }
6768 \f
6769 /* Return true if at least one member of COMPONENT_LIST needs strict
6770    alignment.  */
6771
6772 static bool
6773 components_need_strict_alignment (Node_Id component_list)
6774 {
6775   Node_Id component_decl;
6776
6777   for (component_decl = First_Non_Pragma (Component_Items (component_list));
6778        Present (component_decl);
6779        component_decl = Next_Non_Pragma (component_decl))
6780     {
6781       Entity_Id gnat_field = Defining_Entity (component_decl);
6782
6783       if (Is_Aliased (gnat_field))
6784         return true;
6785
6786       if (Strict_Alignment (Etype (gnat_field)))
6787         return true;
6788     }
6789
6790   return false;
6791 }
6792
6793 /* Return true if TYPE is a type with variable size or a padding type with a
6794    field of variable size or a record that has a field with such a type.  */
6795
6796 static bool
6797 type_has_variable_size (tree type)
6798 {
6799   tree field;
6800
6801   if (!TREE_CONSTANT (TYPE_SIZE (type)))
6802     return true;
6803
6804   if (TYPE_IS_PADDING_P (type)
6805       && !TREE_CONSTANT (DECL_SIZE (TYPE_FIELDS (type))))
6806     return true;
6807
6808   if (!RECORD_OR_UNION_TYPE_P (type))
6809     return false;
6810
6811   for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
6812     if (type_has_variable_size (TREE_TYPE (field)))
6813       return true;
6814
6815   return false;
6816 }
6817 \f
6818 /* Return true if FIELD is an artificial field.  */
6819
6820 static bool
6821 field_is_artificial (tree field)
6822 {
6823   /* These fields are generated by the front-end proper.  */
6824   if (IDENTIFIER_POINTER (DECL_NAME (field)) [0] == '_')
6825     return true;
6826
6827   /* These fields are generated by gigi.  */
6828   if (DECL_INTERNAL_P (field))
6829     return true;
6830
6831   return false;
6832 }
6833
6834 /* Return true if FIELD is a non-artificial aliased field.  */
6835
6836 static bool
6837 field_is_aliased (tree field)
6838 {
6839   if (field_is_artificial (field))
6840     return false;
6841
6842   return DECL_ALIASED_P (field);
6843 }
6844
6845 /* Return true if FIELD is a non-artificial field with self-referential
6846    size.  */
6847
6848 static bool
6849 field_has_self_size (tree field)
6850 {
6851   if (field_is_artificial (field))
6852     return false;
6853
6854   if (DECL_SIZE (field) && TREE_CODE (DECL_SIZE (field)) == INTEGER_CST)
6855     return false;
6856
6857   return CONTAINS_PLACEHOLDER_P (TYPE_SIZE (TREE_TYPE (field)));
6858 }
6859
6860 /* Return true if FIELD is a non-artificial field with variable size.  */
6861
6862 static bool
6863 field_has_variable_size (tree field)
6864 {
6865   if (field_is_artificial (field))
6866     return false;
6867
6868   if (DECL_SIZE (field) && TREE_CODE (DECL_SIZE (field)) == INTEGER_CST)
6869     return false;
6870
6871   return TREE_CODE (TYPE_SIZE (TREE_TYPE (field))) != INTEGER_CST;
6872 }
6873
6874 /* qsort comparer for the bit positions of two record components.  */
6875
6876 static int
6877 compare_field_bitpos (const PTR rt1, const PTR rt2)
6878 {
6879   const_tree const field1 = * (const_tree const *) rt1;
6880   const_tree const field2 = * (const_tree const *) rt2;
6881   const int ret
6882     = tree_int_cst_compare (bit_position (field1), bit_position (field2));
6883
6884   return ret ? ret : (int) (DECL_UID (field1) - DECL_UID (field2));
6885 }
6886
6887 /* Structure holding information for a given variant.  */
6888 typedef struct vinfo
6889 {
6890   /* The record type of the variant.  */
6891   tree type;
6892
6893   /* The name of the variant.  */
6894   tree name;
6895
6896   /* The qualifier of the variant.  */
6897   tree qual;
6898
6899   /* Whether the variant has a rep clause.  */
6900   bool has_rep;
6901
6902   /* Whether the variant is packed.  */
6903   bool packed;
6904
6905 } vinfo_t;
6906
6907 /* Translate and chain the GNAT_COMPONENT_LIST to the GNU_FIELD_LIST, set the
6908    result as the field list of GNU_RECORD_TYPE and finish it up.  Return true
6909    if GNU_RECORD_TYPE has a rep clause which affects the layout (see below).
6910    When called from gnat_to_gnu_entity during the processing of a record type
6911    definition, the GCC node for the parent, if any, will be the single field
6912    of GNU_RECORD_TYPE and the GCC nodes for the discriminants will be on the
6913    GNU_FIELD_LIST.  The other calls to this function are recursive calls for
6914    the component list of a variant and, in this case, GNU_FIELD_LIST is empty.
6915
6916    PACKED is 1 if this is for a packed record, -1 if this is for a record
6917    with Component_Alignment of Storage_Unit, -2 if this is for a record
6918    with a specified alignment.
6919
6920    DEFINITION is true if we are defining this record type.
6921
6922    CANCEL_ALIGNMENT is true if the alignment should be zeroed before laying
6923    out the record.  This means the alignment only serves to force fields to
6924    be bitfields, but not to require the record to be that aligned.  This is
6925    used for variants.
6926
6927    ALL_REP is true if a rep clause is present for all the fields.
6928
6929    UNCHECKED_UNION is true if we are building this type for a record with a
6930    Pragma Unchecked_Union.
6931
6932    ARTIFICIAL is true if this is a type that was generated by the compiler.
6933
6934    DEBUG_INFO is true if we need to write debug information about the type.
6935
6936    MAYBE_UNUSED is true if this type may be unused in the end; this doesn't
6937    mean that its contents may be unused as well, only the container itself.
6938
6939    REORDER is true if we are permitted to reorder components of this type.
6940
6941    FIRST_FREE_POS, if nonzero, is the first (lowest) free field position in
6942    the outer record type down to this variant level.  It is nonzero only if
6943    all the fields down to this level have a rep clause and ALL_REP is false.
6944
6945    P_GNU_REP_LIST, if nonzero, is a pointer to a list to which each field
6946    with a rep clause is to be added; in this case, that is all that should
6947    be done with such fields and the return value will be false.  */
6948
6949 static bool
6950 components_to_record (tree gnu_record_type, Node_Id gnat_component_list,
6951                       tree gnu_field_list, int packed, bool definition,
6952                       bool cancel_alignment, bool all_rep,
6953                       bool unchecked_union, bool artificial,
6954                       bool debug_info, bool maybe_unused, bool reorder,
6955                       tree first_free_pos, tree *p_gnu_rep_list)
6956 {
6957   bool all_rep_and_size = all_rep && TYPE_SIZE (gnu_record_type);
6958   bool variants_have_rep = all_rep;
6959   bool layout_with_rep = false;
6960   bool has_self_field = false;
6961   bool has_aliased_after_self_field = false;
6962   Node_Id component_decl, variant_part;
6963   tree gnu_field, gnu_next, gnu_last;
6964   tree gnu_variant_part = NULL_TREE;
6965   tree gnu_rep_list = NULL_TREE;
6966   tree gnu_var_list = NULL_TREE;
6967   tree gnu_self_list = NULL_TREE;
6968   tree gnu_zero_list = NULL_TREE;
6969
6970   /* For each component referenced in a component declaration create a GCC
6971      field and add it to the list, skipping pragmas in the GNAT list.  */
6972   gnu_last = tree_last (gnu_field_list);
6973   if (Present (Component_Items (gnat_component_list)))
6974     for (component_decl
6975            = First_Non_Pragma (Component_Items (gnat_component_list));
6976          Present (component_decl);
6977          component_decl = Next_Non_Pragma (component_decl))
6978       {
6979         Entity_Id gnat_field = Defining_Entity (component_decl);
6980         Name_Id gnat_name = Chars (gnat_field);
6981
6982         /* If present, the _Parent field must have been created as the single
6983            field of the record type.  Put it before any other fields.  */
6984         if (gnat_name == Name_uParent)
6985           {
6986             gnu_field = TYPE_FIELDS (gnu_record_type);
6987             gnu_field_list = chainon (gnu_field_list, gnu_field);
6988           }
6989         else
6990           {
6991             gnu_field = gnat_to_gnu_field (gnat_field, gnu_record_type, packed,
6992                                            definition, debug_info);
6993
6994             /* If this is the _Tag field, put it before any other fields.  */
6995             if (gnat_name == Name_uTag)
6996               gnu_field_list = chainon (gnu_field_list, gnu_field);
6997
6998             /* If this is the _Controller field, put it before the other
6999                fields except for the _Tag or _Parent field.  */
7000             else if (gnat_name == Name_uController && gnu_last)
7001               {
7002                 DECL_CHAIN (gnu_field) = DECL_CHAIN (gnu_last);
7003                 DECL_CHAIN (gnu_last) = gnu_field;
7004               }
7005
7006             /* If this is a regular field, put it after the other fields.  */
7007             else
7008               {
7009                 DECL_CHAIN (gnu_field) = gnu_field_list;
7010                 gnu_field_list = gnu_field;
7011                 if (!gnu_last)
7012                   gnu_last = gnu_field;
7013
7014                 /* And record information for the final layout.  */
7015                 if (field_has_self_size (gnu_field))
7016                   has_self_field = true;
7017                 else if (has_self_field && field_is_aliased (gnu_field))
7018                   has_aliased_after_self_field = true;
7019               }
7020           }
7021
7022         save_gnu_tree (gnat_field, gnu_field, false);
7023       }
7024
7025   /* At the end of the component list there may be a variant part.  */
7026   variant_part = Variant_Part (gnat_component_list);
7027
7028   /* We create a QUAL_UNION_TYPE for the variant part since the variants are
7029      mutually exclusive and should go in the same memory.  To do this we need
7030      to treat each variant as a record whose elements are created from the
7031      component list for the variant.  So here we create the records from the
7032      lists for the variants and put them all into the QUAL_UNION_TYPE.
7033      If this is an Unchecked_Union, we make a UNION_TYPE instead or
7034      use GNU_RECORD_TYPE if there are no fields so far.  */
7035   if (Present (variant_part))
7036     {
7037       Node_Id gnat_discr = Name (variant_part), variant;
7038       tree gnu_discr = gnat_to_gnu (gnat_discr);
7039       tree gnu_name = TYPE_IDENTIFIER (gnu_record_type);
7040       tree gnu_var_name
7041         = concat_name (get_identifier (Get_Name_String (Chars (gnat_discr))),
7042                        "XVN");
7043       tree gnu_union_type, gnu_union_name;
7044       tree this_first_free_pos, gnu_variant_list = NULL_TREE;
7045       bool union_field_needs_strict_alignment = false;
7046       auto_vec <vinfo_t, 16> variant_types;
7047       vinfo_t *gnu_variant;
7048       unsigned int variants_align = 0;
7049       unsigned int i;
7050
7051       gnu_union_name
7052         = concat_name (gnu_name, IDENTIFIER_POINTER (gnu_var_name));
7053
7054       /* Reuse the enclosing union if this is an Unchecked_Union whose fields
7055          are all in the variant part, to match the layout of C unions.  There
7056          is an associated check below.  */
7057       if (TREE_CODE (gnu_record_type) == UNION_TYPE)
7058         gnu_union_type = gnu_record_type;
7059       else
7060         {
7061           gnu_union_type
7062             = make_node (unchecked_union ? UNION_TYPE : QUAL_UNION_TYPE);
7063
7064           TYPE_NAME (gnu_union_type) = gnu_union_name;
7065           TYPE_ALIGN (gnu_union_type) = 0;
7066           TYPE_PACKED (gnu_union_type) = TYPE_PACKED (gnu_record_type);
7067         }
7068
7069       /* If all the fields down to this level have a rep clause, find out
7070          whether all the fields at this level also have one.  If so, then
7071          compute the new first free position to be passed downward.  */
7072       this_first_free_pos = first_free_pos;
7073       if (this_first_free_pos)
7074         {
7075           for (gnu_field = gnu_field_list;
7076                gnu_field;
7077                gnu_field = DECL_CHAIN (gnu_field))
7078             if (DECL_FIELD_OFFSET (gnu_field))
7079               {
7080                 tree pos = bit_position (gnu_field);
7081                 if (!tree_int_cst_lt (pos, this_first_free_pos))
7082                   this_first_free_pos
7083                     = size_binop (PLUS_EXPR, pos, DECL_SIZE (gnu_field));
7084               }
7085             else
7086               {
7087                 this_first_free_pos = NULL_TREE;
7088                 break;
7089               }
7090         }
7091
7092       /* We build the variants in two passes.  The bulk of the work is done in
7093          the first pass, that is to say translating the GNAT nodes, building
7094          the container types and computing the associated properties.  However
7095          we cannot finish up the container types during this pass because we
7096          don't know where the variant part will be placed until the end.  */
7097       for (variant = First_Non_Pragma (Variants (variant_part));
7098            Present (variant);
7099            variant = Next_Non_Pragma (variant))
7100         {
7101           tree gnu_variant_type = make_node (RECORD_TYPE);
7102           tree gnu_inner_name, gnu_qual;
7103           bool has_rep;
7104           int field_packed;
7105           vinfo_t vinfo;
7106
7107           Get_Variant_Encoding (variant);
7108           gnu_inner_name = get_identifier_with_length (Name_Buffer, Name_Len);
7109           TYPE_NAME (gnu_variant_type)
7110             = concat_name (gnu_union_name,
7111                            IDENTIFIER_POINTER (gnu_inner_name));
7112
7113           /* Set the alignment of the inner type in case we need to make
7114              inner objects into bitfields, but then clear it out so the
7115              record actually gets only the alignment required.  */
7116           TYPE_ALIGN (gnu_variant_type) = TYPE_ALIGN (gnu_record_type);
7117           TYPE_PACKED (gnu_variant_type) = TYPE_PACKED (gnu_record_type);
7118
7119           /* Similarly, if the outer record has a size specified and all
7120              the fields have a rep clause, we can propagate the size.  */
7121           if (all_rep_and_size)
7122             {
7123               TYPE_SIZE (gnu_variant_type) = TYPE_SIZE (gnu_record_type);
7124               TYPE_SIZE_UNIT (gnu_variant_type)
7125                 = TYPE_SIZE_UNIT (gnu_record_type);
7126             }
7127
7128           /* Add the fields into the record type for the variant.  Note that
7129              we aren't sure to really use it at this point, see below.  */
7130           has_rep
7131             = components_to_record (gnu_variant_type, Component_List (variant),
7132                                     NULL_TREE, packed, definition,
7133                                     !all_rep_and_size, all_rep,
7134                                     unchecked_union,
7135                                     true, debug_info, true, reorder,
7136                                     this_first_free_pos,
7137                                     all_rep || this_first_free_pos
7138                                     ? NULL : &gnu_rep_list);
7139
7140           /* Translate the qualifier and annotate the GNAT node.  */
7141           gnu_qual = choices_to_gnu (gnu_discr, Discrete_Choices (variant));
7142           Set_Present_Expr (variant, annotate_value (gnu_qual));
7143
7144           /* Deal with packedness like in gnat_to_gnu_field.  */
7145           if (components_need_strict_alignment (Component_List (variant)))
7146             {
7147               field_packed = 0;
7148               union_field_needs_strict_alignment = true;
7149             }
7150           else
7151             field_packed
7152               = adjust_packed (gnu_variant_type, gnu_record_type, packed);
7153
7154           /* Push this variant onto the stack for the second pass.  */
7155           vinfo.type = gnu_variant_type;
7156           vinfo.name = gnu_inner_name;
7157           vinfo.qual = gnu_qual;
7158           vinfo.has_rep = has_rep;
7159           vinfo.packed = field_packed;
7160           variant_types.safe_push (vinfo);
7161
7162           /* Compute the global properties that will determine the placement of
7163              the variant part.  */
7164           variants_have_rep |= has_rep;
7165           if (!field_packed && TYPE_ALIGN (gnu_variant_type) > variants_align)
7166             variants_align = TYPE_ALIGN (gnu_variant_type);
7167         }
7168
7169       /* Round up the first free position to the alignment of the variant part
7170          for the variants without rep clause.  This will guarantee a consistent
7171          layout independently of the placement of the variant part.  */
7172       if (variants_have_rep && variants_align > 0 && this_first_free_pos)
7173         this_first_free_pos = round_up (this_first_free_pos, variants_align);
7174
7175       /* In the second pass, the container types are adjusted if necessary and
7176          finished up, then the corresponding fields of the variant part are
7177          built with their qualifier, unless this is an unchecked union.  */
7178       FOR_EACH_VEC_ELT (variant_types, i, gnu_variant)
7179         {
7180           tree gnu_variant_type = gnu_variant->type;
7181           tree gnu_field_list = TYPE_FIELDS (gnu_variant_type);
7182
7183           /* If this is an Unchecked_Union whose fields are all in the variant
7184              part and we have a single field with no representation clause or
7185              placed at offset zero, use the field directly to match the layout
7186              of C unions.  */
7187           if (TREE_CODE (gnu_record_type) == UNION_TYPE
7188               && gnu_field_list
7189               && !DECL_CHAIN (gnu_field_list)
7190               && (!DECL_FIELD_OFFSET (gnu_field_list)
7191                   || integer_zerop (bit_position (gnu_field_list))))
7192             {
7193               gnu_field = gnu_field_list;
7194               DECL_CONTEXT (gnu_field) = gnu_record_type;
7195             }
7196           else
7197             {
7198               /* Finalize the variant type now.  We used to throw away empty
7199                  record types but we no longer do that because we need them to
7200                  generate complete debug info for the variant; otherwise, the
7201                  union type definition will be lacking the fields associated
7202                  with these empty variants.  */
7203               if (gnu_field_list && variants_have_rep && !gnu_variant->has_rep)
7204                 {
7205                   /* The variant part will be at offset 0 so we need to ensure
7206                      that the fields are laid out starting from the first free
7207                      position at this level.  */
7208                   tree gnu_rep_type = make_node (RECORD_TYPE);
7209                   tree gnu_rep_part;
7210                   finish_record_type (gnu_rep_type, NULL_TREE, 0, debug_info);
7211                   gnu_rep_part
7212                     = create_rep_part (gnu_rep_type, gnu_variant_type,
7213                                        this_first_free_pos);
7214                   DECL_CHAIN (gnu_rep_part) = gnu_field_list;
7215                   gnu_field_list = gnu_rep_part;
7216                   finish_record_type (gnu_variant_type, gnu_field_list, 0,
7217                                       false);
7218                 }
7219
7220               if (debug_info)
7221                 rest_of_record_type_compilation (gnu_variant_type);
7222               create_type_decl (TYPE_NAME (gnu_variant_type), gnu_variant_type,
7223                                 true, debug_info, gnat_component_list);
7224
7225               gnu_field
7226                 = create_field_decl (gnu_variant->name, gnu_variant_type,
7227                                      gnu_union_type,
7228                                      all_rep_and_size
7229                                      ? TYPE_SIZE (gnu_variant_type) : 0,
7230                                      variants_have_rep ? bitsize_zero_node : 0,
7231                                      gnu_variant->packed, 0);
7232
7233               DECL_INTERNAL_P (gnu_field) = 1;
7234
7235               if (!unchecked_union)
7236                 DECL_QUALIFIER (gnu_field) = gnu_variant->qual;
7237             }
7238
7239           DECL_CHAIN (gnu_field) = gnu_variant_list;
7240           gnu_variant_list = gnu_field;
7241         }
7242
7243       /* Only make the QUAL_UNION_TYPE if there are non-empty variants.  */
7244       if (gnu_variant_list)
7245         {
7246           int union_field_packed;
7247
7248           if (all_rep_and_size)
7249             {
7250               TYPE_SIZE (gnu_union_type) = TYPE_SIZE (gnu_record_type);
7251               TYPE_SIZE_UNIT (gnu_union_type)
7252                 = TYPE_SIZE_UNIT (gnu_record_type);
7253             }
7254
7255           finish_record_type (gnu_union_type, nreverse (gnu_variant_list),
7256                               all_rep_and_size ? 1 : 0, debug_info);
7257
7258           /* If GNU_UNION_TYPE is our record type, it means we must have an
7259              Unchecked_Union with no fields.  Verify that and, if so, just
7260              return.  */
7261           if (gnu_union_type == gnu_record_type)
7262             {
7263               gcc_assert (unchecked_union
7264                           && !gnu_field_list
7265                           && !gnu_rep_list);
7266               return variants_have_rep;
7267             }
7268
7269           create_type_decl (TYPE_NAME (gnu_union_type), gnu_union_type, true,
7270                             debug_info, gnat_component_list);
7271
7272           /* Deal with packedness like in gnat_to_gnu_field.  */
7273           if (union_field_needs_strict_alignment)
7274             union_field_packed = 0;
7275           else
7276             union_field_packed
7277               = adjust_packed (gnu_union_type, gnu_record_type, packed);
7278
7279           gnu_variant_part
7280             = create_field_decl (gnu_var_name, gnu_union_type, gnu_record_type,
7281                                  all_rep_and_size
7282                                  ? TYPE_SIZE (gnu_union_type) : 0,
7283                                  variants_have_rep ? bitsize_zero_node : 0,
7284                                  union_field_packed, 0);
7285
7286           DECL_INTERNAL_P (gnu_variant_part) = 1;
7287         }
7288     }
7289
7290   /* Scan GNU_FIELD_LIST and see if any fields have rep clauses and, if we are
7291      permitted to reorder components, self-referential sizes or variable sizes.
7292      If they do, pull them out and put them onto the appropriate list.  We have
7293      to do this in a separate pass since we want to handle the discriminants
7294      but can't play with them until we've used them in debugging data above.
7295
7296      Similarly, pull out the fields with zero size and no rep clause, as they
7297      would otherwise modify the layout and thus very likely run afoul of the
7298      Ada semantics, which are different from those of C here.
7299
7300      ??? If we reorder them, debugging information will be wrong but there is
7301      nothing that can be done about this at the moment.  */
7302   gnu_last = NULL_TREE;
7303
7304 #define MOVE_FROM_FIELD_LIST_TO(LIST)   \
7305   do {                                  \
7306     if (gnu_last)                       \
7307       DECL_CHAIN (gnu_last) = gnu_next; \
7308     else                                \
7309       gnu_field_list = gnu_next;        \
7310                                         \
7311     DECL_CHAIN (gnu_field) = (LIST);    \
7312     (LIST) = gnu_field;                 \
7313   } while (0)
7314
7315   for (gnu_field = gnu_field_list; gnu_field; gnu_field = gnu_next)
7316     {
7317       gnu_next = DECL_CHAIN (gnu_field);
7318
7319       if (DECL_FIELD_OFFSET (gnu_field))
7320         {
7321           MOVE_FROM_FIELD_LIST_TO (gnu_rep_list);
7322           continue;
7323         }
7324
7325       if ((reorder || has_aliased_after_self_field)
7326           && field_has_self_size (gnu_field))
7327         {
7328           MOVE_FROM_FIELD_LIST_TO (gnu_self_list);
7329           continue;
7330         }
7331
7332       if (reorder && field_has_variable_size (gnu_field))
7333         {
7334           MOVE_FROM_FIELD_LIST_TO (gnu_var_list);
7335           continue;
7336         }
7337
7338       if (DECL_SIZE (gnu_field) && integer_zerop (DECL_SIZE (gnu_field)))
7339         {
7340           DECL_FIELD_OFFSET (gnu_field) = size_zero_node;
7341           SET_DECL_OFFSET_ALIGN (gnu_field, BIGGEST_ALIGNMENT);
7342           DECL_FIELD_BIT_OFFSET (gnu_field) = bitsize_zero_node;
7343           if (field_is_aliased (gnu_field))
7344             TYPE_ALIGN (gnu_record_type)
7345               = MAX (TYPE_ALIGN (gnu_record_type),
7346                      TYPE_ALIGN (TREE_TYPE (gnu_field)));
7347           MOVE_FROM_FIELD_LIST_TO (gnu_zero_list);
7348           continue;
7349         }
7350
7351       gnu_last = gnu_field;
7352     }
7353
7354 #undef MOVE_FROM_FIELD_LIST_TO
7355
7356   gnu_field_list = nreverse (gnu_field_list);
7357
7358   /* If permitted, we reorder the fields as follows:
7359
7360        1) all fixed length fields,
7361        2) all fields whose length doesn't depend on discriminants,
7362        3) all fields whose length depends on discriminants,
7363        4) the variant part,
7364
7365      within the record and within each variant recursively.  */
7366   if (reorder)
7367     gnu_field_list
7368       = chainon (gnu_field_list, chainon (gnu_var_list, gnu_self_list));
7369
7370   /* Otherwise, if there is an aliased field placed after a field whose length
7371      depends on discriminants, we put all the fields of the latter sort, last.
7372      We need to do this in case an object of this record type is mutable.  */
7373   else if (has_aliased_after_self_field)
7374     gnu_field_list = chainon (gnu_field_list, gnu_self_list);
7375
7376   /* If P_REP_LIST is nonzero, this means that we are asked to move the fields
7377      in our REP list to the previous level because this level needs them in
7378      order to do a correct layout, i.e. avoid having overlapping fields.  */
7379   if (p_gnu_rep_list && gnu_rep_list)
7380     *p_gnu_rep_list = chainon (*p_gnu_rep_list, gnu_rep_list);
7381
7382   /* Otherwise, sort the fields by bit position and put them into their own
7383      record, before the others, if we also have fields without rep clause.  */
7384   else if (gnu_rep_list)
7385     {
7386       tree gnu_rep_type, gnu_rep_part;
7387       int i, len = list_length (gnu_rep_list);
7388       tree *gnu_arr = XALLOCAVEC (tree, len);
7389
7390       /* If all the fields have a rep clause, we can do a flat layout.  */
7391       layout_with_rep = !gnu_field_list
7392                         && (!gnu_variant_part || variants_have_rep);
7393       gnu_rep_type
7394         = layout_with_rep ? gnu_record_type : make_node (RECORD_TYPE);
7395
7396       for (gnu_field = gnu_rep_list, i = 0;
7397            gnu_field;
7398            gnu_field = DECL_CHAIN (gnu_field), i++)
7399         gnu_arr[i] = gnu_field;
7400
7401       qsort (gnu_arr, len, sizeof (tree), compare_field_bitpos);
7402
7403       /* Put the fields in the list in order of increasing position, which
7404          means we start from the end.  */
7405       gnu_rep_list = NULL_TREE;
7406       for (i = len - 1; i >= 0; i--)
7407         {
7408           DECL_CHAIN (gnu_arr[i]) = gnu_rep_list;
7409           gnu_rep_list = gnu_arr[i];
7410           DECL_CONTEXT (gnu_arr[i]) = gnu_rep_type;
7411         }
7412
7413       if (layout_with_rep)
7414         gnu_field_list = gnu_rep_list;
7415       else
7416         {
7417           finish_record_type (gnu_rep_type, gnu_rep_list, 1, debug_info);
7418
7419           /* If FIRST_FREE_POS is nonzero, we need to ensure that the fields
7420              without rep clause are laid out starting from this position.
7421              Therefore, we force it as a minimal size on the REP part.  */
7422           gnu_rep_part
7423             = create_rep_part (gnu_rep_type, gnu_record_type, first_free_pos);
7424
7425           /* Chain the REP part at the beginning of the field list.  */
7426           DECL_CHAIN (gnu_rep_part) = gnu_field_list;
7427           gnu_field_list = gnu_rep_part;
7428         }
7429     }
7430
7431   /* Chain the variant part at the end of the field list.  */
7432   if (gnu_variant_part)
7433     gnu_field_list = chainon (gnu_field_list, gnu_variant_part);
7434
7435   if (cancel_alignment)
7436     TYPE_ALIGN (gnu_record_type) = 0;
7437
7438   TYPE_ARTIFICIAL (gnu_record_type) = artificial;
7439
7440   finish_record_type (gnu_record_type, gnu_field_list, layout_with_rep ? 1 : 0,
7441                       debug_info && !maybe_unused);
7442
7443   /* Chain the fields with zero size at the beginning of the field list.  */
7444   if (gnu_zero_list)
7445     TYPE_FIELDS (gnu_record_type)
7446       = chainon (gnu_zero_list, TYPE_FIELDS (gnu_record_type));
7447
7448   return (gnu_rep_list && !p_gnu_rep_list) || variants_have_rep;
7449 }
7450 \f
7451 /* Given GNU_SIZE, a GCC tree representing a size, return a Uint to be
7452    placed into an Esize, Component_Bit_Offset, or Component_Size value
7453    in the GNAT tree.  */
7454
7455 static Uint
7456 annotate_value (tree gnu_size)
7457 {
7458   TCode tcode;
7459   Node_Ref_Or_Val ops[3], ret, pre_op1 = No_Uint;
7460   struct tree_int_map in;
7461   int i;
7462
7463   /* See if we've already saved the value for this node.  */
7464   if (EXPR_P (gnu_size))
7465     {
7466       struct tree_int_map *e;
7467
7468       in.base.from = gnu_size;
7469       e = annotate_value_cache->find (&in);
7470
7471       if (e)
7472         return (Node_Ref_Or_Val) e->to;
7473     }
7474   else
7475     in.base.from = NULL_TREE;
7476
7477   /* If we do not return inside this switch, TCODE will be set to the
7478      code to use for a Create_Node operand and LEN (set above) will be
7479      the number of recursive calls for us to make.  */
7480
7481   switch (TREE_CODE (gnu_size))
7482     {
7483     case INTEGER_CST:
7484       return TREE_OVERFLOW (gnu_size) ? No_Uint : UI_From_gnu (gnu_size);
7485
7486     case COMPONENT_REF:
7487       /* The only case we handle here is a simple discriminant reference.  */
7488       if (DECL_DISCRIMINANT_NUMBER (TREE_OPERAND (gnu_size, 1)))
7489         {
7490           tree n = DECL_DISCRIMINANT_NUMBER (TREE_OPERAND (gnu_size, 1));
7491
7492           /* Climb up the chain of successive extensions, if any.  */
7493           while (TREE_CODE (TREE_OPERAND (gnu_size, 0)) == COMPONENT_REF
7494                  && DECL_NAME (TREE_OPERAND (TREE_OPERAND (gnu_size, 0), 1))
7495                     == parent_name_id)
7496             gnu_size = TREE_OPERAND (gnu_size, 0);
7497
7498           if (TREE_CODE (TREE_OPERAND (gnu_size, 0)) == PLACEHOLDER_EXPR)
7499             return
7500               Create_Node (Discrim_Val, annotate_value (n), No_Uint, No_Uint);
7501         }
7502
7503       return No_Uint;
7504
7505     CASE_CONVERT:   case NON_LVALUE_EXPR:
7506       return annotate_value (TREE_OPERAND (gnu_size, 0));
7507
7508       /* Now just list the operations we handle.  */
7509     case COND_EXPR:             tcode = Cond_Expr; break;
7510     case PLUS_EXPR:             tcode = Plus_Expr; break;
7511     case MINUS_EXPR:            tcode = Minus_Expr; break;
7512     case MULT_EXPR:             tcode = Mult_Expr; break;
7513     case TRUNC_DIV_EXPR:        tcode = Trunc_Div_Expr; break;
7514     case CEIL_DIV_EXPR:         tcode = Ceil_Div_Expr; break;
7515     case FLOOR_DIV_EXPR:        tcode = Floor_Div_Expr; break;
7516     case TRUNC_MOD_EXPR:        tcode = Trunc_Mod_Expr; break;
7517     case CEIL_MOD_EXPR:         tcode = Ceil_Mod_Expr; break;
7518     case FLOOR_MOD_EXPR:        tcode = Floor_Mod_Expr; break;
7519     case EXACT_DIV_EXPR:        tcode = Exact_Div_Expr; break;
7520     case NEGATE_EXPR:           tcode = Negate_Expr; break;
7521     case MIN_EXPR:              tcode = Min_Expr; break;
7522     case MAX_EXPR:              tcode = Max_Expr; break;
7523     case ABS_EXPR:              tcode = Abs_Expr; break;
7524     case TRUTH_ANDIF_EXPR:      tcode = Truth_Andif_Expr; break;
7525     case TRUTH_ORIF_EXPR:       tcode = Truth_Orif_Expr; break;
7526     case TRUTH_AND_EXPR:        tcode = Truth_And_Expr; break;
7527     case TRUTH_OR_EXPR:         tcode = Truth_Or_Expr; break;
7528     case TRUTH_XOR_EXPR:        tcode = Truth_Xor_Expr; break;
7529     case TRUTH_NOT_EXPR:        tcode = Truth_Not_Expr; break;
7530     case LT_EXPR:               tcode = Lt_Expr; break;
7531     case LE_EXPR:               tcode = Le_Expr; break;
7532     case GT_EXPR:               tcode = Gt_Expr; break;
7533     case GE_EXPR:               tcode = Ge_Expr; break;
7534     case EQ_EXPR:               tcode = Eq_Expr; break;
7535     case NE_EXPR:               tcode = Ne_Expr; break;
7536
7537     case BIT_AND_EXPR:
7538       tcode = Bit_And_Expr;
7539       /* For negative values in sizetype, build NEGATE_EXPR of the opposite.
7540          Such values appear in expressions with aligning patterns.  Note that,
7541          since sizetype is unsigned, we have to jump through some hoops.   */
7542       if (TREE_CODE (TREE_OPERAND (gnu_size, 1)) == INTEGER_CST)
7543         {
7544           tree op1 = TREE_OPERAND (gnu_size, 1);
7545           wide_int signed_op1 = wi::sext (op1, TYPE_PRECISION (sizetype));
7546           if (wi::neg_p (signed_op1))
7547             {
7548               op1 = wide_int_to_tree (sizetype, wi::neg (signed_op1));
7549               pre_op1 = annotate_value (build1 (NEGATE_EXPR, sizetype, op1));
7550             }
7551         }
7552       break;
7553
7554     case CALL_EXPR:
7555       /* In regular mode, inline back only if symbolic annotation is requested
7556          in order to avoid memory explosion on big discriminated record types.
7557          But not in ASIS mode, as symbolic annotation is required for DDA.  */
7558       if (List_Representation_Info == 3 || type_annotate_only)
7559         {
7560           tree t = maybe_inline_call_in_expr (gnu_size);
7561           if (t)
7562             return annotate_value (t);
7563         }
7564       else
7565         return Uint_Minus_1;
7566
7567       /* Fall through... */
7568
7569     default:
7570       return No_Uint;
7571     }
7572
7573   /* Now get each of the operands that's relevant for this code.  If any
7574      cannot be expressed as a repinfo node, say we can't.  */
7575   for (i = 0; i < 3; i++)
7576     ops[i] = No_Uint;
7577
7578   for (i = 0; i < TREE_CODE_LENGTH (TREE_CODE (gnu_size)); i++)
7579     {
7580       if (i == 1 && pre_op1 != No_Uint)
7581         ops[i] = pre_op1;
7582       else
7583         ops[i] = annotate_value (TREE_OPERAND (gnu_size, i));
7584       if (ops[i] == No_Uint)
7585         return No_Uint;
7586     }
7587
7588   ret = Create_Node (tcode, ops[0], ops[1], ops[2]);
7589
7590   /* Save the result in the cache.  */
7591   if (in.base.from)
7592     {
7593       struct tree_int_map **h;
7594       /* We can't assume the hash table data hasn't moved since the initial
7595          look up, so we have to search again.  Allocating and inserting an
7596          entry at that point would be an alternative, but then we'd better
7597          discard the entry if we decided not to cache it.  */
7598       h = annotate_value_cache->find_slot (&in, INSERT);
7599       gcc_assert (!*h);
7600       *h = ggc_alloc<tree_int_map> ();
7601       (*h)->base.from = gnu_size;
7602       (*h)->to = ret;
7603     }
7604
7605   return ret;
7606 }
7607
7608 /* Given GNAT_ENTITY, an object (constant, variable, parameter, exception)
7609    and GNU_TYPE, its corresponding GCC type, set Esize and Alignment to the
7610    size and alignment used by Gigi.  Prefer SIZE over TYPE_SIZE if non-null.
7611    BY_REF is true if the object is used by reference.  */
7612
7613 void
7614 annotate_object (Entity_Id gnat_entity, tree gnu_type, tree size, bool by_ref)
7615 {
7616   if (by_ref)
7617     {
7618       if (TYPE_IS_FAT_POINTER_P (gnu_type))
7619         gnu_type = TYPE_UNCONSTRAINED_ARRAY (gnu_type);
7620       else
7621         gnu_type = TREE_TYPE (gnu_type);
7622     }
7623
7624   if (Unknown_Esize (gnat_entity))
7625     {
7626       if (TREE_CODE (gnu_type) == RECORD_TYPE
7627           && TYPE_CONTAINS_TEMPLATE_P (gnu_type))
7628         size = TYPE_SIZE (TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (gnu_type))));
7629       else if (!size)
7630         size = TYPE_SIZE (gnu_type);
7631
7632       if (size)
7633         Set_Esize (gnat_entity, annotate_value (size));
7634     }
7635
7636   if (Unknown_Alignment (gnat_entity))
7637     Set_Alignment (gnat_entity,
7638                    UI_From_Int (TYPE_ALIGN (gnu_type) / BITS_PER_UNIT));
7639 }
7640
7641 /* Return first element of field list whose TREE_PURPOSE is the same as ELEM.
7642    Return NULL_TREE if there is no such element in the list.  */
7643
7644 static tree
7645 purpose_member_field (const_tree elem, tree list)
7646 {
7647   while (list)
7648     {
7649       tree field = TREE_PURPOSE (list);
7650       if (SAME_FIELD_P (field, elem))
7651         return list;
7652       list = TREE_CHAIN (list);
7653     }
7654   return NULL_TREE;
7655 }
7656
7657 /* Given GNAT_ENTITY, a record type, and GNU_TYPE, its corresponding GCC type,
7658    set Component_Bit_Offset and Esize of the components to the position and
7659    size used by Gigi.  */
7660
7661 static void
7662 annotate_rep (Entity_Id gnat_entity, tree gnu_type)
7663 {
7664   Entity_Id gnat_field;
7665   tree gnu_list;
7666
7667   /* We operate by first making a list of all fields and their position (we
7668      can get the size easily) and then update all the sizes in the tree.  */
7669   gnu_list
7670     = build_position_list (gnu_type, false, size_zero_node, bitsize_zero_node,
7671                            BIGGEST_ALIGNMENT, NULL_TREE);
7672
7673   for (gnat_field = First_Entity (gnat_entity);
7674        Present (gnat_field);
7675        gnat_field = Next_Entity (gnat_field))
7676     if (Ekind (gnat_field) == E_Component
7677         || (Ekind (gnat_field) == E_Discriminant
7678             && !Is_Unchecked_Union (Scope (gnat_field))))
7679       {
7680         tree t = purpose_member_field (gnat_to_gnu_field_decl (gnat_field),
7681                                        gnu_list);
7682         if (t)
7683           {
7684             tree parent_offset;
7685
7686             /* If we are just annotating types and the type is tagged, the tag
7687                and the parent components are not generated by the front-end so
7688                we need to add the appropriate offset to each component without
7689                representation clause.  */
7690             if (type_annotate_only
7691                 && Is_Tagged_Type (gnat_entity)
7692                 && No (Component_Clause (gnat_field)))
7693               {
7694                 /* For a component appearing in the current extension, the
7695                    offset is the size of the parent.  */
7696                 if (Is_Derived_Type (gnat_entity)
7697                     && Original_Record_Component (gnat_field) == gnat_field)
7698                   parent_offset
7699                     = UI_To_gnu (Esize (Etype (Base_Type (gnat_entity))),
7700                                  bitsizetype);
7701                 else
7702                   parent_offset = bitsize_int (POINTER_SIZE);
7703
7704                 if (TYPE_FIELDS (gnu_type))
7705                   parent_offset
7706                     = round_up (parent_offset,
7707                                 DECL_ALIGN (TYPE_FIELDS (gnu_type)));
7708               }
7709             else
7710               parent_offset = bitsize_zero_node;
7711
7712             Set_Component_Bit_Offset
7713               (gnat_field,
7714                annotate_value
7715                  (size_binop (PLUS_EXPR,
7716                               bit_from_pos (TREE_VEC_ELT (TREE_VALUE (t), 0),
7717                                             TREE_VEC_ELT (TREE_VALUE (t), 2)),
7718                               parent_offset)));
7719
7720             Set_Esize (gnat_field,
7721                        annotate_value (DECL_SIZE (TREE_PURPOSE (t))));
7722           }
7723         else if (Is_Tagged_Type (gnat_entity) && Is_Derived_Type (gnat_entity))
7724           {
7725             /* If there is no entry, this is an inherited component whose
7726                position is the same as in the parent type.  */
7727             Set_Component_Bit_Offset
7728               (gnat_field,
7729                Component_Bit_Offset (Original_Record_Component (gnat_field)));
7730
7731             Set_Esize (gnat_field,
7732                        Esize (Original_Record_Component (gnat_field)));
7733           }
7734       }
7735 }
7736 \f
7737 /* Scan all fields in GNU_TYPE and return a TREE_LIST where TREE_PURPOSE is
7738    the FIELD_DECL and TREE_VALUE a TREE_VEC containing the byte position, the
7739    value to be placed into DECL_OFFSET_ALIGN and the bit position.  The list
7740    of fields is flattened, except for variant parts if DO_NOT_FLATTEN_VARIANT
7741    is set to true.  GNU_POS is to be added to the position, GNU_BITPOS to the
7742    bit position, OFFSET_ALIGN is the present offset alignment.  GNU_LIST is a
7743    pre-existing list to be chained to the newly created entries.  */
7744
7745 static tree
7746 build_position_list (tree gnu_type, bool do_not_flatten_variant, tree gnu_pos,
7747                      tree gnu_bitpos, unsigned int offset_align, tree gnu_list)
7748 {
7749   tree gnu_field;
7750
7751   for (gnu_field = TYPE_FIELDS (gnu_type);
7752        gnu_field;
7753        gnu_field = DECL_CHAIN (gnu_field))
7754     {
7755       tree gnu_our_bitpos = size_binop (PLUS_EXPR, gnu_bitpos,
7756                                         DECL_FIELD_BIT_OFFSET (gnu_field));
7757       tree gnu_our_offset = size_binop (PLUS_EXPR, gnu_pos,
7758                                         DECL_FIELD_OFFSET (gnu_field));
7759       unsigned int our_offset_align
7760         = MIN (offset_align, DECL_OFFSET_ALIGN (gnu_field));
7761       tree v = make_tree_vec (3);
7762
7763       TREE_VEC_ELT (v, 0) = gnu_our_offset;
7764       TREE_VEC_ELT (v, 1) = size_int (our_offset_align);
7765       TREE_VEC_ELT (v, 2) = gnu_our_bitpos;
7766       gnu_list = tree_cons (gnu_field, v, gnu_list);
7767
7768       /* Recurse on internal fields, flattening the nested fields except for
7769          those in the variant part, if requested.  */
7770       if (DECL_INTERNAL_P (gnu_field))
7771         {
7772           tree gnu_field_type = TREE_TYPE (gnu_field);
7773           if (do_not_flatten_variant
7774               && TREE_CODE (gnu_field_type) == QUAL_UNION_TYPE)
7775             gnu_list
7776               = build_position_list (gnu_field_type, do_not_flatten_variant,
7777                                      size_zero_node, bitsize_zero_node,
7778                                      BIGGEST_ALIGNMENT, gnu_list);
7779           else
7780             gnu_list
7781               = build_position_list (gnu_field_type, do_not_flatten_variant,
7782                                      gnu_our_offset, gnu_our_bitpos,
7783                                      our_offset_align, gnu_list);
7784         }
7785     }
7786
7787   return gnu_list;
7788 }
7789
7790 /* Return a list describing the substitutions needed to reflect the
7791    discriminant substitutions from GNAT_TYPE to GNAT_SUBTYPE.  They can
7792    be in any order.  The values in an element of the list are in the form
7793    of operands to SUBSTITUTE_IN_EXPR.  DEFINITION is true if this is for
7794    a definition of GNAT_SUBTYPE.  */
7795
7796 static vec<subst_pair>
7797 build_subst_list (Entity_Id gnat_subtype, Entity_Id gnat_type, bool definition)
7798 {
7799   vec<subst_pair> gnu_list = vNULL;
7800   Entity_Id gnat_discrim;
7801   Node_Id gnat_constr;
7802
7803   for (gnat_discrim = First_Stored_Discriminant (gnat_type),
7804        gnat_constr = First_Elmt (Stored_Constraint (gnat_subtype));
7805        Present (gnat_discrim);
7806        gnat_discrim = Next_Stored_Discriminant (gnat_discrim),
7807        gnat_constr = Next_Elmt (gnat_constr))
7808     /* Ignore access discriminants.  */
7809     if (!Is_Access_Type (Etype (Node (gnat_constr))))
7810       {
7811         tree gnu_field = gnat_to_gnu_field_decl (gnat_discrim);
7812         tree replacement = convert (TREE_TYPE (gnu_field),
7813                                     elaborate_expression
7814                                     (Node (gnat_constr), gnat_subtype,
7815                                      get_entity_char (gnat_discrim),
7816                                      definition, true, false));
7817         subst_pair s = {gnu_field, replacement};
7818         gnu_list.safe_push (s);
7819       }
7820
7821   return gnu_list;
7822 }
7823
7824 /* Scan all fields in QUAL_UNION_TYPE and return a list describing the
7825    variants of QUAL_UNION_TYPE that are still relevant after applying
7826    the substitutions described in SUBST_LIST.  GNU_LIST is a pre-existing
7827    list to be prepended to the newly created entries.  */
7828
7829 static vec<variant_desc>
7830 build_variant_list (tree qual_union_type, vec<subst_pair> subst_list,
7831                     vec<variant_desc> gnu_list)
7832 {
7833   tree gnu_field;
7834
7835   for (gnu_field = TYPE_FIELDS (qual_union_type);
7836        gnu_field;
7837        gnu_field = DECL_CHAIN (gnu_field))
7838     {
7839       tree qual = DECL_QUALIFIER (gnu_field);
7840       unsigned int i;
7841       subst_pair *s;
7842
7843       FOR_EACH_VEC_ELT (subst_list, i, s)
7844         qual = SUBSTITUTE_IN_EXPR (qual, s->discriminant, s->replacement);
7845
7846       /* If the new qualifier is not unconditionally false, its variant may
7847          still be accessed.  */
7848       if (!integer_zerop (qual))
7849         {
7850           tree variant_type = TREE_TYPE (gnu_field), variant_subpart;
7851           variant_desc v = {variant_type, gnu_field, qual, NULL_TREE};
7852
7853           gnu_list.safe_push (v);
7854
7855           /* Recurse on the variant subpart of the variant, if any.  */
7856           variant_subpart = get_variant_part (variant_type);
7857           if (variant_subpart)
7858             gnu_list = build_variant_list (TREE_TYPE (variant_subpart),
7859                                            subst_list, gnu_list);
7860
7861           /* If the new qualifier is unconditionally true, the subsequent
7862              variants cannot be accessed.  */
7863           if (integer_onep (qual))
7864             break;
7865         }
7866     }
7867
7868   return gnu_list;
7869 }
7870 \f
7871 /* UINT_SIZE is a Uint giving the specified size for an object of GNU_TYPE
7872    corresponding to GNAT_OBJECT.  If the size is valid, return an INTEGER_CST
7873    corresponding to its value.  Otherwise, return NULL_TREE.  KIND is set to
7874    VAR_DECL if we are specifying the size of an object, TYPE_DECL for the
7875    size of a type, and FIELD_DECL for the size of a field.  COMPONENT_P is
7876    true if we are being called to process the Component_Size of GNAT_OBJECT;
7877    this is used only for error messages.  ZERO_OK is true if a size of zero
7878    is permitted; if ZERO_OK is false, it means that a size of zero should be
7879    treated as an unspecified size.  */
7880
7881 static tree
7882 validate_size (Uint uint_size, tree gnu_type, Entity_Id gnat_object,
7883                enum tree_code kind, bool component_p, bool zero_ok)
7884 {
7885   Node_Id gnat_error_node;
7886   tree type_size, size;
7887
7888   /* Return 0 if no size was specified.  */
7889   if (uint_size == No_Uint)
7890     return NULL_TREE;
7891
7892   /* Ignore a negative size since that corresponds to our back-annotation.  */
7893   if (UI_Lt (uint_size, Uint_0))
7894     return NULL_TREE;
7895
7896   /* Find the node to use for error messages.  */
7897   if ((Ekind (gnat_object) == E_Component
7898        || Ekind (gnat_object) == E_Discriminant)
7899       && Present (Component_Clause (gnat_object)))
7900     gnat_error_node = Last_Bit (Component_Clause (gnat_object));
7901   else if (Present (Size_Clause (gnat_object)))
7902     gnat_error_node = Expression (Size_Clause (gnat_object));
7903   else
7904     gnat_error_node = gnat_object;
7905
7906   /* Get the size as an INTEGER_CST.  Issue an error if a size was specified
7907      but cannot be represented in bitsizetype.  */
7908   size = UI_To_gnu (uint_size, bitsizetype);
7909   if (TREE_OVERFLOW (size))
7910     {
7911       if (component_p)
7912         post_error_ne ("component size for& is too large", gnat_error_node,
7913                        gnat_object);
7914       else
7915         post_error_ne ("size for& is too large", gnat_error_node,
7916                        gnat_object);
7917       return NULL_TREE;
7918     }
7919
7920   /* Ignore a zero size if it is not permitted.  */
7921   if (!zero_ok && integer_zerop (size))
7922     return NULL_TREE;
7923
7924   /* The size of objects is always a multiple of a byte.  */
7925   if (kind == VAR_DECL
7926       && !integer_zerop (size_binop (TRUNC_MOD_EXPR, size, bitsize_unit_node)))
7927     {
7928       if (component_p)
7929         post_error_ne ("component size for& is not a multiple of Storage_Unit",
7930                        gnat_error_node, gnat_object);
7931       else
7932         post_error_ne ("size for& is not a multiple of Storage_Unit",
7933                        gnat_error_node, gnat_object);
7934       return NULL_TREE;
7935     }
7936
7937   /* If this is an integral type or a packed array type, the front-end has
7938      already verified the size, so we need not do it here (which would mean
7939      checking against the bounds).  However, if this is an aliased object,
7940      it may not be smaller than the type of the object.  */
7941   if ((INTEGRAL_TYPE_P (gnu_type) || TYPE_IS_PACKED_ARRAY_TYPE_P (gnu_type))
7942       && !(kind == VAR_DECL && Is_Aliased (gnat_object)))
7943     return size;
7944
7945   /* If the object is a record that contains a template, add the size of the
7946      template to the specified size.  */
7947   if (TREE_CODE (gnu_type) == RECORD_TYPE
7948       && TYPE_CONTAINS_TEMPLATE_P (gnu_type))
7949     size = size_binop (PLUS_EXPR, DECL_SIZE (TYPE_FIELDS (gnu_type)), size);
7950
7951   if (kind == VAR_DECL
7952       /* If a type needs strict alignment, a component of this type in
7953          a packed record cannot be packed and thus uses the type size.  */
7954       || (kind == TYPE_DECL && Strict_Alignment (gnat_object)))
7955     type_size = TYPE_SIZE (gnu_type);
7956   else
7957     type_size = rm_size (gnu_type);
7958
7959   /* Modify the size of a discriminated type to be the maximum size.  */
7960   if (type_size && CONTAINS_PLACEHOLDER_P (type_size))
7961     type_size = max_size (type_size, true);
7962
7963   /* If this is an access type or a fat pointer, the minimum size is that given
7964      by the smallest integral mode that's valid for pointers.  */
7965   if (TREE_CODE (gnu_type) == POINTER_TYPE || TYPE_IS_FAT_POINTER_P (gnu_type))
7966     {
7967       machine_mode p_mode = GET_CLASS_NARROWEST_MODE (MODE_INT);
7968       while (!targetm.valid_pointer_mode (p_mode))
7969         p_mode = GET_MODE_WIDER_MODE (p_mode);
7970       type_size = bitsize_int (GET_MODE_BITSIZE (p_mode));
7971     }
7972
7973   /* Issue an error either if the default size of the object isn't a constant
7974      or if the new size is smaller than it.  */
7975   if (TREE_CODE (type_size) != INTEGER_CST
7976       || TREE_OVERFLOW (type_size)
7977       || tree_int_cst_lt (size, type_size))
7978     {
7979       if (component_p)
7980         post_error_ne_tree
7981           ("component size for& too small{, minimum allowed is ^}",
7982            gnat_error_node, gnat_object, type_size);
7983       else
7984         post_error_ne_tree
7985           ("size for& too small{, minimum allowed is ^}",
7986            gnat_error_node, gnat_object, type_size);
7987       return NULL_TREE;
7988     }
7989
7990   return size;
7991 }
7992 \f
7993 /* Similarly, but both validate and process a value of RM size.  This routine
7994    is only called for types.  */
7995
7996 static void
7997 set_rm_size (Uint uint_size, tree gnu_type, Entity_Id gnat_entity)
7998 {
7999   Node_Id gnat_attr_node;
8000   tree old_size, size;
8001
8002   /* Do nothing if no size was specified.  */
8003   if (uint_size == No_Uint)
8004     return;
8005
8006   /* Ignore a negative size since that corresponds to our back-annotation.  */
8007   if (UI_Lt (uint_size, Uint_0))
8008     return;
8009
8010   /* Only issue an error if a Value_Size clause was explicitly given.
8011      Otherwise, we'd be duplicating an error on the Size clause.  */
8012   gnat_attr_node
8013     = Get_Attribute_Definition_Clause (gnat_entity, Attr_Value_Size);
8014
8015   /* Get the size as an INTEGER_CST.  Issue an error if a size was specified
8016      but cannot be represented in bitsizetype.  */
8017   size = UI_To_gnu (uint_size, bitsizetype);
8018   if (TREE_OVERFLOW (size))
8019     {
8020       if (Present (gnat_attr_node))
8021         post_error_ne ("Value_Size for& is too large", gnat_attr_node,
8022                        gnat_entity);
8023       return;
8024     }
8025
8026   /* Ignore a zero size unless a Value_Size clause exists, or a size clause
8027      exists, or this is an integer type, in which case the front-end will
8028      have always set it.  */
8029   if (No (gnat_attr_node)
8030       && integer_zerop (size)
8031       && !Has_Size_Clause (gnat_entity)
8032       && !Is_Discrete_Or_Fixed_Point_Type (gnat_entity))
8033     return;
8034
8035   old_size = rm_size (gnu_type);
8036
8037   /* If the old size is self-referential, get the maximum size.  */
8038   if (CONTAINS_PLACEHOLDER_P (old_size))
8039     old_size = max_size (old_size, true);
8040
8041   /* Issue an error either if the old size of the object isn't a constant or
8042      if the new size is smaller than it.  The front-end has already verified
8043      this for scalar and packed array types.  */
8044   if (TREE_CODE (old_size) != INTEGER_CST
8045       || TREE_OVERFLOW (old_size)
8046       || (AGGREGATE_TYPE_P (gnu_type)
8047           && !(TREE_CODE (gnu_type) == ARRAY_TYPE
8048                && TYPE_PACKED_ARRAY_TYPE_P (gnu_type))
8049           && !(TYPE_IS_PADDING_P (gnu_type)
8050                && TREE_CODE (TREE_TYPE (TYPE_FIELDS (gnu_type))) == ARRAY_TYPE
8051                && TYPE_PACKED_ARRAY_TYPE_P
8052                   (TREE_TYPE (TYPE_FIELDS (gnu_type))))
8053           && tree_int_cst_lt (size, old_size)))
8054     {
8055       if (Present (gnat_attr_node))
8056         post_error_ne_tree
8057           ("Value_Size for& too small{, minimum allowed is ^}",
8058            gnat_attr_node, gnat_entity, old_size);
8059       return;
8060     }
8061
8062   /* Otherwise, set the RM size proper for integral types...  */
8063   if ((TREE_CODE (gnu_type) == INTEGER_TYPE
8064        && Is_Discrete_Or_Fixed_Point_Type (gnat_entity))
8065       || (TREE_CODE (gnu_type) == ENUMERAL_TYPE
8066           || TREE_CODE (gnu_type) == BOOLEAN_TYPE))
8067     SET_TYPE_RM_SIZE (gnu_type, size);
8068
8069   /* ...or the Ada size for record and union types.  */
8070   else if (RECORD_OR_UNION_TYPE_P (gnu_type)
8071            && !TYPE_FAT_POINTER_P (gnu_type))
8072     SET_TYPE_ADA_SIZE (gnu_type, size);
8073 }
8074 \f
8075 /* ALIGNMENT is a Uint giving the alignment specified for GNAT_ENTITY,
8076    a type or object whose present alignment is ALIGN.  If this alignment is
8077    valid, return it.  Otherwise, give an error and return ALIGN.  */
8078
8079 static unsigned int
8080 validate_alignment (Uint alignment, Entity_Id gnat_entity, unsigned int align)
8081 {
8082   unsigned int max_allowed_alignment = get_target_maximum_allowed_alignment ();
8083   unsigned int new_align;
8084   Node_Id gnat_error_node;
8085
8086   /* Don't worry about checking alignment if alignment was not specified
8087      by the source program and we already posted an error for this entity.  */
8088   if (Error_Posted (gnat_entity) && !Has_Alignment_Clause (gnat_entity))
8089     return align;
8090
8091   /* Post the error on the alignment clause if any.  Note, for the implicit
8092      base type of an array type, the alignment clause is on the first
8093      subtype.  */
8094   if (Present (Alignment_Clause (gnat_entity)))
8095     gnat_error_node = Expression (Alignment_Clause (gnat_entity));
8096
8097   else if (Is_Itype (gnat_entity)
8098            && Is_Array_Type (gnat_entity)
8099            && Etype (gnat_entity) == gnat_entity
8100            && Present (Alignment_Clause (First_Subtype (gnat_entity))))
8101     gnat_error_node =
8102       Expression (Alignment_Clause (First_Subtype (gnat_entity)));
8103
8104   else
8105     gnat_error_node = gnat_entity;
8106
8107   /* Within GCC, an alignment is an integer, so we must make sure a value is
8108      specified that fits in that range.  Also, there is an upper bound to
8109      alignments we can support/allow.  */
8110   if (!UI_Is_In_Int_Range (alignment)
8111       || ((new_align = UI_To_Int (alignment)) > max_allowed_alignment))
8112     post_error_ne_num ("largest supported alignment for& is ^",
8113                        gnat_error_node, gnat_entity, max_allowed_alignment);
8114   else if (!(Present (Alignment_Clause (gnat_entity))
8115              && From_At_Mod (Alignment_Clause (gnat_entity)))
8116            && new_align * BITS_PER_UNIT < align)
8117     {
8118       unsigned int double_align;
8119       bool is_capped_double, align_clause;
8120
8121       /* If the default alignment of "double" or larger scalar types is
8122          specifically capped and the new alignment is above the cap, do
8123          not post an error and change the alignment only if there is an
8124          alignment clause; this makes it possible to have the associated
8125          GCC type overaligned by default for performance reasons.  */
8126       if ((double_align = double_float_alignment) > 0)
8127         {
8128           Entity_Id gnat_type
8129             = Is_Type (gnat_entity) ? gnat_entity : Etype (gnat_entity);
8130           is_capped_double
8131             = is_double_float_or_array (gnat_type, &align_clause);
8132         }
8133       else if ((double_align = double_scalar_alignment) > 0)
8134         {
8135           Entity_Id gnat_type
8136             = Is_Type (gnat_entity) ? gnat_entity : Etype (gnat_entity);
8137           is_capped_double
8138             = is_double_scalar_or_array (gnat_type, &align_clause);
8139         }
8140       else
8141         is_capped_double = align_clause = false;
8142
8143       if (is_capped_double && new_align >= double_align)
8144         {
8145           if (align_clause)
8146             align = new_align * BITS_PER_UNIT;
8147         }
8148       else
8149         {
8150           if (is_capped_double)
8151             align = double_align * BITS_PER_UNIT;
8152
8153           post_error_ne_num ("alignment for& must be at least ^",
8154                              gnat_error_node, gnat_entity,
8155                              align / BITS_PER_UNIT);
8156         }
8157     }
8158   else
8159     {
8160       new_align = (new_align > 0 ? new_align * BITS_PER_UNIT : 1);
8161       if (new_align > align)
8162         align = new_align;
8163     }
8164
8165   return align;
8166 }
8167 \f
8168 /* Verify that TYPE is something we can implement atomically.  If not, issue
8169    an error for GNAT_ENTITY.  COMPONENT_P is true if we are being called to
8170    process a component type.  */
8171
8172 static void
8173 check_ok_for_atomic_type (tree type, Entity_Id gnat_entity, bool component_p)
8174 {
8175   Node_Id gnat_error_point = gnat_entity;
8176   Node_Id gnat_node;
8177   machine_mode mode;
8178   enum mode_class mclass;
8179   unsigned int align;
8180   tree size;
8181
8182   /* If this is an anonymous base type, nothing to check, the error will be
8183      reported on the source type if need be.  */
8184   if (!Comes_From_Source (gnat_entity))
8185     return;
8186
8187   mode = TYPE_MODE (type);
8188   mclass = GET_MODE_CLASS (mode);
8189   align = TYPE_ALIGN (type);
8190   size = TYPE_SIZE (type);
8191
8192   /* Consider all aligned floating-point types atomic and any aligned types
8193      that are represented by integers no wider than a machine word.  */
8194   if ((mclass == MODE_FLOAT
8195        || ((mclass == MODE_INT || mclass == MODE_PARTIAL_INT)
8196            && GET_MODE_BITSIZE (mode) <= BITS_PER_WORD))
8197       && align >= GET_MODE_ALIGNMENT (mode))
8198     return;
8199
8200   /* For the moment, also allow anything that has an alignment equal to its
8201      size and which is smaller than a word.  */
8202   if (size
8203       && TREE_CODE (size) == INTEGER_CST
8204       && compare_tree_int (size, align) == 0
8205       && align <= BITS_PER_WORD)
8206     return;
8207
8208   for (gnat_node = First_Rep_Item (gnat_entity);
8209        Present (gnat_node);
8210        gnat_node = Next_Rep_Item (gnat_node))
8211     if (Nkind (gnat_node) == N_Pragma)
8212       {
8213         unsigned char pragma_id
8214           = Get_Pragma_Id (Chars (Pragma_Identifier (gnat_node)));
8215
8216         if ((pragma_id == Pragma_Atomic && !component_p)
8217             || (pragma_id == Pragma_Atomic_Components && component_p))
8218           {
8219             gnat_error_point = First (Pragma_Argument_Associations (gnat_node));
8220             break;
8221           }
8222       }
8223
8224   if (component_p)
8225     post_error_ne ("atomic access to component of & cannot be guaranteed",
8226                    gnat_error_point, gnat_entity);
8227   else if (Is_Volatile_Full_Access (gnat_entity))
8228     post_error_ne ("volatile full access to & cannot be guaranteed",
8229                    gnat_error_point, gnat_entity);
8230   else
8231     post_error_ne ("atomic access to & cannot be guaranteed",
8232                    gnat_error_point, gnat_entity);
8233 }
8234 \f
8235
8236 /* Helper for the intrin compatibility checks family.  Evaluate whether
8237    two types are definitely incompatible.  */
8238
8239 static bool
8240 intrin_types_incompatible_p (tree t1, tree t2)
8241 {
8242   enum tree_code code;
8243
8244   if (TYPE_MAIN_VARIANT (t1) == TYPE_MAIN_VARIANT (t2))
8245     return false;
8246
8247   if (TYPE_MODE (t1) != TYPE_MODE (t2))
8248     return true;
8249
8250   if (TREE_CODE (t1) != TREE_CODE (t2))
8251     return true;
8252
8253   code = TREE_CODE (t1);
8254
8255   switch (code)
8256     {
8257     case INTEGER_TYPE:
8258     case REAL_TYPE:
8259       return TYPE_PRECISION (t1) != TYPE_PRECISION (t2);
8260
8261     case POINTER_TYPE:
8262     case REFERENCE_TYPE:
8263       /* Assume designated types are ok.  We'd need to account for char * and
8264          void * variants to do better, which could rapidly get messy and isn't
8265          clearly worth the effort.  */
8266       return false;
8267
8268     default:
8269       break;
8270     }
8271
8272   return false;
8273 }
8274
8275 /* Helper for intrin_profiles_compatible_p, to perform compatibility checks
8276    on the Ada/builtin argument lists for the INB binding.  */
8277
8278 static bool
8279 intrin_arglists_compatible_p (intrin_binding_t * inb)
8280 {
8281   function_args_iterator ada_iter, btin_iter;
8282
8283   function_args_iter_init (&ada_iter, inb->ada_fntype);
8284   function_args_iter_init (&btin_iter, inb->btin_fntype);
8285
8286   /* Sequence position of the last argument we checked.  */
8287   int argpos = 0;
8288
8289   while (1)
8290     {
8291       tree ada_type = function_args_iter_cond (&ada_iter);
8292       tree btin_type = function_args_iter_cond (&btin_iter);
8293
8294       /* If we've exhausted both lists simultaneously, we're done.  */
8295       if (ada_type == NULL_TREE && btin_type == NULL_TREE)
8296         break;
8297
8298       /* If one list is shorter than the other, they fail to match.  */
8299       if (ada_type == NULL_TREE || btin_type == NULL_TREE)
8300         return false;
8301
8302       /* If we're done with the Ada args and not with the internal builtin
8303          args, or the other way around, complain.  */
8304       if (ada_type == void_type_node
8305           && btin_type != void_type_node)
8306         {
8307           post_error ("?Ada arguments list too short!", inb->gnat_entity);
8308           return false;
8309         }
8310
8311       if (btin_type == void_type_node
8312           && ada_type != void_type_node)
8313         {
8314           post_error_ne_num ("?Ada arguments list too long ('> ^)!",
8315                              inb->gnat_entity, inb->gnat_entity, argpos);
8316           return false;
8317         }
8318
8319       /* Otherwise, check that types match for the current argument.  */
8320       argpos ++;
8321       if (intrin_types_incompatible_p (ada_type, btin_type))
8322         {
8323           post_error_ne_num ("?intrinsic binding type mismatch on argument ^!",
8324                              inb->gnat_entity, inb->gnat_entity, argpos);
8325           return false;
8326         }
8327
8328
8329       function_args_iter_next (&ada_iter);
8330       function_args_iter_next (&btin_iter);
8331     }
8332
8333   return true;
8334 }
8335
8336 /* Helper for intrin_profiles_compatible_p, to perform compatibility checks
8337    on the Ada/builtin return values for the INB binding.  */
8338
8339 static bool
8340 intrin_return_compatible_p (intrin_binding_t * inb)
8341 {
8342   tree ada_return_type = TREE_TYPE (inb->ada_fntype);
8343   tree btin_return_type = TREE_TYPE (inb->btin_fntype);
8344
8345   /* Accept function imported as procedure, common and convenient.  */
8346   if (VOID_TYPE_P (ada_return_type)
8347       && !VOID_TYPE_P (btin_return_type))
8348     return true;
8349
8350   /* If return type is Address (integer type), map it to void *.  */
8351   if (Is_Descendent_Of_Address (Etype (inb->gnat_entity)))
8352     ada_return_type = ptr_type_node;
8353
8354   /* Check return types compatibility otherwise.  Note that this
8355      handles void/void as well.  */
8356   if (intrin_types_incompatible_p (btin_return_type, ada_return_type))
8357     {
8358       post_error ("?intrinsic binding type mismatch on return value!",
8359                   inb->gnat_entity);
8360       return false;
8361     }
8362
8363   return true;
8364 }
8365
8366 /* Check and return whether the Ada and gcc builtin profiles bound by INB are
8367    compatible.  Issue relevant warnings when they are not.
8368
8369    This is intended as a light check to diagnose the most obvious cases, not
8370    as a full fledged type compatibility predicate.  It is the programmer's
8371    responsibility to ensure correctness of the Ada declarations in Imports,
8372    especially when binding straight to a compiler internal.  */
8373
8374 static bool
8375 intrin_profiles_compatible_p (intrin_binding_t * inb)
8376 {
8377   /* Check compatibility on return values and argument lists, each responsible
8378      for posting warnings as appropriate.  Ensure use of the proper sloc for
8379      this purpose.  */
8380
8381   bool arglists_compatible_p, return_compatible_p;
8382   location_t saved_location = input_location;
8383
8384   Sloc_to_locus (Sloc (inb->gnat_entity), &input_location);
8385
8386   return_compatible_p = intrin_return_compatible_p (inb);
8387   arglists_compatible_p = intrin_arglists_compatible_p (inb);
8388
8389   input_location = saved_location;
8390
8391   return return_compatible_p && arglists_compatible_p;
8392 }
8393 \f
8394 /* Return a FIELD_DECL node modeled on OLD_FIELD.  FIELD_TYPE is its type
8395    and RECORD_TYPE is the type of the parent.  If SIZE is nonzero, it is the
8396    specified size for this field.  POS_LIST is a position list describing
8397    the layout of OLD_FIELD and SUBST_LIST a substitution list to be applied
8398    to this layout.  */
8399
8400 static tree
8401 create_field_decl_from (tree old_field, tree field_type, tree record_type,
8402                         tree size, tree pos_list,
8403                         vec<subst_pair> subst_list)
8404 {
8405   tree t = TREE_VALUE (purpose_member (old_field, pos_list));
8406   tree pos = TREE_VEC_ELT (t, 0), bitpos = TREE_VEC_ELT (t, 2);
8407   unsigned int offset_align = tree_to_uhwi (TREE_VEC_ELT (t, 1));
8408   tree new_pos, new_field;
8409   unsigned int i;
8410   subst_pair *s;
8411
8412   if (CONTAINS_PLACEHOLDER_P (pos))
8413     FOR_EACH_VEC_ELT (subst_list, i, s)
8414       pos = SUBSTITUTE_IN_EXPR (pos, s->discriminant, s->replacement);
8415
8416   /* If the position is now a constant, we can set it as the position of the
8417      field when we make it.  Otherwise, we need to deal with it specially.  */
8418   if (TREE_CONSTANT (pos))
8419     new_pos = bit_from_pos (pos, bitpos);
8420   else
8421     new_pos = NULL_TREE;
8422
8423   new_field
8424     = create_field_decl (DECL_NAME (old_field), field_type, record_type,
8425                          size, new_pos, DECL_PACKED (old_field),
8426                          !DECL_NONADDRESSABLE_P (old_field));
8427
8428   if (!new_pos)
8429     {
8430       normalize_offset (&pos, &bitpos, offset_align);
8431       /* Finalize the position.  */
8432       DECL_FIELD_OFFSET (new_field) = variable_size (pos);
8433       DECL_FIELD_BIT_OFFSET (new_field) = bitpos;
8434       SET_DECL_OFFSET_ALIGN (new_field, offset_align);
8435       DECL_SIZE (new_field) = size;
8436       DECL_SIZE_UNIT (new_field)
8437         = convert (sizetype,
8438                    size_binop (CEIL_DIV_EXPR, size, bitsize_unit_node));
8439       layout_decl (new_field, DECL_OFFSET_ALIGN (new_field));
8440     }
8441
8442   DECL_INTERNAL_P (new_field) = DECL_INTERNAL_P (old_field);
8443   SET_DECL_ORIGINAL_FIELD_TO_FIELD (new_field, old_field);
8444   DECL_DISCRIMINANT_NUMBER (new_field) = DECL_DISCRIMINANT_NUMBER (old_field);
8445   TREE_THIS_VOLATILE (new_field) = TREE_THIS_VOLATILE (old_field);
8446
8447   return new_field;
8448 }
8449
8450 /* Create the REP part of RECORD_TYPE with REP_TYPE.  If MIN_SIZE is nonzero,
8451    it is the minimal size the REP_PART must have.  */
8452
8453 static tree
8454 create_rep_part (tree rep_type, tree record_type, tree min_size)
8455 {
8456   tree field;
8457
8458   if (min_size && !tree_int_cst_lt (TYPE_SIZE (rep_type), min_size))
8459     min_size = NULL_TREE;
8460
8461   field = create_field_decl (get_identifier ("REP"), rep_type, record_type,
8462                              min_size, NULL_TREE, 0, 1);
8463   DECL_INTERNAL_P (field) = 1;
8464
8465   return field;
8466 }
8467
8468 /* Return the REP part of RECORD_TYPE, if any.  Otherwise return NULL.  */
8469
8470 static tree
8471 get_rep_part (tree record_type)
8472 {
8473   tree field = TYPE_FIELDS (record_type);
8474
8475   /* The REP part is the first field, internal, another record, and its name
8476      starts with an 'R'.  */
8477   if (field
8478       && DECL_INTERNAL_P (field)
8479       && TREE_CODE (TREE_TYPE (field)) == RECORD_TYPE
8480       && IDENTIFIER_POINTER (DECL_NAME (field)) [0] == 'R')
8481     return field;
8482
8483   return NULL_TREE;
8484 }
8485
8486 /* Return the variant part of RECORD_TYPE, if any.  Otherwise return NULL.  */
8487
8488 tree
8489 get_variant_part (tree record_type)
8490 {
8491   tree field;
8492
8493   /* The variant part is the only internal field that is a qualified union.  */
8494   for (field = TYPE_FIELDS (record_type); field; field = DECL_CHAIN (field))
8495     if (DECL_INTERNAL_P (field)
8496         && TREE_CODE (TREE_TYPE (field)) == QUAL_UNION_TYPE)
8497       return field;
8498
8499   return NULL_TREE;
8500 }
8501
8502 /* Return a new variant part modeled on OLD_VARIANT_PART.  VARIANT_LIST is
8503    the list of variants to be used and RECORD_TYPE is the type of the parent.
8504    POS_LIST is a position list describing the layout of fields present in
8505    OLD_VARIANT_PART and SUBST_LIST a substitution list to be applied to this
8506    layout.  */
8507
8508 static tree
8509 create_variant_part_from (tree old_variant_part,
8510                           vec<variant_desc> variant_list,
8511                           tree record_type, tree pos_list,
8512                           vec<subst_pair> subst_list)
8513 {
8514   tree offset = DECL_FIELD_OFFSET (old_variant_part);
8515   tree old_union_type = TREE_TYPE (old_variant_part);
8516   tree new_union_type, new_variant_part;
8517   tree union_field_list = NULL_TREE;
8518   variant_desc *v;
8519   unsigned int i;
8520
8521   /* First create the type of the variant part from that of the old one.  */
8522   new_union_type = make_node (QUAL_UNION_TYPE);
8523   TYPE_NAME (new_union_type)
8524     = concat_name (TYPE_NAME (record_type),
8525                    IDENTIFIER_POINTER (DECL_NAME (old_variant_part)));
8526
8527   /* If the position of the variant part is constant, subtract it from the
8528      size of the type of the parent to get the new size.  This manual CSE
8529      reduces the code size when not optimizing.  */
8530   if (TREE_CODE (offset) == INTEGER_CST)
8531     {
8532       tree bitpos = DECL_FIELD_BIT_OFFSET (old_variant_part);
8533       tree first_bit = bit_from_pos (offset, bitpos);
8534       TYPE_SIZE (new_union_type)
8535         = size_binop (MINUS_EXPR, TYPE_SIZE (record_type), first_bit);
8536       TYPE_SIZE_UNIT (new_union_type)
8537         = size_binop (MINUS_EXPR, TYPE_SIZE_UNIT (record_type),
8538                       byte_from_pos (offset, bitpos));
8539       SET_TYPE_ADA_SIZE (new_union_type,
8540                          size_binop (MINUS_EXPR, TYPE_ADA_SIZE (record_type),
8541                                      first_bit));
8542       TYPE_ALIGN (new_union_type) = TYPE_ALIGN (old_union_type);
8543       relate_alias_sets (new_union_type, old_union_type, ALIAS_SET_COPY);
8544     }
8545   else
8546     copy_and_substitute_in_size (new_union_type, old_union_type, subst_list);
8547
8548   /* Now finish up the new variants and populate the union type.  */
8549   FOR_EACH_VEC_ELT_REVERSE (variant_list, i, v)
8550     {
8551       tree old_field = v->field, new_field;
8552       tree old_variant, old_variant_subpart, new_variant, field_list;
8553
8554       /* Skip variants that don't belong to this nesting level.  */
8555       if (DECL_CONTEXT (old_field) != old_union_type)
8556         continue;
8557
8558       /* Retrieve the list of fields already added to the new variant.  */
8559       new_variant = v->new_type;
8560       field_list = TYPE_FIELDS (new_variant);
8561
8562       /* If the old variant had a variant subpart, we need to create a new
8563          variant subpart and add it to the field list.  */
8564       old_variant = v->type;
8565       old_variant_subpart = get_variant_part (old_variant);
8566       if (old_variant_subpart)
8567         {
8568           tree new_variant_subpart
8569             = create_variant_part_from (old_variant_subpart, variant_list,
8570                                         new_variant, pos_list, subst_list);
8571           DECL_CHAIN (new_variant_subpart) = field_list;
8572           field_list = new_variant_subpart;
8573         }
8574
8575       /* Finish up the new variant and create the field.  No need for debug
8576          info thanks to the XVS type.  */
8577       finish_record_type (new_variant, nreverse (field_list), 2, false);
8578       compute_record_mode (new_variant);
8579       create_type_decl (TYPE_NAME (new_variant), new_variant, true, false,
8580                         Empty);
8581
8582       new_field
8583         = create_field_decl_from (old_field, new_variant, new_union_type,
8584                                   TYPE_SIZE (new_variant),
8585                                   pos_list, subst_list);
8586       DECL_QUALIFIER (new_field) = v->qual;
8587       DECL_INTERNAL_P (new_field) = 1;
8588       DECL_CHAIN (new_field) = union_field_list;
8589       union_field_list = new_field;
8590     }
8591
8592   /* Finish up the union type and create the variant part.  No need for debug
8593      info thanks to the XVS type.  Note that we don't reverse the field list
8594      because VARIANT_LIST has been traversed in reverse order.  */
8595   finish_record_type (new_union_type, union_field_list, 2, false);
8596   compute_record_mode (new_union_type);
8597   create_type_decl (TYPE_NAME (new_union_type), new_union_type, true, false,
8598                     Empty);
8599
8600   new_variant_part
8601     = create_field_decl_from (old_variant_part, new_union_type, record_type,
8602                               TYPE_SIZE (new_union_type),
8603                               pos_list, subst_list);
8604   DECL_INTERNAL_P (new_variant_part) = 1;
8605
8606   /* With multiple discriminants it is possible for an inner variant to be
8607      statically selected while outer ones are not; in this case, the list
8608      of fields of the inner variant is not flattened and we end up with a
8609      qualified union with a single member.  Drop the useless container.  */
8610   if (!DECL_CHAIN (union_field_list))
8611     {
8612       DECL_CONTEXT (union_field_list) = record_type;
8613       DECL_FIELD_OFFSET (union_field_list)
8614         = DECL_FIELD_OFFSET (new_variant_part);
8615       DECL_FIELD_BIT_OFFSET (union_field_list)
8616         = DECL_FIELD_BIT_OFFSET (new_variant_part);
8617       SET_DECL_OFFSET_ALIGN (union_field_list,
8618                              DECL_OFFSET_ALIGN (new_variant_part));
8619       new_variant_part = union_field_list;
8620     }
8621
8622   return new_variant_part;
8623 }
8624
8625 /* Copy the size (and alignment and alias set) from OLD_TYPE to NEW_TYPE,
8626    which are both RECORD_TYPE, after applying the substitutions described
8627    in SUBST_LIST.  */
8628
8629 static void
8630 copy_and_substitute_in_size (tree new_type, tree old_type,
8631                              vec<subst_pair> subst_list)
8632 {
8633   unsigned int i;
8634   subst_pair *s;
8635
8636   TYPE_SIZE (new_type) = TYPE_SIZE (old_type);
8637   TYPE_SIZE_UNIT (new_type) = TYPE_SIZE_UNIT (old_type);
8638   SET_TYPE_ADA_SIZE (new_type, TYPE_ADA_SIZE (old_type));
8639   TYPE_ALIGN (new_type) = TYPE_ALIGN (old_type);
8640   relate_alias_sets (new_type, old_type, ALIAS_SET_COPY);
8641
8642   if (CONTAINS_PLACEHOLDER_P (TYPE_SIZE (new_type)))
8643     FOR_EACH_VEC_ELT (subst_list, i, s)
8644       TYPE_SIZE (new_type)
8645         = SUBSTITUTE_IN_EXPR (TYPE_SIZE (new_type),
8646                               s->discriminant, s->replacement);
8647
8648   if (CONTAINS_PLACEHOLDER_P (TYPE_SIZE_UNIT (new_type)))
8649     FOR_EACH_VEC_ELT (subst_list, i, s)
8650       TYPE_SIZE_UNIT (new_type)
8651         = SUBSTITUTE_IN_EXPR (TYPE_SIZE_UNIT (new_type),
8652                               s->discriminant, s->replacement);
8653
8654   if (CONTAINS_PLACEHOLDER_P (TYPE_ADA_SIZE (new_type)))
8655     FOR_EACH_VEC_ELT (subst_list, i, s)
8656       SET_TYPE_ADA_SIZE
8657         (new_type, SUBSTITUTE_IN_EXPR (TYPE_ADA_SIZE (new_type),
8658                                        s->discriminant, s->replacement));
8659
8660   /* Finalize the size.  */
8661   TYPE_SIZE (new_type) = variable_size (TYPE_SIZE (new_type));
8662   TYPE_SIZE_UNIT (new_type) = variable_size (TYPE_SIZE_UNIT (new_type));
8663 }
8664
8665 /* Add a parallel type to GNU_TYPE, the translation of GNAT_ENTITY, which is
8666    the implementation type of a packed array type (Is_Packed_Array_Impl_Type).
8667    The parallel type is the original array type if it has been translated.  */
8668
8669 static void
8670 add_parallel_type_for_packed_array (tree gnu_type, Entity_Id gnat_entity)
8671 {
8672   Entity_Id gnat_original_array_type
8673     = Underlying_Type (Original_Array_Type (gnat_entity));
8674   tree gnu_original_array_type;
8675
8676   if (!present_gnu_tree (gnat_original_array_type))
8677     return;
8678
8679   gnu_original_array_type = gnat_to_gnu_type (gnat_original_array_type);
8680
8681   if (TYPE_IS_DUMMY_P (gnu_original_array_type))
8682     return;
8683
8684   add_parallel_type (gnu_type, gnu_original_array_type);
8685 }
8686 \f
8687 /* Given a type T, a FIELD_DECL F, and a replacement value R, return a
8688    type with all size expressions that contain F in a PLACEHOLDER_EXPR
8689    updated by replacing F with R.
8690
8691    The function doesn't update the layout of the type, i.e. it assumes
8692    that the substitution is purely formal.  That's why the replacement
8693    value R must itself contain a PLACEHOLDER_EXPR.  */
8694
8695 tree
8696 substitute_in_type (tree t, tree f, tree r)
8697 {
8698   tree nt;
8699
8700   gcc_assert (CONTAINS_PLACEHOLDER_P (r));
8701
8702   switch (TREE_CODE (t))
8703     {
8704     case INTEGER_TYPE:
8705     case ENUMERAL_TYPE:
8706     case BOOLEAN_TYPE:
8707     case REAL_TYPE:
8708
8709       /* First the domain types of arrays.  */
8710       if (CONTAINS_PLACEHOLDER_P (TYPE_GCC_MIN_VALUE (t))
8711           || CONTAINS_PLACEHOLDER_P (TYPE_GCC_MAX_VALUE (t)))
8712         {
8713           tree low = SUBSTITUTE_IN_EXPR (TYPE_GCC_MIN_VALUE (t), f, r);
8714           tree high = SUBSTITUTE_IN_EXPR (TYPE_GCC_MAX_VALUE (t), f, r);
8715
8716           if (low == TYPE_GCC_MIN_VALUE (t) && high == TYPE_GCC_MAX_VALUE (t))
8717             return t;
8718
8719           nt = copy_type (t);
8720           TYPE_GCC_MIN_VALUE (nt) = low;
8721           TYPE_GCC_MAX_VALUE (nt) = high;
8722
8723           if (TREE_CODE (t) == INTEGER_TYPE && TYPE_INDEX_TYPE (t))
8724             SET_TYPE_INDEX_TYPE
8725               (nt, substitute_in_type (TYPE_INDEX_TYPE (t), f, r));
8726
8727           return nt;
8728         }
8729
8730       /* Then the subtypes.  */
8731       if (CONTAINS_PLACEHOLDER_P (TYPE_RM_MIN_VALUE (t))
8732           || CONTAINS_PLACEHOLDER_P (TYPE_RM_MAX_VALUE (t)))
8733         {
8734           tree low = SUBSTITUTE_IN_EXPR (TYPE_RM_MIN_VALUE (t), f, r);
8735           tree high = SUBSTITUTE_IN_EXPR (TYPE_RM_MAX_VALUE (t), f, r);
8736
8737           if (low == TYPE_RM_MIN_VALUE (t) && high == TYPE_RM_MAX_VALUE (t))
8738             return t;
8739
8740           nt = copy_type (t);
8741           SET_TYPE_RM_MIN_VALUE (nt, low);
8742           SET_TYPE_RM_MAX_VALUE (nt, high);
8743
8744           return nt;
8745         }
8746
8747       return t;
8748
8749     case COMPLEX_TYPE:
8750       nt = substitute_in_type (TREE_TYPE (t), f, r);
8751       if (nt == TREE_TYPE (t))
8752         return t;
8753
8754       return build_complex_type (nt);
8755
8756     case FUNCTION_TYPE:
8757       /* These should never show up here.  */
8758       gcc_unreachable ();
8759
8760     case ARRAY_TYPE:
8761       {
8762         tree component = substitute_in_type (TREE_TYPE (t), f, r);
8763         tree domain = substitute_in_type (TYPE_DOMAIN (t), f, r);
8764
8765         if (component == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
8766           return t;
8767
8768         nt = build_nonshared_array_type (component, domain);
8769         TYPE_ALIGN (nt) = TYPE_ALIGN (t);
8770         TYPE_USER_ALIGN (nt) = TYPE_USER_ALIGN (t);
8771         SET_TYPE_MODE (nt, TYPE_MODE (t));
8772         TYPE_SIZE (nt) = SUBSTITUTE_IN_EXPR (TYPE_SIZE (t), f, r);
8773         TYPE_SIZE_UNIT (nt) = SUBSTITUTE_IN_EXPR (TYPE_SIZE_UNIT (t), f, r);
8774         TYPE_NONALIASED_COMPONENT (nt) = TYPE_NONALIASED_COMPONENT (t);
8775         TYPE_MULTI_ARRAY_P (nt) = TYPE_MULTI_ARRAY_P (t);
8776         TYPE_CONVENTION_FORTRAN_P (nt) = TYPE_CONVENTION_FORTRAN_P (t);
8777         return nt;
8778       }
8779
8780     case RECORD_TYPE:
8781     case UNION_TYPE:
8782     case QUAL_UNION_TYPE:
8783       {
8784         bool changed_field = false;
8785         tree field;
8786
8787         /* Start out with no fields, make new fields, and chain them
8788            in.  If we haven't actually changed the type of any field,
8789            discard everything we've done and return the old type.  */
8790         nt = copy_type (t);
8791         TYPE_FIELDS (nt) = NULL_TREE;
8792
8793         for (field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
8794           {
8795             tree new_field = copy_node (field), new_n;
8796
8797             new_n = substitute_in_type (TREE_TYPE (field), f, r);
8798             if (new_n != TREE_TYPE (field))
8799               {
8800                 TREE_TYPE (new_field) = new_n;
8801                 changed_field = true;
8802               }
8803
8804             new_n = SUBSTITUTE_IN_EXPR (DECL_FIELD_OFFSET (field), f, r);
8805             if (new_n != DECL_FIELD_OFFSET (field))
8806               {
8807                 DECL_FIELD_OFFSET (new_field) = new_n;
8808                 changed_field = true;
8809               }
8810
8811             /* Do the substitution inside the qualifier, if any.  */
8812             if (TREE_CODE (t) == QUAL_UNION_TYPE)
8813               {
8814                 new_n = SUBSTITUTE_IN_EXPR (DECL_QUALIFIER (field), f, r);
8815                 if (new_n != DECL_QUALIFIER (field))
8816                   {
8817                     DECL_QUALIFIER (new_field) = new_n;
8818                     changed_field = true;
8819                   }
8820               }
8821
8822             DECL_CONTEXT (new_field) = nt;
8823             SET_DECL_ORIGINAL_FIELD_TO_FIELD (new_field, field);
8824
8825             DECL_CHAIN (new_field) = TYPE_FIELDS (nt);
8826             TYPE_FIELDS (nt) = new_field;
8827           }
8828
8829         if (!changed_field)
8830           return t;
8831
8832         TYPE_FIELDS (nt) = nreverse (TYPE_FIELDS (nt));
8833         TYPE_SIZE (nt) = SUBSTITUTE_IN_EXPR (TYPE_SIZE (t), f, r);
8834         TYPE_SIZE_UNIT (nt) = SUBSTITUTE_IN_EXPR (TYPE_SIZE_UNIT (t), f, r);
8835         SET_TYPE_ADA_SIZE (nt, SUBSTITUTE_IN_EXPR (TYPE_ADA_SIZE (t), f, r));
8836         return nt;
8837       }
8838
8839     default:
8840       return t;
8841     }
8842 }
8843 \f
8844 /* Return the RM size of GNU_TYPE.  This is the actual number of bits
8845    needed to represent the object.  */
8846
8847 tree
8848 rm_size (tree gnu_type)
8849 {
8850   /* For integral types, we store the RM size explicitly.  */
8851   if (INTEGRAL_TYPE_P (gnu_type) && TYPE_RM_SIZE (gnu_type))
8852     return TYPE_RM_SIZE (gnu_type);
8853
8854   /* Return the RM size of the actual data plus the size of the template.  */
8855   if (TREE_CODE (gnu_type) == RECORD_TYPE
8856       && TYPE_CONTAINS_TEMPLATE_P (gnu_type))
8857     return
8858       size_binop (PLUS_EXPR,
8859                   rm_size (TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (gnu_type)))),
8860                   DECL_SIZE (TYPE_FIELDS (gnu_type)));
8861
8862   /* For record or union types, we store the size explicitly.  */
8863   if (RECORD_OR_UNION_TYPE_P (gnu_type)
8864       && !TYPE_FAT_POINTER_P (gnu_type)
8865       && TYPE_ADA_SIZE (gnu_type))
8866     return TYPE_ADA_SIZE (gnu_type);
8867
8868   /* For other types, this is just the size.  */
8869   return TYPE_SIZE (gnu_type);
8870 }
8871 \f
8872 /* Return the name to be used for GNAT_ENTITY.  If a type, create a
8873    fully-qualified name, possibly with type information encoding.
8874    Otherwise, return the name.  */
8875
8876 static const char *
8877 get_entity_char (Entity_Id gnat_entity)
8878 {
8879   Get_Encoded_Name (gnat_entity);
8880   return ggc_strdup (Name_Buffer);
8881 }
8882
8883 tree
8884 get_entity_name (Entity_Id gnat_entity)
8885 {
8886   Get_Encoded_Name (gnat_entity);
8887   return get_identifier_with_length (Name_Buffer, Name_Len);
8888 }
8889
8890 /* Return an identifier representing the external name to be used for
8891    GNAT_ENTITY.  If SUFFIX is specified, the name is followed by "___"
8892    and the specified suffix.  */
8893
8894 tree
8895 create_concat_name (Entity_Id gnat_entity, const char *suffix)
8896 {
8897   const Entity_Kind kind = Ekind (gnat_entity);
8898   const bool has_suffix = (suffix != NULL);
8899   String_Template temp = {1, has_suffix ? strlen (suffix) : 0};
8900   String_Pointer sp = {suffix, &temp};
8901
8902   Get_External_Name (gnat_entity, has_suffix, sp);
8903
8904   /* A variable using the Stdcall convention lives in a DLL.  We adjust
8905      its name to use the jump table, the _imp__NAME contains the address
8906      for the NAME variable.  */
8907   if ((kind == E_Variable || kind == E_Constant)
8908       && Has_Stdcall_Convention (gnat_entity))
8909     {
8910       const int len = strlen (STDCALL_PREFIX) + Name_Len;
8911       char *new_name = (char *) alloca (len + 1);
8912       strcpy (new_name, STDCALL_PREFIX);
8913       strcat (new_name, Name_Buffer);
8914       return get_identifier_with_length (new_name, len);
8915     }
8916
8917   return get_identifier_with_length (Name_Buffer, Name_Len);
8918 }
8919
8920 /* Given GNU_NAME, an IDENTIFIER_NODE containing a name and SUFFIX, a
8921    string, return a new IDENTIFIER_NODE that is the concatenation of
8922    the name followed by "___" and the specified suffix.  */
8923
8924 tree
8925 concat_name (tree gnu_name, const char *suffix)
8926 {
8927   const int len = IDENTIFIER_LENGTH (gnu_name) + 3 + strlen (suffix);
8928   char *new_name = (char *) alloca (len + 1);
8929   strcpy (new_name, IDENTIFIER_POINTER (gnu_name));
8930   strcat (new_name, "___");
8931   strcat (new_name, suffix);
8932   return get_identifier_with_length (new_name, len);
8933 }
8934
8935 /* Initialize data structures of the decl.c module.  */
8936
8937 void
8938 init_gnat_decl (void)
8939 {
8940   /* Initialize the cache of annotated values.  */
8941   annotate_value_cache = hash_table<value_annotation_hasher>::create_ggc (512);
8942 }
8943
8944 /* Destroy data structures of the decl.c module.  */
8945
8946 void
8947 destroy_gnat_decl (void)
8948 {
8949   /* Destroy the cache of annotated values.  */
8950   annotate_value_cache->empty ();
8951   annotate_value_cache = NULL;
8952 }
8953
8954 #include "gt-ada-decl.h"