OSDN Git Service

89b10c695da818463aafd8f46336f9bb67e0185a
[pf3gnuchains/gcc-fork.git] / gcc / ada / trans.c
1 /****************************************************************************
2  *                                                                          *
3  *                         GNAT COMPILER COMPONENTS                         *
4  *                                                                          *
5  *                                T R A N S                                 *
6  *                                                                          *
7  *                          C Implementation File                           *
8  *                                                                          *
9  *          Copyright (C) 1992-2008, 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 2,  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  distributed with GNAT;  see file COPYING.  If not, write *
19  * to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor, *
20  * Boston, MA 02110-1301, USA.                                              *
21  *                                                                          *
22  * GNAT was originally developed  by the GNAT team at  New York University. *
23  * Extensive contributions were provided by Ada Core Technologies Inc.      *
24  *                                                                          *
25  ****************************************************************************/
26
27 #include "config.h"
28 #include "system.h"
29 #include "coretypes.h"
30 #include "tm.h"
31 #include "tree.h"
32 #include "real.h"
33 #include "flags.h"
34 #include "toplev.h"
35 #include "rtl.h"
36 #include "expr.h"
37 #include "ggc.h"
38 #include "cgraph.h"
39 #include "function.h"
40 #include "except.h"
41 #include "debug.h"
42 #include "output.h"
43 #include "tree-gimple.h"
44 #include "ada.h"
45 #include "types.h"
46 #include "atree.h"
47 #include "elists.h"
48 #include "namet.h"
49 #include "nlists.h"
50 #include "snames.h"
51 #include "stringt.h"
52 #include "uintp.h"
53 #include "urealp.h"
54 #include "fe.h"
55 #include "sinfo.h"
56 #include "einfo.h"
57 #include "ada-tree.h"
58 #include "gigi.h"
59 #include "adadecode.h"
60
61 #include "dwarf2.h"
62 #include "dwarf2out.h"
63
64 /* We should avoid allocating more than ALLOCA_THRESHOLD bytes via alloca,
65    for fear of running out of stack space.  If we need more, we use xmalloc
66    instead.  */
67 #define ALLOCA_THRESHOLD 1000
68
69 /* Let code below know whether we are targetting VMS without need of
70    intrusive preprocessor directives.  */
71 #ifndef TARGET_ABI_OPEN_VMS
72 #define TARGET_ABI_OPEN_VMS 0
73 #endif
74
75 extern char *__gnat_to_canonical_file_spec (char *);
76
77 int max_gnat_nodes;
78 int number_names;
79 int number_files;
80 struct Node *Nodes_Ptr;
81 Node_Id *Next_Node_Ptr;
82 Node_Id *Prev_Node_Ptr;
83 struct Elist_Header *Elists_Ptr;
84 struct Elmt_Item *Elmts_Ptr;
85 struct String_Entry *Strings_Ptr;
86 Char_Code *String_Chars_Ptr;
87 struct List_Header *List_Headers_Ptr;
88
89 /* Current filename without path. */
90 const char *ref_filename;
91
92 /* If true, then gigi is being called on an analyzed but unexpanded
93    tree, and the only purpose of the call is to properly annotate
94    types with representation information. */
95 bool type_annotate_only;
96
97 /* When not optimizing, we cache the 'First, 'Last and 'Length attributes
98    of unconstrained array IN parameters to avoid emitting a great deal of
99    redundant instructions to recompute them each time.  */
100 struct parm_attr GTY (())
101 {
102   int id; /* GTY doesn't like Entity_Id.  */
103   int dim;
104   tree first;
105   tree last;
106   tree length;
107 };
108
109 typedef struct parm_attr *parm_attr;
110
111 DEF_VEC_P(parm_attr);
112 DEF_VEC_ALLOC_P(parm_attr,gc);
113
114 struct language_function GTY(())
115 {
116   VEC(parm_attr,gc) *parm_attr_cache;
117 };
118
119 #define f_parm_attr_cache \
120   DECL_STRUCT_FUNCTION (current_function_decl)->language->parm_attr_cache
121
122 /* A structure used to gather together information about a statement group.
123    We use this to gather related statements, for example the "then" part
124    of a IF.  In the case where it represents a lexical scope, we may also
125    have a BLOCK node corresponding to it and/or cleanups.  */
126
127 struct stmt_group GTY((chain_next ("%h.previous"))) {
128   struct stmt_group *previous;  /* Previous code group.  */
129   tree stmt_list;               /* List of statements for this code group. */
130   tree block;                   /* BLOCK for this code group, if any. */
131   tree cleanups;                /* Cleanups for this code group, if any.  */
132 };
133
134 static GTY(()) struct stmt_group *current_stmt_group;
135
136 /* List of unused struct stmt_group nodes.  */
137 static GTY((deletable)) struct stmt_group *stmt_group_free_list;
138
139 /* A structure used to record information on elaboration procedures
140    we've made and need to process.
141
142    ??? gnat_node should be Node_Id, but gengtype gets confused.  */
143
144 struct elab_info GTY((chain_next ("%h.next"))) {
145   struct elab_info *next;       /* Pointer to next in chain. */
146   tree elab_proc;               /* Elaboration procedure.  */
147   int gnat_node;                /* The N_Compilation_Unit.  */
148 };
149
150 static GTY(()) struct elab_info *elab_info_list;
151
152 /* Free list of TREE_LIST nodes used for stacks.  */
153 static GTY((deletable)) tree gnu_stack_free_list;
154
155 /* List of TREE_LIST nodes representing a stack of exception pointer
156    variables.  TREE_VALUE is the VAR_DECL that stores the address of
157    the raised exception.  Nonzero means we are in an exception
158    handler.  Not used in the zero-cost case.  */
159 static GTY(()) tree gnu_except_ptr_stack;
160
161 /* List of TREE_LIST nodes used to store the current elaboration procedure
162    decl.  TREE_VALUE is the decl.  */
163 static GTY(()) tree gnu_elab_proc_stack;
164
165 /* Variable that stores a list of labels to be used as a goto target instead of
166    a return in some functions.  See processing for N_Subprogram_Body.  */
167 static GTY(()) tree gnu_return_label_stack;
168
169 /* List of TREE_LIST nodes representing a stack of LOOP_STMT nodes.
170    TREE_VALUE of each entry is the label of the corresponding LOOP_STMT.  */
171 static GTY(()) tree gnu_loop_label_stack;
172
173 /* List of TREE_LIST nodes representing labels for switch statements.
174    TREE_VALUE of each entry is the label at the end of the switch.  */
175 static GTY(()) tree gnu_switch_label_stack;
176
177 /* List of TREE_LIST nodes containing the stacks for N_{Push,Pop}_*_Label.  */
178 static GTY(()) tree gnu_constraint_error_label_stack;
179 static GTY(()) tree gnu_storage_error_label_stack;
180 static GTY(()) tree gnu_program_error_label_stack;
181
182 /* Map GNAT tree codes to GCC tree codes for simple expressions.  */
183 static enum tree_code gnu_codes[Number_Node_Kinds];
184
185 /* Current node being treated, in case abort called.  */
186 Node_Id error_gnat_node;
187
188 static void init_code_table (void);
189 static void Compilation_Unit_to_gnu (Node_Id);
190 static void record_code_position (Node_Id);
191 static void insert_code_for (Node_Id);
192 static void add_cleanup (tree, Node_Id);
193 static tree unshare_save_expr (tree *, int *, void *);
194 static void add_stmt_list (List_Id);
195 static void push_exception_label_stack (tree *, Entity_Id);
196 static tree build_stmt_group (List_Id, bool);
197 static void push_stack (tree *, tree, tree);
198 static void pop_stack (tree *);
199 static enum gimplify_status gnat_gimplify_stmt (tree *);
200 static void elaborate_all_entities (Node_Id);
201 static void process_freeze_entity (Node_Id);
202 static void process_inlined_subprograms (Node_Id);
203 static void process_decls (List_Id, List_Id, Node_Id, bool, bool);
204 static tree emit_range_check (tree, Node_Id);
205 static tree emit_index_check (tree, tree, tree, tree);
206 static tree emit_check (tree, tree, int);
207 static tree convert_with_check (Entity_Id, tree, bool, bool, bool);
208 static bool smaller_packable_type_p (tree, tree);
209 static bool addressable_p (tree, tree);
210 static tree assoc_to_constructor (Entity_Id, Node_Id, tree);
211 static tree extract_values (tree, tree);
212 static tree pos_to_constructor (Node_Id, tree, Entity_Id);
213 static tree maybe_implicit_deref (tree);
214 static tree gnat_stabilize_reference (tree, bool);
215 static tree gnat_stabilize_reference_1 (tree, bool);
216 static void set_expr_location_from_node (tree, Node_Id);
217 static int lvalue_required_p (Node_Id, tree, int);
218
219 /* Hooks for debug info back-ends, only supported and used in a restricted set
220    of configurations.  */
221 static const char *extract_encoding (const char *) ATTRIBUTE_UNUSED;
222 static const char *decode_name (const char *) ATTRIBUTE_UNUSED;
223 \f
224 /* This is the main program of the back-end.  It sets up all the table
225    structures and then generates code.  */
226
227 void
228 gigi (Node_Id gnat_root, int max_gnat_node, int number_name,
229       struct Node *nodes_ptr, Node_Id *next_node_ptr, Node_Id *prev_node_ptr,
230       struct Elist_Header *elists_ptr, struct Elmt_Item *elmts_ptr,
231       struct String_Entry *strings_ptr, Char_Code *string_chars_ptr,
232       struct List_Header *list_headers_ptr, Nat number_file,
233       struct File_Info_Type *file_info_ptr,
234       Entity_Id standard_integer, Entity_Id standard_long_long_float,
235       Entity_Id standard_exception_type, Int gigi_operating_mode)
236 {
237   tree gnu_standard_long_long_float;
238   tree gnu_standard_exception_type;
239   struct elab_info *info;
240   int i;
241
242   max_gnat_nodes = max_gnat_node;
243   number_names = number_name;
244   number_files = number_file;
245   Nodes_Ptr = nodes_ptr;
246   Next_Node_Ptr = next_node_ptr;
247   Prev_Node_Ptr = prev_node_ptr;
248   Elists_Ptr = elists_ptr;
249   Elmts_Ptr = elmts_ptr;
250   Strings_Ptr = strings_ptr;
251   String_Chars_Ptr = string_chars_ptr;
252   List_Headers_Ptr = list_headers_ptr;
253
254   type_annotate_only = (gigi_operating_mode == 1);
255
256   for (i = 0; i < number_files; i++)
257     {
258       /* Use the identifier table to make a permanent copy of the filename as
259          the name table gets reallocated after Gigi returns but before all the
260          debugging information is output.  The __gnat_to_canonical_file_spec
261          call translates filenames from pragmas Source_Reference that contain
262          host style syntax not understood by gdb. */
263       const char *filename
264         = IDENTIFIER_POINTER
265            (get_identifier
266             (__gnat_to_canonical_file_spec
267              (Get_Name_String (file_info_ptr[i].File_Name))));
268
269       /* We rely on the order isomorphism between files and line maps.  */
270       gcc_assert ((int) line_table->used == i);
271
272       /* We create the line map for a source file at once, with a fixed number
273          of columns chosen to avoid jumping over the next power of 2.  */
274       linemap_add (line_table, LC_ENTER, 0, filename, 1);
275       linemap_line_start (line_table, file_info_ptr[i].Num_Source_Lines, 252);
276       linemap_position_for_column (line_table, 252 - 1);
277       linemap_add (line_table, LC_LEAVE, 0, NULL, 0);
278     }
279
280   /* Initialize ourselves.  */
281   init_code_table ();
282   init_gnat_to_gnu ();
283   gnat_compute_largest_alignment ();
284   init_dummy_type ();
285
286   /* If we are just annotating types, give VOID_TYPE zero sizes to avoid
287      errors.  */
288   if (type_annotate_only)
289     {
290       TYPE_SIZE (void_type_node) = bitsize_zero_node;
291       TYPE_SIZE_UNIT (void_type_node) = size_zero_node;
292     }
293
294   /* If the GNU type extensions to DWARF are available, setup the hooks.  */
295 #if defined (DWARF2_DEBUGGING_INFO) && defined (DWARF2_GNU_TYPE_EXTENSIONS)
296   /* We condition the name demangling and the generation of type encoding
297      strings on -gdwarf+ and always set descriptive types on.  */
298   if (use_gnu_debug_info_extensions)
299     {
300       dwarf2out_set_type_encoding_func (extract_encoding);
301       dwarf2out_set_demangle_name_func (decode_name);
302     }
303   dwarf2out_set_descriptive_type_func (get_parallel_type);
304 #endif
305
306   /* Enable GNAT stack checking method if needed */
307   if (!Stack_Check_Probes_On_Target)
308     set_stack_check_libfunc (gen_rtx_SYMBOL_REF (Pmode, "_gnat_stack_check"));
309
310   /* Give names and make TYPE_DECLs for common types.  */
311   create_type_decl (get_identifier (SIZE_TYPE), sizetype,
312                     NULL, false, true, Empty);
313   create_type_decl (get_identifier ("integer"), integer_type_node,
314                     NULL, false, true, Empty);
315   create_type_decl (get_identifier ("unsigned char"), char_type_node,
316                     NULL, false, true, Empty);
317   create_type_decl (get_identifier ("long integer"), long_integer_type_node,
318                     NULL, false, true, Empty);
319
320   /* Save the type we made for integer as the type for Standard.Integer.
321      Then make the rest of the standard types.  Note that some of these
322      may be subtypes.  */
323   save_gnu_tree (Base_Type (standard_integer), TYPE_NAME (integer_type_node),
324                  false);
325
326   gnu_except_ptr_stack = tree_cons (NULL_TREE, NULL_TREE, NULL_TREE);
327   gnu_constraint_error_label_stack
328     = tree_cons (NULL_TREE, NULL_TREE, NULL_TREE);
329   gnu_storage_error_label_stack = tree_cons (NULL_TREE, NULL_TREE, NULL_TREE);
330   gnu_program_error_label_stack = tree_cons (NULL_TREE, NULL_TREE, NULL_TREE);
331
332   gnu_standard_long_long_float
333     = gnat_to_gnu_entity (Base_Type (standard_long_long_float), NULL_TREE, 0);
334   gnu_standard_exception_type
335     = gnat_to_gnu_entity (Base_Type (standard_exception_type),  NULL_TREE, 0);
336
337   init_gigi_decls (gnu_standard_long_long_float, gnu_standard_exception_type);
338
339   /* Process any Pragma Ident for the main unit.  */
340 #ifdef ASM_OUTPUT_IDENT
341   if (Present (Ident_String (Main_Unit)))
342     ASM_OUTPUT_IDENT
343       (asm_out_file,
344        TREE_STRING_POINTER (gnat_to_gnu (Ident_String (Main_Unit))));
345 #endif
346
347   /* If we are using the GCC exception mechanism, let GCC know.  */
348   if (Exception_Mechanism == Back_End_Exceptions)
349     gnat_init_gcc_eh ();
350
351   gcc_assert (Nkind (gnat_root) == N_Compilation_Unit);
352   start_stmt_group ();
353   Compilation_Unit_to_gnu (gnat_root);
354
355   /* Now see if we have any elaboration procedures to deal with. */
356   for (info = elab_info_list; info; info = info->next)
357     {
358       tree gnu_body = DECL_SAVED_TREE (info->elab_proc);
359       tree gnu_stmts;
360
361       /* Unshare SAVE_EXPRs between subprograms.  These are not unshared by
362          the gimplifier for obvious reasons, but it turns out that we need to
363          unshare them for the global level because of SAVE_EXPRs made around
364          checks for global objects and around allocators for global objects
365          of variable size, in order to prevent node sharing in the underlying
366          expression.  Note that this implicitly assumes that the SAVE_EXPR
367          nodes themselves are not shared between subprograms, which would be
368          an upstream bug for which we would not change the outcome.  */
369       walk_tree_without_duplicates (&gnu_body, unshare_save_expr, NULL);
370
371       /* Set the current function to be the elaboration procedure and gimplify
372          what we have.  */
373       current_function_decl = info->elab_proc;
374       gimplify_body (&gnu_body, info->elab_proc, true);
375
376       /* We should have a BIND_EXPR, but it may or may not have any statements
377          in it.  If it doesn't have any, we have nothing to do.  */
378       gnu_stmts = gnu_body;
379       if (TREE_CODE (gnu_stmts) == BIND_EXPR)
380         gnu_stmts = BIND_EXPR_BODY (gnu_stmts);
381
382       /* If there are no statements, there is no elaboration code.  */
383       if (!gnu_stmts || !STATEMENT_LIST_HEAD (gnu_stmts))
384         {
385           Set_Has_No_Elaboration_Code (info->gnat_node, 1);
386           cgraph_remove_node (cgraph_node (info->elab_proc));
387         }
388       else
389         {
390           /* Otherwise, compile the function.  Note that we'll be gimplifying
391              it twice, but that's fine for the nodes we use.  */
392           begin_subprog_body (info->elab_proc);
393           end_subprog_body (gnu_body);
394         }
395     }
396
397   /* We cannot track the location of errors past this point.  */
398   error_gnat_node = Empty;
399 }
400 \f
401 /* Return a positive value if an lvalue is required for GNAT_NODE.
402    GNU_TYPE is the type that will be used for GNAT_NODE in the
403    translated GNU tree.  ALIASED indicates whether the underlying
404    object represented by GNAT_NODE is aliased in the Ada sense.
405
406    The function climbs up the GNAT tree starting from the node and
407    returns 1 upon encountering a node that effectively requires an
408    lvalue downstream.  It returns int instead of bool to facilitate
409    usage in non purely binary logic contexts.  */
410
411 static int
412 lvalue_required_p (Node_Id gnat_node, tree gnu_type, int aliased)
413 {
414   Node_Id gnat_parent = Parent (gnat_node), gnat_temp;
415
416   switch (Nkind (gnat_parent))
417     {
418     case N_Reference:
419       return 1;
420
421     case N_Attribute_Reference:
422       {
423         unsigned char id = Get_Attribute_Id (Attribute_Name (gnat_parent));
424         return id == Attr_Address
425                || id == Attr_Access
426                || id == Attr_Unchecked_Access
427                || id == Attr_Unrestricted_Access;
428       }
429
430     case N_Parameter_Association:
431     case N_Function_Call:
432     case N_Procedure_Call_Statement:
433       return (must_pass_by_ref (gnu_type) || default_pass_by_ref (gnu_type));
434
435     case N_Indexed_Component:
436       /* Only the array expression can require an lvalue.  */
437       if (Prefix (gnat_parent) != gnat_node)
438         return 0;
439
440       /* ??? Consider that referencing an indexed component with a
441          non-constant index forces the whole aggregate to memory.
442          Note that N_Integer_Literal is conservative, any static
443          expression in the RM sense could probably be accepted.  */
444       for (gnat_temp = First (Expressions (gnat_parent));
445            Present (gnat_temp);
446            gnat_temp = Next (gnat_temp))
447         if (Nkind (gnat_temp) != N_Integer_Literal)
448           return 1;
449
450       /* ... fall through ... */
451
452     case N_Slice:
453       /* Only the array expression can require an lvalue.  */
454       if (Prefix (gnat_parent) != gnat_node)
455         return 0;
456
457       aliased |= Has_Aliased_Components (Etype (gnat_node));
458       return lvalue_required_p (gnat_parent, gnu_type, aliased);
459
460     case N_Selected_Component:
461       aliased |= Is_Aliased (Entity (Selector_Name (gnat_parent)));
462       return lvalue_required_p (gnat_parent, gnu_type, aliased);
463
464     case N_Object_Renaming_Declaration:
465       /* We need to make a real renaming only if the constant object is
466          aliased or if we may use a renaming pointer; otherwise we can
467          optimize and return the rvalue.  We make an exception if the object
468          is an identifier since in this case the rvalue can be propagated
469          attached to the CONST_DECL.  */
470       return (aliased != 0
471               /* This should match the constant case of the renaming code.  */
472               || Is_Composite_Type (Etype (Name (gnat_parent)))
473               || Nkind (Name (gnat_parent)) == N_Identifier);
474
475     default:
476       return 0;
477     }
478
479   gcc_unreachable ();
480 }
481
482 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Identifier,
483    to a GCC tree, which is returned.  GNU_RESULT_TYPE_P is a pointer
484    to where we should place the result type.  */
485
486 static tree
487 Identifier_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p)
488 {
489   Node_Id gnat_temp, gnat_temp_type;
490   tree gnu_result, gnu_result_type;
491
492   /* Whether we should require an lvalue for GNAT_NODE.  Needed in
493      specific circumstances only, so evaluated lazily.  < 0 means
494      unknown, > 0 means known true, 0 means known false.  */
495   int require_lvalue = -1;
496
497   /* If GNAT_NODE is a constant, whether we should use the initialization
498      value instead of the constant entity, typically for scalars with an
499      address clause when the parent doesn't require an lvalue.  */
500   bool use_constant_initializer = false;
501
502   /* If the Etype of this node does not equal the Etype of the Entity,
503      something is wrong with the entity map, probably in generic
504      instantiation. However, this does not apply to types. Since we sometime
505      have strange Ekind's, just do this test for objects. Also, if the Etype of
506      the Entity is private, the Etype of the N_Identifier is allowed to be the
507      full type and also we consider a packed array type to be the same as the
508      original type. Similarly, a class-wide type is equivalent to a subtype of
509      itself. Finally, if the types are Itypes, one may be a copy of the other,
510      which is also legal.  */
511   gnat_temp = (Nkind (gnat_node) == N_Defining_Identifier
512                ? gnat_node : Entity (gnat_node));
513   gnat_temp_type = Etype (gnat_temp);
514
515   gcc_assert (Etype (gnat_node) == gnat_temp_type
516               || (Is_Packed (gnat_temp_type)
517                   && Etype (gnat_node) == Packed_Array_Type (gnat_temp_type))
518               || (Is_Class_Wide_Type (Etype (gnat_node)))
519               || (IN (Ekind (gnat_temp_type), Private_Kind)
520                   && Present (Full_View (gnat_temp_type))
521                   && ((Etype (gnat_node) == Full_View (gnat_temp_type))
522                       || (Is_Packed (Full_View (gnat_temp_type))
523                           && (Etype (gnat_node)
524                               == Packed_Array_Type (Full_View
525                                                     (gnat_temp_type))))))
526               || (Is_Itype (Etype (gnat_node)) && Is_Itype (gnat_temp_type))
527               || !(Ekind (gnat_temp) == E_Variable
528                    || Ekind (gnat_temp) == E_Component
529                    || Ekind (gnat_temp) == E_Constant
530                    || Ekind (gnat_temp) == E_Loop_Parameter
531                    || IN (Ekind (gnat_temp), Formal_Kind)));
532
533   /* If this is a reference to a deferred constant whose partial view is an
534      unconstrained private type, the proper type is on the full view of the
535      constant, not on the full view of the type, which may be unconstrained.
536
537      This may be a reference to a type, for example in the prefix of the
538      attribute Position, generated for dispatching code (see Make_DT in
539      exp_disp,adb). In that case we need the type itself, not is parent,
540      in particular if it is a derived type  */
541   if (Is_Private_Type (gnat_temp_type)
542       && Has_Unknown_Discriminants (gnat_temp_type)
543       && Ekind (gnat_temp) == E_Constant
544       && Present (Full_View (gnat_temp)))
545     {
546       gnat_temp = Full_View (gnat_temp);
547       gnat_temp_type = Etype (gnat_temp);
548     }
549   else
550     {
551       /* We want to use the Actual_Subtype if it has already been elaborated,
552          otherwise the Etype.  Avoid using Actual_Subtype for packed arrays to
553          simplify things.  */
554       if ((Ekind (gnat_temp) == E_Constant
555            || Ekind (gnat_temp) == E_Variable || Is_Formal (gnat_temp))
556           && !(Is_Array_Type (Etype (gnat_temp))
557                && Present (Packed_Array_Type (Etype (gnat_temp))))
558           && Present (Actual_Subtype (gnat_temp))
559           && present_gnu_tree (Actual_Subtype (gnat_temp)))
560         gnat_temp_type = Actual_Subtype (gnat_temp);
561       else
562         gnat_temp_type = Etype (gnat_node);
563     }
564
565   /* Expand the type of this identifier first, in case it is an enumeral
566      literal, which only get made when the type is expanded.  There is no
567      order-of-elaboration issue here.  */
568   gnu_result_type = get_unpadded_type (gnat_temp_type);
569
570   /* If this is a non-imported scalar constant with an address clause,
571      retrieve the value instead of a pointer to be dereferenced unless
572      an lvalue is required.  This is generally more efficient and actually
573      required if this is a static expression because it might be used
574      in a context where a dereference is inappropriate, such as a case
575      statement alternative or a record discriminant.  There is no possible
576      volatile-ness short-circuit here since Volatile constants must be imported
577      per C.6. */
578   if (Ekind (gnat_temp) == E_Constant && Is_Scalar_Type (gnat_temp_type)
579       && !Is_Imported (gnat_temp)
580       && Present (Address_Clause (gnat_temp)))
581     {
582       require_lvalue = lvalue_required_p (gnat_node, gnu_result_type,
583                                           Is_Aliased (gnat_temp));
584       use_constant_initializer = !require_lvalue;
585     }
586
587   if (use_constant_initializer)
588     {
589       /* If this is a deferred constant, the initializer is attached to
590          the full view.  */
591       if (Present (Full_View (gnat_temp)))
592         gnat_temp = Full_View (gnat_temp);
593
594       gnu_result = gnat_to_gnu (Expression (Declaration_Node (gnat_temp)));
595     }
596   else
597     gnu_result = gnat_to_gnu_entity (gnat_temp, NULL_TREE, 0);
598
599   /* If we are in an exception handler, force this variable into memory to
600      ensure optimization does not remove stores that appear redundant but are
601      actually needed in case an exception occurs.
602
603      ??? Note that we need not do this if the variable is declared within the
604      handler, only if it is referenced in the handler and declared in an
605      enclosing block, but we have no way of testing that right now.
606
607      ??? We used to essentially set the TREE_ADDRESSABLE flag on the variable
608      here, but it can now be removed by the Tree aliasing machinery if the
609      address of the variable is never taken.  All we can do is to make the
610      variable volatile, which might incur the generation of temporaries just
611      to access the memory in some circumstances.  This can be avoided for
612      variables of non-constant size because they are automatically allocated
613      to memory.  There might be no way of allocating a proper temporary for
614      them in any case.  We only do this for SJLJ though.  */
615   if (TREE_VALUE (gnu_except_ptr_stack)
616       && TREE_CODE (gnu_result) == VAR_DECL
617       && TREE_CODE (DECL_SIZE_UNIT (gnu_result)) == INTEGER_CST)
618     TREE_THIS_VOLATILE (gnu_result) = TREE_SIDE_EFFECTS (gnu_result) = 1;
619
620   /* Some objects (such as parameters passed by reference, globals of
621      variable size, and renamed objects) actually represent the address
622      of the object.  In that case, we must do the dereference.  Likewise,
623      deal with parameters to foreign convention subprograms.  */
624   if (DECL_P (gnu_result)
625       && (DECL_BY_REF_P (gnu_result)
626           || (TREE_CODE (gnu_result) == PARM_DECL
627               && DECL_BY_COMPONENT_PTR_P (gnu_result))))
628     {
629       bool ro = DECL_POINTS_TO_READONLY_P (gnu_result);
630       tree renamed_obj;
631
632       if (TREE_CODE (gnu_result) == PARM_DECL
633           && DECL_BY_COMPONENT_PTR_P (gnu_result))
634         gnu_result
635           = build_unary_op (INDIRECT_REF, NULL_TREE,
636                             convert (build_pointer_type (gnu_result_type),
637                                      gnu_result));
638
639       /* If it's a renaming pointer and we are at the right binding level,
640          we can reference the renamed object directly, since the renamed
641          expression has been protected against multiple evaluations.  */
642       else if (TREE_CODE (gnu_result) == VAR_DECL
643                && (renamed_obj = DECL_RENAMED_OBJECT (gnu_result)) != 0
644                && (! DECL_RENAMING_GLOBAL_P (gnu_result)
645                    || global_bindings_p ()))
646         gnu_result = renamed_obj;
647
648       /* Return the underlying CST for a CONST_DECL like a few lines below,
649          after dereferencing in this case.  */
650       else if (TREE_CODE (gnu_result) == CONST_DECL)
651         gnu_result = build_unary_op (INDIRECT_REF, NULL_TREE,
652                                      DECL_INITIAL (gnu_result));
653
654       else
655         gnu_result = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_result);
656
657       TREE_READONLY (gnu_result) = TREE_STATIC (gnu_result) = ro;
658     }
659
660   /* The GNAT tree has the type of a function as the type of its result.  Also
661      use the type of the result if the Etype is a subtype which is nominally
662      unconstrained.  But remove any padding from the resulting type.  */
663   if (TREE_CODE (TREE_TYPE (gnu_result)) == FUNCTION_TYPE
664       || Is_Constr_Subt_For_UN_Aliased (gnat_temp_type))
665     {
666       gnu_result_type = TREE_TYPE (gnu_result);
667       if (TREE_CODE (gnu_result_type) == RECORD_TYPE
668           && TYPE_IS_PADDING_P (gnu_result_type))
669         gnu_result_type = TREE_TYPE (TYPE_FIELDS (gnu_result_type));
670     }
671
672   /* If we have a constant declaration and its initializer at hand,
673      try to return the latter to avoid the need to call fold in lots
674      of places and the need of elaboration code if this Id is used as
675      an initializer itself.  */
676   if (TREE_CONSTANT (gnu_result)
677       && DECL_P (gnu_result)
678       && DECL_INITIAL (gnu_result))
679     {
680       tree object
681         = (TREE_CODE (gnu_result) == CONST_DECL
682            ? DECL_CONST_CORRESPONDING_VAR (gnu_result) : gnu_result);
683
684       /* If there is a corresponding variable, we only want to return
685          the CST value if an lvalue is not required.  Evaluate this
686          now if we have not already done so.  */
687       if (object && require_lvalue < 0)
688         require_lvalue = lvalue_required_p (gnat_node, gnu_result_type,
689                                             Is_Aliased (gnat_temp));
690
691       if (!object || !require_lvalue)
692         gnu_result = unshare_expr (DECL_INITIAL (gnu_result));
693     }
694
695   *gnu_result_type_p = gnu_result_type;
696   return gnu_result;
697 }
698 \f
699 /* Subroutine of gnat_to_gnu to process gnat_node, an N_Pragma.  Return
700    any statements we generate.  */
701
702 static tree
703 Pragma_to_gnu (Node_Id gnat_node)
704 {
705   Node_Id gnat_temp;
706   tree gnu_result = alloc_stmt_list ();
707
708   /* Check for (and ignore) unrecognized pragma and do nothing if we are just
709      annotating types.  */
710   if (type_annotate_only
711       || !Is_Pragma_Name (Chars (Pragma_Identifier (gnat_node))))
712     return gnu_result;
713
714   switch (Get_Pragma_Id (Chars (Pragma_Identifier (gnat_node))))
715     {
716     case Pragma_Inspection_Point:
717       /* Do nothing at top level: all such variables are already viewable.  */
718       if (global_bindings_p ())
719         break;
720
721       for (gnat_temp = First (Pragma_Argument_Associations (gnat_node));
722            Present (gnat_temp);
723            gnat_temp = Next (gnat_temp))
724         {
725           Node_Id gnat_expr = Expression (gnat_temp);
726           tree gnu_expr = gnat_to_gnu (gnat_expr);
727           int use_address;
728           enum machine_mode mode;
729           tree asm_constraint = NULL_TREE;
730 #ifdef ASM_COMMENT_START
731           char *comment;
732 #endif
733
734           if (TREE_CODE (gnu_expr) == UNCONSTRAINED_ARRAY_REF)
735             gnu_expr = TREE_OPERAND (gnu_expr, 0);
736
737           /* Use the value only if it fits into a normal register,
738              otherwise use the address.  */
739           mode = TYPE_MODE (TREE_TYPE (gnu_expr));
740           use_address = ((GET_MODE_CLASS (mode) != MODE_INT
741                           && GET_MODE_CLASS (mode) != MODE_PARTIAL_INT)
742                          || GET_MODE_SIZE (mode) > UNITS_PER_WORD);
743
744           if (use_address)
745             gnu_expr = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr);
746
747 #ifdef ASM_COMMENT_START
748           comment = concat (ASM_COMMENT_START,
749                             " inspection point: ",
750                             Get_Name_String (Chars (gnat_expr)),
751                             use_address ? " address" : "",
752                             " is in %0",
753                             NULL);
754           asm_constraint = build_string (strlen (comment), comment);
755           free (comment);
756 #endif
757           gnu_expr = build4 (ASM_EXPR, void_type_node,
758                              asm_constraint,
759                              NULL_TREE,
760                              tree_cons
761                              (build_tree_list (NULL_TREE,
762                                                build_string (1, "g")),
763                               gnu_expr, NULL_TREE),
764                              NULL_TREE);
765           ASM_VOLATILE_P (gnu_expr) = 1;
766           set_expr_location_from_node (gnu_expr, gnat_node);
767           append_to_statement_list (gnu_expr, &gnu_result);
768         }
769       break;
770
771     case Pragma_Optimize:
772       switch (Chars (Expression
773                      (First (Pragma_Argument_Associations (gnat_node)))))
774         {
775         case Name_Time:  case Name_Space:
776           if (optimize == 0)
777             post_error ("insufficient -O value?", gnat_node);
778           break;
779
780         case Name_Off:
781           if (optimize != 0)
782             post_error ("must specify -O0?", gnat_node);
783           break;
784
785         default:
786           gcc_unreachable ();
787         }
788       break;
789
790     case Pragma_Reviewable:
791       if (write_symbols == NO_DEBUG)
792         post_error ("must specify -g?", gnat_node);
793       break;
794     }
795
796   return gnu_result;
797 }
798 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Attribute,
799    to a GCC tree, which is returned.  GNU_RESULT_TYPE_P is a pointer to
800    where we should place the result type.  ATTRIBUTE is the attribute ID.  */
801
802 static tree
803 Attribute_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p, int attribute)
804 {
805   tree gnu_result = error_mark_node;
806   tree gnu_result_type;
807   tree gnu_expr;
808   bool prefix_unused = false;
809   tree gnu_prefix = gnat_to_gnu (Prefix (gnat_node));
810   tree gnu_type = TREE_TYPE (gnu_prefix);
811
812   /* If the input is a NULL_EXPR, make a new one.  */
813   if (TREE_CODE (gnu_prefix) == NULL_EXPR)
814     {
815       *gnu_result_type_p = get_unpadded_type (Etype (gnat_node));
816       return build1 (NULL_EXPR, *gnu_result_type_p,
817                      TREE_OPERAND (gnu_prefix, 0));
818     }
819
820   switch (attribute)
821     {
822     case Attr_Pos:
823     case Attr_Val:
824       /* These are just conversions until since representation clauses for
825          enumerations are handled in the front end.  */
826       {
827         bool checkp = Do_Range_Check (First (Expressions (gnat_node)));
828
829         gnu_result = gnat_to_gnu (First (Expressions (gnat_node)));
830         gnu_result_type = get_unpadded_type (Etype (gnat_node));
831         gnu_result = convert_with_check (Etype (gnat_node), gnu_result,
832                                          checkp, checkp, true);
833       }
834       break;
835
836     case Attr_Pred:
837     case Attr_Succ:
838       /* These just add or subject the constant 1.  Representation clauses for
839          enumerations are handled in the front-end.  */
840       gnu_expr = gnat_to_gnu (First (Expressions (gnat_node)));
841       gnu_result_type = get_unpadded_type (Etype (gnat_node));
842
843       if (Do_Range_Check (First (Expressions (gnat_node))))
844         {
845           gnu_expr = protect_multiple_eval (gnu_expr);
846           gnu_expr
847             = emit_check
848               (build_binary_op (EQ_EXPR, integer_type_node,
849                                 gnu_expr,
850                                 attribute == Attr_Pred
851                                 ? TYPE_MIN_VALUE (gnu_result_type)
852                                 : TYPE_MAX_VALUE (gnu_result_type)),
853                gnu_expr, CE_Range_Check_Failed);
854         }
855
856       gnu_result
857         = build_binary_op (attribute == Attr_Pred
858                            ? MINUS_EXPR : PLUS_EXPR,
859                            gnu_result_type, gnu_expr,
860                            convert (gnu_result_type, integer_one_node));
861       break;
862
863     case Attr_Address:
864     case Attr_Unrestricted_Access:
865       /* Conversions don't change something's address but can cause us to miss
866          the COMPONENT_REF case below, so strip them off.  */
867       gnu_prefix = remove_conversions (gnu_prefix,
868                                        !Must_Be_Byte_Aligned (gnat_node));
869
870       /* If we are taking 'Address of an unconstrained object, this is the
871          pointer to the underlying array.  */
872       if (attribute == Attr_Address)
873         gnu_prefix = maybe_unconstrained_array (gnu_prefix);
874
875       /* If we are building a static dispatch table, we have to honor
876          TARGET_VTABLE_USES_DESCRIPTORS if we want to be compatible
877          with the C++ ABI.  We do it in the non-static case as well,
878          see gnat_to_gnu_entity, case E_Access_Subprogram_Type.  */
879       else if (TARGET_VTABLE_USES_DESCRIPTORS
880                && Is_Dispatch_Table_Entity (Etype (gnat_node)))
881         {
882           tree gnu_field, gnu_list = NULL_TREE, t;
883           /* Descriptors can only be built here for top-level functions.  */
884           bool build_descriptor = (global_bindings_p () != 0);
885           int i;
886
887           gnu_result_type = get_unpadded_type (Etype (gnat_node));
888
889           /* If we're not going to build the descriptor, we have to retrieve
890              the one which will be built by the linker (or by the compiler
891              later if a static chain is requested).  */
892           if (!build_descriptor)
893             {
894               gnu_result = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_prefix);
895               gnu_result = fold_convert (build_pointer_type (gnu_result_type),
896                                          gnu_result);
897               gnu_result = build1 (INDIRECT_REF, gnu_result_type, gnu_result);
898             }
899
900           for (gnu_field = TYPE_FIELDS (gnu_result_type), i = 0;
901                i < TARGET_VTABLE_USES_DESCRIPTORS;
902                gnu_field = TREE_CHAIN (gnu_field), i++)
903             {
904               if (build_descriptor)
905                 {
906                   t = build2 (FDESC_EXPR, TREE_TYPE (gnu_field), gnu_prefix,
907                               build_int_cst (NULL_TREE, i));
908                   TREE_CONSTANT (t) = 1;
909                 }
910               else
911                 t = build3 (COMPONENT_REF, ptr_void_ftype, gnu_result,
912                             gnu_field, NULL_TREE);
913
914               gnu_list = tree_cons (gnu_field, t, gnu_list);
915             }
916
917           gnu_result = gnat_build_constructor (gnu_result_type, gnu_list);
918           break;
919         }
920
921       /* ... fall through ... */
922
923     case Attr_Access:
924     case Attr_Unchecked_Access:
925     case Attr_Code_Address:
926       gnu_result_type = get_unpadded_type (Etype (gnat_node));
927       gnu_result
928         = build_unary_op (((attribute == Attr_Address
929                             || attribute == Attr_Unrestricted_Access)
930                            && !Must_Be_Byte_Aligned (gnat_node))
931                           ? ATTR_ADDR_EXPR : ADDR_EXPR,
932                           gnu_result_type, gnu_prefix);
933
934       /* For 'Code_Address, find an inner ADDR_EXPR and mark it so that we
935          don't try to build a trampoline.  */
936       if (attribute == Attr_Code_Address)
937         {
938           for (gnu_expr = gnu_result;
939                CONVERT_EXPR_P (gnu_expr);
940                gnu_expr = TREE_OPERAND (gnu_expr, 0))
941             TREE_CONSTANT (gnu_expr) = 1;
942
943           if (TREE_CODE (gnu_expr) == ADDR_EXPR)
944             TREE_NO_TRAMPOLINE (gnu_expr) = TREE_CONSTANT (gnu_expr) = 1;
945         }
946
947       /* For other address attributes applied to a nested function,
948          find an inner ADDR_EXPR and annotate it so that we can issue
949          a useful warning with -Wtrampolines.  */
950       else if (TREE_CODE (TREE_TYPE (gnu_prefix)) == FUNCTION_TYPE)
951         {
952           for (gnu_expr = gnu_result;
953                CONVERT_EXPR_P (gnu_expr);
954                gnu_expr = TREE_OPERAND (gnu_expr, 0))
955             ;
956
957           if (TREE_CODE (gnu_expr) == ADDR_EXPR
958               && decl_function_context (TREE_OPERAND (gnu_expr, 0)))
959             {
960               set_expr_location_from_node (gnu_expr, gnat_node);
961
962               /* Check that we're not violating the No_Implicit_Dynamic_Code
963                  restriction.  Be conservative if we don't know anything
964                  about the trampoline strategy for the target.  */
965               Check_Implicit_Dynamic_Code_Allowed (gnat_node);
966             }
967         }
968       break;
969
970     case Attr_Pool_Address:
971       {
972         tree gnu_obj_type;
973         tree gnu_ptr = gnu_prefix;
974
975         gnu_result_type = get_unpadded_type (Etype (gnat_node));
976
977         /* If this is an unconstrained array, we know the object must have been
978            allocated with the template in front of the object.  So compute the
979            template address.*/
980         if (TYPE_FAT_POINTER_P (TREE_TYPE (gnu_ptr)))
981           gnu_ptr
982             = convert (build_pointer_type
983                        (TYPE_OBJECT_RECORD_TYPE
984                         (TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (gnu_ptr)))),
985                        gnu_ptr);
986
987         gnu_obj_type = TREE_TYPE (TREE_TYPE (gnu_ptr));
988         if (TREE_CODE (gnu_obj_type) == RECORD_TYPE
989             && TYPE_CONTAINS_TEMPLATE_P (gnu_obj_type))
990           {
991             tree gnu_char_ptr_type = build_pointer_type (char_type_node);
992             tree gnu_pos = byte_position (TYPE_FIELDS (gnu_obj_type));
993             tree gnu_byte_offset
994               = convert (sizetype,
995                          size_diffop (size_zero_node, gnu_pos));
996             gnu_byte_offset = fold_build1 (NEGATE_EXPR, sizetype, gnu_byte_offset);
997
998             gnu_ptr = convert (gnu_char_ptr_type, gnu_ptr);
999             gnu_ptr = build_binary_op (POINTER_PLUS_EXPR, gnu_char_ptr_type,
1000                                        gnu_ptr, gnu_byte_offset);
1001           }
1002
1003         gnu_result = convert (gnu_result_type, gnu_ptr);
1004       }
1005       break;
1006
1007     case Attr_Size:
1008     case Attr_Object_Size:
1009     case Attr_Value_Size:
1010     case Attr_Max_Size_In_Storage_Elements:
1011       gnu_expr = gnu_prefix;
1012
1013       /* Remove NOPS from gnu_expr and conversions from gnu_prefix.
1014          We only use GNU_EXPR to see if a COMPONENT_REF was involved. */
1015       while (TREE_CODE (gnu_expr) == NOP_EXPR)
1016         gnu_expr = TREE_OPERAND (gnu_expr, 0);
1017
1018       gnu_prefix = remove_conversions (gnu_prefix, true);
1019       prefix_unused = true;
1020       gnu_type = TREE_TYPE (gnu_prefix);
1021
1022       /* Replace an unconstrained array type with the type of the underlying
1023          array.  We can't do this with a call to maybe_unconstrained_array
1024          since we may have a TYPE_DECL.  For 'Max_Size_In_Storage_Elements,
1025          use the record type that will be used to allocate the object and its
1026          template.  */
1027       if (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE)
1028         {
1029           gnu_type = TYPE_OBJECT_RECORD_TYPE (gnu_type);
1030           if (attribute != Attr_Max_Size_In_Storage_Elements)
1031             gnu_type = TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (gnu_type)));
1032         }
1033
1034       /* If we're looking for the size of a field, return the field size.
1035          Otherwise, if the prefix is an object, or if 'Object_Size or
1036          'Max_Size_In_Storage_Elements has been specified, the result is the
1037          GCC size of the type.  Otherwise, the result is the RM_Size of the
1038          type.  */
1039       if (TREE_CODE (gnu_prefix) == COMPONENT_REF)
1040         gnu_result = DECL_SIZE (TREE_OPERAND (gnu_prefix, 1));
1041       else if (TREE_CODE (gnu_prefix) != TYPE_DECL
1042                || attribute == Attr_Object_Size
1043                || attribute == Attr_Max_Size_In_Storage_Elements)
1044         {
1045           /* If this is a padded type, the GCC size isn't relevant to the
1046              programmer.  Normally, what we want is the RM_Size, which was set
1047              from the specified size, but if it was not set, we want the size
1048              of the relevant field.  Using the MAX of those two produces the
1049              right result in all case.  Don't use the size of the field if it's
1050              a self-referential type, since that's never what's wanted.  */
1051           if (TREE_CODE (gnu_type) == RECORD_TYPE
1052               && TYPE_IS_PADDING_P (gnu_type)
1053               && TREE_CODE (gnu_expr) == COMPONENT_REF)
1054             {
1055               gnu_result = rm_size (gnu_type);
1056               if (!(CONTAINS_PLACEHOLDER_P
1057                     (DECL_SIZE (TREE_OPERAND (gnu_expr, 1)))))
1058                 gnu_result
1059                   = size_binop (MAX_EXPR, gnu_result,
1060                                 DECL_SIZE (TREE_OPERAND (gnu_expr, 1)));
1061             }
1062           else if (Nkind (Prefix (gnat_node)) == N_Explicit_Dereference)
1063             {
1064               Node_Id gnat_deref = Prefix (gnat_node);
1065               Node_Id gnat_actual_subtype = Actual_Designated_Subtype (gnat_deref);
1066               tree gnu_ptr_type = TREE_TYPE (gnat_to_gnu (Prefix (gnat_deref)));
1067               if (TYPE_FAT_OR_THIN_POINTER_P (gnu_ptr_type)
1068                 && Present (gnat_actual_subtype))
1069                 {
1070                   tree gnu_actual_obj_type = gnat_to_gnu_type (gnat_actual_subtype);
1071                   gnu_type = build_unc_object_type_from_ptr (gnu_ptr_type,
1072                                gnu_actual_obj_type, get_identifier ("SIZE"));
1073                 }
1074
1075               gnu_result = TYPE_SIZE (gnu_type);
1076             }
1077           else
1078             gnu_result = TYPE_SIZE (gnu_type);
1079         }
1080       else
1081         gnu_result = rm_size (gnu_type);
1082
1083       gcc_assert (gnu_result);
1084
1085       /* Deal with a self-referential size by returning the maximum size for a
1086          type and by qualifying the size with the object for 'Size of an
1087          object.  */
1088       if (CONTAINS_PLACEHOLDER_P (gnu_result))
1089         {
1090           if (TREE_CODE (gnu_prefix) != TYPE_DECL)
1091             gnu_result = substitute_placeholder_in_expr (gnu_result, gnu_expr);
1092           else
1093             gnu_result = max_size (gnu_result, true);
1094         }
1095
1096       /* If the type contains a template, subtract its size.  */
1097       if (TREE_CODE (gnu_type) == RECORD_TYPE
1098           && TYPE_CONTAINS_TEMPLATE_P (gnu_type))
1099         gnu_result = size_binop (MINUS_EXPR, gnu_result,
1100                                  DECL_SIZE (TYPE_FIELDS (gnu_type)));
1101
1102       gnu_result_type = get_unpadded_type (Etype (gnat_node));
1103
1104       /* Always perform division using unsigned arithmetic as the size cannot
1105          be negative, but may be an overflowed positive value. This provides
1106          correct results for sizes up to 512 MB.
1107
1108          ??? Size should be calculated in storage elements directly.  */
1109
1110       if (attribute == Attr_Max_Size_In_Storage_Elements)
1111         gnu_result = convert (sizetype,
1112                               fold_build2 (CEIL_DIV_EXPR, bitsizetype,
1113                                            gnu_result, bitsize_unit_node));
1114       break;
1115
1116     case Attr_Alignment:
1117       if (TREE_CODE (gnu_prefix) == COMPONENT_REF
1118           && (TREE_CODE (TREE_TYPE (TREE_OPERAND (gnu_prefix, 0)))
1119               == RECORD_TYPE)
1120           && (TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_prefix, 0)))))
1121         gnu_prefix = TREE_OPERAND (gnu_prefix, 0);
1122
1123       gnu_type = TREE_TYPE (gnu_prefix);
1124       gnu_result_type = get_unpadded_type (Etype (gnat_node));
1125       prefix_unused = true;
1126
1127       gnu_result = size_int ((TREE_CODE (gnu_prefix) == COMPONENT_REF
1128                               ? DECL_ALIGN (TREE_OPERAND (gnu_prefix, 1))
1129                               : TYPE_ALIGN (gnu_type)) / BITS_PER_UNIT);
1130       break;
1131
1132     case Attr_First:
1133     case Attr_Last:
1134     case Attr_Range_Length:
1135       prefix_unused = true;
1136
1137       if (INTEGRAL_TYPE_P (gnu_type) || TREE_CODE (gnu_type) == REAL_TYPE)
1138         {
1139           gnu_result_type = get_unpadded_type (Etype (gnat_node));
1140
1141           if (attribute == Attr_First)
1142             gnu_result = TYPE_MIN_VALUE (gnu_type);
1143           else if (attribute == Attr_Last)
1144             gnu_result = TYPE_MAX_VALUE (gnu_type);
1145           else
1146             gnu_result
1147               = build_binary_op
1148                 (MAX_EXPR, get_base_type (gnu_result_type),
1149                  build_binary_op
1150                  (PLUS_EXPR, get_base_type (gnu_result_type),
1151                   build_binary_op (MINUS_EXPR,
1152                                    get_base_type (gnu_result_type),
1153                                    convert (gnu_result_type,
1154                                             TYPE_MAX_VALUE (gnu_type)),
1155                                    convert (gnu_result_type,
1156                                             TYPE_MIN_VALUE (gnu_type))),
1157                   convert (gnu_result_type, integer_one_node)),
1158                  convert (gnu_result_type, integer_zero_node));
1159
1160           break;
1161         }
1162
1163       /* ... fall through ... */
1164
1165     case Attr_Length:
1166       {
1167         int Dimension = (Present (Expressions (gnat_node))
1168                          ? UI_To_Int (Intval (First (Expressions (gnat_node))))
1169                          : 1), i;
1170         struct parm_attr *pa = NULL;
1171         Entity_Id gnat_param = Empty;
1172
1173         /* Make sure any implicit dereference gets done.  */
1174         gnu_prefix = maybe_implicit_deref (gnu_prefix);
1175         gnu_prefix = maybe_unconstrained_array (gnu_prefix);
1176         /* We treat unconstrained array In parameters specially.  */
1177         if (Nkind (Prefix (gnat_node)) == N_Identifier
1178             && !Is_Constrained (Etype (Prefix (gnat_node)))
1179             && Ekind (Entity (Prefix (gnat_node))) == E_In_Parameter)
1180           gnat_param = Entity (Prefix (gnat_node));
1181         gnu_type = TREE_TYPE (gnu_prefix);
1182         prefix_unused = true;
1183         gnu_result_type = get_unpadded_type (Etype (gnat_node));
1184
1185         if (TYPE_CONVENTION_FORTRAN_P (gnu_type))
1186           {
1187             int ndim;
1188             tree gnu_type_temp;
1189
1190             for (ndim = 1, gnu_type_temp = gnu_type;
1191                  TREE_CODE (TREE_TYPE (gnu_type_temp)) == ARRAY_TYPE
1192                  && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type_temp));
1193                  ndim++, gnu_type_temp = TREE_TYPE (gnu_type_temp))
1194               ;
1195
1196             Dimension = ndim + 1 - Dimension;
1197           }
1198
1199         for (i = 1; i < Dimension; i++)
1200           gnu_type = TREE_TYPE (gnu_type);
1201
1202         gcc_assert (TREE_CODE (gnu_type) == ARRAY_TYPE);
1203
1204         /* When not optimizing, look up the slot associated with the parameter
1205            and the dimension in the cache and create a new one on failure.  */
1206         if (!optimize && Present (gnat_param))
1207           {
1208             for (i = 0; VEC_iterate (parm_attr, f_parm_attr_cache, i, pa); i++)
1209               if (pa->id == gnat_param && pa->dim == Dimension)
1210                 break;
1211
1212             if (!pa)
1213               {
1214                 pa = GGC_CNEW (struct parm_attr);
1215                 pa->id = gnat_param;
1216                 pa->dim = Dimension;
1217                 VEC_safe_push (parm_attr, gc, f_parm_attr_cache, pa);
1218               }
1219           }
1220
1221         /* Return the cached expression or build a new one.  */
1222         if (attribute == Attr_First)
1223           {
1224             if (pa && pa->first)
1225               {
1226                 gnu_result = pa->first;
1227                 break;
1228               }
1229
1230             gnu_result
1231               = TYPE_MIN_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type)));
1232           }
1233
1234         else if (attribute == Attr_Last)
1235           {
1236             if (pa && pa->last)
1237               {
1238                 gnu_result = pa->last;
1239                 break;
1240               }
1241
1242             gnu_result
1243               = TYPE_MAX_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type)));
1244           }
1245
1246         else /* attribute == Attr_Range_Length || attribute == Attr_Length  */
1247           {
1248             if (pa && pa->length)
1249               {
1250                 gnu_result = pa->length;
1251                 break;
1252               }
1253             else
1254               {
1255                 /* We used to compute the length as max (hb - lb + 1, 0),
1256                    which could overflow for some cases of empty arrays, e.g.
1257                    when lb == index_type'first.  We now compute the length as
1258                    (hb < lb) ? 0 : hb - lb + 1, which would only overflow in
1259                    much rarer cases, for extremely large arrays we expect
1260                    never to encounter in practice.  In addition, the former
1261                    computation required the use of potentially constraining
1262                    signed arithmetic while the latter doesn't.  */
1263                 
1264                 tree gnu_compute_type = get_base_type (gnu_result_type);
1265
1266                 tree index_type
1267                   = TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type));
1268                 tree lb
1269                   = convert (gnu_compute_type, TYPE_MIN_VALUE (index_type));
1270                 tree hb
1271                   = convert (gnu_compute_type, TYPE_MAX_VALUE (index_type));
1272                 
1273                 gnu_result
1274                   = build3
1275                     (COND_EXPR, gnu_compute_type,
1276                      build_binary_op (LT_EXPR, gnu_compute_type, hb, lb),
1277                      convert (gnu_compute_type, integer_zero_node),
1278                      build_binary_op
1279                      (PLUS_EXPR, gnu_compute_type,
1280                       build_binary_op (MINUS_EXPR, gnu_compute_type, hb, lb),
1281                       convert (gnu_compute_type, integer_one_node)));
1282               }
1283           }
1284
1285         /* If this has a PLACEHOLDER_EXPR, qualify it by the object we are
1286            handling.  Note that these attributes could not have been used on
1287            an unconstrained array type.  */
1288         gnu_result = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_result,
1289                                                      gnu_prefix);
1290
1291         /* Cache the expression we have just computed.  Since we want to do it
1292            at runtime, we force the use of a SAVE_EXPR and let the gimplifier
1293            create the temporary.  */
1294         if (pa)
1295           {
1296             gnu_result
1297               = build1 (SAVE_EXPR, TREE_TYPE (gnu_result), gnu_result);
1298             TREE_SIDE_EFFECTS (gnu_result) = 1;
1299             if (attribute == Attr_First)
1300               pa->first = gnu_result;
1301             else if (attribute == Attr_Last)
1302               pa->last = gnu_result;
1303             else
1304               pa->length = gnu_result;
1305           }
1306         break;
1307       }
1308
1309     case Attr_Bit_Position:
1310     case Attr_Position:
1311     case Attr_First_Bit:
1312     case Attr_Last_Bit:
1313     case Attr_Bit:
1314       {
1315         HOST_WIDE_INT bitsize;
1316         HOST_WIDE_INT bitpos;
1317         tree gnu_offset;
1318         tree gnu_field_bitpos;
1319         tree gnu_field_offset;
1320         tree gnu_inner;
1321         enum machine_mode mode;
1322         int unsignedp, volatilep;
1323
1324         gnu_result_type = get_unpadded_type (Etype (gnat_node));
1325         gnu_prefix = remove_conversions (gnu_prefix, true);
1326         prefix_unused = true;
1327
1328         /* We can have 'Bit on any object, but if it isn't a COMPONENT_REF,
1329            the result is 0.  Don't allow 'Bit on a bare component, though. */
1330         if (attribute == Attr_Bit
1331             && TREE_CODE (gnu_prefix) != COMPONENT_REF
1332             && TREE_CODE (gnu_prefix) != FIELD_DECL)
1333           {
1334             gnu_result = integer_zero_node;
1335             break;
1336           }
1337
1338         else
1339           gcc_assert (TREE_CODE (gnu_prefix) == COMPONENT_REF
1340                       || (attribute == Attr_Bit_Position
1341                           && TREE_CODE (gnu_prefix) == FIELD_DECL));
1342
1343         get_inner_reference (gnu_prefix, &bitsize, &bitpos, &gnu_offset,
1344                              &mode, &unsignedp, &volatilep, false);
1345
1346         if (TREE_CODE (gnu_prefix) == COMPONENT_REF)
1347           {
1348             gnu_field_bitpos = bit_position (TREE_OPERAND (gnu_prefix, 1));
1349             gnu_field_offset = byte_position (TREE_OPERAND (gnu_prefix, 1));
1350
1351             for (gnu_inner = TREE_OPERAND (gnu_prefix, 0);
1352                  TREE_CODE (gnu_inner) == COMPONENT_REF
1353                  && DECL_INTERNAL_P (TREE_OPERAND (gnu_inner, 1));
1354                  gnu_inner = TREE_OPERAND (gnu_inner, 0))
1355               {
1356                 gnu_field_bitpos
1357                   = size_binop (PLUS_EXPR, gnu_field_bitpos,
1358                                 bit_position (TREE_OPERAND (gnu_inner, 1)));
1359                 gnu_field_offset
1360                   = size_binop (PLUS_EXPR, gnu_field_offset,
1361                                 byte_position (TREE_OPERAND (gnu_inner, 1)));
1362               }
1363           }
1364         else if (TREE_CODE (gnu_prefix) == FIELD_DECL)
1365           {
1366             gnu_field_bitpos = bit_position (gnu_prefix);
1367             gnu_field_offset = byte_position (gnu_prefix);
1368           }
1369         else
1370           {
1371             gnu_field_bitpos = bitsize_zero_node;
1372             gnu_field_offset = size_zero_node;
1373           }
1374
1375         switch (attribute)
1376           {
1377           case Attr_Position:
1378             gnu_result = gnu_field_offset;
1379             break;
1380
1381           case Attr_First_Bit:
1382           case Attr_Bit:
1383             gnu_result = size_int (bitpos % BITS_PER_UNIT);
1384             break;
1385
1386           case Attr_Last_Bit:
1387             gnu_result = bitsize_int (bitpos % BITS_PER_UNIT);
1388             gnu_result = size_binop (PLUS_EXPR, gnu_result,
1389                                      TYPE_SIZE (TREE_TYPE (gnu_prefix)));
1390             gnu_result = size_binop (MINUS_EXPR, gnu_result,
1391                                      bitsize_one_node);
1392             break;
1393
1394           case Attr_Bit_Position:
1395             gnu_result = gnu_field_bitpos;
1396             break;
1397                 }
1398
1399         /* If this has a PLACEHOLDER_EXPR, qualify it by the object
1400            we are handling. */
1401         gnu_result = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_result, gnu_prefix);
1402         break;
1403       }
1404
1405     case Attr_Min:
1406     case Attr_Max:
1407       {
1408         tree gnu_lhs = gnat_to_gnu (First (Expressions (gnat_node)));
1409         tree gnu_rhs = gnat_to_gnu (Next (First (Expressions (gnat_node))));
1410
1411         gnu_result_type = get_unpadded_type (Etype (gnat_node));
1412         gnu_result = build_binary_op (attribute == Attr_Min
1413                                       ? MIN_EXPR : MAX_EXPR,
1414                                       gnu_result_type, gnu_lhs, gnu_rhs);
1415       }
1416       break;
1417
1418     case Attr_Passed_By_Reference:
1419       gnu_result = size_int (default_pass_by_ref (gnu_type)
1420                              || must_pass_by_ref (gnu_type));
1421       gnu_result_type = get_unpadded_type (Etype (gnat_node));
1422       break;
1423
1424     case Attr_Component_Size:
1425       if (TREE_CODE (gnu_prefix) == COMPONENT_REF
1426           && (TREE_CODE (TREE_TYPE (TREE_OPERAND (gnu_prefix, 0)))
1427               == RECORD_TYPE)
1428           && (TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_prefix, 0)))))
1429         gnu_prefix = TREE_OPERAND (gnu_prefix, 0);
1430
1431       gnu_prefix = maybe_implicit_deref (gnu_prefix);
1432       gnu_type = TREE_TYPE (gnu_prefix);
1433
1434       if (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE)
1435         gnu_type = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_type))));
1436
1437       while (TREE_CODE (TREE_TYPE (gnu_type)) == ARRAY_TYPE
1438              && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type)))
1439         gnu_type = TREE_TYPE (gnu_type);
1440
1441       gcc_assert (TREE_CODE (gnu_type) == ARRAY_TYPE);
1442
1443       /* Note this size cannot be self-referential.  */
1444       gnu_result = TYPE_SIZE (TREE_TYPE (gnu_type));
1445       gnu_result_type = get_unpadded_type (Etype (gnat_node));
1446       prefix_unused = true;
1447       break;
1448
1449     case Attr_Null_Parameter:
1450       /* This is just a zero cast to the pointer type for
1451          our prefix and dereferenced.  */
1452       gnu_result_type = get_unpadded_type (Etype (gnat_node));
1453       gnu_result
1454         = build_unary_op (INDIRECT_REF, NULL_TREE,
1455                           convert (build_pointer_type (gnu_result_type),
1456                                    integer_zero_node));
1457       TREE_PRIVATE (gnu_result) = 1;
1458       break;
1459
1460     case Attr_Mechanism_Code:
1461       {
1462         int code;
1463         Entity_Id gnat_obj = Entity (Prefix (gnat_node));
1464
1465         prefix_unused = true;
1466         gnu_result_type = get_unpadded_type (Etype (gnat_node));
1467         if (Present (Expressions (gnat_node)))
1468           {
1469             int i = UI_To_Int (Intval (First (Expressions (gnat_node))));
1470
1471             for (gnat_obj = First_Formal (gnat_obj); i > 1;
1472                  i--, gnat_obj = Next_Formal (gnat_obj))
1473               ;
1474           }
1475
1476         code = Mechanism (gnat_obj);
1477         if (code == Default)
1478           code = ((present_gnu_tree (gnat_obj)
1479                    && (DECL_BY_REF_P (get_gnu_tree (gnat_obj))
1480                        || ((TREE_CODE (get_gnu_tree (gnat_obj))
1481                             == PARM_DECL)
1482                            && (DECL_BY_COMPONENT_PTR_P
1483                                (get_gnu_tree (gnat_obj))))))
1484                   ? By_Reference : By_Copy);
1485         gnu_result = convert (gnu_result_type, size_int (- code));
1486       }
1487       break;
1488
1489     default:
1490       /* Say we have an unimplemented attribute.  Then set the value to be
1491          returned to be a zero and hope that's something we can convert to the
1492          type of this attribute.  */
1493       post_error ("unimplemented attribute", gnat_node);
1494       gnu_result_type = get_unpadded_type (Etype (gnat_node));
1495       gnu_result = integer_zero_node;
1496       break;
1497     }
1498
1499   /* If this is an attribute where the prefix was unused, force a use of it if
1500      it has a side-effect.  But don't do it if the prefix is just an entity
1501      name.  However, if an access check is needed, we must do it.  See second
1502      example in AARM 11.6(5.e). */
1503   if (prefix_unused && TREE_SIDE_EFFECTS (gnu_prefix)
1504       && !Is_Entity_Name (Prefix (gnat_node)))
1505     gnu_result = fold_build2 (COMPOUND_EXPR, TREE_TYPE (gnu_result),
1506                               gnu_prefix, gnu_result);
1507
1508   *gnu_result_type_p = gnu_result_type;
1509   return gnu_result;
1510 }
1511 \f
1512 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Case_Statement,
1513    to a GCC tree, which is returned.  */
1514
1515 static tree
1516 Case_Statement_to_gnu (Node_Id gnat_node)
1517 {
1518   tree gnu_result;
1519   tree gnu_expr;
1520   Node_Id gnat_when;
1521
1522   gnu_expr = gnat_to_gnu (Expression (gnat_node));
1523   gnu_expr = convert (get_base_type (TREE_TYPE (gnu_expr)), gnu_expr);
1524
1525   /*  The range of values in a case statement is determined by the rules in
1526       RM 5.4(7-9). In almost all cases, this range is represented by the Etype
1527       of the expression. One exception arises in the case of a simple name that
1528       is parenthesized. This still has the Etype of the name, but since it is
1529       not a name, para 7 does not apply, and we need to go to the base type.
1530       This is the only case where parenthesization affects the dynamic
1531       semantics (i.e. the range of possible values at runtime that is covered
1532       by the others alternative.
1533
1534       Another exception is if the subtype of the expression is non-static.  In
1535       that case, we also have to use the base type.  */
1536   if (Paren_Count (Expression (gnat_node)) != 0
1537       || !Is_OK_Static_Subtype (Underlying_Type
1538                                 (Etype (Expression (gnat_node)))))
1539     gnu_expr = convert (get_base_type (TREE_TYPE (gnu_expr)), gnu_expr);
1540
1541   /* We build a SWITCH_EXPR that contains the code with interspersed
1542      CASE_LABEL_EXPRs for each label.  */
1543
1544   push_stack (&gnu_switch_label_stack, NULL_TREE, create_artificial_label ());
1545   start_stmt_group ();
1546   for (gnat_when = First_Non_Pragma (Alternatives (gnat_node));
1547        Present (gnat_when);
1548        gnat_when = Next_Non_Pragma (gnat_when))
1549     {
1550       Node_Id gnat_choice;
1551       int choices_added = 0;
1552
1553       /* First compile all the different case choices for the current WHEN
1554          alternative.  */
1555       for (gnat_choice = First (Discrete_Choices (gnat_when));
1556            Present (gnat_choice); gnat_choice = Next (gnat_choice))
1557         {
1558           tree gnu_low = NULL_TREE, gnu_high = NULL_TREE;
1559
1560           switch (Nkind (gnat_choice))
1561             {
1562             case N_Range:
1563               gnu_low = gnat_to_gnu (Low_Bound (gnat_choice));
1564               gnu_high = gnat_to_gnu (High_Bound (gnat_choice));
1565               break;
1566
1567             case N_Subtype_Indication:
1568               gnu_low = gnat_to_gnu (Low_Bound (Range_Expression
1569                                                 (Constraint (gnat_choice))));
1570               gnu_high = gnat_to_gnu (High_Bound (Range_Expression
1571                                                   (Constraint (gnat_choice))));
1572               break;
1573
1574             case N_Identifier:
1575             case N_Expanded_Name:
1576               /* This represents either a subtype range or a static value of
1577                  some kind; Ekind says which.  */
1578               if (IN (Ekind (Entity (gnat_choice)), Type_Kind))
1579                 {
1580                   tree gnu_type = get_unpadded_type (Entity (gnat_choice));
1581
1582                   gnu_low = fold (TYPE_MIN_VALUE (gnu_type));
1583                   gnu_high = fold (TYPE_MAX_VALUE (gnu_type));
1584                   break;
1585                 }
1586
1587               /* ... fall through ... */
1588
1589             case N_Character_Literal:
1590             case N_Integer_Literal:
1591               gnu_low = gnat_to_gnu (gnat_choice);
1592               break;
1593
1594             case N_Others_Choice:
1595               break;
1596
1597             default:
1598               gcc_unreachable ();
1599             }
1600
1601           /* If the case value is a subtype that raises Constraint_Error at
1602              run-time because of a wrong bound, then gnu_low or gnu_high is
1603              not transtaleted into an INTEGER_CST.  In such a case, we need
1604              to ensure that the when statement is not added in the tree,
1605              otherwise it will crash the gimplifier.  */
1606           if ((!gnu_low || TREE_CODE (gnu_low) == INTEGER_CST)
1607               && (!gnu_high || TREE_CODE (gnu_high) == INTEGER_CST))
1608             {
1609               add_stmt_with_node (build3 (CASE_LABEL_EXPR, void_type_node,
1610                                           gnu_low, gnu_high,
1611                                           create_artificial_label ()),
1612                                   gnat_choice);
1613               choices_added++;
1614             }
1615         }
1616
1617       /* Push a binding level here in case variables are declared as we want
1618          them to be local to this set of statements instead of to the block
1619          containing the Case statement.  */
1620       if (choices_added > 0)
1621         {
1622           add_stmt (build_stmt_group (Statements (gnat_when), true));
1623           add_stmt (build1 (GOTO_EXPR, void_type_node,
1624                             TREE_VALUE (gnu_switch_label_stack)));
1625         }
1626     }
1627
1628   /* Now emit a definition of the label all the cases branched to. */
1629   add_stmt (build1 (LABEL_EXPR, void_type_node,
1630                     TREE_VALUE (gnu_switch_label_stack)));
1631   gnu_result = build3 (SWITCH_EXPR, TREE_TYPE (gnu_expr), gnu_expr,
1632                        end_stmt_group (), NULL_TREE);
1633   pop_stack (&gnu_switch_label_stack);
1634
1635   return gnu_result;
1636 }
1637 \f
1638 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Loop_Statement,
1639    to a GCC tree, which is returned.  */
1640
1641 static tree
1642 Loop_Statement_to_gnu (Node_Id gnat_node)
1643 {
1644   /* ??? It would be nice to use "build" here, but there's no build5.  */
1645   tree gnu_loop_stmt = build_nt (LOOP_STMT, NULL_TREE, NULL_TREE,
1646                                  NULL_TREE, NULL_TREE, NULL_TREE);
1647   tree gnu_loop_var = NULL_TREE;
1648   Node_Id gnat_iter_scheme = Iteration_Scheme (gnat_node);
1649   tree gnu_cond_expr = NULL_TREE;
1650   tree gnu_result;
1651
1652   TREE_TYPE (gnu_loop_stmt) = void_type_node;
1653   TREE_SIDE_EFFECTS (gnu_loop_stmt) = 1;
1654   LOOP_STMT_LABEL (gnu_loop_stmt) = create_artificial_label ();
1655   set_expr_location_from_node (gnu_loop_stmt, gnat_node);
1656   Sloc_to_locus (Sloc (End_Label (gnat_node)),
1657                  &DECL_SOURCE_LOCATION (LOOP_STMT_LABEL (gnu_loop_stmt)));
1658
1659   /* Save the end label of this LOOP_STMT in a stack so that the corresponding
1660      N_Exit_Statement can find it.  */
1661   push_stack (&gnu_loop_label_stack, NULL_TREE,
1662               LOOP_STMT_LABEL (gnu_loop_stmt));
1663
1664   /* Set the condition that under which the loop should continue.
1665      For "LOOP .... END LOOP;" the condition is always true.  */
1666   if (No (gnat_iter_scheme))
1667     ;
1668   /* The case "WHILE condition LOOP ..... END LOOP;" */
1669   else if (Present (Condition (gnat_iter_scheme)))
1670     LOOP_STMT_TOP_COND (gnu_loop_stmt)
1671       = gnat_to_gnu (Condition (gnat_iter_scheme));
1672   else
1673     {
1674       /* We have an iteration scheme.  */
1675       Node_Id gnat_loop_spec = Loop_Parameter_Specification (gnat_iter_scheme);
1676       Entity_Id gnat_loop_var = Defining_Entity (gnat_loop_spec);
1677       Entity_Id gnat_type = Etype (gnat_loop_var);
1678       tree gnu_type = get_unpadded_type (gnat_type);
1679       tree gnu_low = TYPE_MIN_VALUE (gnu_type);
1680       tree gnu_high = TYPE_MAX_VALUE (gnu_type);
1681       bool reversep = Reverse_Present (gnat_loop_spec);
1682       tree gnu_first = reversep ? gnu_high : gnu_low;
1683       tree gnu_last = reversep ? gnu_low : gnu_high;
1684       enum tree_code end_code = reversep ? GE_EXPR : LE_EXPR;
1685       tree gnu_base_type = get_base_type (gnu_type);
1686       tree gnu_limit = (reversep ? TYPE_MIN_VALUE (gnu_base_type)
1687                         : TYPE_MAX_VALUE (gnu_base_type));
1688
1689       /* We know the loop variable will not overflow if GNU_LAST is a constant
1690          and is not equal to GNU_LIMIT.  If it might overflow, we have to move
1691          the limit test to the end of the loop.  In that case, we have to test
1692          for an empty loop outside the loop.  */
1693       if (TREE_CODE (gnu_last) != INTEGER_CST
1694           || TREE_CODE (gnu_limit) != INTEGER_CST
1695           || tree_int_cst_equal (gnu_last, gnu_limit))
1696         {
1697           gnu_cond_expr
1698             = build3 (COND_EXPR, void_type_node,
1699                       build_binary_op (LE_EXPR, integer_type_node,
1700                                        gnu_low, gnu_high),
1701                       NULL_TREE, alloc_stmt_list ());
1702           set_expr_location_from_node (gnu_cond_expr, gnat_loop_spec);
1703         }
1704
1705       /* Open a new nesting level that will surround the loop to declare the
1706          loop index variable.  */
1707       start_stmt_group ();
1708       gnat_pushlevel ();
1709
1710       /* Declare the loop index and set it to its initial value.  */
1711       gnu_loop_var = gnat_to_gnu_entity (gnat_loop_var, gnu_first, 1);
1712       if (DECL_BY_REF_P (gnu_loop_var))
1713         gnu_loop_var = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_loop_var);
1714
1715       /* The loop variable might be a padded type, so use `convert' to get a
1716          reference to the inner variable if so.  */
1717       gnu_loop_var = convert (get_base_type (gnu_type), gnu_loop_var);
1718
1719       /* Set either the top or bottom exit condition as appropriate depending
1720          on whether or not we know an overflow cannot occur. */
1721       if (gnu_cond_expr)
1722         LOOP_STMT_BOT_COND (gnu_loop_stmt)
1723           = build_binary_op (NE_EXPR, integer_type_node,
1724                              gnu_loop_var, gnu_last);
1725       else
1726         LOOP_STMT_TOP_COND (gnu_loop_stmt)
1727           = build_binary_op (end_code, integer_type_node,
1728                              gnu_loop_var, gnu_last);
1729
1730       LOOP_STMT_UPDATE (gnu_loop_stmt)
1731         = build_binary_op (reversep ? PREDECREMENT_EXPR
1732                            : PREINCREMENT_EXPR,
1733                            TREE_TYPE (gnu_loop_var),
1734                            gnu_loop_var,
1735                            convert (TREE_TYPE (gnu_loop_var),
1736                                     integer_one_node));
1737       set_expr_location_from_node (LOOP_STMT_UPDATE (gnu_loop_stmt),
1738                           gnat_iter_scheme);
1739     }
1740
1741   /* If the loop was named, have the name point to this loop.  In this case,
1742      the association is not a ..._DECL node, but the end label from this
1743      LOOP_STMT. */
1744   if (Present (Identifier (gnat_node)))
1745     save_gnu_tree (Entity (Identifier (gnat_node)),
1746                    LOOP_STMT_LABEL (gnu_loop_stmt), true);
1747
1748   /* Make the loop body into its own block, so any allocated storage will be
1749      released every iteration.  This is needed for stack allocation.  */
1750   LOOP_STMT_BODY (gnu_loop_stmt)
1751     = build_stmt_group (Statements (gnat_node), true);
1752
1753   /* If we declared a variable, then we are in a statement group for that
1754      declaration.  Add the LOOP_STMT to it and make that the "loop".  */
1755   if (gnu_loop_var)
1756     {
1757       add_stmt (gnu_loop_stmt);
1758       gnat_poplevel ();
1759       gnu_loop_stmt = end_stmt_group ();
1760     }
1761
1762   /* If we have an outer COND_EXPR, that's our result and this loop is its
1763      "true" statement.  Otherwise, the result is the LOOP_STMT. */
1764   if (gnu_cond_expr)
1765     {
1766       COND_EXPR_THEN (gnu_cond_expr) = gnu_loop_stmt;
1767       gnu_result = gnu_cond_expr;
1768       recalculate_side_effects (gnu_cond_expr);
1769     }
1770   else
1771     gnu_result = gnu_loop_stmt;
1772
1773   pop_stack (&gnu_loop_label_stack);
1774
1775   return gnu_result;
1776 }
1777 \f
1778 /* Emit statements to establish __gnat_handle_vms_condition as a VMS condition
1779    handler for the current function.  */
1780
1781 /* This is implemented by issuing a call to the appropriate VMS specific
1782    builtin.  To avoid having VMS specific sections in the global gigi decls
1783    array, we maintain the decls of interest here.  We can't declare them
1784    inside the function because we must mark them never to be GC'd, which we
1785    can only do at the global level.  */
1786
1787 static GTY(()) tree vms_builtin_establish_handler_decl = NULL_TREE;
1788 static GTY(()) tree gnat_vms_condition_handler_decl = NULL_TREE;
1789
1790 static void
1791 establish_gnat_vms_condition_handler (void)
1792 {
1793   tree establish_stmt;
1794
1795   /* Elaborate the required decls on the first call.  Check on the decl for
1796      the gnat condition handler to decide, as this is one we create so we are
1797      sure that it will be non null on subsequent calls.  The builtin decl is
1798      looked up so remains null on targets where it is not implemented yet.  */
1799   if (gnat_vms_condition_handler_decl == NULL_TREE)
1800     {
1801       vms_builtin_establish_handler_decl
1802         = builtin_decl_for
1803           (get_identifier ("__builtin_establish_vms_condition_handler"));
1804
1805       gnat_vms_condition_handler_decl
1806         = create_subprog_decl (get_identifier ("__gnat_handle_vms_condition"),
1807                                NULL_TREE,
1808                                build_function_type_list (integer_type_node,
1809                                                          ptr_void_type_node,
1810                                                          ptr_void_type_node,
1811                                                          NULL_TREE),
1812                                NULL_TREE, 0, 1, 1, 0, Empty);
1813     }
1814
1815   /* Do nothing if the establish builtin is not available, which might happen
1816      on targets where the facility is not implemented.  */
1817   if (vms_builtin_establish_handler_decl == NULL_TREE)
1818     return;
1819
1820   establish_stmt
1821     = build_call_1_expr (vms_builtin_establish_handler_decl,
1822                          build_unary_op
1823                          (ADDR_EXPR, NULL_TREE,
1824                           gnat_vms_condition_handler_decl));
1825
1826   add_stmt (establish_stmt);
1827 }
1828 \f
1829 /* Subroutine of gnat_to_gnu to process gnat_node, an N_Subprogram_Body.  We
1830    don't return anything.  */
1831
1832 static void
1833 Subprogram_Body_to_gnu (Node_Id gnat_node)
1834 {
1835   /* Defining identifier of a parameter to the subprogram.  */
1836   Entity_Id gnat_param;
1837   /* The defining identifier for the subprogram body. Note that if a
1838      specification has appeared before for this body, then the identifier
1839      occurring in that specification will also be a defining identifier and all
1840      the calls to this subprogram will point to that specification.  */
1841   Entity_Id gnat_subprog_id
1842     = (Present (Corresponding_Spec (gnat_node))
1843        ? Corresponding_Spec (gnat_node) : Defining_Entity (gnat_node));
1844   /* The FUNCTION_DECL node corresponding to the subprogram spec.   */
1845   tree gnu_subprog_decl;
1846   /* The FUNCTION_TYPE node corresponding to the subprogram spec.  */
1847   tree gnu_subprog_type;
1848   tree gnu_cico_list;
1849   tree gnu_result;
1850   VEC(parm_attr,gc) *cache;
1851
1852   /* If this is a generic object or if it has been eliminated,
1853      ignore it.  */
1854   if (Ekind (gnat_subprog_id) == E_Generic_Procedure
1855       || Ekind (gnat_subprog_id) == E_Generic_Function
1856       || Is_Eliminated (gnat_subprog_id))
1857     return;
1858
1859   /* If this subprogram acts as its own spec, define it.  Otherwise, just get
1860      the already-elaborated tree node.  However, if this subprogram had its
1861      elaboration deferred, we will already have made a tree node for it.  So
1862      treat it as not being defined in that case.  Such a subprogram cannot
1863      have an address clause or a freeze node, so this test is safe, though it
1864      does disable some otherwise-useful error checking.  */
1865   gnu_subprog_decl
1866     = gnat_to_gnu_entity (gnat_subprog_id, NULL_TREE,
1867                           Acts_As_Spec (gnat_node)
1868                           && !present_gnu_tree (gnat_subprog_id));
1869
1870   gnu_subprog_type = TREE_TYPE (gnu_subprog_decl);
1871
1872   /* Propagate the debug mode.  */
1873   if (!Needs_Debug_Info (gnat_subprog_id))
1874     DECL_IGNORED_P (gnu_subprog_decl) = 1;
1875
1876   /* Set the line number in the decl to correspond to that of the body so that
1877      the line number notes are written correctly.  */
1878   Sloc_to_locus (Sloc (gnat_node), &DECL_SOURCE_LOCATION (gnu_subprog_decl));
1879
1880   /* Initialize the information structure for the function.  */
1881   allocate_struct_function (gnu_subprog_decl, false);
1882   DECL_STRUCT_FUNCTION (gnu_subprog_decl)->language
1883     = GGC_CNEW (struct language_function);
1884
1885   begin_subprog_body (gnu_subprog_decl);
1886   gnu_cico_list = TYPE_CI_CO_LIST (gnu_subprog_type);
1887
1888   /* If there are Out parameters, we need to ensure that the return statement
1889      properly copies them out.  We do this by making a new block and converting
1890      any inner return into a goto to a label at the end of the block.  */
1891   push_stack (&gnu_return_label_stack, NULL_TREE,
1892               gnu_cico_list ? create_artificial_label () : NULL_TREE);
1893
1894   /* Get a tree corresponding to the code for the subprogram.  */
1895   start_stmt_group ();
1896   gnat_pushlevel ();
1897
1898   /* See if there are any parameters for which we don't yet have GCC entities.
1899      These must be for Out parameters for which we will be making VAR_DECL
1900      nodes here.  Fill them in to TYPE_CI_CO_LIST, which must contain the empty
1901      entry as well.  We can match up the entries because TYPE_CI_CO_LIST is in
1902      the order of the parameters.  */
1903   for (gnat_param = First_Formal_With_Extras (gnat_subprog_id);
1904        Present (gnat_param);
1905        gnat_param = Next_Formal_With_Extras (gnat_param))
1906     if (!present_gnu_tree (gnat_param))
1907       {
1908         /* Skip any entries that have been already filled in; they must
1909            correspond to In Out parameters.  */
1910         for (; gnu_cico_list && TREE_VALUE (gnu_cico_list);
1911              gnu_cico_list = TREE_CHAIN (gnu_cico_list))
1912           ;
1913
1914         /* Do any needed references for padded types.  */
1915         TREE_VALUE (gnu_cico_list)
1916           = convert (TREE_TYPE (TREE_PURPOSE (gnu_cico_list)),
1917                      gnat_to_gnu_entity (gnat_param, NULL_TREE, 1));
1918       }
1919
1920   /* On VMS, establish our condition handler to possibly turn a condition into
1921      the corresponding exception if the subprogram has a foreign convention or
1922      is exported.
1923
1924      To ensure proper execution of local finalizations on condition instances,
1925      we must turn a condition into the corresponding exception even if there
1926      is no applicable Ada handler, and need at least one condition handler per
1927      possible call chain involving GNAT code.  OTOH, establishing the handler
1928      has a cost so we want to minimize the number of subprograms into which
1929      this happens.  The foreign or exported condition is expected to satisfy
1930      all the constraints.  */
1931   if (TARGET_ABI_OPEN_VMS
1932       && (Has_Foreign_Convention (gnat_node) || Is_Exported (gnat_node)))
1933     establish_gnat_vms_condition_handler ();
1934
1935   process_decls (Declarations (gnat_node), Empty, Empty, true, true);
1936
1937   /* Generate the code of the subprogram itself.  A return statement will be
1938      present and any Out parameters will be handled there.  */
1939   add_stmt (gnat_to_gnu (Handled_Statement_Sequence (gnat_node)));
1940   gnat_poplevel ();
1941   gnu_result = end_stmt_group ();
1942
1943   /* If we populated the parameter attributes cache, we need to make sure
1944      that the cached expressions are evaluated on all possible paths.  */
1945   cache = DECL_STRUCT_FUNCTION (gnu_subprog_decl)->language->parm_attr_cache;
1946   if (cache)
1947     {
1948       struct parm_attr *pa;
1949       int i;
1950
1951       start_stmt_group ();
1952
1953       for (i = 0; VEC_iterate (parm_attr, cache, i, pa); i++)
1954         {
1955           if (pa->first)
1956             add_stmt (pa->first);
1957           if (pa->last)
1958             add_stmt (pa->last);
1959           if (pa->length)
1960             add_stmt (pa->length);
1961         }
1962
1963       add_stmt (gnu_result);
1964       gnu_result = end_stmt_group ();
1965     }
1966
1967   /* If we made a special return label, we need to make a block that contains
1968      the definition of that label and the copying to the return value.  That
1969      block first contains the function, then the label and copy statement.  */
1970   if (TREE_VALUE (gnu_return_label_stack))
1971     {
1972       tree gnu_retval;
1973
1974       start_stmt_group ();
1975       gnat_pushlevel ();
1976       add_stmt (gnu_result);
1977       add_stmt (build1 (LABEL_EXPR, void_type_node,
1978                         TREE_VALUE (gnu_return_label_stack)));
1979
1980       gnu_cico_list = TYPE_CI_CO_LIST (gnu_subprog_type);
1981       if (list_length (gnu_cico_list) == 1)
1982         gnu_retval = TREE_VALUE (gnu_cico_list);
1983       else
1984         gnu_retval = gnat_build_constructor (TREE_TYPE (gnu_subprog_type),
1985                                              gnu_cico_list);
1986
1987       if (DECL_P (gnu_retval) && DECL_BY_REF_P (gnu_retval))
1988         gnu_retval = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_retval);
1989
1990       add_stmt_with_node
1991         (build_return_expr (DECL_RESULT (gnu_subprog_decl), gnu_retval),
1992          gnat_node);
1993       gnat_poplevel ();
1994       gnu_result = end_stmt_group ();
1995     }
1996
1997   pop_stack (&gnu_return_label_stack);
1998
1999   /* Set the end location.  */
2000   Sloc_to_locus
2001     ((Present (End_Label (Handled_Statement_Sequence (gnat_node)))
2002       ? Sloc (End_Label (Handled_Statement_Sequence (gnat_node)))
2003       : Sloc (gnat_node)),
2004      &DECL_STRUCT_FUNCTION (gnu_subprog_decl)->function_end_locus);
2005
2006   end_subprog_body (gnu_result);
2007
2008   /* Disconnect the trees for parameters that we made variables for from the
2009      GNAT entities since these are unusable after we end the function.  */
2010   for (gnat_param = First_Formal_With_Extras (gnat_subprog_id);
2011        Present (gnat_param);
2012        gnat_param = Next_Formal_With_Extras (gnat_param))
2013     if (TREE_CODE (get_gnu_tree (gnat_param)) == VAR_DECL)
2014       save_gnu_tree (gnat_param, NULL_TREE, false);
2015
2016   if (DECL_FUNCTION_STUB (gnu_subprog_decl))
2017     build_function_stub (gnu_subprog_decl, gnat_subprog_id);
2018
2019   mark_out_of_scope (Defining_Unit_Name (Specification (gnat_node)));
2020 }
2021 \f
2022 /* Subroutine of gnat_to_gnu to translate gnat_node, either an N_Function_Call
2023    or an N_Procedure_Call_Statement, to a GCC tree, which is returned.
2024    GNU_RESULT_TYPE_P is a pointer to where we should place the result type.
2025    If GNU_TARGET is non-null, this must be a function call and the result
2026    of the call is to be placed into that object.  */
2027
2028 static tree
2029 call_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p, tree gnu_target)
2030 {
2031   tree gnu_result;
2032   /* The GCC node corresponding to the GNAT subprogram name.  This can either
2033      be a FUNCTION_DECL node if we are dealing with a standard subprogram call,
2034      or an indirect reference expression (an INDIRECT_REF node) pointing to a
2035      subprogram.  */
2036   tree gnu_subprog_node = gnat_to_gnu (Name (gnat_node));
2037   /* The FUNCTION_TYPE node giving the GCC type of the subprogram.  */
2038   tree gnu_subprog_type = TREE_TYPE (gnu_subprog_node);
2039   tree gnu_subprog_addr = build_unary_op (ADDR_EXPR, NULL_TREE,
2040                                           gnu_subprog_node);
2041   Entity_Id gnat_formal;
2042   Node_Id gnat_actual;
2043   tree gnu_actual_list = NULL_TREE;
2044   tree gnu_name_list = NULL_TREE;
2045   tree gnu_before_list = NULL_TREE;
2046   tree gnu_after_list = NULL_TREE;
2047   tree gnu_subprog_call;
2048
2049   switch (Nkind (Name (gnat_node)))
2050     {
2051     case N_Identifier:
2052     case N_Operator_Symbol:
2053     case N_Expanded_Name:
2054     case N_Attribute_Reference:
2055       if (Is_Eliminated (Entity (Name (gnat_node))))
2056         Eliminate_Error_Msg (gnat_node, Entity (Name (gnat_node)));
2057     }
2058
2059   gcc_assert (TREE_CODE (gnu_subprog_type) == FUNCTION_TYPE);
2060
2061   /* If we are calling a stubbed function, make this into a raise of
2062      Program_Error.  Elaborate all our args first.  */
2063   if (TREE_CODE (gnu_subprog_node) == FUNCTION_DECL
2064       && DECL_STUBBED_P (gnu_subprog_node))
2065     {
2066       for (gnat_actual = First_Actual (gnat_node);
2067            Present (gnat_actual);
2068            gnat_actual = Next_Actual (gnat_actual))
2069         add_stmt (gnat_to_gnu (gnat_actual));
2070
2071       {
2072         tree call_expr
2073           = build_call_raise (PE_Stubbed_Subprogram_Called, gnat_node,
2074                               N_Raise_Program_Error);
2075
2076         if (Nkind (gnat_node) == N_Function_Call && !gnu_target)
2077           {
2078             *gnu_result_type_p = TREE_TYPE (gnu_subprog_type);
2079             return build1 (NULL_EXPR, *gnu_result_type_p, call_expr);
2080           }
2081         else
2082           return call_expr;
2083       }
2084     }
2085
2086   /* If we are calling by supplying a pointer to a target, set up that
2087      pointer as the first argument.  Use GNU_TARGET if one was passed;
2088      otherwise, make a target by building a variable of the maximum size
2089      of the type.  */
2090   if (TYPE_RETURNS_BY_TARGET_PTR_P (gnu_subprog_type))
2091     {
2092       tree gnu_real_ret_type
2093         = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (gnu_subprog_type)));
2094
2095       if (!gnu_target)
2096         {
2097           tree gnu_obj_type
2098             = maybe_pad_type (gnu_real_ret_type,
2099                               max_size (TYPE_SIZE (gnu_real_ret_type), true),
2100                               0, Etype (Name (gnat_node)), "PAD", false,
2101                               false, false);
2102
2103           /* ??? We may be about to create a static temporary if we happen to
2104              be at the global binding level.  That's a regression from what
2105              the 3.x back-end would generate in the same situation, but we
2106              don't have a mechanism in Gigi for creating automatic variables
2107              in the elaboration routines.  */
2108           gnu_target
2109             = create_var_decl (create_tmp_var_name ("LR"), NULL, gnu_obj_type,
2110                                NULL, false, false, false, false, NULL,
2111                                gnat_node);
2112         }
2113
2114       gnu_actual_list
2115         = tree_cons (NULL_TREE,
2116                      build_unary_op (ADDR_EXPR, NULL_TREE,
2117                                      unchecked_convert (gnu_real_ret_type,
2118                                                         gnu_target,
2119                                                         false)),
2120                      NULL_TREE);
2121
2122     }
2123
2124   /* The only way we can be making a call via an access type is if Name is an
2125      explicit dereference.  In that case, get the list of formal args from the
2126      type the access type is pointing to.  Otherwise, get the formals from
2127      entity being called.  */
2128   if (Nkind (Name (gnat_node)) == N_Explicit_Dereference)
2129     gnat_formal = First_Formal_With_Extras (Etype (Name (gnat_node)));
2130   else if (Nkind (Name (gnat_node)) == N_Attribute_Reference)
2131     /* Assume here that this must be 'Elab_Body or 'Elab_Spec.  */
2132     gnat_formal = 0;
2133   else
2134     gnat_formal = First_Formal_With_Extras (Entity (Name (gnat_node)));
2135
2136   /* Create the list of the actual parameters as GCC expects it, namely a chain
2137      of TREE_LIST nodes in which the TREE_VALUE field of each node is a
2138      parameter-expression and the TREE_PURPOSE field is null.  Skip Out
2139      parameters not passed by reference and don't need to be copied in.  */
2140   for (gnat_actual = First_Actual (gnat_node);
2141        Present (gnat_actual);
2142        gnat_formal = Next_Formal_With_Extras (gnat_formal),
2143        gnat_actual = Next_Actual (gnat_actual))
2144     {
2145       tree gnu_formal
2146         = (present_gnu_tree (gnat_formal)
2147            ? get_gnu_tree (gnat_formal) : NULL_TREE);
2148       tree gnu_formal_type = gnat_to_gnu_type (Etype (gnat_formal));
2149       /* We must suppress conversions that can cause the creation of a
2150          temporary in the Out or In Out case because we need the real
2151          object in this case, either to pass its address if it's passed
2152          by reference or as target of the back copy done after the call
2153          if it uses the copy-in copy-out mechanism.  We do it in the In
2154          case too, except for an unchecked conversion because it alone
2155          can cause the actual to be misaligned and the addressability
2156          test is applied to the real object.  */
2157       bool suppress_type_conversion
2158         = ((Nkind (gnat_actual) == N_Unchecked_Type_Conversion
2159             && Ekind (gnat_formal) != E_In_Parameter)
2160            || (Nkind (gnat_actual) == N_Type_Conversion
2161                && Is_Composite_Type (Underlying_Type (Etype (gnat_formal)))));
2162       Node_Id gnat_name = (suppress_type_conversion
2163                            ? Expression (gnat_actual) : gnat_actual);
2164       tree gnu_name = gnat_to_gnu (gnat_name), gnu_name_type;
2165       tree gnu_actual;
2166
2167       /* If it's possible we may need to use this expression twice, make sure
2168          that any side-effects are handled via SAVE_EXPRs.  Likewise if we need
2169          to force side-effects before the call.
2170          ??? This is more conservative than we need since we don't need to do
2171          this for pass-by-ref with no conversion.  */
2172       if (Ekind (gnat_formal) != E_In_Parameter)
2173         gnu_name = gnat_stabilize_reference (gnu_name, true);
2174
2175       /* If we are passing a non-addressable parameter by reference, pass the
2176          address of a copy.  In the Out or In Out case, set up to copy back
2177          out after the call.  */
2178       if (gnu_formal
2179           && (DECL_BY_REF_P (gnu_formal)
2180               || (TREE_CODE (gnu_formal) == PARM_DECL
2181                   && (DECL_BY_COMPONENT_PTR_P (gnu_formal)
2182                       || (DECL_BY_DESCRIPTOR_P (gnu_formal)))))
2183           && (gnu_name_type = gnat_to_gnu_type (Etype (gnat_name)))
2184           && !addressable_p (gnu_name, gnu_name_type))
2185         {
2186           tree gnu_copy = gnu_name, gnu_temp;
2187
2188           /* If the type is by_reference, a copy is not allowed.  */
2189           if (Is_By_Reference_Type (Etype (gnat_formal)))
2190             post_error
2191               ("misaligned actual cannot be passed by reference", gnat_actual);
2192
2193           /* For users of Starlet we issue a warning because the
2194              interface apparently assumes that by-ref parameters
2195              outlive the procedure invocation.  The code still
2196              will not work as intended, but we cannot do much
2197              better since other low-level parts of the back-end
2198              would allocate temporaries at will because of the
2199              misalignment if we did not do so here.  */
2200           else if (Is_Valued_Procedure (Entity (Name (gnat_node))))
2201             {
2202               post_error
2203                 ("?possible violation of implicit assumption", gnat_actual);
2204               post_error_ne
2205                 ("?made by pragma Import_Valued_Procedure on &", gnat_actual,
2206                  Entity (Name (gnat_node)));
2207               post_error_ne ("?because of misalignment of &", gnat_actual,
2208                              gnat_formal);
2209             }
2210
2211           /* Remove any unpadding from the object and reset the copy.  */
2212           if (TREE_CODE (gnu_name) == COMPONENT_REF
2213               && ((TREE_CODE (TREE_TYPE (TREE_OPERAND (gnu_name, 0)))
2214                    == RECORD_TYPE)
2215                   && (TYPE_IS_PADDING_P
2216                       (TREE_TYPE (TREE_OPERAND (gnu_name, 0))))))
2217             gnu_name = gnu_copy = TREE_OPERAND (gnu_name, 0);
2218
2219           /* Otherwise convert to the nominal type of the object if it's
2220              a record type.  There are several cases in which we need to
2221              make the temporary using this type instead of the actual type
2222              of the object if they are distinct, because the expectations
2223              of the callee would otherwise not be met:
2224                - if it's a justified modular type,
2225                - if the actual type is a smaller packable version of it.  */
2226           else if (TREE_CODE (gnu_name_type) == RECORD_TYPE
2227                    && (TYPE_JUSTIFIED_MODULAR_P (gnu_name_type)
2228                        || smaller_packable_type_p (TREE_TYPE (gnu_name),
2229                                                  gnu_name_type)))
2230             gnu_name = convert (gnu_name_type, gnu_name);
2231
2232           /* Make a SAVE_EXPR to both properly account for potential side
2233              effects and handle the creation of a temporary copy.  Special
2234              code in gnat_gimplify_expr ensures that the same temporary is
2235              used as the object and copied back after the call if needed.  */
2236           gnu_name = build1 (SAVE_EXPR, TREE_TYPE (gnu_name), gnu_name);
2237           TREE_SIDE_EFFECTS (gnu_name) = 1;
2238
2239           /* Set up to move the copy back to the original.  */
2240           if (Ekind (gnat_formal) != E_In_Parameter)
2241             {
2242               gnu_temp = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_copy,
2243                                           gnu_name);
2244               set_expr_location_from_node (gnu_temp, gnat_actual);
2245               append_to_statement_list (gnu_temp, &gnu_after_list);
2246             }
2247         }
2248
2249       /* Start from the real object and build the actual.  */
2250       gnu_actual = gnu_name;
2251
2252       /* If this was a procedure call, we may not have removed any padding.
2253          So do it here for the part we will use as an input, if any.  */
2254       if (Ekind (gnat_formal) != E_Out_Parameter
2255           && TREE_CODE (TREE_TYPE (gnu_actual)) == RECORD_TYPE
2256           && TYPE_IS_PADDING_P (TREE_TYPE (gnu_actual)))
2257         gnu_actual = convert (get_unpadded_type (Etype (gnat_actual)),
2258                               gnu_actual);
2259
2260       /* Do any needed conversions for the actual and make sure that it is
2261          in range of the formal's type.  */
2262       if (suppress_type_conversion)
2263         {
2264           /* Put back the conversion we suppressed above in the computation
2265              of the real object.  Note that we treat a conversion between
2266              aggregate types as if it is an unchecked conversion here.  */
2267           gnu_actual
2268             = unchecked_convert (gnat_to_gnu_type (Etype (gnat_actual)),
2269                                  gnu_actual,
2270                                  (Nkind (gnat_actual)
2271                                   == N_Unchecked_Type_Conversion)
2272                                  && No_Truncation (gnat_actual));
2273
2274           if (Ekind (gnat_formal) != E_Out_Parameter
2275               && Do_Range_Check (gnat_actual))
2276             gnu_actual = emit_range_check (gnu_actual, Etype (gnat_formal));
2277         }
2278       else
2279         {
2280           if (Ekind (gnat_formal) != E_Out_Parameter
2281               && Do_Range_Check (gnat_actual))
2282             gnu_actual = emit_range_check (gnu_actual, Etype (gnat_formal));
2283
2284           /* We may have suppressed a conversion to the Etype of the actual
2285              since the parent is a procedure call.  So put it back here.
2286              ??? We use the reverse order compared to the case above because
2287              of an awkward interaction with the check and actually don't put
2288              back the conversion at all if a check is emitted.  This is also
2289              done for the conversion to the formal's type just below.  */
2290           if (TREE_CODE (gnu_actual) != SAVE_EXPR)
2291             gnu_actual = convert (gnat_to_gnu_type (Etype (gnat_actual)),
2292                                   gnu_actual);
2293         }
2294
2295       if (TREE_CODE (gnu_actual) != SAVE_EXPR)
2296         gnu_actual = convert (gnu_formal_type, gnu_actual);
2297
2298       /* Unless this is an In parameter, we must remove any justified modular
2299          building from GNU_NAME to get an lvalue.  */
2300       if (Ekind (gnat_formal) != E_In_Parameter
2301           && TREE_CODE (gnu_name) == CONSTRUCTOR
2302           && TREE_CODE (TREE_TYPE (gnu_name)) == RECORD_TYPE
2303           && TYPE_JUSTIFIED_MODULAR_P (TREE_TYPE (gnu_name)))
2304         gnu_name = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_name))),
2305                             gnu_name);
2306
2307       /* If we have not saved a GCC object for the formal, it means it is an
2308          Out parameter not passed by reference and that does not need to be
2309          copied in. Otherwise, look at the PARM_DECL to see if it is passed by
2310          reference. */
2311       if (gnu_formal
2312           && TREE_CODE (gnu_formal) == PARM_DECL
2313           && DECL_BY_REF_P (gnu_formal))
2314         {
2315           if (Ekind (gnat_formal) != E_In_Parameter)
2316             {
2317               /* In Out or Out parameters passed by reference don't use the
2318                  copy-in copy-out mechanism so the address of the real object
2319                  must be passed to the function.  */
2320               gnu_actual = gnu_name;
2321
2322               /* If we have a padded type, be sure we've removed padding.  */
2323               if (TREE_CODE (TREE_TYPE (gnu_actual)) == RECORD_TYPE
2324                   && TYPE_IS_PADDING_P (TREE_TYPE (gnu_actual))
2325                   && TREE_CODE (gnu_actual) != SAVE_EXPR)
2326                 gnu_actual = convert (get_unpadded_type (Etype (gnat_actual)),
2327                                       gnu_actual);
2328
2329               /* If we have the constructed subtype of an aliased object
2330                  with an unconstrained nominal subtype, the type of the
2331                  actual includes the template, although it is formally
2332                  constrained.  So we need to convert it back to the real
2333                  constructed subtype to retrieve the constrained part
2334                  and takes its address.  */
2335               if (TREE_CODE (TREE_TYPE (gnu_actual)) == RECORD_TYPE
2336                   && TYPE_CONTAINS_TEMPLATE_P (TREE_TYPE (gnu_actual))
2337                   && TREE_CODE (gnu_actual) != SAVE_EXPR
2338                   && Is_Constr_Subt_For_UN_Aliased (Etype (gnat_actual))
2339                   && Is_Array_Type (Etype (gnat_actual)))
2340                 gnu_actual = convert (gnat_to_gnu_type (Etype (gnat_actual)),
2341                                       gnu_actual);
2342             }
2343
2344           /* The symmetry of the paths to the type of an entity is broken here
2345              since arguments don't know that they will be passed by ref. */
2346           gnu_formal_type = TREE_TYPE (get_gnu_tree (gnat_formal));
2347           gnu_actual = build_unary_op (ADDR_EXPR, gnu_formal_type, gnu_actual);
2348         }
2349       else if (gnu_formal
2350                && TREE_CODE (gnu_formal) == PARM_DECL
2351                && DECL_BY_COMPONENT_PTR_P (gnu_formal))
2352         {
2353           gnu_formal_type = TREE_TYPE (get_gnu_tree (gnat_formal));
2354           gnu_actual = maybe_implicit_deref (gnu_actual);
2355           gnu_actual = maybe_unconstrained_array (gnu_actual);
2356
2357           if (TREE_CODE (gnu_formal_type) == RECORD_TYPE
2358               && TYPE_IS_PADDING_P (gnu_formal_type))
2359             {
2360               gnu_formal_type = TREE_TYPE (TYPE_FIELDS (gnu_formal_type));
2361               gnu_actual = convert (gnu_formal_type, gnu_actual);
2362             }
2363
2364           /* Take the address of the object and convert to the proper pointer
2365              type.  We'd like to actually compute the address of the beginning
2366              of the array using an ADDR_EXPR of an ARRAY_REF, but there's a
2367              possibility that the ARRAY_REF might return a constant and we'd be
2368              getting the wrong address.  Neither approach is exactly correct,
2369              but this is the most likely to work in all cases.  */
2370           gnu_actual = convert (gnu_formal_type,
2371                                 build_unary_op (ADDR_EXPR, NULL_TREE,
2372                                                 gnu_actual));
2373         }
2374       else if (gnu_formal
2375                && TREE_CODE (gnu_formal) == PARM_DECL
2376                && DECL_BY_DESCRIPTOR_P (gnu_formal))
2377         {
2378           /* If arg is 'Null_Parameter, pass zero descriptor.  */
2379           if ((TREE_CODE (gnu_actual) == INDIRECT_REF
2380                || TREE_CODE (gnu_actual) == UNCONSTRAINED_ARRAY_REF)
2381               && TREE_PRIVATE (gnu_actual))
2382             gnu_actual = convert (DECL_ARG_TYPE (get_gnu_tree (gnat_formal)),
2383                                   integer_zero_node);
2384           else
2385             gnu_actual = build_unary_op (ADDR_EXPR, NULL_TREE,
2386                                          fill_vms_descriptor (gnu_actual,
2387                                                               gnat_formal));
2388         }
2389       else
2390         {
2391           tree gnu_actual_size = TYPE_SIZE (TREE_TYPE (gnu_actual));
2392
2393           if (Ekind (gnat_formal) != E_In_Parameter)
2394             gnu_name_list = tree_cons (NULL_TREE, gnu_name, gnu_name_list);
2395
2396           if (!gnu_formal || TREE_CODE (gnu_formal) != PARM_DECL)
2397             continue;
2398
2399           /* If this is 'Null_Parameter, pass a zero even though we are
2400              dereferencing it.  */
2401           else if (TREE_CODE (gnu_actual) == INDIRECT_REF
2402                    && TREE_PRIVATE (gnu_actual)
2403                    && host_integerp (gnu_actual_size, 1)
2404                    && 0 >= compare_tree_int (gnu_actual_size,
2405                                                    BITS_PER_WORD))
2406             gnu_actual
2407               = unchecked_convert (DECL_ARG_TYPE (gnu_formal),
2408                                    convert (gnat_type_for_size
2409                                             (tree_low_cst (gnu_actual_size, 1),
2410                                              1),
2411                                             integer_zero_node),
2412                                    false);
2413           else
2414             gnu_actual = convert (DECL_ARG_TYPE (gnu_formal), gnu_actual);
2415         }
2416
2417       gnu_actual_list = tree_cons (NULL_TREE, gnu_actual, gnu_actual_list);
2418     }
2419
2420   gnu_subprog_call = build_call_list (TREE_TYPE (gnu_subprog_type),
2421                                       gnu_subprog_addr,
2422                                       nreverse (gnu_actual_list));
2423   set_expr_location_from_node (gnu_subprog_call, gnat_node);
2424
2425   /* If we return by passing a target, the result is the target after the
2426      call.  We must not emit the call directly here because this might be
2427      evaluated as part of an expression with conditions to control whether
2428      the call should be emitted or not.  */
2429   if (TYPE_RETURNS_BY_TARGET_PTR_P (gnu_subprog_type))
2430     {
2431       /* Conceptually, what we need is a COMPOUND_EXPR with the call followed
2432          by the target object converted to the proper type.  Doing so would
2433          potentially be very inefficient, however, as this expression might
2434          end up wrapped into an outer SAVE_EXPR later on, which would incur a
2435          pointless temporary copy of the whole object.
2436
2437          What we do instead is build a COMPOUND_EXPR returning the address of
2438          the target, and then dereference.  Wrapping the COMPOUND_EXPR into a
2439          SAVE_EXPR later on then only incurs a pointer copy.  */
2440
2441       tree gnu_result_type
2442         = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (gnu_subprog_type)));
2443
2444       /* Build and return
2445          (result_type) *[gnu_subprog_call (&gnu_target, ...), &gnu_target]  */
2446
2447       tree gnu_target_address
2448         = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_target);
2449       set_expr_location_from_node (gnu_target_address, gnat_node);
2450
2451       gnu_result
2452         = build2 (COMPOUND_EXPR, TREE_TYPE (gnu_target_address),
2453                   gnu_subprog_call, gnu_target_address);
2454
2455       gnu_result
2456         = unchecked_convert (gnu_result_type,
2457                              build_unary_op (INDIRECT_REF, NULL_TREE,
2458                                              gnu_result),
2459                              false);
2460
2461       *gnu_result_type_p = gnu_result_type;
2462       return gnu_result;
2463     }
2464
2465   /* If it is a function call, the result is the call expression unless
2466      a target is specified, in which case we copy the result into the target
2467      and return the assignment statement.  */
2468   else if (Nkind (gnat_node) == N_Function_Call)
2469     {
2470       gnu_result = gnu_subprog_call;
2471
2472       /* If the function returns an unconstrained array or by reference,
2473          we have to de-dereference the pointer.  */
2474       if (TYPE_RETURNS_UNCONSTRAINED_P (gnu_subprog_type)
2475           || TYPE_RETURNS_BY_REF_P (gnu_subprog_type))
2476         gnu_result = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_result);
2477
2478       if (gnu_target)
2479         gnu_result = build_binary_op (MODIFY_EXPR, NULL_TREE,
2480                                       gnu_target, gnu_result);
2481       else
2482         *gnu_result_type_p = get_unpadded_type (Etype (gnat_node));
2483
2484       return gnu_result;
2485     }
2486
2487   /* If this is the case where the GNAT tree contains a procedure call
2488      but the Ada procedure has copy in copy out parameters, the special
2489      parameter passing mechanism must be used.  */
2490   else if (TYPE_CI_CO_LIST (gnu_subprog_type) != NULL_TREE)
2491     {
2492       /* List of FIELD_DECLs associated with the PARM_DECLs of the copy
2493          in copy out parameters.  */
2494       tree scalar_return_list = TYPE_CI_CO_LIST (gnu_subprog_type);
2495       int length = list_length (scalar_return_list);
2496
2497       if (length > 1)
2498         {
2499           tree gnu_name;
2500
2501           gnu_subprog_call = save_expr (gnu_subprog_call);
2502           gnu_name_list = nreverse (gnu_name_list);
2503
2504           /* If any of the names had side-effects, ensure they are all
2505              evaluated before the call.  */
2506           for (gnu_name = gnu_name_list; gnu_name;
2507                gnu_name = TREE_CHAIN (gnu_name))
2508             if (TREE_SIDE_EFFECTS (TREE_VALUE (gnu_name)))
2509               append_to_statement_list (TREE_VALUE (gnu_name),
2510                                         &gnu_before_list);
2511         }
2512
2513       if (Nkind (Name (gnat_node)) == N_Explicit_Dereference)
2514         gnat_formal = First_Formal_With_Extras (Etype (Name (gnat_node)));
2515       else
2516         gnat_formal = First_Formal_With_Extras (Entity (Name (gnat_node)));
2517
2518       for (gnat_actual = First_Actual (gnat_node);
2519            Present (gnat_actual);
2520            gnat_formal = Next_Formal_With_Extras (gnat_formal),
2521            gnat_actual = Next_Actual (gnat_actual))
2522         /* If we are dealing with a copy in copy out parameter, we must
2523            retrieve its value from the record returned in the call.  */
2524         if (!(present_gnu_tree (gnat_formal)
2525               && TREE_CODE (get_gnu_tree (gnat_formal)) == PARM_DECL
2526               && (DECL_BY_REF_P (get_gnu_tree (gnat_formal))
2527                   || (TREE_CODE (get_gnu_tree (gnat_formal)) == PARM_DECL
2528                       && ((DECL_BY_COMPONENT_PTR_P (get_gnu_tree (gnat_formal))
2529                            || (DECL_BY_DESCRIPTOR_P
2530                                (get_gnu_tree (gnat_formal))))))))
2531             && Ekind (gnat_formal) != E_In_Parameter)
2532           {
2533             /* Get the value to assign to this Out or In Out parameter.  It is
2534                either the result of the function if there is only a single such
2535                parameter or the appropriate field from the record returned.  */
2536             tree gnu_result
2537               = length == 1 ? gnu_subprog_call
2538                 : build_component_ref (gnu_subprog_call, NULL_TREE,
2539                                        TREE_PURPOSE (scalar_return_list),
2540                                        false);
2541
2542             /* If the actual is a conversion, get the inner expression, which
2543                will be the real destination, and convert the result to the
2544                type of the actual parameter.  */
2545             tree gnu_actual
2546               = maybe_unconstrained_array (TREE_VALUE (gnu_name_list));
2547
2548             /* If the result is a padded type, remove the padding.  */
2549             if (TREE_CODE (TREE_TYPE (gnu_result)) == RECORD_TYPE
2550                 && TYPE_IS_PADDING_P (TREE_TYPE (gnu_result)))
2551               gnu_result = convert (TREE_TYPE (TYPE_FIELDS
2552                                                (TREE_TYPE (gnu_result))),
2553                                     gnu_result);
2554
2555             /* If the actual is a type conversion, the real target object is
2556                denoted by the inner Expression and we need to convert the
2557                result to the associated type.
2558                We also need to convert our gnu assignment target to this type
2559                if the corresponding GNU_NAME was constructed from the GNAT
2560                conversion node and not from the inner Expression.  */
2561             if (Nkind (gnat_actual) == N_Type_Conversion)
2562               {
2563                 gnu_result
2564                   = convert_with_check
2565                     (Etype (Expression (gnat_actual)), gnu_result,
2566                      Do_Overflow_Check (gnat_actual),
2567                      Do_Range_Check (Expression (gnat_actual)),
2568                      Float_Truncate (gnat_actual));
2569
2570                 if (!Is_Composite_Type (Underlying_Type (Etype (gnat_formal))))
2571                   gnu_actual = convert (TREE_TYPE (gnu_result), gnu_actual);
2572               }
2573
2574             /* Unchecked conversions as actuals for Out parameters are not
2575                allowed in user code because they are not variables, but do
2576                occur in front-end expansions.  The associated GNU_NAME is
2577                always obtained from the inner expression in such cases.  */
2578             else if (Nkind (gnat_actual) == N_Unchecked_Type_Conversion)
2579               gnu_result = unchecked_convert (TREE_TYPE (gnu_actual),
2580                                               gnu_result,
2581                                               No_Truncation (gnat_actual));
2582             else
2583               {
2584                 if (Do_Range_Check (gnat_actual))
2585                   gnu_result = emit_range_check (gnu_result,
2586                                                  Etype (gnat_actual));
2587
2588                 if (!(!TREE_CONSTANT (TYPE_SIZE (TREE_TYPE (gnu_actual)))
2589                       && TREE_CONSTANT (TYPE_SIZE (TREE_TYPE (gnu_result)))))
2590                   gnu_result = convert (TREE_TYPE (gnu_actual), gnu_result);
2591               }
2592
2593             gnu_result = build_binary_op (MODIFY_EXPR, NULL_TREE,
2594                                           gnu_actual, gnu_result);
2595             set_expr_location_from_node (gnu_result, gnat_actual);
2596             append_to_statement_list (gnu_result, &gnu_before_list);
2597             scalar_return_list = TREE_CHAIN (scalar_return_list);
2598             gnu_name_list = TREE_CHAIN (gnu_name_list);
2599           }
2600         }
2601   else
2602     append_to_statement_list (gnu_subprog_call, &gnu_before_list);
2603
2604   append_to_statement_list (gnu_after_list, &gnu_before_list);
2605   return gnu_before_list;
2606 }
2607 \f
2608 /* Subroutine of gnat_to_gnu to translate gnat_node, an
2609    N_Handled_Sequence_Of_Statements, to a GCC tree, which is returned.  */
2610
2611 static tree
2612 Handled_Sequence_Of_Statements_to_gnu (Node_Id gnat_node)
2613 {
2614   tree gnu_jmpsave_decl = NULL_TREE;
2615   tree gnu_jmpbuf_decl = NULL_TREE;
2616   /* If just annotating, ignore all EH and cleanups.  */
2617   bool gcc_zcx = (!type_annotate_only
2618                   && Present (Exception_Handlers (gnat_node))
2619                   && Exception_Mechanism == Back_End_Exceptions);
2620   bool setjmp_longjmp
2621     = (!type_annotate_only && Present (Exception_Handlers (gnat_node))
2622        && Exception_Mechanism == Setjmp_Longjmp);
2623   bool at_end = !type_annotate_only && Present (At_End_Proc (gnat_node));
2624   bool binding_for_block = (at_end || gcc_zcx || setjmp_longjmp);
2625   tree gnu_inner_block; /* The statement(s) for the block itself.  */
2626   tree gnu_result;
2627   tree gnu_expr;
2628   Node_Id gnat_temp;
2629
2630   /* The GCC exception handling mechanism can handle both ZCX and SJLJ schemes
2631      and we have our own SJLJ mechanism.  To call the GCC mechanism, we call
2632      add_cleanup, and when we leave the binding, end_stmt_group will create
2633      the TRY_FINALLY_EXPR.
2634
2635      ??? The region level calls down there have been specifically put in place
2636      for a ZCX context and currently the order in which things are emitted
2637      (region/handlers) is different from the SJLJ case. Instead of putting
2638      other calls with different conditions at other places for the SJLJ case,
2639      it seems cleaner to reorder things for the SJLJ case and generalize the
2640      condition to make it not ZCX specific.
2641
2642      If there are any exceptions or cleanup processing involved, we need an
2643      outer statement group (for Setjmp_Longjmp) and binding level.  */
2644   if (binding_for_block)
2645     {
2646       start_stmt_group ();
2647       gnat_pushlevel ();
2648     }
2649
2650   /* If using setjmp_longjmp, make the variables for the setjmp buffer and save
2651      area for address of previous buffer.  Do this first since we need to have
2652      the setjmp buf known for any decls in this block.  */
2653   if (setjmp_longjmp)
2654     {
2655       gnu_jmpsave_decl = create_var_decl (get_identifier ("JMPBUF_SAVE"),
2656                                           NULL_TREE, jmpbuf_ptr_type,
2657                                           build_call_0_expr (get_jmpbuf_decl),
2658                                           false, false, false, false, NULL,
2659                                           gnat_node);
2660       DECL_ARTIFICIAL (gnu_jmpsave_decl) = 1;
2661
2662       /* The __builtin_setjmp receivers will immediately reinstall it.  Now
2663          because of the unstructured form of EH used by setjmp_longjmp, there
2664          might be forward edges going to __builtin_setjmp receivers on which
2665          it is uninitialized, although they will never be actually taken.  */
2666       TREE_NO_WARNING (gnu_jmpsave_decl) = 1;
2667       gnu_jmpbuf_decl = create_var_decl (get_identifier ("JMP_BUF"),
2668                                          NULL_TREE, jmpbuf_type,
2669                                          NULL_TREE, false, false, false, false,
2670                                          NULL, gnat_node);
2671       DECL_ARTIFICIAL (gnu_jmpbuf_decl) = 1;
2672
2673       set_block_jmpbuf_decl (gnu_jmpbuf_decl);
2674
2675       /* When we exit this block, restore the saved value.  */
2676       add_cleanup (build_call_1_expr (set_jmpbuf_decl, gnu_jmpsave_decl),
2677                    End_Label (gnat_node));
2678     }
2679
2680   /* If we are to call a function when exiting this block, add a cleanup
2681      to the binding level we made above.  Note that add_cleanup is FIFO
2682      so we must register this cleanup after the EH cleanup just above.  */
2683   if (at_end)
2684     add_cleanup (build_call_0_expr (gnat_to_gnu (At_End_Proc (gnat_node))),
2685                  End_Label (gnat_node));
2686
2687   /* Now build the tree for the declarations and statements inside this block.
2688      If this is SJLJ, set our jmp_buf as the current buffer.  */
2689   start_stmt_group ();
2690
2691   if (setjmp_longjmp)
2692     add_stmt (build_call_1_expr (set_jmpbuf_decl,
2693                                  build_unary_op (ADDR_EXPR, NULL_TREE,
2694                                                  gnu_jmpbuf_decl)));
2695
2696   if (Present (First_Real_Statement (gnat_node)))
2697     process_decls (Statements (gnat_node), Empty,
2698                    First_Real_Statement (gnat_node), true, true);
2699
2700   /* Generate code for each statement in the block.  */
2701   for (gnat_temp = (Present (First_Real_Statement (gnat_node))
2702                     ? First_Real_Statement (gnat_node)
2703                     : First (Statements (gnat_node)));
2704        Present (gnat_temp); gnat_temp = Next (gnat_temp))
2705     add_stmt (gnat_to_gnu (gnat_temp));
2706   gnu_inner_block = end_stmt_group ();
2707
2708   /* Now generate code for the two exception models, if either is relevant for
2709      this block.  */
2710   if (setjmp_longjmp)
2711     {
2712       tree *gnu_else_ptr = 0;
2713       tree gnu_handler;
2714
2715       /* Make a binding level for the exception handling declarations and code
2716          and set up gnu_except_ptr_stack for the handlers to use.  */
2717       start_stmt_group ();
2718       gnat_pushlevel ();
2719
2720       push_stack (&gnu_except_ptr_stack, NULL_TREE,
2721                   create_var_decl (get_identifier ("EXCEPT_PTR"),
2722                                    NULL_TREE,
2723                                    build_pointer_type (except_type_node),
2724                                    build_call_0_expr (get_excptr_decl), false,
2725                                    false, false, false, NULL, gnat_node));
2726
2727       /* Generate code for each handler. The N_Exception_Handler case does the
2728          real work and returns a COND_EXPR for each handler, which we chain
2729          together here.  */
2730       for (gnat_temp = First_Non_Pragma (Exception_Handlers (gnat_node));
2731            Present (gnat_temp); gnat_temp = Next_Non_Pragma (gnat_temp))
2732         {
2733           gnu_expr = gnat_to_gnu (gnat_temp);
2734
2735           /* If this is the first one, set it as the outer one. Otherwise,
2736              point the "else" part of the previous handler to us. Then point
2737              to our "else" part.  */
2738           if (!gnu_else_ptr)
2739             add_stmt (gnu_expr);
2740           else
2741             *gnu_else_ptr = gnu_expr;
2742
2743           gnu_else_ptr = &COND_EXPR_ELSE (gnu_expr);
2744         }
2745
2746       /* If none of the exception handlers did anything, re-raise but do not
2747          defer abortion.  */
2748       gnu_expr = build_call_1_expr (raise_nodefer_decl,
2749                                     TREE_VALUE (gnu_except_ptr_stack));
2750       set_expr_location_from_node (gnu_expr, gnat_node);
2751
2752       if (gnu_else_ptr)
2753         *gnu_else_ptr = gnu_expr;
2754       else
2755         add_stmt (gnu_expr);
2756
2757       /* End the binding level dedicated to the exception handlers and get the
2758          whole statement group.  */
2759       pop_stack (&gnu_except_ptr_stack);
2760       gnat_poplevel ();
2761       gnu_handler = end_stmt_group ();
2762
2763       /* If the setjmp returns 1, we restore our incoming longjmp value and
2764          then check the handlers.  */
2765       start_stmt_group ();
2766       add_stmt_with_node (build_call_1_expr (set_jmpbuf_decl,
2767                                              gnu_jmpsave_decl),
2768                           gnat_node);
2769       add_stmt (gnu_handler);
2770       gnu_handler = end_stmt_group ();
2771
2772       /* This block is now "if (setjmp) ... <handlers> else <block>".  */
2773       gnu_result = build3 (COND_EXPR, void_type_node,
2774                            (build_call_1_expr
2775                             (setjmp_decl,
2776                              build_unary_op (ADDR_EXPR, NULL_TREE,
2777                                              gnu_jmpbuf_decl))),
2778                            gnu_handler, gnu_inner_block);
2779     }
2780   else if (gcc_zcx)
2781     {
2782       tree gnu_handlers;
2783
2784       /* First make a block containing the handlers.  */
2785       start_stmt_group ();
2786       for (gnat_temp = First_Non_Pragma (Exception_Handlers (gnat_node));
2787            Present (gnat_temp);
2788            gnat_temp = Next_Non_Pragma (gnat_temp))
2789         add_stmt (gnat_to_gnu (gnat_temp));
2790       gnu_handlers = end_stmt_group ();
2791
2792       /* Now make the TRY_CATCH_EXPR for the block.  */
2793       gnu_result = build2 (TRY_CATCH_EXPR, void_type_node,
2794                            gnu_inner_block, gnu_handlers);
2795     }
2796   else
2797     gnu_result = gnu_inner_block;
2798
2799   /* Now close our outer block, if we had to make one.  */
2800   if (binding_for_block)
2801     {
2802       add_stmt (gnu_result);
2803       gnat_poplevel ();
2804       gnu_result = end_stmt_group ();
2805     }
2806
2807   return gnu_result;
2808 }
2809 \f
2810 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Exception_Handler,
2811    to a GCC tree, which is returned.  This is the variant for Setjmp_Longjmp
2812    exception handling.  */
2813
2814 static tree
2815 Exception_Handler_to_gnu_sjlj (Node_Id gnat_node)
2816 {
2817   /* Unless this is "Others" or the special "Non-Ada" exception for Ada, make
2818      an "if" statement to select the proper exceptions.  For "Others", exclude
2819      exceptions where Handled_By_Others is nonzero unless the All_Others flag
2820      is set. For "Non-ada", accept an exception if "Lang" is 'V'.  */
2821   tree gnu_choice = integer_zero_node;
2822   tree gnu_body = build_stmt_group (Statements (gnat_node), false);
2823   Node_Id gnat_temp;
2824
2825   for (gnat_temp = First (Exception_Choices (gnat_node));
2826        gnat_temp; gnat_temp = Next (gnat_temp))
2827     {
2828       tree this_choice;
2829
2830       if (Nkind (gnat_temp) == N_Others_Choice)
2831         {
2832           if (All_Others (gnat_temp))
2833             this_choice = integer_one_node;
2834           else
2835             this_choice
2836               = build_binary_op
2837                 (EQ_EXPR, integer_type_node,
2838                  convert
2839                  (integer_type_node,
2840                   build_component_ref
2841                   (build_unary_op
2842                    (INDIRECT_REF, NULL_TREE,
2843                     TREE_VALUE (gnu_except_ptr_stack)),
2844                    get_identifier ("not_handled_by_others"), NULL_TREE,
2845                    false)),
2846                  integer_zero_node);
2847         }
2848
2849       else if (Nkind (gnat_temp) == N_Identifier
2850                || Nkind (gnat_temp) == N_Expanded_Name)
2851         {
2852           Entity_Id gnat_ex_id = Entity (gnat_temp);
2853           tree gnu_expr;
2854
2855           /* Exception may be a renaming. Recover original exception which is
2856              the one elaborated and registered.  */
2857           if (Present (Renamed_Object (gnat_ex_id)))
2858             gnat_ex_id = Renamed_Object (gnat_ex_id);
2859
2860           gnu_expr = gnat_to_gnu_entity (gnat_ex_id, NULL_TREE, 0);
2861
2862           this_choice
2863             = build_binary_op
2864               (EQ_EXPR, integer_type_node, TREE_VALUE (gnu_except_ptr_stack),
2865                convert (TREE_TYPE (TREE_VALUE (gnu_except_ptr_stack)),
2866                         build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr)));
2867
2868           /* If this is the distinguished exception "Non_Ada_Error" (and we are
2869              in VMS mode), also allow a non-Ada exception (a VMS condition) t
2870              match.  */
2871           if (Is_Non_Ada_Error (Entity (gnat_temp)))
2872             {
2873               tree gnu_comp
2874                 = build_component_ref
2875                   (build_unary_op (INDIRECT_REF, NULL_TREE,
2876                                    TREE_VALUE (gnu_except_ptr_stack)),
2877                    get_identifier ("lang"), NULL_TREE, false);
2878
2879               this_choice
2880                 = build_binary_op
2881                   (TRUTH_ORIF_EXPR, integer_type_node,
2882                    build_binary_op (EQ_EXPR, integer_type_node, gnu_comp,
2883                                     build_int_cst (TREE_TYPE (gnu_comp), 'V')),
2884                    this_choice);
2885             }
2886         }
2887       else
2888         gcc_unreachable ();
2889
2890       gnu_choice = build_binary_op (TRUTH_ORIF_EXPR, integer_type_node,
2891                                     gnu_choice, this_choice);
2892     }
2893
2894   return build3 (COND_EXPR, void_type_node, gnu_choice, gnu_body, NULL_TREE);
2895 }
2896 \f
2897 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Exception_Handler,
2898    to a GCC tree, which is returned.  This is the variant for ZCX.  */
2899
2900 static tree
2901 Exception_Handler_to_gnu_zcx (Node_Id gnat_node)
2902 {
2903   tree gnu_etypes_list = NULL_TREE;
2904   tree gnu_expr;
2905   tree gnu_etype;
2906   tree gnu_current_exc_ptr;
2907   tree gnu_incoming_exc_ptr;
2908   Node_Id gnat_temp;
2909
2910   /* We build a TREE_LIST of nodes representing what exception types this
2911      handler can catch, with special cases for others and all others cases.
2912
2913      Each exception type is actually identified by a pointer to the exception
2914      id, or to a dummy object for "others" and "all others".
2915
2916      Care should be taken to ensure that the control flow impact of "others"
2917      and "all others" is known to GCC. lang_eh_type_covers is doing the trick
2918      currently.  */
2919   for (gnat_temp = First (Exception_Choices (gnat_node));
2920        gnat_temp; gnat_temp = Next (gnat_temp))
2921     {
2922       if (Nkind (gnat_temp) == N_Others_Choice)
2923         {
2924           tree gnu_expr
2925             = All_Others (gnat_temp) ? all_others_decl : others_decl;
2926
2927           gnu_etype
2928             = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr);
2929         }
2930       else if (Nkind (gnat_temp) == N_Identifier
2931                || Nkind (gnat_temp) == N_Expanded_Name)
2932         {
2933           Entity_Id gnat_ex_id = Entity (gnat_temp);
2934
2935           /* Exception may be a renaming. Recover original exception which is
2936              the one elaborated and registered.  */
2937           if (Present (Renamed_Object (gnat_ex_id)))
2938             gnat_ex_id = Renamed_Object (gnat_ex_id);
2939
2940           gnu_expr = gnat_to_gnu_entity (gnat_ex_id, NULL_TREE, 0);
2941           gnu_etype = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr);
2942
2943           /* The Non_Ada_Error case for VMS exceptions is handled
2944              by the personality routine.  */
2945         }
2946       else
2947         gcc_unreachable ();
2948
2949       /* The GCC interface expects NULL to be passed for catch all handlers, so
2950          it would be quite tempting to set gnu_etypes_list to NULL if gnu_etype
2951          is integer_zero_node.  It would not work, however, because GCC's
2952          notion of "catch all" is stronger than our notion of "others".  Until
2953          we correctly use the cleanup interface as well, doing that would
2954          prevent the "all others" handlers from being seen, because nothing
2955          can be caught beyond a catch all from GCC's point of view.  */
2956       gnu_etypes_list = tree_cons (NULL_TREE, gnu_etype, gnu_etypes_list);
2957     }
2958
2959   start_stmt_group ();
2960   gnat_pushlevel ();
2961
2962   /* Expand a call to the begin_handler hook at the beginning of the handler,
2963      and arrange for a call to the end_handler hook to occur on every possible
2964      exit path.
2965
2966      The hooks expect a pointer to the low level occurrence. This is required
2967      for our stack management scheme because a raise inside the handler pushes
2968      a new occurrence on top of the stack, which means that this top does not
2969      necessarily match the occurrence this handler was dealing with.
2970
2971      The EXC_PTR_EXPR object references the exception occurrence being
2972      propagated. Upon handler entry, this is the exception for which the
2973      handler is triggered. This might not be the case upon handler exit,
2974      however, as we might have a new occurrence propagated by the handler's
2975      body, and the end_handler hook called as a cleanup in this context.
2976
2977      We use a local variable to retrieve the incoming value at handler entry
2978      time, and reuse it to feed the end_handler hook's argument at exit.  */
2979   gnu_current_exc_ptr = build0 (EXC_PTR_EXPR, ptr_type_node);
2980   gnu_incoming_exc_ptr = create_var_decl (get_identifier ("EXPTR"), NULL_TREE,
2981                                           ptr_type_node, gnu_current_exc_ptr,
2982                                           false, false, false, false, NULL,
2983                                           gnat_node);
2984
2985   add_stmt_with_node (build_call_1_expr (begin_handler_decl,
2986                                          gnu_incoming_exc_ptr),
2987                       gnat_node);
2988   /* ??? We don't seem to have an End_Label at hand to set the location.  */
2989   add_cleanup (build_call_1_expr (end_handler_decl, gnu_incoming_exc_ptr),
2990                Empty);
2991   add_stmt_list (Statements (gnat_node));
2992   gnat_poplevel ();
2993
2994   return build2 (CATCH_EXPR, void_type_node, gnu_etypes_list,
2995                  end_stmt_group ());
2996 }
2997 \f
2998 /* Subroutine of gnat_to_gnu to generate code for an N_Compilation unit.  */
2999
3000 static void
3001 Compilation_Unit_to_gnu (Node_Id gnat_node)
3002 {
3003   /* Make the decl for the elaboration procedure.  */
3004   bool body_p = (Defining_Entity (Unit (gnat_node)),
3005             Nkind (Unit (gnat_node)) == N_Package_Body
3006             || Nkind (Unit (gnat_node)) == N_Subprogram_Body);
3007   Entity_Id gnat_unit_entity = Defining_Entity (Unit (gnat_node));
3008   tree gnu_elab_proc_decl
3009     = create_subprog_decl
3010       (create_concat_name (gnat_unit_entity,
3011                            body_p ? "elabb" : "elabs"),
3012        NULL_TREE, void_ftype, NULL_TREE, false, true, false, NULL,
3013        gnat_unit_entity);
3014   struct elab_info *info;
3015
3016   push_stack (&gnu_elab_proc_stack, NULL_TREE, gnu_elab_proc_decl);
3017
3018   DECL_ELABORATION_PROC_P (gnu_elab_proc_decl) = 1;
3019   allocate_struct_function (gnu_elab_proc_decl, false);
3020   Sloc_to_locus (Sloc (gnat_unit_entity), &cfun->function_end_locus);
3021   set_cfun (NULL);
3022
3023   /* For a body, first process the spec if there is one. */
3024   if (Nkind (Unit (gnat_node)) == N_Package_Body
3025       || (Nkind (Unit (gnat_node)) == N_Subprogram_Body
3026               && !Acts_As_Spec (gnat_node)))
3027     {
3028       add_stmt (gnat_to_gnu (Library_Unit (gnat_node)));
3029       finalize_from_with_types ();
3030     }
3031
3032   process_inlined_subprograms (gnat_node);
3033
3034   if (type_annotate_only && gnat_node == Cunit (Main_Unit))
3035     {
3036       elaborate_all_entities (gnat_node);
3037
3038       if (Nkind (Unit (gnat_node)) == N_Subprogram_Declaration
3039           || Nkind (Unit (gnat_node)) == N_Generic_Package_Declaration
3040           || Nkind (Unit (gnat_node)) == N_Generic_Subprogram_Declaration)
3041         return;
3042     }
3043
3044   process_decls (Declarations (Aux_Decls_Node (gnat_node)), Empty, Empty,
3045                  true, true);
3046   add_stmt (gnat_to_gnu (Unit (gnat_node)));
3047
3048   /* Process any pragmas and actions following the unit.  */
3049   add_stmt_list (Pragmas_After (Aux_Decls_Node (gnat_node)));
3050   add_stmt_list (Actions (Aux_Decls_Node (gnat_node)));
3051   finalize_from_with_types ();
3052
3053   /* Save away what we've made so far and record this potential elaboration
3054      procedure.  */
3055   info = (struct elab_info *) ggc_alloc (sizeof (struct elab_info));
3056   set_current_block_context (gnu_elab_proc_decl);
3057   gnat_poplevel ();
3058   DECL_SAVED_TREE (gnu_elab_proc_decl) = end_stmt_group ();
3059   info->next = elab_info_list;
3060   info->elab_proc = gnu_elab_proc_decl;
3061   info->gnat_node = gnat_node;
3062   elab_info_list = info;
3063
3064   /* Generate elaboration code for this unit, if necessary, and say whether
3065      we did or not.  */
3066   pop_stack (&gnu_elab_proc_stack);
3067
3068   /* Invalidate the global renaming pointers.  This is necessary because
3069      stabilization of the renamed entities may create SAVE_EXPRs which
3070      have been tied to a specific elaboration routine just above.  */
3071   invalidate_global_renaming_pointers ();
3072 }
3073 \f
3074 /* This function is the driver of the GNAT to GCC tree transformation
3075    process.  It is the entry point of the tree transformer.  GNAT_NODE is the
3076    root of some GNAT tree.  Return the root of the corresponding GCC tree.
3077    If this is an expression, return the GCC equivalent of the expression.  If
3078    it is a statement, return the statement.  In the case when called for a
3079    statement, it may also add statements to the current statement group, in
3080    which case anything it returns is to be interpreted as occurring after
3081    anything `it already added.  */
3082
3083 tree
3084 gnat_to_gnu (Node_Id gnat_node)
3085 {
3086   bool went_into_elab_proc = false;
3087   tree gnu_result = error_mark_node; /* Default to no value. */
3088   tree gnu_result_type = void_type_node;
3089   tree gnu_expr;
3090   tree gnu_lhs, gnu_rhs;
3091   Node_Id gnat_temp;
3092
3093   /* Save node number for error message and set location information.  */
3094   error_gnat_node = gnat_node;
3095   Sloc_to_locus (Sloc (gnat_node), &input_location);
3096
3097   if (type_annotate_only
3098       && IN (Nkind (gnat_node), N_Statement_Other_Than_Procedure_Call))
3099     return alloc_stmt_list ();
3100
3101   /* If this node is a non-static subexpression and we are only
3102      annotating types, make this into a NULL_EXPR.  */
3103   if (type_annotate_only
3104       && IN (Nkind (gnat_node), N_Subexpr)
3105       && Nkind (gnat_node) != N_Identifier
3106       && !Compile_Time_Known_Value (gnat_node))
3107     return build1 (NULL_EXPR, get_unpadded_type (Etype (gnat_node)),
3108                    build_call_raise (CE_Range_Check_Failed, gnat_node,
3109                                      N_Raise_Constraint_Error));
3110
3111   /* If this is a Statement and we are at top level, it must be part of the
3112      elaboration procedure, so mark us as being in that procedure and push our
3113      context.
3114
3115      If we are in the elaboration procedure, check if we are violating a
3116      No_Elaboration_Code restriction by having a statement there.  */
3117   if ((IN (Nkind (gnat_node), N_Statement_Other_Than_Procedure_Call)
3118        && Nkind (gnat_node) != N_Null_Statement)
3119       || Nkind (gnat_node) == N_Procedure_Call_Statement
3120       || Nkind (gnat_node) == N_Label
3121       || Nkind (gnat_node) == N_Implicit_Label_Declaration
3122       || Nkind (gnat_node) == N_Handled_Sequence_Of_Statements
3123       || ((Nkind (gnat_node) == N_Raise_Constraint_Error
3124            || Nkind (gnat_node) == N_Raise_Storage_Error
3125            || Nkind (gnat_node) == N_Raise_Program_Error)
3126           && (Ekind (Etype (gnat_node)) == E_Void)))
3127     {
3128       if (!current_function_decl)
3129         {
3130           current_function_decl = TREE_VALUE (gnu_elab_proc_stack);
3131           start_stmt_group ();
3132           gnat_pushlevel ();
3133           went_into_elab_proc = true;
3134         }
3135
3136       /* Don't check for a possible No_Elaboration_Code restriction violation
3137          on N_Handled_Sequence_Of_Statements, as we want to signal an error on
3138          every nested real statement instead.  This also avoids triggering
3139          spurious errors on dummy (empty) sequences created by the front-end
3140          for package bodies in some cases.  */
3141
3142       if (current_function_decl == TREE_VALUE (gnu_elab_proc_stack)
3143           && Nkind (gnat_node) != N_Handled_Sequence_Of_Statements)
3144         Check_Elaboration_Code_Allowed (gnat_node);
3145     }
3146
3147   switch (Nkind (gnat_node))
3148     {
3149       /********************************/
3150       /* Chapter 2: Lexical Elements: */
3151       /********************************/
3152
3153     case N_Identifier:
3154     case N_Expanded_Name:
3155     case N_Operator_Symbol:
3156     case N_Defining_Identifier:
3157       gnu_result = Identifier_to_gnu (gnat_node, &gnu_result_type);
3158       break;
3159
3160     case N_Integer_Literal:
3161       {
3162         tree gnu_type;
3163
3164         /* Get the type of the result, looking inside any padding and
3165            justified modular types.  Then get the value in that type.  */
3166         gnu_type = gnu_result_type = get_unpadded_type (Etype (gnat_node));
3167
3168         if (TREE_CODE (gnu_type) == RECORD_TYPE
3169             && TYPE_JUSTIFIED_MODULAR_P (gnu_type))
3170           gnu_type = TREE_TYPE (TYPE_FIELDS (gnu_type));
3171
3172         gnu_result = UI_To_gnu (Intval (gnat_node), gnu_type);
3173
3174         /* If the result overflows (meaning it doesn't fit in its base type),
3175            abort.  We would like to check that the value is within the range
3176            of the subtype, but that causes problems with subtypes whose usage
3177            will raise Constraint_Error and with biased representation, so
3178            we don't.  */
3179         gcc_assert (!TREE_OVERFLOW (gnu_result));
3180       }
3181       break;
3182
3183     case N_Character_Literal:
3184       /* If a Entity is present, it means that this was one of the
3185          literals in a user-defined character type.  In that case,
3186          just return the value in the CONST_DECL.  Otherwise, use the
3187          character code.  In that case, the base type should be an
3188          INTEGER_TYPE, but we won't bother checking for that.  */
3189       gnu_result_type = get_unpadded_type (Etype (gnat_node));
3190       if (Present (Entity (gnat_node)))
3191         gnu_result = DECL_INITIAL (get_gnu_tree (Entity (gnat_node)));
3192       else
3193         gnu_result
3194           = build_int_cst_type
3195               (gnu_result_type, UI_To_CC (Char_Literal_Value (gnat_node)));
3196       break;
3197
3198     case N_Real_Literal:
3199       /* If this is of a fixed-point type, the value we want is the
3200          value of the corresponding integer.  */
3201       if (IN (Ekind (Underlying_Type (Etype (gnat_node))), Fixed_Point_Kind))
3202         {
3203           gnu_result_type = get_unpadded_type (Etype (gnat_node));
3204           gnu_result = UI_To_gnu (Corresponding_Integer_Value (gnat_node),
3205                                   gnu_result_type);
3206           gcc_assert (!TREE_OVERFLOW (gnu_result));
3207         }
3208
3209       /* We should never see a Vax_Float type literal, since the front end
3210          is supposed to transform these using appropriate conversions */
3211       else if (Vax_Float (Underlying_Type (Etype (gnat_node))))
3212         gcc_unreachable ();
3213
3214       else
3215         {
3216           Ureal ur_realval = Realval (gnat_node);
3217
3218           gnu_result_type = get_unpadded_type (Etype (gnat_node));
3219
3220           /* If the real value is zero, so is the result.  Otherwise,
3221              convert it to a machine number if it isn't already.  That
3222              forces BASE to 0 or 2 and simplifies the rest of our logic.  */
3223           if (UR_Is_Zero (ur_realval))
3224             gnu_result = convert (gnu_result_type, integer_zero_node);
3225           else
3226             {
3227               if (!Is_Machine_Number (gnat_node))
3228                 ur_realval
3229                   = Machine (Base_Type (Underlying_Type (Etype (gnat_node))),
3230                              ur_realval, Round_Even, gnat_node);
3231
3232               gnu_result
3233                 = UI_To_gnu (Numerator (ur_realval), gnu_result_type);
3234
3235               /* If we have a base of zero, divide by the denominator.
3236                  Otherwise, the base must be 2 and we scale the value, which
3237                  we know can fit in the mantissa of the type (hence the use
3238                  of that type above).  */
3239               if (No (Rbase (ur_realval)))
3240                 gnu_result
3241                   = build_binary_op (RDIV_EXPR,
3242                                      get_base_type (gnu_result_type),
3243                                      gnu_result,
3244                                      UI_To_gnu (Denominator (ur_realval),
3245                                                 gnu_result_type));
3246               else
3247                 {
3248                   REAL_VALUE_TYPE tmp;
3249
3250                   gcc_assert (Rbase (ur_realval) == 2);
3251                   real_ldexp (&tmp, &TREE_REAL_CST (gnu_result),
3252                               - UI_To_Int (Denominator (ur_realval)));
3253                   gnu_result = build_real (gnu_result_type, tmp);
3254                 }
3255             }
3256
3257           /* Now see if we need to negate the result.  Do it this way to
3258              properly handle -0.  */
3259           if (UR_Is_Negative (Realval (gnat_node)))
3260             gnu_result
3261               = build_unary_op (NEGATE_EXPR, get_base_type (gnu_result_type),
3262                                 gnu_result);
3263         }
3264
3265       break;
3266
3267     case N_String_Literal:
3268       gnu_result_type = get_unpadded_type (Etype (gnat_node));
3269       if (TYPE_PRECISION (TREE_TYPE (gnu_result_type)) == HOST_BITS_PER_CHAR)
3270         {
3271           String_Id gnat_string = Strval (gnat_node);
3272           int length = String_Length (gnat_string);
3273           int i;
3274           char *string;
3275           if (length >= ALLOCA_THRESHOLD)
3276              string = XNEWVEC (char, length + 1); /* in case of large strings */
3277           else
3278              string = (char *) alloca (length + 1);
3279
3280           /* Build the string with the characters in the literal.  Note
3281              that Ada strings are 1-origin.  */
3282           for (i = 0; i < length; i++)
3283             string[i] = Get_String_Char (gnat_string, i + 1);
3284
3285           /* Put a null at the end of the string in case it's in a context
3286              where GCC will want to treat it as a C string.  */
3287           string[i] = 0;
3288
3289           gnu_result = build_string (length, string);
3290
3291           /* Strings in GCC don't normally have types, but we want
3292              this to not be converted to the array type.  */
3293           TREE_TYPE (gnu_result) = gnu_result_type;
3294
3295           if (length >= ALLOCA_THRESHOLD) /* free if heap-allocated */
3296              free (string);
3297         }
3298       else
3299         {
3300           /* Build a list consisting of each character, then make
3301              the aggregate.  */
3302           String_Id gnat_string = Strval (gnat_node);
3303           int length = String_Length (gnat_string);
3304           int i;
3305           tree gnu_list = NULL_TREE;
3306           tree gnu_idx = TYPE_MIN_VALUE (TYPE_DOMAIN (gnu_result_type));
3307
3308           for (i = 0; i < length; i++)
3309             {
3310               gnu_list
3311                 = tree_cons (gnu_idx,
3312                              build_int_cst (TREE_TYPE (gnu_result_type),
3313                                             Get_String_Char (gnat_string,
3314                                                              i + 1)),
3315                              gnu_list);
3316
3317               gnu_idx = int_const_binop (PLUS_EXPR, gnu_idx, integer_one_node,
3318                                          0);
3319             }
3320
3321           gnu_result
3322             = gnat_build_constructor (gnu_result_type, nreverse (gnu_list));
3323         }
3324       break;
3325
3326     case N_Pragma:
3327       gnu_result = Pragma_to_gnu (gnat_node);
3328       break;
3329
3330     /**************************************/
3331     /* Chapter 3: Declarations and Types: */
3332     /**************************************/
3333
3334     case N_Subtype_Declaration:
3335     case N_Full_Type_Declaration:
3336     case N_Incomplete_Type_Declaration:
3337     case N_Private_Type_Declaration:
3338     case N_Private_Extension_Declaration:
3339     case N_Task_Type_Declaration:
3340       process_type (Defining_Entity (gnat_node));
3341       gnu_result = alloc_stmt_list ();
3342       break;
3343
3344     case N_Object_Declaration:
3345     case N_Exception_Declaration:
3346       gnat_temp = Defining_Entity (gnat_node);
3347       gnu_result = alloc_stmt_list ();
3348
3349       /* If we are just annotating types and this object has an unconstrained
3350          or task type, don't elaborate it.   */
3351       if (type_annotate_only
3352           && (((Is_Array_Type (Etype (gnat_temp))
3353                 || Is_Record_Type (Etype (gnat_temp)))
3354                && !Is_Constrained (Etype (gnat_temp)))
3355             || Is_Concurrent_Type (Etype (gnat_temp))))
3356         break;
3357
3358       if (Present (Expression (gnat_node))
3359           && !(Nkind (gnat_node) == N_Object_Declaration
3360                && No_Initialization (gnat_node))
3361           && (!type_annotate_only
3362               || Compile_Time_Known_Value (Expression (gnat_node))))
3363         {
3364           gnu_expr = gnat_to_gnu (Expression (gnat_node));
3365           if (Do_Range_Check (Expression (gnat_node)))
3366             gnu_expr = emit_range_check (gnu_expr, Etype (gnat_temp));
3367
3368           /* If this object has its elaboration delayed, we must force
3369              evaluation of GNU_EXPR right now and save it for when the object
3370              is frozen.  */
3371           if (Present (Freeze_Node (gnat_temp)))
3372             {
3373               if ((Is_Public (gnat_temp) || global_bindings_p ())
3374                   && !TREE_CONSTANT (gnu_expr))
3375                 gnu_expr
3376                   = create_var_decl (create_concat_name (gnat_temp, "init"),
3377                                      NULL_TREE, TREE_TYPE (gnu_expr),
3378                                      gnu_expr, false, Is_Public (gnat_temp),
3379                                      false, false, NULL, gnat_temp);
3380               else
3381                 gnu_expr = maybe_variable (gnu_expr);
3382
3383               save_gnu_tree (gnat_node, gnu_expr, true);
3384             }
3385         }
3386       else
3387         gnu_expr = NULL_TREE;
3388
3389       if (type_annotate_only && gnu_expr && TREE_CODE (gnu_expr) == ERROR_MARK)
3390         gnu_expr = NULL_TREE;
3391
3392       if (No (Freeze_Node (gnat_temp)))
3393         gnat_to_gnu_entity (gnat_temp, gnu_expr, 1);
3394       break;
3395
3396     case N_Object_Renaming_Declaration:
3397       gnat_temp = Defining_Entity (gnat_node);
3398
3399       /* Don't do anything if this renaming is handled by the front end or if
3400          we are just annotating types and this object has a composite or task
3401          type, don't elaborate it.  We return the result in case it has any
3402          SAVE_EXPRs in it that need to be evaluated here.  */
3403       if (!Is_Renaming_Of_Object (gnat_temp)
3404           && ! (type_annotate_only
3405                 && (Is_Array_Type (Etype (gnat_temp))
3406                     || Is_Record_Type (Etype (gnat_temp))
3407                     || Is_Concurrent_Type (Etype (gnat_temp)))))
3408         gnu_result
3409           = gnat_to_gnu_entity (gnat_temp,
3410                                 gnat_to_gnu (Renamed_Object (gnat_temp)), 1);
3411       else
3412         gnu_result = alloc_stmt_list ();
3413       break;
3414
3415     case N_Implicit_Label_Declaration:
3416       gnat_to_gnu_entity (Defining_Entity (gnat_node), NULL_TREE, 1);
3417       gnu_result = alloc_stmt_list ();
3418       break;
3419
3420     case N_Exception_Renaming_Declaration:
3421     case N_Number_Declaration:
3422     case N_Package_Renaming_Declaration:
3423     case N_Subprogram_Renaming_Declaration:
3424       /* These are fully handled in the front end.  */
3425       gnu_result = alloc_stmt_list ();
3426       break;
3427
3428     /*************************************/
3429     /* Chapter 4: Names and Expressions: */
3430     /*************************************/
3431
3432     case N_Explicit_Dereference:
3433       gnu_result = gnat_to_gnu (Prefix (gnat_node));
3434       gnu_result_type = get_unpadded_type (Etype (gnat_node));
3435       gnu_result = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_result);
3436       break;
3437
3438     case N_Indexed_Component:
3439       {
3440         tree gnu_array_object = gnat_to_gnu (Prefix (gnat_node));
3441         tree gnu_type;
3442         int ndim;
3443         int i;
3444         Node_Id *gnat_expr_array;
3445
3446         gnu_array_object = maybe_implicit_deref (gnu_array_object);
3447         gnu_array_object = maybe_unconstrained_array (gnu_array_object);
3448
3449         /* If we got a padded type, remove it too.  */
3450         if (TREE_CODE (TREE_TYPE (gnu_array_object)) == RECORD_TYPE
3451             && TYPE_IS_PADDING_P (TREE_TYPE (gnu_array_object)))
3452           gnu_array_object
3453             = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_array_object))),
3454                        gnu_array_object);
3455
3456         gnu_result = gnu_array_object;
3457
3458         /* First compute the number of dimensions of the array, then
3459            fill the expression array, the order depending on whether
3460            this is a Convention_Fortran array or not.  */
3461         for (ndim = 1, gnu_type = TREE_TYPE (gnu_array_object);
3462              TREE_CODE (TREE_TYPE (gnu_type)) == ARRAY_TYPE
3463              && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type));
3464              ndim++, gnu_type = TREE_TYPE (gnu_type))
3465           ;
3466
3467         gnat_expr_array = (Node_Id *) alloca (ndim * sizeof (Node_Id));
3468
3469         if (TYPE_CONVENTION_FORTRAN_P (TREE_TYPE (gnu_array_object)))
3470           for (i = ndim - 1, gnat_temp = First (Expressions (gnat_node));
3471                i >= 0;
3472                i--, gnat_temp = Next (gnat_temp))
3473             gnat_expr_array[i] = gnat_temp;
3474         else
3475           for (i = 0, gnat_temp = First (Expressions (gnat_node));
3476                i < ndim;
3477                i++, gnat_temp = Next (gnat_temp))
3478             gnat_expr_array[i] = gnat_temp;
3479
3480         for (i = 0, gnu_type = TREE_TYPE (gnu_array_object);
3481              i < ndim; i++, gnu_type = TREE_TYPE (gnu_type))
3482           {
3483             gcc_assert (TREE_CODE (gnu_type) == ARRAY_TYPE);
3484             gnat_temp = gnat_expr_array[i];
3485             gnu_expr = gnat_to_gnu (gnat_temp);
3486
3487             if (Do_Range_Check (gnat_temp))
3488               gnu_expr
3489                 = emit_index_check
3490                   (gnu_array_object, gnu_expr,
3491                    TYPE_MIN_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type))),
3492                    TYPE_MAX_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type))));
3493
3494             gnu_result = build_binary_op (ARRAY_REF, NULL_TREE,
3495                                           gnu_result, gnu_expr);
3496           }
3497       }
3498
3499       gnu_result_type = get_unpadded_type (Etype (gnat_node));
3500       break;
3501
3502     case N_Slice:
3503       {
3504         tree gnu_type;
3505         Node_Id gnat_range_node = Discrete_Range (gnat_node);
3506
3507         gnu_result = gnat_to_gnu (Prefix (gnat_node));
3508         gnu_result_type = get_unpadded_type (Etype (gnat_node));
3509
3510         /* Do any implicit dereferences of the prefix and do any needed
3511            range check.  */
3512         gnu_result = maybe_implicit_deref (gnu_result);
3513         gnu_result = maybe_unconstrained_array (gnu_result);
3514         gnu_type = TREE_TYPE (gnu_result);
3515         if (Do_Range_Check (gnat_range_node))
3516           {
3517             /* Get the bounds of the slice.  */
3518             tree gnu_index_type
3519               = TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_result_type));
3520             tree gnu_min_expr = TYPE_MIN_VALUE (gnu_index_type);
3521             tree gnu_max_expr = TYPE_MAX_VALUE (gnu_index_type);
3522             /* Get the permitted bounds.  */
3523             tree gnu_base_index_type
3524               = TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type));
3525             tree gnu_base_min_expr = TYPE_MIN_VALUE (gnu_base_index_type);
3526             tree gnu_base_max_expr = TYPE_MAX_VALUE (gnu_base_index_type);
3527             tree gnu_expr_l, gnu_expr_h, gnu_expr_type;
3528
3529             /* Check to see that the minimum slice value is in range.  */
3530             gnu_expr_l = emit_index_check (gnu_result,
3531                                            gnu_min_expr,
3532                                            gnu_base_min_expr,
3533                                            gnu_base_max_expr);
3534
3535             /* Check to see that the maximum slice value is in range.  */
3536             gnu_expr_h = emit_index_check (gnu_result,
3537                                            gnu_max_expr,
3538                                            gnu_base_min_expr,
3539                                            gnu_base_max_expr);
3540
3541             /* Derive a good type to convert everything to.  */
3542             gnu_expr_type = get_base_type (TREE_TYPE (gnu_expr_l));
3543
3544             /* Build a compound expression that does the range checks and
3545                returns the low bound.  */
3546             gnu_expr = build_binary_op (COMPOUND_EXPR, gnu_expr_type,
3547                                         convert (gnu_expr_type, gnu_expr_h),
3548                                         convert (gnu_expr_type, gnu_expr_l));
3549
3550            /* Build a conditional expression that does the range check and
3551               returns the low bound if the slice is not empty (max >= min),
3552               and returns the naked low bound otherwise (max < min), unless
3553               it is non-constant and the high bound is; this prevents VRP
3554               from inferring bogus ranges on the unlikely path.  */
3555             gnu_expr = fold_build3 (COND_EXPR, gnu_expr_type,
3556                                     build_binary_op (GE_EXPR, gnu_expr_type,
3557                                                      convert (gnu_expr_type,
3558                                                               gnu_max_expr),
3559                                                      convert (gnu_expr_type,
3560                                                               gnu_min_expr)),
3561                                     gnu_expr,
3562                                     TREE_CODE (gnu_min_expr) != INTEGER_CST
3563                                     && TREE_CODE (gnu_max_expr) == INTEGER_CST
3564                                     ? gnu_max_expr : gnu_min_expr);
3565           }
3566         else
3567           /* Simply return the naked low bound.  */
3568           gnu_expr = TYPE_MIN_VALUE (TYPE_DOMAIN (gnu_result_type));
3569
3570         gnu_result = build_binary_op (ARRAY_RANGE_REF, gnu_result_type,
3571                                       gnu_result, gnu_expr);
3572       }
3573       break;
3574
3575     case N_Selected_Component:
3576       {
3577         tree gnu_prefix = gnat_to_gnu (Prefix (gnat_node));
3578         Entity_Id gnat_field = Entity (Selector_Name (gnat_node));
3579         Entity_Id gnat_pref_type = Etype (Prefix (gnat_node));
3580         tree gnu_field;
3581
3582         while (IN (Ekind (gnat_pref_type), Incomplete_Or_Private_Kind)
3583                || IN (Ekind (gnat_pref_type), Access_Kind))
3584           {
3585             if (IN (Ekind (gnat_pref_type), Incomplete_Or_Private_Kind))
3586               gnat_pref_type = Underlying_Type (gnat_pref_type);
3587             else if (IN (Ekind (gnat_pref_type), Access_Kind))
3588               gnat_pref_type = Designated_Type (gnat_pref_type);
3589           }
3590
3591         gnu_prefix = maybe_implicit_deref (gnu_prefix);
3592
3593         /* For discriminant references in tagged types always substitute the
3594            corresponding discriminant as the actual selected component. */
3595
3596         if (Is_Tagged_Type (gnat_pref_type))
3597           while (Present (Corresponding_Discriminant (gnat_field)))
3598             gnat_field = Corresponding_Discriminant (gnat_field);
3599
3600         /* For discriminant references of untagged types always substitute the
3601            corresponding stored discriminant. */
3602
3603         else if (Present (Corresponding_Discriminant (gnat_field)))
3604           gnat_field = Original_Record_Component (gnat_field);
3605
3606         /* Handle extracting the real or imaginary part of a complex.
3607            The real part is the first field and the imaginary the last.  */
3608
3609         if (TREE_CODE (TREE_TYPE (gnu_prefix)) == COMPLEX_TYPE)
3610           gnu_result = build_unary_op (Present (Next_Entity (gnat_field))
3611                                        ? REALPART_EXPR : IMAGPART_EXPR,
3612                                        NULL_TREE, gnu_prefix);
3613         else
3614           {
3615             gnu_field = gnat_to_gnu_field_decl (gnat_field);
3616
3617             /* If there are discriminants, the prefix might be
3618                evaluated more than once, which is a problem if it has
3619                side-effects. */
3620             if (Has_Discriminants (Is_Access_Type (Etype (Prefix (gnat_node)))
3621                                    ? Designated_Type (Etype
3622                                                       (Prefix (gnat_node)))
3623                                    : Etype (Prefix (gnat_node))))
3624               gnu_prefix = gnat_stabilize_reference (gnu_prefix, false);
3625
3626             gnu_result
3627               = build_component_ref (gnu_prefix, NULL_TREE, gnu_field,
3628                                      (Nkind (Parent (gnat_node))
3629                                       == N_Attribute_Reference));
3630           }
3631
3632         gcc_assert (gnu_result);
3633         gnu_result_type = get_unpadded_type (Etype (gnat_node));
3634       }
3635       break;
3636
3637     case N_Attribute_Reference:
3638       {
3639         /* The attribute designator (like an enumeration value). */
3640         int attribute = Get_Attribute_Id (Attribute_Name (gnat_node));
3641
3642         /* The Elab_Spec and Elab_Body attributes are special in that
3643            Prefix is a unit, not an object with a GCC equivalent.  Similarly
3644            for Elaborated, since that variable isn't otherwise known.  */
3645         if (attribute == Attr_Elab_Body || attribute == Attr_Elab_Spec)
3646           return (create_subprog_decl
3647                   (create_concat_name (Entity (Prefix (gnat_node)),
3648                                        attribute == Attr_Elab_Body
3649                                        ? "elabb" : "elabs"),
3650                    NULL_TREE, void_ftype, NULL_TREE, false, true, true, NULL,
3651                    gnat_node));
3652
3653         gnu_result = Attribute_to_gnu (gnat_node, &gnu_result_type, attribute);
3654       }
3655       break;
3656
3657     case N_Reference:
3658       /* Like 'Access as far as we are concerned.  */
3659       gnu_result = gnat_to_gnu (Prefix (gnat_node));
3660       gnu_result = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_result);
3661       gnu_result_type = get_unpadded_type (Etype (gnat_node));
3662       break;
3663
3664     case N_Aggregate:
3665     case N_Extension_Aggregate:
3666       {
3667         tree gnu_aggr_type;
3668
3669         /* ??? It is wrong to evaluate the type now, but there doesn't
3670            seem to be any other practical way of doing it.  */
3671
3672         gcc_assert (!Expansion_Delayed (gnat_node));
3673
3674         gnu_aggr_type = gnu_result_type
3675           = get_unpadded_type (Etype (gnat_node));
3676
3677         if (TREE_CODE (gnu_result_type) == RECORD_TYPE
3678             && TYPE_CONTAINS_TEMPLATE_P (gnu_result_type))
3679           gnu_aggr_type
3680             = TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (gnu_result_type)));
3681
3682         if (Null_Record_Present (gnat_node))
3683           gnu_result = gnat_build_constructor (gnu_aggr_type, NULL_TREE);
3684
3685         else if (TREE_CODE (gnu_aggr_type) == RECORD_TYPE
3686                  || TREE_CODE (gnu_aggr_type) == UNION_TYPE)
3687           gnu_result
3688             = assoc_to_constructor (Etype (gnat_node),
3689                                     First (Component_Associations (gnat_node)),
3690                                     gnu_aggr_type);
3691         else if (TREE_CODE (gnu_aggr_type) == ARRAY_TYPE)
3692           gnu_result = pos_to_constructor (First (Expressions (gnat_node)),
3693                                            gnu_aggr_type,
3694                                            Component_Type (Etype (gnat_node)));
3695         else if (TREE_CODE (gnu_aggr_type) == COMPLEX_TYPE)
3696           gnu_result
3697             = build_binary_op
3698               (COMPLEX_EXPR, gnu_aggr_type,
3699                gnat_to_gnu (Expression (First
3700                                         (Component_Associations (gnat_node)))),
3701                gnat_to_gnu (Expression
3702                             (Next
3703                              (First (Component_Associations (gnat_node))))));
3704         else
3705           gcc_unreachable ();
3706
3707         gnu_result = convert (gnu_result_type, gnu_result);
3708       }
3709       break;
3710
3711     case N_Null:
3712       if (TARGET_VTABLE_USES_DESCRIPTORS
3713           && Ekind (Etype (gnat_node)) == E_Access_Subprogram_Type
3714           && Is_Dispatch_Table_Entity (Etype (gnat_node)))
3715         gnu_result = null_fdesc_node;
3716       else
3717         gnu_result = null_pointer_node;
3718       gnu_result_type = get_unpadded_type (Etype (gnat_node));
3719       break;
3720
3721     case N_Type_Conversion:
3722     case N_Qualified_Expression:
3723       /* Get the operand expression.  */
3724       gnu_result = gnat_to_gnu (Expression (gnat_node));
3725       gnu_result_type = get_unpadded_type (Etype (gnat_node));
3726
3727       gnu_result
3728         = convert_with_check (Etype (gnat_node), gnu_result,
3729                               Do_Overflow_Check (gnat_node),
3730                               Do_Range_Check (Expression (gnat_node)),
3731                               Nkind (gnat_node) == N_Type_Conversion
3732                               && Float_Truncate (gnat_node));
3733       break;
3734
3735     case N_Unchecked_Type_Conversion:
3736       gnu_result = gnat_to_gnu (Expression (gnat_node));
3737       gnu_result_type = get_unpadded_type (Etype (gnat_node));
3738
3739       /* If the result is a pointer type, see if we are improperly
3740          converting to a stricter alignment.  */
3741       if (STRICT_ALIGNMENT && POINTER_TYPE_P (gnu_result_type)
3742           && IN (Ekind (Etype (gnat_node)), Access_Kind))
3743         {
3744           unsigned int align = known_alignment (gnu_result);
3745           tree gnu_obj_type = TREE_TYPE (gnu_result_type);
3746           unsigned int oalign = TYPE_ALIGN (gnu_obj_type);
3747
3748           if (align != 0 && align < oalign && !TYPE_ALIGN_OK (gnu_obj_type))
3749             post_error_ne_tree_2
3750               ("?source alignment (^) '< alignment of & (^)",
3751                gnat_node, Designated_Type (Etype (gnat_node)),
3752                size_int (align / BITS_PER_UNIT), oalign / BITS_PER_UNIT);
3753         }
3754
3755       /* If we are converting a descriptor to a function pointer, first
3756          build the pointer.  */
3757       if (TARGET_VTABLE_USES_DESCRIPTORS
3758           && TREE_TYPE (gnu_result) == fdesc_type_node
3759           && POINTER_TYPE_P (gnu_result_type))
3760         gnu_result = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_result);
3761
3762       gnu_result = unchecked_convert (gnu_result_type, gnu_result,
3763                                       No_Truncation (gnat_node));
3764       break;
3765
3766     case N_In:
3767     case N_Not_In:
3768       {
3769         tree gnu_object = gnat_to_gnu (Left_Opnd (gnat_node));
3770         Node_Id gnat_range = Right_Opnd (gnat_node);
3771         tree gnu_low;
3772         tree gnu_high;
3773
3774         /* GNAT_RANGE is either an N_Range node or an identifier
3775            denoting a subtype.  */
3776         if (Nkind (gnat_range) == N_Range)
3777           {
3778             gnu_low = gnat_to_gnu (Low_Bound (gnat_range));
3779             gnu_high = gnat_to_gnu (High_Bound (gnat_range));
3780           }
3781         else if (Nkind (gnat_range) == N_Identifier
3782               || Nkind (gnat_range) == N_Expanded_Name)
3783           {
3784             tree gnu_range_type = get_unpadded_type (Entity (gnat_range));
3785
3786             gnu_low = TYPE_MIN_VALUE (gnu_range_type);
3787             gnu_high = TYPE_MAX_VALUE (gnu_range_type);
3788           }
3789         else
3790           gcc_unreachable ();
3791
3792         gnu_result_type = get_unpadded_type (Etype (gnat_node));
3793
3794         /* If LOW and HIGH are identical, perform an equality test.
3795            Otherwise, ensure that GNU_OBJECT is only evaluated once
3796            and perform a full range test.  */
3797         if (operand_equal_p (gnu_low, gnu_high, 0))
3798           gnu_result = build_binary_op (EQ_EXPR, gnu_result_type,
3799                                         gnu_object, gnu_low);
3800         else
3801           {
3802             gnu_object = protect_multiple_eval (gnu_object);
3803             gnu_result
3804               = build_binary_op (TRUTH_ANDIF_EXPR, gnu_result_type,
3805                                  build_binary_op (GE_EXPR, gnu_result_type,
3806                                                   gnu_object, gnu_low),
3807                                  build_binary_op (LE_EXPR, gnu_result_type,
3808                                                   gnu_object, gnu_high));
3809           }
3810
3811         if (Nkind (gnat_node) == N_Not_In)
3812           gnu_result = invert_truthvalue (gnu_result);
3813       }
3814       break;
3815
3816     case N_Op_Divide:
3817       gnu_lhs = gnat_to_gnu (Left_Opnd (gnat_node));
3818       gnu_rhs = gnat_to_gnu (Right_Opnd (gnat_node));
3819       gnu_result_type = get_unpadded_type (Etype (gnat_node));
3820       gnu_result = build_binary_op (FLOAT_TYPE_P (gnu_result_type)
3821                                     ? RDIV_EXPR
3822                                     : (Rounded_Result (gnat_node)
3823                                        ? ROUND_DIV_EXPR : TRUNC_DIV_EXPR),
3824                                     gnu_result_type, gnu_lhs, gnu_rhs);
3825       break;
3826
3827     case N_Op_Or:    case N_Op_And:      case N_Op_Xor:
3828       /* These can either be operations on booleans or on modular types.
3829          Fall through for boolean types since that's the way GNU_CODES is
3830          set up.  */
3831       if (IN (Ekind (Underlying_Type (Etype (gnat_node))),
3832               Modular_Integer_Kind))
3833         {
3834           enum tree_code code
3835             = (Nkind (gnat_node) == N_Op_Or ? BIT_IOR_EXPR
3836                : Nkind (gnat_node) == N_Op_And ? BIT_AND_EXPR
3837                : BIT_XOR_EXPR);
3838
3839           gnu_lhs = gnat_to_gnu (Left_Opnd (gnat_node));
3840           gnu_rhs = gnat_to_gnu (Right_Opnd (gnat_node));
3841           gnu_result_type = get_unpadded_type (Etype (gnat_node));
3842           gnu_result = build_binary_op (code, gnu_result_type,
3843                                         gnu_lhs, gnu_rhs);
3844           break;
3845         }
3846
3847       /* ... fall through ... */
3848
3849     case N_Op_Eq:    case N_Op_Ne:       case N_Op_Lt:
3850     case N_Op_Le:    case N_Op_Gt:       case N_Op_Ge:
3851     case N_Op_Add:   case N_Op_Subtract: case N_Op_Multiply:
3852     case N_Op_Mod:   case N_Op_Rem:
3853     case N_Op_Rotate_Left:
3854     case N_Op_Rotate_Right:
3855     case N_Op_Shift_Left:
3856     case N_Op_Shift_Right:
3857     case N_Op_Shift_Right_Arithmetic:
3858     case N_And_Then: case N_Or_Else:
3859       {
3860         enum tree_code code = gnu_codes[Nkind (gnat_node)];
3861         bool ignore_lhs_overflow = false;
3862         tree gnu_type;
3863
3864         gnu_lhs = gnat_to_gnu (Left_Opnd (gnat_node));
3865         gnu_rhs = gnat_to_gnu (Right_Opnd (gnat_node));
3866         gnu_type = gnu_result_type = get_unpadded_type (Etype (gnat_node));
3867
3868         /* If this is a comparison operator, convert any references to
3869            an unconstrained array value into a reference to the
3870            actual array.  */
3871         if (TREE_CODE_CLASS (code) == tcc_comparison)
3872           {
3873             gnu_lhs = maybe_unconstrained_array (gnu_lhs);
3874             gnu_rhs = maybe_unconstrained_array (gnu_rhs);
3875           }
3876
3877         /* If the result type is a private type, its full view may be a
3878            numeric subtype. The representation we need is that of its base
3879            type, given that it is the result of an arithmetic operation.  */
3880         else if (Is_Private_Type (Etype (gnat_node)))
3881           gnu_type = gnu_result_type
3882             = get_unpadded_type (Base_Type (Full_View (Etype (gnat_node))));
3883
3884         /* If this is a shift whose count is not guaranteed to be correct,
3885            we need to adjust the shift count.  */
3886         if (IN (Nkind (gnat_node), N_Op_Shift)
3887             && !Shift_Count_OK (gnat_node))
3888           {
3889             tree gnu_count_type = get_base_type (TREE_TYPE (gnu_rhs));
3890             tree gnu_max_shift
3891               = convert (gnu_count_type, TYPE_SIZE (gnu_type));
3892
3893             if (Nkind (gnat_node) == N_Op_Rotate_Left
3894                 || Nkind (gnat_node) == N_Op_Rotate_Right)
3895               gnu_rhs = build_binary_op (TRUNC_MOD_EXPR, gnu_count_type,
3896                                          gnu_rhs, gnu_max_shift);
3897             else if (Nkind (gnat_node) == N_Op_Shift_Right_Arithmetic)
3898               gnu_rhs
3899                 = build_binary_op
3900                   (MIN_EXPR, gnu_count_type,
3901                    build_binary_op (MINUS_EXPR,
3902                                     gnu_count_type,
3903                                     gnu_max_shift,
3904                                     convert (gnu_count_type,
3905                                              integer_one_node)),
3906                    gnu_rhs);
3907           }
3908
3909         /* For right shifts, the type says what kind of shift to do,
3910            so we may need to choose a different type.  In this case,
3911            we have to ignore integer overflow lest it propagates all
3912            the way down and causes a CE to be explicitly raised.  */
3913         if (Nkind (gnat_node) == N_Op_Shift_Right
3914             && !TYPE_UNSIGNED (gnu_type))
3915           {
3916             gnu_type = gnat_unsigned_type (gnu_type);
3917             ignore_lhs_overflow = true;
3918           }
3919         else if (Nkind (gnat_node) == N_Op_Shift_Right_Arithmetic
3920                  && TYPE_UNSIGNED (gnu_type))
3921           {
3922             gnu_type = gnat_signed_type (gnu_type);
3923             ignore_lhs_overflow = true;
3924           }
3925
3926         if (gnu_type != gnu_result_type)
3927           {
3928             tree gnu_old_lhs = gnu_lhs;
3929             gnu_lhs = convert (gnu_type, gnu_lhs);
3930             if (TREE_CODE (gnu_lhs) == INTEGER_CST && ignore_lhs_overflow)
3931               TREE_OVERFLOW (gnu_lhs) = TREE_OVERFLOW (gnu_old_lhs);
3932             gnu_rhs = convert (gnu_type, gnu_rhs);
3933           }
3934
3935         gnu_result = build_binary_op (code, gnu_type, gnu_lhs, gnu_rhs);
3936
3937         /* If this is a logical shift with the shift count not verified,
3938            we must return zero if it is too large.  We cannot compensate
3939            above in this case.  */
3940         if ((Nkind (gnat_node) == N_Op_Shift_Left
3941              || Nkind (gnat_node) == N_Op_Shift_Right)
3942             && !Shift_Count_OK (gnat_node))
3943           gnu_result
3944             = build_cond_expr
3945               (gnu_type,
3946                build_binary_op (GE_EXPR, integer_type_node,
3947                                 gnu_rhs,
3948                                 convert (TREE_TYPE (gnu_rhs),
3949                                          TYPE_SIZE (gnu_type))),
3950                convert (gnu_type, integer_zero_node),
3951                gnu_result);
3952       }
3953       break;
3954
3955     case N_Conditional_Expression:
3956       {
3957         tree gnu_cond = gnat_to_gnu (First (Expressions (gnat_node)));
3958         tree gnu_true = gnat_to_gnu (Next (First (Expressions (gnat_node))));
3959         tree gnu_false
3960           = gnat_to_gnu (Next (Next (First (Expressions (gnat_node)))));
3961
3962         gnu_result_type = get_unpadded_type (Etype (gnat_node));
3963         gnu_result = build_cond_expr (gnu_result_type,
3964                                       gnat_truthvalue_conversion (gnu_cond),
3965                                       gnu_true, gnu_false);
3966       }
3967       break;
3968
3969     case N_Op_Plus:
3970       gnu_result = gnat_to_gnu (Right_Opnd (gnat_node));
3971       gnu_result_type = get_unpadded_type (Etype (gnat_node));
3972       break;
3973
3974     case N_Op_Not:
3975       /* This case can apply to a boolean or a modular type.
3976          Fall through for a boolean operand since GNU_CODES is set
3977          up to handle this.  */
3978       if (Is_Modular_Integer_Type (Etype (gnat_node))
3979           || (Ekind (Etype (gnat_node)) == E_Private_Type
3980               && Is_Modular_Integer_Type (Full_View (Etype (gnat_node)))))
3981         {
3982           gnu_expr = gnat_to_gnu (Right_Opnd (gnat_node));
3983           gnu_result_type = get_unpadded_type (Etype (gnat_node));
3984           gnu_result = build_unary_op (BIT_NOT_EXPR, gnu_result_type,
3985                                        gnu_expr);
3986           break;
3987         }
3988
3989       /* ... fall through ... */
3990
3991     case N_Op_Minus:  case N_Op_Abs:
3992       gnu_expr = gnat_to_gnu (Right_Opnd (gnat_node));
3993
3994       if (Ekind (Etype (gnat_node)) != E_Private_Type)
3995          gnu_result_type = get_unpadded_type (Etype (gnat_node));
3996       else
3997          gnu_result_type = get_unpadded_type (Base_Type
3998                                               (Full_View (Etype (gnat_node))));
3999
4000       gnu_result = build_unary_op (gnu_codes[Nkind (gnat_node)],
4001                                    gnu_result_type, gnu_expr);
4002       break;
4003
4004     case N_Allocator:
4005       {
4006         tree gnu_init = 0;
4007         tree gnu_type;
4008         bool ignore_init_type = false;
4009
4010         gnat_temp = Expression (gnat_node);
4011
4012         /* The Expression operand can either be an N_Identifier or
4013            Expanded_Name, which must represent a type, or a
4014            N_Qualified_Expression, which contains both the object type and an
4015            initial value for the object.  */
4016         if (Nkind (gnat_temp) == N_Identifier
4017             || Nkind (gnat_temp) == N_Expanded_Name)
4018           gnu_type = gnat_to_gnu_type (Entity (gnat_temp));
4019         else if (Nkind (gnat_temp) == N_Qualified_Expression)
4020           {
4021             Entity_Id gnat_desig_type
4022               = Designated_Type (Underlying_Type (Etype (gnat_node)));
4023
4024             ignore_init_type = Has_Constrained_Partial_View (gnat_desig_type);
4025             gnu_init = gnat_to_gnu (Expression (gnat_temp));
4026
4027             gnu_init = maybe_unconstrained_array (gnu_init);
4028             if (Do_Range_Check (Expression (gnat_temp)))
4029               gnu_init = emit_range_check (gnu_init, gnat_desig_type);
4030
4031             if (Is_Elementary_Type (gnat_desig_type)
4032                 || Is_Constrained (gnat_desig_type))
4033               {
4034                 gnu_type = gnat_to_gnu_type (gnat_desig_type);
4035                 gnu_init = convert (gnu_type, gnu_init);
4036               }
4037             else
4038               {
4039                 gnu_type = gnat_to_gnu_type (Etype (Expression (gnat_temp)));
4040                 if (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE)
4041                   gnu_type = TREE_TYPE (gnu_init);
4042
4043                 gnu_init = convert (gnu_type, gnu_init);
4044               }
4045           }
4046         else
4047           gcc_unreachable ();
4048
4049         gnu_result_type = get_unpadded_type (Etype (gnat_node));
4050         return build_allocator (gnu_type, gnu_init, gnu_result_type,
4051                                 Procedure_To_Call (gnat_node),
4052                                 Storage_Pool (gnat_node), gnat_node,
4053                                 ignore_init_type);
4054       }
4055       break;
4056
4057     /***************************/
4058     /* Chapter 5: Statements:  */
4059     /***************************/
4060
4061     case N_Label:
4062       gnu_result = build1 (LABEL_EXPR, void_type_node,
4063                            gnat_to_gnu (Identifier (gnat_node)));
4064       break;
4065
4066     case N_Null_Statement:
4067       gnu_result = alloc_stmt_list ();
4068       break;
4069
4070     case N_Assignment_Statement:
4071       /* Get the LHS and RHS of the statement and convert any reference to an
4072          unconstrained array into a reference to the underlying array.
4073          If we are not to do range checking and the RHS is an N_Function_Call,
4074          pass the LHS to the call function.  */
4075       gnu_lhs = maybe_unconstrained_array (gnat_to_gnu (Name (gnat_node)));
4076
4077       /* If the type has a size that overflows, convert this into raise of
4078          Storage_Error: execution shouldn't have gotten here anyway.  */
4079       if (TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (gnu_lhs))) == INTEGER_CST
4080            && TREE_OVERFLOW (TYPE_SIZE_UNIT (TREE_TYPE (gnu_lhs))))
4081         gnu_result = build_call_raise (SE_Object_Too_Large, gnat_node,
4082                                        N_Raise_Storage_Error);
4083       else if (Nkind (Expression (gnat_node)) == N_Function_Call
4084                && !Do_Range_Check (Expression (gnat_node)))
4085         gnu_result = call_to_gnu (Expression (gnat_node),
4086                                   &gnu_result_type, gnu_lhs);
4087       else
4088         {
4089           gnu_rhs
4090             = maybe_unconstrained_array (gnat_to_gnu (Expression (gnat_node)));
4091
4092           /* If range check is needed, emit code to generate it */
4093           if (Do_Range_Check (Expression (gnat_node)))
4094             gnu_rhs = emit_range_check (gnu_rhs, Etype (Name (gnat_node)));
4095
4096           gnu_result
4097             = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_lhs, gnu_rhs);
4098         }
4099       break;
4100
4101     case N_If_Statement:
4102       {
4103         tree *gnu_else_ptr;     /* Point to put next "else if" or "else". */
4104
4105         /* Make the outer COND_EXPR.  Avoid non-determinism.  */
4106         gnu_result = build3 (COND_EXPR, void_type_node,
4107                              gnat_to_gnu (Condition (gnat_node)),
4108                              NULL_TREE, NULL_TREE);
4109         COND_EXPR_THEN (gnu_result)
4110           = build_stmt_group (Then_Statements (gnat_node), false);
4111         TREE_SIDE_EFFECTS (gnu_result) = 1;
4112         gnu_else_ptr = &COND_EXPR_ELSE (gnu_result);
4113
4114         /* Now make a COND_EXPR for each of the "else if" parts.  Put each
4115            into the previous "else" part and point to where to put any
4116            outer "else".  Also avoid non-determinism.  */
4117         if (Present (Elsif_Parts (gnat_node)))
4118           for (gnat_temp = First (Elsif_Parts (gnat_node));
4119                Present (gnat_temp); gnat_temp = Next (gnat_temp))
4120             {
4121               gnu_expr = build3 (COND_EXPR, void_type_node,
4122                                  gnat_to_gnu (Condition (gnat_temp)),
4123                                  NULL_TREE, NULL_TREE);
4124               COND_EXPR_THEN (gnu_expr)
4125                 = build_stmt_group (Then_Statements (gnat_temp), false);
4126               TREE_SIDE_EFFECTS (gnu_expr) = 1;
4127               set_expr_location_from_node (gnu_expr, gnat_temp);
4128               *gnu_else_ptr = gnu_expr;
4129               gnu_else_ptr = &COND_EXPR_ELSE (gnu_expr);
4130             }
4131
4132         *gnu_else_ptr = build_stmt_group (Else_Statements (gnat_node), false);
4133       }
4134       break;
4135
4136     case N_Case_Statement:
4137       gnu_result = Case_Statement_to_gnu (gnat_node);
4138       break;
4139
4140     case N_Loop_Statement:
4141       gnu_result = Loop_Statement_to_gnu (gnat_node);
4142       break;
4143
4144     case N_Block_Statement:
4145       start_stmt_group ();
4146       gnat_pushlevel ();
4147       process_decls (Declarations (gnat_node), Empty, Empty, true, true);
4148       add_stmt (gnat_to_gnu (Handled_Statement_Sequence (gnat_node)));
4149       gnat_poplevel ();
4150       gnu_result = end_stmt_group ();
4151
4152       if (Present (Identifier (gnat_node)))
4153         mark_out_of_scope (Entity (Identifier (gnat_node)));
4154       break;
4155
4156     case N_Exit_Statement:
4157       gnu_result
4158         = build2 (EXIT_STMT, void_type_node,
4159                   (Present (Condition (gnat_node))
4160                    ? gnat_to_gnu (Condition (gnat_node)) : NULL_TREE),
4161                   (Present (Name (gnat_node))
4162                    ? get_gnu_tree (Entity (Name (gnat_node)))
4163                    : TREE_VALUE (gnu_loop_label_stack)));
4164       break;
4165
4166     case N_Return_Statement:
4167       {
4168         /* The gnu function type of the subprogram currently processed.  */
4169         tree gnu_subprog_type = TREE_TYPE (current_function_decl);
4170         /* The return value from the subprogram.  */
4171         tree gnu_ret_val = NULL_TREE;
4172         /* The place to put the return value.  */
4173         tree gnu_lhs;
4174
4175         /* If we are dealing with a "return;" from an Ada procedure with
4176            parameters passed by copy in copy out, we need to return a record
4177            containing the final values of these parameters.  If the list
4178            contains only one entry, return just that entry.
4179
4180            For a full description of the copy in copy out parameter mechanism,
4181            see the part of the gnat_to_gnu_entity routine dealing with the
4182            translation of subprograms.
4183
4184            But if we have a return label defined, convert this into
4185            a branch to that label.  */
4186
4187         if (TREE_VALUE (gnu_return_label_stack))
4188           {
4189             gnu_result = build1 (GOTO_EXPR, void_type_node,
4190                                  TREE_VALUE (gnu_return_label_stack));
4191             break;
4192           }
4193
4194         else if (TYPE_CI_CO_LIST (gnu_subprog_type))
4195           {
4196             gnu_lhs = DECL_RESULT (current_function_decl);
4197             if (list_length (TYPE_CI_CO_LIST (gnu_subprog_type)) == 1)
4198               gnu_ret_val = TREE_VALUE (TYPE_CI_CO_LIST (gnu_subprog_type));
4199             else
4200               gnu_ret_val
4201                 = gnat_build_constructor (TREE_TYPE (gnu_subprog_type),
4202                                           TYPE_CI_CO_LIST (gnu_subprog_type));
4203           }
4204
4205         /* If the Ada subprogram is a function, we just need to return the
4206            expression.   If the subprogram returns an unconstrained
4207            array, we have to allocate a new version of the result and
4208            return it.  If we return by reference, return a pointer.  */
4209
4210         else if (Present (Expression (gnat_node)))
4211           {
4212             /* If the current function returns by target pointer and we
4213                are doing a call, pass that target to the call.  */
4214             if (TYPE_RETURNS_BY_TARGET_PTR_P (gnu_subprog_type)
4215                 && Nkind (Expression (gnat_node)) == N_Function_Call)
4216               {
4217                 gnu_lhs
4218                   = build_unary_op (INDIRECT_REF, NULL_TREE,
4219                                     DECL_ARGUMENTS (current_function_decl));
4220                 gnu_result = call_to_gnu (Expression (gnat_node),
4221                                           &gnu_result_type, gnu_lhs);
4222               }
4223             else
4224               {
4225                 gnu_ret_val = gnat_to_gnu (Expression (gnat_node));
4226
4227                 if (TYPE_RETURNS_BY_TARGET_PTR_P (gnu_subprog_type))
4228                   /* The original return type was unconstrained so dereference
4229                      the TARGET pointer in the actual return value's type. */
4230                   gnu_lhs
4231                     = build_unary_op (INDIRECT_REF, TREE_TYPE (gnu_ret_val),
4232                                       DECL_ARGUMENTS (current_function_decl));
4233                 else
4234                   gnu_lhs = DECL_RESULT (current_function_decl);
4235
4236                 /* Do not remove the padding from GNU_RET_VAL if the inner
4237                    type is self-referential since we want to allocate the fixed
4238                    size in that case.  */
4239                 if (TREE_CODE (gnu_ret_val) == COMPONENT_REF
4240                     && (TREE_CODE (TREE_TYPE (TREE_OPERAND (gnu_ret_val, 0)))
4241                         == RECORD_TYPE)
4242                     && (TYPE_IS_PADDING_P
4243                         (TREE_TYPE (TREE_OPERAND (gnu_ret_val, 0))))
4244                     && (CONTAINS_PLACEHOLDER_P
4245                         (TYPE_SIZE (TREE_TYPE (gnu_ret_val)))))
4246                   gnu_ret_val = TREE_OPERAND (gnu_ret_val, 0);
4247
4248                 if (TYPE_RETURNS_BY_REF_P (gnu_subprog_type)
4249                     || By_Ref (gnat_node))
4250                   gnu_ret_val
4251                     = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_ret_val);
4252
4253                 else if (TYPE_RETURNS_UNCONSTRAINED_P (gnu_subprog_type))
4254                   {
4255                     gnu_ret_val = maybe_unconstrained_array (gnu_ret_val);
4256                     gnu_ret_val
4257                       = build_allocator (TREE_TYPE (gnu_ret_val),
4258                                          gnu_ret_val,
4259                                          TREE_TYPE (gnu_subprog_type),
4260                                          Procedure_To_Call (gnat_node),
4261                                          Storage_Pool (gnat_node),
4262                                          gnat_node, false);
4263                   }
4264               }
4265           }
4266         else
4267           /* If the Ada subprogram is a regular procedure, just return.  */
4268           gnu_lhs = NULL_TREE;
4269
4270         if (TYPE_RETURNS_BY_TARGET_PTR_P (gnu_subprog_type))
4271           {
4272             if (gnu_ret_val)
4273               gnu_result = build_binary_op (MODIFY_EXPR, NULL_TREE,
4274                                             gnu_lhs, gnu_ret_val);
4275             add_stmt_with_node (gnu_result, gnat_node);
4276             gnu_lhs = NULL_TREE;
4277           }
4278
4279         gnu_result = build_return_expr (gnu_lhs, gnu_ret_val);
4280       }
4281       break;
4282
4283     case N_Goto_Statement:
4284       gnu_result = build1 (GOTO_EXPR, void_type_node,
4285                            gnat_to_gnu (Name (gnat_node)));
4286       break;
4287
4288     /****************************/
4289     /* Chapter 6: Subprograms:  */
4290     /****************************/
4291
4292     case N_Subprogram_Declaration:
4293       /* Unless there is a freeze node, declare the subprogram.  We consider
4294          this a "definition" even though we're not generating code for
4295          the subprogram because we will be making the corresponding GCC
4296          node here. */
4297
4298       if (No (Freeze_Node (Defining_Entity (Specification (gnat_node)))))
4299         gnat_to_gnu_entity (Defining_Entity (Specification (gnat_node)),
4300                             NULL_TREE, 1);
4301       gnu_result = alloc_stmt_list ();
4302       break;
4303
4304     case N_Abstract_Subprogram_Declaration:
4305       /* This subprogram doesn't exist for code generation purposes, but we
4306          have to elaborate the types of any parameters and result, unless
4307          they are imported types (nothing to generate in this case).  */
4308
4309       /* Process the parameter types first.  */
4310
4311       for (gnat_temp
4312            = First_Formal_With_Extras
4313               (Defining_Entity (Specification (gnat_node)));
4314            Present (gnat_temp);
4315            gnat_temp = Next_Formal_With_Extras (gnat_temp))
4316         if (Is_Itype (Etype (gnat_temp))
4317             && !From_With_Type (Etype (gnat_temp)))
4318           gnat_to_gnu_entity (Etype (gnat_temp), NULL_TREE, 0);
4319
4320
4321       /* Then the result type, set to Standard_Void_Type for procedures.  */
4322
4323       {
4324         Entity_Id gnat_temp_type
4325           = Etype (Defining_Entity (Specification (gnat_node)));
4326
4327         if (Is_Itype (gnat_temp_type) && !From_With_Type (gnat_temp_type))
4328           gnat_to_gnu_entity (Etype (gnat_temp_type), NULL_TREE, 0);
4329       }
4330
4331       gnu_result = alloc_stmt_list ();
4332       break;
4333
4334     case N_Defining_Program_Unit_Name:
4335       /* For a child unit identifier go up a level to get the
4336          specification.  We get this when we try to find the spec of
4337          a child unit package that is the compilation unit being compiled. */
4338       gnu_result = gnat_to_gnu (Parent (gnat_node));
4339       break;
4340
4341     case N_Subprogram_Body:
4342       Subprogram_Body_to_gnu (gnat_node);
4343       gnu_result = alloc_stmt_list ();
4344       break;
4345
4346     case N_Function_Call:
4347     case N_Procedure_Call_Statement:
4348       gnu_result = call_to_gnu (gnat_node, &gnu_result_type, NULL_TREE);
4349       break;
4350
4351     /*************************/
4352     /* Chapter 7: Packages:  */
4353     /*************************/
4354
4355     case N_Package_Declaration:
4356       gnu_result = gnat_to_gnu (Specification (gnat_node));
4357       break;
4358
4359     case N_Package_Specification:
4360
4361       start_stmt_group ();
4362       process_decls (Visible_Declarations (gnat_node),
4363                      Private_Declarations (gnat_node), Empty, true, true);
4364       gnu_result = end_stmt_group ();
4365       break;
4366
4367     case N_Package_Body:
4368
4369       /* If this is the body of a generic package - do nothing */
4370       if (Ekind (Corresponding_Spec (gnat_node)) == E_Generic_Package)
4371         {
4372           gnu_result = alloc_stmt_list ();
4373           break;
4374         }
4375
4376       start_stmt_group ();
4377       process_decls (Declarations (gnat_node), Empty, Empty, true, true);
4378
4379       if (Present (Handled_Statement_Sequence (gnat_node)))
4380         add_stmt (gnat_to_gnu (Handled_Statement_Sequence (gnat_node)));
4381
4382       gnu_result = end_stmt_group ();
4383       break;
4384
4385     /*********************************/
4386     /* Chapter 8: Visibility Rules:  */
4387     /*********************************/
4388
4389     case N_Use_Package_Clause:
4390     case N_Use_Type_Clause:
4391       /* Nothing to do here - but these may appear in list of declarations */
4392       gnu_result = alloc_stmt_list ();
4393       break;
4394
4395     /***********************/
4396     /* Chapter 9: Tasks:   */
4397     /***********************/
4398
4399     case N_Protected_Type_Declaration:
4400       gnu_result = alloc_stmt_list ();
4401       break;
4402
4403     case N_Single_Task_Declaration:
4404       gnat_to_gnu_entity (Defining_Entity (gnat_node), NULL_TREE, 1);
4405       gnu_result = alloc_stmt_list ();
4406       break;
4407
4408     /***********************************************************/
4409     /* Chapter 10: Program Structure and Compilation Issues:   */
4410     /***********************************************************/
4411
4412     case N_Compilation_Unit:
4413
4414       /* This is not called for the main unit, which is handled in function
4415          gigi above.  */
4416       start_stmt_group ();
4417       gnat_pushlevel ();
4418
4419       Compilation_Unit_to_gnu (gnat_node);
4420       gnu_result = alloc_stmt_list ();
4421       break;
4422
4423     case N_Subprogram_Body_Stub:
4424     case N_Package_Body_Stub:
4425     case N_Protected_Body_Stub:
4426     case N_Task_Body_Stub:
4427       /* Simply process whatever unit is being inserted.  */
4428       gnu_result = gnat_to_gnu (Unit (Library_Unit (gnat_node)));
4429       break;
4430
4431     case N_Subunit:
4432       gnu_result = gnat_to_gnu (Proper_Body (gnat_node));
4433       break;
4434
4435     /***************************/
4436     /* Chapter 11: Exceptions: */
4437     /***************************/
4438
4439     case N_Handled_Sequence_Of_Statements:
4440       /* If there is an At_End procedure attached to this node, and the EH
4441          mechanism is SJLJ, we must have at least a corresponding At_End
4442          handler, unless the No_Exception_Handlers restriction is set.  */
4443       gcc_assert (type_annotate_only
4444                   || Exception_Mechanism != Setjmp_Longjmp
4445                   || No (At_End_Proc (gnat_node))
4446                   || Present (Exception_Handlers (gnat_node))
4447                   || No_Exception_Handlers_Set ());
4448
4449       gnu_result = Handled_Sequence_Of_Statements_to_gnu (gnat_node);
4450       break;
4451
4452     case N_Exception_Handler:
4453       if (Exception_Mechanism == Setjmp_Longjmp)
4454         gnu_result = Exception_Handler_to_gnu_sjlj (gnat_node);
4455       else if (Exception_Mechanism == Back_End_Exceptions)
4456         gnu_result = Exception_Handler_to_gnu_zcx (gnat_node);
4457       else
4458         gcc_unreachable ();
4459
4460       break;
4461
4462     case N_Push_Constraint_Error_Label:
4463       push_exception_label_stack (&gnu_constraint_error_label_stack,
4464                                   Exception_Label (gnat_node));
4465       break;
4466
4467     case N_Push_Storage_Error_Label:
4468       push_exception_label_stack (&gnu_storage_error_label_stack,
4469                                   Exception_Label (gnat_node));
4470       break;
4471
4472     case N_Push_Program_Error_Label:
4473       push_exception_label_stack (&gnu_program_error_label_stack,
4474                                   Exception_Label (gnat_node));
4475       break;
4476
4477     case N_Pop_Constraint_Error_Label:
4478       gnu_constraint_error_label_stack
4479         = TREE_CHAIN (gnu_constraint_error_label_stack);
4480       break;
4481
4482     case N_Pop_Storage_Error_Label:
4483       gnu_storage_error_label_stack
4484         = TREE_CHAIN (gnu_storage_error_label_stack);
4485       break;
4486
4487     case N_Pop_Program_Error_Label:
4488       gnu_program_error_label_stack
4489         = TREE_CHAIN (gnu_program_error_label_stack);
4490       break;
4491
4492     /*******************************/
4493     /* Chapter 12: Generic Units:  */
4494     /*******************************/
4495
4496     case N_Generic_Function_Renaming_Declaration:
4497     case N_Generic_Package_Renaming_Declaration:
4498     case N_Generic_Procedure_Renaming_Declaration:
4499     case N_Generic_Package_Declaration:
4500     case N_Generic_Subprogram_Declaration:
4501     case N_Package_Instantiation:
4502     case N_Procedure_Instantiation:
4503     case N_Function_Instantiation:
4504       /* These nodes can appear on a declaration list but there is nothing to
4505          to be done with them.  */
4506       gnu_result = alloc_stmt_list ();
4507       break;
4508
4509     /***************************************************/
4510     /* Chapter 13: Representation Clauses and          */
4511     /*             Implementation-Dependent Features:  */
4512     /***************************************************/
4513
4514     case N_Attribute_Definition_Clause:
4515
4516       gnu_result = alloc_stmt_list ();
4517
4518       /* The only one we need deal with is for 'Address.  For the others, SEM
4519          puts the information elsewhere.  We need only deal with 'Address
4520          if the object has a Freeze_Node (which it never will currently).  */
4521       if (Get_Attribute_Id (Chars (gnat_node)) != Attr_Address
4522           || No (Freeze_Node (Entity (Name (gnat_node)))))
4523         break;
4524
4525       /* Get the value to use as the address and save it as the
4526          equivalent for GNAT_TEMP.  When the object is frozen,
4527          gnat_to_gnu_entity will do the right thing. */
4528       save_gnu_tree (Entity (Name (gnat_node)),
4529                      gnat_to_gnu (Expression (gnat_node)), true);
4530       break;
4531
4532     case N_Enumeration_Representation_Clause:
4533     case N_Record_Representation_Clause:
4534     case N_At_Clause:
4535       /* We do nothing with these.  SEM puts the information elsewhere.  */
4536       gnu_result = alloc_stmt_list ();
4537       break;
4538
4539     case N_Code_Statement:
4540       if (!type_annotate_only)
4541         {
4542           tree gnu_template = gnat_to_gnu (Asm_Template (gnat_node));
4543           tree gnu_inputs = NULL_TREE, gnu_outputs = NULL_TREE;
4544           tree gnu_clobbers = NULL_TREE, tail;
4545           bool allows_mem, allows_reg, fake;
4546           int ninputs, noutputs, i;
4547           const char **oconstraints;
4548           const char *constraint;
4549           char *clobber;
4550
4551           /* First retrieve the 3 operand lists built by the front-end.  */
4552           Setup_Asm_Outputs (gnat_node);
4553           while (Present (gnat_temp = Asm_Output_Variable ()))
4554             {
4555               tree gnu_value = gnat_to_gnu (gnat_temp);
4556               tree gnu_constr = build_tree_list (NULL_TREE, gnat_to_gnu
4557                                                  (Asm_Output_Constraint ()));
4558
4559               gnu_outputs = tree_cons (gnu_constr, gnu_value, gnu_outputs);
4560               Next_Asm_Output ();
4561             }
4562
4563           Setup_Asm_Inputs (gnat_node);
4564           while (Present (gnat_temp = Asm_Input_Value ()))
4565             {
4566               tree gnu_value = gnat_to_gnu (gnat_temp);
4567               tree gnu_constr = build_tree_list (NULL_TREE, gnat_to_gnu
4568                                                  (Asm_Input_Constraint ()));
4569
4570               gnu_inputs = tree_cons (gnu_constr, gnu_value, gnu_inputs);
4571               Next_Asm_Input ();
4572             }
4573
4574           Clobber_Setup (gnat_node);
4575           while ((clobber = Clobber_Get_Next ()))
4576             gnu_clobbers
4577               = tree_cons (NULL_TREE,
4578                            build_string (strlen (clobber) + 1, clobber),
4579                            gnu_clobbers);
4580
4581           /* Then perform some standard checking and processing on the
4582              operands.  In particular, mark them addressable if needed.  */
4583           gnu_outputs = nreverse (gnu_outputs);
4584           noutputs = list_length (gnu_outputs);
4585           gnu_inputs = nreverse (gnu_inputs);
4586           ninputs = list_length (gnu_inputs);
4587           oconstraints
4588             = (const char **) alloca (noutputs * sizeof (const char *));
4589
4590           for (i = 0, tail = gnu_outputs; tail; ++i, tail = TREE_CHAIN (tail))
4591             {
4592               tree output = TREE_VALUE (tail);
4593               constraint
4594                 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (tail)));
4595               oconstraints[i] = constraint;
4596
4597               if (parse_output_constraint (&constraint, i, ninputs, noutputs,
4598                                            &allows_mem, &allows_reg, &fake))
4599                 {
4600                   /* If the operand is going to end up in memory,
4601                      mark it addressable.  Note that we don't test
4602                      allows_mem like in the input case below; this
4603                      is modelled on the C front-end.  */
4604                   if (!allows_reg
4605                       && !gnat_mark_addressable (output))
4606                     output = error_mark_node;
4607                 }
4608               else
4609                 output = error_mark_node;
4610
4611               TREE_VALUE (tail) = output;
4612             }
4613
4614           for (i = 0, tail = gnu_inputs; tail; ++i, tail = TREE_CHAIN (tail))
4615             {
4616               tree input = TREE_VALUE (tail);
4617               constraint
4618                 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (tail)));
4619
4620               if (parse_input_constraint (&constraint, i, ninputs, noutputs,
4621                                           0, oconstraints,
4622                                           &allows_mem, &allows_reg))
4623                 {
4624                   /* If the operand is going to end up in memory,
4625                      mark it addressable.  */
4626                   if (!allows_reg && allows_mem
4627                       && !gnat_mark_addressable (input))
4628                     input = error_mark_node;
4629                 }
4630               else
4631                 input = error_mark_node;
4632
4633               TREE_VALUE (tail) = input;
4634             }
4635
4636           gnu_result = build4 (ASM_EXPR,  void_type_node,
4637                                gnu_template, gnu_outputs,
4638                                gnu_inputs, gnu_clobbers);
4639           ASM_VOLATILE_P (gnu_result) = Is_Asm_Volatile (gnat_node);
4640         }
4641       else
4642         gnu_result = alloc_stmt_list ();
4643
4644       break;
4645
4646     /***************************************************/
4647     /* Added Nodes                                     */
4648     /***************************************************/
4649
4650     case N_Freeze_Entity:
4651       start_stmt_group ();
4652       process_freeze_entity (gnat_node);
4653       process_decls (Actions (gnat_node), Empty, Empty, true, true);
4654       gnu_result = end_stmt_group ();
4655       break;
4656
4657     case N_Itype_Reference:
4658       if (!present_gnu_tree (Itype (gnat_node)))
4659         process_type (Itype (gnat_node));
4660
4661       gnu_result = alloc_stmt_list ();
4662       break;
4663
4664     case N_Free_Statement:
4665       if (!type_annotate_only)
4666         {
4667           tree gnu_ptr = gnat_to_gnu (Expression (gnat_node));
4668           tree gnu_ptr_type = TREE_TYPE (gnu_ptr);
4669           tree gnu_obj_type;
4670           tree gnu_actual_obj_type = 0;
4671           tree gnu_obj_size;
4672           unsigned int align;
4673           unsigned int default_allocator_alignment
4674             = get_target_default_allocator_alignment () * BITS_PER_UNIT;
4675
4676           /* If this is a thin pointer, we must dereference it to create
4677              a fat pointer, then go back below to a thin pointer.  The
4678              reason for this is that we need a fat pointer someplace in
4679              order to properly compute the size.  */
4680           if (TYPE_THIN_POINTER_P (TREE_TYPE (gnu_ptr)))
4681             gnu_ptr = build_unary_op (ADDR_EXPR, NULL_TREE,
4682                                       build_unary_op (INDIRECT_REF, NULL_TREE,
4683                                                       gnu_ptr));
4684
4685           /* If this is an unconstrained array, we know the object must
4686              have been allocated with the template in front of the object.
4687              So pass the template address, but get the total size.  Do this
4688              by converting to a thin pointer.  */
4689           if (TYPE_FAT_POINTER_P (TREE_TYPE (gnu_ptr)))
4690             gnu_ptr
4691               = convert (build_pointer_type
4692                          (TYPE_OBJECT_RECORD_TYPE
4693                           (TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (gnu_ptr)))),
4694                          gnu_ptr);
4695
4696           gnu_obj_type = TREE_TYPE (TREE_TYPE (gnu_ptr));
4697
4698           if (Present (Actual_Designated_Subtype (gnat_node)))
4699             {
4700               gnu_actual_obj_type
4701                 = gnat_to_gnu_type (Actual_Designated_Subtype (gnat_node));
4702
4703               if (TYPE_FAT_OR_THIN_POINTER_P (gnu_ptr_type))
4704                 gnu_actual_obj_type
4705                   = build_unc_object_type_from_ptr (gnu_ptr_type,
4706                       gnu_actual_obj_type,
4707                       get_identifier ("DEALLOC"));
4708             }
4709           else
4710             gnu_actual_obj_type = gnu_obj_type;
4711
4712           gnu_obj_size = TYPE_SIZE_UNIT (gnu_actual_obj_type);
4713           align = TYPE_ALIGN (gnu_obj_type);
4714
4715           if (TREE_CODE (gnu_obj_type) == RECORD_TYPE
4716               && TYPE_CONTAINS_TEMPLATE_P (gnu_obj_type))
4717             {
4718               tree gnu_char_ptr_type = build_pointer_type (char_type_node);
4719               tree gnu_pos = byte_position (TYPE_FIELDS (gnu_obj_type));
4720               tree gnu_byte_offset
4721                 = convert (sizetype,
4722                            size_diffop (size_zero_node, gnu_pos));
4723               gnu_byte_offset = fold_build1 (NEGATE_EXPR, sizetype, gnu_byte_offset);
4724
4725               gnu_ptr = convert (gnu_char_ptr_type, gnu_ptr);
4726               gnu_ptr = build_binary_op (POINTER_PLUS_EXPR, gnu_char_ptr_type,
4727                                          gnu_ptr, gnu_byte_offset);
4728             }
4729
4730           /* If the object was allocated from the default storage pool, the
4731              alignment was greater than what the allocator provides, and this
4732              is not a fat or thin pointer, what we have in gnu_ptr here is an
4733              address dynamically adjusted to match the alignment requirement
4734              (see build_allocator).  What we need to pass to free is the
4735              initial allocator's return value, which has been stored just in
4736              front of the block we have.  */
4737
4738           if (No (Procedure_To_Call (gnat_node))
4739               && align > default_allocator_alignment
4740               && ! TYPE_FAT_OR_THIN_POINTER_P (gnu_ptr_type))
4741             {
4742               /* We set GNU_PTR
4743                  as * (void **)((void *)GNU_PTR - (void *)sizeof(void *))
4744                  in two steps:  */
4745
4746               /* GNU_PTR (void *)
4747                  = (void *)GNU_PTR - (void *)sizeof (void *))  */
4748               gnu_ptr
4749                 = build_binary_op
4750                     (POINTER_PLUS_EXPR, ptr_void_type_node,
4751                      convert (ptr_void_type_node, gnu_ptr),
4752                      size_int (-POINTER_SIZE/BITS_PER_UNIT));
4753
4754               /* GNU_PTR (void *) = *(void **)GNU_PTR  */
4755               gnu_ptr
4756                 = build_unary_op
4757                     (INDIRECT_REF, NULL_TREE,
4758                      convert (build_pointer_type (ptr_void_type_node),
4759                               gnu_ptr));
4760             }
4761
4762           gnu_result = build_call_alloc_dealloc (gnu_ptr, gnu_obj_size, align,
4763                                                  Procedure_To_Call (gnat_node),
4764                                                  Storage_Pool (gnat_node),
4765                                                  gnat_node);
4766         }
4767       break;
4768
4769     case N_Raise_Constraint_Error:
4770     case N_Raise_Program_Error:
4771     case N_Raise_Storage_Error:
4772       if (type_annotate_only)
4773         {
4774           gnu_result = alloc_stmt_list ();
4775           break;
4776         }
4777
4778       gnu_result_type = get_unpadded_type (Etype (gnat_node));
4779       gnu_result
4780         = build_call_raise (UI_To_Int (Reason (gnat_node)), gnat_node,
4781                             Nkind (gnat_node));
4782
4783       /* If the type is VOID, this is a statement, so we need to
4784          generate the code for the call.  Handle a Condition, if there
4785          is one.  */
4786       if (TREE_CODE (gnu_result_type) == VOID_TYPE)
4787         {
4788           set_expr_location_from_node (gnu_result, gnat_node);
4789
4790           if (Present (Condition (gnat_node)))
4791             gnu_result = build3 (COND_EXPR, void_type_node,
4792                                  gnat_to_gnu (Condition (gnat_node)),
4793                                  gnu_result, alloc_stmt_list ());
4794         }
4795       else
4796         gnu_result = build1 (NULL_EXPR, gnu_result_type, gnu_result);
4797       break;
4798
4799     case N_Validate_Unchecked_Conversion:
4800       {
4801         Entity_Id gnat_target_type = Target_Type (gnat_node);
4802         tree gnu_source_type = gnat_to_gnu_type (Source_Type (gnat_node));
4803         tree gnu_target_type = gnat_to_gnu_type (gnat_target_type);
4804
4805         /* No need for any warning in this case.  */
4806         if (!flag_strict_aliasing)
4807           ;
4808
4809         /* If the result is a pointer type, see if we are either converting
4810            from a non-pointer or from a pointer to a type with a different
4811            alias set and warn if so.  If the result is defined in the same
4812            unit as this unchecked conversion, we can allow this because we
4813            can know to make the pointer type behave properly.  */
4814         else if (POINTER_TYPE_P (gnu_target_type)
4815                  && !In_Same_Source_Unit (gnat_target_type, gnat_node)
4816                  && !No_Strict_Aliasing (Underlying_Type (gnat_target_type)))
4817           {
4818             tree gnu_source_desig_type = POINTER_TYPE_P (gnu_source_type)
4819                                          ? TREE_TYPE (gnu_source_type)
4820                                          : NULL_TREE;
4821             tree gnu_target_desig_type = TREE_TYPE (gnu_target_type);
4822
4823             if ((TYPE_DUMMY_P (gnu_target_desig_type)
4824                  || get_alias_set (gnu_target_desig_type) != 0)
4825                 && (!POINTER_TYPE_P (gnu_source_type)
4826                     || (TYPE_DUMMY_P (gnu_source_desig_type)
4827                         != TYPE_DUMMY_P (gnu_target_desig_type))
4828                     || (TYPE_DUMMY_P (gnu_source_desig_type)
4829                         && gnu_source_desig_type != gnu_target_desig_type)
4830                     || (get_alias_set (gnu_source_desig_type)
4831                         != get_alias_set (gnu_target_desig_type))))
4832               {
4833                 post_error_ne
4834                   ("?possible aliasing problem for type&",
4835                    gnat_node, Target_Type (gnat_node));
4836                 post_error
4837                   ("\\?use -fno-strict-aliasing switch for references",
4838                    gnat_node);
4839                 post_error_ne
4840                   ("\\?or use `pragma No_Strict_Aliasing (&);`",
4841                    gnat_node, Target_Type (gnat_node));
4842               }
4843           }
4844
4845         /* But if the result is a fat pointer type, we have no mechanism to
4846            do that, so we unconditionally warn in problematic cases.  */
4847         else if (TYPE_FAT_POINTER_P (gnu_target_type))
4848           {
4849             tree gnu_source_array_type
4850               = TYPE_FAT_POINTER_P (gnu_source_type)
4851                 ? TREE_TYPE (TREE_TYPE (TYPE_FIELDS (gnu_source_type)))
4852                 : NULL_TREE;
4853             tree gnu_target_array_type
4854               = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (gnu_target_type)));
4855
4856             if ((TYPE_DUMMY_P (gnu_target_array_type)
4857                  || get_alias_set (gnu_target_array_type) != 0)
4858                 && (!TYPE_FAT_POINTER_P (gnu_source_type)
4859                     || (TYPE_DUMMY_P (gnu_source_array_type)
4860                         != TYPE_DUMMY_P (gnu_target_array_type))
4861                     || (TYPE_DUMMY_P (gnu_source_array_type)
4862                         && gnu_source_array_type != gnu_target_array_type)
4863                     || (get_alias_set (gnu_source_array_type)
4864                         != get_alias_set (gnu_target_array_type))))
4865               {
4866                 post_error_ne
4867                   ("?possible aliasing problem for type&",
4868                    gnat_node, Target_Type (gnat_node));
4869                 post_error
4870                   ("\\?use -fno-strict-aliasing switch for references",
4871                    gnat_node);
4872               }
4873           }
4874       }
4875       gnu_result = alloc_stmt_list ();
4876       break;
4877
4878     case N_Raise_Statement:
4879     case N_Function_Specification:
4880     case N_Procedure_Specification:
4881     case N_Op_Concat:
4882     case N_Component_Association:
4883     case N_Task_Body:
4884     default:
4885       gcc_assert (type_annotate_only);
4886       gnu_result = alloc_stmt_list ();
4887     }
4888
4889   /* If we pushed our level as part of processing the elaboration routine,
4890      pop it back now.  */
4891   if (went_into_elab_proc)
4892     {
4893       add_stmt (gnu_result);
4894       gnat_poplevel ();
4895       gnu_result = end_stmt_group ();
4896       current_function_decl = NULL_TREE;
4897     }
4898
4899   /* Set the location information on the result if it is a real expression.
4900      References can be reused for multiple GNAT nodes and they would get
4901      the location information of their last use.  Note that we may have
4902      no result if we tried to build a CALL_EXPR node to a procedure with
4903      no side-effects and optimization is enabled.  */
4904   if (gnu_result
4905       && EXPR_P (gnu_result)
4906       && TREE_CODE (gnu_result) != NOP_EXPR
4907       && !REFERENCE_CLASS_P (gnu_result))
4908     set_expr_location_from_node (gnu_result, gnat_node);
4909
4910   /* If we're supposed to return something of void_type, it means we have
4911      something we're elaborating for effect, so just return.  */
4912   if (TREE_CODE (gnu_result_type) == VOID_TYPE)
4913     return gnu_result;
4914
4915   /* If the result is a constant that overflows, raise constraint error.  */
4916   else if (TREE_CODE (gnu_result) == INTEGER_CST
4917       && TREE_OVERFLOW (gnu_result))
4918     {
4919       post_error ("Constraint_Error will be raised at run-time?", gnat_node);
4920
4921       gnu_result
4922         = build1 (NULL_EXPR, gnu_result_type,
4923                   build_call_raise (CE_Overflow_Check_Failed, gnat_node,
4924                                     N_Raise_Constraint_Error));
4925     }
4926
4927   /* If our result has side-effects and is of an unconstrained type,
4928      make a SAVE_EXPR so that we can be sure it will only be referenced
4929      once.  Note we must do this before any conversions.  */
4930   if (TREE_SIDE_EFFECTS (gnu_result)
4931       && (TREE_CODE (gnu_result_type) == UNCONSTRAINED_ARRAY_TYPE
4932           || CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_result_type))))
4933     gnu_result = gnat_stabilize_reference (gnu_result, false);
4934
4935   /* Now convert the result to the result type, unless we are in one of the
4936      following cases:
4937
4938        1. If this is the Name of an assignment statement or a parameter of
4939           a procedure call, return the result almost unmodified since the
4940           RHS will have to be converted to our type in that case, unless
4941           the result type has a simpler size.   Similarly, don't convert
4942           integral types that are the operands of an unchecked conversion
4943           since we need to ignore those conversions (for 'Valid).
4944
4945        2. If we have a label (which doesn't have any well-defined type), a
4946           field or an error, return the result almost unmodified.  Also don't
4947           do the conversion if the result type involves a PLACEHOLDER_EXPR in
4948           its size since those are the cases where the front end may have the
4949           type wrong due to "instantiating" the unconstrained record with
4950           discriminant values.  Similarly, if the two types are record types
4951           with the same name don't convert.  This will be the case when we are
4952           converting from a packable version of a type to its original type and
4953           we need those conversions to be NOPs in order for assignments into
4954           these types to work properly.
4955
4956        3. If the type is void or if we have no result, return error_mark_node
4957           to show we have no result.
4958
4959        4. Finally, if the type of the result is already correct.  */
4960
4961   if (Present (Parent (gnat_node))
4962       && ((Nkind (Parent (gnat_node)) == N_Assignment_Statement
4963            && Name (Parent (gnat_node)) == gnat_node)
4964           || (Nkind (Parent (gnat_node)) == N_Procedure_Call_Statement
4965               && Name (Parent (gnat_node)) != gnat_node)
4966           || Nkind (Parent (gnat_node)) == N_Parameter_Association
4967           || (Nkind (Parent (gnat_node)) == N_Unchecked_Type_Conversion
4968               && !AGGREGATE_TYPE_P (gnu_result_type)
4969               && !AGGREGATE_TYPE_P (TREE_TYPE (gnu_result))))
4970       && !(TYPE_SIZE (gnu_result_type)
4971            && TYPE_SIZE (TREE_TYPE (gnu_result))
4972            && (AGGREGATE_TYPE_P (gnu_result_type)
4973                == AGGREGATE_TYPE_P (TREE_TYPE (gnu_result)))
4974            && ((TREE_CODE (TYPE_SIZE (gnu_result_type)) == INTEGER_CST
4975                 && (TREE_CODE (TYPE_SIZE (TREE_TYPE (gnu_result)))
4976                     != INTEGER_CST))
4977                || (TREE_CODE (TYPE_SIZE (gnu_result_type)) != INTEGER_CST
4978                    && !CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_result_type))
4979                    && (CONTAINS_PLACEHOLDER_P
4980                        (TYPE_SIZE (TREE_TYPE (gnu_result))))))
4981            && !(TREE_CODE (gnu_result_type) == RECORD_TYPE
4982                 && TYPE_JUSTIFIED_MODULAR_P (gnu_result_type))))
4983     {
4984       /* Remove padding only if the inner object is of self-referential
4985          size: in that case it must be an object of unconstrained type
4986          with a default discriminant and we want to avoid copying too
4987          much data.  */
4988       if (TREE_CODE (TREE_TYPE (gnu_result)) == RECORD_TYPE
4989           && TYPE_IS_PADDING_P (TREE_TYPE (gnu_result))
4990           && CONTAINS_PLACEHOLDER_P (TYPE_SIZE (TREE_TYPE (TYPE_FIELDS
4991                                      (TREE_TYPE (gnu_result))))))
4992         gnu_result = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_result))),
4993                               gnu_result);
4994     }
4995
4996   else if (TREE_CODE (gnu_result) == LABEL_DECL
4997            || TREE_CODE (gnu_result) == FIELD_DECL
4998            || TREE_CODE (gnu_result) == ERROR_MARK
4999            || (TYPE_SIZE (gnu_result_type)
5000                && TREE_CODE (TYPE_SIZE (gnu_result_type)) != INTEGER_CST
5001                && TREE_CODE (gnu_result) != INDIRECT_REF
5002                && CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_result_type)))
5003            || ((TYPE_NAME (gnu_result_type)
5004                 == TYPE_NAME (TREE_TYPE (gnu_result)))
5005                && TREE_CODE (gnu_result_type) == RECORD_TYPE
5006                && TREE_CODE (TREE_TYPE (gnu_result)) == RECORD_TYPE))
5007     {
5008       /* Remove any padding.  */
5009       if (TREE_CODE (TREE_TYPE (gnu_result)) == RECORD_TYPE
5010           && TYPE_IS_PADDING_P (TREE_TYPE (gnu_result)))
5011         gnu_result = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_result))),
5012                               gnu_result);
5013     }
5014
5015   else if (gnu_result == error_mark_node || gnu_result_type == void_type_node)
5016     gnu_result = error_mark_node;
5017
5018   else if (gnu_result_type != TREE_TYPE (gnu_result))
5019     gnu_result = convert (gnu_result_type, gnu_result);
5020
5021   /* We don't need any NOP_EXPR or NON_LVALUE_EXPR on the result.  */
5022   while ((TREE_CODE (gnu_result) == NOP_EXPR
5023           || TREE_CODE (gnu_result) == NON_LVALUE_EXPR)
5024          && TREE_TYPE (TREE_OPERAND (gnu_result, 0)) == TREE_TYPE (gnu_result))
5025     gnu_result = TREE_OPERAND (gnu_result, 0);
5026
5027   return gnu_result;
5028 }
5029 \f
5030 /* Subroutine of above to push the exception label stack.  GNU_STACK is
5031    a pointer to the stack to update and GNAT_LABEL, if present, is the
5032    label to push onto the stack.  */
5033
5034 static void
5035 push_exception_label_stack (tree *gnu_stack, Entity_Id gnat_label)
5036 {
5037   tree gnu_label = (Present (gnat_label)
5038                     ? gnat_to_gnu_entity (gnat_label, NULL_TREE, 0)
5039                     : NULL_TREE);
5040
5041   *gnu_stack = tree_cons (NULL_TREE, gnu_label, *gnu_stack);
5042 }
5043 \f
5044 /* Record the current code position in GNAT_NODE.  */
5045
5046 static void
5047 record_code_position (Node_Id gnat_node)
5048 {
5049   tree stmt_stmt = build1 (STMT_STMT, void_type_node, NULL_TREE);
5050
5051   add_stmt_with_node (stmt_stmt, gnat_node);
5052   save_gnu_tree (gnat_node, stmt_stmt, true);
5053 }
5054
5055 /* Insert the code for GNAT_NODE at the position saved for that node.  */
5056
5057 static void
5058 insert_code_for (Node_Id gnat_node)
5059 {
5060   STMT_STMT_STMT (get_gnu_tree (gnat_node)) = gnat_to_gnu (gnat_node);
5061   save_gnu_tree (gnat_node, NULL_TREE, true);
5062 }
5063 \f
5064 /* Start a new statement group chained to the previous group.  */
5065
5066 void
5067 start_stmt_group (void)
5068 {
5069   struct stmt_group *group = stmt_group_free_list;
5070
5071   /* First see if we can get one from the free list.  */
5072   if (group)
5073     stmt_group_free_list = group->previous;
5074   else
5075     group = (struct stmt_group *) ggc_alloc (sizeof (struct stmt_group));
5076
5077   group->previous = current_stmt_group;
5078   group->stmt_list = group->block = group->cleanups = NULL_TREE;
5079   current_stmt_group = group;
5080 }
5081
5082 /* Add GNU_STMT to the current statement group.  */
5083
5084 void
5085 add_stmt (tree gnu_stmt)
5086 {
5087   append_to_statement_list (gnu_stmt, &current_stmt_group->stmt_list);
5088 }
5089
5090 /* Similar, but set the location of GNU_STMT to that of GNAT_NODE.  */
5091
5092 void
5093 add_stmt_with_node (tree gnu_stmt, Node_Id gnat_node)
5094 {
5095   if (Present (gnat_node))
5096     set_expr_location_from_node (gnu_stmt, gnat_node);
5097   add_stmt (gnu_stmt);
5098 }
5099
5100 /* Add a declaration statement for GNU_DECL to the current statement group.
5101    Get SLOC from Entity_Id.  */
5102
5103 void
5104 add_decl_expr (tree gnu_decl, Entity_Id gnat_entity)
5105 {
5106   tree type = TREE_TYPE (gnu_decl);
5107   tree gnu_stmt, gnu_init, t;
5108
5109   /* If this is a variable that Gigi is to ignore, we may have been given
5110      an ERROR_MARK.  So test for it.  We also might have been given a
5111      reference for a renaming.  So only do something for a decl.  Also
5112      ignore a TYPE_DECL for an UNCONSTRAINED_ARRAY_TYPE.  */
5113   if (!DECL_P (gnu_decl)
5114       || (TREE_CODE (gnu_decl) == TYPE_DECL
5115           && TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE))
5116     return;
5117
5118   gnu_stmt = build1 (DECL_EXPR, void_type_node, gnu_decl);
5119
5120   /* If we are global, we don't want to actually output the DECL_EXPR for
5121      this decl since we already have evaluated the expressions in the
5122      sizes and positions as globals and doing it again would be wrong.  */
5123   if (global_bindings_p ())
5124     {
5125       /* Mark everything as used to prevent node sharing with subprograms.
5126          Note that walk_tree knows how to deal with TYPE_DECL, but neither
5127          VAR_DECL nor CONST_DECL.  This appears to be somewhat arbitrary.  */
5128       mark_visited (&gnu_stmt);
5129       if (TREE_CODE (gnu_decl) == VAR_DECL
5130           || TREE_CODE (gnu_decl) == CONST_DECL)
5131         {
5132           mark_visited (&DECL_SIZE (gnu_decl));
5133           mark_visited (&DECL_SIZE_UNIT (gnu_decl));
5134           mark_visited (&DECL_INITIAL (gnu_decl));
5135         }
5136       /* In any case, we have to deal with our own TYPE_ADA_SIZE field.  */
5137       if (TREE_CODE (gnu_decl) == TYPE_DECL
5138           && (TREE_CODE (type) == RECORD_TYPE
5139               || TREE_CODE (type) == UNION_TYPE
5140               || TREE_CODE (type) == QUAL_UNION_TYPE)
5141           && (t = TYPE_ADA_SIZE (type)))
5142         mark_visited (&t);
5143     }
5144   else
5145     add_stmt_with_node (gnu_stmt, gnat_entity);
5146
5147   /* If this is a variable and an initializer is attached to it, it must be
5148      valid for the context.  Similar to init_const in create_var_decl_1.  */
5149   if (TREE_CODE (gnu_decl) == VAR_DECL
5150       && (gnu_init = DECL_INITIAL (gnu_decl)) != NULL_TREE
5151       && (!gnat_types_compatible_p (type, TREE_TYPE (gnu_init))
5152           || (TREE_STATIC (gnu_decl)
5153               && !initializer_constant_valid_p (gnu_init,
5154                                                 TREE_TYPE (gnu_init)))))
5155     {
5156       /* If GNU_DECL has a padded type, convert it to the unpadded
5157          type so the assignment is done properly.  */
5158       if (TREE_CODE (type) == RECORD_TYPE && TYPE_IS_PADDING_P (type))
5159         t = convert (TREE_TYPE (TYPE_FIELDS (type)), gnu_decl);
5160       else
5161         t = gnu_decl;
5162
5163       gnu_stmt = build_binary_op (MODIFY_EXPR, NULL_TREE, t, gnu_init);
5164
5165       DECL_INITIAL (gnu_decl) = NULL_TREE;
5166       if (TREE_READONLY (gnu_decl))
5167         {
5168           TREE_READONLY (gnu_decl) = 0;
5169           DECL_READONLY_ONCE_ELAB (gnu_decl) = 1;
5170         }
5171
5172       add_stmt_with_node (gnu_stmt, gnat_entity);
5173     }
5174 }
5175
5176 /* Callback for walk_tree to mark the visited trees rooted at *TP.  */
5177
5178 static tree
5179 mark_visited_r (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED)
5180 {
5181   if (TREE_VISITED (*tp))
5182     *walk_subtrees = 0;
5183
5184   /* Don't mark a dummy type as visited because we want to mark its sizes
5185      and fields once it's filled in.  */
5186   else if (!TYPE_IS_DUMMY_P (*tp))
5187     TREE_VISITED (*tp) = 1;
5188
5189   if (TYPE_P (*tp))
5190     TYPE_SIZES_GIMPLIFIED (*tp) = 1;
5191
5192   return NULL_TREE;
5193 }
5194
5195 /* Utility function to unshare expressions wrapped up in a SAVE_EXPR.  */
5196
5197 static tree
5198 unshare_save_expr (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
5199                    void *data ATTRIBUTE_UNUSED)
5200 {
5201   tree t = *tp;
5202
5203   if (TREE_CODE (t) == SAVE_EXPR)
5204     TREE_OPERAND (t, 0) = unshare_expr (TREE_OPERAND (t, 0));
5205
5206   return NULL_TREE;
5207 }
5208
5209 /* Mark nodes rooted at *TP with TREE_VISITED and types as having their
5210    sized gimplified.  We use this to indicate all variable sizes and
5211    positions in global types may not be shared by any subprogram.  */
5212
5213 void
5214 mark_visited (tree *tp)
5215 {
5216   walk_tree (tp, mark_visited_r, NULL, NULL);
5217 }
5218
5219 /* Add GNU_CLEANUP, a cleanup action, to the current code group and
5220    set its location to that of GNAT_NODE if present.  */
5221
5222 static void
5223 add_cleanup (tree gnu_cleanup, Node_Id gnat_node)
5224 {
5225   if (Present (gnat_node))
5226     set_expr_location_from_node (gnu_cleanup, gnat_node);
5227   append_to_statement_list (gnu_cleanup, &current_stmt_group->cleanups);
5228 }
5229
5230 /* Set the BLOCK node corresponding to the current code group to GNU_BLOCK.  */
5231
5232 void
5233 set_block_for_group (tree gnu_block)
5234 {
5235   gcc_assert (!current_stmt_group->block);
5236   current_stmt_group->block = gnu_block;
5237 }
5238
5239 /* Return code corresponding to the current code group.  It is normally
5240    a STATEMENT_LIST, but may also be a BIND_EXPR or TRY_FINALLY_EXPR if
5241    BLOCK or cleanups were set.  */
5242
5243 tree
5244 end_stmt_group (void)
5245 {
5246   struct stmt_group *group = current_stmt_group;
5247   tree gnu_retval = group->stmt_list;
5248
5249   /* If this is a null list, allocate a new STATEMENT_LIST.  Then, if there
5250      are cleanups, make a TRY_FINALLY_EXPR.  Last, if there is a BLOCK,
5251      make a BIND_EXPR.  Note that we nest in that because the cleanup may
5252      reference variables in the block.  */
5253   if (gnu_retval == NULL_TREE)
5254     gnu_retval = alloc_stmt_list ();
5255
5256   if (group->cleanups)
5257     gnu_retval = build2 (TRY_FINALLY_EXPR, void_type_node, gnu_retval,
5258                          group->cleanups);
5259
5260   if (current_stmt_group->block)
5261     gnu_retval = build3 (BIND_EXPR, void_type_node, BLOCK_VARS (group->block),
5262                          gnu_retval, group->block);
5263
5264   /* Remove this group from the stack and add it to the free list.  */
5265   current_stmt_group = group->previous;
5266   group->previous = stmt_group_free_list;
5267   stmt_group_free_list = group;
5268
5269   return gnu_retval;
5270 }
5271
5272 /* Add a list of statements from GNAT_LIST, a possibly-empty list of
5273    statements.*/
5274
5275 static void
5276 add_stmt_list (List_Id gnat_list)
5277 {
5278   Node_Id gnat_node;
5279
5280   if (Present (gnat_list))
5281     for (gnat_node = First (gnat_list); Present (gnat_node);
5282          gnat_node = Next (gnat_node))
5283       add_stmt (gnat_to_gnu (gnat_node));
5284 }
5285
5286 /* Build a tree from GNAT_LIST, a possibly-empty list of statements.
5287    If BINDING_P is true, push and pop a binding level around the list.  */
5288
5289 static tree
5290 build_stmt_group (List_Id gnat_list, bool binding_p)
5291 {
5292   start_stmt_group ();
5293   if (binding_p)
5294     gnat_pushlevel ();
5295
5296   add_stmt_list (gnat_list);
5297   if (binding_p)
5298     gnat_poplevel ();
5299
5300   return end_stmt_group ();
5301 }
5302 \f
5303 /* Push and pop routines for stacks.  We keep a free list around so we
5304    don't waste tree nodes.  */
5305
5306 static void
5307 push_stack (tree *gnu_stack_ptr, tree gnu_purpose, tree gnu_value)
5308 {
5309   tree gnu_node = gnu_stack_free_list;
5310
5311   if (gnu_node)
5312     {
5313       gnu_stack_free_list = TREE_CHAIN (gnu_node);
5314       TREE_CHAIN (gnu_node) = *gnu_stack_ptr;
5315       TREE_PURPOSE (gnu_node) = gnu_purpose;
5316       TREE_VALUE (gnu_node) = gnu_value;
5317     }
5318   else
5319     gnu_node = tree_cons (gnu_purpose, gnu_value, *gnu_stack_ptr);
5320
5321   *gnu_stack_ptr = gnu_node;
5322 }
5323
5324 static void
5325 pop_stack (tree *gnu_stack_ptr)
5326 {
5327   tree gnu_node = *gnu_stack_ptr;
5328
5329   *gnu_stack_ptr = TREE_CHAIN (gnu_node);
5330   TREE_CHAIN (gnu_node) = gnu_stack_free_list;
5331   gnu_stack_free_list = gnu_node;
5332 }
5333 \f
5334 /* Generate GIMPLE in place for the expression at *EXPR_P.  */
5335
5336 int
5337 gnat_gimplify_expr (tree *expr_p, tree *pre_p, tree *post_p ATTRIBUTE_UNUSED)
5338 {
5339   tree expr = *expr_p;
5340   tree op;
5341
5342   if (IS_ADA_STMT (expr))
5343     return gnat_gimplify_stmt (expr_p);
5344
5345   switch (TREE_CODE (expr))
5346     {
5347     case NULL_EXPR:
5348       /* If this is for a scalar, just make a VAR_DECL for it.  If for
5349          an aggregate, get a null pointer of the appropriate type and
5350          dereference it.  */
5351       if (AGGREGATE_TYPE_P (TREE_TYPE (expr)))
5352         *expr_p = build1 (INDIRECT_REF, TREE_TYPE (expr),
5353                           convert (build_pointer_type (TREE_TYPE (expr)),
5354                                    integer_zero_node));
5355       else
5356         {
5357           *expr_p = create_tmp_var (TREE_TYPE (expr), NULL);
5358           TREE_NO_WARNING (*expr_p) = 1;
5359         }
5360
5361       gimplify_and_add (TREE_OPERAND (expr, 0), pre_p);
5362       return GS_OK;
5363
5364     case UNCONSTRAINED_ARRAY_REF:
5365       /* We should only do this if we are just elaborating for side-effects,
5366          but we can't know that yet.  */
5367       *expr_p = TREE_OPERAND (*expr_p, 0);
5368       return GS_OK;
5369
5370     case ADDR_EXPR:
5371       op = TREE_OPERAND (expr, 0);
5372
5373       /* If we're taking the address of a constant CONSTRUCTOR, force it to
5374          be put into static memory.  We know it's going to be readonly given
5375          the semantics we have and it's required to be static memory in
5376          the case when the reference is in an elaboration procedure.   */
5377       if (TREE_CODE (op) == CONSTRUCTOR && TREE_CONSTANT (op))
5378         {
5379           tree new_var = create_tmp_var (TREE_TYPE (op), "C");
5380
5381           TREE_READONLY (new_var) = 1;
5382           TREE_STATIC (new_var) = 1;
5383           TREE_ADDRESSABLE (new_var) = 1;
5384           DECL_INITIAL (new_var) = op;
5385
5386           TREE_OPERAND (expr, 0) = new_var;
5387           recompute_tree_invariant_for_addr_expr (expr);
5388           return GS_ALL_DONE;
5389         }
5390
5391       /* If we are taking the address of a SAVE_EXPR, we are typically
5392          processing a misaligned argument to be passed by reference in a
5393          procedure call.  We just mark the operand as addressable + not
5394          readonly here and let the common gimplifier code perform the
5395          temporary creation, initialization, and "instantiation" in place of
5396          the SAVE_EXPR in further operands, in particular in the copy back
5397          code inserted after the call.  */
5398       else if (TREE_CODE (op) == SAVE_EXPR)
5399         {
5400           TREE_ADDRESSABLE (op) = 1;
5401           TREE_READONLY (op) = 0;
5402         }
5403
5404       /* We let the gimplifier process &COND_EXPR and expect it to yield the
5405          address of the selected operand when it is addressable.  Besides, we
5406          also expect addressable_p to only let COND_EXPRs where both arms are
5407          addressable reach here.  */
5408       else if (TREE_CODE (op) == COND_EXPR)
5409         ;
5410
5411       /* Otherwise, if we are taking the address of something that is neither
5412          reference, declaration, or constant, make a variable for the operand
5413          here and then take its address.  If we don't do it this way, we may
5414          confuse the gimplifier because it needs to know the variable is
5415          addressable at this point.  This duplicates code in
5416          internal_get_tmp_var, which is unfortunate.  */
5417       else if (TREE_CODE_CLASS (TREE_CODE (op)) != tcc_reference
5418                && TREE_CODE_CLASS (TREE_CODE (op)) != tcc_declaration
5419                && TREE_CODE_CLASS (TREE_CODE (op)) != tcc_constant)
5420         {
5421           tree new_var = create_tmp_var (TREE_TYPE (op), "A");
5422           tree mod = build2 (GIMPLE_MODIFY_STMT, TREE_TYPE (op), new_var, op);
5423
5424           TREE_ADDRESSABLE (new_var) = 1;
5425
5426           if (EXPR_HAS_LOCATION (op))
5427             SET_EXPR_LOCUS (mod, EXPR_LOCUS (op));
5428
5429           gimplify_and_add (mod, pre_p);
5430           TREE_OPERAND (expr, 0) = new_var;
5431           recompute_tree_invariant_for_addr_expr (expr);
5432           return GS_ALL_DONE;
5433         }
5434
5435       /* ... fall through ... */
5436
5437     default:
5438       return GS_UNHANDLED;
5439     }
5440 }
5441
5442 /* Generate GIMPLE in place for the statement at *STMT_P.  */
5443
5444 static enum gimplify_status
5445 gnat_gimplify_stmt (tree *stmt_p)
5446 {
5447   tree stmt = *stmt_p;
5448
5449   switch (TREE_CODE (stmt))
5450     {
5451     case STMT_STMT:
5452       *stmt_p = STMT_STMT_STMT (stmt);
5453       return GS_OK;
5454
5455     case LOOP_STMT:
5456       {
5457         tree gnu_start_label = create_artificial_label ();
5458         tree gnu_end_label = LOOP_STMT_LABEL (stmt);
5459         tree t;
5460
5461         /* Set to emit the statements of the loop.  */
5462         *stmt_p = NULL_TREE;
5463
5464         /* We first emit the start label and then a conditional jump to
5465            the end label if there's a top condition, then the body of the
5466            loop, then a conditional branch to the end label, then the update,
5467            if any, and finally a jump to the start label and the definition
5468            of the end label.  */
5469         append_to_statement_list (build1 (LABEL_EXPR, void_type_node,
5470                                           gnu_start_label),
5471                                   stmt_p);
5472
5473         if (LOOP_STMT_TOP_COND (stmt))
5474           append_to_statement_list (build3 (COND_EXPR, void_type_node,
5475                                             LOOP_STMT_TOP_COND (stmt),
5476                                             alloc_stmt_list (),
5477                                             build1 (GOTO_EXPR,
5478                                                     void_type_node,
5479                                                     gnu_end_label)),
5480                                     stmt_p);
5481
5482         append_to_statement_list (LOOP_STMT_BODY (stmt), stmt_p);
5483
5484         if (LOOP_STMT_BOT_COND (stmt))
5485           append_to_statement_list (build3 (COND_EXPR, void_type_node,
5486                                             LOOP_STMT_BOT_COND (stmt),
5487                                             alloc_stmt_list (),
5488                                             build1 (GOTO_EXPR,
5489                                                     void_type_node,
5490                                                     gnu_end_label)),
5491                                     stmt_p);
5492
5493         if (LOOP_STMT_UPDATE (stmt))
5494           append_to_statement_list (LOOP_STMT_UPDATE (stmt), stmt_p);
5495
5496         t = build1 (GOTO_EXPR, void_type_node, gnu_start_label);
5497         set_expr_location (t, DECL_SOURCE_LOCATION (gnu_end_label));
5498         append_to_statement_list (t, stmt_p);
5499
5500         append_to_statement_list (build1 (LABEL_EXPR, void_type_node,
5501                                           gnu_end_label),
5502                                   stmt_p);
5503         return GS_OK;
5504       }
5505
5506     case EXIT_STMT:
5507       /* Build a statement to jump to the corresponding end label, then
5508          see if it needs to be conditional.  */
5509       *stmt_p = build1 (GOTO_EXPR, void_type_node, EXIT_STMT_LABEL (stmt));
5510       if (EXIT_STMT_COND (stmt))
5511         *stmt_p = build3 (COND_EXPR, void_type_node,
5512                           EXIT_STMT_COND (stmt), *stmt_p, alloc_stmt_list ());
5513       return GS_OK;
5514
5515     default:
5516       gcc_unreachable ();
5517     }
5518 }
5519 \f
5520 /* Force references to each of the entities in packages withed by GNAT_NODE.
5521    Operate recursively but check that we aren't elaborating something more
5522    than once.
5523
5524    This routine is exclusively called in type_annotate mode, to compute DDA
5525    information for types in withed units, for ASIS use.  */
5526
5527 static void
5528 elaborate_all_entities (Node_Id gnat_node)
5529 {
5530   Entity_Id gnat_with_clause, gnat_entity;
5531
5532   /* Process each unit only once.  As we trace the context of all relevant
5533      units transitively, including generic bodies, we may encounter the
5534      same generic unit repeatedly.  */
5535   if (!present_gnu_tree (gnat_node))
5536      save_gnu_tree (gnat_node, integer_zero_node, true);
5537
5538   /* Save entities in all context units.  A body may have an implicit_with
5539      on its own spec, if the context includes a child unit, so don't save
5540      the spec twice.  */
5541   for (gnat_with_clause = First (Context_Items (gnat_node));
5542        Present (gnat_with_clause);
5543        gnat_with_clause = Next (gnat_with_clause))
5544     if (Nkind (gnat_with_clause) == N_With_Clause
5545         && !present_gnu_tree (Library_Unit (gnat_with_clause))
5546         && Library_Unit (gnat_with_clause) != Library_Unit (Cunit (Main_Unit)))
5547       {
5548         elaborate_all_entities (Library_Unit (gnat_with_clause));
5549
5550         if (Ekind (Entity (Name (gnat_with_clause))) == E_Package)
5551           {
5552             for (gnat_entity = First_Entity (Entity (Name (gnat_with_clause)));
5553                  Present (gnat_entity);
5554                  gnat_entity = Next_Entity (gnat_entity))
5555               if (Is_Public (gnat_entity)
5556                   && Convention (gnat_entity) != Convention_Intrinsic
5557                   && Ekind (gnat_entity) != E_Package
5558                   && Ekind (gnat_entity) != E_Package_Body
5559                   && Ekind (gnat_entity) != E_Operator
5560                   && !(IN (Ekind (gnat_entity), Type_Kind)
5561                        && !Is_Frozen (gnat_entity))
5562                   && !((Ekind (gnat_entity) == E_Procedure
5563                         || Ekind (gnat_entity) == E_Function)
5564                        && Is_Intrinsic_Subprogram (gnat_entity))
5565                   && !IN (Ekind (gnat_entity), Named_Kind)
5566                   && !IN (Ekind (gnat_entity), Generic_Unit_Kind))
5567                 gnat_to_gnu_entity (gnat_entity, NULL_TREE, 0);
5568           }
5569         else if (Ekind (Entity (Name (gnat_with_clause))) == E_Generic_Package)
5570           {
5571             Node_Id gnat_body
5572               = Corresponding_Body (Unit (Library_Unit (gnat_with_clause)));
5573
5574             /* Retrieve compilation unit node of generic body.  */
5575             while (Present (gnat_body)
5576                    && Nkind (gnat_body) != N_Compilation_Unit)
5577               gnat_body = Parent (gnat_body);
5578
5579             /* If body is available, elaborate its context.  */
5580             if (Present (gnat_body))
5581               elaborate_all_entities (gnat_body);
5582           }
5583       }
5584
5585   if (Nkind (Unit (gnat_node)) == N_Package_Body)
5586     elaborate_all_entities (Library_Unit (gnat_node));
5587 }
5588 \f
5589 /* Do the processing of N_Freeze_Entity, GNAT_NODE.  */
5590
5591 static void
5592 process_freeze_entity (Node_Id gnat_node)
5593 {
5594   Entity_Id gnat_entity = Entity (gnat_node);
5595   tree gnu_old;
5596   tree gnu_new;
5597   tree gnu_init
5598     = (Nkind (Declaration_Node (gnat_entity)) == N_Object_Declaration
5599        && present_gnu_tree (Declaration_Node (gnat_entity)))
5600       ? get_gnu_tree (Declaration_Node (gnat_entity)) : NULL_TREE;
5601
5602   /* If this is a package, need to generate code for the package.  */
5603   if (Ekind (gnat_entity) == E_Package)
5604     {
5605       insert_code_for
5606         (Parent (Corresponding_Body
5607                  (Parent (Declaration_Node (gnat_entity)))));
5608       return;
5609     }
5610
5611   /* Check for old definition after the above call.  This Freeze_Node
5612      might be for one its Itypes.  */
5613   gnu_old
5614     = present_gnu_tree (gnat_entity) ? get_gnu_tree (gnat_entity) : 0;
5615
5616   /* If this entity has an Address representation clause, GNU_OLD is the
5617      address, so discard it here. */
5618   if (Present (Address_Clause (gnat_entity)))
5619     gnu_old = 0;
5620
5621   /* Don't do anything for class-wide types they are always
5622      transformed into their root type.  */
5623   if (Ekind (gnat_entity) == E_Class_Wide_Type
5624       || (Ekind (gnat_entity) == E_Class_Wide_Subtype
5625           && Present (Equivalent_Type (gnat_entity))))
5626     return;
5627
5628   /* Don't do anything for subprograms that may have been elaborated before
5629      their freeze nodes.  This can happen, for example because of an inner call
5630      in an instance body, or a previous compilation of a spec for inlining
5631      purposes. */
5632   if (gnu_old
5633       && ((TREE_CODE (gnu_old) == FUNCTION_DECL
5634            && (Ekind (gnat_entity) == E_Function
5635                || Ekind (gnat_entity) == E_Procedure))
5636           || (gnu_old
5637               && TREE_CODE (TREE_TYPE (gnu_old)) == FUNCTION_TYPE
5638               && Ekind (gnat_entity) == E_Subprogram_Type)))
5639     return;
5640
5641   /* If we have a non-dummy type old tree, we have nothing to do, except
5642      aborting if this is the public view of a private type whose full view was
5643      not delayed, as this node was never delayed as it should have been.  We
5644      let this happen for concurrent types and their Corresponding_Record_Type,
5645      however, because each might legitimately be elaborated before it's own
5646      freeze node, e.g. while processing the other.  */
5647   if (gnu_old
5648       && !(TREE_CODE (gnu_old) == TYPE_DECL
5649            && TYPE_IS_DUMMY_P (TREE_TYPE (gnu_old))))
5650     {
5651       gcc_assert ((IN (Ekind (gnat_entity), Incomplete_Or_Private_Kind)
5652                    && Present (Full_View (gnat_entity))
5653                    && No (Freeze_Node (Full_View (gnat_entity))))
5654                   || Is_Concurrent_Type (gnat_entity)
5655                   || (IN (Ekind (gnat_entity), Record_Kind)
5656                       && Is_Concurrent_Record_Type (gnat_entity)));
5657       return;
5658     }
5659
5660   /* Reset the saved tree, if any, and elaborate the object or type for real.
5661      If there is a full declaration, elaborate it and copy the type to
5662      GNAT_ENTITY.  Likewise if this is the record subtype corresponding to
5663      a class wide type or subtype. */
5664   if (gnu_old)
5665     {
5666       save_gnu_tree (gnat_entity, NULL_TREE, false);
5667       if (IN (Ekind (gnat_entity), Incomplete_Or_Private_Kind)
5668           && Present (Full_View (gnat_entity))
5669           && present_gnu_tree (Full_View (gnat_entity)))
5670         save_gnu_tree (Full_View (gnat_entity), NULL_TREE, false);
5671       if (Present (Class_Wide_Type (gnat_entity))
5672           && Class_Wide_Type (gnat_entity) != gnat_entity)
5673         save_gnu_tree (Class_Wide_Type (gnat_entity), NULL_TREE, false);
5674     }
5675
5676   if (IN (Ekind (gnat_entity), Incomplete_Or_Private_Kind)
5677       && Present (Full_View (gnat_entity)))
5678     {
5679       gnu_new = gnat_to_gnu_entity (Full_View (gnat_entity), NULL_TREE, 1);
5680
5681       /* Propagate back-annotations from full view to partial view.  */
5682       if (Unknown_Alignment (gnat_entity))
5683         Set_Alignment (gnat_entity, Alignment (Full_View (gnat_entity)));
5684
5685       if (Unknown_Esize (gnat_entity))
5686         Set_Esize (gnat_entity, Esize (Full_View (gnat_entity)));
5687
5688       if (Unknown_RM_Size (gnat_entity))
5689         Set_RM_Size (gnat_entity, RM_Size (Full_View (gnat_entity)));
5690
5691       /* The above call may have defined this entity (the simplest example
5692          of this is when we have a private enumeral type since the bounds
5693          will have the public view.  */
5694       if (!present_gnu_tree (gnat_entity))
5695         save_gnu_tree (gnat_entity, gnu_new, false);
5696       if (Present (Class_Wide_Type (gnat_entity))
5697           && Class_Wide_Type (gnat_entity) != gnat_entity)
5698         save_gnu_tree (Class_Wide_Type (gnat_entity), gnu_new, false);
5699     }
5700   else
5701     gnu_new = gnat_to_gnu_entity (gnat_entity, gnu_init, 1);
5702
5703   /* If we've made any pointers to the old version of this type, we
5704      have to update them.  */
5705   if (gnu_old)
5706     update_pointer_to (TYPE_MAIN_VARIANT (TREE_TYPE (gnu_old)),
5707                        TREE_TYPE (gnu_new));
5708 }
5709 \f
5710 /* Process the list of inlined subprograms of GNAT_NODE, which is an
5711    N_Compilation_Unit.  */
5712
5713 static void
5714 process_inlined_subprograms (Node_Id gnat_node)
5715 {
5716   Entity_Id gnat_entity;
5717   Node_Id gnat_body;
5718
5719   /* If we can inline, generate RTL for all the inlined subprograms.
5720      Define the entity first so we set DECL_EXTERNAL.  */
5721   if (optimize > 0 && !flag_really_no_inline)
5722     for (gnat_entity = First_Inlined_Subprogram (gnat_node);
5723          Present (gnat_entity);
5724          gnat_entity = Next_Inlined_Subprogram (gnat_entity))
5725       {
5726         gnat_body = Parent (Declaration_Node (gnat_entity));
5727
5728         if (Nkind (gnat_body) != N_Subprogram_Body)
5729           {
5730             /* ??? This really should always be Present.  */
5731             if (No (Corresponding_Body (gnat_body)))
5732               continue;
5733
5734             gnat_body
5735               = Parent (Declaration_Node (Corresponding_Body (gnat_body)));
5736           }
5737
5738         if (Present (gnat_body))
5739           {
5740             gnat_to_gnu_entity (gnat_entity, NULL_TREE, 0);
5741             add_stmt (gnat_to_gnu (gnat_body));
5742           }
5743       }
5744 }
5745 \f
5746 /* Elaborate decls in the lists GNAT_DECLS and GNAT_DECLS2, if present.
5747    We make two passes, one to elaborate anything other than bodies (but
5748    we declare a function if there was no spec).  The second pass
5749    elaborates the bodies.
5750
5751    GNAT_END_LIST gives the element in the list past the end.  Normally,
5752    this is Empty, but can be First_Real_Statement for a
5753    Handled_Sequence_Of_Statements.
5754
5755    We make a complete pass through both lists if PASS1P is true, then make
5756    the second pass over both lists if PASS2P is true.  The lists usually
5757    correspond to the public and private parts of a package.  */
5758
5759 static void
5760 process_decls (List_Id gnat_decls, List_Id gnat_decls2,
5761                Node_Id gnat_end_list, bool pass1p, bool pass2p)
5762 {
5763   List_Id gnat_decl_array[2];
5764   Node_Id gnat_decl;
5765   int i;
5766
5767   gnat_decl_array[0] = gnat_decls, gnat_decl_array[1] = gnat_decls2;
5768
5769   if (pass1p)
5770     for (i = 0; i <= 1; i++)
5771       if (Present (gnat_decl_array[i]))
5772         for (gnat_decl = First (gnat_decl_array[i]);
5773              gnat_decl != gnat_end_list; gnat_decl = Next (gnat_decl))
5774           {
5775             /* For package specs, we recurse inside the declarations,
5776                thus taking the two pass approach inside the boundary.  */
5777             if (Nkind (gnat_decl) == N_Package_Declaration
5778                 && (Nkind (Specification (gnat_decl)
5779                            == N_Package_Specification)))
5780               process_decls (Visible_Declarations (Specification (gnat_decl)),
5781                              Private_Declarations (Specification (gnat_decl)),
5782                              Empty, true, false);
5783
5784             /* Similarly for any declarations in the actions of a
5785                freeze node.  */
5786             else if (Nkind (gnat_decl) == N_Freeze_Entity)
5787               {
5788                 process_freeze_entity (gnat_decl);
5789                 process_decls (Actions (gnat_decl), Empty, Empty, true, false);
5790               }
5791
5792             /* Package bodies with freeze nodes get their elaboration deferred
5793                until the freeze node, but the code must be placed in the right
5794                place, so record the code position now.  */
5795             else if (Nkind (gnat_decl) == N_Package_Body
5796                      && Present (Freeze_Node (Corresponding_Spec (gnat_decl))))
5797               record_code_position (gnat_decl);
5798
5799             else if (Nkind (gnat_decl) == N_Package_Body_Stub
5800                      && Present (Library_Unit (gnat_decl))
5801                      && Present (Freeze_Node
5802                                  (Corresponding_Spec
5803                                   (Proper_Body (Unit
5804                                                 (Library_Unit (gnat_decl)))))))
5805               record_code_position
5806                 (Proper_Body (Unit (Library_Unit (gnat_decl))));
5807
5808             /* We defer most subprogram bodies to the second pass.  */
5809             else if (Nkind (gnat_decl) == N_Subprogram_Body)
5810               {
5811                 if (Acts_As_Spec (gnat_decl))
5812                   {
5813                     Node_Id gnat_subprog_id = Defining_Entity (gnat_decl);
5814
5815                     if (Ekind (gnat_subprog_id) != E_Generic_Procedure
5816                         && Ekind (gnat_subprog_id) != E_Generic_Function)
5817                       gnat_to_gnu_entity (gnat_subprog_id, NULL_TREE, 1);
5818                   }
5819               }
5820             /* For bodies and stubs that act as their own specs, the entity
5821                itself must be elaborated in the first pass, because it may
5822                be used in other declarations. */
5823             else if (Nkind (gnat_decl) == N_Subprogram_Body_Stub)
5824               {
5825                   Node_Id gnat_subprog_id =
5826                      Defining_Entity (Specification (gnat_decl));
5827
5828                     if (Ekind (gnat_subprog_id) != E_Subprogram_Body
5829                         && Ekind (gnat_subprog_id) != E_Generic_Procedure
5830                         && Ekind (gnat_subprog_id) != E_Generic_Function)
5831                       gnat_to_gnu_entity (gnat_subprog_id, NULL_TREE, 1);
5832                }
5833
5834             /* Concurrent stubs stand for the corresponding subprogram bodies,
5835                which are deferred like other bodies.  */
5836             else if (Nkind (gnat_decl) == N_Task_Body_Stub
5837                      || Nkind (gnat_decl) == N_Protected_Body_Stub)
5838               ;
5839             else
5840               add_stmt (gnat_to_gnu (gnat_decl));
5841           }
5842
5843   /* Here we elaborate everything we deferred above except for package bodies,
5844      which are elaborated at their freeze nodes.  Note that we must also
5845      go inside things (package specs and freeze nodes) the first pass did.  */
5846   if (pass2p)
5847     for (i = 0; i <= 1; i++)
5848       if (Present (gnat_decl_array[i]))
5849         for (gnat_decl = First (gnat_decl_array[i]);
5850              gnat_decl != gnat_end_list; gnat_decl = Next (gnat_decl))
5851           {
5852             if (Nkind (gnat_decl) == N_Subprogram_Body
5853                 || Nkind (gnat_decl) == N_Subprogram_Body_Stub
5854                 || Nkind (gnat_decl) == N_Task_Body_Stub
5855                 || Nkind (gnat_decl) == N_Protected_Body_Stub)
5856               add_stmt (gnat_to_gnu (gnat_decl));
5857
5858             else if (Nkind (gnat_decl) == N_Package_Declaration
5859                      && (Nkind (Specification (gnat_decl)
5860                                 == N_Package_Specification)))
5861               process_decls (Visible_Declarations (Specification (gnat_decl)),
5862                              Private_Declarations (Specification (gnat_decl)),
5863                              Empty, false, true);
5864
5865             else if (Nkind (gnat_decl) == N_Freeze_Entity)
5866               process_decls (Actions (gnat_decl), Empty, Empty, false, true);
5867           }
5868 }
5869 \f
5870 /* Emit code for a range check. GNU_EXPR is the expression to be checked,
5871    GNAT_RANGE_TYPE the gnat type or subtype containing the bounds against
5872    which we have to check. */
5873
5874 static tree
5875 emit_range_check (tree gnu_expr, Entity_Id gnat_range_type)
5876 {
5877   tree gnu_range_type = get_unpadded_type (gnat_range_type);
5878   tree gnu_low  = TYPE_MIN_VALUE (gnu_range_type);
5879   tree gnu_high = TYPE_MAX_VALUE (gnu_range_type);
5880   tree gnu_compare_type = get_base_type (TREE_TYPE (gnu_expr));
5881
5882   /* If GNU_EXPR has GNAT_RANGE_TYPE as its base type, no check is needed.
5883      This can for example happen when translating 'Val or 'Value.  */
5884   if (gnu_compare_type == gnu_range_type)
5885     return gnu_expr;
5886
5887   /* If GNU_EXPR has an integral type that is narrower than GNU_RANGE_TYPE,
5888      we can't do anything since we might be truncating the bounds.  No
5889      check is needed in this case.  */
5890   if (INTEGRAL_TYPE_P (TREE_TYPE (gnu_expr))
5891       && (TYPE_PRECISION (gnu_compare_type)
5892           < TYPE_PRECISION (get_base_type (gnu_range_type))))
5893     return gnu_expr;
5894
5895   /* Checked expressions must be evaluated only once. */
5896   gnu_expr = protect_multiple_eval (gnu_expr);
5897
5898   /* There's no good type to use here, so we might as well use
5899      integer_type_node. Note that the form of the check is
5900         (not (expr >= lo)) or (not (expr <= hi))
5901       the reason for this slightly convoluted form is that NaNs
5902       are not considered to be in range in the float case. */
5903   return emit_check
5904     (build_binary_op (TRUTH_ORIF_EXPR, integer_type_node,
5905                       invert_truthvalue
5906                       (build_binary_op (GE_EXPR, integer_type_node,
5907                                        convert (gnu_compare_type, gnu_expr),
5908                                        convert (gnu_compare_type, gnu_low))),
5909                       invert_truthvalue
5910                       (build_binary_op (LE_EXPR, integer_type_node,
5911                                         convert (gnu_compare_type, gnu_expr),
5912                                         convert (gnu_compare_type,
5913                                                  gnu_high)))),
5914      gnu_expr, CE_Range_Check_Failed);
5915 }
5916 \f
5917 /* Emit code for an index check. GNU_ARRAY_OBJECT is the array object
5918    which we are about to index, GNU_EXPR is the index expression to be
5919    checked, GNU_LOW and GNU_HIGH are the lower and upper bounds
5920    against which GNU_EXPR has to be checked. Note that for index
5921    checking we cannot use the emit_range_check function (although very
5922    similar code needs to be generated in both cases) since for index
5923    checking the array type against which we are checking the indices
5924    may be unconstrained and consequently we need to retrieve the
5925    actual index bounds from the array object itself
5926    (GNU_ARRAY_OBJECT). The place where we need to do that is in
5927    subprograms having unconstrained array formal parameters */
5928
5929 static tree
5930 emit_index_check (tree gnu_array_object,
5931                   tree gnu_expr,
5932                   tree gnu_low,
5933                   tree gnu_high)
5934 {
5935   tree gnu_expr_check;
5936
5937   /* Checked expressions must be evaluated only once. */
5938   gnu_expr = protect_multiple_eval (gnu_expr);
5939
5940   /* Must do this computation in the base type in case the expression's
5941      type is an unsigned subtypes.  */
5942   gnu_expr_check = convert (get_base_type (TREE_TYPE (gnu_expr)), gnu_expr);
5943
5944   /* If GNU_LOW or GNU_HIGH are a PLACEHOLDER_EXPR, qualify them by
5945      the object we are handling. */
5946   gnu_low = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_low, gnu_array_object);
5947   gnu_high = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_high, gnu_array_object);
5948
5949   /* There's no good type to use here, so we might as well use
5950      integer_type_node.   */
5951   return emit_check
5952     (build_binary_op (TRUTH_ORIF_EXPR, integer_type_node,
5953                       build_binary_op (LT_EXPR, integer_type_node,
5954                                        gnu_expr_check,
5955                                        convert (TREE_TYPE (gnu_expr_check),
5956                                                 gnu_low)),
5957                       build_binary_op (GT_EXPR, integer_type_node,
5958                                        gnu_expr_check,
5959                                        convert (TREE_TYPE (gnu_expr_check),
5960                                                 gnu_high))),
5961      gnu_expr, CE_Index_Check_Failed);
5962 }
5963 \f
5964 /* GNU_COND contains the condition corresponding to an access, discriminant or
5965    range check of value GNU_EXPR.  Build a COND_EXPR that returns GNU_EXPR if
5966    GNU_COND is false and raises a CONSTRAINT_ERROR if GNU_COND is true.
5967    REASON is the code that says why the exception was raised.  */
5968
5969 static tree
5970 emit_check (tree gnu_cond, tree gnu_expr, int reason)
5971 {
5972   tree gnu_call;
5973   tree gnu_result;
5974
5975   gnu_call = build_call_raise (reason, Empty, N_Raise_Constraint_Error);
5976
5977   /* Use an outer COMPOUND_EXPR to make sure that GNU_EXPR will get evaluated
5978      in front of the comparison in case it ends up being a SAVE_EXPR.  Put the
5979      whole thing inside its own SAVE_EXPR so the inner SAVE_EXPR doesn't leak
5980      out.  */
5981   gnu_result = fold_build3 (COND_EXPR, TREE_TYPE (gnu_expr), gnu_cond,
5982                             build2 (COMPOUND_EXPR, TREE_TYPE (gnu_expr),
5983                                     gnu_call, gnu_expr),
5984                             gnu_expr);
5985
5986   /* If GNU_EXPR has side effects, make the outer COMPOUND_EXPR and
5987      protect it.  Otherwise, show GNU_RESULT has no side effects: we
5988      don't need to evaluate it just for the check.  */
5989   if (TREE_SIDE_EFFECTS (gnu_expr))
5990     gnu_result
5991       = build2 (COMPOUND_EXPR, TREE_TYPE (gnu_expr), gnu_expr, gnu_result);
5992   else
5993     TREE_SIDE_EFFECTS (gnu_result) = 0;
5994
5995   /* ??? Unfortunately, if we don't put a SAVE_EXPR around this whole thing,
5996      we will repeatedly do the test.  It would be nice if GCC was able
5997      to optimize this and only do it once.  */
5998   return save_expr (gnu_result);
5999 }
6000 \f
6001 /* Return an expression that converts GNU_EXPR to GNAT_TYPE, doing
6002    overflow checks if OVERFLOW_P is nonzero and range checks if
6003    RANGE_P is nonzero.  GNAT_TYPE is known to be an integral type.
6004    If TRUNCATE_P is nonzero, do a float to integer conversion with
6005    truncation; otherwise round.  */
6006
6007 static tree
6008 convert_with_check (Entity_Id gnat_type, tree gnu_expr, bool overflowp,
6009                     bool rangep, bool truncatep)
6010 {
6011   tree gnu_type = get_unpadded_type (gnat_type);
6012   tree gnu_in_type = TREE_TYPE (gnu_expr);
6013   tree gnu_in_basetype = get_base_type (gnu_in_type);
6014   tree gnu_base_type = get_base_type (gnu_type);
6015   tree gnu_result = gnu_expr;
6016
6017   /* If we are not doing any checks, the output is an integral type, and
6018      the input is not a floating type, just do the conversion.  This
6019      shortcut is required to avoid problems with packed array types
6020      and simplifies code in all cases anyway.   */
6021   if (!rangep && !overflowp && INTEGRAL_TYPE_P (gnu_base_type)
6022       && !FLOAT_TYPE_P (gnu_in_type))
6023     return convert (gnu_type, gnu_expr);
6024
6025   /* First convert the expression to its base type.  This
6026      will never generate code, but makes the tests below much simpler.
6027      But don't do this if converting from an integer type to an unconstrained
6028      array type since then we need to get the bounds from the original
6029      (unpacked) type.  */
6030   if (TREE_CODE (gnu_type) != UNCONSTRAINED_ARRAY_TYPE)
6031     gnu_result = convert (gnu_in_basetype, gnu_result);
6032
6033   /* If overflow checks are requested,  we need to be sure the result will
6034      fit in the output base type.  But don't do this if the input
6035      is integer and the output floating-point.  */
6036   if (overflowp
6037       && !(FLOAT_TYPE_P (gnu_base_type) && INTEGRAL_TYPE_P (gnu_in_basetype)))
6038     {
6039       /* Ensure GNU_EXPR only gets evaluated once.  */
6040       tree gnu_input = protect_multiple_eval (gnu_result);
6041       tree gnu_cond = integer_zero_node;
6042       tree gnu_in_lb = TYPE_MIN_VALUE (gnu_in_basetype);
6043       tree gnu_in_ub = TYPE_MAX_VALUE (gnu_in_basetype);
6044       tree gnu_out_lb = TYPE_MIN_VALUE (gnu_base_type);
6045       tree gnu_out_ub = TYPE_MAX_VALUE (gnu_base_type);
6046
6047       /* Convert the lower bounds to signed types, so we're sure we're
6048          comparing them properly.  Likewise, convert the upper bounds
6049          to unsigned types.  */
6050       if (INTEGRAL_TYPE_P (gnu_in_basetype) && TYPE_UNSIGNED (gnu_in_basetype))
6051         gnu_in_lb = convert (gnat_signed_type (gnu_in_basetype), gnu_in_lb);
6052
6053       if (INTEGRAL_TYPE_P (gnu_in_basetype)
6054           && !TYPE_UNSIGNED (gnu_in_basetype))
6055         gnu_in_ub = convert (gnat_unsigned_type (gnu_in_basetype), gnu_in_ub);
6056
6057       if (INTEGRAL_TYPE_P (gnu_base_type) && TYPE_UNSIGNED (gnu_base_type))
6058         gnu_out_lb = convert (gnat_signed_type (gnu_base_type), gnu_out_lb);
6059
6060       if (INTEGRAL_TYPE_P (gnu_base_type) && !TYPE_UNSIGNED (gnu_base_type))
6061         gnu_out_ub = convert (gnat_unsigned_type (gnu_base_type), gnu_out_ub);
6062
6063       /* Check each bound separately and only if the result bound
6064          is tighter than the bound on the input type.  Note that all the
6065          types are base types, so the bounds must be constant. Also,
6066          the comparison is done in the base type of the input, which
6067          always has the proper signedness.  First check for input
6068          integer (which means output integer), output float (which means
6069          both float), or mixed, in which case we always compare.
6070          Note that we have to do the comparison which would *fail* in the
6071          case of an error since if it's an FP comparison and one of the
6072          values is a NaN or Inf, the comparison will fail.  */
6073       if (INTEGRAL_TYPE_P (gnu_in_basetype)
6074           ? tree_int_cst_lt (gnu_in_lb, gnu_out_lb)
6075           : (FLOAT_TYPE_P (gnu_base_type)
6076              ? REAL_VALUES_LESS (TREE_REAL_CST (gnu_in_lb),
6077                                  TREE_REAL_CST (gnu_out_lb))
6078              : 1))
6079         gnu_cond
6080           = invert_truthvalue
6081             (build_binary_op (GE_EXPR, integer_type_node,
6082                               gnu_input, convert (gnu_in_basetype,
6083                                                   gnu_out_lb)));
6084
6085       if (INTEGRAL_TYPE_P (gnu_in_basetype)
6086           ? tree_int_cst_lt (gnu_out_ub, gnu_in_ub)
6087           : (FLOAT_TYPE_P (gnu_base_type)
6088              ? REAL_VALUES_LESS (TREE_REAL_CST (gnu_out_ub),
6089                                  TREE_REAL_CST (gnu_in_lb))
6090              : 1))
6091         gnu_cond
6092           = build_binary_op (TRUTH_ORIF_EXPR, integer_type_node, gnu_cond,
6093                              invert_truthvalue
6094                              (build_binary_op (LE_EXPR, integer_type_node,
6095                                                gnu_input,
6096                                                convert (gnu_in_basetype,
6097                                                         gnu_out_ub))));
6098
6099       if (!integer_zerop (gnu_cond))
6100         gnu_result = emit_check (gnu_cond, gnu_input,
6101                                  CE_Overflow_Check_Failed);
6102     }
6103
6104   /* Now convert to the result base type.  If this is a non-truncating
6105      float-to-integer conversion, round.  */
6106   if (INTEGRAL_TYPE_P (gnu_base_type) && FLOAT_TYPE_P (gnu_in_basetype)
6107       && !truncatep)
6108     {
6109       REAL_VALUE_TYPE half_minus_pred_half, pred_half;
6110       tree gnu_conv, gnu_zero, gnu_comp, gnu_saved_result, calc_type;
6111       tree gnu_pred_half, gnu_add_pred_half, gnu_subtract_pred_half;
6112       const struct real_format *fmt;
6113
6114       /* The following calculations depend on proper rounding to even
6115          of each arithmetic operation. In order to prevent excess
6116          precision from spoiling this property, use the widest hardware
6117          floating-point type.
6118
6119          FIXME: For maximum efficiency, this should only be done for machines
6120          and types where intermediates may have extra precision.  */
6121
6122       calc_type = longest_float_type_node;
6123       /* FIXME: Should not have padding in the first place */
6124       if (TREE_CODE (calc_type) == RECORD_TYPE
6125               && TYPE_IS_PADDING_P (calc_type))
6126         calc_type = TREE_TYPE (TYPE_FIELDS (calc_type));
6127
6128       /* Compute the exact value calc_type'Pred (0.5) at compile time. */
6129       fmt = REAL_MODE_FORMAT (TYPE_MODE (calc_type));
6130       real_2expN (&half_minus_pred_half, -(fmt->p) - 1, TYPE_MODE (calc_type));
6131       REAL_ARITHMETIC (pred_half, MINUS_EXPR, dconsthalf,
6132                        half_minus_pred_half);
6133       gnu_pred_half = build_real (calc_type, pred_half);
6134
6135       /* If the input is strictly negative, subtract this value
6136          and otherwise add it from the input. For 0.5, the result
6137          is exactly between 1.0 and the machine number preceding 1.0
6138          (for calc_type). Since the last bit of 1.0 is even, this 0.5
6139          will round to 1.0, while all other number with an absolute
6140          value less than 0.5 round to 0.0. For larger numbers exactly
6141          halfway between integers, rounding will always be correct as
6142          the true mathematical result will be closer to the higher
6143          integer compared to the lower one. So, this constant works
6144          for all floating-point numbers.
6145
6146          The reason to use the same constant with subtract/add instead
6147          of a positive and negative constant is to allow the comparison
6148          to be scheduled in parallel with retrieval of the constant and
6149          conversion of the input to the calc_type (if necessary).
6150       */
6151
6152       gnu_zero = convert (gnu_in_basetype, integer_zero_node);
6153       gnu_saved_result = save_expr (gnu_result);
6154       gnu_conv = convert (calc_type, gnu_saved_result);
6155       gnu_comp = build2 (GE_EXPR, integer_type_node,
6156                         gnu_saved_result, gnu_zero);
6157       gnu_add_pred_half
6158         = build2 (PLUS_EXPR, calc_type, gnu_conv, gnu_pred_half);
6159       gnu_subtract_pred_half
6160         = build2 (MINUS_EXPR, calc_type, gnu_conv, gnu_pred_half);
6161       gnu_result = build3 (COND_EXPR, calc_type, gnu_comp,
6162                            gnu_add_pred_half, gnu_subtract_pred_half);
6163     }
6164
6165   if (TREE_CODE (gnu_base_type) == INTEGER_TYPE
6166       && TYPE_HAS_ACTUAL_BOUNDS_P (gnu_base_type)
6167       && TREE_CODE (gnu_result) == UNCONSTRAINED_ARRAY_REF)
6168     gnu_result = unchecked_convert (gnu_base_type, gnu_result, false);
6169   else
6170     gnu_result = convert (gnu_base_type, gnu_result);
6171
6172   /* Finally, do the range check if requested.  Note that if the
6173      result type is a modular type, the range check is actually
6174      an overflow check.  */
6175
6176   if (rangep
6177       || (TREE_CODE (gnu_base_type) == INTEGER_TYPE
6178           && TYPE_MODULAR_P (gnu_base_type) && overflowp))
6179     gnu_result = emit_range_check (gnu_result, gnat_type);
6180
6181   return convert (gnu_type, gnu_result);
6182 }
6183 \f
6184 /* Return true if TYPE is a smaller packable version of RECORD_TYPE.  */
6185
6186 static bool
6187 smaller_packable_type_p (tree type, tree record_type)
6188 {
6189   tree size, rsize;
6190
6191   /* We're not interested in variants here.  */
6192   if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (record_type))
6193     return false;
6194
6195   /* Like a variant, a packable version keeps the original TYPE_NAME.  */
6196   if (TYPE_NAME (type) != TYPE_NAME (record_type))
6197     return false;
6198
6199   size = TYPE_SIZE (type);
6200   rsize = TYPE_SIZE (record_type);
6201
6202   if (!(TREE_CODE (size) == INTEGER_CST && TREE_CODE (rsize) == INTEGER_CST))
6203     return false;
6204
6205   return tree_int_cst_lt (size, rsize) != 0;
6206 }
6207
6208 /* Return true if GNU_EXPR can be directly addressed.  This is the case
6209    unless it is an expression involving computation or if it involves a
6210    reference to a bitfield or to an object not sufficiently aligned for
6211    its type.  If GNU_TYPE is non-null, return true only if GNU_EXPR can
6212    be directly addressed as an object of this type.
6213
6214    *** Notes on addressability issues in the Ada compiler ***
6215
6216    This predicate is necessary in order to bridge the gap between Gigi
6217    and the middle-end about addressability of GENERIC trees.  A tree
6218    is said to be addressable if it can be directly addressed, i.e. if
6219    its address can be taken, is a multiple of the type's alignment on
6220    strict-alignment architectures and returns the first storage unit
6221    assigned to the object represented by the tree.
6222
6223    In the C family of languages, everything is in practice addressable
6224    at the language level, except for bit-fields.  This means that these
6225    compilers will take the address of any tree that doesn't represent
6226    a bit-field reference and expect the result to be the first storage
6227    unit assigned to the object.  Even in cases where this will result
6228    in unaligned accesses at run time, nothing is supposed to be done
6229    and the program is considered as erroneous instead (see PR c/18287).
6230
6231    The implicit assumptions made in the middle-end are in keeping with
6232    the C viewpoint described above:
6233      - the address of a bit-field reference is supposed to be never
6234        taken; the compiler (generally) will stop on such a construct,
6235      - any other tree is addressable if it is formally addressable,
6236        i.e. if it is formally allowed to be the operand of ADDR_EXPR.
6237
6238    In Ada, the viewpoint is the opposite one: nothing is addressable
6239    at the language level unless explicitly declared so.  This means
6240    that the compiler will both make sure that the trees representing
6241    references to addressable ("aliased" in Ada parlance) objects are
6242    addressable and make no real attempts at ensuring that the trees
6243    representing references to non-addressable objects are addressable.
6244
6245    In the first case, Ada is effectively equivalent to C and handing
6246    down the direct result of applying ADDR_EXPR to these trees to the
6247    middle-end works flawlessly.  In the second case, Ada cannot afford
6248    to consider the program as erroneous if the address of trees that
6249    are not addressable is requested for technical reasons, unlike C;
6250    as a consequence, the Ada compiler must arrange for either making
6251    sure that this address is not requested in the middle-end or for
6252    compensating by inserting temporaries if it is requested in Gigi.
6253
6254    The first goal can be achieved because the middle-end should not
6255    request the address of non-addressable trees on its own; the only
6256    exception is for the invocation of low-level block operations like
6257    memcpy, for which the addressability requirements are lower since
6258    the type's alignment can be disregarded.  In practice, this means
6259    that Gigi must make sure that such operations cannot be applied to
6260    non-BLKmode bit-fields.
6261
6262    The second goal is achieved by means of the addressable_p predicate
6263    and by inserting SAVE_EXPRs around trees deemed non-addressable.
6264    They will be turned during gimplification into proper temporaries
6265    whose address will be used in lieu of that of the original tree.  */
6266
6267 static bool
6268 addressable_p (tree gnu_expr, tree gnu_type)
6269 {
6270   /* The size of the real type of the object must not be smaller than
6271      that of the expected type, otherwise an indirect access in the
6272      latter type would be larger than the object.  Only records need
6273      to be considered in practice.  */
6274   if (gnu_type
6275       && TREE_CODE (gnu_type) == RECORD_TYPE
6276       && smaller_packable_type_p (TREE_TYPE (gnu_expr), gnu_type))
6277     return false;
6278
6279   switch (TREE_CODE (gnu_expr))
6280     {
6281     case VAR_DECL:
6282     case PARM_DECL:
6283     case FUNCTION_DECL:
6284     case RESULT_DECL:
6285       /* All DECLs are addressable: if they are in a register, we can force
6286          them to memory.  */
6287       return true;
6288
6289     case UNCONSTRAINED_ARRAY_REF:
6290     case INDIRECT_REF:
6291     case CONSTRUCTOR:
6292     case STRING_CST:
6293     case INTEGER_CST:
6294     case NULL_EXPR:
6295     case SAVE_EXPR:
6296     case CALL_EXPR:
6297       return true;
6298
6299     case COND_EXPR:
6300       /* We accept &COND_EXPR as soon as both operands are addressable and
6301          expect the outcome to be the address of the selected operand.  */
6302       return (addressable_p (TREE_OPERAND (gnu_expr, 1), NULL_TREE)
6303               && addressable_p (TREE_OPERAND (gnu_expr, 2), NULL_TREE));
6304
6305     case COMPONENT_REF:
6306       return (((!DECL_BIT_FIELD (TREE_OPERAND (gnu_expr, 1))
6307                 /* Even with DECL_BIT_FIELD cleared, we have to ensure that
6308                    the field is sufficiently aligned, in case it is subject
6309                    to a pragma Component_Alignment.  But we don't need to
6310                    check the alignment of the containing record, as it is
6311                    guaranteed to be not smaller than that of its most
6312                    aligned field that is not a bit-field.  */
6313                 && (!STRICT_ALIGNMENT
6314                     || DECL_ALIGN (TREE_OPERAND (gnu_expr, 1))
6315                        >= TYPE_ALIGN (TREE_TYPE (gnu_expr))))
6316                /* The field of a padding record is always addressable.  */
6317                || TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_expr, 0))))
6318               && addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE));
6319
6320     case ARRAY_REF:  case ARRAY_RANGE_REF:
6321     case REALPART_EXPR:  case IMAGPART_EXPR:
6322     case NOP_EXPR:
6323       return addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE);
6324
6325     case CONVERT_EXPR:
6326       return (AGGREGATE_TYPE_P (TREE_TYPE (gnu_expr))
6327               && addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE));
6328
6329     case VIEW_CONVERT_EXPR:
6330       {
6331         /* This is addressable if we can avoid a copy.  */
6332         tree type = TREE_TYPE (gnu_expr);
6333         tree inner_type = TREE_TYPE (TREE_OPERAND (gnu_expr, 0));
6334         return (((TYPE_MODE (type) == TYPE_MODE (inner_type)
6335                   && (!STRICT_ALIGNMENT
6336                       || TYPE_ALIGN (type) <= TYPE_ALIGN (inner_type)
6337                       || TYPE_ALIGN (inner_type) >= BIGGEST_ALIGNMENT))
6338                  || ((TYPE_MODE (type) == BLKmode
6339                       || TYPE_MODE (inner_type) == BLKmode)
6340                      && (!STRICT_ALIGNMENT
6341                          || TYPE_ALIGN (type) <= TYPE_ALIGN (inner_type)
6342                          || TYPE_ALIGN (inner_type) >= BIGGEST_ALIGNMENT
6343                          || TYPE_ALIGN_OK (type)
6344                          || TYPE_ALIGN_OK (inner_type))))
6345                 && addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE));
6346       }
6347
6348     default:
6349       return false;
6350     }
6351 }
6352 \f
6353 /* Do the processing for the declaration of a GNAT_ENTITY, a type.  If
6354    a separate Freeze node exists, delay the bulk of the processing.  Otherwise
6355    make a GCC type for GNAT_ENTITY and set up the correspondence.  */
6356
6357 void
6358 process_type (Entity_Id gnat_entity)
6359 {
6360   tree gnu_old
6361     = present_gnu_tree (gnat_entity) ? get_gnu_tree (gnat_entity) : 0;
6362   tree gnu_new;
6363
6364   /* If we are to delay elaboration of this type, just do any
6365      elaborations needed for expressions within the declaration and
6366      make a dummy type entry for this node and its Full_View (if
6367      any) in case something points to it.  Don't do this if it
6368      has already been done (the only way that can happen is if
6369      the private completion is also delayed).  */
6370   if (Present (Freeze_Node (gnat_entity))
6371       || (IN (Ekind (gnat_entity), Incomplete_Or_Private_Kind)
6372           && Present (Full_View (gnat_entity))
6373           && Freeze_Node (Full_View (gnat_entity))
6374           && !present_gnu_tree (Full_View (gnat_entity))))
6375     {
6376       elaborate_entity (gnat_entity);
6377
6378       if (!gnu_old)
6379         {
6380           tree gnu_decl = create_type_decl (get_entity_name (gnat_entity),
6381                                             make_dummy_type (gnat_entity),
6382                                             NULL, false, false, gnat_entity);
6383
6384           save_gnu_tree (gnat_entity, gnu_decl, false);
6385           if (IN (Ekind (gnat_entity), Incomplete_Or_Private_Kind)
6386               && Present (Full_View (gnat_entity)))
6387             save_gnu_tree (Full_View (gnat_entity), gnu_decl, false);
6388         }
6389
6390       return;
6391     }
6392
6393   /* If we saved away a dummy type for this node it means that this
6394      made the type that corresponds to the full type of an incomplete
6395      type.  Clear that type for now and then update the type in the
6396      pointers.  */
6397   if (gnu_old)
6398     {
6399       gcc_assert (TREE_CODE (gnu_old) == TYPE_DECL
6400                   && TYPE_IS_DUMMY_P (TREE_TYPE (gnu_old)));
6401
6402       save_gnu_tree (gnat_entity, NULL_TREE, false);
6403     }
6404
6405   /* Now fully elaborate the type.  */
6406   gnu_new = gnat_to_gnu_entity (gnat_entity, NULL_TREE, 1);
6407   gcc_assert (TREE_CODE (gnu_new) == TYPE_DECL);
6408
6409   /* If we have an old type and we've made pointers to this type,
6410      update those pointers.  */
6411   if (gnu_old)
6412     update_pointer_to (TYPE_MAIN_VARIANT (TREE_TYPE (gnu_old)),
6413                        TREE_TYPE (gnu_new));
6414
6415   /* If this is a record type corresponding to a task or protected type
6416      that is a completion of an incomplete type, perform a similar update
6417      on the type.  */
6418   /* ??? Including protected types here is a guess. */
6419
6420   if (IN (Ekind (gnat_entity), Record_Kind)
6421       && Is_Concurrent_Record_Type (gnat_entity)
6422       && present_gnu_tree (Corresponding_Concurrent_Type (gnat_entity)))
6423     {
6424       tree gnu_task_old
6425         = get_gnu_tree (Corresponding_Concurrent_Type (gnat_entity));
6426
6427       save_gnu_tree (Corresponding_Concurrent_Type (gnat_entity),
6428                      NULL_TREE, false);
6429       save_gnu_tree (Corresponding_Concurrent_Type (gnat_entity),
6430                      gnu_new, false);
6431
6432       update_pointer_to (TYPE_MAIN_VARIANT (TREE_TYPE (gnu_task_old)),
6433                          TREE_TYPE (gnu_new));
6434     }
6435 }
6436 \f
6437 /* GNAT_ENTITY is the type of the resulting constructors,
6438    GNAT_ASSOC is the front of the Component_Associations of an N_Aggregate,
6439    and GNU_TYPE is the GCC type of the corresponding record.
6440
6441    Return a CONSTRUCTOR to build the record.  */
6442
6443 static tree
6444 assoc_to_constructor (Entity_Id gnat_entity, Node_Id gnat_assoc, tree gnu_type)
6445 {
6446   tree gnu_list, gnu_result;
6447
6448   /* We test for GNU_FIELD being empty in the case where a variant
6449      was the last thing since we don't take things off GNAT_ASSOC in
6450      that case.  We check GNAT_ASSOC in case we have a variant, but it
6451      has no fields.  */
6452
6453   for (gnu_list = NULL_TREE; Present (gnat_assoc);
6454        gnat_assoc = Next (gnat_assoc))
6455     {
6456       Node_Id gnat_field = First (Choices (gnat_assoc));
6457       tree gnu_field = gnat_to_gnu_field_decl (Entity (gnat_field));
6458       tree gnu_expr = gnat_to_gnu (Expression (gnat_assoc));
6459
6460       /* The expander is supposed to put a single component selector name
6461          in every record component association */
6462       gcc_assert (No (Next (gnat_field)));
6463
6464       /* Ignore fields that have Corresponding_Discriminants since we'll
6465          be setting that field in the parent.  */
6466       if (Present (Corresponding_Discriminant (Entity (gnat_field)))
6467           && Is_Tagged_Type (Scope (Entity (gnat_field))))
6468         continue;
6469
6470       /* Also ignore discriminants of Unchecked_Unions.  */
6471       else if (Is_Unchecked_Union (gnat_entity)
6472                && Ekind (Entity (gnat_field)) == E_Discriminant)
6473         continue;
6474
6475       /* Before assigning a value in an aggregate make sure range checks
6476          are done if required.  Then convert to the type of the field.  */
6477       if (Do_Range_Check (Expression (gnat_assoc)))
6478         gnu_expr = emit_range_check (gnu_expr, Etype (gnat_field));
6479
6480       gnu_expr = convert (TREE_TYPE (gnu_field), gnu_expr);
6481
6482       /* Add the field and expression to the list.  */
6483       gnu_list = tree_cons (gnu_field, gnu_expr, gnu_list);
6484     }
6485
6486   gnu_result = extract_values (gnu_list, gnu_type);
6487
6488 #ifdef ENABLE_CHECKING
6489   {
6490     tree gnu_field;
6491
6492     /* Verify every entry in GNU_LIST was used.  */
6493     for (gnu_field = gnu_list; gnu_field; gnu_field = TREE_CHAIN (gnu_field))
6494       gcc_assert (TREE_ADDRESSABLE (gnu_field));
6495   }
6496 #endif
6497
6498   return gnu_result;
6499 }
6500
6501 /* Builds a possibly nested constructor for array aggregates. GNAT_EXPR
6502    is the first element of an array aggregate. It may itself be an
6503    aggregate (an array or record aggregate). GNU_ARRAY_TYPE is the gnu type
6504    corresponding to the array aggregate. GNAT_COMPONENT_TYPE is the type
6505    of the array component. It is needed for range checking. */
6506
6507 static tree
6508 pos_to_constructor (Node_Id gnat_expr, tree gnu_array_type,
6509                     Entity_Id gnat_component_type)
6510 {
6511   tree gnu_expr_list = NULL_TREE;
6512   tree gnu_index = TYPE_MIN_VALUE (TYPE_DOMAIN (gnu_array_type));
6513   tree gnu_expr;
6514
6515   for ( ; Present (gnat_expr); gnat_expr = Next (gnat_expr))
6516     {
6517       /* If the expression is itself an array aggregate then first build the
6518          innermost constructor if it is part of our array (multi-dimensional
6519          case).  */
6520
6521       if (Nkind (gnat_expr) == N_Aggregate
6522           && TREE_CODE (TREE_TYPE (gnu_array_type)) == ARRAY_TYPE
6523           && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_array_type)))
6524         gnu_expr = pos_to_constructor (First (Expressions (gnat_expr)),
6525                                        TREE_TYPE (gnu_array_type),
6526                                        gnat_component_type);
6527       else
6528         {
6529           gnu_expr = gnat_to_gnu (gnat_expr);
6530
6531           /* before assigning the element to the array make sure it is
6532              in range */
6533           if (Do_Range_Check (gnat_expr))
6534             gnu_expr = emit_range_check (gnu_expr, gnat_component_type);
6535         }
6536
6537       gnu_expr_list
6538         = tree_cons (gnu_index, convert (TREE_TYPE (gnu_array_type), gnu_expr),
6539                      gnu_expr_list);
6540
6541       gnu_index = int_const_binop (PLUS_EXPR, gnu_index, integer_one_node, 0);
6542     }
6543
6544   return gnat_build_constructor (gnu_array_type, nreverse (gnu_expr_list));
6545 }
6546 \f
6547 /* Subroutine of assoc_to_constructor: VALUES is a list of field associations,
6548    some of which are from RECORD_TYPE.  Return a CONSTRUCTOR consisting
6549    of the associations that are from RECORD_TYPE.  If we see an internal
6550    record, make a recursive call to fill it in as well.  */
6551
6552 static tree
6553 extract_values (tree values, tree record_type)
6554 {
6555   tree result = NULL_TREE;
6556   tree field, tem;
6557
6558   for (field = TYPE_FIELDS (record_type); field; field = TREE_CHAIN (field))
6559     {
6560       tree value = 0;
6561
6562       /* _Parent is an internal field, but may have values in the aggregate,
6563          so check for values first.  */
6564       if ((tem = purpose_member (field, values)))
6565         {
6566           value = TREE_VALUE (tem);
6567           TREE_ADDRESSABLE (tem) = 1;
6568         }
6569
6570       else if (DECL_INTERNAL_P (field))
6571         {
6572           value = extract_values (values, TREE_TYPE (field));
6573           if (TREE_CODE (value) == CONSTRUCTOR
6574               && VEC_empty (constructor_elt, CONSTRUCTOR_ELTS (value)))
6575             value = 0;
6576         }
6577       else
6578         /* If we have a record subtype, the names will match, but not the
6579            actual FIELD_DECLs.  */
6580         for (tem = values; tem; tem = TREE_CHAIN (tem))
6581           if (DECL_NAME (TREE_PURPOSE (tem)) == DECL_NAME (field))
6582             {
6583               value = convert (TREE_TYPE (field), TREE_VALUE (tem));
6584               TREE_ADDRESSABLE (tem) = 1;
6585             }
6586
6587       if (!value)
6588         continue;
6589
6590       result = tree_cons (field, value, result);
6591     }
6592
6593   return gnat_build_constructor (record_type, nreverse (result));
6594 }
6595 \f
6596 /* EXP is to be treated as an array or record.  Handle the cases when it is
6597    an access object and perform the required dereferences.  */
6598
6599 static tree
6600 maybe_implicit_deref (tree exp)
6601 {
6602   /* If the type is a pointer, dereference it.  */
6603
6604   if (POINTER_TYPE_P (TREE_TYPE (exp)) || TYPE_FAT_POINTER_P (TREE_TYPE (exp)))
6605     exp = build_unary_op (INDIRECT_REF, NULL_TREE, exp);
6606
6607   /* If we got a padded type, remove it too.  */
6608   if (TREE_CODE (TREE_TYPE (exp)) == RECORD_TYPE
6609       && TYPE_IS_PADDING_P (TREE_TYPE (exp)))
6610     exp = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (exp))), exp);
6611
6612   return exp;
6613 }
6614 \f
6615 /* Protect EXP from multiple evaluation.  This may make a SAVE_EXPR.  */
6616
6617 tree
6618 protect_multiple_eval (tree exp)
6619 {
6620   tree type = TREE_TYPE (exp);
6621
6622   /* If this has no side effects, we don't need to do anything.  */
6623   if (!TREE_SIDE_EFFECTS (exp))
6624     return exp;
6625
6626   /* If it is a conversion, protect what's inside the conversion.
6627      Similarly, if we're indirectly referencing something, we only
6628      actually need to protect the address since the data itself can't
6629      change in these situations.  */
6630   else if (TREE_CODE (exp) == NON_LVALUE_EXPR
6631            || CONVERT_EXPR_P (exp)
6632            || TREE_CODE (exp) == VIEW_CONVERT_EXPR
6633            || TREE_CODE (exp) == INDIRECT_REF
6634            || TREE_CODE (exp) == UNCONSTRAINED_ARRAY_REF)
6635     return build1 (TREE_CODE (exp), type,
6636                    protect_multiple_eval (TREE_OPERAND (exp, 0)));
6637
6638   /* If EXP is a fat pointer or something that can be placed into a register,
6639      just make a SAVE_EXPR.  */
6640   if (TYPE_FAT_POINTER_P (type) || TYPE_MODE (type) != BLKmode)
6641     return save_expr (exp);
6642
6643   /* Otherwise, dereference, protect the address, and re-reference.  */
6644   else
6645     return
6646       build_unary_op (INDIRECT_REF, type,
6647                       save_expr (build_unary_op (ADDR_EXPR,
6648                                                  build_reference_type (type),
6649                                                  exp)));
6650 }
6651 \f
6652 /* This is equivalent to stabilize_reference in tree.c, but we know how to
6653    handle our own nodes and we take extra arguments.  FORCE says whether to
6654    force evaluation of everything.  We set SUCCESS to true unless we walk
6655    through something we don't know how to stabilize.  */
6656
6657 tree
6658 maybe_stabilize_reference (tree ref, bool force, bool *success)
6659 {
6660   tree type = TREE_TYPE (ref);
6661   enum tree_code code = TREE_CODE (ref);
6662   tree result;
6663
6664   /* Assume we'll success unless proven otherwise.  */
6665   *success = true;
6666
6667   switch (code)
6668     {
6669     case CONST_DECL:
6670     case VAR_DECL:
6671     case PARM_DECL:
6672     case RESULT_DECL:
6673       /* No action is needed in this case.  */
6674       return ref;
6675
6676     case ADDR_EXPR:
6677     CASE_CONVERT:
6678     case FLOAT_EXPR:
6679     case FIX_TRUNC_EXPR:
6680     case VIEW_CONVERT_EXPR:
6681       result
6682         = build1 (code, type,
6683                   maybe_stabilize_reference (TREE_OPERAND (ref, 0), force,
6684                                              success));
6685       break;
6686
6687     case INDIRECT_REF:
6688     case UNCONSTRAINED_ARRAY_REF:
6689       result = build1 (code, type,
6690                        gnat_stabilize_reference_1 (TREE_OPERAND (ref, 0),
6691                                                    force));
6692       break;
6693
6694     case COMPONENT_REF:
6695      result = build3 (COMPONENT_REF, type,
6696                       maybe_stabilize_reference (TREE_OPERAND (ref, 0), force,
6697                                                  success),
6698                       TREE_OPERAND (ref, 1), NULL_TREE);
6699       break;
6700
6701     case BIT_FIELD_REF:
6702       result = build3 (BIT_FIELD_REF, type,
6703                        maybe_stabilize_reference (TREE_OPERAND (ref, 0), force,
6704                                                   success),
6705                        gnat_stabilize_reference_1 (TREE_OPERAND (ref, 1),
6706                                                    force),
6707                        gnat_stabilize_reference_1 (TREE_OPERAND (ref, 2),
6708                                                    force));
6709       break;
6710
6711     case ARRAY_REF:
6712     case ARRAY_RANGE_REF:
6713       result = build4 (code, type,
6714                        maybe_stabilize_reference (TREE_OPERAND (ref, 0), force,
6715                                                   success),
6716                        gnat_stabilize_reference_1 (TREE_OPERAND (ref, 1),
6717                                                    force),
6718                        NULL_TREE, NULL_TREE);
6719       break;
6720
6721     case COMPOUND_EXPR:
6722       result = gnat_stabilize_reference_1 (ref, force);
6723       break;
6724
6725     case CALL_EXPR:
6726       /* This generates better code than the scheme in protect_multiple_eval
6727          because large objects will be returned via invisible reference in
6728          most ABIs so the temporary will directly be filled by the callee.  */
6729       result = gnat_stabilize_reference_1 (ref, force);
6730       break;
6731
6732     case CONSTRUCTOR:
6733       /* Constructors with 1 element are used extensively to formally
6734          convert objects to special wrapping types.  */
6735       if (TREE_CODE (type) == RECORD_TYPE
6736           && VEC_length (constructor_elt, CONSTRUCTOR_ELTS (ref)) == 1)
6737         {
6738           tree index
6739             = VEC_index (constructor_elt, CONSTRUCTOR_ELTS (ref), 0)->index;
6740           tree value
6741             = VEC_index (constructor_elt, CONSTRUCTOR_ELTS (ref), 0)->value;
6742           result
6743             = build_constructor_single (type, index,
6744                                         gnat_stabilize_reference_1 (value,
6745                                                                     force));
6746         }
6747       else
6748         {
6749           *success = false;
6750           return ref;
6751         }
6752       break;
6753
6754     case ERROR_MARK:
6755       ref = error_mark_node;
6756
6757       /* ...  Fallthru to failure ... */
6758
6759       /* If arg isn't a kind of lvalue we recognize, make no change.
6760          Caller should recognize the error for an invalid lvalue.  */
6761     default:
6762       *success = false;
6763       return ref;
6764     }
6765
6766   TREE_READONLY (result) = TREE_READONLY (ref);
6767
6768   /* TREE_THIS_VOLATILE and TREE_SIDE_EFFECTS attached to the initial
6769      expression may not be sustained across some paths, such as the way via
6770      build1 for INDIRECT_REF.  We re-populate those flags here for the general
6771      case, which is consistent with the GCC version of this routine.
6772
6773      Special care should be taken regarding TREE_SIDE_EFFECTS, because some
6774      paths introduce side effects where there was none initially (e.g. calls
6775      to save_expr), and we also want to keep track of that.  */
6776
6777   TREE_THIS_VOLATILE (result) = TREE_THIS_VOLATILE (ref);
6778   TREE_SIDE_EFFECTS (result) |= TREE_SIDE_EFFECTS (ref);
6779
6780   return result;
6781 }
6782
6783 /* Wrapper around maybe_stabilize_reference, for common uses without
6784    lvalue restrictions and without need to examine the success
6785    indication.  */
6786
6787 static tree
6788 gnat_stabilize_reference (tree ref, bool force)
6789 {
6790   bool dummy;
6791   return maybe_stabilize_reference (ref, force, &dummy);
6792 }
6793
6794 /* Similar to stabilize_reference_1 in tree.c, but supports an extra
6795    arg to force a SAVE_EXPR for everything.  */
6796
6797 static tree
6798 gnat_stabilize_reference_1 (tree e, bool force)
6799 {
6800   enum tree_code code = TREE_CODE (e);
6801   tree type = TREE_TYPE (e);
6802   tree result;
6803
6804   /* We cannot ignore const expressions because it might be a reference
6805      to a const array but whose index contains side-effects.  But we can
6806      ignore things that are actual constant or that already have been
6807      handled by this function.  */
6808
6809   if (TREE_CONSTANT (e) || code == SAVE_EXPR)
6810     return e;
6811
6812   switch (TREE_CODE_CLASS (code))
6813     {
6814     case tcc_exceptional:
6815     case tcc_type:
6816     case tcc_declaration:
6817     case tcc_comparison:
6818     case tcc_statement:
6819     case tcc_expression:
6820     case tcc_reference:
6821     case tcc_vl_exp:
6822       /* If this is a COMPONENT_REF of a fat pointer, save the entire
6823          fat pointer.  This may be more efficient, but will also allow
6824          us to more easily find the match for the PLACEHOLDER_EXPR.  */
6825       if (code == COMPONENT_REF
6826           && TYPE_FAT_POINTER_P (TREE_TYPE (TREE_OPERAND (e, 0))))
6827         result = build3 (COMPONENT_REF, type,
6828                          gnat_stabilize_reference_1 (TREE_OPERAND (e, 0),
6829                                                      force),
6830                          TREE_OPERAND (e, 1), TREE_OPERAND (e, 2));
6831       else if (TREE_SIDE_EFFECTS (e) || force)
6832         return save_expr (e);
6833       else
6834         return e;
6835       break;
6836
6837     case tcc_constant:
6838       /* Constants need no processing.  In fact, we should never reach
6839          here.  */
6840       return e;
6841
6842     case tcc_binary:
6843       /* Recursively stabilize each operand.  */
6844       result = build2 (code, type,
6845                        gnat_stabilize_reference_1 (TREE_OPERAND (e, 0), force),
6846                        gnat_stabilize_reference_1 (TREE_OPERAND (e, 1),
6847                                                    force));
6848       break;
6849
6850     case tcc_unary:
6851       /* Recursively stabilize each operand.  */
6852       result = build1 (code, type,
6853                        gnat_stabilize_reference_1 (TREE_OPERAND (e, 0),
6854                                                    force));
6855       break;
6856
6857     default:
6858       gcc_unreachable ();
6859     }
6860
6861   TREE_READONLY (result) = TREE_READONLY (e);
6862
6863   TREE_THIS_VOLATILE (result) = TREE_THIS_VOLATILE (e);
6864   TREE_SIDE_EFFECTS (result) |= TREE_SIDE_EFFECTS (e);
6865   return result;
6866 }
6867 \f
6868 /* Convert SLOC into LOCUS.  Return true if SLOC corresponds to a source code
6869    location and false if it doesn't.  In the former case, set the Gigi global
6870    variable REF_FILENAME to the simple debug file name as given by sinput.  */
6871
6872 bool
6873 Sloc_to_locus (Source_Ptr Sloc, location_t *locus)
6874 {
6875   if (Sloc == No_Location)
6876     return false;
6877
6878   if (Sloc <= Standard_Location)
6879     {
6880       if (*locus == UNKNOWN_LOCATION)
6881         *locus = BUILTINS_LOCATION;
6882       return false;
6883     }
6884   else
6885     {
6886       Source_File_Index file = Get_Source_File_Index (Sloc);
6887       Logical_Line_Number line = Get_Logical_Line_Number (Sloc);
6888       Column_Number column = Get_Column_Number (Sloc);
6889       struct line_map *map = &line_table->maps[file - 1];
6890
6891       /* Translate the location according to the line-map.h formula.  */
6892       *locus = map->start_location
6893                 + ((line - map->to_line) << map->column_bits)
6894                 + (column & ((1 << map->column_bits) - 1));
6895     }
6896
6897   ref_filename
6898     = IDENTIFIER_POINTER
6899       (get_identifier
6900        (Get_Name_String (Debug_Source_Name (Get_Source_File_Index (Sloc)))));;
6901
6902   return true;
6903 }
6904
6905 /* Similar to set_expr_location, but start with the Sloc of GNAT_NODE and
6906    don't do anything if it doesn't correspond to a source location.  */
6907
6908 static void
6909 set_expr_location_from_node (tree node, Node_Id gnat_node)
6910 {
6911   location_t locus;
6912
6913   if (!Sloc_to_locus (Sloc (gnat_node), &locus))
6914     return;
6915
6916   set_expr_location (node, locus);
6917 }
6918 \f
6919 /* Return a colon-separated list of encodings contained in encoded Ada
6920    name.  */
6921
6922 static const char *
6923 extract_encoding (const char *name)
6924 {
6925   char *encoding = GGC_NEWVEC (char, strlen (name));
6926   
6927   get_encoding (name, encoding);
6928   
6929   return encoding;
6930 }
6931
6932 /* Extract the Ada name from an encoded name.  */
6933
6934 static const char *
6935 decode_name (const char *name)
6936 {
6937   char *decoded = GGC_NEWVEC (char, strlen (name) * 2 + 60);
6938   
6939   __gnat_decode (name, decoded, 0);
6940   
6941   return decoded;
6942 }
6943 \f
6944 /* Post an error message.  MSG is the error message, properly annotated.
6945    NODE is the node at which to post the error and the node to use for the
6946    "&" substitution.  */
6947
6948 void
6949 post_error (const char *msg, Node_Id node)
6950 {
6951   String_Template temp;
6952   Fat_Pointer fp;
6953
6954   temp.Low_Bound = 1, temp.High_Bound = strlen (msg);
6955   fp.Array = msg, fp.Bounds = &temp;
6956   if (Present (node))
6957     Error_Msg_N (fp, node);
6958 }
6959
6960 /* Similar, but NODE is the node at which to post the error and ENT
6961    is the node to use for the "&" substitution.  */
6962
6963 void
6964 post_error_ne (const char *msg, Node_Id node, Entity_Id ent)
6965 {
6966   String_Template temp;
6967   Fat_Pointer fp;
6968
6969   temp.Low_Bound = 1, temp.High_Bound = strlen (msg);
6970   fp.Array = msg, fp.Bounds = &temp;
6971   if (Present (node))
6972     Error_Msg_NE (fp, node, ent);
6973 }
6974
6975 /* Similar, but NODE is the node at which to post the error, ENT is the node
6976    to use for the "&" substitution, and N is the number to use for the ^.  */
6977
6978 void
6979 post_error_ne_num (const char *msg, Node_Id node, Entity_Id ent, int n)
6980 {
6981   String_Template temp;
6982   Fat_Pointer fp;
6983
6984   temp.Low_Bound = 1, temp.High_Bound = strlen (msg);
6985   fp.Array = msg, fp.Bounds = &temp;
6986   Error_Msg_Uint_1 = UI_From_Int (n);
6987
6988   if (Present (node))
6989     Error_Msg_NE (fp, node, ent);
6990 }
6991 \f
6992 /* Similar to post_error_ne_num, but T is a GCC tree representing the
6993    number to write.  If the tree represents a constant that fits within
6994    a host integer, the text inside curly brackets in MSG will be output
6995    (presumably including a '^').  Otherwise that text will not be output
6996    and the text inside square brackets will be output instead.  */
6997
6998 void
6999 post_error_ne_tree (const char *msg, Node_Id node, Entity_Id ent, tree t)
7000 {
7001   char *newmsg = XALLOCAVEC (char, strlen (msg) + 1);
7002   String_Template temp = {1, 0};
7003   Fat_Pointer fp;
7004   char start_yes, end_yes, start_no, end_no;
7005   const char *p;
7006   char *q;
7007
7008   fp.Array = newmsg, fp.Bounds = &temp;
7009
7010   if (host_integerp (t, 1)
7011 #if HOST_BITS_PER_WIDE_INT > HOST_BITS_PER_INT
7012       &&
7013       compare_tree_int
7014       (t, (((unsigned HOST_WIDE_INT) 1 << (HOST_BITS_PER_INT - 1)) - 1)) < 0
7015 #endif
7016       )
7017     {
7018       Error_Msg_Uint_1 = UI_From_Int (tree_low_cst (t, 1));
7019       start_yes = '{', end_yes = '}', start_no = '[', end_no = ']';
7020     }
7021   else
7022     start_yes = '[', end_yes = ']', start_no = '{', end_no = '}';
7023
7024   for (p = msg, q = newmsg; *p; p++)
7025     {
7026       if (*p == start_yes)
7027         for (p++; *p != end_yes; p++)
7028           *q++ = *p;
7029       else if (*p == start_no)
7030         for (p++; *p != end_no; p++)
7031           ;
7032       else
7033         *q++ = *p;
7034     }
7035
7036   *q = 0;
7037
7038   temp.High_Bound = strlen (newmsg);
7039   if (Present (node))
7040     Error_Msg_NE (fp, node, ent);
7041 }
7042
7043 /* Similar to post_error_ne_tree, except that NUM is a second
7044    integer to write in the message.  */
7045
7046 void
7047 post_error_ne_tree_2 (const char *msg,
7048                       Node_Id node,
7049                       Entity_Id ent,
7050                       tree t,
7051                       int num)
7052 {
7053   Error_Msg_Uint_2 = UI_From_Int (num);
7054   post_error_ne_tree (msg, node, ent, t);
7055 }
7056 \f
7057 /* Initialize the table that maps GNAT codes to GCC codes for simple
7058    binary and unary operations.  */
7059
7060 static void
7061 init_code_table (void)
7062 {
7063   gnu_codes[N_And_Then] = TRUTH_ANDIF_EXPR;
7064   gnu_codes[N_Or_Else] = TRUTH_ORIF_EXPR;
7065
7066   gnu_codes[N_Op_And] = TRUTH_AND_EXPR;
7067   gnu_codes[N_Op_Or] = TRUTH_OR_EXPR;
7068   gnu_codes[N_Op_Xor] = TRUTH_XOR_EXPR;
7069   gnu_codes[N_Op_Eq] = EQ_EXPR;
7070   gnu_codes[N_Op_Ne] = NE_EXPR;
7071   gnu_codes[N_Op_Lt] = LT_EXPR;
7072   gnu_codes[N_Op_Le] = LE_EXPR;
7073   gnu_codes[N_Op_Gt] = GT_EXPR;
7074   gnu_codes[N_Op_Ge] = GE_EXPR;
7075   gnu_codes[N_Op_Add] = PLUS_EXPR;
7076   gnu_codes[N_Op_Subtract] = MINUS_EXPR;
7077   gnu_codes[N_Op_Multiply] = MULT_EXPR;
7078   gnu_codes[N_Op_Mod] = FLOOR_MOD_EXPR;
7079   gnu_codes[N_Op_Rem] = TRUNC_MOD_EXPR;
7080   gnu_codes[N_Op_Minus] = NEGATE_EXPR;
7081   gnu_codes[N_Op_Abs] = ABS_EXPR;
7082   gnu_codes[N_Op_Not] = TRUTH_NOT_EXPR;
7083   gnu_codes[N_Op_Rotate_Left] = LROTATE_EXPR;
7084   gnu_codes[N_Op_Rotate_Right] = RROTATE_EXPR;
7085   gnu_codes[N_Op_Shift_Left] = LSHIFT_EXPR;
7086   gnu_codes[N_Op_Shift_Right] = RSHIFT_EXPR;
7087   gnu_codes[N_Op_Shift_Right_Arithmetic] = RSHIFT_EXPR;
7088 }
7089
7090 /* Return a label to branch to for the exception type in KIND or NULL_TREE
7091    if none.  */
7092
7093 tree
7094 get_exception_label (char kind)
7095 {
7096   if (kind == N_Raise_Constraint_Error)
7097     return TREE_VALUE (gnu_constraint_error_label_stack);
7098   else if (kind == N_Raise_Storage_Error)
7099     return TREE_VALUE (gnu_storage_error_label_stack);
7100   else if (kind == N_Raise_Program_Error)
7101     return TREE_VALUE (gnu_program_error_label_stack);
7102   else
7103     return NULL_TREE;
7104 }
7105
7106 #include "gt-ada-trans.h"