OSDN Git Service

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