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