OSDN Git Service

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