OSDN Git Service

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