OSDN Git Service

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