OSDN Git Service

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